repo_id
stringlengths
6
101
size
int64
367
5.14M
file_path
stringlengths
2
269
content
stringlengths
367
5.14M
294coder/Efficient-MIF
1,337
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/neldermead/centroid.m
function y = centroid(M, x) % Attempts the computation of a centroid of a set of points on a manifold. % % function y = centroid(M, x) % % M is a structure representing a manifold. % x is a cell of points on that manifold. % This file is part of Manopt: www.manopt.org. % Original author: Nicolas Boumal, Dec. 30, 2012. % Contributors: % Change log: % For now, just apply a few steps of gradient descent for Karcher means n = numel(x); problem.M = M; problem.cost = @cost; function val = cost(y) val = 0; for i = 1 : n val = val + M.dist(y, x{i})^2; end val = val/2; end problem.grad = @grad; function g = grad(y) g = M.zerovec(y); for i = 1 : n g = M.lincomb(y, 1, g, -1, M.log(y, x{i})); end end % This line can be uncommented to check that the gradient is indeed % correct. This should always be the case if the dist and the log % functions in the manifold are correct. % checkgradient(problem); pause; query = warning('query', 'manopt:getHessian:approx'); warning('off', 'manopt:getHessian:approx'); options.verbosity = 0; options.maxiter = 15; y = trustregions(problem, x{randi(n)}, options); warning(query.state, 'manopt:getHessian:approx'); end
2881099/FreeSql.AdminLTE
1,552
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/bootstrap4-duallistbox/bootstrap-duallistbox.min.css
.bootstrap-duallistbox-container .buttons{width:100%;margin-bottom:-1px}.bootstrap-duallistbox-container label{display:block}.bootstrap-duallistbox-container .info{display:inline-block;margin-bottom:5px;font-size:11px}.bootstrap-duallistbox-container .clear1,.bootstrap-duallistbox-container .clear2{display:none;font-size:10px}.bootstrap-duallistbox-container .box1.filtered .clear1,.bootstrap-duallistbox-container .box2.filtered .clear2{display:inline-block}.bootstrap-duallistbox-container .move,.bootstrap-duallistbox-container .remove{width:50%;box-sizing:content-box}.bootstrap-duallistbox-container .btn-group .btn{border-bottom-left-radius:0;border-bottom-right-radius:0}.bootstrap-duallistbox-container:not(.moveonselect) select{border-top-left-radius:0;border-top-right-radius:0}.bootstrap-duallistbox-container .moveall,.bootstrap-duallistbox-container .removeall{width:50%;box-sizing:content-box}.bootstrap-duallistbox-container.bs2compatible .btn-group>.btn+.btn{margin-left:0}.bootstrap-duallistbox-container select{width:100%;height:300px;padding:0}.bootstrap-duallistbox-container .filter{display:inline-block;width:100%;height:31px;margin:0 0 5px 0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.bootstrap-duallistbox-container .filter.placeholder{color:#aaa}.bootstrap-duallistbox-container.moveonselect .move,.bootstrap-duallistbox-container.moveonselect .remove{display:none}.bootstrap-duallistbox-container.moveonselect .moveall,.bootstrap-duallistbox-container.moveonselect .removeall{width:100%}
281677160/openwrt-package
2,359
luci-app-tencentddns/luasrc/model/cbi/tencentddns.lua
local a=require"luci.sys" local e=luci.model.uci.cursor() local e=require"nixio.fs" require("luci.sys") local t,e,o t=Map("tencentddns",translate("TencentDDNS")) e=t:section(TypedSection,"base",translate("Base")) e.anonymous=true enable=e:option(Flag,"enable",translate("enable")) enable.rmempty=false enable=e:option(Flag,"clean",translate("Clean Before Update"),translate("Clean Before Update mean")) enable.rmempty=false token=e:option(Value,"key_id",translate("Key ID"),translate("Key ID Mean")) email=e:option(Value,"key_token",translate("Key Token"),translate("Key Token Mean")) email.password = true iface=e:option(ListValue,"interface",translate("WAN-IP Source"),translate("Select the WAN-IP Source for TencentDDNS, like wan/internet")) iface:value("",translate("Select WAN-IP Source")) iface:value("internet") iface:value("wan") iface.rmempty=false main=e:option(Value,"main_domain",translate("Main Domain"),translate("For example: test.github.com -> github.com")) main.rmempty=false sub=e:option(Value,"sub_domain",translate("Sub Domain"),translate("For example: test.github.com -> test")) sub.rmempty=false time=e:option(Value,"time",translate("Inspection Time"),translate("Unit: Minute, Range: 1-59")) time.rmempty=false e=t:section(TypedSection,"base",translate("Update Log")) e.anonymous=true local a="/var/log/tencentddns.log" tvlog=e:option(TextValue,"sylogtext") tvlog.rows=16 tvlog.readonly="readonly" tvlog.wrap="off" function tvlog.cfgvalue(e,e) sylogtext="" if a and nixio.fs.access(a) then sylogtext=luci.sys.exec("tail -n 100 %s"%a) end return sylogtext end tvlog.write=function(e,e,e) end local e=luci.http.formvalue("cbi.apply") if e then local key, val local Enable local Keyid local Keytoken local Domain local Subdomian for key, val in pairs(luci.http.formvalue()) do if(string.find(key,"enable")) then Enable=val elseif(string.find(key,"key_id")) then Keyid=val elseif(string.find(key,"key_token")) then Keytoken=val elseif(string.find(key,"main_domain")) then Domain=val elseif(string.find(key,"sub_domain")) then Subdomian=val end end io.popen("/etc/init.d/tencentddns restart") end return t
294coder/Efficient-MIF
9,950
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/neldermead/neldermead.m
function [x, cost, info, options] = neldermead(problem, x, options) % Nelder Mead optimization algorithm for derivative-free minimization. % % function [x, cost, info, options] = neldermead(problem) % function [x, cost, info, options] = neldermead(problem, x0) % function [x, cost, info, options] = neldermead(problem, x0, options) % function [x, cost, info, options] = neldermead(problem, [], options) % % Apply a Nelder-Mead minimization algorithm to the problem defined in % the problem structure, starting with the population x0 if it is provided % (otherwise, a random population on the manifold is generated). A % population is a cell containing points on the manifold. The number of % elements in the cell must be dim+1, where dim is the dimension of the % manifold: problem.M.dim(). % % To specify options whilst not specifying an initial guess, give x0 as [] % (the empty matrix). % % This algorithm is a plain adaptation of the Euclidean Nelder-Mead method % to the Riemannian setting. It comes with no convergence guarantees and % there is room for improvement. In particular, we compute centroids as % Karcher means, which seems overly expensive: cheaper forms of % average-like quantities might work better. % This solver is useful nonetheless for problems for which no derivatives % are available, and it may constitute a starting point for the development % of other Riemannian derivative-free methods. % % None of the options are mandatory. See in code for details. % % Requires problem.M.pairmean(x, y) to be defined (computes the average % between two points, x and y). % % If options.statsfun is defined, it will receive a cell of points x (the % current simplex being considered at that iteration), and, if required, % one store structure corresponding to the best point, x{1}. The points are % ordered by increasing cost: f(x{1}) <= f(x{2}) <= ... <= f(x{dim+1}), % where dim = problem.M.dim(). % % Based on http://www.optimization-online.org/DB_FILE/2007/08/1742.pdf. % % See also: manopt/solvers/pso/pso % This file is part of Manopt: www.manopt.org. % Original author: Nicolas Boumal, Dec. 30, 2012. % Contributors: % Change log: % % April 4, 2015 (NB): % Working with the new StoreDB class system. % Clarified interactions with statsfun and store. % % Nov. 11, 2016 (NB): % If options.verbosity is < 2, prints minimal output. % Verify that the problem description is sufficient for the solver. if ~canGetCost(problem) warning('manopt:getCost', ... 'No cost provided. The algorithm will likely abort.'); end % Dimension of the manifold dim = problem.M.dim(); % Set local defaults here localdefaults.storedepth = 0; % no need for caching localdefaults.maxcostevals = max(1000, 2*dim); localdefaults.maxiter = max(2000, 4*dim); localdefaults.reflection = 1; localdefaults.expansion = 2; localdefaults.contraction = .5; % forced to .5 to enable using pairmean functions in manifolds. % localdefaults.shrinkage = .5; % Merge global and local defaults, then merge w/ user options, if any. localdefaults = mergeOptions(getGlobalDefaults(), localdefaults); if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(localdefaults, options); % Start timing for initialization. timetic = tic(); % If no initial simplex x is given by the user, generate one at random. if ~exist('x', 'var') || isempty(x) x = cell(dim+1, 1); for i = 1 : dim+1 x{i} = problem.M.rand(); end end % Create a store database and a key for each point. storedb = StoreDB(options.storedepth); key = cell(size(x)); for i = 1 : dim+1; key{i} = storedb.getNewKey(); end % Compute objective-related quantities for x, and setup a % function evaluations counter. costs = zeros(dim+1, 1); for i = 1 : dim+1 costs(i) = getCost(problem, x{i}, storedb, key{i}); end costevals = dim+1; % Sort simplex points by cost. [costs, order] = sort(costs); x = x(order); key = key(order); % Iteration counter. % At any point, iter is the number of fully executed iterations so far. iter = 0; % Save stats in a struct array info, and preallocate. % savestats will be called twice for the initial iterate (number 0), % which is unfortunate, but not problematic. stats = savestats(); info(1) = stats; info(min(10000, options.maxiter+1)).iter = []; % Start iterating until stopping criterion triggers. while true % Make sure we don't use to much memory for the store database. storedb.purge(); stats = savestats(); info(iter+1) = stats; %#ok<AGROW> iter = iter + 1; % Start timing this iteration. timetic = tic(); % Sort simplex points by cost. [costs, order] = sort(costs); x = x(order); key = key(order); % Log / display iteration information here. if options.verbosity >= 2 fprintf('Cost evals: %7d\tBest cost: %+.4e\t', ... costevals, costs(1)); end % Run standard stopping criterion checks. [stop, reason] = stoppingcriterion(problem, x, options, info, iter); if stop if options.verbosity >= 1 fprintf([reason '\n']); end break; end % Compute a centroid for the dim best points. xbar = centroid(problem.M, x(1:end-1)); % Compute the direction for moving along the axis xbar - worst x. vec = problem.M.log(xbar, x{end}); % Reflection step xr = problem.M.exp(xbar, vec, -options.reflection); keyr = storedb.getNewKey(); costr = getCost(problem, xr, storedb, keyr); costevals = costevals + 1; % If the reflected point is honorable, drop the worst point, % replace it by the reflected point and start new iteration. if costr >= costs(1) && costr < costs(end-1) if options.verbosity >= 2 fprintf('Reflection\n'); end costs(end) = costr; x{end} = xr; key{end} = keyr; continue; end % If the reflected point is better than the best point, expand. if costr < costs(1) xe = problem.M.exp(xbar, vec, -options.expansion); keye = storedb.getNewKey(); coste = getCost(problem, xe, storedb, keye); costevals = costevals + 1; if coste < costr if options.verbosity >= 2 fprintf('Expansion\n'); end costs(end) = coste; x{end} = xe; key{end} = keye; continue; else if options.verbosity >= 2 fprintf('Reflection (failed expansion)\n'); end costs(end) = costr; x{end} = xr; key{end} = keyr; continue; end end % If the reflected point is worse than the second to worst point, % contract. if costr >= costs(end-1) if costr < costs(end) % do an outside contraction xoc = problem.M.exp(xbar, vec, -options.contraction); keyoc = storedb.getNewKey(); costoc = getCost(problem, xoc, storedb, keyoc); costevals = costevals + 1; if costoc <= costr if options.verbosity >= 2 fprintf('Outside contraction\n'); end costs(end) = costoc; x{end} = xoc; key{end} = keyoc; continue; end else % do an inside contraction xic = problem.M.exp(xbar, vec, options.contraction); keyic = storedb.getNewKey(); costic = getCost(problem, xic, storedb, keyic); costevals = costevals + 1; if costic <= costs(end) if options.verbosity >= 2 fprintf('Inside contraction\n'); end costs(end) = costic; x{end} = xic; key{end} = keyic; continue; end end end % If we get here, shrink the simplex around x{1}. if options.verbosity >= 2 fprintf('Shrinkage\n'); end for i = 2 : dim+1 x{i} = problem.M.pairmean(x{1}, x{i}); key{i} = storedb.getNewKey(); costs(i) = getCost(problem, x{i}, storedb, key{i}); end costevals = costevals + dim; end info = info(1:iter); % Iteration done: return only the best point found. cost = costs(1); x = x{1}; key = key{1}; % Routine in charge of collecting the current iteration stats. function stats = savestats() stats.iter = iter; stats.cost = costs(1); stats.costevals = costevals; if iter == 0 stats.time = toc(timetic); else stats.time = info(iter).time + toc(timetic); end % The statsfun can only possibly receive one store structure. We % pass the key to the best point, so that the best point's store % will be passed. But the whole cell x of points is passed through. stats = applyStatsfun(problem, x, storedb, key{1}, options, stats); end end
2881099/FreeSql.AdminLTE
16,856
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/bootstrap4-duallistbox/jquery.bootstrap-duallistbox.min.js
/* * Bootstrap Duallistbox - v4.0.2 * A responsive dual listbox widget optimized for Twitter Bootstrap. It works on all modern browsers and on touch devices. * http://www.virtuosoft.eu/code/bootstrap-duallistbox/ * * Made by István Ujj-Mészáros * Under Apache License v2.0 License */ !function(n){"function"==typeof define&&define.amd?define(["jquery"],n):"object"==typeof module&&module.exports?module.exports=function(e,t){return void 0===t&&(t="undefined"!=typeof window?require("jquery"):require("jquery")(e)),n(t),t}:n(jQuery)}(function(a){var i="bootstrapDualListbox",n={filterTextClear:"show all",filterPlaceHolder:"Filter",moveSelectedLabel:"Move selected",moveAllLabel:"Move all",removeSelectedLabel:"Remove selected",removeAllLabel:"Remove all",moveOnSelect:!0,moveOnDoubleClick:!0,preserveSelectionOnMove:!1,selectedListLabel:!1,nonSelectedListLabel:!1,helperSelectNamePostfix:"_helper",selectorMinimalHeight:100,showFilterInputs:!0,nonSelectedFilter:"",selectedFilter:"",infoText:"Showing all {0}",infoTextFiltered:'<span class="badge badge-warning">Filtered</span> {0} from {1}',infoTextEmpty:"Empty list",filterOnValues:!1,sortByInputOrder:!1,eventMoveOverride:!1,eventMoveAllOverride:!1,eventRemoveOverride:!1,eventRemoveAllOverride:!1,btnClass:"btn-outline-secondary",btnMoveText:"&gt;",btnRemoveText:"&lt;",btnMoveAllText:"&gt;&gt;",btnRemoveAllText:"&lt;&lt;"},s=/android/i.test(navigator.userAgent.toLowerCase());function l(e,t){this.element=a(e),this.settings=a.extend({},n,t),this._defaults=n,this._name=i,this.init()}function t(e){e.element.trigger("change")}function o(s){s.element.find("option").each(function(e,t){var n=a(t);void 0===n.data("original-index")&&n.data("original-index",s.elementCount++),void 0===n.data("_selected")&&n.data("_selected",!1)})}function r(s,i,l){s.element.find("option").each(function(e,t){var n=a(t);n.data("original-index")===i&&(n.prop("selected",l),l?(n.attr("data-sortindex",s.sortIndex),s.sortIndex++):n.removeAttr("data-sortindex"))})}function c(e,n){return console.log(e,n),e.replace(/{(\d+)}/g,function(e,t){return void 0!==n[t]?n[t]:e})}function h(e){if(e.settings.infoText){var t=e.elements.select1.find("option").length,n=e.elements.select2.find("option").length,s=e.element.find("option").length-e.selectedElements,i=e.selectedElements,l="";l=0==s?e.settings.infoTextEmpty:c(t===s?e.settings.infoText:e.settings.infoTextFiltered,[t,s]),e.elements.info1.html(l),e.elements.box1.toggleClass("filtered",!(t===s||0==s)),l=0===i?e.settings.infoTextEmpty:c(n===i?e.settings.infoText:e.settings.infoTextFiltered,[n,i]),e.elements.info2.html(l),e.elements.box2.toggleClass("filtered",!(n===i||0===i))}}function m(s){s.selectedElements=0,s.elements.select1.empty(),s.elements.select2.empty(),s.element.find("option").each(function(e,t){var n=a(t);n.prop("selected")?(s.selectedElements++,s.elements.select2.append(n.clone(!0).prop("selected",n.data("_selected")))):s.elements.select1.append(n.clone(!0).prop("selected",n.data("_selected")))}),s.settings.showFilterInputs&&(e(s,1),e(s,2)),h(s)}function e(i,l){if(i.settings.showFilterInputs){d(i,l),i.elements["select"+l].empty().scrollTop(0);var o,r=i.element.find("option"),e=i.element;e=1===l?r.not(":selected"):e.find("option:selected");try{o=new RegExp(a.trim(i.elements["filterInput"+l].val()),"gi")}catch(e){o=new RegExp("/a^/","gi")}e.each(function(e,t){var n=a(t),s=!0;(t.text.match(o)||i.settings.filterOnValues&&n.attr("value").match(o))&&(s=!1,i.elements["select"+l].append(n.clone(!0).prop("selected",n.data("_selected")))),r.eq(n.data("original-index")).data("filtered"+l,s)}),h(i)}}function d(e,t){var s=e.element.find("option");e.elements["select"+t].find("option").each(function(e,t){var n=a(t);s.eq(n.data("original-index")).data("_selected",n.prop("selected"))})}function u(e){var t=e.children("option");t.sort(function(e,t){var n=parseInt(e.getAttribute("data-sortindex")),s=parseInt(t.getAttribute("data-sortindex"));return s<n?1:n<s?-1:0}),t.detach().appendTo(e)}function v(e,t){e.find("option").sort(function(e,t){return a(e).data("original-index")>a(t).data("original-index")?1:-1}).appendTo(e),m(t)}function f(s){"all"!==s.settings.preserveSelectionOnMove||s.settings.moveOnSelect?"moved"!==s.settings.preserveSelectionOnMove||s.settings.moveOnSelect||d(s,1):(d(s,1),d(s,2)),s.elements.select1.find("option:selected").each(function(e,t){var n=a(t);n.data("filtered1")||r(s,n.data("original-index"),!0)}),m(s),t(s),s.settings.sortByInputOrder?u(s.elements.select2):v(s.elements.select2,s)}function p(s){"all"!==s.settings.preserveSelectionOnMove||s.settings.moveOnSelect?"moved"!==s.settings.preserveSelectionOnMove||s.settings.moveOnSelect||d(s,2):(d(s,1),d(s,2)),s.elements.select2.find("option:selected").each(function(e,t){var n=a(t);n.data("filtered2")||r(s,n.data("original-index"),!1)}),m(s),t(s),v(s.elements.select1,s),s.settings.sortByInputOrder&&u(s.elements.select2)}function g(n){n.elements.form.submit(function(e){n.elements.filterInput1.is(":focus")?(e.preventDefault(),n.elements.filterInput1.focusout()):n.elements.filterInput2.is(":focus")&&(e.preventDefault(),n.elements.filterInput2.focusout())}),n.element.on("bootstrapDualListbox.refresh",function(e,t){n.refresh(t)}),n.elements.filterClear1.on("click",function(){n.setNonSelectedFilter("",!0)}),n.elements.filterClear2.on("click",function(){n.setSelectedFilter("",!0)}),!1===n.settings.eventMoveOverride&&n.elements.moveButton.on("click",function(){f(n)}),!1===n.settings.eventMoveAllOverride&&n.elements.moveAllButton.on("click",function(){var s;"all"!==(s=n).settings.preserveSelectionOnMove||s.settings.moveOnSelect?"moved"!==s.settings.preserveSelectionOnMove||s.settings.moveOnSelect||d(s,1):(d(s,1),d(s,2)),s.element.find("option").each(function(e,t){var n=a(t);n.data("filtered1")||(n.prop("selected",!0),n.attr("data-sortindex",s.sortIndex),s.sortIndex++)}),m(s),t(s)}),!1===n.settings.eventRemoveOverride&&n.elements.removeButton.on("click",function(){p(n)}),!1===n.settings.eventRemoveAllOverride&&n.elements.removeAllButton.on("click",function(){var e;"all"!==(e=n).settings.preserveSelectionOnMove||e.settings.moveOnSelect?"moved"!==e.settings.preserveSelectionOnMove||e.settings.moveOnSelect||d(e,2):(d(e,1),d(e,2)),e.element.find("option").each(function(e,t){var n=a(t);n.data("filtered2")||(n.prop("selected",!1),n.removeAttr("data-sortindex"))}),m(e),t(e)}),n.elements.filterInput1.on("change keyup",function(){e(n,1)}),n.elements.filterInput2.on("change keyup",function(){e(n,2)})}l.prototype={init:function(){this.container=a('<div class="bootstrap-duallistbox-container row"> <div class="box1 col-md-6"> <label></label> <span class="info-container"> <span class="info"></span> <button type="button" class="btn btn-sm clear1" style="float:right!important;"></button> </span> <input class="form-control filter" type="text"> <div class="btn-group buttons"> <button type="button" class="btn moveall"></button> <button type="button" class="btn move"></button> </div> <select multiple="multiple"></select> </div> <div class="box2 col-md-6"> <label></label> <span class="info-container"> <span class="info"></span> <button type="button" class="btn btn-sm clear2" style="float:right!important;"></button> </span> <input class="form-control filter" type="text"> <div class="btn-group buttons"> <button type="button" class="btn remove"></button> <button type="button" class="btn removeall"></button> </div> <select multiple="multiple"></select> </div></div>').insertBefore(this.element),this.elements={originalSelect:this.element,box1:a(".box1",this.container),box2:a(".box2",this.container),filterInput1:a(".box1 .filter",this.container),filterInput2:a(".box2 .filter",this.container),filterClear1:a(".box1 .clear1",this.container),filterClear2:a(".box2 .clear2",this.container),label1:a(".box1 > label",this.container),label2:a(".box2 > label",this.container),info1:a(".box1 .info",this.container),info2:a(".box2 .info",this.container),select1:a(".box1 select",this.container),select2:a(".box2 select",this.container),moveButton:a(".box1 .move",this.container),removeButton:a(".box2 .remove",this.container),moveAllButton:a(".box1 .moveall",this.container),removeAllButton:a(".box2 .removeall",this.container),form:a(a(".box1 .filter",this.container)[0].form)},this.originalSelectName=this.element.attr("name")||"";var e="bootstrap-duallistbox-nonselected-list_"+this.originalSelectName,t="bootstrap-duallistbox-selected-list_"+this.originalSelectName;return this.elements.select1.attr("id",e),this.elements.select2.attr("id",t),this.elements.label1.attr("for",e),this.elements.label2.attr("for",t),this.selectedElements=0,this.sortIndex=0,this.elementCount=0,this.setFilterTextClear(this.settings.filterTextClear),this.setFilterPlaceHolder(this.settings.filterPlaceHolder),this.setMoveSelectedLabel(this.settings.moveSelectedLabel),this.setMoveAllLabel(this.settings.moveAllLabel),this.setRemoveSelectedLabel(this.settings.removeSelectedLabel),this.setRemoveAllLabel(this.settings.removeAllLabel),this.setMoveOnSelect(this.settings.moveOnSelect),this.setMoveOnDoubleClick(this.settings.moveOnDoubleClick),this.setPreserveSelectionOnMove(this.settings.preserveSelectionOnMove),this.setSelectedListLabel(this.settings.selectedListLabel),this.setNonSelectedListLabel(this.settings.nonSelectedListLabel),this.setHelperSelectNamePostfix(this.settings.helperSelectNamePostfix),this.setSelectOrMinimalHeight(this.settings.selectorMinimalHeight),o(this),this.setShowFilterInputs(this.settings.showFilterInputs),this.setNonSelectedFilter(this.settings.nonSelectedFilter),this.setSelectedFilter(this.settings.selectedFilter),this.setInfoText(this.settings.infoText),this.setInfoTextFiltered(this.settings.infoTextFiltered),this.setInfoTextEmpty(this.settings.infoTextEmpty),this.setFilterOnValues(this.settings.filterOnValues),this.setSortByInputOrder(this.settings.sortByInputOrder),this.setEventMoveOverride(this.settings.eventMoveOverride),this.setEventMoveAllOverride(this.settings.eventMoveAllOverride),this.setEventRemoveOverride(this.settings.eventRemoveOverride),this.setEventRemoveAllOverride(this.settings.eventRemoveAllOverride),this.setBtnClass(this.settings.btnClass),this.setBtnMoveText(this.settings.btnMoveText),this.setBtnRemoveText(this.settings.btnRemoveText),this.setBtnMoveAllText(this.settings.btnMoveAllText),this.setBtnRemoveAllText(this.settings.btnRemoveAllText),this.element.hide(),g(this),m(this),this.element},setFilterTextClear:function(e,t){return this.settings.filterTextClear=e,this.elements.filterClear1.html(e),this.elements.filterClear2.html(e),t&&m(this),this.element},setFilterPlaceHolder:function(e,t){return this.settings.filterPlaceHolder=e,this.elements.filterInput1.attr("placeholder",e),this.elements.filterInput2.attr("placeholder",e),t&&m(this),this.element},setMoveSelectedLabel:function(e,t){return this.settings.moveSelectedLabel=e,this.elements.moveButton.attr("title",e),t&&m(this),this.element},setMoveAllLabel:function(e,t){return this.settings.moveAllLabel=e,this.elements.moveAllButton.attr("title",e),t&&m(this),this.element},setRemoveSelectedLabel:function(e,t){return this.settings.removeSelectedLabel=e,this.elements.removeButton.attr("title",e),t&&m(this),this.element},setRemoveAllLabel:function(e,t){return this.settings.removeAllLabel=e,this.elements.removeAllButton.attr("title",e),t&&m(this),this.element},setMoveOnSelect:function(e,t){if(s&&(e=!0),this.settings.moveOnSelect=e,this.settings.moveOnSelect){this.container.addClass("moveonselect");var n=this;this.elements.select1.on("change",function(){f(n)}),this.elements.select2.on("change",function(){p(n)}),this.elements.moveButton.detach(),this.elements.removeButton.detach()}else this.container.removeClass("moveonselect"),this.elements.select1.off("change"),this.elements.select2.off("change"),this.elements.moveButton.insertAfter(this.elements.moveAllButton),this.elements.removeButton.insertBefore(this.elements.removeAllButton);return t&&m(this),this.element},setMoveOnDoubleClick:function(e,t){if(s&&(e=!1),this.settings.moveOnDoubleClick=e,this.settings.moveOnDoubleClick){this.container.addClass("moveondoubleclick");var n=this;this.elements.select1.on("dblclick",function(){f(n)}),this.elements.select2.on("dblclick",function(){p(n)})}else this.container.removeClass("moveondoubleclick"),this.elements.select1.off("dblclick"),this.elements.select2.off("dblclick");return t&&m(this),this.element},setPreserveSelectionOnMove:function(e,t){return s&&(e=!1),this.settings.preserveSelectionOnMove=e,t&&m(this),this.element},setSelectedListLabel:function(e,t){return(this.settings.selectedListLabel=e)?this.elements.label2.show().html(e):this.elements.label2.hide().html(e),t&&m(this),this.element},setNonSelectedListLabel:function(e,t){return(this.settings.nonSelectedListLabel=e)?this.elements.label1.show().html(e):this.elements.label1.hide().html(e),t&&m(this),this.element},setHelperSelectNamePostfix:function(e,t){return(this.settings.helperSelectNamePostfix=e)?(this.elements.select1.attr("name",this.originalSelectName+e+"1"),this.elements.select2.attr("name",this.originalSelectName+e+"2")):(this.elements.select1.removeAttr("name"),this.elements.select2.removeAttr("name")),t&&m(this),this.element},setSelectOrMinimalHeight:function(e,t){this.settings.selectorMinimalHeight=e;var n=this.element.height();return this.element.height()<e&&(n=e),this.elements.select1.height(n),this.elements.select2.height(n),t&&m(this),this.element},setShowFilterInputs:function(e,t){return e?(this.elements.filterInput1.show(),this.elements.filterInput2.show()):(this.setNonSelectedFilter(""),this.setSelectedFilter(""),m(this),this.elements.filterInput1.hide(),this.elements.filterInput2.hide()),this.settings.showFilterInputs=e,t&&m(this),this.element},setNonSelectedFilter:function(e,t){if(this.settings.showFilterInputs)return this.settings.nonSelectedFilter=e,this.elements.filterInput1.val(e),t&&m(this),this.element},setSelectedFilter:function(e,t){if(this.settings.showFilterInputs)return this.settings.selectedFilter=e,this.elements.filterInput2.val(e),t&&m(this),this.element},setInfoText:function(e,t){return(this.settings.infoText=e)?(this.elements.info1.show(),this.elements.info2.show()):(this.elements.info1.hide(),this.elements.info2.hide()),t&&m(this),this.element},setInfoTextFiltered:function(e,t){return this.settings.infoTextFiltered=e,t&&m(this),this.element},setInfoTextEmpty:function(e,t){return this.settings.infoTextEmpty=e,t&&m(this),this.element},setFilterOnValues:function(e,t){return this.settings.filterOnValues=e,t&&m(this),this.element},setSortByInputOrder:function(e,t){return this.settings.sortByInputOrder=e,t&&m(this),this.element},setEventMoveOverride:function(e,t){return this.settings.eventMoveOverride=e,t&&m(this),this.element},setEventMoveAllOverride:function(e,t){return this.settings.eventMoveAllOverride=e,t&&m(this),this.element},setEventRemoveOverride:function(e,t){return this.settings.eventRemoveOverride=e,t&&m(this),this.element},setEventRemoveAllOverride:function(e,t){return this.settings.eventRemoveAllOverride=e,t&&m(this),this.element},setBtnClass:function(e,t){return this.settings.btnClass=e,this.elements.moveButton.attr("class","btn move").addClass(e),this.elements.removeButton.attr("class","btn remove").addClass(e),this.elements.moveAllButton.attr("class","btn moveall").addClass(e),this.elements.removeAllButton.attr("class","btn removeall").addClass(e),t&&m(this),this.element},setBtnMoveText:function(e,t){return this.settings.btnMoveText=e,this.elements.moveButton.html(e),t&&m(this),this.element},setBtnRemoveText:function(e,t){return this.settings.btnMoveText=e,this.elements.removeButton.html(e),t&&m(this),this.element},setBtnMoveAllText:function(e,t){return this.settings.btnMoveText=e,this.elements.moveAllButton.html(e),t&&m(this),this.element},setBtnRemoveAllText:function(e,t){return this.settings.btnMoveText=e,this.elements.removeAllButton.html(e),t&&m(this),this.element},getContainer:function(){return this.container},refresh:function(e){var t;o(this),e?(t=this).elements.select1.find("option").each(function(){t.element.find("option").data("_selected",!1)}):(d(this,1),d(this,2)),m(this)},destroy:function(){return this.container.remove(),this.element.show(),a.data(this,"plugin_"+i,null),this.element}},a.fn[i]=function(n){var t,s=arguments;return void 0===n||"object"==typeof n?this.each(function(){a(this).is("select")?a.data(this,"plugin_"+i)||a.data(this,"plugin_"+i,new l(this,n)):a(this).find("select").each(function(e,t){a(t).bootstrapDualListbox(n)})}):"string"==typeof n&&"_"!==n[0]&&"init"!==n?(this.each(function(){var e=a.data(this,"plugin_"+i);e instanceof l&&"function"==typeof e[n]&&(t=e[n].apply(e,Array.prototype.slice.call(s,1)))}),void 0!==t?t:this):void 0}});
294coder/Efficient-MIF
5,495
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/preconditioners/preconhessiansolve.m
function preconfun = preconhessiansolve(problem, options) % Preconditioner based on the inverse Hessian, by solving linear systems. % % function preconfun = preconhessiansolve(problem) % function preconfun = preconhessiansolve(problem, options) % % Input: % % A Manopt problem structure (already containing the manifold and enough % information to compute the Hessian of the cost) and an options structure % (optional, currently ignored). Notice that if the Hessian is not positive % definite, then its inverse is not positive definite either and this % preconditioner is not suitable. % % If the Hessian cannot be computed on 'problem', a warning is issued. An % approximation of the Hessian will be used instead, and the present % preconditioner will attempt to invert that (although it may not be a % linear operator). If no approximate Hessian is provided either, a generic % approximation is used. Behavior is unspecified. % % Output: % % Returns a function handle, encapsulating a generic preconditioner of the % Hessian based on solving linear systems of the form: % Hessian(x)[preconfun(x, xdot)] = xdot, % where x is the point on the manifold, xdot is the input to the % preconditioner (a tangent vector) and preconfun(x, xdot) is returned % (also a tangent vector). The solve may be approximate. % % The returned preconfun has this calling pattern: % % function precxdot = preconfun(x, xdot) % function precxdot = preconfun(x, xdot, storedb) % function precxdot = preconfun(x, xdot, storedb, key) % % x is a point on the manifold problem.M, xdot is a tangent vector to that % manifold at x, storedb is a StoreDB object, and key is the StoreDB key to % point x. % % Usage: % % Typically, the user will set problem.M and other fields to define the % cost, the gradient and the Hessian (typically, problem.cost, problem.grad % and problem.hess, or problem.egrad and problem.ehess). Then, to use this % generic purpose Hessian preconditioner: % % problem.precon = preconhessiansolve(problem, options); % % Passing that problem structure to the conjugategradients solver % (which uses preconditioning) configured in steepest descent mode results % in a type of Riemannian Newton method. % % See also: conjugategradients % This file is part of Manopt: www.manopt.org. % Original author: Nicolas Boumal, April 9, 2015. % Contributors: % Change log: % Check availability of the Hessian, or at least of an approximation. if ~canGetHessian(problem) && ~canGetApproxHessian(problem) % Note: we do not give a warning if an approximate Hessian is % explicitly given in the problem description, as in that case the % user seems to be aware of the issue. warning('manopt:getHessian:approx', ... ['No Hessian provided. Using an FD approximation instead.\n' ... 'To disable this warning: warning(''off'', ''manopt:getHessian:approx'')']); problem.approxhess = approxhessianFD(problem); end % Set local defaults here, and merge with user options, if any. localdefaults = struct(); if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(localdefaults, options); % Build and return the function handle here. This extra construct via % funhandle makes it possible to make storedb and key optional. preconfun = @funhandle; function precxdot = funhandle(x, xdot, storedb, key) % Allow omission of the key, and even of storedb. if ~exist('key', 'var') if ~exist('storedb', 'var') storedb = StoreDB(); end key = storedb.getNewKey(); end precxdot = hessiansolvehelper(options, problem, x, xdot, ... storedb, key); end end function precxdot = hessiansolvehelper(options, problem, x, xdot, storedb, key) % This function does the actual work. % Exclude the case where xdot is zero norm_xdot = problem.M.norm(x, xdot); if norm_xdot < eps precxdot = problem.M.zerovec(x); return; end % Get a shorthand for the Hessian of the cost on M at x. hessian = @(u) getHessian(problem, x, u, storedb, key); % Setup an optimization problem on the tangent space to problem.M at x. M = problem.M; tgtspace = tangentspacefactory(M, x); prblm.M = tgtspace; prblm.cost = @cost; prblm.grad = @grad; prblm.hess = @(u, udot) 2*hessian(hessian(udot))/norm_xdot; function [f, store] = cost(u, store) if ~isfield(store, 'residue') Hu = hessian(u); store.residue = M.lincomb(x, 1, Hu, -1, xdot); end f = M.norm(x, store.residue).^2 / norm_xdot; end function [g, store] = grad(u, store) if ~isfield(store, 'residue') Hu = hessian(u); store.residue = M.lincomb(x, 1, Hu, -1, xdot); end g = 2 * hessian(store.residue) / norm_xdot; end % checkgradient(prblm); pause; % checkhessian(prblm); pause; localdefaults.solver = @trustregions; localdefaults.verbosity = 0; % Merge local defaults with user options, if any. if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(localdefaults, options); % Solve the linear system by solving the optimization problem. precxdot = manoptsolve(prblm, M.zerovec(), options); end
281677160/openwrt-package
1,015
luci-app-tencentddns/po/zh_Hans/tencentddns.po
msgid "" msgstr "Content-Type: text/plain; charset=UTF-8\n" msgid "TencentDDNS" msgstr "腾讯云DDNS" msgid "enable" msgstr "启用" msgid "Clean Before Update" msgstr "清除所有同名记录" msgid "Clean Before Update mean" msgstr "如果有相同的域名的A解析记录,DDNS会将其覆盖" msgid "Base" msgstr "基本设置" msgid "Key ID" msgstr "密钥ID" msgid "Key ID Mean" msgstr "DNSPod后台密钥管理中的ID" msgid "Key Token" msgstr "密钥Token" msgid "Key Token Mean" msgstr "DNSPod后台密钥管理中的Token" msgid "WAN-IP Source" msgstr "WAN-IP来源" msgid "Select WAN-IP Source" msgstr "选择WAN-IP来源" msgid "Select the WAN-IP Source for TencentDDNS, like wan/internet" msgstr "动态域名的IP来源,如wan/internet" msgid "Main Domain" msgstr "主域名" msgid "Sub Domain" msgstr "子域名" msgid "For example: test.github.com -> github.com" msgstr "例如: test.github.com 则填: github.com" msgid "For example: test.github.com -> test" msgstr "例如: test.github.com, 则填: test" msgid "Inspection Time" msgstr "检查时间" msgid "Unit: Minute, Range: 1-59" msgstr "域名检查间隔时间,单位分钟,范围1-59" msgid "Update Log" msgstr "更新记录"
2881099/FreeSql.AdminLTE
152,725
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote.min.js
/*! Summernote v0.8.20 | (c) 2013- Alan Hong and contributors | MIT license */ !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e(require("jQuery"));else if("function"==typeof define&&define.amd)define(["jQuery"],e);else{var n="object"==typeof exports?e(require("jQuery")):e(t.jQuery);for(var o in n)("object"==typeof exports?exports:t)[o]=n[o]}}(self,(function(t){return(()=>{"use strict";var e={9770:(t,e,n)=>{var o=n(1145),i=n.n(o);i().summernote=i().summernote||{lang:{}},i().extend(i().summernote.lang,{"en-US":{font:{bold:"Bold",italic:"Italic",underline:"Underline",clear:"Remove Font Style",height:"Line Height",name:"Font Family",strikethrough:"Strikethrough",subscript:"Subscript",superscript:"Superscript",size:"Font Size",sizeunit:"Font Size Unit"},image:{image:"Picture",insert:"Insert Image",resizeFull:"Resize full",resizeHalf:"Resize half",resizeQuarter:"Resize quarter",resizeNone:"Original size",floatLeft:"Float Left",floatRight:"Float Right",floatNone:"Remove float",shapeRounded:"Shape: Rounded",shapeCircle:"Shape: Circle",shapeThumbnail:"Shape: Thumbnail",shapeNone:"Shape: None",dragImageHere:"Drag image or text here",dropImage:"Drop image or Text",selectFromFiles:"Select from files",maximumFileSize:"Maximum file size",maximumFileSizeError:"Maximum file size exceeded.",url:"Image URL",remove:"Remove Image",original:"Original"},video:{video:"Video",videoLink:"Video Link",insert:"Insert Video",url:"Video URL",providers:"(YouTube, Google Drive, Vimeo, Vine, Instagram, DailyMotion, Youku, Peertube)"},link:{link:"Link",insert:"Insert Link",unlink:"Unlink",edit:"Edit",textToDisplay:"Text to display",url:"To what URL should this link go?",openInNewWindow:"Open in new window",useProtocol:"Use default protocol"},table:{table:"Table",addRowAbove:"Add row above",addRowBelow:"Add row below",addColLeft:"Add column left",addColRight:"Add column right",delRow:"Delete row",delCol:"Delete column",delTable:"Delete table"},hr:{insert:"Insert Horizontal Rule"},style:{style:"Style",p:"Normal",blockquote:"Quote",pre:"Code",h1:"Header 1",h2:"Header 2",h3:"Header 3",h4:"Header 4",h5:"Header 5",h6:"Header 6"},lists:{unordered:"Unordered list",ordered:"Ordered list"},options:{help:"Help",fullscreen:"Full Screen",codeview:"Code View"},paragraph:{paragraph:"Paragraph",outdent:"Outdent",indent:"Indent",left:"Align left",center:"Align center",right:"Align right",justify:"Justify full"},color:{recent:"Recent Color",more:"More Color",background:"Background Color",foreground:"Text Color",transparent:"Transparent",setTransparent:"Set transparent",reset:"Reset",resetToDefault:"Reset to default",cpSelect:"Select"},shortcut:{shortcuts:"Keyboard shortcuts",close:"Close",textFormatting:"Text formatting",action:"Action",paragraphFormatting:"Paragraph formatting",documentStyle:"Document Style",extraKeys:"Extra keys"},help:{escape:"Escape",insertParagraph:"Insert Paragraph",undo:"Undo the last command",redo:"Redo the last command",tab:"Tab",untab:"Untab",bold:"Set a bold style",italic:"Set a italic style",underline:"Set a underline style",strikethrough:"Set a strikethrough style",removeFormat:"Clean a style",justifyLeft:"Set left align",justifyCenter:"Set center align",justifyRight:"Set right align",justifyFull:"Set full align",insertUnorderedList:"Toggle unordered list",insertOrderedList:"Toggle ordered list",outdent:"Outdent on current paragraph",indent:"Indent on current paragraph",formatPara:"Change current block's format as a paragraph(P tag)",formatH1:"Change current block's format as H1",formatH2:"Change current block's format as H2",formatH3:"Change current block's format as H3",formatH4:"Change current block's format as H4",formatH5:"Change current block's format as H5",formatH6:"Change current block's format as H6",insertHorizontalRule:"Insert horizontal rule","linkDialog.show":"Show Link Dialog"},history:{undo:"Undo",redo:"Redo"},specialChar:{specialChar:"SPECIAL CHARACTERS",select:"Select Special characters"},output:{noSelection:"No Selection Made!"}}})},1145:e=>{e.exports=t}},n={};function o(t){var i=n[t];if(void 0!==i)return i.exports;var r=n[t]={exports:{}};return e[t](r,r.exports,o),r.exports}o.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return o.d(e,{a:e}),e},o.d=(t,e)=>{for(var n in e)o.o(e,n)&&!o.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},o.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),o.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var i={};return(()=>{o.r(i);var t=o(1145),e=o.n(t),n=(o(9770),["sans-serif","serif","monospace","cursive","fantasy"]);function r(t){return-1===e().inArray(t.toLowerCase(),n)?"'".concat(t,"'"):t}var a,s=navigator.userAgent,l=/MSIE|Trident/i.test(s);if(l){var c=/MSIE (\d+[.]\d+)/.exec(s);c&&(a=parseFloat(c[1])),(c=/Trident\/.*rv:([0-9]{1,}[.0-9]{0,})/.exec(s))&&(a=parseFloat(c[1]))}var u=/Edge\/\d+/.test(s),d="ontouchstart"in window||navigator.MaxTouchPoints>0||navigator.msMaxTouchPoints>0,h=l?"DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted":"input";const f={isMac:navigator.appVersion.indexOf("Mac")>-1,isMSIE:l,isEdge:u,isFF:!u&&/firefox/i.test(s),isPhantom:/PhantomJS/i.test(s),isWebkit:!u&&/webkit/i.test(s),isChrome:!u&&/chrome/i.test(s),isSafari:!u&&/safari/i.test(s)&&!/chrome/i.test(s),browserVersion:a,isSupportTouch:d,isFontInstalled:function(t){var e="Comic Sans MS"===t?"Courier New":"Comic Sans MS",n="mmmmmmmmmmwwwww",o=document.createElement("canvas").getContext("2d");o.font="200px '"+e+"'";var i=o.measureText(n).width;return o.font="200px "+r(t)+', "'+e+'"',i!==o.measureText(n).width},isW3CRangeSupport:!!document.createRange,inputEventName:h,genericFontFamilies:n,validFontName:r};var p=0;const v={eq:function(t){return function(e){return t===e}},eq2:function(t,e){return t===e},peq2:function(t){return function(e,n){return e[t]===n[t]}},ok:function(){return!0},fail:function(){return!1},self:function(t){return t},not:function(t){return function(){return!t.apply(t,arguments)}},and:function(t,e){return function(n){return t(n)&&e(n)}},invoke:function(t,e){return function(){return t[e].apply(t,arguments)}},resetUniqueId:function(){p=0},uniqueId:function(t){var e=++p+"";return t?t+e:e},rect2bnd:function(t){var n=e()(document);return{top:t.top+n.scrollTop(),left:t.left+n.scrollLeft(),width:t.right-t.left,height:t.bottom-t.top}},invertObject:function(t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[t[n]]=n);return e},namespaceToCamel:function(t,e){return(e=e||"")+t.split(".").map((function(t){return t.substring(0,1).toUpperCase()+t.substring(1)})).join("")},debounce:function(t,e,n){var o;return function(){var i=this,r=arguments,a=function(){o=null,n||t.apply(i,r)},s=n&&!o;clearTimeout(o),o=setTimeout(a,e),s&&t.apply(i,r)}},isValidUrl:function(t){return/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/gi.test(t)}};function m(t){return t[0]}function g(t){return t[t.length-1]}function b(t){return t.slice(1)}function y(t,e){if(t&&t.length&&e){if(t.indexOf)return-1!==t.indexOf(e);if(t.contains)return t.contains(e)}return!1}const k={head:m,last:g,initial:function(t){return t.slice(0,t.length-1)},tail:b,prev:function(t,e){if(t&&t.length&&e){var n=t.indexOf(e);return-1===n?null:t[n-1]}return null},next:function(t,e){if(t&&t.length&&e){var n=t.indexOf(e);return-1===n?null:t[n+1]}return null},find:function(t,e){for(var n=0,o=t.length;n<o;n++){var i=t[n];if(e(i))return i}},contains:y,all:function(t,e){for(var n=0,o=t.length;n<o;n++)if(!e(t[n]))return!1;return!0},sum:function(t,e){return e=e||v.self,t.reduce((function(t,n){return t+e(n)}),0)},from:function(t){for(var e=[],n=t.length,o=-1;++o<n;)e[o]=t[o];return e},isEmpty:function(t){return!t||!t.length},clusterBy:function(t,e){return t.length?b(t).reduce((function(t,n){var o=g(t);return e(g(o),n)?o[o.length]=n:t[t.length]=[n],t}),[[m(t)]]):[]},compact:function(t){for(var e=[],n=0,o=t.length;n<o;n++)t[n]&&e.push(t[n]);return e},unique:function(t){for(var e=[],n=0,o=t.length;n<o;n++)y(e,t[n])||e.push(t[n]);return e}};var w=String.fromCharCode(160);function C(t){return t&&e()(t).hasClass("note-editable")}function x(t){return t=t.toUpperCase(),function(e){return e&&e.nodeName.toUpperCase()===t}}function S(t){return t&&3===t.nodeType}function T(t){return t&&/^BR|^IMG|^HR|^IFRAME|^BUTTON|^INPUT|^AUDIO|^VIDEO|^EMBED/.test(t.nodeName.toUpperCase())}function E(t){return!C(t)&&(t&&/^DIV|^P|^LI|^H[1-7]/.test(t.nodeName.toUpperCase()))}var I=x("PRE"),$=x("LI");var N=x("TABLE"),P=x("DATA");function R(t){return!(H(t)||L(t)||A(t)||E(t)||N(t)||D(t)||P(t))}function L(t){return t&&/^UL|^OL/.test(t.nodeName.toUpperCase())}var A=x("HR");function F(t){return t&&/^TD|^TH/.test(t.nodeName.toUpperCase())}var D=x("BLOCKQUOTE");function H(t){return F(t)||D(t)||C(t)}var z=x("A");var B=x("BODY");var M=f.isMSIE&&f.browserVersion<11?"&nbsp;":"<br>";function O(t){return S(t)?t.nodeValue.length:t?t.childNodes.length:0}function U(t){var e=O(t);return 0===e||(!S(t)&&1===e&&t.innerHTML===M||!(!k.all(t.childNodes,S)||""!==t.innerHTML))}function j(t){T(t)||O(t)||(t.innerHTML=M)}function W(t,e){for(;t;){if(e(t))return t;if(C(t))break;t=t.parentNode}return null}function K(t,e){e=e||v.fail;var n=[];return W(t,(function(t){return C(t)||n.push(t),e(t)})),n}function V(t,e){e=e||v.fail;for(var n=[];t&&!e(t);)n.push(t),t=t.nextSibling;return n}function q(t,e){var n=e.nextSibling,o=e.parentNode;return n?o.insertBefore(t,n):o.appendChild(t),t}function _(t,n){return e().each(n,(function(e,n){t.appendChild(n)})),t}function G(t){return 0===t.offset}function Y(t){return t.offset===O(t.node)}function Z(t){return G(t)||Y(t)}function Q(t,e){for(;t&&t!==e;){if(0!==J(t))return!1;t=t.parentNode}return!0}function X(t,e){if(!e)return!1;for(;t&&t!==e;){if(J(t)!==O(t.parentNode)-1)return!1;t=t.parentNode}return!0}function J(t){for(var e=0;t=t.previousSibling;)e+=1;return e}function tt(t){return!!(t&&t.childNodes&&t.childNodes.length)}function et(t,e){var n,o;if(0===t.offset){if(C(t.node))return null;n=t.node.parentNode,o=J(t.node)}else tt(t.node)?o=O(n=t.node.childNodes[t.offset-1]):(n=t.node,o=e?0:t.offset-1);return{node:n,offset:o}}function nt(t,e){var n,o;if(O(t.node)===t.offset){if(C(t.node))return null;var i=it(t.node);i?(n=i,o=0):(n=t.node.parentNode,o=J(t.node)+1)}else tt(t.node)?(n=t.node.childNodes[t.offset],o=0):(n=t.node,o=e?O(t.node):t.offset+1);return{node:n,offset:o}}function ot(t,e){var n,o=0;if(U(t.node))return null===t.node?null:{node:n=t.node.nextSibling,offset:o=0};if(O(t.node)===t.offset){if(C(t.node))return null;n=t.node.parentNode,o=J(t.node)+1,C(n)&&(n=t.node.nextSibling,o=0)}else if(tt(t.node)){if(o=0,U(n=t.node.childNodes[t.offset]))return U(t.node.nextSibling)?null:{node:t.node.nextSibling,offset:o}}else if(n=t.node,o=e?O(t.node):t.offset+1,U(n))return null;return{node:n,offset:o}}function it(t){if(t.nextSibling&&t.parent===t.nextSibling.parent)return S(t.nextSibling)?t.nextSibling:it(t.nextSibling)}function rt(t,e){return t.node===e.node&&t.offset===e.offset}function at(t,e){var n=e&&e.isSkipPaddingBlankHTML,o=e&&e.isNotSplitEdgePoint,i=e&&e.isDiscardEmptySplits;if(i&&(n=!0),Z(t)&&(S(t.node)||o)){if(G(t))return t.node;if(Y(t))return t.node.nextSibling}if(S(t.node))return t.node.splitText(t.offset);var r=t.node.childNodes[t.offset],a=q(t.node.cloneNode(!1),t.node);return _(a,V(r)),n||(j(t.node),j(a)),i&&(U(t.node)&&ct(t.node),U(a))?(ct(a),t.node.nextSibling):a}function st(t,e,n){var o=K(e.node,v.eq(t));return o.length?1===o.length?at(e,n):o.reduce((function(t,o){return t===e.node&&(t=at(e,n)),at({node:o,offset:t?J(t):O(o)},n)})):null}function lt(t){return document.createElement(t)}function ct(t,e){if(t&&t.parentNode){if(t.removeNode)return t.removeNode(e);var n=t.parentNode;if(!e){for(var o=[],i=0,r=t.childNodes.length;i<r;i++)o.push(t.childNodes[i]);for(var a=0,s=o.length;a<s;a++)n.insertBefore(o[a],t)}n.removeChild(t)}}var ut=x("TEXTAREA");function dt(t,e){var n=ut(t[0])?t.val():t.html();return e?n.replace(/[\n\r]/g,""):n}const ht={NBSP_CHAR:w,ZERO_WIDTH_NBSP_CHAR:"\ufeff",blank:M,emptyPara:"<p>".concat(M,"</p>"),makePredByNodeName:x,isEditable:C,isControlSizing:function(t){return t&&e()(t).hasClass("note-control-sizing")},isText:S,isElement:function(t){return t&&1===t.nodeType},isVoid:T,isPara:E,isPurePara:function(t){return E(t)&&!$(t)},isHeading:function(t){return t&&/^H[1-7]/.test(t.nodeName.toUpperCase())},isInline:R,isBlock:v.not(R),isBodyInline:function(t){return R(t)&&!W(t,E)},isBody:B,isParaInline:function(t){return R(t)&&!!W(t,E)},isPre:I,isList:L,isTable:N,isData:P,isCell:F,isBlockquote:D,isBodyContainer:H,isAnchor:z,isDiv:x("DIV"),isLi:$,isBR:x("BR"),isSpan:x("SPAN"),isB:x("B"),isU:x("U"),isS:x("S"),isI:x("I"),isImg:x("IMG"),isTextarea:ut,deepestChildIsEmpty:function(t){do{if(null===t.firstElementChild||""===t.firstElementChild.innerHTML)break}while(t=t.firstElementChild);return U(t)},isEmpty:U,isEmptyAnchor:v.and(z,U),isClosestSibling:function(t,e){return t.nextSibling===e||t.previousSibling===e},withClosestSiblings:function(t,e){e=e||v.ok;var n=[];return t.previousSibling&&e(t.previousSibling)&&n.push(t.previousSibling),n.push(t),t.nextSibling&&e(t.nextSibling)&&n.push(t.nextSibling),n},nodeLength:O,isLeftEdgePoint:G,isRightEdgePoint:Y,isEdgePoint:Z,isLeftEdgeOf:Q,isRightEdgeOf:X,isLeftEdgePointOf:function(t,e){return G(t)&&Q(t.node,e)},isRightEdgePointOf:function(t,e){return Y(t)&&X(t.node,e)},prevPoint:et,nextPoint:nt,nextPointWithEmptyNode:ot,isSamePoint:rt,isVisiblePoint:function(t){if(S(t.node)||!tt(t.node)||U(t.node))return!0;var e=t.node.childNodes[t.offset-1],n=t.node.childNodes[t.offset];return!((e&&!T(e)||n&&!T(n))&&!N(n))},prevPointUntil:function(t,e){for(;t;){if(e(t))return t;t=et(t)}return null},nextPointUntil:function(t,e){for(;t;){if(e(t))return t;t=nt(t)}return null},isCharPoint:function(t){if(!S(t.node))return!1;var e=t.node.nodeValue.charAt(t.offset-1);return e&&" "!==e&&e!==w},isSpacePoint:function(t){if(!S(t.node))return!1;var e=t.node.nodeValue.charAt(t.offset-1);return" "===e||e===w},walkPoint:function(t,e,n,o){for(var i=t;i&&(n(i),!rt(i,e));){i=ot(i,o&&t.node!==i.node&&e.node!==i.node)}},ancestor:W,singleChildAncestor:function(t,e){for(t=t.parentNode;t&&1===O(t);){if(e(t))return t;if(C(t))break;t=t.parentNode}return null},listAncestor:K,lastAncestor:function(t,e){var n=K(t);return k.last(n.filter(e))},listNext:V,listPrev:function(t,e){e=e||v.fail;for(var n=[];t&&!e(t);)n.push(t),t=t.previousSibling;return n},listDescendant:function(t,e){var n=[];return e=e||v.ok,function o(i){t!==i&&e(i)&&n.push(i);for(var r=0,a=i.childNodes.length;r<a;r++)o(i.childNodes[r])}(t),n},commonAncestor:function(t,e){for(var n=K(t),o=e;o;o=o.parentNode)if(n.indexOf(o)>-1)return o;return null},wrap:function(t,n){var o=t.parentNode,i=e()("<"+n+">")[0];return o.insertBefore(i,t),i.appendChild(t),i},insertAfter:q,appendChildNodes:_,position:J,hasChildren:tt,makeOffsetPath:function(t,e){return K(e,v.eq(t)).map(J).reverse()},fromOffsetPath:function(t,e){for(var n=t,o=0,i=e.length;o<i;o++)n=n.childNodes.length<=e[o]?n.childNodes[n.childNodes.length-1]:n.childNodes[e[o]];return n},splitTree:st,splitPoint:function(t,e){var n,o,i=e?E:H,r=K(t.node,i),a=k.last(r)||t.node;i(a)?(n=r[r.length-2],o=a):o=(n=a).parentNode;var s=n&&st(n,t,{isSkipPaddingBlankHTML:e,isNotSplitEdgePoint:e});return s||o!==t.node||(s=t.node.childNodes[t.offset]),{rightNode:s,container:o}},create:lt,createText:function(t){return document.createTextNode(t)},remove:ct,removeWhile:function(t,e){for(;t&&!C(t)&&e(t);){var n=t.parentNode;ct(t),t=n}},replace:function(t,e){if(t.nodeName.toUpperCase()===e.toUpperCase())return t;var n=lt(e);return t.style.cssText&&(n.style.cssText=t.style.cssText),_(n,k.from(t.childNodes)),q(n,t),ct(t),n},html:function(t,e){var n=dt(t);if(e){n=(n=n.replace(/<(\/?)(\b(?!!)[^>\s]*)(.*?)(\s*\/?>)/g,(function(t,e,n){n=n.toUpperCase();var o=/^DIV|^TD|^TH|^P|^LI|^H[1-7]/.test(n)&&!!e,i=/^BLOCKQUOTE|^TABLE|^TBODY|^TR|^HR|^UL|^OL/.test(n);return t+(o||i?"\n":"")}))).trim()}return n},value:dt,posFromPlaceholder:function(t){var n=e()(t),o=n.offset(),i=n.outerHeight(!0);return{left:o.left,top:o.top+i}},attachEvents:function(t,e){Object.keys(e).forEach((function(n){t.on(n,e[n])}))},detachEvents:function(t,e){Object.keys(e).forEach((function(n){t.off(n,e[n])}))},isCustomStyleTag:function(t){return t&&!S(t)&&k.contains(t.classList,"note-styletag")}};function ft(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var pt=function(){function t(n,o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$note=n,this.memos={},this.modules={},this.layoutInfo={},this.options=e().extend(!0,{},o),e().summernote.ui=e().summernote.ui_template(this.options),this.ui=e().summernote.ui,this.initialize()}var n,o,i;return n=t,o=[{key:"initialize",value:function(){return this.layoutInfo=this.ui.createLayout(this.$note),this._initialize(),this.$note.hide(),this}},{key:"destroy",value:function(){this._destroy(),this.$note.removeData("summernote"),this.ui.removeLayout(this.$note,this.layoutInfo)}},{key:"reset",value:function(){var t=this.isDisabled();this.code(ht.emptyPara),this._destroy(),this._initialize(),t&&this.disable()}},{key:"_initialize",value:function(){var t=this;this.options.id=v.uniqueId(e().now()),this.options.container=this.options.container||this.layoutInfo.editor;var n=e().extend({},this.options.buttons);Object.keys(n).forEach((function(e){t.memo("button."+e,n[e])}));var o=e().extend({},this.options.modules,e().summernote.plugins||{});Object.keys(o).forEach((function(e){t.module(e,o[e],!0)})),Object.keys(this.modules).forEach((function(e){t.initializeModule(e)}))}},{key:"_destroy",value:function(){var t=this;Object.keys(this.modules).reverse().forEach((function(e){t.removeModule(e)})),Object.keys(this.memos).forEach((function(e){t.removeMemo(e)})),this.triggerEvent("destroy",this)}},{key:"code",value:function(t){var e=this.invoke("codeview.isActivated");if(void 0===t)return this.invoke("codeview.sync"),e?this.layoutInfo.codable.val():this.layoutInfo.editable.html();e?this.invoke("codeview.sync",t):this.layoutInfo.editable.html(t),this.$note.val(t),this.triggerEvent("change",t,this.layoutInfo.editable)}},{key:"isDisabled",value:function(){return"false"===this.layoutInfo.editable.attr("contenteditable")}},{key:"enable",value:function(){this.layoutInfo.editable.attr("contenteditable",!0),this.invoke("toolbar.activate",!0),this.triggerEvent("disable",!1),this.options.editing=!0}},{key:"disable",value:function(){this.invoke("codeview.isActivated")&&this.invoke("codeview.deactivate"),this.layoutInfo.editable.attr("contenteditable",!1),this.options.editing=!1,this.invoke("toolbar.deactivate",!0),this.triggerEvent("disable",!0)}},{key:"triggerEvent",value:function(){var t=k.head(arguments),e=k.tail(k.from(arguments)),n=this.options.callbacks[v.namespaceToCamel(t,"on")];n&&n.apply(this.$note[0],e),this.$note.trigger("summernote."+t,e)}},{key:"initializeModule",value:function(t){var e=this.modules[t];e.shouldInitialize=e.shouldInitialize||v.ok,e.shouldInitialize()&&(e.initialize&&e.initialize(),e.events&&ht.attachEvents(this.$note,e.events))}},{key:"module",value:function(t,e,n){if(1===arguments.length)return this.modules[t];this.modules[t]=new e(this),n||this.initializeModule(t)}},{key:"removeModule",value:function(t){var e=this.modules[t];e.shouldInitialize()&&(e.events&&ht.detachEvents(this.$note,e.events),e.destroy&&e.destroy()),delete this.modules[t]}},{key:"memo",value:function(t,e){if(1===arguments.length)return this.memos[t];this.memos[t]=e}},{key:"removeMemo",value:function(t){this.memos[t]&&this.memos[t].destroy&&this.memos[t].destroy(),delete this.memos[t]}},{key:"createInvokeHandlerAndUpdateState",value:function(t,e){var n=this;return function(o){n.createInvokeHandler(t,e)(o),n.invoke("buttons.updateCurrentStyle")}}},{key:"createInvokeHandler",value:function(t,n){var o=this;return function(i){i.preventDefault();var r=e()(i.target);o.invoke(t,n||r.closest("[data-value]").data("value"),r)}}},{key:"invoke",value:function(){var t=k.head(arguments),e=k.tail(k.from(arguments)),n=t.split("."),o=n.length>1,i=o&&k.head(n),r=o?k.last(n):k.head(n),a=this.modules[i||"editor"];return!i&&this[r]?this[r].apply(this,e):a&&a[r]&&a.shouldInitialize()?a[r].apply(a,e):void 0}}],o&&ft(n.prototype,o),i&&ft(n,i),t}();function vt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}function mt(t,e){var n,o,i=t.parentElement(),r=document.body.createTextRange(),a=k.from(i.childNodes);for(n=0;n<a.length;n++)if(!ht.isText(a[n])){if(r.moveToElementText(a[n]),r.compareEndPoints("StartToStart",t)>=0)break;o=a[n]}if(0!==n&&ht.isText(a[n-1])){var s=document.body.createTextRange(),l=null;s.moveToElementText(o||i),s.collapse(!o),l=o?o.nextSibling:i.firstChild;var c=t.duplicate();c.setEndPoint("StartToStart",s);for(var u=c.text.replace(/[\r\n]/g,"").length;u>l.nodeValue.length&&l.nextSibling;)u-=l.nodeValue.length,l=l.nextSibling;l.nodeValue;e&&l.nextSibling&&ht.isText(l.nextSibling)&&u===l.nodeValue.length&&(u-=l.nodeValue.length,l=l.nextSibling),i=l,n=u}return{cont:i,offset:n}}function gt(t){var e=document.body.createTextRange(),n=function t(e,n){var o,i;if(ht.isText(e)){var r=ht.listPrev(e,v.not(ht.isText)),a=k.last(r).previousSibling;o=a||e.parentNode,n+=k.sum(k.tail(r),ht.nodeLength),i=!a}else{if(o=e.childNodes[n]||e,ht.isText(o))return t(o,0);n=0,i=!1}return{node:o,collapseToStart:i,offset:n}}(t.node,t.offset);return e.moveToElementText(n.node),e.collapse(n.collapseToStart),e.moveStart("character",n.offset),e}e().fn.extend({summernote:function(){var t=e().type(k.head(arguments)),n="string"===t,o="object"===t,i=e().extend({},e().summernote.options,o?k.head(arguments):{});i.langInfo=e().extend(!0,{},e().summernote.lang["en-US"],e().summernote.lang[i.lang]),i.icons=e().extend(!0,{},e().summernote.options.icons,i.icons),i.tooltip="auto"===i.tooltip?!f.isSupportTouch:i.tooltip,this.each((function(t,n){var o=e()(n);if(!o.data("summernote")){var r=new pt(o,i);o.data("summernote",r),o.data("summernote").triggerEvent("init",r.layoutInfo)}}));var r=this.first();if(r.length){var a=r.data("summernote");if(n)return a.invoke.apply(a,k.from(arguments));i.focus&&a.invoke("editor.focus")}return this}});var bt=function(){function t(e,n,o,i){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.sc=e,this.so=n,this.ec=o,this.eo=i,this.isOnEditable=this.makeIsOn(ht.isEditable),this.isOnList=this.makeIsOn(ht.isList),this.isOnAnchor=this.makeIsOn(ht.isAnchor),this.isOnCell=this.makeIsOn(ht.isCell),this.isOnData=this.makeIsOn(ht.isData)}var n,o,i;return n=t,o=[{key:"nativeRange",value:function(){if(f.isW3CRangeSupport){var t=document.createRange();return t.setStart(this.sc,this.so),t.setEnd(this.ec,this.eo),t}var e=gt({node:this.sc,offset:this.so});return e.setEndPoint("EndToEnd",gt({node:this.ec,offset:this.eo})),e}},{key:"getPoints",value:function(){return{sc:this.sc,so:this.so,ec:this.ec,eo:this.eo}}},{key:"getStartPoint",value:function(){return{node:this.sc,offset:this.so}}},{key:"getEndPoint",value:function(){return{node:this.ec,offset:this.eo}}},{key:"select",value:function(){var t=this.nativeRange();if(f.isW3CRangeSupport){var e=document.getSelection();e.rangeCount>0&&e.removeAllRanges(),e.addRange(t)}else t.select();return this}},{key:"scrollIntoView",value:function(t){var n=e()(t).height();return t.scrollTop+n<this.sc.offsetTop&&(t.scrollTop+=Math.abs(t.scrollTop+n-this.sc.offsetTop)),this}},{key:"normalize",value:function(){var e=function(t,e){if(!t)return t;if(ht.isVisiblePoint(t)&&(!ht.isEdgePoint(t)||ht.isRightEdgePoint(t)&&!e||ht.isLeftEdgePoint(t)&&e||ht.isRightEdgePoint(t)&&e&&ht.isVoid(t.node.nextSibling)||ht.isLeftEdgePoint(t)&&!e&&ht.isVoid(t.node.previousSibling)||ht.isBlock(t.node)&&ht.isEmpty(t.node)))return t;var n=ht.ancestor(t.node,ht.isBlock),o=!1;if(!o){var i=ht.prevPoint(t)||{node:null};o=(ht.isLeftEdgePointOf(t,n)||ht.isVoid(i.node))&&!e}var r=!1;if(!r){var a=ht.nextPoint(t)||{node:null};r=(ht.isRightEdgePointOf(t,n)||ht.isVoid(a.node))&&e}if(o||r){if(ht.isVisiblePoint(t))return t;e=!e}return(e?ht.nextPointUntil(ht.nextPoint(t),ht.isVisiblePoint):ht.prevPointUntil(ht.prevPoint(t),ht.isVisiblePoint))||t},n=e(this.getEndPoint(),!1),o=this.isCollapsed()?n:e(this.getStartPoint(),!0);return new t(o.node,o.offset,n.node,n.offset)}},{key:"nodes",value:function(t,e){t=t||v.ok;var n=e&&e.includeAncestor,o=e&&e.fullyContains,i=this.getStartPoint(),r=this.getEndPoint(),a=[],s=[];return ht.walkPoint(i,r,(function(e){var i;ht.isEditable(e.node)||(o?(ht.isLeftEdgePoint(e)&&s.push(e.node),ht.isRightEdgePoint(e)&&k.contains(s,e.node)&&(i=e.node)):i=n?ht.ancestor(e.node,t):e.node,i&&t(i)&&a.push(i))}),!0),k.unique(a)}},{key:"commonAncestor",value:function(){return ht.commonAncestor(this.sc,this.ec)}},{key:"expand",value:function(e){var n=ht.ancestor(this.sc,e),o=ht.ancestor(this.ec,e);if(!n&&!o)return new t(this.sc,this.so,this.ec,this.eo);var i=this.getPoints();return n&&(i.sc=n,i.so=0),o&&(i.ec=o,i.eo=ht.nodeLength(o)),new t(i.sc,i.so,i.ec,i.eo)}},{key:"collapse",value:function(e){return e?new t(this.sc,this.so,this.sc,this.so):new t(this.ec,this.eo,this.ec,this.eo)}},{key:"splitText",value:function(){var e=this.sc===this.ec,n=this.getPoints();return ht.isText(this.ec)&&!ht.isEdgePoint(this.getEndPoint())&&this.ec.splitText(this.eo),ht.isText(this.sc)&&!ht.isEdgePoint(this.getStartPoint())&&(n.sc=this.sc.splitText(this.so),n.so=0,e&&(n.ec=n.sc,n.eo=this.eo-this.so)),new t(n.sc,n.so,n.ec,n.eo)}},{key:"deleteContents",value:function(){if(this.isCollapsed())return this;var n=this.splitText(),o=n.nodes(null,{fullyContains:!0}),i=ht.prevPointUntil(n.getStartPoint(),(function(t){return!k.contains(o,t.node)})),r=[];return e().each(o,(function(t,e){var n=e.parentNode;i.node!==n&&1===ht.nodeLength(n)&&r.push(n),ht.remove(e,!1)})),e().each(r,(function(t,e){ht.remove(e,!1)})),new t(i.node,i.offset,i.node,i.offset).normalize()}},{key:"makeIsOn",value:function(t){return function(){var e=ht.ancestor(this.sc,t);return!!e&&e===ht.ancestor(this.ec,t)}}},{key:"isLeftEdgeOf",value:function(t){if(!ht.isLeftEdgePoint(this.getStartPoint()))return!1;var e=ht.ancestor(this.sc,t);return e&&ht.isLeftEdgeOf(this.sc,e)}},{key:"isCollapsed",value:function(){return this.sc===this.ec&&this.so===this.eo}},{key:"wrapBodyInlineWithPara",value:function(){if(ht.isBodyContainer(this.sc)&&ht.isEmpty(this.sc))return this.sc.innerHTML=ht.emptyPara,new t(this.sc.firstChild,0,this.sc.firstChild,0);var e,n=this.normalize();if(ht.isParaInline(this.sc)||ht.isPara(this.sc))return n;if(ht.isInline(n.sc)){var o=ht.listAncestor(n.sc,v.not(ht.isInline));e=k.last(o),ht.isInline(e)||(e=o[o.length-2]||n.sc.childNodes[n.so])}else e=n.sc.childNodes[n.so>0?n.so-1:0];if(e){var i=ht.listPrev(e,ht.isParaInline).reverse();if((i=i.concat(ht.listNext(e.nextSibling,ht.isParaInline))).length){var r=ht.wrap(k.head(i),"p");ht.appendChildNodes(r,k.tail(i))}}return this.normalize()}},{key:"insertNode",value:function(t){var e=this;(ht.isText(t)||ht.isInline(t))&&(e=this.wrapBodyInlineWithPara().deleteContents());var n=ht.splitPoint(e.getStartPoint(),ht.isInline(t));return n.rightNode?(n.rightNode.parentNode.insertBefore(t,n.rightNode),ht.isEmpty(n.rightNode)&&ht.isPara(t)&&n.rightNode.parentNode.removeChild(n.rightNode)):n.container.appendChild(t),t}},{key:"pasteHTML",value:function(t){t=e().trim(t);var n=e()("<div></div>").html(t)[0],o=k.from(n.childNodes),i=this,r=!1;return i.so>=0&&(o=o.reverse(),r=!0),o=o.map((function(t){return i.insertNode(t)})),r&&(o=o.reverse()),o}},{key:"toString",value:function(){var t=this.nativeRange();return f.isW3CRangeSupport?t.toString():t.text}},{key:"getWordRange",value:function(e){var n=this.getEndPoint();if(!ht.isCharPoint(n))return this;var o=ht.prevPointUntil(n,(function(t){return!ht.isCharPoint(t)}));return e&&(n=ht.nextPointUntil(n,(function(t){return!ht.isCharPoint(t)}))),new t(o.node,o.offset,n.node,n.offset)}},{key:"getWordsRange",value:function(e){var n=this.getEndPoint(),o=function(t){return!ht.isCharPoint(t)&&!ht.isSpacePoint(t)};if(o(n))return this;var i=ht.prevPointUntil(n,o);return e&&(n=ht.nextPointUntil(n,o)),new t(i.node,i.offset,n.node,n.offset)}},{key:"getWordsMatchRange",value:function(e){var n=this.getEndPoint(),o=ht.prevPointUntil(n,(function(o){if(!ht.isCharPoint(o)&&!ht.isSpacePoint(o))return!0;var i=new t(o.node,o.offset,n.node,n.offset),r=e.exec(i.toString());return r&&0===r.index})),i=new t(o.node,o.offset,n.node,n.offset),r=i.toString(),a=e.exec(r);return a&&a[0].length===r.length?i:null}},{key:"bookmark",value:function(t){return{s:{path:ht.makeOffsetPath(t,this.sc),offset:this.so},e:{path:ht.makeOffsetPath(t,this.ec),offset:this.eo}}}},{key:"paraBookmark",value:function(t){return{s:{path:k.tail(ht.makeOffsetPath(k.head(t),this.sc)),offset:this.so},e:{path:k.tail(ht.makeOffsetPath(k.last(t),this.ec)),offset:this.eo}}}},{key:"getClientRects",value:function(){return this.nativeRange().getClientRects()}}],o&&vt(n.prototype,o),i&&vt(n,i),t}();const yt={create:function(t,e,n,o){if(4===arguments.length)return new bt(t,e,n,o);if(2===arguments.length)return new bt(t,e,n=t,o=e);var i=this.createFromSelection();if(!i&&1===arguments.length){var r=arguments[0];return ht.isEditable(r)&&(r=r.lastChild),this.createFromBodyElement(r,ht.emptyPara===arguments[0].innerHTML)}return i},createFromBodyElement:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=this.createFromNode(t);return n.collapse(e)},createFromSelection:function(){var t,e,n,o;if(f.isW3CRangeSupport){var i=document.getSelection();if(!i||0===i.rangeCount)return null;if(ht.isBody(i.anchorNode))return null;var r=i.getRangeAt(0);t=r.startContainer,e=r.startOffset,n=r.endContainer,o=r.endOffset}else{var a=document.selection.createRange(),s=a.duplicate();s.collapse(!1);var l=a;l.collapse(!0);var c=mt(l,!0),u=mt(s,!1);ht.isText(c.node)&&ht.isLeftEdgePoint(c)&&ht.isTextNode(u.node)&&ht.isRightEdgePoint(u)&&u.node.nextSibling===c.node&&(c=u),t=c.cont,e=c.offset,n=u.cont,o=u.offset}return new bt(t,e,n,o)},createFromNode:function(t){var e=t,n=0,o=t,i=ht.nodeLength(o);return ht.isVoid(e)&&(n=ht.listPrev(e).length-1,e=e.parentNode),ht.isBR(o)?(i=ht.listPrev(o).length-1,o=o.parentNode):ht.isVoid(o)&&(i=ht.listPrev(o).length,o=o.parentNode),this.create(e,n,o,i)},createFromNodeBefore:function(t){return this.createFromNode(t).collapse(!0)},createFromNodeAfter:function(t){return this.createFromNode(t).collapse()},createFromBookmark:function(t,e){var n=ht.fromOffsetPath(t,e.s.path),o=e.s.offset,i=ht.fromOffsetPath(t,e.e.path),r=e.e.offset;return new bt(n,o,i,r)},createFromParaBookmark:function(t,e){var n=t.s.offset,o=t.e.offset,i=ht.fromOffsetPath(k.head(e),t.s.path),r=ht.fromOffsetPath(k.last(e),t.e.path);return new bt(i,n,r,o)}};var kt={BACKSPACE:8,TAB:9,ENTER:13,ESCAPE:27,SPACE:32,DELETE:46,LEFT:37,UP:38,RIGHT:39,DOWN:40,NUM0:48,NUM1:49,NUM2:50,NUM3:51,NUM4:52,NUM5:53,NUM6:54,NUM7:55,NUM8:56,B:66,E:69,I:73,J:74,K:75,L:76,R:82,S:83,U:85,V:86,Y:89,Z:90,SLASH:191,LEFTBRACKET:219,BACKSLASH:220,RIGHTBRACKET:221,HOME:36,END:35,PAGEUP:33,PAGEDOWN:34};const wt={isEdit:function(t){return k.contains([kt.BACKSPACE,kt.TAB,kt.ENTER,kt.SPACE,kt.DELETE],t)},isMove:function(t){return k.contains([kt.LEFT,kt.UP,kt.RIGHT,kt.DOWN],t)},isNavigation:function(t){return k.contains([kt.HOME,kt.END,kt.PAGEUP,kt.PAGEDOWN],t)},nameFromCode:v.invertObject(kt),code:kt};function Ct(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var xt=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.stack=[],this.stackOffset=-1,this.context=e,this.$editable=e.layoutInfo.editable,this.editable=this.$editable[0]}var e,n,o;return e=t,(n=[{key:"makeSnapshot",value:function(){var t=yt.create(this.editable);return{contents:this.$editable.html(),bookmark:t&&t.isOnEditable()?t.bookmark(this.editable):{s:{path:[],offset:0},e:{path:[],offset:0}}}}},{key:"applySnapshot",value:function(t){null!==t.contents&&this.$editable.html(t.contents),null!==t.bookmark&&yt.createFromBookmark(this.editable,t.bookmark).select()}},{key:"rewind",value:function(){this.$editable.html()!==this.stack[this.stackOffset].contents&&this.recordUndo(),this.stackOffset=0,this.applySnapshot(this.stack[this.stackOffset])}},{key:"commit",value:function(){this.stack=[],this.stackOffset=-1,this.recordUndo()}},{key:"reset",value:function(){this.stack=[],this.stackOffset=-1,this.$editable.html(""),this.recordUndo()}},{key:"undo",value:function(){this.$editable.html()!==this.stack[this.stackOffset].contents&&this.recordUndo(),this.stackOffset>0&&(this.stackOffset--,this.applySnapshot(this.stack[this.stackOffset]))}},{key:"redo",value:function(){this.stack.length-1>this.stackOffset&&(this.stackOffset++,this.applySnapshot(this.stack[this.stackOffset]))}},{key:"recordUndo",value:function(){this.stackOffset++,this.stack.length>this.stackOffset&&(this.stack=this.stack.slice(0,this.stackOffset)),this.stack.push(this.makeSnapshot()),this.stack.length>this.context.options.historyLimit&&(this.stack.shift(),this.stackOffset-=1)}}])&&Ct(e.prototype,n),o&&Ct(e,o),t}();function St(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Tt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var n,o,i;return n=t,o=[{key:"jQueryCSS",value:function(t,n){var o={};return e().each(n,(function(e,n){o[n]=t.css(n)})),o}},{key:"fromNode",value:function(t){var e=this.jQueryCSS(t,["font-family","font-size","text-align","list-style-type","line-height"])||{},n=t[0].style.fontSize||e["font-size"];return e["font-size"]=parseInt(n,10),e["font-size-unit"]=n.match(/[a-z%]+$/),e}},{key:"stylePara",value:function(t,n){e().each(t.nodes(ht.isPara,{includeAncestor:!0}),(function(t,o){e()(o).css(n)}))}},{key:"styleNodes",value:function(t,n){t=t.splitText();var o=n&&n.nodeName||"SPAN",i=!(!n||!n.expandClosestSibling),r=!(!n||!n.onlyPartialContains);if(t.isCollapsed())return[t.insertNode(ht.create(o))];var a=ht.makePredByNodeName(o),s=t.nodes(ht.isText,{fullyContains:!0}).map((function(t){return ht.singleChildAncestor(t,a)||ht.wrap(t,o)}));if(i){if(r){var l=t.nodes();a=v.and(a,(function(t){return k.contains(l,t)}))}return s.map((function(t){var n=ht.withClosestSiblings(t,a),o=k.head(n),i=k.tail(n);return e().each(i,(function(t,e){ht.appendChildNodes(o,e.childNodes),ht.remove(e)})),k.head(n)}))}return s}},{key:"current",value:function(t){var n=e()(ht.isElement(t.sc)?t.sc:t.sc.parentNode),o=this.fromNode(n);try{o=e().extend(o,{"font-bold":document.queryCommandState("bold")?"bold":"normal","font-italic":document.queryCommandState("italic")?"italic":"normal","font-underline":document.queryCommandState("underline")?"underline":"normal","font-subscript":document.queryCommandState("subscript")?"subscript":"normal","font-superscript":document.queryCommandState("superscript")?"superscript":"normal","font-strikethrough":document.queryCommandState("strikethrough")?"strikethrough":"normal","font-family":document.queryCommandValue("fontname")||o["font-family"]})}catch(t){}if(t.isOnList()){var i=["circle","disc","disc-leading-zero","square"].indexOf(o["list-style-type"])>-1;o["list-style"]=i?"unordered":"ordered"}else o["list-style"]="none";var r=ht.ancestor(t.sc,ht.isPara);if(r&&r.style["line-height"])o["line-height"]=r.style.lineHeight;else{var a=parseInt(o["line-height"],10)/parseInt(o["font-size"],10);o["line-height"]=a.toFixed(1)}return o.anchor=t.isOnAnchor()&&ht.ancestor(t.sc,ht.isAnchor),o.ancestors=ht.listAncestor(t.sc,ht.isEditable),o.range=t,o}}],o&&St(n.prototype,o),i&&St(n,i),t}();function Et(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var It=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var n,o,i;return n=t,o=[{key:"insertOrderedList",value:function(t){this.toggleList("OL",t)}},{key:"insertUnorderedList",value:function(t){this.toggleList("UL",t)}},{key:"indent",value:function(t){var n=this,o=yt.create(t).wrapBodyInlineWithPara(),i=o.nodes(ht.isPara,{includeAncestor:!0}),r=k.clusterBy(i,v.peq2("parentNode"));e().each(r,(function(t,o){var i=k.head(o);if(ht.isLi(i)){var r=n.findList(i.previousSibling);r?o.map((function(t){return r.appendChild(t)})):(n.wrapList(o,i.parentNode.nodeName),o.map((function(t){return t.parentNode})).map((function(t){return n.appendToPrevious(t)})))}else e().each(o,(function(t,n){e()(n).css("marginLeft",(function(t,e){return(parseInt(e,10)||0)+25}))}))})),o.select()}},{key:"outdent",value:function(t){var n=this,o=yt.create(t).wrapBodyInlineWithPara(),i=o.nodes(ht.isPara,{includeAncestor:!0}),r=k.clusterBy(i,v.peq2("parentNode"));e().each(r,(function(t,o){var i=k.head(o);ht.isLi(i)?n.releaseList([o]):e().each(o,(function(t,n){e()(n).css("marginLeft",(function(t,e){return(e=parseInt(e,10)||0)>25?e-25:""}))}))})),o.select()}},{key:"toggleList",value:function(t,n){var o=this,i=yt.create(n).wrapBodyInlineWithPara(),r=i.nodes(ht.isPara,{includeAncestor:!0}),a=i.paraBookmark(r),s=k.clusterBy(r,v.peq2("parentNode"));if(k.find(r,ht.isPurePara)){var l=[];e().each(s,(function(e,n){l=l.concat(o.wrapList(n,t))})),r=l}else{var c=i.nodes(ht.isList,{includeAncestor:!0}).filter((function(n){return!e().nodeName(n,t)}));c.length?e().each(c,(function(e,n){ht.replace(n,t)})):r=this.releaseList(s,!0)}yt.createFromParaBookmark(a,r).select()}},{key:"wrapList",value:function(t,e){var n=k.head(t),o=k.last(t),i=ht.isList(n.previousSibling)&&n.previousSibling,r=ht.isList(o.nextSibling)&&o.nextSibling,a=i||ht.insertAfter(ht.create(e||"UL"),o);return t=t.map((function(t){return ht.isPurePara(t)?ht.replace(t,"LI"):t})),ht.appendChildNodes(a,t),r&&(ht.appendChildNodes(a,k.from(r.childNodes)),ht.remove(r)),t}},{key:"releaseList",value:function(t,n){var o=this,i=[];return e().each(t,(function(t,r){var a=k.head(r),s=k.last(r),l=n?ht.lastAncestor(a,ht.isList):a.parentNode,c=l.parentNode;if("LI"===l.parentNode.nodeName)r.map((function(t){var e=o.findNextSiblings(t);c.nextSibling?c.parentNode.insertBefore(t,c.nextSibling):c.parentNode.appendChild(t),e.length&&(o.wrapList(e,l.nodeName),t.appendChild(e[0].parentNode))})),0===l.children.length&&c.removeChild(l),0===c.childNodes.length&&c.parentNode.removeChild(c);else{var u=l.childNodes.length>1?ht.splitTree(l,{node:s.parentNode,offset:ht.position(s)+1},{isSkipPaddingBlankHTML:!0}):null,d=ht.splitTree(l,{node:a.parentNode,offset:ht.position(a)},{isSkipPaddingBlankHTML:!0});r=n?ht.listDescendant(d,ht.isLi):k.from(d.childNodes).filter(ht.isLi),!n&&ht.isList(l.parentNode)||(r=r.map((function(t){return ht.replace(t,"P")}))),e().each(k.from(r).reverse(),(function(t,e){ht.insertAfter(e,l)}));var h=k.compact([l,d,u]);e().each(h,(function(t,n){var o=[n].concat(ht.listDescendant(n,ht.isList));e().each(o.reverse(),(function(t,e){ht.nodeLength(e)||ht.remove(e,!0)}))}))}i=i.concat(r)})),i}},{key:"appendToPrevious",value:function(t){return t.previousSibling?ht.appendChildNodes(t.previousSibling,[t]):this.wrapList([t],"LI")}},{key:"findList",value:function(t){return t?k.find(t.children,(function(t){return["OL","UL"].indexOf(t.nodeName)>-1})):null}},{key:"findNextSiblings",value:function(t){for(var e=[];t.nextSibling;)e.push(t.nextSibling),t=t.nextSibling;return e}}],o&&Et(n.prototype,o),i&&Et(n,i),t}();function $t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Nt=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.bullet=new It,this.options=e.options}var n,o,i;return n=t,o=[{key:"insertTab",value:function(t,e){var n=ht.createText(new Array(e+1).join(ht.NBSP_CHAR));(t=t.deleteContents()).insertNode(n,!0),(t=yt.create(n,e)).select()}},{key:"insertParagraph",value:function(t,n){n=(n=(n=n||yt.create(t)).deleteContents()).wrapBodyInlineWithPara();var o,i=ht.ancestor(n.sc,ht.isPara);if(i){if(ht.isLi(i)&&(ht.isEmpty(i)||ht.deepestChildIsEmpty(i)))return void this.bullet.toggleList(i.parentNode.nodeName);var r=null;if(1===this.options.blockquoteBreakingLevel?r=ht.ancestor(i,ht.isBlockquote):2===this.options.blockquoteBreakingLevel&&(r=ht.lastAncestor(i,ht.isBlockquote)),r){o=e()(ht.emptyPara)[0],ht.isRightEdgePoint(n.getStartPoint())&&ht.isBR(n.sc.nextSibling)&&e()(n.sc.nextSibling).remove();var a=ht.splitTree(r,n.getStartPoint(),{isDiscardEmptySplits:!0});a?a.parentNode.insertBefore(o,a):ht.insertAfter(o,r)}else{o=ht.splitTree(i,n.getStartPoint());var s=ht.listDescendant(i,ht.isEmptyAnchor);s=s.concat(ht.listDescendant(o,ht.isEmptyAnchor)),e().each(s,(function(t,e){ht.remove(e)})),(ht.isHeading(o)||ht.isPre(o)||ht.isCustomStyleTag(o))&&ht.isEmpty(o)&&(o=ht.replace(o,"p"))}}else{var l=n.sc.childNodes[n.so];o=e()(ht.emptyPara)[0],l?n.sc.insertBefore(o,l):n.sc.appendChild(o)}yt.create(o,0).normalize().select().scrollIntoView(t)}}],o&&$t(n.prototype,o),i&&$t(n,i),t}();function Pt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Rt=function t(e,n,o,i){var r={colPos:0,rowPos:0},a=[],s=[];function l(t,e,n,o,i,r,s){var l={baseRow:n,baseCell:o,isRowSpan:i,isColSpan:r,isVirtual:s};a[t]||(a[t]=[]),a[t][e]=l}function c(t,e,n,o){return{baseCell:t.baseCell,action:e,virtualTable:{rowIndex:n,cellIndex:o}}}function u(t,e){if(!a[t])return e;if(!a[t][e])return e;for(var n=e;a[t][n];)if(n++,!a[t][n])return n}function d(t,e){var n=u(t.rowIndex,e.cellIndex),o=e.colSpan>1,i=e.rowSpan>1,a=t.rowIndex===r.rowPos&&e.cellIndex===r.colPos;l(t.rowIndex,n,t,e,i,o,!1);var s=e.attributes.rowSpan?parseInt(e.attributes.rowSpan.value,10):0;if(s>1)for(var c=1;c<s;c++){var d=t.rowIndex+c;h(d,n,e,a),l(d,n,t,e,!0,o,!0)}var f=e.attributes.colSpan?parseInt(e.attributes.colSpan.value,10):0;if(f>1)for(var p=1;p<f;p++){var v=u(t.rowIndex,n+p);h(t.rowIndex,v,e,a),l(t.rowIndex,v,t,e,i,!0,!0)}}function h(t,e,n,o){t===r.rowPos&&r.colPos>=n.cellIndex&&n.cellIndex<=e&&!o&&r.colPos++}function f(e){switch(n){case t.where.Column:if(e.isColSpan)return t.resultAction.SubtractSpanCount;break;case t.where.Row:if(!e.isVirtual&&e.isRowSpan)return t.resultAction.AddCell;if(e.isRowSpan)return t.resultAction.SubtractSpanCount}return t.resultAction.RemoveCell}function p(e){switch(n){case t.where.Column:if(e.isColSpan)return t.resultAction.SumSpanCount;if(e.isRowSpan&&e.isVirtual)return t.resultAction.Ignore;break;case t.where.Row:if(e.isRowSpan)return t.resultAction.SumSpanCount;if(e.isColSpan&&e.isVirtual)return t.resultAction.Ignore}return t.resultAction.AddCell}this.getActionList=function(){for(var e=n===t.where.Row?r.rowPos:-1,i=n===t.where.Column?r.colPos:-1,l=0,u=!0;u;){var d=e>=0?e:l,h=i>=0?i:l,v=a[d];if(!v)return u=!1,s;var m=v[h];if(!m)return u=!1,s;var g=t.resultAction.Ignore;switch(o){case t.requestAction.Add:g=p(m);break;case t.requestAction.Delete:g=f(m)}s.push(c(m,g,d,h)),l++}return s},e&&e.tagName&&("td"===e.tagName.toLowerCase()||"th"===e.tagName.toLowerCase())&&(r.colPos=e.cellIndex,e.parentElement&&e.parentElement.tagName&&"tr"===e.parentElement.tagName.toLowerCase()&&(r.rowPos=e.parentElement.rowIndex)),function(){for(var t=i.rows,e=0;e<t.length;e++)for(var n=t[e].cells,o=0;o<n.length;o++)d(t[e],n[o])}()};Rt.where={Row:0,Column:1},Rt.requestAction={Add:0,Delete:1},Rt.resultAction={Ignore:0,SubtractSpanCount:1,RemoveCell:2,AddCell:3,SumSpanCount:4};var Lt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var n,o,i;return n=t,o=[{key:"tab",value:function(t,e){var n=ht.ancestor(t.commonAncestor(),ht.isCell),o=ht.ancestor(n,ht.isTable),i=ht.listDescendant(o,ht.isCell),r=k[e?"prev":"next"](i,n);r&&yt.create(r,0).select()}},{key:"addRow",value:function(t,n){for(var o=ht.ancestor(t.commonAncestor(),ht.isCell),i=e()(o).closest("tr"),r=this.recoverAttributes(i),a=e()("<tr"+r+"></tr>"),s=new Rt(o,Rt.where.Row,Rt.requestAction.Add,e()(i).closest("table")[0]).getActionList(),l=0;l<s.length;l++){var c=s[l],u=this.recoverAttributes(c.baseCell);switch(c.action){case Rt.resultAction.AddCell:a.append("<td"+u+">"+ht.blank+"</td>");break;case Rt.resultAction.SumSpanCount:if("top"===n&&(c.baseCell.parent?c.baseCell.closest("tr").rowIndex:0)<=i[0].rowIndex){var d=e()("<div></div>").append(e()("<td"+u+">"+ht.blank+"</td>").removeAttr("rowspan")).html();a.append(d);break}var h=parseInt(c.baseCell.rowSpan,10);h++,c.baseCell.setAttribute("rowSpan",h)}}if("top"===n)i.before(a);else{if(o.rowSpan>1){var f=i[0].rowIndex+(o.rowSpan-2);return void e()(e()(i).parent().find("tr")[f]).after(e()(a))}i.after(a)}}},{key:"addCol",value:function(t,n){var o=ht.ancestor(t.commonAncestor(),ht.isCell),i=e()(o).closest("tr");e()(i).siblings().push(i);for(var r=new Rt(o,Rt.where.Column,Rt.requestAction.Add,e()(i).closest("table")[0]).getActionList(),a=0;a<r.length;a++){var s=r[a],l=this.recoverAttributes(s.baseCell);switch(s.action){case Rt.resultAction.AddCell:"right"===n?e()(s.baseCell).after("<td"+l+">"+ht.blank+"</td>"):e()(s.baseCell).before("<td"+l+">"+ht.blank+"</td>");break;case Rt.resultAction.SumSpanCount:if("right"===n){var c=parseInt(s.baseCell.colSpan,10);c++,s.baseCell.setAttribute("colSpan",c)}else e()(s.baseCell).before("<td"+l+">"+ht.blank+"</td>")}}}},{key:"recoverAttributes",value:function(t){var e="";if(!t)return e;for(var n=t.attributes||[],o=0;o<n.length;o++)"id"!==n[o].name.toLowerCase()&&n[o].specified&&(e+=" "+n[o].name+"='"+n[o].value+"'");return e}},{key:"deleteRow",value:function(t){for(var n=ht.ancestor(t.commonAncestor(),ht.isCell),o=e()(n).closest("tr"),i=o.children("td, th").index(e()(n)),r=o[0].rowIndex,a=new Rt(n,Rt.where.Row,Rt.requestAction.Delete,e()(o).closest("table")[0]).getActionList(),s=0;s<a.length;s++)if(a[s]){var l=a[s].baseCell,c=a[s].virtualTable,u=l.rowSpan&&l.rowSpan>1,d=u?parseInt(l.rowSpan,10):0;switch(a[s].action){case Rt.resultAction.Ignore:continue;case Rt.resultAction.AddCell:var h=o.next("tr")[0];if(!h)continue;var f=o[0].cells[i];u&&(d>2?(d--,h.insertBefore(f,h.cells[i]),h.cells[i].setAttribute("rowSpan",d),h.cells[i].innerHTML=""):2===d&&(h.insertBefore(f,h.cells[i]),h.cells[i].removeAttribute("rowSpan"),h.cells[i].innerHTML=""));continue;case Rt.resultAction.SubtractSpanCount:u&&(d>2?(d--,l.setAttribute("rowSpan",d),c.rowIndex!==r&&l.cellIndex===i&&(l.innerHTML="")):2===d&&(l.removeAttribute("rowSpan"),c.rowIndex!==r&&l.cellIndex===i&&(l.innerHTML="")));continue;case Rt.resultAction.RemoveCell:continue}}o.remove()}},{key:"deleteCol",value:function(t){for(var n=ht.ancestor(t.commonAncestor(),ht.isCell),o=e()(n).closest("tr"),i=o.children("td, th").index(e()(n)),r=new Rt(n,Rt.where.Column,Rt.requestAction.Delete,e()(o).closest("table")[0]).getActionList(),a=0;a<r.length;a++)if(r[a])switch(r[a].action){case Rt.resultAction.Ignore:continue;case Rt.resultAction.SubtractSpanCount:var s=r[a].baseCell;if(s.colSpan&&s.colSpan>1){var l=s.colSpan?parseInt(s.colSpan,10):0;l>2?(l--,s.setAttribute("colSpan",l),s.cellIndex===i&&(s.innerHTML="")):2===l&&(s.removeAttribute("colSpan"),s.cellIndex===i&&(s.innerHTML=""))}continue;case Rt.resultAction.RemoveCell:ht.remove(r[a].baseCell,!0);continue}}},{key:"createTable",value:function(t,n,o){for(var i,r=[],a=0;a<t;a++)r.push("<td>"+ht.blank+"</td>");i=r.join("");for(var s,l=[],c=0;c<n;c++)l.push("<tr>"+i+"</tr>");s=l.join("");var u=e()("<table>"+s+"</table>");return o&&o.tableClassName&&u.addClass(o.tableClassName),u[0]}},{key:"deleteTable",value:function(t){var n=ht.ancestor(t.commonAncestor(),ht.isCell);e()(n).closest("table").remove()}}],o&&Pt(n.prototype,o),i&&Pt(n,i),t}();function At(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Ft=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$note=n.layoutInfo.note,this.$editor=n.layoutInfo.editor,this.$editable=n.layoutInfo.editable,this.options=n.options,this.lang=this.options.langInfo,this.editable=this.$editable[0],this.lastRange=null,this.snapshot=null,this.style=new Tt,this.table=new Lt,this.typing=new Nt(n),this.bullet=new It,this.history=new xt(n),this.context.memo("help.escape",this.lang.help.escape),this.context.memo("help.undo",this.lang.help.undo),this.context.memo("help.redo",this.lang.help.redo),this.context.memo("help.tab",this.lang.help.tab),this.context.memo("help.untab",this.lang.help.untab),this.context.memo("help.insertParagraph",this.lang.help.insertParagraph),this.context.memo("help.insertOrderedList",this.lang.help.insertOrderedList),this.context.memo("help.insertUnorderedList",this.lang.help.insertUnorderedList),this.context.memo("help.indent",this.lang.help.indent),this.context.memo("help.outdent",this.lang.help.outdent),this.context.memo("help.formatPara",this.lang.help.formatPara),this.context.memo("help.insertHorizontalRule",this.lang.help.insertHorizontalRule),this.context.memo("help.fontName",this.lang.help.fontName);for(var i=["bold","italic","underline","strikethrough","superscript","subscript","justifyLeft","justifyCenter","justifyRight","justifyFull","formatBlock","removeFormat","backColor"],r=0,a=i.length;r<a;r++)this[i[r]]=function(t){return function(e){o.beforeCommand(),document.execCommand(t,!1,e),o.afterCommand(!0)}}(i[r]),this.context.memo("help."+i[r],this.lang.help[i[r]]);this.fontName=this.wrapCommand((function(t){return o.fontStyling("font-family",f.validFontName(t))})),this.fontSize=this.wrapCommand((function(t){var e=o.currentStyle()["font-size-unit"];return o.fontStyling("font-size",t+e)})),this.fontSizeUnit=this.wrapCommand((function(t){var e=o.currentStyle()["font-size"];return o.fontStyling("font-size",e+t)}));for(var s=1;s<=6;s++)this["formatH"+s]=function(t){return function(){o.formatBlock("H"+t)}}(s),this.context.memo("help.formatH"+s,this.lang.help["formatH"+s]);this.insertParagraph=this.wrapCommand((function(){o.typing.insertParagraph(o.editable)})),this.insertOrderedList=this.wrapCommand((function(){o.bullet.insertOrderedList(o.editable)})),this.insertUnorderedList=this.wrapCommand((function(){o.bullet.insertUnorderedList(o.editable)})),this.indent=this.wrapCommand((function(){o.bullet.indent(o.editable)})),this.outdent=this.wrapCommand((function(){o.bullet.outdent(o.editable)})),this.insertNode=this.wrapCommand((function(t){o.isLimited(e()(t).text().length)||(o.getLastRange().insertNode(t),o.setLastRange(yt.createFromNodeAfter(t).select()))})),this.insertText=this.wrapCommand((function(t){if(!o.isLimited(t.length)){var e=o.getLastRange().insertNode(ht.createText(t));o.setLastRange(yt.create(e,ht.nodeLength(e)).select())}})),this.pasteHTML=this.wrapCommand((function(t){if(!o.isLimited(t.length)){t=o.context.invoke("codeview.purify",t);var e=o.getLastRange().pasteHTML(t);o.setLastRange(yt.createFromNodeAfter(k.last(e)).select())}})),this.formatBlock=this.wrapCommand((function(t,e){var n=o.options.callbacks.onApplyCustomStyle;n?n.call(o,e,o.context,o.onFormatBlock):o.onFormatBlock(t,e)})),this.insertHorizontalRule=this.wrapCommand((function(){var t=o.getLastRange().insertNode(ht.create("HR"));t.nextSibling&&o.setLastRange(yt.create(t.nextSibling,0).normalize().select())})),this.lineHeight=this.wrapCommand((function(t){o.style.stylePara(o.getLastRange(),{lineHeight:t})})),this.createLink=this.wrapCommand((function(t){var n=t.url,i=t.text,r=t.isNewWindow,a=t.checkProtocol,s=t.range||o.getLastRange(),l=i.length-s.toString().length;if(!(l>0&&o.isLimited(l))){var c=s.toString()!==i;"string"==typeof n&&(n=n.trim()),o.options.onCreateLink?n=o.options.onCreateLink(n):a&&(n=/^([A-Za-z][A-Za-z0-9+-.]*\:|#|\/)/.test(n)?n:o.options.defaultProtocol+n);var u=[];if(c){var d=(s=s.deleteContents()).insertNode(e()("<A>"+i+"</A>")[0]);u.push(d)}else u=o.style.styleNodes(s,{nodeName:"A",expandClosestSibling:!0,onlyPartialContains:!0});e().each(u,(function(t,o){e()(o).attr("href",n),r?e()(o).attr("target","_blank"):e()(o).removeAttr("target")})),o.setLastRange(o.createRangeFromList(u).select())}})),this.color=this.wrapCommand((function(t){var e=t.foreColor,n=t.backColor;e&&document.execCommand("foreColor",!1,e),n&&document.execCommand("backColor",!1,n)})),this.foreColor=this.wrapCommand((function(t){document.execCommand("foreColor",!1,t)})),this.insertTable=this.wrapCommand((function(t){var e=t.split("x");o.getLastRange().deleteContents().insertNode(o.table.createTable(e[0],e[1],o.options))})),this.removeMedia=this.wrapCommand((function(){var t=e()(o.restoreTarget()).parent();t.closest("figure").length?t.closest("figure").remove():t=e()(o.restoreTarget()).detach(),o.context.triggerEvent("media.delete",t,o.$editable)})),this.floatMe=this.wrapCommand((function(t){var n=e()(o.restoreTarget());n.toggleClass("note-float-left","left"===t),n.toggleClass("note-float-right","right"===t),n.css("float","none"===t?"":t)})),this.resize=this.wrapCommand((function(t){var n=e()(o.restoreTarget());0===(t=parseFloat(t))?n.css("width",""):n.css({width:100*t+"%",height:""})}))}var n,o,i;return n=t,o=[{key:"initialize",value:function(){var t=this;this.$editable.on("keydown",(function(e){if(e.keyCode===wt.code.ENTER&&t.context.triggerEvent("enter",e),t.context.triggerEvent("keydown",e),t.snapshot=t.history.makeSnapshot(),t.hasKeyShortCut=!1,e.isDefaultPrevented()||(t.options.shortcuts?t.hasKeyShortCut=t.handleKeyMap(e):t.preventDefaultEditableShortCuts(e)),t.isLimited(1,e)){var n=t.getLastRange();if(n.eo-n.so==0)return!1}t.setLastRange(),t.options.recordEveryKeystroke&&!1===t.hasKeyShortCut&&t.history.recordUndo()})).on("keyup",(function(e){t.setLastRange(),t.context.triggerEvent("keyup",e)})).on("focus",(function(e){t.setLastRange(),t.context.triggerEvent("focus",e)})).on("blur",(function(e){t.context.triggerEvent("blur",e)})).on("mousedown",(function(e){t.context.triggerEvent("mousedown",e)})).on("mouseup",(function(e){t.setLastRange(),t.history.recordUndo(),t.context.triggerEvent("mouseup",e)})).on("scroll",(function(e){t.context.triggerEvent("scroll",e)})).on("paste",(function(e){t.setLastRange(),t.context.triggerEvent("paste",e)})).on("input",(function(){t.isLimited(0)&&t.snapshot&&t.history.applySnapshot(t.snapshot)})),this.$editable.attr("spellcheck",this.options.spellCheck),this.$editable.attr("autocorrect",this.options.spellCheck),this.options.disableGrammar&&this.$editable.attr("data-gramm",!1),this.$editable.html(ht.html(this.$note)||ht.emptyPara),this.$editable.on(f.inputEventName,v.debounce((function(){t.context.triggerEvent("change",t.$editable.html(),t.$editable)}),10)),this.$editable.on("focusin",(function(e){t.context.triggerEvent("focusin",e)})).on("focusout",(function(e){t.context.triggerEvent("focusout",e)})),this.options.airMode?this.options.overrideContextMenu&&this.$editor.on("contextmenu",(function(e){return t.context.triggerEvent("contextmenu",e),!1})):(this.options.width&&this.$editor.outerWidth(this.options.width),this.options.height&&this.$editable.outerHeight(this.options.height),this.options.maxHeight&&this.$editable.css("max-height",this.options.maxHeight),this.options.minHeight&&this.$editable.css("min-height",this.options.minHeight)),this.history.recordUndo(),this.setLastRange()}},{key:"destroy",value:function(){this.$editable.off()}},{key:"handleKeyMap",value:function(t){var e=this.options.keyMap[f.isMac?"mac":"pc"],n=[];t.metaKey&&n.push("CMD"),t.ctrlKey&&!t.altKey&&n.push("CTRL"),t.shiftKey&&n.push("SHIFT");var o=wt.nameFromCode[t.keyCode];o&&n.push(o);var i=e[n.join("+")];if("TAB"!==o||this.options.tabDisable)if(i){if(!1!==this.context.invoke(i))return t.preventDefault(),!0}else wt.isEdit(t.keyCode)&&this.afterCommand();else this.afterCommand();return!1}},{key:"preventDefaultEditableShortCuts",value:function(t){(t.ctrlKey||t.metaKey)&&k.contains([66,73,85],t.keyCode)&&t.preventDefault()}},{key:"isLimited",value:function(t,e){return t=t||0,(void 0===e||!(wt.isMove(e.keyCode)||wt.isNavigation(e.keyCode)||e.ctrlKey||e.metaKey||k.contains([wt.code.BACKSPACE,wt.code.DELETE],e.keyCode)))&&this.options.maxTextLength>0&&this.$editable.text().length+t>this.options.maxTextLength}},{key:"createRange",value:function(){return this.focus(),this.setLastRange(),this.getLastRange()}},{key:"createRangeFromList",value:function(t){var e=yt.createFromNodeBefore(k.head(t)).getStartPoint(),n=yt.createFromNodeAfter(k.last(t)).getEndPoint();return yt.create(e.node,e.offset,n.node,n.offset)}},{key:"setLastRange",value:function(t){t?this.lastRange=t:(this.lastRange=yt.create(this.editable),0===e()(this.lastRange.sc).closest(".note-editable").length&&(this.lastRange=yt.createFromBodyElement(this.editable)))}},{key:"getLastRange",value:function(){return this.lastRange||this.setLastRange(),this.lastRange}},{key:"saveRange",value:function(t){t&&this.getLastRange().collapse().select()}},{key:"restoreRange",value:function(){this.lastRange&&(this.lastRange.select(),this.focus())}},{key:"saveTarget",value:function(t){this.$editable.data("target",t)}},{key:"clearTarget",value:function(){this.$editable.removeData("target")}},{key:"restoreTarget",value:function(){return this.$editable.data("target")}},{key:"currentStyle",value:function(){var t=yt.create();return t&&(t=t.normalize()),t?this.style.current(t):this.style.fromNode(this.$editable)}},{key:"styleFromNode",value:function(t){return this.style.fromNode(t)}},{key:"undo",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.undo(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"commit",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.commit(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"redo",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.redo(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"beforeCommand",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),document.execCommand("styleWithCSS",!1,this.options.styleWithCSS),this.focus()}},{key:"afterCommand",value:function(t){this.normalizeContent(),this.history.recordUndo(),t||this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"tab",value:function(){var t=this.getLastRange();if(t.isCollapsed()&&t.isOnCell())this.table.tab(t);else{if(0===this.options.tabSize)return!1;this.isLimited(this.options.tabSize)||(this.beforeCommand(),this.typing.insertTab(t,this.options.tabSize),this.afterCommand())}}},{key:"untab",value:function(){var t=this.getLastRange();if(t.isCollapsed()&&t.isOnCell())this.table.tab(t,!0);else if(0===this.options.tabSize)return!1}},{key:"wrapCommand",value:function(t){return function(){this.beforeCommand(),t.apply(this,arguments),this.afterCommand()}}},{key:"insertImage",value:function(t,n){var o,i=this;return(o=t,e().Deferred((function(t){var n=e()("<img>");n.one("load",(function(){n.off("error abort"),t.resolve(n)})).one("error abort",(function(){n.off("load").detach(),t.reject(n)})).css({display:"none"}).appendTo(document.body).attr("src",o)})).promise()).then((function(t){i.beforeCommand(),"function"==typeof n?n(t):("string"==typeof n&&t.attr("data-filename",n),t.css("width",Math.min(i.$editable.width(),t.width()))),t.show(),i.getLastRange().insertNode(t[0]),i.setLastRange(yt.createFromNodeAfter(t[0]).select()),i.afterCommand()})).fail((function(t){i.context.triggerEvent("image.upload.error",t)}))}},{key:"insertImagesAsDataURL",value:function(t){var n=this;e().each(t,(function(t,o){var i=o.name;n.options.maximumImageFileSize&&n.options.maximumImageFileSize<o.size?n.context.triggerEvent("image.upload.error",n.lang.image.maximumFileSizeError):function(t){return e().Deferred((function(n){e().extend(new FileReader,{onload:function(t){var e=t.target.result;n.resolve(e)},onerror:function(t){n.reject(t)}}).readAsDataURL(t)})).promise()}(o).then((function(t){return n.insertImage(t,i)})).fail((function(){n.context.triggerEvent("image.upload.error")}))}))}},{key:"insertImagesOrCallback",value:function(t){this.options.callbacks.onImageUpload?this.context.triggerEvent("image.upload",t):this.insertImagesAsDataURL(t)}},{key:"getSelectedText",value:function(){var t=this.getLastRange();return t.isOnAnchor()&&(t=yt.createFromNode(ht.ancestor(t.sc,ht.isAnchor))),t.toString()}},{key:"onFormatBlock",value:function(t,n){if(document.execCommand("FormatBlock",!1,f.isMSIE?"<"+t+">":t),n&&n.length&&(n[0].tagName.toUpperCase()!==t.toUpperCase()&&(n=n.find(t)),n&&n.length)){var o=this.createRange(),i=e()([o.sc,o.ec]).closest(t);i.removeClass();var r=n[0].className||"";r&&i.addClass(r)}}},{key:"formatPara",value:function(){this.formatBlock("P")}},{key:"fontStyling",value:function(t,n){var o=this.getLastRange();if(""!==o){var i=this.style.styleNodes(o);if(this.$editor.find(".note-status-output").html(""),e()(i).css(t,n),o.isCollapsed()){var r=k.head(i);r&&!ht.nodeLength(r)&&(r.innerHTML=ht.ZERO_WIDTH_NBSP_CHAR,yt.createFromNode(r.firstChild).select(),this.setLastRange(),this.$editable.data("bogus",r))}else this.setLastRange(this.createRangeFromList(i).select())}else{var a=e().now();this.$editor.find(".note-status-output").html('<div id="note-status-output-'+a+'" class="alert alert-info">'+this.lang.output.noSelection+"</div>"),setTimeout((function(){e()("#note-status-output-"+a).remove()}),5e3)}}},{key:"unlink",value:function(){var t=this.getLastRange();if(t.isOnAnchor()){var e=ht.ancestor(t.sc,ht.isAnchor);(t=yt.createFromNode(e)).select(),this.setLastRange(),this.beforeCommand(),document.execCommand("unlink"),this.afterCommand()}}},{key:"getLinkInfo",value:function(){var t=this.getLastRange().expand(ht.isAnchor),n=e()(k.head(t.nodes(ht.isAnchor))),o={range:t,text:t.toString(),url:n.length?n.attr("href"):""};return n.length&&(o.isNewWindow="_blank"===n.attr("target")),o}},{key:"addRow",value:function(t){var e=this.getLastRange(this.$editable);e.isCollapsed()&&e.isOnCell()&&(this.beforeCommand(),this.table.addRow(e,t),this.afterCommand())}},{key:"addCol",value:function(t){var e=this.getLastRange(this.$editable);e.isCollapsed()&&e.isOnCell()&&(this.beforeCommand(),this.table.addCol(e,t),this.afterCommand())}},{key:"deleteRow",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteRow(t),this.afterCommand())}},{key:"deleteCol",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteCol(t),this.afterCommand())}},{key:"deleteTable",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteTable(t),this.afterCommand())}},{key:"resizeTo",value:function(t,e,n){var o;if(n){var i=t.y/t.x,r=e.data("ratio");o={width:r>i?t.x:t.y/r,height:r>i?t.x*r:t.y}}else o={width:t.x,height:t.y};e.css(o)}},{key:"hasFocus",value:function(){return this.$editable.is(":focus")}},{key:"focus",value:function(){this.hasFocus()||this.$editable.focus()}},{key:"isEmpty",value:function(){return ht.isEmpty(this.$editable[0])||ht.emptyPara===this.$editable.html()}},{key:"empty",value:function(){this.context.invoke("code",ht.emptyPara)}},{key:"normalizeContent",value:function(){this.$editable[0].normalize()}}],o&&At(n.prototype,o),i&&At(n,i),t}();function Dt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Ht=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editable=e.layoutInfo.editable}var e,n,o;return e=t,(n=[{key:"initialize",value:function(){this.$editable.on("paste",this.pasteByEvent.bind(this))}},{key:"pasteByEvent",value:function(t){var e=this,n=t.originalEvent.clipboardData;if(n&&n.items&&n.items.length){var o=n.items.length>1?n.items[1]:k.head(n.items);"file"===o.kind&&-1!==o.type.indexOf("image/")?(this.context.invoke("editor.insertImagesOrCallback",[o.getAsFile()]),t.preventDefault()):"string"===o.kind&&this.context.invoke("editor.isLimited",n.getData("Text").length)&&t.preventDefault()}else if(window.clipboardData){var i=window.clipboardData.getData("text");this.context.invoke("editor.isLimited",i.length)&&t.preventDefault()}setTimeout((function(){e.context.invoke("editor.afterCommand")}),10)}}])&&Dt(e.prototype,n),o&&Dt(e,o),t}();function zt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Bt=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$eventListener=e()(document),this.$editor=n.layoutInfo.editor,this.$editable=n.layoutInfo.editable,this.options=n.options,this.lang=this.options.langInfo,this.documentEventHandlers={},this.$dropzone=e()(['<div class="note-dropzone">','<div class="note-dropzone-message"></div>',"</div>"].join("")).prependTo(this.$editor)}var n,o,i;return n=t,o=[{key:"initialize",value:function(){this.options.disableDragAndDrop?(this.documentEventHandlers.onDrop=function(t){t.preventDefault()},this.$eventListener=this.$dropzone,this.$eventListener.on("drop",this.documentEventHandlers.onDrop)):this.attachDragAndDropEvent()}},{key:"attachDragAndDropEvent",value:function(){var t=this,n=e()(),o=this.$dropzone.find(".note-dropzone-message");this.documentEventHandlers.onDragenter=function(e){var i=t.context.invoke("codeview.isActivated"),r=t.$editor.width()>0&&t.$editor.height()>0;i||n.length||!r||(t.$editor.addClass("dragover"),t.$dropzone.width(t.$editor.width()),t.$dropzone.height(t.$editor.height()),o.text(t.lang.image.dragImageHere)),n=n.add(e.target)},this.documentEventHandlers.onDragleave=function(o){(n=n.not(o.target)).length&&"BODY"!==o.target.nodeName||(n=e()(),t.$editor.removeClass("dragover"))},this.documentEventHandlers.onDrop=function(){n=e()(),t.$editor.removeClass("dragover")},this.$eventListener.on("dragenter",this.documentEventHandlers.onDragenter).on("dragleave",this.documentEventHandlers.onDragleave).on("drop",this.documentEventHandlers.onDrop),this.$dropzone.on("dragenter",(function(){t.$dropzone.addClass("hover"),o.text(t.lang.image.dropImage)})).on("dragleave",(function(){t.$dropzone.removeClass("hover"),o.text(t.lang.image.dragImageHere)})),this.$dropzone.on("drop",(function(n){var o=n.originalEvent.dataTransfer;n.preventDefault(),o&&o.files&&o.files.length?(t.$editable.focus(),t.context.invoke("editor.insertImagesOrCallback",o.files)):e().each(o.types,(function(n,i){if(!(i.toLowerCase().indexOf("_moz_")>-1)){var r=o.getData(i);i.toLowerCase().indexOf("text")>-1?t.context.invoke("editor.pasteHTML",r):e()(r).each((function(e,n){t.context.invoke("editor.insertNode",n)}))}}))})).on("dragover",!1)}},{key:"destroy",value:function(){var t=this;Object.keys(this.documentEventHandlers).forEach((function(e){t.$eventListener.off(e.substr(2).toLowerCase(),t.documentEventHandlers[e])})),this.documentEventHandlers={}}}],o&&zt(n.prototype,o),i&&zt(n,i),t}();function Mt(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(!t)return;if("string"==typeof t)return Ot(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Ot(t,e)}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,i=function(){};return{s:i,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,r=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw r}}}}function Ot(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=new Array(e);n<e;n++)o[n]=t[n];return o}function Ut(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var jt=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editor=e.layoutInfo.editor,this.$editable=e.layoutInfo.editable,this.$codable=e.layoutInfo.codable,this.options=e.options,this.CodeMirrorConstructor=window.CodeMirror,this.options.codemirror.CodeMirrorConstructor&&(this.CodeMirrorConstructor=this.options.codemirror.CodeMirrorConstructor)}var e,n,o;return e=t,n=[{key:"sync",value:function(t){var e=this.isActivated(),n=this.CodeMirrorConstructor;e&&(t?n?this.$codable.data("cmEditor").getDoc().setValue(t):this.$codable.val(t):n&&this.$codable.data("cmEditor").save())}},{key:"initialize",value:function(){var t=this;this.$codable.on("keyup",(function(e){e.keyCode===wt.code.ESCAPE&&t.deactivate()}))}},{key:"isActivated",value:function(){return this.$editor.hasClass("codeview")}},{key:"toggle",value:function(){this.isActivated()?this.deactivate():this.activate(),this.context.triggerEvent("codeview.toggled")}},{key:"purify",value:function(t){if(this.options.codeviewFilter&&(t=t.replace(this.options.codeviewFilterRegex,""),this.options.codeviewIframeFilter)){var e=this.options.codeviewIframeWhitelistSrc.concat(this.options.codeviewIframeWhitelistSrcBase);t=t.replace(/(<iframe.*?>.*?(?:<\/iframe>)?)/gi,(function(t){if(/<.+src(?==?('|"|\s)?)[\s\S]+src(?=('|"|\s)?)[^>]*?>/i.test(t))return"";var n,o=Mt(e);try{for(o.s();!(n=o.n()).done;){var i=n.value;if(new RegExp('src="(https?:)?//'+i.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")+'/(.+)"').test(t))return t}}catch(t){o.e(t)}finally{o.f()}return""}))}return t}},{key:"activate",value:function(){var t=this,e=this.CodeMirrorConstructor;if(this.$codable.val(ht.html(this.$editable,this.options.prettifyHtml)),this.$codable.height(this.$editable.height()),this.context.invoke("toolbar.updateCodeview",!0),this.context.invoke("airPopover.updateCodeview",!0),this.$editor.addClass("codeview"),this.$codable.focus(),e){var n=e.fromTextArea(this.$codable[0],this.options.codemirror);if(this.options.codemirror.tern){var o=new e.TernServer(this.options.codemirror.tern);n.ternServer=o,n.on("cursorActivity",(function(t){o.updateArgHints(t)}))}n.on("blur",(function(e){t.context.triggerEvent("blur.codeview",n.getValue(),e)})),n.on("change",(function(){t.context.triggerEvent("change.codeview",n.getValue(),n)})),n.setSize(null,this.$editable.outerHeight()),this.$codable.data("cmEditor",n)}else this.$codable.on("blur",(function(e){t.context.triggerEvent("blur.codeview",t.$codable.val(),e)})),this.$codable.on("input",(function(){t.context.triggerEvent("change.codeview",t.$codable.val(),t.$codable)}))}},{key:"deactivate",value:function(){if(this.CodeMirrorConstructor){var t=this.$codable.data("cmEditor");this.$codable.val(t.getValue()),t.toTextArea()}var e=this.purify(ht.value(this.$codable,this.options.prettifyHtml)||ht.emptyPara),n=this.$editable.html()!==e;this.$editable.html(e),this.$editable.height(this.options.height?this.$codable.height():"auto"),this.$editor.removeClass("codeview"),n&&this.context.triggerEvent("change",this.$editable.html(),this.$editable),this.$editable.focus(),this.context.invoke("toolbar.updateCodeview",!1),this.context.invoke("airPopover.updateCodeview",!1)}},{key:"destroy",value:function(){this.isActivated()&&this.deactivate()}}],n&&Ut(e.prototype,n),o&&Ut(e,o),t}();function Wt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Kt=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$document=e()(document),this.$statusbar=n.layoutInfo.statusbar,this.$editable=n.layoutInfo.editable,this.$codable=n.layoutInfo.codable,this.options=n.options}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t=this;this.options.airMode||this.options.disableResizeEditor?this.destroy():this.$statusbar.on("mousedown",(function(e){e.preventDefault(),e.stopPropagation();var n=t.$editable.offset().top-t.$document.scrollTop(),o=t.$codable.offset().top-t.$document.scrollTop(),i=function(e){var i=e.clientY-(n+24),r=e.clientY-(o+24);i=t.options.minheight>0?Math.max(i,t.options.minheight):i,i=t.options.maxHeight>0?Math.min(i,t.options.maxHeight):i,r=t.options.minheight>0?Math.max(r,t.options.minheight):r,r=t.options.maxHeight>0?Math.min(r,t.options.maxHeight):r,t.$editable.height(i),t.$codable.height(r)};t.$document.on("mousemove",i).one("mouseup",(function(){t.$document.off("mousemove",i)}))}))}},{key:"destroy",value:function(){this.$statusbar.off(),this.$statusbar.addClass("locked")}}])&&Wt(n.prototype,o),i&&Wt(n,i),t}();function Vt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var qt=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$editor=n.layoutInfo.editor,this.$toolbar=n.layoutInfo.toolbar,this.$editable=n.layoutInfo.editable,this.$codable=n.layoutInfo.codable,this.$window=e()(window),this.$scrollbar=e()("html, body"),this.scrollbarClassName="note-fullscreen-body",this.onResize=function(){o.resizeTo({h:o.$window.height()-o.$toolbar.outerHeight()})}}var n,o,i;return n=t,(o=[{key:"resizeTo",value:function(t){this.$editable.css("height",t.h),this.$codable.css("height",t.h),this.$codable.data("cmeditor")&&this.$codable.data("cmeditor").setsize(null,t.h)}},{key:"toggle",value:function(){this.$editor.toggleClass("fullscreen");var t=this.isFullscreen();this.$scrollbar.toggleClass(this.scrollbarClassName,t),t?(this.$editable.data("orgHeight",this.$editable.css("height")),this.$editable.data("orgMaxHeight",this.$editable.css("maxHeight")),this.$editable.css("maxHeight",""),this.$window.on("resize",this.onResize).trigger("resize")):(this.$window.off("resize",this.onResize),this.resizeTo({h:this.$editable.data("orgHeight")}),this.$editable.css("maxHeight",this.$editable.css("orgMaxHeight"))),this.context.invoke("toolbar.updateFullscreen",t)}},{key:"isFullscreen",value:function(){return this.$editor.hasClass("fullscreen")}},{key:"destroy",value:function(){this.$scrollbar.removeClass(this.scrollbarClassName)}}])&&Vt(n.prototype,o),i&&Vt(n,i),t}();function _t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Gt=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$document=e()(document),this.$editingArea=n.layoutInfo.editingArea,this.options=n.options,this.lang=this.options.langInfo,this.events={"summernote.mousedown":function(t,e){o.update(e.target,e)&&e.preventDefault()},"summernote.keyup summernote.scroll summernote.change summernote.dialog.shown":function(){o.update()},"summernote.disable summernote.blur":function(){o.hide()},"summernote.codeview.toggled":function(){o.update()}}}var n,o,i;return n=t,o=[{key:"initialize",value:function(){var t=this;this.$handle=e()(['<div class="note-handle">','<div class="note-control-selection">','<div class="note-control-selection-bg"></div>','<div class="note-control-holder note-control-nw"></div>','<div class="note-control-holder note-control-ne"></div>','<div class="note-control-holder note-control-sw"></div>','<div class="',this.options.disableResizeImage?"note-control-holder":"note-control-sizing",' note-control-se"></div>',this.options.disableResizeImage?"":'<div class="note-control-selection-info"></div>',"</div>","</div>"].join("")).prependTo(this.$editingArea),this.$handle.on("mousedown",(function(e){if(ht.isControlSizing(e.target)){e.preventDefault(),e.stopPropagation();var n=t.$handle.find(".note-control-selection").data("target"),o=n.offset(),i=t.$document.scrollTop(),r=function(e){t.context.invoke("editor.resizeTo",{x:e.clientX-o.left,y:e.clientY-(o.top-i)},n,!e.shiftKey),t.update(n[0],e)};t.$document.on("mousemove",r).one("mouseup",(function(e){e.preventDefault(),t.$document.off("mousemove",r),t.context.invoke("editor.afterCommand")})),n.data("ratio")||n.data("ratio",n.height()/n.width())}})),this.$handle.on("wheel",(function(e){e.preventDefault(),t.update()}))}},{key:"destroy",value:function(){this.$handle.remove()}},{key:"update",value:function(t,n){if(this.context.isDisabled())return!1;var o=ht.isImg(t),i=this.$handle.find(".note-control-selection");if(this.context.invoke("imagePopover.update",t,n),o){var r=e()(t),a=r.position(),s={left:a.left+parseInt(r.css("marginLeft"),10),top:a.top+parseInt(r.css("marginTop"),10)},l={w:r.outerWidth(!1),h:r.outerHeight(!1)};i.css({display:"block",left:s.left,top:s.top,width:l.w,height:l.h}).data("target",r);var c=new Image;c.src=r.attr("src");var u=l.w+"x"+l.h+" ("+this.lang.image.original+": "+c.width+"x"+c.height+")";i.find(".note-control-selection-info").text(u),this.context.invoke("editor.saveTarget",t)}else this.hide();return o}},{key:"hide",value:function(){this.context.invoke("editor.clearTarget"),this.$handle.children().hide()}}],o&&_t(n.prototype,o),i&&_t(n,i),t}();function Yt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Zt=/^([A-Za-z][A-Za-z0-9+-.]*\:[\/]{2}|tel:|mailto:[A-Z0-9._%+-]+@|xmpp:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i,Qt=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.options=e.options,this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||n.handleKeyup(e)},"summernote.keydown":function(t,e){n.handleKeydown(e)}}}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){this.lastWordRange=null}},{key:"destroy",value:function(){this.lastWordRange=null}},{key:"replace",value:function(){if(this.lastWordRange){var t=this.lastWordRange.toString(),n=t.match(Zt);if(n&&(n[1]||n[2])){var o=n[1]?t:"http://"+t,i=this.options.showDomainOnlyForAutolink?t.replace(/^(?:https?:\/\/)?(?:tel?:?)?(?:mailto?:?)?(?:xmpp?:?)?(?:www\.)?/i,"").split("/")[0]:t,r=e()("<a></a>").html(i).attr("href",o)[0];this.context.options.linkTargetBlank&&e()(r).attr("target","_blank"),this.lastWordRange.insertNode(r),this.lastWordRange=null,this.context.invoke("editor.focus")}}}},{key:"handleKeydown",value:function(t){if(k.contains([wt.code.ENTER,wt.code.SPACE],t.keyCode)){var e=this.context.invoke("editor.createRange").getWordRange();this.lastWordRange=e}}},{key:"handleKeyup",value:function(t){k.contains([wt.code.ENTER,wt.code.SPACE],t.keyCode)&&this.replace()}}])&&Yt(n.prototype,o),i&&Yt(n,i),t}();function Xt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Jt=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$note=e.layoutInfo.note,this.events={"summernote.change":function(){n.$note.val(e.invoke("code"))}}}var e,n,o;return e=t,(n=[{key:"shouldInitialize",value:function(){return ht.isTextarea(this.$note[0])}}])&&Xt(e.prototype,n),o&&Xt(e,o),t}();function te(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ee=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.options=e.options.replace||{},this.keys=[wt.code.ENTER,wt.code.SPACE,wt.code.PERIOD,wt.code.COMMA,wt.code.SEMICOLON,wt.code.SLASH],this.previousKeydownCode=null,this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||n.handleKeyup(e)},"summernote.keydown":function(t,e){n.handleKeydown(e)}}}var e,n,o;return e=t,(n=[{key:"shouldInitialize",value:function(){return!!this.options.match}},{key:"initialize",value:function(){this.lastWord=null}},{key:"destroy",value:function(){this.lastWord=null}},{key:"replace",value:function(){if(this.lastWord){var t=this,e=this.lastWord.toString();this.options.match(e,(function(e){if(e){var n="";if("string"==typeof e?n=ht.createText(e):e instanceof jQuery?n=e[0]:e instanceof Node&&(n=e),!n)return;t.lastWord.insertNode(n),t.lastWord=null,t.context.invoke("editor.focus")}}))}}},{key:"handleKeydown",value:function(t){if(this.previousKeydownCode&&k.contains(this.keys,this.previousKeydownCode))this.previousKeydownCode=t.keyCode;else{if(k.contains(this.keys,t.keyCode)){var e=this.context.invoke("editor.createRange").getWordRange();this.lastWord=e}this.previousKeydownCode=t.keyCode}}},{key:"handleKeyup",value:function(t){k.contains(this.keys,t.keyCode)&&this.replace()}}])&&te(e.prototype,n),o&&te(e,o),t}();function ne(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var oe=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editingArea=e.layoutInfo.editingArea,this.options=e.options,!0===this.options.inheritPlaceholder&&(this.options.placeholder=this.context.$note.attr("placeholder")||this.options.placeholder),this.events={"summernote.init summernote.change":function(){n.update()},"summernote.codeview.toggled":function(){n.update()}}}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return!!this.options.placeholder}},{key:"initialize",value:function(){var t=this;this.$placeholder=e()('<div class="note-placeholder"></div>'),this.$placeholder.on("click",(function(){t.context.invoke("focus")})).html(this.options.placeholder).prependTo(this.$editingArea),this.update()}},{key:"destroy",value:function(){this.$placeholder.remove()}},{key:"update",value:function(){var t=!this.context.invoke("codeview.isActivated")&&this.context.invoke("editor.isEmpty");this.$placeholder.toggle(t)}}])&&ne(n.prototype,o),i&&ne(n,i),t}();function ie(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var re=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.ui=e().summernote.ui,this.context=n,this.$toolbar=n.layoutInfo.toolbar,this.options=n.options,this.lang=this.options.langInfo,this.invertedKeyMap=v.invertObject(this.options.keyMap[f.isMac?"mac":"pc"])}var n,o,i;return n=t,o=[{key:"representShortcut",value:function(t){var e=this.invertedKeyMap[t];return this.options.shortcuts&&e?(f.isMac&&(e=e.replace("CMD","⌘").replace("SHIFT","⇧"))," ("+(e=e.replace("BACKSLASH","\\").replace("SLASH","/").replace("LEFTBRACKET","[").replace("RIGHTBRACKET","]"))+")"):""}},{key:"button",value:function(t){return!this.options.tooltip&&t.tooltip&&delete t.tooltip,t.container=this.options.container,this.ui.button(t)}},{key:"initialize",value:function(){this.addToolbarButtons(),this.addImagePopoverButtons(),this.addLinkPopoverButtons(),this.addTablePopoverButtons(),this.fontInstalledMap={}}},{key:"destroy",value:function(){delete this.fontInstalledMap}},{key:"isFontInstalled",value:function(t){return Object.prototype.hasOwnProperty.call(this.fontInstalledMap,t)||(this.fontInstalledMap[t]=f.isFontInstalled(t)||k.contains(this.options.fontNamesIgnoreCheck,t)),this.fontInstalledMap[t]}},{key:"isFontDeservedToAdd",value:function(t){return""!==(t=t.toLowerCase())&&this.isFontInstalled(t)&&-1===f.genericFontFamilies.indexOf(t)}},{key:"colorPalette",value:function(t,n,o,i){var r=this;return this.ui.buttonGroup({className:"note-color "+t,children:[this.button({className:"note-current-color-button",contents:this.ui.icon(this.options.icons.font+" note-recent-color"),tooltip:n,click:function(t){var n=e()(t.currentTarget);o&&i?r.context.invoke("editor.color",{backColor:n.attr("data-backColor"),foreColor:n.attr("data-foreColor")}):o?r.context.invoke("editor.color",{backColor:n.attr("data-backColor")}):i&&r.context.invoke("editor.color",{foreColor:n.attr("data-foreColor")})},callback:function(t){var e=t.find(".note-recent-color");o&&(e.css("background-color",r.options.colorButton.backColor),t.attr("data-backColor",r.options.colorButton.backColor)),i?(e.css("color",r.options.colorButton.foreColor),t.attr("data-foreColor",r.options.colorButton.foreColor)):e.css("color","transparent")}}),this.button({className:"dropdown-toggle",contents:this.ui.dropdownButtonContents("",this.options),tooltip:this.lang.color.more,data:{toggle:"dropdown"}}),this.ui.dropdown({items:(o?['<div class="note-palette">','<div class="note-palette-title">'+this.lang.color.background+"</div>","<div>",'<button type="button" class="note-color-reset btn btn-light btn-default" data-event="backColor" data-value="transparent">',this.lang.color.transparent,"</button>","</div>",'<div class="note-holder" data-event="backColor">\x3c!-- back colors --\x3e</div>',"<div>",'<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="backColorPicker-'+this.options.id+'">',this.lang.color.cpSelect,"</button>",'<input type="color" id="backColorPicker-'+this.options.id+'" class="note-btn note-color-select-btn" value="'+this.options.colorButton.backColor+'" data-event="backColorPalette-'+this.options.id+'">',"</div>",'<div class="note-holder-custom" id="backColorPalette-'+this.options.id+'" data-event="backColor"></div>',"</div>"].join(""):"")+(i?['<div class="note-palette">','<div class="note-palette-title">'+this.lang.color.foreground+"</div>","<div>",'<button type="button" class="note-color-reset btn btn-light btn-default" data-event="removeFormat" data-value="foreColor">',this.lang.color.resetToDefault,"</button>","</div>",'<div class="note-holder" data-event="foreColor">\x3c!-- fore colors --\x3e</div>',"<div>",'<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="foreColorPicker-'+this.options.id+'">',this.lang.color.cpSelect,"</button>",'<input type="color" id="foreColorPicker-'+this.options.id+'" class="note-btn note-color-select-btn" value="'+this.options.colorButton.foreColor+'" data-event="foreColorPalette-'+this.options.id+'">',"</div>",'<div class="note-holder-custom" id="foreColorPalette-'+this.options.id+'" data-event="foreColor"></div>',"</div>"].join(""):""),callback:function(t){t.find(".note-holder").each((function(t,n){var o=e()(n);o.append(r.ui.palette({colors:r.options.colors,colorsName:r.options.colorsName,eventName:o.data("event"),container:r.options.container,tooltip:r.options.tooltip}).render())}));var n=[["#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF"]];t.find(".note-holder-custom").each((function(t,o){var i=e()(o);i.append(r.ui.palette({colors:n,colorsName:n,eventName:i.data("event"),container:r.options.container,tooltip:r.options.tooltip}).render())})),t.find("input[type=color]").each((function(n,o){e()(o).change((function(){var n=t.find("#"+e()(this).data("event")).find(".note-color-btn").first(),o=this.value.toUpperCase();n.css("background-color",o).attr("aria-label",o).attr("data-value",o).attr("data-original-title",o),n.click()}))}))},click:function(n){n.stopPropagation();var o=e()("."+t).find(".note-dropdown-menu"),i=e()(n.target),a=i.data("event"),s=i.attr("data-value");if("openPalette"===a){var l=o.find("#"+s),c=e()(o.find("#"+l.data("event")).find(".note-color-row")[0]),u=c.find(".note-color-btn").last().detach(),d=l.val();u.css("background-color",d).attr("aria-label",d).attr("data-value",d).attr("data-original-title",d),c.prepend(u),l.click()}else{if(k.contains(["backColor","foreColor"],a)){var h="backColor"===a?"background-color":"color",f=i.closest(".note-color").find(".note-recent-color"),p=i.closest(".note-color").find(".note-current-color-button");f.css(h,s),p.attr("data-"+a,s)}r.context.invoke("editor."+a,s)}}})]}).render()}},{key:"addToolbarButtons",value:function(){var t=this;this.context.memo("button.style",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.magic),t.options),tooltip:t.lang.style.style,data:{toggle:"dropdown"}}),t.ui.dropdown({className:"dropdown-style",items:t.options.styleTags,title:t.lang.style.style,template:function(e){"string"==typeof e&&(e={tag:e,title:Object.prototype.hasOwnProperty.call(t.lang.style,e)?t.lang.style[e]:e});var n=e.tag,o=e.title;return"<"+n+(e.style?' style="'+e.style+'" ':"")+(e.className?' class="'+e.className+'"':"")+">"+o+"</"+n+">"},click:t.context.createInvokeHandler("editor.formatBlock")})]).render()}));for(var n=function(e,n){var o=t.options.styleTags[e];t.context.memo("button.style."+o,(function(){return t.button({className:"note-btn-style-"+o,contents:'<div data-value="'+o+'">'+o.toUpperCase()+"</div>",tooltip:t.lang.style[o],click:t.context.createInvokeHandler("editor.formatBlock")}).render()}))},o=0,i=this.options.styleTags.length;o<i;o++)n(o);this.context.memo("button.bold",(function(){return t.button({className:"note-btn-bold",contents:t.ui.icon(t.options.icons.bold),tooltip:t.lang.font.bold+t.representShortcut("bold"),click:t.context.createInvokeHandlerAndUpdateState("editor.bold")}).render()})),this.context.memo("button.italic",(function(){return t.button({className:"note-btn-italic",contents:t.ui.icon(t.options.icons.italic),tooltip:t.lang.font.italic+t.representShortcut("italic"),click:t.context.createInvokeHandlerAndUpdateState("editor.italic")}).render()})),this.context.memo("button.underline",(function(){return t.button({className:"note-btn-underline",contents:t.ui.icon(t.options.icons.underline),tooltip:t.lang.font.underline+t.representShortcut("underline"),click:t.context.createInvokeHandlerAndUpdateState("editor.underline")}).render()})),this.context.memo("button.clear",(function(){return t.button({contents:t.ui.icon(t.options.icons.eraser),tooltip:t.lang.font.clear+t.representShortcut("removeFormat"),click:t.context.createInvokeHandler("editor.removeFormat")}).render()})),this.context.memo("button.strikethrough",(function(){return t.button({className:"note-btn-strikethrough",contents:t.ui.icon(t.options.icons.strikethrough),tooltip:t.lang.font.strikethrough+t.representShortcut("strikethrough"),click:t.context.createInvokeHandlerAndUpdateState("editor.strikethrough")}).render()})),this.context.memo("button.superscript",(function(){return t.button({className:"note-btn-superscript",contents:t.ui.icon(t.options.icons.superscript),tooltip:t.lang.font.superscript,click:t.context.createInvokeHandlerAndUpdateState("editor.superscript")}).render()})),this.context.memo("button.subscript",(function(){return t.button({className:"note-btn-subscript",contents:t.ui.icon(t.options.icons.subscript),tooltip:t.lang.font.subscript,click:t.context.createInvokeHandlerAndUpdateState("editor.subscript")}).render()})),this.context.memo("button.fontname",(function(){var n=t.context.invoke("editor.currentStyle");return t.options.addDefaultFonts&&e().each(n["font-family"].split(","),(function(e,n){n=n.trim().replace(/['"]+/g,""),t.isFontDeservedToAdd(n)&&-1===t.options.fontNames.indexOf(n)&&t.options.fontNames.push(n)})),t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontname"></span>',t.options),tooltip:t.lang.font.name,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontname",checkClassName:t.options.icons.menuCheck,items:t.options.fontNames.filter(t.isFontInstalled.bind(t)),title:t.lang.font.name,template:function(t){return'<span style="font-family: '+f.validFontName(t)+'">'+t+"</span>"},click:t.context.createInvokeHandlerAndUpdateState("editor.fontName")})]).render()})),this.context.memo("button.fontsize",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontsize"></span>',t.options),tooltip:t.lang.font.size,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontsize",checkClassName:t.options.icons.menuCheck,items:t.options.fontSizes,title:t.lang.font.size,click:t.context.createInvokeHandlerAndUpdateState("editor.fontSize")})]).render()})),this.context.memo("button.fontsizeunit",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontsizeunit"></span>',t.options),tooltip:t.lang.font.sizeunit,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontsizeunit",checkClassName:t.options.icons.menuCheck,items:t.options.fontSizeUnits,title:t.lang.font.sizeunit,click:t.context.createInvokeHandlerAndUpdateState("editor.fontSizeUnit")})]).render()})),this.context.memo("button.color",(function(){return t.colorPalette("note-color-all",t.lang.color.recent,!0,!0)})),this.context.memo("button.forecolor",(function(){return t.colorPalette("note-color-fore",t.lang.color.foreground,!1,!0)})),this.context.memo("button.backcolor",(function(){return t.colorPalette("note-color-back",t.lang.color.background,!0,!1)})),this.context.memo("button.ul",(function(){return t.button({contents:t.ui.icon(t.options.icons.unorderedlist),tooltip:t.lang.lists.unordered+t.representShortcut("insertUnorderedList"),click:t.context.createInvokeHandler("editor.insertUnorderedList")}).render()})),this.context.memo("button.ol",(function(){return t.button({contents:t.ui.icon(t.options.icons.orderedlist),tooltip:t.lang.lists.ordered+t.representShortcut("insertOrderedList"),click:t.context.createInvokeHandler("editor.insertOrderedList")}).render()}));var r=this.button({contents:this.ui.icon(this.options.icons.alignLeft),tooltip:this.lang.paragraph.left+this.representShortcut("justifyLeft"),click:this.context.createInvokeHandler("editor.justifyLeft")}),a=this.button({contents:this.ui.icon(this.options.icons.alignCenter),tooltip:this.lang.paragraph.center+this.representShortcut("justifyCenter"),click:this.context.createInvokeHandler("editor.justifyCenter")}),s=this.button({contents:this.ui.icon(this.options.icons.alignRight),tooltip:this.lang.paragraph.right+this.representShortcut("justifyRight"),click:this.context.createInvokeHandler("editor.justifyRight")}),l=this.button({contents:this.ui.icon(this.options.icons.alignJustify),tooltip:this.lang.paragraph.justify+this.representShortcut("justifyFull"),click:this.context.createInvokeHandler("editor.justifyFull")}),c=this.button({contents:this.ui.icon(this.options.icons.outdent),tooltip:this.lang.paragraph.outdent+this.representShortcut("outdent"),click:this.context.createInvokeHandler("editor.outdent")}),u=this.button({contents:this.ui.icon(this.options.icons.indent),tooltip:this.lang.paragraph.indent+this.representShortcut("indent"),click:this.context.createInvokeHandler("editor.indent")});this.context.memo("button.justifyLeft",v.invoke(r,"render")),this.context.memo("button.justifyCenter",v.invoke(a,"render")),this.context.memo("button.justifyRight",v.invoke(s,"render")),this.context.memo("button.justifyFull",v.invoke(l,"render")),this.context.memo("button.outdent",v.invoke(c,"render")),this.context.memo("button.indent",v.invoke(u,"render")),this.context.memo("button.paragraph",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.alignLeft),t.options),tooltip:t.lang.paragraph.paragraph,data:{toggle:"dropdown"}}),t.ui.dropdown([t.ui.buttonGroup({className:"note-align",children:[r,a,s,l]}),t.ui.buttonGroup({className:"note-list",children:[c,u]})])]).render()})),this.context.memo("button.height",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.textHeight),t.options),tooltip:t.lang.font.height,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({items:t.options.lineHeights,checkClassName:t.options.icons.menuCheck,className:"dropdown-line-height",title:t.lang.font.height,click:t.context.createInvokeHandler("editor.lineHeight")})]).render()})),this.context.memo("button.table",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.table),t.options),tooltip:t.lang.table.table,data:{toggle:"dropdown"}}),t.ui.dropdown({title:t.lang.table.table,className:"note-table",items:['<div class="note-dimension-picker">','<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>','<div class="note-dimension-picker-highlighted"></div>','<div class="note-dimension-picker-unhighlighted"></div>',"</div>",'<div class="note-dimension-display">1 x 1</div>'].join("")})],{callback:function(e){e.find(".note-dimension-picker-mousecatcher").css({width:t.options.insertTableMaxSize.col+"em",height:t.options.insertTableMaxSize.row+"em"}).mouseup(t.context.createInvokeHandler("editor.insertTable")).on("mousemove",t.tableMoveHandler.bind(t))}}).render()})),this.context.memo("button.link",(function(){return t.button({contents:t.ui.icon(t.options.icons.link),tooltip:t.lang.link.link+t.representShortcut("linkDialog.show"),click:t.context.createInvokeHandler("linkDialog.show")}).render()})),this.context.memo("button.picture",(function(){return t.button({contents:t.ui.icon(t.options.icons.picture),tooltip:t.lang.image.image,click:t.context.createInvokeHandler("imageDialog.show")}).render()})),this.context.memo("button.video",(function(){return t.button({contents:t.ui.icon(t.options.icons.video),tooltip:t.lang.video.video,click:t.context.createInvokeHandler("videoDialog.show")}).render()})),this.context.memo("button.hr",(function(){return t.button({contents:t.ui.icon(t.options.icons.minus),tooltip:t.lang.hr.insert+t.representShortcut("insertHorizontalRule"),click:t.context.createInvokeHandler("editor.insertHorizontalRule")}).render()})),this.context.memo("button.fullscreen",(function(){return t.button({className:"btn-fullscreen note-codeview-keep",contents:t.ui.icon(t.options.icons.arrowsAlt),tooltip:t.lang.options.fullscreen,click:t.context.createInvokeHandler("fullscreen.toggle")}).render()})),this.context.memo("button.codeview",(function(){return t.button({className:"btn-codeview note-codeview-keep",contents:t.ui.icon(t.options.icons.code),tooltip:t.lang.options.codeview,click:t.context.createInvokeHandler("codeview.toggle")}).render()})),this.context.memo("button.redo",(function(){return t.button({contents:t.ui.icon(t.options.icons.redo),tooltip:t.lang.history.redo+t.representShortcut("redo"),click:t.context.createInvokeHandler("editor.redo")}).render()})),this.context.memo("button.undo",(function(){return t.button({contents:t.ui.icon(t.options.icons.undo),tooltip:t.lang.history.undo+t.representShortcut("undo"),click:t.context.createInvokeHandler("editor.undo")}).render()})),this.context.memo("button.help",(function(){return t.button({contents:t.ui.icon(t.options.icons.question),tooltip:t.lang.options.help,click:t.context.createInvokeHandler("helpDialog.show")}).render()}))}},{key:"addImagePopoverButtons",value:function(){var t=this;this.context.memo("button.resizeFull",(function(){return t.button({contents:'<span class="note-fontsize-10">100%</span>',tooltip:t.lang.image.resizeFull,click:t.context.createInvokeHandler("editor.resize","1")}).render()})),this.context.memo("button.resizeHalf",(function(){return t.button({contents:'<span class="note-fontsize-10">50%</span>',tooltip:t.lang.image.resizeHalf,click:t.context.createInvokeHandler("editor.resize","0.5")}).render()})),this.context.memo("button.resizeQuarter",(function(){return t.button({contents:'<span class="note-fontsize-10">25%</span>',tooltip:t.lang.image.resizeQuarter,click:t.context.createInvokeHandler("editor.resize","0.25")}).render()})),this.context.memo("button.resizeNone",(function(){return t.button({contents:t.ui.icon(t.options.icons.rollback),tooltip:t.lang.image.resizeNone,click:t.context.createInvokeHandler("editor.resize","0")}).render()})),this.context.memo("button.floatLeft",(function(){return t.button({contents:t.ui.icon(t.options.icons.floatLeft),tooltip:t.lang.image.floatLeft,click:t.context.createInvokeHandler("editor.floatMe","left")}).render()})),this.context.memo("button.floatRight",(function(){return t.button({contents:t.ui.icon(t.options.icons.floatRight),tooltip:t.lang.image.floatRight,click:t.context.createInvokeHandler("editor.floatMe","right")}).render()})),this.context.memo("button.floatNone",(function(){return t.button({contents:t.ui.icon(t.options.icons.rollback),tooltip:t.lang.image.floatNone,click:t.context.createInvokeHandler("editor.floatMe","none")}).render()})),this.context.memo("button.removeMedia",(function(){return t.button({contents:t.ui.icon(t.options.icons.trash),tooltip:t.lang.image.remove,click:t.context.createInvokeHandler("editor.removeMedia")}).render()}))}},{key:"addLinkPopoverButtons",value:function(){var t=this;this.context.memo("button.linkDialogShow",(function(){return t.button({contents:t.ui.icon(t.options.icons.link),tooltip:t.lang.link.edit,click:t.context.createInvokeHandler("linkDialog.show")}).render()})),this.context.memo("button.unlink",(function(){return t.button({contents:t.ui.icon(t.options.icons.unlink),tooltip:t.lang.link.unlink,click:t.context.createInvokeHandler("editor.unlink")}).render()}))}},{key:"addTablePopoverButtons",value:function(){var t=this;this.context.memo("button.addRowUp",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowAbove),tooltip:t.lang.table.addRowAbove,click:t.context.createInvokeHandler("editor.addRow","top")}).render()})),this.context.memo("button.addRowDown",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowBelow),tooltip:t.lang.table.addRowBelow,click:t.context.createInvokeHandler("editor.addRow","bottom")}).render()})),this.context.memo("button.addColLeft",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colBefore),tooltip:t.lang.table.addColLeft,click:t.context.createInvokeHandler("editor.addCol","left")}).render()})),this.context.memo("button.addColRight",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colAfter),tooltip:t.lang.table.addColRight,click:t.context.createInvokeHandler("editor.addCol","right")}).render()})),this.context.memo("button.deleteRow",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowRemove),tooltip:t.lang.table.delRow,click:t.context.createInvokeHandler("editor.deleteRow")}).render()})),this.context.memo("button.deleteCol",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colRemove),tooltip:t.lang.table.delCol,click:t.context.createInvokeHandler("editor.deleteCol")}).render()})),this.context.memo("button.deleteTable",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.trash),tooltip:t.lang.table.delTable,click:t.context.createInvokeHandler("editor.deleteTable")}).render()}))}},{key:"build",value:function(t,e){for(var n=0,o=e.length;n<o;n++){for(var i=e[n],r=Array.isArray(i)?i[0]:i,a=Array.isArray(i)?1===i.length?[i[0]]:i[1]:[i],s=this.ui.buttonGroup({className:"note-"+r}).render(),l=0,c=a.length;l<c;l++){var u=this.context.memo("button."+a[l]);u&&s.append("function"==typeof u?u(this.context):u)}s.appendTo(t)}}},{key:"updateCurrentStyle",value:function(t){var n=t||this.$toolbar,o=this.context.invoke("editor.currentStyle");if(this.updateBtnStates(n,{".note-btn-bold":function(){return"bold"===o["font-bold"]},".note-btn-italic":function(){return"italic"===o["font-italic"]},".note-btn-underline":function(){return"underline"===o["font-underline"]},".note-btn-subscript":function(){return"subscript"===o["font-subscript"]},".note-btn-superscript":function(){return"superscript"===o["font-superscript"]},".note-btn-strikethrough":function(){return"strikethrough"===o["font-strikethrough"]}}),o["font-family"]){var i=o["font-family"].split(",").map((function(t){return t.replace(/[\'\"]/g,"").replace(/\s+$/,"").replace(/^\s+/,"")})),r=k.find(i,this.isFontInstalled.bind(this));n.find(".dropdown-fontname a").each((function(t,n){var o=e()(n),i=o.data("value")+""==r+"";o.toggleClass("checked",i)})),n.find(".note-current-fontname").text(r).css("font-family",r)}if(o["font-size"]){var a=o["font-size"];n.find(".dropdown-fontsize a").each((function(t,n){var o=e()(n),i=o.data("value")+""==a+"";o.toggleClass("checked",i)})),n.find(".note-current-fontsize").text(a);var s=o["font-size-unit"];n.find(".dropdown-fontsizeunit a").each((function(t,n){var o=e()(n),i=o.data("value")+""==s+"";o.toggleClass("checked",i)})),n.find(".note-current-fontsizeunit").text(s)}if(o["line-height"]){var l=o["line-height"];n.find(".dropdown-line-height a").each((function(t,n){var o=e()(n),i=e()(n).data("value")+""==l+"";o.toggleClass("checked",i)})),n.find(".note-current-line-height").text(l)}}},{key:"updateBtnStates",value:function(t,n){var o=this;e().each(n,(function(e,n){o.ui.toggleBtnActive(t.find(e),n())}))}},{key:"tableMoveHandler",value:function(t){var n,o=e()(t.target.parentNode),i=o.next(),r=o.find(".note-dimension-picker-mousecatcher"),a=o.find(".note-dimension-picker-highlighted"),s=o.find(".note-dimension-picker-unhighlighted");if(void 0===t.offsetX){var l=e()(t.target).offset();n={x:t.pageX-l.left,y:t.pageY-l.top}}else n={x:t.offsetX,y:t.offsetY};var c=Math.ceil(n.x/18)||1,u=Math.ceil(n.y/18)||1;a.css({width:c+"em",height:u+"em"}),r.data("value",c+"x"+u),c>3&&c<this.options.insertTableMaxSize.col&&s.css({width:c+1+"em"}),u>3&&u<this.options.insertTableMaxSize.row&&s.css({height:u+1+"em"}),i.html(c+" x "+u)}}],o&&ie(n.prototype,o),i&&ie(n,i),t}();function ae(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var se=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$window=e()(window),this.$document=e()(document),this.ui=e().summernote.ui,this.$note=n.layoutInfo.note,this.$editor=n.layoutInfo.editor,this.$toolbar=n.layoutInfo.toolbar,this.$editable=n.layoutInfo.editable,this.$statusbar=n.layoutInfo.statusbar,this.options=n.options,this.isFollowing=!1,this.followScroll=this.followScroll.bind(this)}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return!this.options.airMode}},{key:"initialize",value:function(){var t=this;this.options.toolbar=this.options.toolbar||[],this.options.toolbar.length?this.context.invoke("buttons.build",this.$toolbar,this.options.toolbar):this.$toolbar.hide(),this.options.toolbarContainer&&this.$toolbar.appendTo(this.options.toolbarContainer),this.changeContainer(!1),this.$note.on("summernote.keyup summernote.mouseup summernote.change",(function(){t.context.invoke("buttons.updateCurrentStyle")})),this.context.invoke("buttons.updateCurrentStyle"),this.options.followingToolbar&&this.$window.on("scroll resize",this.followScroll)}},{key:"destroy",value:function(){this.$toolbar.children().remove(),this.options.followingToolbar&&this.$window.off("scroll resize",this.followScroll)}},{key:"followScroll",value:function(){if(this.$editor.hasClass("fullscreen"))return!1;var t=this.$editor.outerHeight(),n=this.$editor.width(),o=this.$toolbar.height(),i=this.$statusbar.height(),r=0;this.options.otherStaticBar&&(r=e()(this.options.otherStaticBar).outerHeight());var a=this.$document.scrollTop(),s=this.$editor.offset().top,l=s-r,c=s+t-r-o-i;!this.isFollowing&&a>l&&a<c-o?(this.isFollowing=!0,this.$editable.css({marginTop:this.$toolbar.outerHeight()}),this.$toolbar.css({position:"fixed",top:r,width:n,zIndex:1e3})):this.isFollowing&&(a<l||a>c)&&(this.isFollowing=!1,this.$toolbar.css({position:"relative",top:0,width:"100%",zIndex:"auto"}),this.$editable.css({marginTop:""}))}},{key:"changeContainer",value:function(t){t?this.$toolbar.prependTo(this.$editor):this.options.toolbarContainer&&this.$toolbar.appendTo(this.options.toolbarContainer),this.options.followingToolbar&&this.followScroll()}},{key:"updateFullscreen",value:function(t){this.ui.toggleBtnActive(this.$toolbar.find(".btn-fullscreen"),t),this.changeContainer(t)}},{key:"updateCodeview",value:function(t){this.ui.toggleBtnActive(this.$toolbar.find(".btn-codeview"),t),t?this.deactivate():this.activate()}},{key:"activate",value:function(t){var e=this.$toolbar.find("button");t||(e=e.not(".note-codeview-keep")),this.ui.toggleBtn(e,!0)}},{key:"deactivate",value:function(t){var e=this.$toolbar.find("button");t||(e=e.not(".note-codeview-keep")),this.ui.toggleBtn(e,!1)}}])&&ae(n.prototype,o),i&&ae(n,i),t}();function le(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ce=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo,n.memo("help.linkDialog.show",this.options.langInfo.help["linkDialog.show"])}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,n=['<div class="form-group note-form-group">','<label for="note-dialog-link-txt-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.link.textToDisplay,"</label>"),'<input id="note-dialog-link-txt-'.concat(this.options.id,'" class="note-link-text form-control note-form-control note-input" type="text"/>'),"</div>",'<div class="form-group note-form-group">','<label for="note-dialog-link-url-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.link.url,"</label>"),'<input id="note-dialog-link-url-'.concat(this.options.id,'" class="note-link-url form-control note-form-control note-input" type="text" value="http://"/>'),"</div>",this.options.disableLinkTarget?"":e()("<div></div>").append(this.ui.checkbox({className:"sn-checkbox-open-in-new-window",text:this.lang.link.openInNewWindow,checked:!0}).render()).html(),e()("<div></div>").append(this.ui.checkbox({className:"sn-checkbox-use-protocol",text:this.lang.link.useProtocol,checked:!0}).render()).html()].join(""),o='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-link-btn",'" value="').concat(this.lang.link.insert,'" disabled>');this.$dialog=this.ui.dialog({className:"link-dialog",title:this.lang.link.insert,fade:this.options.dialogsFade,body:n,footer:o}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"toggleLinkBtn",value:function(t,e,n){this.ui.toggleBtn(t,e.val()&&n.val())}},{key:"showLinkDialog",value:function(t){var n=this;return e().Deferred((function(e){var o=n.$dialog.find(".note-link-text"),i=n.$dialog.find(".note-link-url"),r=n.$dialog.find(".note-link-btn"),a=n.$dialog.find(".sn-checkbox-open-in-new-window input[type=checkbox]"),s=n.$dialog.find(".sn-checkbox-use-protocol input[type=checkbox]");n.ui.onDialogShown(n.$dialog,(function(){n.context.triggerEvent("dialog.shown"),!t.url&&v.isValidUrl(t.text)&&(t.url=t.text),o.on("input paste propertychange",(function(){t.text=o.val(),n.toggleLinkBtn(r,o,i)})).val(t.text),i.on("input paste propertychange",(function(){t.text||o.val(i.val()),n.toggleLinkBtn(r,o,i)})).val(t.url),f.isSupportTouch||i.trigger("focus"),n.toggleLinkBtn(r,o,i),n.bindEnterKey(i,r),n.bindEnterKey(o,r);var l=void 0!==t.isNewWindow?t.isNewWindow:n.context.options.linkTargetBlank;a.prop("checked",l);var c=!t.url&&n.context.options.useProtocol;s.prop("checked",c),r.one("click",(function(r){r.preventDefault(),e.resolve({range:t.range,url:i.val(),text:o.val(),isNewWindow:a.is(":checked"),checkProtocol:s.is(":checked")}),n.ui.hideDialog(n.$dialog)}))})),n.ui.onDialogHidden(n.$dialog,(function(){o.off(),i.off(),r.off(),"pending"===e.state()&&e.reject()})),n.ui.showDialog(n.$dialog)})).promise()}},{key:"show",value:function(){var t=this,e=this.context.invoke("editor.getLinkInfo");this.context.invoke("editor.saveRange"),this.showLinkDialog(e).then((function(e){t.context.invoke("editor.restoreRange"),t.context.invoke("editor.createLink",e)})).fail((function(){t.context.invoke("editor.restoreRange")}))}}])&&le(n.prototype,o),i&&le(n,i),t}();function ue(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var de=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.options=n.options,this.events={"summernote.keyup summernote.mouseup summernote.change summernote.scroll":function(){o.update()},"summernote.disable summernote.dialog.shown":function(){o.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&o.$popover[0].contains(e.originalEvent.relatedTarget)||o.hide()}}}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return!k.isEmpty(this.options.popover.link)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-link-popover",callback:function(t){t.find(".popover-content,.note-popover-content").prepend('<span><a target="_blank"></a>&nbsp;</span>')}}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.link),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(){if(this.context.invoke("editor.hasFocus")){var t=this.context.invoke("editor.getLastRange");if(t.isCollapsed()&&t.isOnAnchor()){var n=ht.ancestor(t.sc,ht.isAnchor),o=e()(n).attr("href");this.$popover.find("a").attr("href",o).text(o);var i=ht.posFromPlaceholder(n),r=e()(this.options.container).offset();i.top-=r.top,i.left-=r.left,this.$popover.css({display:"block",left:i.left,top:i.top})}else this.hide()}else this.hide()}},{key:"hide",value:function(){this.$popover.hide()}}])&&ue(n.prototype,o),i&&ue(n,i),t}();function he(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var fe=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t="";if(this.options.maximumImageFileSize){var e=Math.floor(Math.log(this.options.maximumImageFileSize)/Math.log(1024)),n=1*(this.options.maximumImageFileSize/Math.pow(1024,e)).toFixed(2)+" "+" KMGTP"[e]+"B";t="<small>".concat(this.lang.image.maximumFileSize+" : "+n,"</small>")}var o=this.options.dialogsInBody?this.$body:this.options.container,i=['<div class="form-group note-form-group note-group-select-from-files">','<label for="note-dialog-image-file-'+this.options.id+'" class="note-form-label">'+this.lang.image.selectFromFiles+"</label>",'<input id="note-dialog-image-file-'+this.options.id+'" class="note-image-input form-control-file note-form-control note-input" ',' type="file" name="files" accept="'+this.options.acceptImageFileTypes+'" multiple="multiple"/>',t,"</div>",'<div class="form-group note-group-image-url">','<label for="note-dialog-image-url-'+this.options.id+'" class="note-form-label">'+this.lang.image.url+"</label>",'<input id="note-dialog-image-url-'+this.options.id+'" class="note-image-url form-control note-form-control note-input" type="text"/>',"</div>"].join(""),r='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-image-btn",'" value="').concat(this.lang.image.insert,'" disabled>');this.$dialog=this.ui.dialog({title:this.lang.image.insert,fade:this.options.dialogsFade,body:i,footer:r}).render().appendTo(o)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"show",value:function(){var t=this;this.context.invoke("editor.saveRange"),this.showImageDialog().then((function(e){t.ui.hideDialog(t.$dialog),t.context.invoke("editor.restoreRange"),"string"==typeof e?t.options.callbacks.onImageLinkInsert?t.context.triggerEvent("image.link.insert",e):t.context.invoke("editor.insertImage",e):t.context.invoke("editor.insertImagesOrCallback",e)})).fail((function(){t.context.invoke("editor.restoreRange")}))}},{key:"showImageDialog",value:function(){var t=this;return e().Deferred((function(e){var n=t.$dialog.find(".note-image-input"),o=t.$dialog.find(".note-image-url"),i=t.$dialog.find(".note-image-btn");t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),n.replaceWith(n.clone().on("change",(function(t){e.resolve(t.target.files||t.target.value)})).val("")),o.on("input paste propertychange",(function(){t.ui.toggleBtn(i,o.val())})).val(""),f.isSupportTouch||o.trigger("focus"),i.click((function(t){t.preventDefault(),e.resolve(o.val())})),t.bindEnterKey(o,i)})),t.ui.onDialogHidden(t.$dialog,(function(){n.off(),o.off(),i.off(),"pending"===e.state()&&e.reject()})),t.ui.showDialog(t.$dialog)}))}}])&&he(n.prototype,o),i&&he(n,i),t}();function pe(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ve=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.editable=n.layoutInfo.editable[0],this.options=n.options,this.events={"summernote.disable summernote.dialog.shown":function(){o.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&o.$popover[0].contains(e.originalEvent.relatedTarget)||o.hide()}}}var n,o,i;return n=t,o=[{key:"shouldInitialize",value:function(){return!k.isEmpty(this.options.popover.image)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-image-popover"}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.image),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t,n){if(ht.isImg(t)){var o=e()(t).offset(),i=e()(this.options.container).offset(),r={};this.options.popatmouse?(r.left=n.pageX-20,r.top=n.pageY):r=o,r.top-=i.top,r.left-=i.left,this.$popover.css({display:"block",left:r.left,top:r.top})}else this.hide()}},{key:"hide",value:function(){this.$popover.hide()}}],o&&pe(n.prototype,o),i&&pe(n,i),t}();function me(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ge=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.options=n.options,this.events={"summernote.mousedown":function(t,e){o.update(e.target)},"summernote.keyup summernote.scroll summernote.change":function(){o.update()},"summernote.disable summernote.dialog.shown":function(){o.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&o.$popover[0].contains(e.originalEvent.relatedTarget)||o.hide()}}}var n,o,i;return n=t,o=[{key:"shouldInitialize",value:function(){return!k.isEmpty(this.options.popover.table)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-table-popover"}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.table),f.isFF&&document.execCommand("enableInlineTableEditing",!1,!1),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t){if(this.context.isDisabled())return!1;var n=ht.isCell(t)||ht.isCell(null==t?void 0:t.parentElement);if(n){var o=ht.posFromPlaceholder(t),i=e()(this.options.container).offset();o.top-=i.top,o.left-=i.left,this.$popover.css({display:"block",left:o.left,top:o.top})}else this.hide();return n}},{key:"hide",value:function(){this.$popover.hide()}}],o&&me(n.prototype,o),i&&me(n,i),t}();function be(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ye=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,e=['<div class="form-group note-form-group row-fluid">','<label for="note-dialog-video-url-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.video.url,' <small class="text-muted">').concat(this.lang.video.providers,"</small></label>"),'<input id="note-dialog-video-url-'.concat(this.options.id,'" class="note-video-url form-control note-form-control note-input" type="text"/>'),"</div>"].join(""),n='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-video-btn",'" value="').concat(this.lang.video.insert,'" disabled>');this.$dialog=this.ui.dialog({title:this.lang.video.insert,fade:this.options.dialogsFade,body:e,footer:n}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"createVideoNode",value:function(t){var n,o=t.match(/\/\/(?:(?:www|m)\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))([\w|-]{11})(?:(?:[\?&]t=)(\S+))?$/),i=t.match(/(?:\.|\/\/)drive\.google\.com\/file\/d\/(.[a-zA-Z0-9_-]*)\/view/),r=t.match(/(?:www\.|\/\/)instagram\.com\/p\/(.[a-zA-Z0-9_-]*)/),a=t.match(/\/\/vine\.co\/v\/([a-zA-Z0-9]+)/),s=t.match(/\/\/(player\.)?vimeo\.com\/([a-z]*\/)*(\d+)[?]?.*/),l=t.match(/.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/),c=t.match(/\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/),u=t.match(/\/\/(.*)\/videos\/watch\/([^?]*)(?:\?(?:start=(\w*))?(?:&stop=(\w*))?(?:&loop=([10]))?(?:&autoplay=([10]))?(?:&muted=([10]))?)?/),d=t.match(/\/\/v\.qq\.com.*?vid=(.+)/),h=t.match(/\/\/v\.qq\.com\/x?\/?(page|cover).*?\/([^\/]+)\.html\??.*/),f=t.match(/^.+.(mp4|m4v)$/),p=t.match(/^.+.(ogg|ogv)$/),v=t.match(/^.+.(webm)$/),m=t.match(/(?:www\.|\/\/)facebook\.com\/([^\/]+)\/videos\/([0-9]+)/);if(o&&11===o[1].length){var g=o[1],b=0;if(void 0!==o[2]){var y=o[2].match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/);if(y)for(var k=[3600,60,1],w=0,C=k.length;w<C;w++)b+=void 0!==y[w+1]?k[w]*parseInt(y[w+1],10):0}n=e()("<iframe>").attr("frameborder",0).attr("src","//www.youtube.com/embed/"+g+(b>0?"?start="+b:"")).attr("width","640").attr("height","360")}else if(i&&i[0].length)n=e()("<iframe>").attr("frameborder",0).attr("src","https://drive.google.com/file/d/"+i[1]+"/preview").attr("width","640").attr("height","480");else if(r&&r[0].length)n=e()("<iframe>").attr("frameborder",0).attr("src","https://instagram.com/p/"+r[1]+"/embed/").attr("width","612").attr("height","710").attr("scrolling","no").attr("allowtransparency","true");else if(a&&a[0].length)n=e()("<iframe>").attr("frameborder",0).attr("src",a[0]+"/embed/simple").attr("width","600").attr("height","600").attr("class","vine-embed");else if(s&&s[3].length)n=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("src","//player.vimeo.com/video/"+s[3]).attr("width","640").attr("height","360");else if(l&&l[2].length)n=e()("<iframe>").attr("frameborder",0).attr("src","//www.dailymotion.com/embed/video/"+l[2]).attr("width","640").attr("height","360");else if(c&&c[1].length)n=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("height","498").attr("width","510").attr("src","//player.youku.com/embed/"+c[1]);else if(u&&u[0].length){var x=0;"undefined"!==u[2]&&(x=u[2]);var S=0;"undefined"!==u[3]&&(S=u[3]);var T=0;"undefined"!==u[4]&&(T=u[4]);var E=0;"undefined"!==u[5]&&(E=u[5]);var I=0;"undefined"!==u[6]&&(I=u[6]),n=e()('<iframe allowfullscreen sandbox="allow-same-origin allow-scripts allow-popups">').attr("frameborder",0).attr("src","//"+u[1]+"/videos/embed/"+u[2]+"?loop="+T+"&autoplay="+E+"&muted="+I+(x>0?"&start="+x:"")+(S>0?"&end="+b:"")).attr("width","560").attr("height","315")}else if(d&&d[1].length||h&&h[2].length){var $=d&&d[1].length?d[1]:h[2];n=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("height","310").attr("width","500").attr("src","https://v.qq.com/txp/iframe/player.html?vid="+$+"&amp;auto=0")}else if(f||p||v)n=e()("<video controls>").attr("src",t).attr("width","640").attr("height","360");else{if(!m||!m[0].length)return!1;n=e()("<iframe>").attr("frameborder",0).attr("src","https://www.facebook.com/plugins/video.php?href="+encodeURIComponent(m[0])+"&show_text=0&width=560").attr("width","560").attr("height","301").attr("scrolling","no").attr("allowtransparency","true")}return n.addClass("note-video-clip"),n[0]}},{key:"show",value:function(){var t=this,e=this.context.invoke("editor.getSelectedText");this.context.invoke("editor.saveRange"),this.showVideoDialog(e).then((function(e){t.ui.hideDialog(t.$dialog),t.context.invoke("editor.restoreRange");var n=t.createVideoNode(e);n&&t.context.invoke("editor.insertNode",n)})).fail((function(){t.context.invoke("editor.restoreRange")}))}},{key:"showVideoDialog",value:function(){var t=this;return e().Deferred((function(e){var n=t.$dialog.find(".note-video-url"),o=t.$dialog.find(".note-video-btn");t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),n.on("input paste propertychange",(function(){t.ui.toggleBtn(o,n.val())})),f.isSupportTouch||n.trigger("focus"),o.click((function(t){t.preventDefault(),e.resolve(n.val())})),t.bindEnterKey(n,o)})),t.ui.onDialogHidden(t.$dialog,(function(){n.off(),o.off(),"pending"===e.state()&&e.reject()})),t.ui.showDialog(t.$dialog)}))}}])&&be(n.prototype,o),i&&be(n,i),t}();function ke(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var we=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo}var n,o,i;return n=t,o=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,e=['<p class="text-center">','<a href="http://summernote.org/" target="_blank" rel="noopener noreferrer">Summernote 0.8.20</a> · ','<a href="https://github.com/summernote/summernote" target="_blank" rel="noopener noreferrer">Project</a> · ','<a href="https://github.com/summernote/summernote/issues" target="_blank" rel="noopener noreferrer">Issues</a>',"</p>"].join("");this.$dialog=this.ui.dialog({title:this.lang.options.help,fade:this.options.dialogsFade,body:this.createShortcutList(),footer:e,callback:function(t){t.find(".modal-body,.note-modal-body").css({"max-height":300,overflow:"scroll"})}}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"createShortcutList",value:function(){var t=this,n=this.options.keyMap[f.isMac?"mac":"pc"];return Object.keys(n).map((function(o){var i=n[o],r=e()('<div><div class="help-list-item"></div></div>');return r.append(e()("<label><kbd>"+o+"</kdb></label>").css({width:180,"margin-right":10})).append(e()("<span></span>").html(t.context.memo("help."+i)||i)),r.html()})).join("")}},{key:"showHelpDialog",value:function(){var t=this;return e().Deferred((function(e){t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),e.resolve()})),t.ui.showDialog(t.$dialog)})).promise()}},{key:"show",value:function(){var t=this;this.context.invoke("editor.saveRange"),this.showHelpDialog().then((function(){t.context.invoke("editor.restoreRange")}))}}],o&&ke(n.prototype,o),i&&ke(n,i),t}();function Ce(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var xe=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.options=n.options,this.hidable=!0,this.onContextmenu=!1,this.pageX=null,this.pageY=null,this.events={"summernote.contextmenu":function(t){o.options.editing&&(t.preventDefault(),t.stopPropagation(),o.onContextmenu=!0,o.update(!0))},"summernote.mousedown":function(t,e){o.pageX=e.pageX,o.pageY=e.pageY},"summernote.keyup summernote.mouseup summernote.scroll":function(t,e){o.options.editing&&!o.onContextmenu&&(o.pageX=e.pageX,o.pageY=e.pageY,o.update()),o.onContextmenu=!1},"summernote.disable summernote.change summernote.dialog.shown summernote.blur":function(){o.hide()},"summernote.focusout":function(){o.$popover.is(":active,:focus")||o.hide()}}}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return this.options.airMode&&!k.isEmpty(this.options.popover.air)}},{key:"initialize",value:function(){var t=this;this.$popover=this.ui.popover({className:"note-air-popover"}).render().appendTo(this.options.container);var e=this.$popover.find(".popover-content");this.context.invoke("buttons.build",e,this.options.popover.air),this.$popover.on("mousedown",(function(){t.hidable=!1})),this.$popover.on("mouseup",(function(){t.hidable=!0}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t){var n=this.context.invoke("editor.currentStyle");if(!n.range||n.range.isCollapsed()&&!t)this.hide();else{var o={left:this.pageX,top:this.pageY},i=e()(this.options.container).offset();o.top-=i.top,o.left-=i.left,this.$popover.css({display:"block",left:Math.max(o.left,0)+-5,top:o.top+5}),this.context.invoke("buttons.updateCurrentStyle",this.$popover)}}},{key:"updateCodeview",value:function(t){this.ui.toggleBtnActive(this.$popover.find(".btn-codeview"),t),t&&this.hide()}},{key:"hide",value:function(){this.hidable&&this.$popover.hide()}}])&&Ce(n.prototype,o),i&&Ce(n,i),t}();function Se(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Te=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$editable=n.layoutInfo.editable,this.options=n.options,this.hint=this.options.hint||[],this.direction=this.options.hintDirection||"bottom",this.hints=Array.isArray(this.hint)?this.hint:[this.hint],this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||o.handleKeyup(e)},"summernote.keydown":function(t,e){o.handleKeydown(e)},"summernote.disable summernote.dialog.shown summernote.blur":function(){o.hide()}}}var n,o,i;return n=t,o=[{key:"shouldInitialize",value:function(){return this.hints.length>0}},{key:"initialize",value:function(){var t=this;this.lastWordRange=null,this.matchingWord=null,this.$popover=this.ui.popover({className:"note-hint-popover",hideArrow:!0,direction:""}).render().appendTo(this.options.container),this.$popover.hide(),this.$content=this.$popover.find(".popover-content,.note-popover-content"),this.$content.on("click",".note-hint-item",(function(n){t.$content.find(".active").removeClass("active"),e()(n.currentTarget).addClass("active"),t.replace()})),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"selectItem",value:function(t){this.$content.find(".active").removeClass("active"),t.addClass("active"),this.$content[0].scrollTop=t[0].offsetTop-this.$content.innerHeight()/2}},{key:"moveDown",value:function(){var t=this.$content.find(".note-hint-item.active"),e=t.next();if(e.length)this.selectItem(e);else{var n=t.parent().next();n.length||(n=this.$content.find(".note-hint-group").first()),this.selectItem(n.find(".note-hint-item").first())}}},{key:"moveUp",value:function(){var t=this.$content.find(".note-hint-item.active"),e=t.prev();if(e.length)this.selectItem(e);else{var n=t.parent().prev();n.length||(n=this.$content.find(".note-hint-group").last()),this.selectItem(n.find(".note-hint-item").last())}}},{key:"replace",value:function(){var t=this.$content.find(".note-hint-item.active");if(t.length){var n=this.nodeFromItem(t);if(null!==this.matchingWord&&0===this.matchingWord.length)this.lastWordRange.so=this.lastWordRange.eo;else if(null!==this.matchingWord&&this.matchingWord.length>0&&!this.lastWordRange.isCollapsed()){var o=this.lastWordRange.eo-this.lastWordRange.so-this.matchingWord.length;o>0&&(this.lastWordRange.so+=o)}if(this.lastWordRange.insertNode(n),"next"===this.options.hintSelect){var i=document.createTextNode("");e()(n).after(i),yt.createFromNodeBefore(i).select()}else yt.createFromNodeAfter(n).select();this.lastWordRange=null,this.hide(),this.context.invoke("editor.focus"),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}}},{key:"nodeFromItem",value:function(t){var e=this.hints[t.data("index")],n=t.data("item"),o=e.content?e.content(n):n;return"string"==typeof o&&(o=ht.createText(o)),o}},{key:"createItemTemplates",value:function(t,n){var o=this.hints[t];return n.map((function(n){var i=e()('<div class="note-hint-item"></div>');return i.append(o.template?o.template(n):n+""),i.data({index:t,item:n}),i}))}},{key:"handleKeydown",value:function(t){this.$popover.is(":visible")&&(t.keyCode===wt.code.ENTER?(t.preventDefault(),this.replace()):t.keyCode===wt.code.UP?(t.preventDefault(),this.moveUp()):t.keyCode===wt.code.DOWN&&(t.preventDefault(),this.moveDown()))}},{key:"searchKeyword",value:function(t,e,n){var o=this.hints[t];if(o&&o.match.test(e)&&o.search){var i=o.match.exec(e);this.matchingWord=i[0],o.search(i[1],n)}else n()}},{key:"createGroup",value:function(t,n){var o=this,i=e()('<div class="note-hint-group note-hint-group-'+t+'"></div>');return this.searchKeyword(t,n,(function(e){(e=e||[]).length&&(i.html(o.createItemTemplates(t,e)),o.show())})),i}},{key:"handleKeyup",value:function(t){var n=this;if(!k.contains([wt.code.ENTER,wt.code.UP,wt.code.DOWN],t.keyCode)){var o,i,r=this.context.invoke("editor.getLastRange");if("words"===this.options.hintMode){if(o=r.getWordsRange(r),i=o.toString(),this.hints.forEach((function(t){if(t.match.test(i))return o=r.getWordsMatchRange(t.match),!1})),!o)return void this.hide();i=o.toString()}else o=r.getWordRange(),i=o.toString();if(this.hints.length&&i){this.$content.empty();var a=v.rect2bnd(k.last(o.getClientRects())),s=e()(this.options.container).offset();a&&(a.top-=s.top,a.left-=s.left,this.$popover.hide(),this.lastWordRange=o,this.hints.forEach((function(t,e){t.match.test(i)&&n.createGroup(e,i).appendTo(n.$content)})),this.$content.find(".note-hint-item:first").addClass("active"),"top"===this.direction?this.$popover.css({left:a.left,top:a.top-this.$popover.outerHeight()-5}):this.$popover.css({left:a.left,top:a.top+a.height+5}))}else this.hide()}}},{key:"show",value:function(){this.$popover.show()}},{key:"hide",value:function(){this.$popover.hide()}}],o&&Se(n.prototype,o),i&&Se(n,i),t}();function Ee(t){return Ee="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ee(t)}function Ie(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}e().summernote=e().extend(e().summernote,{version:"0.8.20",plugins:{},dom:ht,range:yt,lists:k,options:{langInfo:e().summernote.lang["en-US"],editing:!0,modules:{editor:Ft,clipboard:Ht,dropzone:Bt,codeview:jt,statusbar:Kt,fullscreen:qt,handle:Gt,hintPopover:Te,autoLink:Qt,autoSync:Jt,autoReplace:ee,placeholder:oe,buttons:re,toolbar:se,linkDialog:ce,linkPopover:de,imageDialog:fe,imagePopover:ve,tablePopover:ge,videoDialog:ye,helpDialog:we,airPopover:xe},buttons:{},lang:"en-US",followingToolbar:!1,toolbarPosition:"top",otherStaticBar:"",codeviewKeepButton:!1,toolbar:[["style",["style"]],["font",["bold","underline","clear"]],["fontname",["fontname"]],["color",["color"]],["para",["ul","ol","paragraph"]],["table",["table"]],["insert",["link","picture","video"]],["view",["fullscreen","codeview","help"]]],popatmouse:!0,popover:{image:[["resize",["resizeFull","resizeHalf","resizeQuarter","resizeNone"]],["float",["floatLeft","floatRight","floatNone"]],["remove",["removeMedia"]]],link:[["link",["linkDialogShow","unlink"]]],table:[["add",["addRowDown","addRowUp","addColLeft","addColRight"]],["delete",["deleteRow","deleteCol","deleteTable"]]],air:[["color",["color"]],["font",["bold","underline","clear"]],["para",["ul","paragraph"]],["table",["table"]],["insert",["link","picture"]],["view",["fullscreen","codeview"]]]},airMode:!1,overrideContextMenu:!1,width:null,height:null,linkTargetBlank:!0,useProtocol:!0,defaultProtocol:"http://",focus:!1,tabDisabled:!1,tabSize:4,styleWithCSS:!1,shortcuts:!0,textareaAutoSync:!0,tooltip:"auto",container:null,maxTextLength:0,blockquoteBreakingLevel:2,spellCheck:!0,disableGrammar:!1,placeholder:null,inheritPlaceholder:!1,recordEveryKeystroke:!1,historyLimit:200,showDomainOnlyForAutolink:!1,hintMode:"word",hintSelect:"after",hintDirection:"bottom",styleTags:["p","blockquote","pre","h1","h2","h3","h4","h5","h6"],fontNames:["Arial","Arial Black","Comic Sans MS","Courier New","Helvetica Neue","Helvetica","Impact","Lucida Grande","Tahoma","Times New Roman","Verdana"],fontNamesIgnoreCheck:[],addDefaultFonts:!0,fontSizes:["8","9","10","11","12","14","18","24","36"],fontSizeUnits:["px","pt"],colors:[["#000000","#424242","#636363","#9C9C94","#CEC6CE","#EFEFEF","#F7F7F7","#FFFFFF"],["#FF0000","#FF9C00","#FFFF00","#00FF00","#00FFFF","#0000FF","#9C00FF","#FF00FF"],["#F7C6CE","#FFE7CE","#FFEFC6","#D6EFD6","#CEDEE7","#CEE7F7","#D6D6E7","#E7D6DE"],["#E79C9C","#FFC69C","#FFE79C","#B5D6A5","#A5C6CE","#9CC6EF","#B5A5D6","#D6A5BD"],["#E76363","#F7AD6B","#FFD663","#94BD7B","#73A5AD","#6BADDE","#8C7BC6","#C67BA5"],["#CE0000","#E79439","#EFC631","#6BA54A","#4A7B8C","#3984C6","#634AA5","#A54A7B"],["#9C0000","#B56308","#BD9400","#397B21","#104A5A","#085294","#311873","#731842"],["#630000","#7B3900","#846300","#295218","#083139","#003163","#21104A","#4A1031"]],colorsName:[["Black","Tundora","Dove Gray","Star Dust","Pale Slate","Gallery","Alabaster","White"],["Red","Orange Peel","Yellow","Green","Cyan","Blue","Electric Violet","Magenta"],["Azalea","Karry","Egg White","Zanah","Botticelli","Tropical Blue","Mischka","Twilight"],["Tonys Pink","Peach Orange","Cream Brulee","Sprout","Casper","Perano","Cold Purple","Careys Pink"],["Mandy","Rajah","Dandelion","Olivine","Gulf Stream","Viking","Blue Marguerite","Puce"],["Guardsman Red","Fire Bush","Golden Dream","Chelsea Cucumber","Smalt Blue","Boston Blue","Butterfly Bush","Cadillac"],["Sangria","Mai Tai","Buddha Gold","Forest Green","Eden","Venice Blue","Meteorite","Claret"],["Rosewood","Cinnamon","Olive","Parsley","Tiber","Midnight Blue","Valentino","Loulou"]],colorButton:{foreColor:"#000000",backColor:"#FFFF00"},lineHeights:["1.0","1.2","1.4","1.5","1.6","1.8","2.0","3.0"],tableClassName:"table table-bordered",insertTableMaxSize:{col:10,row:10},dialogsInBody:!1,dialogsFade:!1,maximumImageFileSize:null,acceptImageFileTypes:"image/*",callbacks:{onBeforeCommand:null,onBlur:null,onBlurCodeview:null,onChange:null,onChangeCodeview:null,onDialogShown:null,onEnter:null,onFocus:null,onImageLinkInsert:null,onImageUpload:null,onImageUploadError:null,onInit:null,onKeydown:null,onKeyup:null,onMousedown:null,onMouseup:null,onPaste:null,onScroll:null},codemirror:{mode:"text/html",htmlMode:!0,lineNumbers:!0},codeviewFilter:!0,codeviewFilterRegex:/<\/*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|ilayer|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|t(?:itle|extarea)|xml)[^>]*?>/gi,codeviewIframeFilter:!0,codeviewIframeWhitelistSrc:[],codeviewIframeWhitelistSrcBase:["www.youtube.com","www.youtube-nocookie.com","www.facebook.com","vine.co","instagram.com","player.vimeo.com","www.dailymotion.com","player.youku.com","jumpingbean.tv","v.qq.com"],keyMap:{pc:{ESC:"escape",ENTER:"insertParagraph","CTRL+Z":"undo","CTRL+Y":"redo",TAB:"tab","SHIFT+TAB":"untab","CTRL+B":"bold","CTRL+I":"italic","CTRL+U":"underline","CTRL+SHIFT+S":"strikethrough","CTRL+BACKSLASH":"removeFormat","CTRL+SHIFT+L":"justifyLeft","CTRL+SHIFT+E":"justifyCenter","CTRL+SHIFT+R":"justifyRight","CTRL+SHIFT+J":"justifyFull","CTRL+SHIFT+NUM7":"insertUnorderedList","CTRL+SHIFT+NUM8":"insertOrderedList","CTRL+LEFTBRACKET":"outdent","CTRL+RIGHTBRACKET":"indent","CTRL+NUM0":"formatPara","CTRL+NUM1":"formatH1","CTRL+NUM2":"formatH2","CTRL+NUM3":"formatH3","CTRL+NUM4":"formatH4","CTRL+NUM5":"formatH5","CTRL+NUM6":"formatH6","CTRL+ENTER":"insertHorizontalRule","CTRL+K":"linkDialog.show"},mac:{ESC:"escape",ENTER:"insertParagraph","CMD+Z":"undo","CMD+SHIFT+Z":"redo",TAB:"tab","SHIFT+TAB":"untab","CMD+B":"bold","CMD+I":"italic","CMD+U":"underline","CMD+SHIFT+S":"strikethrough","CMD+BACKSLASH":"removeFormat","CMD+SHIFT+L":"justifyLeft","CMD+SHIFT+E":"justifyCenter","CMD+SHIFT+R":"justifyRight","CMD+SHIFT+J":"justifyFull","CMD+SHIFT+NUM7":"insertUnorderedList","CMD+SHIFT+NUM8":"insertOrderedList","CMD+LEFTBRACKET":"outdent","CMD+RIGHTBRACKET":"indent","CMD+NUM0":"formatPara","CMD+NUM1":"formatH1","CMD+NUM2":"formatH2","CMD+NUM3":"formatH3","CMD+NUM4":"formatH4","CMD+NUM5":"formatH5","CMD+NUM6":"formatH6","CMD+ENTER":"insertHorizontalRule","CMD+K":"linkDialog.show"}},icons:{align:"note-icon-align",alignCenter:"note-icon-align-center",alignJustify:"note-icon-align-justify",alignLeft:"note-icon-align-left",alignRight:"note-icon-align-right",rowBelow:"note-icon-row-below",colBefore:"note-icon-col-before",colAfter:"note-icon-col-after",rowAbove:"note-icon-row-above",rowRemove:"note-icon-row-remove",colRemove:"note-icon-col-remove",indent:"note-icon-align-indent",outdent:"note-icon-align-outdent",arrowsAlt:"note-icon-arrows-alt",bold:"note-icon-bold",caret:"note-icon-caret",circle:"note-icon-circle",close:"note-icon-close",code:"note-icon-code",eraser:"note-icon-eraser",floatLeft:"note-icon-float-left",floatRight:"note-icon-float-right",font:"note-icon-font",frame:"note-icon-frame",italic:"note-icon-italic",link:"note-icon-link",unlink:"note-icon-chain-broken",magic:"note-icon-magic",menuCheck:"note-icon-menu-check",minus:"note-icon-minus",orderedlist:"note-icon-orderedlist",pencil:"note-icon-pencil",picture:"note-icon-picture",question:"note-icon-question",redo:"note-icon-redo",rollback:"note-icon-rollback",square:"note-icon-square",strikethrough:"note-icon-strikethrough",subscript:"note-icon-subscript",superscript:"note-icon-superscript",table:"note-icon-table",textHeight:"note-icon-text-height",trash:"note-icon-trash",underline:"note-icon-underline",undo:"note-icon-undo",unorderedlist:"note-icon-unorderedlist",video:"note-icon-video"}}});var $e=function(){function t(e,n,o,i){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.markup=e,this.children=n,this.options=o,this.callback=i}var n,o,i;return n=t,(o=[{key:"render",value:function(t){var n=e()(this.markup);if(this.options&&this.options.contents&&n.html(this.options.contents),this.options&&this.options.className&&n.addClass(this.options.className),this.options&&this.options.data&&e().each(this.options.data,(function(t,e){n.attr("data-"+t,e)})),this.options&&this.options.click&&n.on("click",this.options.click),this.children){var o=n.find(".note-children-container");this.children.forEach((function(t){t.render(o.length?o:n)}))}return this.callback&&this.callback(n,this.options),this.options&&this.options.callback&&this.options.callback(n),t&&t.append(n),n}}])&&Ie(n.prototype,o),i&&Ie(n,i),t}();const Ne=function(t,e){return function(){var n="object"===Ee(arguments[1])?arguments[1]:arguments[0],o=Array.isArray(arguments[0])?arguments[0]:[];return n&&n.children&&(o=n.children),new $e(t,o,n,e)}};function Pe(t){return Pe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Pe(t)}var Re=Ne('<div class="note-editor note-frame panel panel-default"></div>'),Le=Ne('<div class="panel-heading note-toolbar" role="toolbar"></div>'),Ae=Ne('<div class="note-editing-area"></div>'),Fe=Ne('<textarea class="note-codable" aria-multiline="true"></textarea>'),De=Ne('<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>'),He=Ne(['<output class="note-status-output" role="status" aria-live="polite"></output>','<div class="note-statusbar" role="status">','<div class="note-resizebar" aria-label="Resize">','<div class="note-icon-bar"></div>','<div class="note-icon-bar"></div>','<div class="note-icon-bar"></div>',"</div>","</div>"].join("")),ze=Ne('<div class="note-editor note-airframe"></div>'),Be=Ne(['<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>','<output class="note-status-output" role="status" aria-live="polite"></output>'].join("")),Me=Ne('<div class="note-btn-group btn-group"></div>'),Oe=Ne('<ul class="note-dropdown-menu dropdown-menu"></ul>',(function(t,e){var n=Array.isArray(e.items)?e.items.map((function(t){var n="string"==typeof t?t:t.value||"",o=e.template?e.template(t):t,i="object"===Pe(t)?t.option:void 0;return'<li aria-label="'+n+'"><a href="#" '+('data-value="'+n+'"'+(void 0!==i?' data-option="'+i+'"':""))+">"+o+"</a></li>"})).join(""):e.items;t.html(n).attr({"aria-label":e.title}),e&&e.codeviewKeepButton&&t.addClass("note-codeview-keep")})),Ue=function(t,e){return t+" "+qe(e.icons.caret,"span")},je=Ne('<ul class="note-dropdown-menu dropdown-menu note-check"></ul>',(function(t,e){var n=Array.isArray(e.items)?e.items.map((function(t){var n="string"==typeof t?t:t.value||"",o=e.template?e.template(t):t;return'<li aria-label="'+t+'"><a href="#" data-value="'+n+'">'+qe(e.checkClassName)+" "+o+"</a></li>"})).join(""):e.items;t.html(n).attr({"aria-label":e.title}),e&&e.codeviewKeepButton&&t.addClass("note-codeview-keep")})),We=Ne('<div class="modal note-modal" aria-hidden="false" tabindex="-1" role="dialog"></div>',(function(t,e){e.fade&&t.addClass("fade"),t.attr({"aria-label":e.title}),t.html(['<div class="modal-dialog">','<div class="modal-content">',e.title?'<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close" aria-hidden="true">&times;</button><h4 class="modal-title">'+e.title+"</h4></div>":"",'<div class="modal-body">'+e.body+"</div>",e.footer?'<div class="modal-footer">'+e.footer+"</div>":"","</div>","</div>"].join(""))})),Ke=Ne(['<div class="note-popover popover in">','<div class="arrow"></div>','<div class="popover-content note-children-container"></div>',"</div>"].join(""),(function(t,e){var n=void 0!==e.direction?e.direction:"bottom";t.addClass(n),e.hideArrow&&t.find(".arrow").hide()})),Ve=Ne('<div class="checkbox"></div>',(function(t,e){t.html(["<label"+(e.id?' for="note-'+e.id+'"':"")+">",'<input type="checkbox"'+(e.id?' id="note-'+e.id+'"':""),e.checked?" checked":"",' aria-checked="'+(e.checked?"true":"false")+'"/>',e.text?e.text:"","</label>"].join(""))})),qe=function(t,e){return t.match(/^</)?t:"<"+(e=e||"i")+' class="'+t+'"></'+e+">"};e().summernote=e().extend(e().summernote,{ui_template:function(t){return{editor:Re,toolbar:Le,editingArea:Ae,codable:Fe,editable:De,statusbar:He,airEditor:ze,airEditable:Be,buttonGroup:Me,dropdown:Oe,dropdownButtonContents:Ue,dropdownCheck:je,dialog:We,popover:Ke,checkbox:Ve,icon:qe,options:t,palette:function(e,n){return Ne('<div class="note-color-palette"></div>',(function(e,n){for(var o=[],i=0,r=n.colors.length;i<r;i++){for(var a=n.eventName,s=n.colors[i],l=n.colorsName[i],c=[],u=0,d=s.length;u<d;u++){var h=s[u],f=l[u];c.push(['<button type="button" class="note-color-btn"','style="background-color:',h,'" ','data-event="',a,'" ','data-value="',h,'" ','title="',f,'" ','aria-label="',f,'" ','data-toggle="button" tabindex="-1"></button>'].join(""))}o.push('<div class="note-color-row">'+c.join("")+"</div>")}e.html(o.join("")),n.tooltip&&e.find(".note-color-btn").tooltip({container:n.container||t.container,trigger:"hover",placement:"bottom"})}))(e,n)},button:function(n,o){return Ne('<button type="button" class="note-btn btn btn-default btn-sm" tabindex="-1"></button>',(function(n,o){o&&o.tooltip&&n.attr({title:o.tooltip,"aria-label":o.tooltip}).tooltip({container:o.container||t.container,trigger:"hover",placement:"bottom"}).on("click",(function(t){e()(t.currentTarget).tooltip("hide")})),o&&o.codeviewButton&&n.addClass("note-codeview-keep")}))(n,o)},toggleBtn:function(t,e){t.toggleClass("disabled",!e),t.attr("disabled",!e)},toggleBtnActive:function(t,e){t.toggleClass("active",e)},onDialogShown:function(t,e){t.one("shown.bs.modal",e)},onDialogHidden:function(t,e){t.one("hidden.bs.modal",e)},showDialog:function(t){t.modal("show")},hideDialog:function(t){t.modal("hide")},createLayout:function(e){var n=(t.airMode?ze([Ae([Fe(),Be()])]):"bottom"===t.toolbarPosition?Re([Ae([Fe(),De()]),Le(),He()]):Re([Le(),Ae([Fe(),De()]),He()])).render();return n.insertAfter(e),{note:e,editor:n,toolbar:n.find(".note-toolbar"),editingArea:n.find(".note-editing-area"),editable:n.find(".note-editable"),codable:n.find(".note-codable"),statusbar:n.find(".note-statusbar")}},removeLayout:function(t,e){t.html(e.editable.html()),e.editor.remove(),t.show()}}},interface:"bs3"})})(),i})()}));
294coder/Efficient-MIF
3,947
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/gradientapproximations/approxgradientFD.m
function gradfun = approxgradientFD(problem, options) % Gradient approx. fnctn handle based on finite differences of the cost. % % function gradfun = approxgradientFD(problem) % function gradfun = approxgradientFD(problem, options) % % Input: % % A Manopt problem structure (already containing the manifold and enough % information to compute the cost) and an options structure (optional), % containing one option: % options.stepsize (positive double; default: 2^-23). % options.subspacedim (positive integer; default: [], for M.dim()). % % If the cost cannot be computed on 'problem', a warning is issued. % % Output: % % Returns a function handle, encapsulating a generic finite difference % approximation of the gradient of the problem cost. The finite difference % is based on M.dim()+1 computations of the cost. % % The returned gradfun has this calling pattern: % % function gradfd = gradfun(x) % function gradfd = gradfun(x, storedb) % function gradfd = gradfun(x, storedb, key) % % x is a point on the manifold problem.M, storedb is a StoreDB object, % and key is the StoreDB key to point x. % % Usage: % % Typically, the user will set problem.M and other fields to define the % cost (typically, problem.cost). Then, to use this generic purpose % gradient approximation: % % problem.approxgrad = approxgradientFD(problem, options); % % See also: steepestdescent conjugategradient % This file is part of Manopt: www.manopt.org. % Original author: Nicolas Boumal, Nov. 1, 2016. % Contributors: % Change log: % This gradient approximation is based on the cost: % check availability. if ~canGetCost(problem) warning('manopt:approxgradFD:nocost', ... 'approxgradFD requires the cost to be computable.'); end % Set local defaults here, and merge with user options, if any. localdefaults.stepsize = 2^-23; localdefaults.subspacedim = []; if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(localdefaults, options); % % Finite-difference parameters % How far do we look? stepsize = options.stepsize; % Approximate the projection of the gradient on a random subspace of % what dimension? If [], uses full tangent space. subspacedim = options.subspacedim; % Build and return the function handle here. This extra construct via % funhandle makes it possible to make storedb and key optional. gradfun = @funhandle; function gradfd = funhandle(x, storedb, key) % Allow omission of the key, and even of storedb. if ~exist('key', 'var') if ~exist('storedb', 'var') storedb = StoreDB(); end key = storedb.getNewKey(); end gradfd = gradientFD(stepsize, subspacedim, problem, x, storedb, key); end end function gradfd = gradientFD(stepsize, subspacedim, problem, x, storedb, key) % This function does the actual work. % % Original code: Nov. 1, 2016 (NB). % Evaluate the cost at the root point fx = getCost(problem, x, storedb, key); % Pick an orthonormal basis for the tangent space at x, or a subspace % thereof. The default is a full subspace. If a strict subspace is % picked, the returned vector approximates the orthogonal projection of % the gradient to that subspace. B = tangentorthobasis(problem.M, x, subspacedim); % Use finite differences to approximate the directional derivative % along each direction in the basis B. df = zeros(size(B)); for k = 1 : numel(B) % Move in the B{k} direction xk = problem.M.retr(x, B{k}, stepsize); % Evaluate the cost there fxk = getCost(problem, xk, storedb); % Finite difference df(k) = (fxk - fx)/stepsize; end % Build the gradient approximation. gradfd = lincomb(problem.M, x, B, df); end
281677160/openwrt-package
4,568
luci-app-tencentddns/root/usr/sbin/tencentddns
#!/bin/sh NAME=tencentddns log_file=/var/log/$NAME.log uci_bool_by_name() { case "$(uci get $NAME.$1.$2 2>/dev/null)" in 1|on|true|yes|enabled) return 0;; esac return 1 } intelnetip() { tmp_ip=`curl -sL -m 5 -4 myip.ipip.net/s | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | tail -n1` if [ "Z$tmp_ip" == "Z" ]; then tmp_ip=`curl -sL -m 5 -4 www.cip.cc | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | tail -n1` fi if [ "Z$tmp_ip" == "Z" ]; then tmp_ip=`curl -sL -m 5 -4 ip.3322.net | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | tail -n1` fi if [ "Z$tmp_ip" == "Z" ]; then tmp_ip=`curl -sL -m 5 -4 ifcfg.cn | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | tail -n1` fi echo -n $tmp_ip } resolve2ip() { # resolve2ip domain<string> domain=$1 tmp_ip=`nslookup $domain ambulance.dnspod.net 2>/dev/null | sed '/^Server/d; /#53$/d' | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | tail -n1` if [ "Z$tmp_ip" == "Z" ]; then tmp_ip=`nslookup $domain lupus.dnspod.net 2>/dev/null | sed '/^Server/d; /#53$/d' | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | tail -n1` fi if [ "Z$tmp_ip" == "Z" ]; then tmp_ip=`curl -sL -m 5 -4 "119.29.29.29/d?dn=$domain" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | tail -n1` fi echo -n $tmp_ip } check_tencentddns() { echo "$DATE WAN-IP: ${ip}" if [ "Z$ip" == "Z" ]; then echo "$DATE ERROR, cant get WAN-IP..." return 0 fi current_ip=$(resolve2ip "$sub_dm.$main_dm") if [ "Z$current_ip" == "Z" ]; then rrid='' # NO Resolve IP Means new Record_ID fi echo "$DATE DOMAIN-IP: ${current_ip}" if [ "Z$ip" == "Z$current_ip" ]; then echo "$DATE IP dont need UPDATE..." return 0 else echo "$DATE UPDATING..." return 1 fi } urlencode() { # urlencode url<string> out='' for c in $(echo -n $1 | sed 's/[^\n]/&\n/g'); do case $c in [a-zA-Z0-9._-]) out="$out$c" ;; *) out="$out$(printf '%%%02X' "'$c")" ;; esac done echo -n $out } send_request() { curl -s -X POST https://dnsapi.cn/$1 -d "login_token=$ak_id,$ak_token&format=json&"$2 } get_recordid() { sed 's/"records"/\n/g' | sed -n '2p' | sed 's/ttl/\n/g' | sed -n 's/.*"id[^0-9]*\([0-9]*\).*/\1\n/p' | sort -ru | sed /^$/d } get_recordid2() { sed 's/"record"/\n/g' | sed -n '2p' | sed -n 's/.*"id[^0-9]*\([0-9]*\).*/\1\n/p' | sort -ru | sed /^$/d } query_recordid() { send_request "Record.List" "domain=$main_dm&sub_domain=$sub_dm&record_type=A" } update_record() { send_request "Record.Ddns" "domain=$main_dm&sub_domain=$sub_dm&record_id=$1&record_type=A&record_line=%e9%bb%98%e8%ae%a4&value=$ip" } add_record() { send_request "Record.Create" "domain=$main_dm&sub_domain=$sub_dm&record_type=A&record_line=%e9%bb%98%e8%ae%a4&value=$ip" } del_record() { send_request "Record.Remove" "domain=$main_dm&record_id=$1" } do_ddns_record() { if uci_bool_by_name base clean ; then query_recordid | get_recordid | while read rr; do echo "$DATE Clean record $sub_dm.$main_dm: $rr" del_record $rr >/dev/null timestamp=$(date -u "+%Y-%m-%dT%H%%3A%M%%3A%SZ") done rrid='' fi if [ "Z$rrid" == "Z" ]; then rrid=`query_recordid | get_recordid` fi if [ "Z$rrid" == "Z" ]; then rrid=`add_record | get_recordid2` echo "$DATE ADD record $rrid" else update_record $rrid >/dev/null 2>&1 echo "$DATE UPDATE record $rrid" fi if [ "Z$rrid" == "Z" ]; then # failed echo "$DATE # ERROR, Please Check Config/Time" else # save rrid uci set tencentddns.base.record_id=$rrid uci commit tencentddns echo "$DATE # UPDATED($ip)" fi } clean_log() { if [ $(cat $log_file 2>/dev/null | wc -l) -ge 16 ]; then rm -f $log_file && touch $log_file echo "$DATE Log Cleaned" fi } [ -x /usr/bin/openssl -a -x /usr/bin/curl -a -x /bin/sed ] || ( echo "Need [ openssl + curl + sed ]" && exit 1 ) ak_id=$(uci get $NAME.base.key_id 2>/dev/null) ak_token=$(uci get $NAME.base.key_token 2>/dev/null) rrid=$(uci get $NAME.base.record_id 2>/dev/null) main_dm=$(uci get $NAME.base.main_domain 2>/dev/null) sub_dm=$(uci get $NAME.base.sub_domain 2>/dev/null) iface=$(uci get $NAME.base.interface 2>/dev/null) if [ "Z$iface" == "Zinternet" -o "Z$iface" == "Z" ]; then ip=$(intelnetip) else ip=$(ubus call network.interface.$iface status | grep '"address"' | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) fi DATE=$(date +'%Y-%m-%d %H:%M:%S') timestamp=$(date -u "+%Y-%m-%dT%H%%3A%M%%3A%SZ") clean_log check_tencentddns || do_ddns_record
294coder/Efficient-MIF
9,403
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/steepestdescent/steepestdescent.m
function [x, cost, info, options] = steepestdescent(problem, x, options) % Steepest descent (gradient descent) minimization algorithm for Manopt. % % function [x, cost, info, options] = steepestdescent(problem) % function [x, cost, info, options] = steepestdescent(problem, x0) % function [x, cost, info, options] = steepestdescent(problem, x0, options) % function [x, cost, info, options] = steepestdescent(problem, [], options) % % Apply the steepest descent minimization algorithm to the problem defined % in the problem structure, starting at x0 if it is provided (otherwise, at % a random point on the manifold). To specify options whilst not specifying % an initial guess, give x0 as [] (the empty matrix). % % In most of the examples bundled with the toolbox (see link below), the % solver can be replaced by the present one if need be. % % The outputs x and cost are the best reached point on the manifold and its % cost. The struct-array info contains information about the iterations: % iter : the iteration number (0 for the initial guess) % cost : cost value % time : elapsed time in seconds % gradnorm : Riemannian norm of the gradient % stepsize : norm of the last tangent vector retracted % linesearch : information logged by options.linesearch % And possibly additional information logged by options.statsfun. % For example, type [info.gradnorm] to obtain a vector of the successive % gradient norms reached. % % The options structure is used to overwrite the default values. All % options have a default value and are hence optional. To force an option % value, pass an options structure with a field options.optionname, where % optionname is one of the following and the default value is indicated % between parentheses: % % tolgradnorm (1e-6) % The algorithm terminates if the norm of the gradient drops below this. % maxiter (1000) % The algorithm terminates if maxiter iterations have been executed. % maxtime (Inf) % The algorithm terminates if maxtime seconds elapsed. % minstepsize (1e-10) % The algorithm terminates if the linesearch returns a displacement % vector (to be retracted) smaller in norm than this value. % linesearch (@linesearch or @linesearch_hint) % Function handle to a line search function. The options structure is % passed to the line search too, so you can pass it parameters. See % each line search's documentation for info. Another available line % search in manopt is @linesearch_adaptive, in % /manopt/linesearch/linesearch_adaptive.m % If the problem structure includes a line search hint, then the % default line search used is @linesearch_hint. % statsfun (none) % Function handle to a function that will be called after each % iteration to provide the opportunity to log additional statistics. % They will be returned in the info struct. See the generic Manopt % documentation about solvers for further information. % stopfun (none) % Function handle to a function that will be called at each iteration % to provide the opportunity to specify additional stopping criteria. % See the generic Manopt documentation about solvers for further % information. % verbosity (3) % Integer number used to tune the amount of output the algorithm % generates during execution (mostly as text in the command window). % The higher, the more output. 0 means silent. % storedepth (2) % Maximum number of different points x of the manifold for which a % store structure will be kept in memory in the storedb. If the % caching features of Manopt are not used, this is irrelevant. For % the SD algorithm, a store depth of 2 should always be sufficient. % % % See also: conjugategradient trustregions manopt/solvers/linesearch manopt/examples % This file is part of Manopt: www.manopt.org. % Original author: Nicolas Boumal, Dec. 30, 2012. % Contributors: % Change log: % % April 3, 2015 (NB): % Works with the new StoreDB class system. % Verify that the problem description is sufficient for the solver. if ~canGetCost(problem) warning('manopt:getCost', ... 'No cost provided. The algorithm will likely abort.'); end if ~canGetGradient(problem) && ~canGetApproxGradient(problem) % Note: we do not give a warning if an approximate gradient is % explicitly given in the problem description, as in that case the % user seems to be aware of the issue. warning('manopt:getGradient:approx', ... ['No gradient provided. Using an FD approximation instead (slow).\n' ... 'It may be necessary to increase options.tolgradnorm.\n' ... 'To disable this warning: warning(''off'', ''manopt:getGradient:approx'')']); problem.approxgrad = approxgradientFD(problem); end % Set local defaults here localdefaults.minstepsize = 1e-10; localdefaults.maxiter = 1000; localdefaults.tolgradnorm = 1e-6; % Depending on whether the problem structure specifies a hint for % line-search algorithms, choose a default line-search that works on % its own (typical) or that uses the hint. if ~canGetLinesearch(problem) localdefaults.linesearch = @linesearch; else localdefaults.linesearch = @linesearch_hint; end % Merge global and local defaults, then merge w/ user options, if any. localdefaults = mergeOptions(getGlobalDefaults(), localdefaults); if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(localdefaults, options); timetic = tic(); % If no initial point x is given by the user, generate one at random. if ~exist('x', 'var') || isempty(x) x = problem.M.rand(); end % Create a store database and get a key for the current x storedb = StoreDB(options.storedepth); key = storedb.getNewKey(); % Compute objective-related quantities for x [cost, grad] = getCostGrad(problem, x, storedb, key); gradnorm = problem.M.norm(x, grad); % Iteration counter. % At any point, iter is the number of fully executed iterations so far. iter = 0; % Save stats in a struct array info, and preallocate. stats = savestats(); info(1) = stats; info(min(10000, options.maxiter+1)).iter = []; if options.verbosity >= 2 fprintf(' iter\t cost val\t grad. norm\n'); end % Start iterating until stopping criterion triggers while true % Display iteration information if options.verbosity >= 2 fprintf('%5d\t%+.16e\t%.8e\n', iter, cost, gradnorm); end % Start timing this iteration timetic = tic(); % Run standard stopping criterion checks [stop, reason] = stoppingcriterion(problem, x, options, ... info, iter+1); % If none triggered, run specific stopping criterion check if ~stop && stats.stepsize < options.minstepsize stop = true; reason = sprintf(['Last stepsize smaller than minimum ' ... 'allowed; options.minstepsize = %g.'], ... options.minstepsize); end if stop if options.verbosity >= 1 fprintf([reason '\n']); end break; end % Pick the descent direction as minus the gradient desc_dir = problem.M.lincomb(x, -1, grad); % Execute the line search [stepsize, newx, newkey, lsstats] = options.linesearch( ... problem, x, desc_dir, cost, -gradnorm^2, ... options, storedb, key); % Compute the new cost-related quantities for x [newcost, newgrad] = getCostGrad(problem, newx, storedb, newkey); newgradnorm = problem.M.norm(newx, newgrad); % Make sure we don't use too much memory for the store database storedb.purge(); % Transfer iterate info x = newx; key = newkey; cost = newcost; grad = newgrad; gradnorm = newgradnorm; % iter is the number of iterations we have accomplished. iter = iter + 1; % Log statistics for freshly executed iteration stats = savestats(); info(iter+1) = stats; end info = info(1:iter+1); if options.verbosity >= 1 fprintf('Total time is %f [s] (excludes statsfun)\n', ... info(end).time); end % Routine in charge of collecting the current iteration stats function stats = savestats() stats.iter = iter; stats.cost = cost; stats.gradnorm = gradnorm; if iter == 0 stats.stepsize = NaN; stats.time = toc(timetic); stats.linesearch = []; else stats.stepsize = stepsize; stats.time = info(iter).time + toc(timetic); stats.linesearch = lsstats; end stats = applyStatsfun(problem, x, storedb, key, options, stats); end end
281677160/openwrt-package
1,397
luci-app-tencentddns/root/etc/init.d/tencentddns
#!/bin/sh /etc/rc.common START=80 NAME=tencentddns NE_TIPS='TencentDDNS NOT ENABLED' restart() { start } uci_get_by_name() { local ret=$(uci get $NAME.$1.$2 2>/dev/null) echo ${ret:=$3} } uci_bool_by_name() { case "$(uci_get_by_name $1 $2)" in 1|on|true|yes|enabled) return 0;; esac return 1 } add_hotplug() { cat <<EOF > "/etc/hotplug.d/iface/${START}-${NAME}" #!/bin/sh /etc/rc.common [ "Z\$ACTION" = "Zifup" -a "Z\$INTERFACE" = "Zwan" ] || exit 0 DATE=\$(date +'%Y-%m-%d %H:%M:%S') ( sleep 10 && ( echo "\$DATE IFUP-WAN" && /usr/sbin/tencentddns ) >> /var/log/tencentddns.log 2>&1 ) & exit 0 EOF chmod +x "/etc/hotplug.d/iface/${START}-${NAME}" } start() { $(uci_bool_by_name base enable) || { stop return 0 } add_hotplug sed -i "/${NE_TIPS}/d" /var/log/tencentddns.log time=$(uci_get_by_name base time 10) [ 0 -lt $time -a $time -lt 60 ] || time=10 [ -f /etc/crontabs/root ] || mkdir -p /etc/crontabs && touch /etc/crontabs/root sed -i '/tencentddns/d' /etc/crontabs/root echo "*/$time * * * * /usr/sbin/tencentddns >> /var/log/tencentddns.log 2>&1" >> /etc/crontabs/root /etc/init.d/cron restart ( /usr/sbin/tencentddns >> /var/log/tencentddns.log 2>&1 ) & } stop() { rm -rf "/etc/hotplug.d/iface/${START}-${NAME}" sed -i '/tencentddns/d' /etc/crontabs/root >/dev/null 2>&1 /etc/init.d/cron restart echo "${NE_TIPS}" > /var/log/tencentddns.log }
2881099/FreeSql.AdminLTE
153,024
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-bs4.min.js
/*! Summernote v0.8.20 | (c) 2013- Alan Hong and contributors | MIT license */ !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e(require("jQuery"));else if("function"==typeof define&&define.amd)define(["jQuery"],e);else{var n="object"==typeof exports?e(require("jQuery")):e(t.jQuery);for(var o in n)("object"==typeof exports?exports:t)[o]=n[o]}}(self,(function(t){return(()=>{"use strict";var e={9770:(t,e,n)=>{var o=n(1145),i=n.n(o);i().summernote=i().summernote||{lang:{}},i().extend(i().summernote.lang,{"en-US":{font:{bold:"Bold",italic:"Italic",underline:"Underline",clear:"Remove Font Style",height:"Line Height",name:"Font Family",strikethrough:"Strikethrough",subscript:"Subscript",superscript:"Superscript",size:"Font Size",sizeunit:"Font Size Unit"},image:{image:"Picture",insert:"Insert Image",resizeFull:"Resize full",resizeHalf:"Resize half",resizeQuarter:"Resize quarter",resizeNone:"Original size",floatLeft:"Float Left",floatRight:"Float Right",floatNone:"Remove float",shapeRounded:"Shape: Rounded",shapeCircle:"Shape: Circle",shapeThumbnail:"Shape: Thumbnail",shapeNone:"Shape: None",dragImageHere:"Drag image or text here",dropImage:"Drop image or Text",selectFromFiles:"Select from files",maximumFileSize:"Maximum file size",maximumFileSizeError:"Maximum file size exceeded.",url:"Image URL",remove:"Remove Image",original:"Original"},video:{video:"Video",videoLink:"Video Link",insert:"Insert Video",url:"Video URL",providers:"(YouTube, Google Drive, Vimeo, Vine, Instagram, DailyMotion, Youku, Peertube)"},link:{link:"Link",insert:"Insert Link",unlink:"Unlink",edit:"Edit",textToDisplay:"Text to display",url:"To what URL should this link go?",openInNewWindow:"Open in new window",useProtocol:"Use default protocol"},table:{table:"Table",addRowAbove:"Add row above",addRowBelow:"Add row below",addColLeft:"Add column left",addColRight:"Add column right",delRow:"Delete row",delCol:"Delete column",delTable:"Delete table"},hr:{insert:"Insert Horizontal Rule"},style:{style:"Style",p:"Normal",blockquote:"Quote",pre:"Code",h1:"Header 1",h2:"Header 2",h3:"Header 3",h4:"Header 4",h5:"Header 5",h6:"Header 6"},lists:{unordered:"Unordered list",ordered:"Ordered list"},options:{help:"Help",fullscreen:"Full Screen",codeview:"Code View"},paragraph:{paragraph:"Paragraph",outdent:"Outdent",indent:"Indent",left:"Align left",center:"Align center",right:"Align right",justify:"Justify full"},color:{recent:"Recent Color",more:"More Color",background:"Background Color",foreground:"Text Color",transparent:"Transparent",setTransparent:"Set transparent",reset:"Reset",resetToDefault:"Reset to default",cpSelect:"Select"},shortcut:{shortcuts:"Keyboard shortcuts",close:"Close",textFormatting:"Text formatting",action:"Action",paragraphFormatting:"Paragraph formatting",documentStyle:"Document Style",extraKeys:"Extra keys"},help:{escape:"Escape",insertParagraph:"Insert Paragraph",undo:"Undo the last command",redo:"Redo the last command",tab:"Tab",untab:"Untab",bold:"Set a bold style",italic:"Set a italic style",underline:"Set a underline style",strikethrough:"Set a strikethrough style",removeFormat:"Clean a style",justifyLeft:"Set left align",justifyCenter:"Set center align",justifyRight:"Set right align",justifyFull:"Set full align",insertUnorderedList:"Toggle unordered list",insertOrderedList:"Toggle ordered list",outdent:"Outdent on current paragraph",indent:"Indent on current paragraph",formatPara:"Change current block's format as a paragraph(P tag)",formatH1:"Change current block's format as H1",formatH2:"Change current block's format as H2",formatH3:"Change current block's format as H3",formatH4:"Change current block's format as H4",formatH5:"Change current block's format as H5",formatH6:"Change current block's format as H6",insertHorizontalRule:"Insert horizontal rule","linkDialog.show":"Show Link Dialog"},history:{undo:"Undo",redo:"Redo"},specialChar:{specialChar:"SPECIAL CHARACTERS",select:"Select Special characters"},output:{noSelection:"No Selection Made!"}}})},1145:e=>{e.exports=t}},n={};function o(t){var i=n[t];if(void 0!==i)return i.exports;var r=n[t]={exports:{}};return e[t](r,r.exports,o),r.exports}o.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return o.d(e,{a:e}),e},o.d=(t,e)=>{for(var n in e)o.o(e,n)&&!o.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},o.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),o.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var i={};return(()=>{o.r(i);var t=o(1145),e=o.n(t),n=(o(9770),["sans-serif","serif","monospace","cursive","fantasy"]);function r(t){return-1===e().inArray(t.toLowerCase(),n)?"'".concat(t,"'"):t}var a,s=navigator.userAgent,l=/MSIE|Trident/i.test(s);if(l){var c=/MSIE (\d+[.]\d+)/.exec(s);c&&(a=parseFloat(c[1])),(c=/Trident\/.*rv:([0-9]{1,}[.0-9]{0,})/.exec(s))&&(a=parseFloat(c[1]))}var u=/Edge\/\d+/.test(s),d="ontouchstart"in window||navigator.MaxTouchPoints>0||navigator.msMaxTouchPoints>0,h=l?"DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted":"input";const f={isMac:navigator.appVersion.indexOf("Mac")>-1,isMSIE:l,isEdge:u,isFF:!u&&/firefox/i.test(s),isPhantom:/PhantomJS/i.test(s),isWebkit:!u&&/webkit/i.test(s),isChrome:!u&&/chrome/i.test(s),isSafari:!u&&/safari/i.test(s)&&!/chrome/i.test(s),browserVersion:a,isSupportTouch:d,isFontInstalled:function(t){var e="Comic Sans MS"===t?"Courier New":"Comic Sans MS",n="mmmmmmmmmmwwwww",o=document.createElement("canvas").getContext("2d");o.font="200px '"+e+"'";var i=o.measureText(n).width;return o.font="200px "+r(t)+', "'+e+'"',i!==o.measureText(n).width},isW3CRangeSupport:!!document.createRange,inputEventName:h,genericFontFamilies:n,validFontName:r};var p=0;const m={eq:function(t){return function(e){return t===e}},eq2:function(t,e){return t===e},peq2:function(t){return function(e,n){return e[t]===n[t]}},ok:function(){return!0},fail:function(){return!1},self:function(t){return t},not:function(t){return function(){return!t.apply(t,arguments)}},and:function(t,e){return function(n){return t(n)&&e(n)}},invoke:function(t,e){return function(){return t[e].apply(t,arguments)}},resetUniqueId:function(){p=0},uniqueId:function(t){var e=++p+"";return t?t+e:e},rect2bnd:function(t){var n=e()(document);return{top:t.top+n.scrollTop(),left:t.left+n.scrollLeft(),width:t.right-t.left,height:t.bottom-t.top}},invertObject:function(t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[t[n]]=n);return e},namespaceToCamel:function(t,e){return(e=e||"")+t.split(".").map((function(t){return t.substring(0,1).toUpperCase()+t.substring(1)})).join("")},debounce:function(t,e,n){var o;return function(){var i=this,r=arguments,a=function(){o=null,n||t.apply(i,r)},s=n&&!o;clearTimeout(o),o=setTimeout(a,e),s&&t.apply(i,r)}},isValidUrl:function(t){return/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/gi.test(t)}};function v(t){return t[0]}function g(t){return t[t.length-1]}function b(t){return t.slice(1)}function y(t,e){if(t&&t.length&&e){if(t.indexOf)return-1!==t.indexOf(e);if(t.contains)return t.contains(e)}return!1}const k={head:v,last:g,initial:function(t){return t.slice(0,t.length-1)},tail:b,prev:function(t,e){if(t&&t.length&&e){var n=t.indexOf(e);return-1===n?null:t[n-1]}return null},next:function(t,e){if(t&&t.length&&e){var n=t.indexOf(e);return-1===n?null:t[n+1]}return null},find:function(t,e){for(var n=0,o=t.length;n<o;n++){var i=t[n];if(e(i))return i}},contains:y,all:function(t,e){for(var n=0,o=t.length;n<o;n++)if(!e(t[n]))return!1;return!0},sum:function(t,e){return e=e||m.self,t.reduce((function(t,n){return t+e(n)}),0)},from:function(t){for(var e=[],n=t.length,o=-1;++o<n;)e[o]=t[o];return e},isEmpty:function(t){return!t||!t.length},clusterBy:function(t,e){return t.length?b(t).reduce((function(t,n){var o=g(t);return e(g(o),n)?o[o.length]=n:t[t.length]=[n],t}),[[v(t)]]):[]},compact:function(t){for(var e=[],n=0,o=t.length;n<o;n++)t[n]&&e.push(t[n]);return e},unique:function(t){for(var e=[],n=0,o=t.length;n<o;n++)y(e,t[n])||e.push(t[n]);return e}};var w=String.fromCharCode(160);function C(t){return t&&e()(t).hasClass("note-editable")}function x(t){return t=t.toUpperCase(),function(e){return e&&e.nodeName.toUpperCase()===t}}function S(t){return t&&3===t.nodeType}function T(t){return t&&/^BR|^IMG|^HR|^IFRAME|^BUTTON|^INPUT|^AUDIO|^VIDEO|^EMBED/.test(t.nodeName.toUpperCase())}function E(t){return!C(t)&&(t&&/^DIV|^P|^LI|^H[1-7]/.test(t.nodeName.toUpperCase()))}var I=x("PRE"),$=x("LI");var N=x("TABLE"),P=x("DATA");function R(t){return!(H(t)||L(t)||A(t)||E(t)||N(t)||D(t)||P(t))}function L(t){return t&&/^UL|^OL/.test(t.nodeName.toUpperCase())}var A=x("HR");function F(t){return t&&/^TD|^TH/.test(t.nodeName.toUpperCase())}var D=x("BLOCKQUOTE");function H(t){return F(t)||D(t)||C(t)}var z=x("A");var B=x("BODY");var M=f.isMSIE&&f.browserVersion<11?"&nbsp;":"<br>";function O(t){return S(t)?t.nodeValue.length:t?t.childNodes.length:0}function U(t){var e=O(t);return 0===e||(!S(t)&&1===e&&t.innerHTML===M||!(!k.all(t.childNodes,S)||""!==t.innerHTML))}function j(t){T(t)||O(t)||(t.innerHTML=M)}function W(t,e){for(;t;){if(e(t))return t;if(C(t))break;t=t.parentNode}return null}function K(t,e){e=e||m.fail;var n=[];return W(t,(function(t){return C(t)||n.push(t),e(t)})),n}function V(t,e){e=e||m.fail;for(var n=[];t&&!e(t);)n.push(t),t=t.nextSibling;return n}function q(t,e){var n=e.nextSibling,o=e.parentNode;return n?o.insertBefore(t,n):o.appendChild(t),t}function _(t,n){return e().each(n,(function(e,n){t.appendChild(n)})),t}function G(t){return 0===t.offset}function Y(t){return t.offset===O(t.node)}function Z(t){return G(t)||Y(t)}function Q(t,e){for(;t&&t!==e;){if(0!==J(t))return!1;t=t.parentNode}return!0}function X(t,e){if(!e)return!1;for(;t&&t!==e;){if(J(t)!==O(t.parentNode)-1)return!1;t=t.parentNode}return!0}function J(t){for(var e=0;t=t.previousSibling;)e+=1;return e}function tt(t){return!!(t&&t.childNodes&&t.childNodes.length)}function et(t,e){var n,o;if(0===t.offset){if(C(t.node))return null;n=t.node.parentNode,o=J(t.node)}else tt(t.node)?o=O(n=t.node.childNodes[t.offset-1]):(n=t.node,o=e?0:t.offset-1);return{node:n,offset:o}}function nt(t,e){var n,o;if(O(t.node)===t.offset){if(C(t.node))return null;var i=it(t.node);i?(n=i,o=0):(n=t.node.parentNode,o=J(t.node)+1)}else tt(t.node)?(n=t.node.childNodes[t.offset],o=0):(n=t.node,o=e?O(t.node):t.offset+1);return{node:n,offset:o}}function ot(t,e){var n,o=0;if(U(t.node))return null===t.node?null:{node:n=t.node.nextSibling,offset:o=0};if(O(t.node)===t.offset){if(C(t.node))return null;n=t.node.parentNode,o=J(t.node)+1,C(n)&&(n=t.node.nextSibling,o=0)}else if(tt(t.node)){if(o=0,U(n=t.node.childNodes[t.offset]))return U(t.node.nextSibling)?null:{node:t.node.nextSibling,offset:o}}else if(n=t.node,o=e?O(t.node):t.offset+1,U(n))return null;return{node:n,offset:o}}function it(t){if(t.nextSibling&&t.parent===t.nextSibling.parent)return S(t.nextSibling)?t.nextSibling:it(t.nextSibling)}function rt(t,e){return t.node===e.node&&t.offset===e.offset}function at(t,e){var n=e&&e.isSkipPaddingBlankHTML,o=e&&e.isNotSplitEdgePoint,i=e&&e.isDiscardEmptySplits;if(i&&(n=!0),Z(t)&&(S(t.node)||o)){if(G(t))return t.node;if(Y(t))return t.node.nextSibling}if(S(t.node))return t.node.splitText(t.offset);var r=t.node.childNodes[t.offset],a=q(t.node.cloneNode(!1),t.node);return _(a,V(r)),n||(j(t.node),j(a)),i&&(U(t.node)&&ct(t.node),U(a))?(ct(a),t.node.nextSibling):a}function st(t,e,n){var o=K(e.node,m.eq(t));return o.length?1===o.length?at(e,n):o.reduce((function(t,o){return t===e.node&&(t=at(e,n)),at({node:o,offset:t?J(t):O(o)},n)})):null}function lt(t){return document.createElement(t)}function ct(t,e){if(t&&t.parentNode){if(t.removeNode)return t.removeNode(e);var n=t.parentNode;if(!e){for(var o=[],i=0,r=t.childNodes.length;i<r;i++)o.push(t.childNodes[i]);for(var a=0,s=o.length;a<s;a++)n.insertBefore(o[a],t)}n.removeChild(t)}}var ut=x("TEXTAREA");function dt(t,e){var n=ut(t[0])?t.val():t.html();return e?n.replace(/[\n\r]/g,""):n}const ht={NBSP_CHAR:w,ZERO_WIDTH_NBSP_CHAR:"\ufeff",blank:M,emptyPara:"<p>".concat(M,"</p>"),makePredByNodeName:x,isEditable:C,isControlSizing:function(t){return t&&e()(t).hasClass("note-control-sizing")},isText:S,isElement:function(t){return t&&1===t.nodeType},isVoid:T,isPara:E,isPurePara:function(t){return E(t)&&!$(t)},isHeading:function(t){return t&&/^H[1-7]/.test(t.nodeName.toUpperCase())},isInline:R,isBlock:m.not(R),isBodyInline:function(t){return R(t)&&!W(t,E)},isBody:B,isParaInline:function(t){return R(t)&&!!W(t,E)},isPre:I,isList:L,isTable:N,isData:P,isCell:F,isBlockquote:D,isBodyContainer:H,isAnchor:z,isDiv:x("DIV"),isLi:$,isBR:x("BR"),isSpan:x("SPAN"),isB:x("B"),isU:x("U"),isS:x("S"),isI:x("I"),isImg:x("IMG"),isTextarea:ut,deepestChildIsEmpty:function(t){do{if(null===t.firstElementChild||""===t.firstElementChild.innerHTML)break}while(t=t.firstElementChild);return U(t)},isEmpty:U,isEmptyAnchor:m.and(z,U),isClosestSibling:function(t,e){return t.nextSibling===e||t.previousSibling===e},withClosestSiblings:function(t,e){e=e||m.ok;var n=[];return t.previousSibling&&e(t.previousSibling)&&n.push(t.previousSibling),n.push(t),t.nextSibling&&e(t.nextSibling)&&n.push(t.nextSibling),n},nodeLength:O,isLeftEdgePoint:G,isRightEdgePoint:Y,isEdgePoint:Z,isLeftEdgeOf:Q,isRightEdgeOf:X,isLeftEdgePointOf:function(t,e){return G(t)&&Q(t.node,e)},isRightEdgePointOf:function(t,e){return Y(t)&&X(t.node,e)},prevPoint:et,nextPoint:nt,nextPointWithEmptyNode:ot,isSamePoint:rt,isVisiblePoint:function(t){if(S(t.node)||!tt(t.node)||U(t.node))return!0;var e=t.node.childNodes[t.offset-1],n=t.node.childNodes[t.offset];return!((e&&!T(e)||n&&!T(n))&&!N(n))},prevPointUntil:function(t,e){for(;t;){if(e(t))return t;t=et(t)}return null},nextPointUntil:function(t,e){for(;t;){if(e(t))return t;t=nt(t)}return null},isCharPoint:function(t){if(!S(t.node))return!1;var e=t.node.nodeValue.charAt(t.offset-1);return e&&" "!==e&&e!==w},isSpacePoint:function(t){if(!S(t.node))return!1;var e=t.node.nodeValue.charAt(t.offset-1);return" "===e||e===w},walkPoint:function(t,e,n,o){for(var i=t;i&&(n(i),!rt(i,e));){i=ot(i,o&&t.node!==i.node&&e.node!==i.node)}},ancestor:W,singleChildAncestor:function(t,e){for(t=t.parentNode;t&&1===O(t);){if(e(t))return t;if(C(t))break;t=t.parentNode}return null},listAncestor:K,lastAncestor:function(t,e){var n=K(t);return k.last(n.filter(e))},listNext:V,listPrev:function(t,e){e=e||m.fail;for(var n=[];t&&!e(t);)n.push(t),t=t.previousSibling;return n},listDescendant:function(t,e){var n=[];return e=e||m.ok,function o(i){t!==i&&e(i)&&n.push(i);for(var r=0,a=i.childNodes.length;r<a;r++)o(i.childNodes[r])}(t),n},commonAncestor:function(t,e){for(var n=K(t),o=e;o;o=o.parentNode)if(n.indexOf(o)>-1)return o;return null},wrap:function(t,n){var o=t.parentNode,i=e()("<"+n+">")[0];return o.insertBefore(i,t),i.appendChild(t),i},insertAfter:q,appendChildNodes:_,position:J,hasChildren:tt,makeOffsetPath:function(t,e){return K(e,m.eq(t)).map(J).reverse()},fromOffsetPath:function(t,e){for(var n=t,o=0,i=e.length;o<i;o++)n=n.childNodes.length<=e[o]?n.childNodes[n.childNodes.length-1]:n.childNodes[e[o]];return n},splitTree:st,splitPoint:function(t,e){var n,o,i=e?E:H,r=K(t.node,i),a=k.last(r)||t.node;i(a)?(n=r[r.length-2],o=a):o=(n=a).parentNode;var s=n&&st(n,t,{isSkipPaddingBlankHTML:e,isNotSplitEdgePoint:e});return s||o!==t.node||(s=t.node.childNodes[t.offset]),{rightNode:s,container:o}},create:lt,createText:function(t){return document.createTextNode(t)},remove:ct,removeWhile:function(t,e){for(;t&&!C(t)&&e(t);){var n=t.parentNode;ct(t),t=n}},replace:function(t,e){if(t.nodeName.toUpperCase()===e.toUpperCase())return t;var n=lt(e);return t.style.cssText&&(n.style.cssText=t.style.cssText),_(n,k.from(t.childNodes)),q(n,t),ct(t),n},html:function(t,e){var n=dt(t);if(e){n=(n=n.replace(/<(\/?)(\b(?!!)[^>\s]*)(.*?)(\s*\/?>)/g,(function(t,e,n){n=n.toUpperCase();var o=/^DIV|^TD|^TH|^P|^LI|^H[1-7]/.test(n)&&!!e,i=/^BLOCKQUOTE|^TABLE|^TBODY|^TR|^HR|^UL|^OL/.test(n);return t+(o||i?"\n":"")}))).trim()}return n},value:dt,posFromPlaceholder:function(t){var n=e()(t),o=n.offset(),i=n.outerHeight(!0);return{left:o.left,top:o.top+i}},attachEvents:function(t,e){Object.keys(e).forEach((function(n){t.on(n,e[n])}))},detachEvents:function(t,e){Object.keys(e).forEach((function(n){t.off(n,e[n])}))},isCustomStyleTag:function(t){return t&&!S(t)&&k.contains(t.classList,"note-styletag")}};function ft(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var pt=function(){function t(n,o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$note=n,this.memos={},this.modules={},this.layoutInfo={},this.options=e().extend(!0,{},o),e().summernote.ui=e().summernote.ui_template(this.options),this.ui=e().summernote.ui,this.initialize()}var n,o,i;return n=t,o=[{key:"initialize",value:function(){return this.layoutInfo=this.ui.createLayout(this.$note),this._initialize(),this.$note.hide(),this}},{key:"destroy",value:function(){this._destroy(),this.$note.removeData("summernote"),this.ui.removeLayout(this.$note,this.layoutInfo)}},{key:"reset",value:function(){var t=this.isDisabled();this.code(ht.emptyPara),this._destroy(),this._initialize(),t&&this.disable()}},{key:"_initialize",value:function(){var t=this;this.options.id=m.uniqueId(e().now()),this.options.container=this.options.container||this.layoutInfo.editor;var n=e().extend({},this.options.buttons);Object.keys(n).forEach((function(e){t.memo("button."+e,n[e])}));var o=e().extend({},this.options.modules,e().summernote.plugins||{});Object.keys(o).forEach((function(e){t.module(e,o[e],!0)})),Object.keys(this.modules).forEach((function(e){t.initializeModule(e)}))}},{key:"_destroy",value:function(){var t=this;Object.keys(this.modules).reverse().forEach((function(e){t.removeModule(e)})),Object.keys(this.memos).forEach((function(e){t.removeMemo(e)})),this.triggerEvent("destroy",this)}},{key:"code",value:function(t){var e=this.invoke("codeview.isActivated");if(void 0===t)return this.invoke("codeview.sync"),e?this.layoutInfo.codable.val():this.layoutInfo.editable.html();e?this.invoke("codeview.sync",t):this.layoutInfo.editable.html(t),this.$note.val(t),this.triggerEvent("change",t,this.layoutInfo.editable)}},{key:"isDisabled",value:function(){return"false"===this.layoutInfo.editable.attr("contenteditable")}},{key:"enable",value:function(){this.layoutInfo.editable.attr("contenteditable",!0),this.invoke("toolbar.activate",!0),this.triggerEvent("disable",!1),this.options.editing=!0}},{key:"disable",value:function(){this.invoke("codeview.isActivated")&&this.invoke("codeview.deactivate"),this.layoutInfo.editable.attr("contenteditable",!1),this.options.editing=!1,this.invoke("toolbar.deactivate",!0),this.triggerEvent("disable",!0)}},{key:"triggerEvent",value:function(){var t=k.head(arguments),e=k.tail(k.from(arguments)),n=this.options.callbacks[m.namespaceToCamel(t,"on")];n&&n.apply(this.$note[0],e),this.$note.trigger("summernote."+t,e)}},{key:"initializeModule",value:function(t){var e=this.modules[t];e.shouldInitialize=e.shouldInitialize||m.ok,e.shouldInitialize()&&(e.initialize&&e.initialize(),e.events&&ht.attachEvents(this.$note,e.events))}},{key:"module",value:function(t,e,n){if(1===arguments.length)return this.modules[t];this.modules[t]=new e(this),n||this.initializeModule(t)}},{key:"removeModule",value:function(t){var e=this.modules[t];e.shouldInitialize()&&(e.events&&ht.detachEvents(this.$note,e.events),e.destroy&&e.destroy()),delete this.modules[t]}},{key:"memo",value:function(t,e){if(1===arguments.length)return this.memos[t];this.memos[t]=e}},{key:"removeMemo",value:function(t){this.memos[t]&&this.memos[t].destroy&&this.memos[t].destroy(),delete this.memos[t]}},{key:"createInvokeHandlerAndUpdateState",value:function(t,e){var n=this;return function(o){n.createInvokeHandler(t,e)(o),n.invoke("buttons.updateCurrentStyle")}}},{key:"createInvokeHandler",value:function(t,n){var o=this;return function(i){i.preventDefault();var r=e()(i.target);o.invoke(t,n||r.closest("[data-value]").data("value"),r)}}},{key:"invoke",value:function(){var t=k.head(arguments),e=k.tail(k.from(arguments)),n=t.split("."),o=n.length>1,i=o&&k.head(n),r=o?k.last(n):k.head(n),a=this.modules[i||"editor"];return!i&&this[r]?this[r].apply(this,e):a&&a[r]&&a.shouldInitialize()?a[r].apply(a,e):void 0}}],o&&ft(n.prototype,o),i&&ft(n,i),t}();function mt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}function vt(t,e){var n,o,i=t.parentElement(),r=document.body.createTextRange(),a=k.from(i.childNodes);for(n=0;n<a.length;n++)if(!ht.isText(a[n])){if(r.moveToElementText(a[n]),r.compareEndPoints("StartToStart",t)>=0)break;o=a[n]}if(0!==n&&ht.isText(a[n-1])){var s=document.body.createTextRange(),l=null;s.moveToElementText(o||i),s.collapse(!o),l=o?o.nextSibling:i.firstChild;var c=t.duplicate();c.setEndPoint("StartToStart",s);for(var u=c.text.replace(/[\r\n]/g,"").length;u>l.nodeValue.length&&l.nextSibling;)u-=l.nodeValue.length,l=l.nextSibling;l.nodeValue;e&&l.nextSibling&&ht.isText(l.nextSibling)&&u===l.nodeValue.length&&(u-=l.nodeValue.length,l=l.nextSibling),i=l,n=u}return{cont:i,offset:n}}function gt(t){var e=document.body.createTextRange(),n=function t(e,n){var o,i;if(ht.isText(e)){var r=ht.listPrev(e,m.not(ht.isText)),a=k.last(r).previousSibling;o=a||e.parentNode,n+=k.sum(k.tail(r),ht.nodeLength),i=!a}else{if(o=e.childNodes[n]||e,ht.isText(o))return t(o,0);n=0,i=!1}return{node:o,collapseToStart:i,offset:n}}(t.node,t.offset);return e.moveToElementText(n.node),e.collapse(n.collapseToStart),e.moveStart("character",n.offset),e}e().fn.extend({summernote:function(){var t=e().type(k.head(arguments)),n="string"===t,o="object"===t,i=e().extend({},e().summernote.options,o?k.head(arguments):{});i.langInfo=e().extend(!0,{},e().summernote.lang["en-US"],e().summernote.lang[i.lang]),i.icons=e().extend(!0,{},e().summernote.options.icons,i.icons),i.tooltip="auto"===i.tooltip?!f.isSupportTouch:i.tooltip,this.each((function(t,n){var o=e()(n);if(!o.data("summernote")){var r=new pt(o,i);o.data("summernote",r),o.data("summernote").triggerEvent("init",r.layoutInfo)}}));var r=this.first();if(r.length){var a=r.data("summernote");if(n)return a.invoke.apply(a,k.from(arguments));i.focus&&a.invoke("editor.focus")}return this}});var bt=function(){function t(e,n,o,i){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.sc=e,this.so=n,this.ec=o,this.eo=i,this.isOnEditable=this.makeIsOn(ht.isEditable),this.isOnList=this.makeIsOn(ht.isList),this.isOnAnchor=this.makeIsOn(ht.isAnchor),this.isOnCell=this.makeIsOn(ht.isCell),this.isOnData=this.makeIsOn(ht.isData)}var n,o,i;return n=t,o=[{key:"nativeRange",value:function(){if(f.isW3CRangeSupport){var t=document.createRange();return t.setStart(this.sc,this.so),t.setEnd(this.ec,this.eo),t}var e=gt({node:this.sc,offset:this.so});return e.setEndPoint("EndToEnd",gt({node:this.ec,offset:this.eo})),e}},{key:"getPoints",value:function(){return{sc:this.sc,so:this.so,ec:this.ec,eo:this.eo}}},{key:"getStartPoint",value:function(){return{node:this.sc,offset:this.so}}},{key:"getEndPoint",value:function(){return{node:this.ec,offset:this.eo}}},{key:"select",value:function(){var t=this.nativeRange();if(f.isW3CRangeSupport){var e=document.getSelection();e.rangeCount>0&&e.removeAllRanges(),e.addRange(t)}else t.select();return this}},{key:"scrollIntoView",value:function(t){var n=e()(t).height();return t.scrollTop+n<this.sc.offsetTop&&(t.scrollTop+=Math.abs(t.scrollTop+n-this.sc.offsetTop)),this}},{key:"normalize",value:function(){var e=function(t,e){if(!t)return t;if(ht.isVisiblePoint(t)&&(!ht.isEdgePoint(t)||ht.isRightEdgePoint(t)&&!e||ht.isLeftEdgePoint(t)&&e||ht.isRightEdgePoint(t)&&e&&ht.isVoid(t.node.nextSibling)||ht.isLeftEdgePoint(t)&&!e&&ht.isVoid(t.node.previousSibling)||ht.isBlock(t.node)&&ht.isEmpty(t.node)))return t;var n=ht.ancestor(t.node,ht.isBlock),o=!1;if(!o){var i=ht.prevPoint(t)||{node:null};o=(ht.isLeftEdgePointOf(t,n)||ht.isVoid(i.node))&&!e}var r=!1;if(!r){var a=ht.nextPoint(t)||{node:null};r=(ht.isRightEdgePointOf(t,n)||ht.isVoid(a.node))&&e}if(o||r){if(ht.isVisiblePoint(t))return t;e=!e}return(e?ht.nextPointUntil(ht.nextPoint(t),ht.isVisiblePoint):ht.prevPointUntil(ht.prevPoint(t),ht.isVisiblePoint))||t},n=e(this.getEndPoint(),!1),o=this.isCollapsed()?n:e(this.getStartPoint(),!0);return new t(o.node,o.offset,n.node,n.offset)}},{key:"nodes",value:function(t,e){t=t||m.ok;var n=e&&e.includeAncestor,o=e&&e.fullyContains,i=this.getStartPoint(),r=this.getEndPoint(),a=[],s=[];return ht.walkPoint(i,r,(function(e){var i;ht.isEditable(e.node)||(o?(ht.isLeftEdgePoint(e)&&s.push(e.node),ht.isRightEdgePoint(e)&&k.contains(s,e.node)&&(i=e.node)):i=n?ht.ancestor(e.node,t):e.node,i&&t(i)&&a.push(i))}),!0),k.unique(a)}},{key:"commonAncestor",value:function(){return ht.commonAncestor(this.sc,this.ec)}},{key:"expand",value:function(e){var n=ht.ancestor(this.sc,e),o=ht.ancestor(this.ec,e);if(!n&&!o)return new t(this.sc,this.so,this.ec,this.eo);var i=this.getPoints();return n&&(i.sc=n,i.so=0),o&&(i.ec=o,i.eo=ht.nodeLength(o)),new t(i.sc,i.so,i.ec,i.eo)}},{key:"collapse",value:function(e){return e?new t(this.sc,this.so,this.sc,this.so):new t(this.ec,this.eo,this.ec,this.eo)}},{key:"splitText",value:function(){var e=this.sc===this.ec,n=this.getPoints();return ht.isText(this.ec)&&!ht.isEdgePoint(this.getEndPoint())&&this.ec.splitText(this.eo),ht.isText(this.sc)&&!ht.isEdgePoint(this.getStartPoint())&&(n.sc=this.sc.splitText(this.so),n.so=0,e&&(n.ec=n.sc,n.eo=this.eo-this.so)),new t(n.sc,n.so,n.ec,n.eo)}},{key:"deleteContents",value:function(){if(this.isCollapsed())return this;var n=this.splitText(),o=n.nodes(null,{fullyContains:!0}),i=ht.prevPointUntil(n.getStartPoint(),(function(t){return!k.contains(o,t.node)})),r=[];return e().each(o,(function(t,e){var n=e.parentNode;i.node!==n&&1===ht.nodeLength(n)&&r.push(n),ht.remove(e,!1)})),e().each(r,(function(t,e){ht.remove(e,!1)})),new t(i.node,i.offset,i.node,i.offset).normalize()}},{key:"makeIsOn",value:function(t){return function(){var e=ht.ancestor(this.sc,t);return!!e&&e===ht.ancestor(this.ec,t)}}},{key:"isLeftEdgeOf",value:function(t){if(!ht.isLeftEdgePoint(this.getStartPoint()))return!1;var e=ht.ancestor(this.sc,t);return e&&ht.isLeftEdgeOf(this.sc,e)}},{key:"isCollapsed",value:function(){return this.sc===this.ec&&this.so===this.eo}},{key:"wrapBodyInlineWithPara",value:function(){if(ht.isBodyContainer(this.sc)&&ht.isEmpty(this.sc))return this.sc.innerHTML=ht.emptyPara,new t(this.sc.firstChild,0,this.sc.firstChild,0);var e,n=this.normalize();if(ht.isParaInline(this.sc)||ht.isPara(this.sc))return n;if(ht.isInline(n.sc)){var o=ht.listAncestor(n.sc,m.not(ht.isInline));e=k.last(o),ht.isInline(e)||(e=o[o.length-2]||n.sc.childNodes[n.so])}else e=n.sc.childNodes[n.so>0?n.so-1:0];if(e){var i=ht.listPrev(e,ht.isParaInline).reverse();if((i=i.concat(ht.listNext(e.nextSibling,ht.isParaInline))).length){var r=ht.wrap(k.head(i),"p");ht.appendChildNodes(r,k.tail(i))}}return this.normalize()}},{key:"insertNode",value:function(t){var e=this;(ht.isText(t)||ht.isInline(t))&&(e=this.wrapBodyInlineWithPara().deleteContents());var n=ht.splitPoint(e.getStartPoint(),ht.isInline(t));return n.rightNode?(n.rightNode.parentNode.insertBefore(t,n.rightNode),ht.isEmpty(n.rightNode)&&ht.isPara(t)&&n.rightNode.parentNode.removeChild(n.rightNode)):n.container.appendChild(t),t}},{key:"pasteHTML",value:function(t){t=e().trim(t);var n=e()("<div></div>").html(t)[0],o=k.from(n.childNodes),i=this,r=!1;return i.so>=0&&(o=o.reverse(),r=!0),o=o.map((function(t){return i.insertNode(t)})),r&&(o=o.reverse()),o}},{key:"toString",value:function(){var t=this.nativeRange();return f.isW3CRangeSupport?t.toString():t.text}},{key:"getWordRange",value:function(e){var n=this.getEndPoint();if(!ht.isCharPoint(n))return this;var o=ht.prevPointUntil(n,(function(t){return!ht.isCharPoint(t)}));return e&&(n=ht.nextPointUntil(n,(function(t){return!ht.isCharPoint(t)}))),new t(o.node,o.offset,n.node,n.offset)}},{key:"getWordsRange",value:function(e){var n=this.getEndPoint(),o=function(t){return!ht.isCharPoint(t)&&!ht.isSpacePoint(t)};if(o(n))return this;var i=ht.prevPointUntil(n,o);return e&&(n=ht.nextPointUntil(n,o)),new t(i.node,i.offset,n.node,n.offset)}},{key:"getWordsMatchRange",value:function(e){var n=this.getEndPoint(),o=ht.prevPointUntil(n,(function(o){if(!ht.isCharPoint(o)&&!ht.isSpacePoint(o))return!0;var i=new t(o.node,o.offset,n.node,n.offset),r=e.exec(i.toString());return r&&0===r.index})),i=new t(o.node,o.offset,n.node,n.offset),r=i.toString(),a=e.exec(r);return a&&a[0].length===r.length?i:null}},{key:"bookmark",value:function(t){return{s:{path:ht.makeOffsetPath(t,this.sc),offset:this.so},e:{path:ht.makeOffsetPath(t,this.ec),offset:this.eo}}}},{key:"paraBookmark",value:function(t){return{s:{path:k.tail(ht.makeOffsetPath(k.head(t),this.sc)),offset:this.so},e:{path:k.tail(ht.makeOffsetPath(k.last(t),this.ec)),offset:this.eo}}}},{key:"getClientRects",value:function(){return this.nativeRange().getClientRects()}}],o&&mt(n.prototype,o),i&&mt(n,i),t}();const yt={create:function(t,e,n,o){if(4===arguments.length)return new bt(t,e,n,o);if(2===arguments.length)return new bt(t,e,n=t,o=e);var i=this.createFromSelection();if(!i&&1===arguments.length){var r=arguments[0];return ht.isEditable(r)&&(r=r.lastChild),this.createFromBodyElement(r,ht.emptyPara===arguments[0].innerHTML)}return i},createFromBodyElement:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=this.createFromNode(t);return n.collapse(e)},createFromSelection:function(){var t,e,n,o;if(f.isW3CRangeSupport){var i=document.getSelection();if(!i||0===i.rangeCount)return null;if(ht.isBody(i.anchorNode))return null;var r=i.getRangeAt(0);t=r.startContainer,e=r.startOffset,n=r.endContainer,o=r.endOffset}else{var a=document.selection.createRange(),s=a.duplicate();s.collapse(!1);var l=a;l.collapse(!0);var c=vt(l,!0),u=vt(s,!1);ht.isText(c.node)&&ht.isLeftEdgePoint(c)&&ht.isTextNode(u.node)&&ht.isRightEdgePoint(u)&&u.node.nextSibling===c.node&&(c=u),t=c.cont,e=c.offset,n=u.cont,o=u.offset}return new bt(t,e,n,o)},createFromNode:function(t){var e=t,n=0,o=t,i=ht.nodeLength(o);return ht.isVoid(e)&&(n=ht.listPrev(e).length-1,e=e.parentNode),ht.isBR(o)?(i=ht.listPrev(o).length-1,o=o.parentNode):ht.isVoid(o)&&(i=ht.listPrev(o).length,o=o.parentNode),this.create(e,n,o,i)},createFromNodeBefore:function(t){return this.createFromNode(t).collapse(!0)},createFromNodeAfter:function(t){return this.createFromNode(t).collapse()},createFromBookmark:function(t,e){var n=ht.fromOffsetPath(t,e.s.path),o=e.s.offset,i=ht.fromOffsetPath(t,e.e.path),r=e.e.offset;return new bt(n,o,i,r)},createFromParaBookmark:function(t,e){var n=t.s.offset,o=t.e.offset,i=ht.fromOffsetPath(k.head(e),t.s.path),r=ht.fromOffsetPath(k.last(e),t.e.path);return new bt(i,n,r,o)}};var kt={BACKSPACE:8,TAB:9,ENTER:13,ESCAPE:27,SPACE:32,DELETE:46,LEFT:37,UP:38,RIGHT:39,DOWN:40,NUM0:48,NUM1:49,NUM2:50,NUM3:51,NUM4:52,NUM5:53,NUM6:54,NUM7:55,NUM8:56,B:66,E:69,I:73,J:74,K:75,L:76,R:82,S:83,U:85,V:86,Y:89,Z:90,SLASH:191,LEFTBRACKET:219,BACKSLASH:220,RIGHTBRACKET:221,HOME:36,END:35,PAGEUP:33,PAGEDOWN:34};const wt={isEdit:function(t){return k.contains([kt.BACKSPACE,kt.TAB,kt.ENTER,kt.SPACE,kt.DELETE],t)},isMove:function(t){return k.contains([kt.LEFT,kt.UP,kt.RIGHT,kt.DOWN],t)},isNavigation:function(t){return k.contains([kt.HOME,kt.END,kt.PAGEUP,kt.PAGEDOWN],t)},nameFromCode:m.invertObject(kt),code:kt};function Ct(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var xt=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.stack=[],this.stackOffset=-1,this.context=e,this.$editable=e.layoutInfo.editable,this.editable=this.$editable[0]}var e,n,o;return e=t,(n=[{key:"makeSnapshot",value:function(){var t=yt.create(this.editable);return{contents:this.$editable.html(),bookmark:t&&t.isOnEditable()?t.bookmark(this.editable):{s:{path:[],offset:0},e:{path:[],offset:0}}}}},{key:"applySnapshot",value:function(t){null!==t.contents&&this.$editable.html(t.contents),null!==t.bookmark&&yt.createFromBookmark(this.editable,t.bookmark).select()}},{key:"rewind",value:function(){this.$editable.html()!==this.stack[this.stackOffset].contents&&this.recordUndo(),this.stackOffset=0,this.applySnapshot(this.stack[this.stackOffset])}},{key:"commit",value:function(){this.stack=[],this.stackOffset=-1,this.recordUndo()}},{key:"reset",value:function(){this.stack=[],this.stackOffset=-1,this.$editable.html(""),this.recordUndo()}},{key:"undo",value:function(){this.$editable.html()!==this.stack[this.stackOffset].contents&&this.recordUndo(),this.stackOffset>0&&(this.stackOffset--,this.applySnapshot(this.stack[this.stackOffset]))}},{key:"redo",value:function(){this.stack.length-1>this.stackOffset&&(this.stackOffset++,this.applySnapshot(this.stack[this.stackOffset]))}},{key:"recordUndo",value:function(){this.stackOffset++,this.stack.length>this.stackOffset&&(this.stack=this.stack.slice(0,this.stackOffset)),this.stack.push(this.makeSnapshot()),this.stack.length>this.context.options.historyLimit&&(this.stack.shift(),this.stackOffset-=1)}}])&&Ct(e.prototype,n),o&&Ct(e,o),t}();function St(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Tt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var n,o,i;return n=t,o=[{key:"jQueryCSS",value:function(t,n){var o={};return e().each(n,(function(e,n){o[n]=t.css(n)})),o}},{key:"fromNode",value:function(t){var e=this.jQueryCSS(t,["font-family","font-size","text-align","list-style-type","line-height"])||{},n=t[0].style.fontSize||e["font-size"];return e["font-size"]=parseInt(n,10),e["font-size-unit"]=n.match(/[a-z%]+$/),e}},{key:"stylePara",value:function(t,n){e().each(t.nodes(ht.isPara,{includeAncestor:!0}),(function(t,o){e()(o).css(n)}))}},{key:"styleNodes",value:function(t,n){t=t.splitText();var o=n&&n.nodeName||"SPAN",i=!(!n||!n.expandClosestSibling),r=!(!n||!n.onlyPartialContains);if(t.isCollapsed())return[t.insertNode(ht.create(o))];var a=ht.makePredByNodeName(o),s=t.nodes(ht.isText,{fullyContains:!0}).map((function(t){return ht.singleChildAncestor(t,a)||ht.wrap(t,o)}));if(i){if(r){var l=t.nodes();a=m.and(a,(function(t){return k.contains(l,t)}))}return s.map((function(t){var n=ht.withClosestSiblings(t,a),o=k.head(n),i=k.tail(n);return e().each(i,(function(t,e){ht.appendChildNodes(o,e.childNodes),ht.remove(e)})),k.head(n)}))}return s}},{key:"current",value:function(t){var n=e()(ht.isElement(t.sc)?t.sc:t.sc.parentNode),o=this.fromNode(n);try{o=e().extend(o,{"font-bold":document.queryCommandState("bold")?"bold":"normal","font-italic":document.queryCommandState("italic")?"italic":"normal","font-underline":document.queryCommandState("underline")?"underline":"normal","font-subscript":document.queryCommandState("subscript")?"subscript":"normal","font-superscript":document.queryCommandState("superscript")?"superscript":"normal","font-strikethrough":document.queryCommandState("strikethrough")?"strikethrough":"normal","font-family":document.queryCommandValue("fontname")||o["font-family"]})}catch(t){}if(t.isOnList()){var i=["circle","disc","disc-leading-zero","square"].indexOf(o["list-style-type"])>-1;o["list-style"]=i?"unordered":"ordered"}else o["list-style"]="none";var r=ht.ancestor(t.sc,ht.isPara);if(r&&r.style["line-height"])o["line-height"]=r.style.lineHeight;else{var a=parseInt(o["line-height"],10)/parseInt(o["font-size"],10);o["line-height"]=a.toFixed(1)}return o.anchor=t.isOnAnchor()&&ht.ancestor(t.sc,ht.isAnchor),o.ancestors=ht.listAncestor(t.sc,ht.isEditable),o.range=t,o}}],o&&St(n.prototype,o),i&&St(n,i),t}();function Et(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var It=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var n,o,i;return n=t,o=[{key:"insertOrderedList",value:function(t){this.toggleList("OL",t)}},{key:"insertUnorderedList",value:function(t){this.toggleList("UL",t)}},{key:"indent",value:function(t){var n=this,o=yt.create(t).wrapBodyInlineWithPara(),i=o.nodes(ht.isPara,{includeAncestor:!0}),r=k.clusterBy(i,m.peq2("parentNode"));e().each(r,(function(t,o){var i=k.head(o);if(ht.isLi(i)){var r=n.findList(i.previousSibling);r?o.map((function(t){return r.appendChild(t)})):(n.wrapList(o,i.parentNode.nodeName),o.map((function(t){return t.parentNode})).map((function(t){return n.appendToPrevious(t)})))}else e().each(o,(function(t,n){e()(n).css("marginLeft",(function(t,e){return(parseInt(e,10)||0)+25}))}))})),o.select()}},{key:"outdent",value:function(t){var n=this,o=yt.create(t).wrapBodyInlineWithPara(),i=o.nodes(ht.isPara,{includeAncestor:!0}),r=k.clusterBy(i,m.peq2("parentNode"));e().each(r,(function(t,o){var i=k.head(o);ht.isLi(i)?n.releaseList([o]):e().each(o,(function(t,n){e()(n).css("marginLeft",(function(t,e){return(e=parseInt(e,10)||0)>25?e-25:""}))}))})),o.select()}},{key:"toggleList",value:function(t,n){var o=this,i=yt.create(n).wrapBodyInlineWithPara(),r=i.nodes(ht.isPara,{includeAncestor:!0}),a=i.paraBookmark(r),s=k.clusterBy(r,m.peq2("parentNode"));if(k.find(r,ht.isPurePara)){var l=[];e().each(s,(function(e,n){l=l.concat(o.wrapList(n,t))})),r=l}else{var c=i.nodes(ht.isList,{includeAncestor:!0}).filter((function(n){return!e().nodeName(n,t)}));c.length?e().each(c,(function(e,n){ht.replace(n,t)})):r=this.releaseList(s,!0)}yt.createFromParaBookmark(a,r).select()}},{key:"wrapList",value:function(t,e){var n=k.head(t),o=k.last(t),i=ht.isList(n.previousSibling)&&n.previousSibling,r=ht.isList(o.nextSibling)&&o.nextSibling,a=i||ht.insertAfter(ht.create(e||"UL"),o);return t=t.map((function(t){return ht.isPurePara(t)?ht.replace(t,"LI"):t})),ht.appendChildNodes(a,t),r&&(ht.appendChildNodes(a,k.from(r.childNodes)),ht.remove(r)),t}},{key:"releaseList",value:function(t,n){var o=this,i=[];return e().each(t,(function(t,r){var a=k.head(r),s=k.last(r),l=n?ht.lastAncestor(a,ht.isList):a.parentNode,c=l.parentNode;if("LI"===l.parentNode.nodeName)r.map((function(t){var e=o.findNextSiblings(t);c.nextSibling?c.parentNode.insertBefore(t,c.nextSibling):c.parentNode.appendChild(t),e.length&&(o.wrapList(e,l.nodeName),t.appendChild(e[0].parentNode))})),0===l.children.length&&c.removeChild(l),0===c.childNodes.length&&c.parentNode.removeChild(c);else{var u=l.childNodes.length>1?ht.splitTree(l,{node:s.parentNode,offset:ht.position(s)+1},{isSkipPaddingBlankHTML:!0}):null,d=ht.splitTree(l,{node:a.parentNode,offset:ht.position(a)},{isSkipPaddingBlankHTML:!0});r=n?ht.listDescendant(d,ht.isLi):k.from(d.childNodes).filter(ht.isLi),!n&&ht.isList(l.parentNode)||(r=r.map((function(t){return ht.replace(t,"P")}))),e().each(k.from(r).reverse(),(function(t,e){ht.insertAfter(e,l)}));var h=k.compact([l,d,u]);e().each(h,(function(t,n){var o=[n].concat(ht.listDescendant(n,ht.isList));e().each(o.reverse(),(function(t,e){ht.nodeLength(e)||ht.remove(e,!0)}))}))}i=i.concat(r)})),i}},{key:"appendToPrevious",value:function(t){return t.previousSibling?ht.appendChildNodes(t.previousSibling,[t]):this.wrapList([t],"LI")}},{key:"findList",value:function(t){return t?k.find(t.children,(function(t){return["OL","UL"].indexOf(t.nodeName)>-1})):null}},{key:"findNextSiblings",value:function(t){for(var e=[];t.nextSibling;)e.push(t.nextSibling),t=t.nextSibling;return e}}],o&&Et(n.prototype,o),i&&Et(n,i),t}();function $t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Nt=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.bullet=new It,this.options=e.options}var n,o,i;return n=t,o=[{key:"insertTab",value:function(t,e){var n=ht.createText(new Array(e+1).join(ht.NBSP_CHAR));(t=t.deleteContents()).insertNode(n,!0),(t=yt.create(n,e)).select()}},{key:"insertParagraph",value:function(t,n){n=(n=(n=n||yt.create(t)).deleteContents()).wrapBodyInlineWithPara();var o,i=ht.ancestor(n.sc,ht.isPara);if(i){if(ht.isLi(i)&&(ht.isEmpty(i)||ht.deepestChildIsEmpty(i)))return void this.bullet.toggleList(i.parentNode.nodeName);var r=null;if(1===this.options.blockquoteBreakingLevel?r=ht.ancestor(i,ht.isBlockquote):2===this.options.blockquoteBreakingLevel&&(r=ht.lastAncestor(i,ht.isBlockquote)),r){o=e()(ht.emptyPara)[0],ht.isRightEdgePoint(n.getStartPoint())&&ht.isBR(n.sc.nextSibling)&&e()(n.sc.nextSibling).remove();var a=ht.splitTree(r,n.getStartPoint(),{isDiscardEmptySplits:!0});a?a.parentNode.insertBefore(o,a):ht.insertAfter(o,r)}else{o=ht.splitTree(i,n.getStartPoint());var s=ht.listDescendant(i,ht.isEmptyAnchor);s=s.concat(ht.listDescendant(o,ht.isEmptyAnchor)),e().each(s,(function(t,e){ht.remove(e)})),(ht.isHeading(o)||ht.isPre(o)||ht.isCustomStyleTag(o))&&ht.isEmpty(o)&&(o=ht.replace(o,"p"))}}else{var l=n.sc.childNodes[n.so];o=e()(ht.emptyPara)[0],l?n.sc.insertBefore(o,l):n.sc.appendChild(o)}yt.create(o,0).normalize().select().scrollIntoView(t)}}],o&&$t(n.prototype,o),i&&$t(n,i),t}();function Pt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Rt=function t(e,n,o,i){var r={colPos:0,rowPos:0},a=[],s=[];function l(t,e,n,o,i,r,s){var l={baseRow:n,baseCell:o,isRowSpan:i,isColSpan:r,isVirtual:s};a[t]||(a[t]=[]),a[t][e]=l}function c(t,e,n,o){return{baseCell:t.baseCell,action:e,virtualTable:{rowIndex:n,cellIndex:o}}}function u(t,e){if(!a[t])return e;if(!a[t][e])return e;for(var n=e;a[t][n];)if(n++,!a[t][n])return n}function d(t,e){var n=u(t.rowIndex,e.cellIndex),o=e.colSpan>1,i=e.rowSpan>1,a=t.rowIndex===r.rowPos&&e.cellIndex===r.colPos;l(t.rowIndex,n,t,e,i,o,!1);var s=e.attributes.rowSpan?parseInt(e.attributes.rowSpan.value,10):0;if(s>1)for(var c=1;c<s;c++){var d=t.rowIndex+c;h(d,n,e,a),l(d,n,t,e,!0,o,!0)}var f=e.attributes.colSpan?parseInt(e.attributes.colSpan.value,10):0;if(f>1)for(var p=1;p<f;p++){var m=u(t.rowIndex,n+p);h(t.rowIndex,m,e,a),l(t.rowIndex,m,t,e,i,!0,!0)}}function h(t,e,n,o){t===r.rowPos&&r.colPos>=n.cellIndex&&n.cellIndex<=e&&!o&&r.colPos++}function f(e){switch(n){case t.where.Column:if(e.isColSpan)return t.resultAction.SubtractSpanCount;break;case t.where.Row:if(!e.isVirtual&&e.isRowSpan)return t.resultAction.AddCell;if(e.isRowSpan)return t.resultAction.SubtractSpanCount}return t.resultAction.RemoveCell}function p(e){switch(n){case t.where.Column:if(e.isColSpan)return t.resultAction.SumSpanCount;if(e.isRowSpan&&e.isVirtual)return t.resultAction.Ignore;break;case t.where.Row:if(e.isRowSpan)return t.resultAction.SumSpanCount;if(e.isColSpan&&e.isVirtual)return t.resultAction.Ignore}return t.resultAction.AddCell}this.getActionList=function(){for(var e=n===t.where.Row?r.rowPos:-1,i=n===t.where.Column?r.colPos:-1,l=0,u=!0;u;){var d=e>=0?e:l,h=i>=0?i:l,m=a[d];if(!m)return u=!1,s;var v=m[h];if(!v)return u=!1,s;var g=t.resultAction.Ignore;switch(o){case t.requestAction.Add:g=p(v);break;case t.requestAction.Delete:g=f(v)}s.push(c(v,g,d,h)),l++}return s},e&&e.tagName&&("td"===e.tagName.toLowerCase()||"th"===e.tagName.toLowerCase())&&(r.colPos=e.cellIndex,e.parentElement&&e.parentElement.tagName&&"tr"===e.parentElement.tagName.toLowerCase()&&(r.rowPos=e.parentElement.rowIndex)),function(){for(var t=i.rows,e=0;e<t.length;e++)for(var n=t[e].cells,o=0;o<n.length;o++)d(t[e],n[o])}()};Rt.where={Row:0,Column:1},Rt.requestAction={Add:0,Delete:1},Rt.resultAction={Ignore:0,SubtractSpanCount:1,RemoveCell:2,AddCell:3,SumSpanCount:4};var Lt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var n,o,i;return n=t,o=[{key:"tab",value:function(t,e){var n=ht.ancestor(t.commonAncestor(),ht.isCell),o=ht.ancestor(n,ht.isTable),i=ht.listDescendant(o,ht.isCell),r=k[e?"prev":"next"](i,n);r&&yt.create(r,0).select()}},{key:"addRow",value:function(t,n){for(var o=ht.ancestor(t.commonAncestor(),ht.isCell),i=e()(o).closest("tr"),r=this.recoverAttributes(i),a=e()("<tr"+r+"></tr>"),s=new Rt(o,Rt.where.Row,Rt.requestAction.Add,e()(i).closest("table")[0]).getActionList(),l=0;l<s.length;l++){var c=s[l],u=this.recoverAttributes(c.baseCell);switch(c.action){case Rt.resultAction.AddCell:a.append("<td"+u+">"+ht.blank+"</td>");break;case Rt.resultAction.SumSpanCount:if("top"===n&&(c.baseCell.parent?c.baseCell.closest("tr").rowIndex:0)<=i[0].rowIndex){var d=e()("<div></div>").append(e()("<td"+u+">"+ht.blank+"</td>").removeAttr("rowspan")).html();a.append(d);break}var h=parseInt(c.baseCell.rowSpan,10);h++,c.baseCell.setAttribute("rowSpan",h)}}if("top"===n)i.before(a);else{if(o.rowSpan>1){var f=i[0].rowIndex+(o.rowSpan-2);return void e()(e()(i).parent().find("tr")[f]).after(e()(a))}i.after(a)}}},{key:"addCol",value:function(t,n){var o=ht.ancestor(t.commonAncestor(),ht.isCell),i=e()(o).closest("tr");e()(i).siblings().push(i);for(var r=new Rt(o,Rt.where.Column,Rt.requestAction.Add,e()(i).closest("table")[0]).getActionList(),a=0;a<r.length;a++){var s=r[a],l=this.recoverAttributes(s.baseCell);switch(s.action){case Rt.resultAction.AddCell:"right"===n?e()(s.baseCell).after("<td"+l+">"+ht.blank+"</td>"):e()(s.baseCell).before("<td"+l+">"+ht.blank+"</td>");break;case Rt.resultAction.SumSpanCount:if("right"===n){var c=parseInt(s.baseCell.colSpan,10);c++,s.baseCell.setAttribute("colSpan",c)}else e()(s.baseCell).before("<td"+l+">"+ht.blank+"</td>")}}}},{key:"recoverAttributes",value:function(t){var e="";if(!t)return e;for(var n=t.attributes||[],o=0;o<n.length;o++)"id"!==n[o].name.toLowerCase()&&n[o].specified&&(e+=" "+n[o].name+"='"+n[o].value+"'");return e}},{key:"deleteRow",value:function(t){for(var n=ht.ancestor(t.commonAncestor(),ht.isCell),o=e()(n).closest("tr"),i=o.children("td, th").index(e()(n)),r=o[0].rowIndex,a=new Rt(n,Rt.where.Row,Rt.requestAction.Delete,e()(o).closest("table")[0]).getActionList(),s=0;s<a.length;s++)if(a[s]){var l=a[s].baseCell,c=a[s].virtualTable,u=l.rowSpan&&l.rowSpan>1,d=u?parseInt(l.rowSpan,10):0;switch(a[s].action){case Rt.resultAction.Ignore:continue;case Rt.resultAction.AddCell:var h=o.next("tr")[0];if(!h)continue;var f=o[0].cells[i];u&&(d>2?(d--,h.insertBefore(f,h.cells[i]),h.cells[i].setAttribute("rowSpan",d),h.cells[i].innerHTML=""):2===d&&(h.insertBefore(f,h.cells[i]),h.cells[i].removeAttribute("rowSpan"),h.cells[i].innerHTML=""));continue;case Rt.resultAction.SubtractSpanCount:u&&(d>2?(d--,l.setAttribute("rowSpan",d),c.rowIndex!==r&&l.cellIndex===i&&(l.innerHTML="")):2===d&&(l.removeAttribute("rowSpan"),c.rowIndex!==r&&l.cellIndex===i&&(l.innerHTML="")));continue;case Rt.resultAction.RemoveCell:continue}}o.remove()}},{key:"deleteCol",value:function(t){for(var n=ht.ancestor(t.commonAncestor(),ht.isCell),o=e()(n).closest("tr"),i=o.children("td, th").index(e()(n)),r=new Rt(n,Rt.where.Column,Rt.requestAction.Delete,e()(o).closest("table")[0]).getActionList(),a=0;a<r.length;a++)if(r[a])switch(r[a].action){case Rt.resultAction.Ignore:continue;case Rt.resultAction.SubtractSpanCount:var s=r[a].baseCell;if(s.colSpan&&s.colSpan>1){var l=s.colSpan?parseInt(s.colSpan,10):0;l>2?(l--,s.setAttribute("colSpan",l),s.cellIndex===i&&(s.innerHTML="")):2===l&&(s.removeAttribute("colSpan"),s.cellIndex===i&&(s.innerHTML=""))}continue;case Rt.resultAction.RemoveCell:ht.remove(r[a].baseCell,!0);continue}}},{key:"createTable",value:function(t,n,o){for(var i,r=[],a=0;a<t;a++)r.push("<td>"+ht.blank+"</td>");i=r.join("");for(var s,l=[],c=0;c<n;c++)l.push("<tr>"+i+"</tr>");s=l.join("");var u=e()("<table>"+s+"</table>");return o&&o.tableClassName&&u.addClass(o.tableClassName),u[0]}},{key:"deleteTable",value:function(t){var n=ht.ancestor(t.commonAncestor(),ht.isCell);e()(n).closest("table").remove()}}],o&&Pt(n.prototype,o),i&&Pt(n,i),t}();function At(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Ft=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$note=n.layoutInfo.note,this.$editor=n.layoutInfo.editor,this.$editable=n.layoutInfo.editable,this.options=n.options,this.lang=this.options.langInfo,this.editable=this.$editable[0],this.lastRange=null,this.snapshot=null,this.style=new Tt,this.table=new Lt,this.typing=new Nt(n),this.bullet=new It,this.history=new xt(n),this.context.memo("help.escape",this.lang.help.escape),this.context.memo("help.undo",this.lang.help.undo),this.context.memo("help.redo",this.lang.help.redo),this.context.memo("help.tab",this.lang.help.tab),this.context.memo("help.untab",this.lang.help.untab),this.context.memo("help.insertParagraph",this.lang.help.insertParagraph),this.context.memo("help.insertOrderedList",this.lang.help.insertOrderedList),this.context.memo("help.insertUnorderedList",this.lang.help.insertUnorderedList),this.context.memo("help.indent",this.lang.help.indent),this.context.memo("help.outdent",this.lang.help.outdent),this.context.memo("help.formatPara",this.lang.help.formatPara),this.context.memo("help.insertHorizontalRule",this.lang.help.insertHorizontalRule),this.context.memo("help.fontName",this.lang.help.fontName);for(var i=["bold","italic","underline","strikethrough","superscript","subscript","justifyLeft","justifyCenter","justifyRight","justifyFull","formatBlock","removeFormat","backColor"],r=0,a=i.length;r<a;r++)this[i[r]]=function(t){return function(e){o.beforeCommand(),document.execCommand(t,!1,e),o.afterCommand(!0)}}(i[r]),this.context.memo("help."+i[r],this.lang.help[i[r]]);this.fontName=this.wrapCommand((function(t){return o.fontStyling("font-family",f.validFontName(t))})),this.fontSize=this.wrapCommand((function(t){var e=o.currentStyle()["font-size-unit"];return o.fontStyling("font-size",t+e)})),this.fontSizeUnit=this.wrapCommand((function(t){var e=o.currentStyle()["font-size"];return o.fontStyling("font-size",e+t)}));for(var s=1;s<=6;s++)this["formatH"+s]=function(t){return function(){o.formatBlock("H"+t)}}(s),this.context.memo("help.formatH"+s,this.lang.help["formatH"+s]);this.insertParagraph=this.wrapCommand((function(){o.typing.insertParagraph(o.editable)})),this.insertOrderedList=this.wrapCommand((function(){o.bullet.insertOrderedList(o.editable)})),this.insertUnorderedList=this.wrapCommand((function(){o.bullet.insertUnorderedList(o.editable)})),this.indent=this.wrapCommand((function(){o.bullet.indent(o.editable)})),this.outdent=this.wrapCommand((function(){o.bullet.outdent(o.editable)})),this.insertNode=this.wrapCommand((function(t){o.isLimited(e()(t).text().length)||(o.getLastRange().insertNode(t),o.setLastRange(yt.createFromNodeAfter(t).select()))})),this.insertText=this.wrapCommand((function(t){if(!o.isLimited(t.length)){var e=o.getLastRange().insertNode(ht.createText(t));o.setLastRange(yt.create(e,ht.nodeLength(e)).select())}})),this.pasteHTML=this.wrapCommand((function(t){if(!o.isLimited(t.length)){t=o.context.invoke("codeview.purify",t);var e=o.getLastRange().pasteHTML(t);o.setLastRange(yt.createFromNodeAfter(k.last(e)).select())}})),this.formatBlock=this.wrapCommand((function(t,e){var n=o.options.callbacks.onApplyCustomStyle;n?n.call(o,e,o.context,o.onFormatBlock):o.onFormatBlock(t,e)})),this.insertHorizontalRule=this.wrapCommand((function(){var t=o.getLastRange().insertNode(ht.create("HR"));t.nextSibling&&o.setLastRange(yt.create(t.nextSibling,0).normalize().select())})),this.lineHeight=this.wrapCommand((function(t){o.style.stylePara(o.getLastRange(),{lineHeight:t})})),this.createLink=this.wrapCommand((function(t){var n=t.url,i=t.text,r=t.isNewWindow,a=t.checkProtocol,s=t.range||o.getLastRange(),l=i.length-s.toString().length;if(!(l>0&&o.isLimited(l))){var c=s.toString()!==i;"string"==typeof n&&(n=n.trim()),o.options.onCreateLink?n=o.options.onCreateLink(n):a&&(n=/^([A-Za-z][A-Za-z0-9+-.]*\:|#|\/)/.test(n)?n:o.options.defaultProtocol+n);var u=[];if(c){var d=(s=s.deleteContents()).insertNode(e()("<A>"+i+"</A>")[0]);u.push(d)}else u=o.style.styleNodes(s,{nodeName:"A",expandClosestSibling:!0,onlyPartialContains:!0});e().each(u,(function(t,o){e()(o).attr("href",n),r?e()(o).attr("target","_blank"):e()(o).removeAttr("target")})),o.setLastRange(o.createRangeFromList(u).select())}})),this.color=this.wrapCommand((function(t){var e=t.foreColor,n=t.backColor;e&&document.execCommand("foreColor",!1,e),n&&document.execCommand("backColor",!1,n)})),this.foreColor=this.wrapCommand((function(t){document.execCommand("foreColor",!1,t)})),this.insertTable=this.wrapCommand((function(t){var e=t.split("x");o.getLastRange().deleteContents().insertNode(o.table.createTable(e[0],e[1],o.options))})),this.removeMedia=this.wrapCommand((function(){var t=e()(o.restoreTarget()).parent();t.closest("figure").length?t.closest("figure").remove():t=e()(o.restoreTarget()).detach(),o.context.triggerEvent("media.delete",t,o.$editable)})),this.floatMe=this.wrapCommand((function(t){var n=e()(o.restoreTarget());n.toggleClass("note-float-left","left"===t),n.toggleClass("note-float-right","right"===t),n.css("float","none"===t?"":t)})),this.resize=this.wrapCommand((function(t){var n=e()(o.restoreTarget());0===(t=parseFloat(t))?n.css("width",""):n.css({width:100*t+"%",height:""})}))}var n,o,i;return n=t,o=[{key:"initialize",value:function(){var t=this;this.$editable.on("keydown",(function(e){if(e.keyCode===wt.code.ENTER&&t.context.triggerEvent("enter",e),t.context.triggerEvent("keydown",e),t.snapshot=t.history.makeSnapshot(),t.hasKeyShortCut=!1,e.isDefaultPrevented()||(t.options.shortcuts?t.hasKeyShortCut=t.handleKeyMap(e):t.preventDefaultEditableShortCuts(e)),t.isLimited(1,e)){var n=t.getLastRange();if(n.eo-n.so==0)return!1}t.setLastRange(),t.options.recordEveryKeystroke&&!1===t.hasKeyShortCut&&t.history.recordUndo()})).on("keyup",(function(e){t.setLastRange(),t.context.triggerEvent("keyup",e)})).on("focus",(function(e){t.setLastRange(),t.context.triggerEvent("focus",e)})).on("blur",(function(e){t.context.triggerEvent("blur",e)})).on("mousedown",(function(e){t.context.triggerEvent("mousedown",e)})).on("mouseup",(function(e){t.setLastRange(),t.history.recordUndo(),t.context.triggerEvent("mouseup",e)})).on("scroll",(function(e){t.context.triggerEvent("scroll",e)})).on("paste",(function(e){t.setLastRange(),t.context.triggerEvent("paste",e)})).on("input",(function(){t.isLimited(0)&&t.snapshot&&t.history.applySnapshot(t.snapshot)})),this.$editable.attr("spellcheck",this.options.spellCheck),this.$editable.attr("autocorrect",this.options.spellCheck),this.options.disableGrammar&&this.$editable.attr("data-gramm",!1),this.$editable.html(ht.html(this.$note)||ht.emptyPara),this.$editable.on(f.inputEventName,m.debounce((function(){t.context.triggerEvent("change",t.$editable.html(),t.$editable)}),10)),this.$editable.on("focusin",(function(e){t.context.triggerEvent("focusin",e)})).on("focusout",(function(e){t.context.triggerEvent("focusout",e)})),this.options.airMode?this.options.overrideContextMenu&&this.$editor.on("contextmenu",(function(e){return t.context.triggerEvent("contextmenu",e),!1})):(this.options.width&&this.$editor.outerWidth(this.options.width),this.options.height&&this.$editable.outerHeight(this.options.height),this.options.maxHeight&&this.$editable.css("max-height",this.options.maxHeight),this.options.minHeight&&this.$editable.css("min-height",this.options.minHeight)),this.history.recordUndo(),this.setLastRange()}},{key:"destroy",value:function(){this.$editable.off()}},{key:"handleKeyMap",value:function(t){var e=this.options.keyMap[f.isMac?"mac":"pc"],n=[];t.metaKey&&n.push("CMD"),t.ctrlKey&&!t.altKey&&n.push("CTRL"),t.shiftKey&&n.push("SHIFT");var o=wt.nameFromCode[t.keyCode];o&&n.push(o);var i=e[n.join("+")];if("TAB"!==o||this.options.tabDisable)if(i){if(!1!==this.context.invoke(i))return t.preventDefault(),!0}else wt.isEdit(t.keyCode)&&this.afterCommand();else this.afterCommand();return!1}},{key:"preventDefaultEditableShortCuts",value:function(t){(t.ctrlKey||t.metaKey)&&k.contains([66,73,85],t.keyCode)&&t.preventDefault()}},{key:"isLimited",value:function(t,e){return t=t||0,(void 0===e||!(wt.isMove(e.keyCode)||wt.isNavigation(e.keyCode)||e.ctrlKey||e.metaKey||k.contains([wt.code.BACKSPACE,wt.code.DELETE],e.keyCode)))&&this.options.maxTextLength>0&&this.$editable.text().length+t>this.options.maxTextLength}},{key:"createRange",value:function(){return this.focus(),this.setLastRange(),this.getLastRange()}},{key:"createRangeFromList",value:function(t){var e=yt.createFromNodeBefore(k.head(t)).getStartPoint(),n=yt.createFromNodeAfter(k.last(t)).getEndPoint();return yt.create(e.node,e.offset,n.node,n.offset)}},{key:"setLastRange",value:function(t){t?this.lastRange=t:(this.lastRange=yt.create(this.editable),0===e()(this.lastRange.sc).closest(".note-editable").length&&(this.lastRange=yt.createFromBodyElement(this.editable)))}},{key:"getLastRange",value:function(){return this.lastRange||this.setLastRange(),this.lastRange}},{key:"saveRange",value:function(t){t&&this.getLastRange().collapse().select()}},{key:"restoreRange",value:function(){this.lastRange&&(this.lastRange.select(),this.focus())}},{key:"saveTarget",value:function(t){this.$editable.data("target",t)}},{key:"clearTarget",value:function(){this.$editable.removeData("target")}},{key:"restoreTarget",value:function(){return this.$editable.data("target")}},{key:"currentStyle",value:function(){var t=yt.create();return t&&(t=t.normalize()),t?this.style.current(t):this.style.fromNode(this.$editable)}},{key:"styleFromNode",value:function(t){return this.style.fromNode(t)}},{key:"undo",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.undo(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"commit",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.commit(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"redo",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.redo(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"beforeCommand",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),document.execCommand("styleWithCSS",!1,this.options.styleWithCSS),this.focus()}},{key:"afterCommand",value:function(t){this.normalizeContent(),this.history.recordUndo(),t||this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"tab",value:function(){var t=this.getLastRange();if(t.isCollapsed()&&t.isOnCell())this.table.tab(t);else{if(0===this.options.tabSize)return!1;this.isLimited(this.options.tabSize)||(this.beforeCommand(),this.typing.insertTab(t,this.options.tabSize),this.afterCommand())}}},{key:"untab",value:function(){var t=this.getLastRange();if(t.isCollapsed()&&t.isOnCell())this.table.tab(t,!0);else if(0===this.options.tabSize)return!1}},{key:"wrapCommand",value:function(t){return function(){this.beforeCommand(),t.apply(this,arguments),this.afterCommand()}}},{key:"insertImage",value:function(t,n){var o,i=this;return(o=t,e().Deferred((function(t){var n=e()("<img>");n.one("load",(function(){n.off("error abort"),t.resolve(n)})).one("error abort",(function(){n.off("load").detach(),t.reject(n)})).css({display:"none"}).appendTo(document.body).attr("src",o)})).promise()).then((function(t){i.beforeCommand(),"function"==typeof n?n(t):("string"==typeof n&&t.attr("data-filename",n),t.css("width",Math.min(i.$editable.width(),t.width()))),t.show(),i.getLastRange().insertNode(t[0]),i.setLastRange(yt.createFromNodeAfter(t[0]).select()),i.afterCommand()})).fail((function(t){i.context.triggerEvent("image.upload.error",t)}))}},{key:"insertImagesAsDataURL",value:function(t){var n=this;e().each(t,(function(t,o){var i=o.name;n.options.maximumImageFileSize&&n.options.maximumImageFileSize<o.size?n.context.triggerEvent("image.upload.error",n.lang.image.maximumFileSizeError):function(t){return e().Deferred((function(n){e().extend(new FileReader,{onload:function(t){var e=t.target.result;n.resolve(e)},onerror:function(t){n.reject(t)}}).readAsDataURL(t)})).promise()}(o).then((function(t){return n.insertImage(t,i)})).fail((function(){n.context.triggerEvent("image.upload.error")}))}))}},{key:"insertImagesOrCallback",value:function(t){this.options.callbacks.onImageUpload?this.context.triggerEvent("image.upload",t):this.insertImagesAsDataURL(t)}},{key:"getSelectedText",value:function(){var t=this.getLastRange();return t.isOnAnchor()&&(t=yt.createFromNode(ht.ancestor(t.sc,ht.isAnchor))),t.toString()}},{key:"onFormatBlock",value:function(t,n){if(document.execCommand("FormatBlock",!1,f.isMSIE?"<"+t+">":t),n&&n.length&&(n[0].tagName.toUpperCase()!==t.toUpperCase()&&(n=n.find(t)),n&&n.length)){var o=this.createRange(),i=e()([o.sc,o.ec]).closest(t);i.removeClass();var r=n[0].className||"";r&&i.addClass(r)}}},{key:"formatPara",value:function(){this.formatBlock("P")}},{key:"fontStyling",value:function(t,n){var o=this.getLastRange();if(""!==o){var i=this.style.styleNodes(o);if(this.$editor.find(".note-status-output").html(""),e()(i).css(t,n),o.isCollapsed()){var r=k.head(i);r&&!ht.nodeLength(r)&&(r.innerHTML=ht.ZERO_WIDTH_NBSP_CHAR,yt.createFromNode(r.firstChild).select(),this.setLastRange(),this.$editable.data("bogus",r))}else this.setLastRange(this.createRangeFromList(i).select())}else{var a=e().now();this.$editor.find(".note-status-output").html('<div id="note-status-output-'+a+'" class="alert alert-info">'+this.lang.output.noSelection+"</div>"),setTimeout((function(){e()("#note-status-output-"+a).remove()}),5e3)}}},{key:"unlink",value:function(){var t=this.getLastRange();if(t.isOnAnchor()){var e=ht.ancestor(t.sc,ht.isAnchor);(t=yt.createFromNode(e)).select(),this.setLastRange(),this.beforeCommand(),document.execCommand("unlink"),this.afterCommand()}}},{key:"getLinkInfo",value:function(){var t=this.getLastRange().expand(ht.isAnchor),n=e()(k.head(t.nodes(ht.isAnchor))),o={range:t,text:t.toString(),url:n.length?n.attr("href"):""};return n.length&&(o.isNewWindow="_blank"===n.attr("target")),o}},{key:"addRow",value:function(t){var e=this.getLastRange(this.$editable);e.isCollapsed()&&e.isOnCell()&&(this.beforeCommand(),this.table.addRow(e,t),this.afterCommand())}},{key:"addCol",value:function(t){var e=this.getLastRange(this.$editable);e.isCollapsed()&&e.isOnCell()&&(this.beforeCommand(),this.table.addCol(e,t),this.afterCommand())}},{key:"deleteRow",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteRow(t),this.afterCommand())}},{key:"deleteCol",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteCol(t),this.afterCommand())}},{key:"deleteTable",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteTable(t),this.afterCommand())}},{key:"resizeTo",value:function(t,e,n){var o;if(n){var i=t.y/t.x,r=e.data("ratio");o={width:r>i?t.x:t.y/r,height:r>i?t.x*r:t.y}}else o={width:t.x,height:t.y};e.css(o)}},{key:"hasFocus",value:function(){return this.$editable.is(":focus")}},{key:"focus",value:function(){this.hasFocus()||this.$editable.focus()}},{key:"isEmpty",value:function(){return ht.isEmpty(this.$editable[0])||ht.emptyPara===this.$editable.html()}},{key:"empty",value:function(){this.context.invoke("code",ht.emptyPara)}},{key:"normalizeContent",value:function(){this.$editable[0].normalize()}}],o&&At(n.prototype,o),i&&At(n,i),t}();function Dt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Ht=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editable=e.layoutInfo.editable}var e,n,o;return e=t,(n=[{key:"initialize",value:function(){this.$editable.on("paste",this.pasteByEvent.bind(this))}},{key:"pasteByEvent",value:function(t){var e=this,n=t.originalEvent.clipboardData;if(n&&n.items&&n.items.length){var o=n.items.length>1?n.items[1]:k.head(n.items);"file"===o.kind&&-1!==o.type.indexOf("image/")?(this.context.invoke("editor.insertImagesOrCallback",[o.getAsFile()]),t.preventDefault()):"string"===o.kind&&this.context.invoke("editor.isLimited",n.getData("Text").length)&&t.preventDefault()}else if(window.clipboardData){var i=window.clipboardData.getData("text");this.context.invoke("editor.isLimited",i.length)&&t.preventDefault()}setTimeout((function(){e.context.invoke("editor.afterCommand")}),10)}}])&&Dt(e.prototype,n),o&&Dt(e,o),t}();function zt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Bt=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$eventListener=e()(document),this.$editor=n.layoutInfo.editor,this.$editable=n.layoutInfo.editable,this.options=n.options,this.lang=this.options.langInfo,this.documentEventHandlers={},this.$dropzone=e()(['<div class="note-dropzone">','<div class="note-dropzone-message"></div>',"</div>"].join("")).prependTo(this.$editor)}var n,o,i;return n=t,o=[{key:"initialize",value:function(){this.options.disableDragAndDrop?(this.documentEventHandlers.onDrop=function(t){t.preventDefault()},this.$eventListener=this.$dropzone,this.$eventListener.on("drop",this.documentEventHandlers.onDrop)):this.attachDragAndDropEvent()}},{key:"attachDragAndDropEvent",value:function(){var t=this,n=e()(),o=this.$dropzone.find(".note-dropzone-message");this.documentEventHandlers.onDragenter=function(e){var i=t.context.invoke("codeview.isActivated"),r=t.$editor.width()>0&&t.$editor.height()>0;i||n.length||!r||(t.$editor.addClass("dragover"),t.$dropzone.width(t.$editor.width()),t.$dropzone.height(t.$editor.height()),o.text(t.lang.image.dragImageHere)),n=n.add(e.target)},this.documentEventHandlers.onDragleave=function(o){(n=n.not(o.target)).length&&"BODY"!==o.target.nodeName||(n=e()(),t.$editor.removeClass("dragover"))},this.documentEventHandlers.onDrop=function(){n=e()(),t.$editor.removeClass("dragover")},this.$eventListener.on("dragenter",this.documentEventHandlers.onDragenter).on("dragleave",this.documentEventHandlers.onDragleave).on("drop",this.documentEventHandlers.onDrop),this.$dropzone.on("dragenter",(function(){t.$dropzone.addClass("hover"),o.text(t.lang.image.dropImage)})).on("dragleave",(function(){t.$dropzone.removeClass("hover"),o.text(t.lang.image.dragImageHere)})),this.$dropzone.on("drop",(function(n){var o=n.originalEvent.dataTransfer;n.preventDefault(),o&&o.files&&o.files.length?(t.$editable.focus(),t.context.invoke("editor.insertImagesOrCallback",o.files)):e().each(o.types,(function(n,i){if(!(i.toLowerCase().indexOf("_moz_")>-1)){var r=o.getData(i);i.toLowerCase().indexOf("text")>-1?t.context.invoke("editor.pasteHTML",r):e()(r).each((function(e,n){t.context.invoke("editor.insertNode",n)}))}}))})).on("dragover",!1)}},{key:"destroy",value:function(){var t=this;Object.keys(this.documentEventHandlers).forEach((function(e){t.$eventListener.off(e.substr(2).toLowerCase(),t.documentEventHandlers[e])})),this.documentEventHandlers={}}}],o&&zt(n.prototype,o),i&&zt(n,i),t}();function Mt(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(!t)return;if("string"==typeof t)return Ot(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Ot(t,e)}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,i=function(){};return{s:i,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,r=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw r}}}}function Ot(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=new Array(e);n<e;n++)o[n]=t[n];return o}function Ut(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var jt=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editor=e.layoutInfo.editor,this.$editable=e.layoutInfo.editable,this.$codable=e.layoutInfo.codable,this.options=e.options,this.CodeMirrorConstructor=window.CodeMirror,this.options.codemirror.CodeMirrorConstructor&&(this.CodeMirrorConstructor=this.options.codemirror.CodeMirrorConstructor)}var e,n,o;return e=t,n=[{key:"sync",value:function(t){var e=this.isActivated(),n=this.CodeMirrorConstructor;e&&(t?n?this.$codable.data("cmEditor").getDoc().setValue(t):this.$codable.val(t):n&&this.$codable.data("cmEditor").save())}},{key:"initialize",value:function(){var t=this;this.$codable.on("keyup",(function(e){e.keyCode===wt.code.ESCAPE&&t.deactivate()}))}},{key:"isActivated",value:function(){return this.$editor.hasClass("codeview")}},{key:"toggle",value:function(){this.isActivated()?this.deactivate():this.activate(),this.context.triggerEvent("codeview.toggled")}},{key:"purify",value:function(t){if(this.options.codeviewFilter&&(t=t.replace(this.options.codeviewFilterRegex,""),this.options.codeviewIframeFilter)){var e=this.options.codeviewIframeWhitelistSrc.concat(this.options.codeviewIframeWhitelistSrcBase);t=t.replace(/(<iframe.*?>.*?(?:<\/iframe>)?)/gi,(function(t){if(/<.+src(?==?('|"|\s)?)[\s\S]+src(?=('|"|\s)?)[^>]*?>/i.test(t))return"";var n,o=Mt(e);try{for(o.s();!(n=o.n()).done;){var i=n.value;if(new RegExp('src="(https?:)?//'+i.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")+'/(.+)"').test(t))return t}}catch(t){o.e(t)}finally{o.f()}return""}))}return t}},{key:"activate",value:function(){var t=this,e=this.CodeMirrorConstructor;if(this.$codable.val(ht.html(this.$editable,this.options.prettifyHtml)),this.$codable.height(this.$editable.height()),this.context.invoke("toolbar.updateCodeview",!0),this.context.invoke("airPopover.updateCodeview",!0),this.$editor.addClass("codeview"),this.$codable.focus(),e){var n=e.fromTextArea(this.$codable[0],this.options.codemirror);if(this.options.codemirror.tern){var o=new e.TernServer(this.options.codemirror.tern);n.ternServer=o,n.on("cursorActivity",(function(t){o.updateArgHints(t)}))}n.on("blur",(function(e){t.context.triggerEvent("blur.codeview",n.getValue(),e)})),n.on("change",(function(){t.context.triggerEvent("change.codeview",n.getValue(),n)})),n.setSize(null,this.$editable.outerHeight()),this.$codable.data("cmEditor",n)}else this.$codable.on("blur",(function(e){t.context.triggerEvent("blur.codeview",t.$codable.val(),e)})),this.$codable.on("input",(function(){t.context.triggerEvent("change.codeview",t.$codable.val(),t.$codable)}))}},{key:"deactivate",value:function(){if(this.CodeMirrorConstructor){var t=this.$codable.data("cmEditor");this.$codable.val(t.getValue()),t.toTextArea()}var e=this.purify(ht.value(this.$codable,this.options.prettifyHtml)||ht.emptyPara),n=this.$editable.html()!==e;this.$editable.html(e),this.$editable.height(this.options.height?this.$codable.height():"auto"),this.$editor.removeClass("codeview"),n&&this.context.triggerEvent("change",this.$editable.html(),this.$editable),this.$editable.focus(),this.context.invoke("toolbar.updateCodeview",!1),this.context.invoke("airPopover.updateCodeview",!1)}},{key:"destroy",value:function(){this.isActivated()&&this.deactivate()}}],n&&Ut(e.prototype,n),o&&Ut(e,o),t}();function Wt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Kt=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$document=e()(document),this.$statusbar=n.layoutInfo.statusbar,this.$editable=n.layoutInfo.editable,this.$codable=n.layoutInfo.codable,this.options=n.options}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t=this;this.options.airMode||this.options.disableResizeEditor?this.destroy():this.$statusbar.on("mousedown",(function(e){e.preventDefault(),e.stopPropagation();var n=t.$editable.offset().top-t.$document.scrollTop(),o=t.$codable.offset().top-t.$document.scrollTop(),i=function(e){var i=e.clientY-(n+24),r=e.clientY-(o+24);i=t.options.minheight>0?Math.max(i,t.options.minheight):i,i=t.options.maxHeight>0?Math.min(i,t.options.maxHeight):i,r=t.options.minheight>0?Math.max(r,t.options.minheight):r,r=t.options.maxHeight>0?Math.min(r,t.options.maxHeight):r,t.$editable.height(i),t.$codable.height(r)};t.$document.on("mousemove",i).one("mouseup",(function(){t.$document.off("mousemove",i)}))}))}},{key:"destroy",value:function(){this.$statusbar.off(),this.$statusbar.addClass("locked")}}])&&Wt(n.prototype,o),i&&Wt(n,i),t}();function Vt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var qt=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$editor=n.layoutInfo.editor,this.$toolbar=n.layoutInfo.toolbar,this.$editable=n.layoutInfo.editable,this.$codable=n.layoutInfo.codable,this.$window=e()(window),this.$scrollbar=e()("html, body"),this.scrollbarClassName="note-fullscreen-body",this.onResize=function(){o.resizeTo({h:o.$window.height()-o.$toolbar.outerHeight()})}}var n,o,i;return n=t,(o=[{key:"resizeTo",value:function(t){this.$editable.css("height",t.h),this.$codable.css("height",t.h),this.$codable.data("cmeditor")&&this.$codable.data("cmeditor").setsize(null,t.h)}},{key:"toggle",value:function(){this.$editor.toggleClass("fullscreen");var t=this.isFullscreen();this.$scrollbar.toggleClass(this.scrollbarClassName,t),t?(this.$editable.data("orgHeight",this.$editable.css("height")),this.$editable.data("orgMaxHeight",this.$editable.css("maxHeight")),this.$editable.css("maxHeight",""),this.$window.on("resize",this.onResize).trigger("resize")):(this.$window.off("resize",this.onResize),this.resizeTo({h:this.$editable.data("orgHeight")}),this.$editable.css("maxHeight",this.$editable.css("orgMaxHeight"))),this.context.invoke("toolbar.updateFullscreen",t)}},{key:"isFullscreen",value:function(){return this.$editor.hasClass("fullscreen")}},{key:"destroy",value:function(){this.$scrollbar.removeClass(this.scrollbarClassName)}}])&&Vt(n.prototype,o),i&&Vt(n,i),t}();function _t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Gt=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$document=e()(document),this.$editingArea=n.layoutInfo.editingArea,this.options=n.options,this.lang=this.options.langInfo,this.events={"summernote.mousedown":function(t,e){o.update(e.target,e)&&e.preventDefault()},"summernote.keyup summernote.scroll summernote.change summernote.dialog.shown":function(){o.update()},"summernote.disable summernote.blur":function(){o.hide()},"summernote.codeview.toggled":function(){o.update()}}}var n,o,i;return n=t,o=[{key:"initialize",value:function(){var t=this;this.$handle=e()(['<div class="note-handle">','<div class="note-control-selection">','<div class="note-control-selection-bg"></div>','<div class="note-control-holder note-control-nw"></div>','<div class="note-control-holder note-control-ne"></div>','<div class="note-control-holder note-control-sw"></div>','<div class="',this.options.disableResizeImage?"note-control-holder":"note-control-sizing",' note-control-se"></div>',this.options.disableResizeImage?"":'<div class="note-control-selection-info"></div>',"</div>","</div>"].join("")).prependTo(this.$editingArea),this.$handle.on("mousedown",(function(e){if(ht.isControlSizing(e.target)){e.preventDefault(),e.stopPropagation();var n=t.$handle.find(".note-control-selection").data("target"),o=n.offset(),i=t.$document.scrollTop(),r=function(e){t.context.invoke("editor.resizeTo",{x:e.clientX-o.left,y:e.clientY-(o.top-i)},n,!e.shiftKey),t.update(n[0],e)};t.$document.on("mousemove",r).one("mouseup",(function(e){e.preventDefault(),t.$document.off("mousemove",r),t.context.invoke("editor.afterCommand")})),n.data("ratio")||n.data("ratio",n.height()/n.width())}})),this.$handle.on("wheel",(function(e){e.preventDefault(),t.update()}))}},{key:"destroy",value:function(){this.$handle.remove()}},{key:"update",value:function(t,n){if(this.context.isDisabled())return!1;var o=ht.isImg(t),i=this.$handle.find(".note-control-selection");if(this.context.invoke("imagePopover.update",t,n),o){var r=e()(t),a=r.position(),s={left:a.left+parseInt(r.css("marginLeft"),10),top:a.top+parseInt(r.css("marginTop"),10)},l={w:r.outerWidth(!1),h:r.outerHeight(!1)};i.css({display:"block",left:s.left,top:s.top,width:l.w,height:l.h}).data("target",r);var c=new Image;c.src=r.attr("src");var u=l.w+"x"+l.h+" ("+this.lang.image.original+": "+c.width+"x"+c.height+")";i.find(".note-control-selection-info").text(u),this.context.invoke("editor.saveTarget",t)}else this.hide();return o}},{key:"hide",value:function(){this.context.invoke("editor.clearTarget"),this.$handle.children().hide()}}],o&&_t(n.prototype,o),i&&_t(n,i),t}();function Yt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Zt=/^([A-Za-z][A-Za-z0-9+-.]*\:[\/]{2}|tel:|mailto:[A-Z0-9._%+-]+@|xmpp:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i,Qt=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.options=e.options,this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||n.handleKeyup(e)},"summernote.keydown":function(t,e){n.handleKeydown(e)}}}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){this.lastWordRange=null}},{key:"destroy",value:function(){this.lastWordRange=null}},{key:"replace",value:function(){if(this.lastWordRange){var t=this.lastWordRange.toString(),n=t.match(Zt);if(n&&(n[1]||n[2])){var o=n[1]?t:"http://"+t,i=this.options.showDomainOnlyForAutolink?t.replace(/^(?:https?:\/\/)?(?:tel?:?)?(?:mailto?:?)?(?:xmpp?:?)?(?:www\.)?/i,"").split("/")[0]:t,r=e()("<a></a>").html(i).attr("href",o)[0];this.context.options.linkTargetBlank&&e()(r).attr("target","_blank"),this.lastWordRange.insertNode(r),this.lastWordRange=null,this.context.invoke("editor.focus")}}}},{key:"handleKeydown",value:function(t){if(k.contains([wt.code.ENTER,wt.code.SPACE],t.keyCode)){var e=this.context.invoke("editor.createRange").getWordRange();this.lastWordRange=e}}},{key:"handleKeyup",value:function(t){k.contains([wt.code.ENTER,wt.code.SPACE],t.keyCode)&&this.replace()}}])&&Yt(n.prototype,o),i&&Yt(n,i),t}();function Xt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Jt=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$note=e.layoutInfo.note,this.events={"summernote.change":function(){n.$note.val(e.invoke("code"))}}}var e,n,o;return e=t,(n=[{key:"shouldInitialize",value:function(){return ht.isTextarea(this.$note[0])}}])&&Xt(e.prototype,n),o&&Xt(e,o),t}();function te(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ee=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.options=e.options.replace||{},this.keys=[wt.code.ENTER,wt.code.SPACE,wt.code.PERIOD,wt.code.COMMA,wt.code.SEMICOLON,wt.code.SLASH],this.previousKeydownCode=null,this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||n.handleKeyup(e)},"summernote.keydown":function(t,e){n.handleKeydown(e)}}}var e,n,o;return e=t,(n=[{key:"shouldInitialize",value:function(){return!!this.options.match}},{key:"initialize",value:function(){this.lastWord=null}},{key:"destroy",value:function(){this.lastWord=null}},{key:"replace",value:function(){if(this.lastWord){var t=this,e=this.lastWord.toString();this.options.match(e,(function(e){if(e){var n="";if("string"==typeof e?n=ht.createText(e):e instanceof jQuery?n=e[0]:e instanceof Node&&(n=e),!n)return;t.lastWord.insertNode(n),t.lastWord=null,t.context.invoke("editor.focus")}}))}}},{key:"handleKeydown",value:function(t){if(this.previousKeydownCode&&k.contains(this.keys,this.previousKeydownCode))this.previousKeydownCode=t.keyCode;else{if(k.contains(this.keys,t.keyCode)){var e=this.context.invoke("editor.createRange").getWordRange();this.lastWord=e}this.previousKeydownCode=t.keyCode}}},{key:"handleKeyup",value:function(t){k.contains(this.keys,t.keyCode)&&this.replace()}}])&&te(e.prototype,n),o&&te(e,o),t}();function ne(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var oe=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editingArea=e.layoutInfo.editingArea,this.options=e.options,!0===this.options.inheritPlaceholder&&(this.options.placeholder=this.context.$note.attr("placeholder")||this.options.placeholder),this.events={"summernote.init summernote.change":function(){n.update()},"summernote.codeview.toggled":function(){n.update()}}}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return!!this.options.placeholder}},{key:"initialize",value:function(){var t=this;this.$placeholder=e()('<div class="note-placeholder"></div>'),this.$placeholder.on("click",(function(){t.context.invoke("focus")})).html(this.options.placeholder).prependTo(this.$editingArea),this.update()}},{key:"destroy",value:function(){this.$placeholder.remove()}},{key:"update",value:function(){var t=!this.context.invoke("codeview.isActivated")&&this.context.invoke("editor.isEmpty");this.$placeholder.toggle(t)}}])&&ne(n.prototype,o),i&&ne(n,i),t}();function ie(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var re=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.ui=e().summernote.ui,this.context=n,this.$toolbar=n.layoutInfo.toolbar,this.options=n.options,this.lang=this.options.langInfo,this.invertedKeyMap=m.invertObject(this.options.keyMap[f.isMac?"mac":"pc"])}var n,o,i;return n=t,o=[{key:"representShortcut",value:function(t){var e=this.invertedKeyMap[t];return this.options.shortcuts&&e?(f.isMac&&(e=e.replace("CMD","⌘").replace("SHIFT","⇧"))," ("+(e=e.replace("BACKSLASH","\\").replace("SLASH","/").replace("LEFTBRACKET","[").replace("RIGHTBRACKET","]"))+")"):""}},{key:"button",value:function(t){return!this.options.tooltip&&t.tooltip&&delete t.tooltip,t.container=this.options.container,this.ui.button(t)}},{key:"initialize",value:function(){this.addToolbarButtons(),this.addImagePopoverButtons(),this.addLinkPopoverButtons(),this.addTablePopoverButtons(),this.fontInstalledMap={}}},{key:"destroy",value:function(){delete this.fontInstalledMap}},{key:"isFontInstalled",value:function(t){return Object.prototype.hasOwnProperty.call(this.fontInstalledMap,t)||(this.fontInstalledMap[t]=f.isFontInstalled(t)||k.contains(this.options.fontNamesIgnoreCheck,t)),this.fontInstalledMap[t]}},{key:"isFontDeservedToAdd",value:function(t){return""!==(t=t.toLowerCase())&&this.isFontInstalled(t)&&-1===f.genericFontFamilies.indexOf(t)}},{key:"colorPalette",value:function(t,n,o,i){var r=this;return this.ui.buttonGroup({className:"note-color "+t,children:[this.button({className:"note-current-color-button",contents:this.ui.icon(this.options.icons.font+" note-recent-color"),tooltip:n,click:function(t){var n=e()(t.currentTarget);o&&i?r.context.invoke("editor.color",{backColor:n.attr("data-backColor"),foreColor:n.attr("data-foreColor")}):o?r.context.invoke("editor.color",{backColor:n.attr("data-backColor")}):i&&r.context.invoke("editor.color",{foreColor:n.attr("data-foreColor")})},callback:function(t){var e=t.find(".note-recent-color");o&&(e.css("background-color",r.options.colorButton.backColor),t.attr("data-backColor",r.options.colorButton.backColor)),i?(e.css("color",r.options.colorButton.foreColor),t.attr("data-foreColor",r.options.colorButton.foreColor)):e.css("color","transparent")}}),this.button({className:"dropdown-toggle",contents:this.ui.dropdownButtonContents("",this.options),tooltip:this.lang.color.more,data:{toggle:"dropdown"}}),this.ui.dropdown({items:(o?['<div class="note-palette">','<div class="note-palette-title">'+this.lang.color.background+"</div>","<div>",'<button type="button" class="note-color-reset btn btn-light btn-default" data-event="backColor" data-value="transparent">',this.lang.color.transparent,"</button>","</div>",'<div class="note-holder" data-event="backColor">\x3c!-- back colors --\x3e</div>',"<div>",'<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="backColorPicker-'+this.options.id+'">',this.lang.color.cpSelect,"</button>",'<input type="color" id="backColorPicker-'+this.options.id+'" class="note-btn note-color-select-btn" value="'+this.options.colorButton.backColor+'" data-event="backColorPalette-'+this.options.id+'">',"</div>",'<div class="note-holder-custom" id="backColorPalette-'+this.options.id+'" data-event="backColor"></div>',"</div>"].join(""):"")+(i?['<div class="note-palette">','<div class="note-palette-title">'+this.lang.color.foreground+"</div>","<div>",'<button type="button" class="note-color-reset btn btn-light btn-default" data-event="removeFormat" data-value="foreColor">',this.lang.color.resetToDefault,"</button>","</div>",'<div class="note-holder" data-event="foreColor">\x3c!-- fore colors --\x3e</div>',"<div>",'<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="foreColorPicker-'+this.options.id+'">',this.lang.color.cpSelect,"</button>",'<input type="color" id="foreColorPicker-'+this.options.id+'" class="note-btn note-color-select-btn" value="'+this.options.colorButton.foreColor+'" data-event="foreColorPalette-'+this.options.id+'">',"</div>",'<div class="note-holder-custom" id="foreColorPalette-'+this.options.id+'" data-event="foreColor"></div>',"</div>"].join(""):""),callback:function(t){t.find(".note-holder").each((function(t,n){var o=e()(n);o.append(r.ui.palette({colors:r.options.colors,colorsName:r.options.colorsName,eventName:o.data("event"),container:r.options.container,tooltip:r.options.tooltip}).render())}));var n=[["#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF"]];t.find(".note-holder-custom").each((function(t,o){var i=e()(o);i.append(r.ui.palette({colors:n,colorsName:n,eventName:i.data("event"),container:r.options.container,tooltip:r.options.tooltip}).render())})),t.find("input[type=color]").each((function(n,o){e()(o).change((function(){var n=t.find("#"+e()(this).data("event")).find(".note-color-btn").first(),o=this.value.toUpperCase();n.css("background-color",o).attr("aria-label",o).attr("data-value",o).attr("data-original-title",o),n.click()}))}))},click:function(n){n.stopPropagation();var o=e()("."+t).find(".note-dropdown-menu"),i=e()(n.target),a=i.data("event"),s=i.attr("data-value");if("openPalette"===a){var l=o.find("#"+s),c=e()(o.find("#"+l.data("event")).find(".note-color-row")[0]),u=c.find(".note-color-btn").last().detach(),d=l.val();u.css("background-color",d).attr("aria-label",d).attr("data-value",d).attr("data-original-title",d),c.prepend(u),l.click()}else{if(k.contains(["backColor","foreColor"],a)){var h="backColor"===a?"background-color":"color",f=i.closest(".note-color").find(".note-recent-color"),p=i.closest(".note-color").find(".note-current-color-button");f.css(h,s),p.attr("data-"+a,s)}r.context.invoke("editor."+a,s)}}})]}).render()}},{key:"addToolbarButtons",value:function(){var t=this;this.context.memo("button.style",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.magic),t.options),tooltip:t.lang.style.style,data:{toggle:"dropdown"}}),t.ui.dropdown({className:"dropdown-style",items:t.options.styleTags,title:t.lang.style.style,template:function(e){"string"==typeof e&&(e={tag:e,title:Object.prototype.hasOwnProperty.call(t.lang.style,e)?t.lang.style[e]:e});var n=e.tag,o=e.title;return"<"+n+(e.style?' style="'+e.style+'" ':"")+(e.className?' class="'+e.className+'"':"")+">"+o+"</"+n+">"},click:t.context.createInvokeHandler("editor.formatBlock")})]).render()}));for(var n=function(e,n){var o=t.options.styleTags[e];t.context.memo("button.style."+o,(function(){return t.button({className:"note-btn-style-"+o,contents:'<div data-value="'+o+'">'+o.toUpperCase()+"</div>",tooltip:t.lang.style[o],click:t.context.createInvokeHandler("editor.formatBlock")}).render()}))},o=0,i=this.options.styleTags.length;o<i;o++)n(o);this.context.memo("button.bold",(function(){return t.button({className:"note-btn-bold",contents:t.ui.icon(t.options.icons.bold),tooltip:t.lang.font.bold+t.representShortcut("bold"),click:t.context.createInvokeHandlerAndUpdateState("editor.bold")}).render()})),this.context.memo("button.italic",(function(){return t.button({className:"note-btn-italic",contents:t.ui.icon(t.options.icons.italic),tooltip:t.lang.font.italic+t.representShortcut("italic"),click:t.context.createInvokeHandlerAndUpdateState("editor.italic")}).render()})),this.context.memo("button.underline",(function(){return t.button({className:"note-btn-underline",contents:t.ui.icon(t.options.icons.underline),tooltip:t.lang.font.underline+t.representShortcut("underline"),click:t.context.createInvokeHandlerAndUpdateState("editor.underline")}).render()})),this.context.memo("button.clear",(function(){return t.button({contents:t.ui.icon(t.options.icons.eraser),tooltip:t.lang.font.clear+t.representShortcut("removeFormat"),click:t.context.createInvokeHandler("editor.removeFormat")}).render()})),this.context.memo("button.strikethrough",(function(){return t.button({className:"note-btn-strikethrough",contents:t.ui.icon(t.options.icons.strikethrough),tooltip:t.lang.font.strikethrough+t.representShortcut("strikethrough"),click:t.context.createInvokeHandlerAndUpdateState("editor.strikethrough")}).render()})),this.context.memo("button.superscript",(function(){return t.button({className:"note-btn-superscript",contents:t.ui.icon(t.options.icons.superscript),tooltip:t.lang.font.superscript,click:t.context.createInvokeHandlerAndUpdateState("editor.superscript")}).render()})),this.context.memo("button.subscript",(function(){return t.button({className:"note-btn-subscript",contents:t.ui.icon(t.options.icons.subscript),tooltip:t.lang.font.subscript,click:t.context.createInvokeHandlerAndUpdateState("editor.subscript")}).render()})),this.context.memo("button.fontname",(function(){var n=t.context.invoke("editor.currentStyle");return t.options.addDefaultFonts&&e().each(n["font-family"].split(","),(function(e,n){n=n.trim().replace(/['"]+/g,""),t.isFontDeservedToAdd(n)&&-1===t.options.fontNames.indexOf(n)&&t.options.fontNames.push(n)})),t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontname"></span>',t.options),tooltip:t.lang.font.name,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontname",checkClassName:t.options.icons.menuCheck,items:t.options.fontNames.filter(t.isFontInstalled.bind(t)),title:t.lang.font.name,template:function(t){return'<span style="font-family: '+f.validFontName(t)+'">'+t+"</span>"},click:t.context.createInvokeHandlerAndUpdateState("editor.fontName")})]).render()})),this.context.memo("button.fontsize",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontsize"></span>',t.options),tooltip:t.lang.font.size,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontsize",checkClassName:t.options.icons.menuCheck,items:t.options.fontSizes,title:t.lang.font.size,click:t.context.createInvokeHandlerAndUpdateState("editor.fontSize")})]).render()})),this.context.memo("button.fontsizeunit",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontsizeunit"></span>',t.options),tooltip:t.lang.font.sizeunit,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontsizeunit",checkClassName:t.options.icons.menuCheck,items:t.options.fontSizeUnits,title:t.lang.font.sizeunit,click:t.context.createInvokeHandlerAndUpdateState("editor.fontSizeUnit")})]).render()})),this.context.memo("button.color",(function(){return t.colorPalette("note-color-all",t.lang.color.recent,!0,!0)})),this.context.memo("button.forecolor",(function(){return t.colorPalette("note-color-fore",t.lang.color.foreground,!1,!0)})),this.context.memo("button.backcolor",(function(){return t.colorPalette("note-color-back",t.lang.color.background,!0,!1)})),this.context.memo("button.ul",(function(){return t.button({contents:t.ui.icon(t.options.icons.unorderedlist),tooltip:t.lang.lists.unordered+t.representShortcut("insertUnorderedList"),click:t.context.createInvokeHandler("editor.insertUnorderedList")}).render()})),this.context.memo("button.ol",(function(){return t.button({contents:t.ui.icon(t.options.icons.orderedlist),tooltip:t.lang.lists.ordered+t.representShortcut("insertOrderedList"),click:t.context.createInvokeHandler("editor.insertOrderedList")}).render()}));var r=this.button({contents:this.ui.icon(this.options.icons.alignLeft),tooltip:this.lang.paragraph.left+this.representShortcut("justifyLeft"),click:this.context.createInvokeHandler("editor.justifyLeft")}),a=this.button({contents:this.ui.icon(this.options.icons.alignCenter),tooltip:this.lang.paragraph.center+this.representShortcut("justifyCenter"),click:this.context.createInvokeHandler("editor.justifyCenter")}),s=this.button({contents:this.ui.icon(this.options.icons.alignRight),tooltip:this.lang.paragraph.right+this.representShortcut("justifyRight"),click:this.context.createInvokeHandler("editor.justifyRight")}),l=this.button({contents:this.ui.icon(this.options.icons.alignJustify),tooltip:this.lang.paragraph.justify+this.representShortcut("justifyFull"),click:this.context.createInvokeHandler("editor.justifyFull")}),c=this.button({contents:this.ui.icon(this.options.icons.outdent),tooltip:this.lang.paragraph.outdent+this.representShortcut("outdent"),click:this.context.createInvokeHandler("editor.outdent")}),u=this.button({contents:this.ui.icon(this.options.icons.indent),tooltip:this.lang.paragraph.indent+this.representShortcut("indent"),click:this.context.createInvokeHandler("editor.indent")});this.context.memo("button.justifyLeft",m.invoke(r,"render")),this.context.memo("button.justifyCenter",m.invoke(a,"render")),this.context.memo("button.justifyRight",m.invoke(s,"render")),this.context.memo("button.justifyFull",m.invoke(l,"render")),this.context.memo("button.outdent",m.invoke(c,"render")),this.context.memo("button.indent",m.invoke(u,"render")),this.context.memo("button.paragraph",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.alignLeft),t.options),tooltip:t.lang.paragraph.paragraph,data:{toggle:"dropdown"}}),t.ui.dropdown([t.ui.buttonGroup({className:"note-align",children:[r,a,s,l]}),t.ui.buttonGroup({className:"note-list",children:[c,u]})])]).render()})),this.context.memo("button.height",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.textHeight),t.options),tooltip:t.lang.font.height,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({items:t.options.lineHeights,checkClassName:t.options.icons.menuCheck,className:"dropdown-line-height",title:t.lang.font.height,click:t.context.createInvokeHandler("editor.lineHeight")})]).render()})),this.context.memo("button.table",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.table),t.options),tooltip:t.lang.table.table,data:{toggle:"dropdown"}}),t.ui.dropdown({title:t.lang.table.table,className:"note-table",items:['<div class="note-dimension-picker">','<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>','<div class="note-dimension-picker-highlighted"></div>','<div class="note-dimension-picker-unhighlighted"></div>',"</div>",'<div class="note-dimension-display">1 x 1</div>'].join("")})],{callback:function(e){e.find(".note-dimension-picker-mousecatcher").css({width:t.options.insertTableMaxSize.col+"em",height:t.options.insertTableMaxSize.row+"em"}).mouseup(t.context.createInvokeHandler("editor.insertTable")).on("mousemove",t.tableMoveHandler.bind(t))}}).render()})),this.context.memo("button.link",(function(){return t.button({contents:t.ui.icon(t.options.icons.link),tooltip:t.lang.link.link+t.representShortcut("linkDialog.show"),click:t.context.createInvokeHandler("linkDialog.show")}).render()})),this.context.memo("button.picture",(function(){return t.button({contents:t.ui.icon(t.options.icons.picture),tooltip:t.lang.image.image,click:t.context.createInvokeHandler("imageDialog.show")}).render()})),this.context.memo("button.video",(function(){return t.button({contents:t.ui.icon(t.options.icons.video),tooltip:t.lang.video.video,click:t.context.createInvokeHandler("videoDialog.show")}).render()})),this.context.memo("button.hr",(function(){return t.button({contents:t.ui.icon(t.options.icons.minus),tooltip:t.lang.hr.insert+t.representShortcut("insertHorizontalRule"),click:t.context.createInvokeHandler("editor.insertHorizontalRule")}).render()})),this.context.memo("button.fullscreen",(function(){return t.button({className:"btn-fullscreen note-codeview-keep",contents:t.ui.icon(t.options.icons.arrowsAlt),tooltip:t.lang.options.fullscreen,click:t.context.createInvokeHandler("fullscreen.toggle")}).render()})),this.context.memo("button.codeview",(function(){return t.button({className:"btn-codeview note-codeview-keep",contents:t.ui.icon(t.options.icons.code),tooltip:t.lang.options.codeview,click:t.context.createInvokeHandler("codeview.toggle")}).render()})),this.context.memo("button.redo",(function(){return t.button({contents:t.ui.icon(t.options.icons.redo),tooltip:t.lang.history.redo+t.representShortcut("redo"),click:t.context.createInvokeHandler("editor.redo")}).render()})),this.context.memo("button.undo",(function(){return t.button({contents:t.ui.icon(t.options.icons.undo),tooltip:t.lang.history.undo+t.representShortcut("undo"),click:t.context.createInvokeHandler("editor.undo")}).render()})),this.context.memo("button.help",(function(){return t.button({contents:t.ui.icon(t.options.icons.question),tooltip:t.lang.options.help,click:t.context.createInvokeHandler("helpDialog.show")}).render()}))}},{key:"addImagePopoverButtons",value:function(){var t=this;this.context.memo("button.resizeFull",(function(){return t.button({contents:'<span class="note-fontsize-10">100%</span>',tooltip:t.lang.image.resizeFull,click:t.context.createInvokeHandler("editor.resize","1")}).render()})),this.context.memo("button.resizeHalf",(function(){return t.button({contents:'<span class="note-fontsize-10">50%</span>',tooltip:t.lang.image.resizeHalf,click:t.context.createInvokeHandler("editor.resize","0.5")}).render()})),this.context.memo("button.resizeQuarter",(function(){return t.button({contents:'<span class="note-fontsize-10">25%</span>',tooltip:t.lang.image.resizeQuarter,click:t.context.createInvokeHandler("editor.resize","0.25")}).render()})),this.context.memo("button.resizeNone",(function(){return t.button({contents:t.ui.icon(t.options.icons.rollback),tooltip:t.lang.image.resizeNone,click:t.context.createInvokeHandler("editor.resize","0")}).render()})),this.context.memo("button.floatLeft",(function(){return t.button({contents:t.ui.icon(t.options.icons.floatLeft),tooltip:t.lang.image.floatLeft,click:t.context.createInvokeHandler("editor.floatMe","left")}).render()})),this.context.memo("button.floatRight",(function(){return t.button({contents:t.ui.icon(t.options.icons.floatRight),tooltip:t.lang.image.floatRight,click:t.context.createInvokeHandler("editor.floatMe","right")}).render()})),this.context.memo("button.floatNone",(function(){return t.button({contents:t.ui.icon(t.options.icons.rollback),tooltip:t.lang.image.floatNone,click:t.context.createInvokeHandler("editor.floatMe","none")}).render()})),this.context.memo("button.removeMedia",(function(){return t.button({contents:t.ui.icon(t.options.icons.trash),tooltip:t.lang.image.remove,click:t.context.createInvokeHandler("editor.removeMedia")}).render()}))}},{key:"addLinkPopoverButtons",value:function(){var t=this;this.context.memo("button.linkDialogShow",(function(){return t.button({contents:t.ui.icon(t.options.icons.link),tooltip:t.lang.link.edit,click:t.context.createInvokeHandler("linkDialog.show")}).render()})),this.context.memo("button.unlink",(function(){return t.button({contents:t.ui.icon(t.options.icons.unlink),tooltip:t.lang.link.unlink,click:t.context.createInvokeHandler("editor.unlink")}).render()}))}},{key:"addTablePopoverButtons",value:function(){var t=this;this.context.memo("button.addRowUp",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowAbove),tooltip:t.lang.table.addRowAbove,click:t.context.createInvokeHandler("editor.addRow","top")}).render()})),this.context.memo("button.addRowDown",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowBelow),tooltip:t.lang.table.addRowBelow,click:t.context.createInvokeHandler("editor.addRow","bottom")}).render()})),this.context.memo("button.addColLeft",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colBefore),tooltip:t.lang.table.addColLeft,click:t.context.createInvokeHandler("editor.addCol","left")}).render()})),this.context.memo("button.addColRight",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colAfter),tooltip:t.lang.table.addColRight,click:t.context.createInvokeHandler("editor.addCol","right")}).render()})),this.context.memo("button.deleteRow",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowRemove),tooltip:t.lang.table.delRow,click:t.context.createInvokeHandler("editor.deleteRow")}).render()})),this.context.memo("button.deleteCol",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colRemove),tooltip:t.lang.table.delCol,click:t.context.createInvokeHandler("editor.deleteCol")}).render()})),this.context.memo("button.deleteTable",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.trash),tooltip:t.lang.table.delTable,click:t.context.createInvokeHandler("editor.deleteTable")}).render()}))}},{key:"build",value:function(t,e){for(var n=0,o=e.length;n<o;n++){for(var i=e[n],r=Array.isArray(i)?i[0]:i,a=Array.isArray(i)?1===i.length?[i[0]]:i[1]:[i],s=this.ui.buttonGroup({className:"note-"+r}).render(),l=0,c=a.length;l<c;l++){var u=this.context.memo("button."+a[l]);u&&s.append("function"==typeof u?u(this.context):u)}s.appendTo(t)}}},{key:"updateCurrentStyle",value:function(t){var n=t||this.$toolbar,o=this.context.invoke("editor.currentStyle");if(this.updateBtnStates(n,{".note-btn-bold":function(){return"bold"===o["font-bold"]},".note-btn-italic":function(){return"italic"===o["font-italic"]},".note-btn-underline":function(){return"underline"===o["font-underline"]},".note-btn-subscript":function(){return"subscript"===o["font-subscript"]},".note-btn-superscript":function(){return"superscript"===o["font-superscript"]},".note-btn-strikethrough":function(){return"strikethrough"===o["font-strikethrough"]}}),o["font-family"]){var i=o["font-family"].split(",").map((function(t){return t.replace(/[\'\"]/g,"").replace(/\s+$/,"").replace(/^\s+/,"")})),r=k.find(i,this.isFontInstalled.bind(this));n.find(".dropdown-fontname a").each((function(t,n){var o=e()(n),i=o.data("value")+""==r+"";o.toggleClass("checked",i)})),n.find(".note-current-fontname").text(r).css("font-family",r)}if(o["font-size"]){var a=o["font-size"];n.find(".dropdown-fontsize a").each((function(t,n){var o=e()(n),i=o.data("value")+""==a+"";o.toggleClass("checked",i)})),n.find(".note-current-fontsize").text(a);var s=o["font-size-unit"];n.find(".dropdown-fontsizeunit a").each((function(t,n){var o=e()(n),i=o.data("value")+""==s+"";o.toggleClass("checked",i)})),n.find(".note-current-fontsizeunit").text(s)}if(o["line-height"]){var l=o["line-height"];n.find(".dropdown-line-height a").each((function(t,n){var o=e()(n),i=e()(n).data("value")+""==l+"";o.toggleClass("checked",i)})),n.find(".note-current-line-height").text(l)}}},{key:"updateBtnStates",value:function(t,n){var o=this;e().each(n,(function(e,n){o.ui.toggleBtnActive(t.find(e),n())}))}},{key:"tableMoveHandler",value:function(t){var n,o=e()(t.target.parentNode),i=o.next(),r=o.find(".note-dimension-picker-mousecatcher"),a=o.find(".note-dimension-picker-highlighted"),s=o.find(".note-dimension-picker-unhighlighted");if(void 0===t.offsetX){var l=e()(t.target).offset();n={x:t.pageX-l.left,y:t.pageY-l.top}}else n={x:t.offsetX,y:t.offsetY};var c=Math.ceil(n.x/18)||1,u=Math.ceil(n.y/18)||1;a.css({width:c+"em",height:u+"em"}),r.data("value",c+"x"+u),c>3&&c<this.options.insertTableMaxSize.col&&s.css({width:c+1+"em"}),u>3&&u<this.options.insertTableMaxSize.row&&s.css({height:u+1+"em"}),i.html(c+" x "+u)}}],o&&ie(n.prototype,o),i&&ie(n,i),t}();function ae(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var se=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$window=e()(window),this.$document=e()(document),this.ui=e().summernote.ui,this.$note=n.layoutInfo.note,this.$editor=n.layoutInfo.editor,this.$toolbar=n.layoutInfo.toolbar,this.$editable=n.layoutInfo.editable,this.$statusbar=n.layoutInfo.statusbar,this.options=n.options,this.isFollowing=!1,this.followScroll=this.followScroll.bind(this)}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return!this.options.airMode}},{key:"initialize",value:function(){var t=this;this.options.toolbar=this.options.toolbar||[],this.options.toolbar.length?this.context.invoke("buttons.build",this.$toolbar,this.options.toolbar):this.$toolbar.hide(),this.options.toolbarContainer&&this.$toolbar.appendTo(this.options.toolbarContainer),this.changeContainer(!1),this.$note.on("summernote.keyup summernote.mouseup summernote.change",(function(){t.context.invoke("buttons.updateCurrentStyle")})),this.context.invoke("buttons.updateCurrentStyle"),this.options.followingToolbar&&this.$window.on("scroll resize",this.followScroll)}},{key:"destroy",value:function(){this.$toolbar.children().remove(),this.options.followingToolbar&&this.$window.off("scroll resize",this.followScroll)}},{key:"followScroll",value:function(){if(this.$editor.hasClass("fullscreen"))return!1;var t=this.$editor.outerHeight(),n=this.$editor.width(),o=this.$toolbar.height(),i=this.$statusbar.height(),r=0;this.options.otherStaticBar&&(r=e()(this.options.otherStaticBar).outerHeight());var a=this.$document.scrollTop(),s=this.$editor.offset().top,l=s-r,c=s+t-r-o-i;!this.isFollowing&&a>l&&a<c-o?(this.isFollowing=!0,this.$editable.css({marginTop:this.$toolbar.outerHeight()}),this.$toolbar.css({position:"fixed",top:r,width:n,zIndex:1e3})):this.isFollowing&&(a<l||a>c)&&(this.isFollowing=!1,this.$toolbar.css({position:"relative",top:0,width:"100%",zIndex:"auto"}),this.$editable.css({marginTop:""}))}},{key:"changeContainer",value:function(t){t?this.$toolbar.prependTo(this.$editor):this.options.toolbarContainer&&this.$toolbar.appendTo(this.options.toolbarContainer),this.options.followingToolbar&&this.followScroll()}},{key:"updateFullscreen",value:function(t){this.ui.toggleBtnActive(this.$toolbar.find(".btn-fullscreen"),t),this.changeContainer(t)}},{key:"updateCodeview",value:function(t){this.ui.toggleBtnActive(this.$toolbar.find(".btn-codeview"),t),t?this.deactivate():this.activate()}},{key:"activate",value:function(t){var e=this.$toolbar.find("button");t||(e=e.not(".note-codeview-keep")),this.ui.toggleBtn(e,!0)}},{key:"deactivate",value:function(t){var e=this.$toolbar.find("button");t||(e=e.not(".note-codeview-keep")),this.ui.toggleBtn(e,!1)}}])&&ae(n.prototype,o),i&&ae(n,i),t}();function le(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ce=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo,n.memo("help.linkDialog.show",this.options.langInfo.help["linkDialog.show"])}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,n=['<div class="form-group note-form-group">','<label for="note-dialog-link-txt-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.link.textToDisplay,"</label>"),'<input id="note-dialog-link-txt-'.concat(this.options.id,'" class="note-link-text form-control note-form-control note-input" type="text"/>'),"</div>",'<div class="form-group note-form-group">','<label for="note-dialog-link-url-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.link.url,"</label>"),'<input id="note-dialog-link-url-'.concat(this.options.id,'" class="note-link-url form-control note-form-control note-input" type="text" value="http://"/>'),"</div>",this.options.disableLinkTarget?"":e()("<div></div>").append(this.ui.checkbox({className:"sn-checkbox-open-in-new-window",text:this.lang.link.openInNewWindow,checked:!0}).render()).html(),e()("<div></div>").append(this.ui.checkbox({className:"sn-checkbox-use-protocol",text:this.lang.link.useProtocol,checked:!0}).render()).html()].join(""),o='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-link-btn",'" value="').concat(this.lang.link.insert,'" disabled>');this.$dialog=this.ui.dialog({className:"link-dialog",title:this.lang.link.insert,fade:this.options.dialogsFade,body:n,footer:o}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"toggleLinkBtn",value:function(t,e,n){this.ui.toggleBtn(t,e.val()&&n.val())}},{key:"showLinkDialog",value:function(t){var n=this;return e().Deferred((function(e){var o=n.$dialog.find(".note-link-text"),i=n.$dialog.find(".note-link-url"),r=n.$dialog.find(".note-link-btn"),a=n.$dialog.find(".sn-checkbox-open-in-new-window input[type=checkbox]"),s=n.$dialog.find(".sn-checkbox-use-protocol input[type=checkbox]");n.ui.onDialogShown(n.$dialog,(function(){n.context.triggerEvent("dialog.shown"),!t.url&&m.isValidUrl(t.text)&&(t.url=t.text),o.on("input paste propertychange",(function(){t.text=o.val(),n.toggleLinkBtn(r,o,i)})).val(t.text),i.on("input paste propertychange",(function(){t.text||o.val(i.val()),n.toggleLinkBtn(r,o,i)})).val(t.url),f.isSupportTouch||i.trigger("focus"),n.toggleLinkBtn(r,o,i),n.bindEnterKey(i,r),n.bindEnterKey(o,r);var l=void 0!==t.isNewWindow?t.isNewWindow:n.context.options.linkTargetBlank;a.prop("checked",l);var c=!t.url&&n.context.options.useProtocol;s.prop("checked",c),r.one("click",(function(r){r.preventDefault(),e.resolve({range:t.range,url:i.val(),text:o.val(),isNewWindow:a.is(":checked"),checkProtocol:s.is(":checked")}),n.ui.hideDialog(n.$dialog)}))})),n.ui.onDialogHidden(n.$dialog,(function(){o.off(),i.off(),r.off(),"pending"===e.state()&&e.reject()})),n.ui.showDialog(n.$dialog)})).promise()}},{key:"show",value:function(){var t=this,e=this.context.invoke("editor.getLinkInfo");this.context.invoke("editor.saveRange"),this.showLinkDialog(e).then((function(e){t.context.invoke("editor.restoreRange"),t.context.invoke("editor.createLink",e)})).fail((function(){t.context.invoke("editor.restoreRange")}))}}])&&le(n.prototype,o),i&&le(n,i),t}();function ue(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var de=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.options=n.options,this.events={"summernote.keyup summernote.mouseup summernote.change summernote.scroll":function(){o.update()},"summernote.disable summernote.dialog.shown":function(){o.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&o.$popover[0].contains(e.originalEvent.relatedTarget)||o.hide()}}}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return!k.isEmpty(this.options.popover.link)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-link-popover",callback:function(t){t.find(".popover-content,.note-popover-content").prepend('<span><a target="_blank"></a>&nbsp;</span>')}}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.link),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(){if(this.context.invoke("editor.hasFocus")){var t=this.context.invoke("editor.getLastRange");if(t.isCollapsed()&&t.isOnAnchor()){var n=ht.ancestor(t.sc,ht.isAnchor),o=e()(n).attr("href");this.$popover.find("a").attr("href",o).text(o);var i=ht.posFromPlaceholder(n),r=e()(this.options.container).offset();i.top-=r.top,i.left-=r.left,this.$popover.css({display:"block",left:i.left,top:i.top})}else this.hide()}else this.hide()}},{key:"hide",value:function(){this.$popover.hide()}}])&&ue(n.prototype,o),i&&ue(n,i),t}();function he(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var fe=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t="";if(this.options.maximumImageFileSize){var e=Math.floor(Math.log(this.options.maximumImageFileSize)/Math.log(1024)),n=1*(this.options.maximumImageFileSize/Math.pow(1024,e)).toFixed(2)+" "+" KMGTP"[e]+"B";t="<small>".concat(this.lang.image.maximumFileSize+" : "+n,"</small>")}var o=this.options.dialogsInBody?this.$body:this.options.container,i=['<div class="form-group note-form-group note-group-select-from-files">','<label for="note-dialog-image-file-'+this.options.id+'" class="note-form-label">'+this.lang.image.selectFromFiles+"</label>",'<input id="note-dialog-image-file-'+this.options.id+'" class="note-image-input form-control-file note-form-control note-input" ',' type="file" name="files" accept="'+this.options.acceptImageFileTypes+'" multiple="multiple"/>',t,"</div>",'<div class="form-group note-group-image-url">','<label for="note-dialog-image-url-'+this.options.id+'" class="note-form-label">'+this.lang.image.url+"</label>",'<input id="note-dialog-image-url-'+this.options.id+'" class="note-image-url form-control note-form-control note-input" type="text"/>',"</div>"].join(""),r='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-image-btn",'" value="').concat(this.lang.image.insert,'" disabled>');this.$dialog=this.ui.dialog({title:this.lang.image.insert,fade:this.options.dialogsFade,body:i,footer:r}).render().appendTo(o)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"show",value:function(){var t=this;this.context.invoke("editor.saveRange"),this.showImageDialog().then((function(e){t.ui.hideDialog(t.$dialog),t.context.invoke("editor.restoreRange"),"string"==typeof e?t.options.callbacks.onImageLinkInsert?t.context.triggerEvent("image.link.insert",e):t.context.invoke("editor.insertImage",e):t.context.invoke("editor.insertImagesOrCallback",e)})).fail((function(){t.context.invoke("editor.restoreRange")}))}},{key:"showImageDialog",value:function(){var t=this;return e().Deferred((function(e){var n=t.$dialog.find(".note-image-input"),o=t.$dialog.find(".note-image-url"),i=t.$dialog.find(".note-image-btn");t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),n.replaceWith(n.clone().on("change",(function(t){e.resolve(t.target.files||t.target.value)})).val("")),o.on("input paste propertychange",(function(){t.ui.toggleBtn(i,o.val())})).val(""),f.isSupportTouch||o.trigger("focus"),i.click((function(t){t.preventDefault(),e.resolve(o.val())})),t.bindEnterKey(o,i)})),t.ui.onDialogHidden(t.$dialog,(function(){n.off(),o.off(),i.off(),"pending"===e.state()&&e.reject()})),t.ui.showDialog(t.$dialog)}))}}])&&he(n.prototype,o),i&&he(n,i),t}();function pe(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var me=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.editable=n.layoutInfo.editable[0],this.options=n.options,this.events={"summernote.disable summernote.dialog.shown":function(){o.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&o.$popover[0].contains(e.originalEvent.relatedTarget)||o.hide()}}}var n,o,i;return n=t,o=[{key:"shouldInitialize",value:function(){return!k.isEmpty(this.options.popover.image)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-image-popover"}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.image),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t,n){if(ht.isImg(t)){var o=e()(t).offset(),i=e()(this.options.container).offset(),r={};this.options.popatmouse?(r.left=n.pageX-20,r.top=n.pageY):r=o,r.top-=i.top,r.left-=i.left,this.$popover.css({display:"block",left:r.left,top:r.top})}else this.hide()}},{key:"hide",value:function(){this.$popover.hide()}}],o&&pe(n.prototype,o),i&&pe(n,i),t}();function ve(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ge=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.options=n.options,this.events={"summernote.mousedown":function(t,e){o.update(e.target)},"summernote.keyup summernote.scroll summernote.change":function(){o.update()},"summernote.disable summernote.dialog.shown":function(){o.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&o.$popover[0].contains(e.originalEvent.relatedTarget)||o.hide()}}}var n,o,i;return n=t,o=[{key:"shouldInitialize",value:function(){return!k.isEmpty(this.options.popover.table)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-table-popover"}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.table),f.isFF&&document.execCommand("enableInlineTableEditing",!1,!1),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t){if(this.context.isDisabled())return!1;var n=ht.isCell(t)||ht.isCell(null==t?void 0:t.parentElement);if(n){var o=ht.posFromPlaceholder(t),i=e()(this.options.container).offset();o.top-=i.top,o.left-=i.left,this.$popover.css({display:"block",left:o.left,top:o.top})}else this.hide();return n}},{key:"hide",value:function(){this.$popover.hide()}}],o&&ve(n.prototype,o),i&&ve(n,i),t}();function be(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ye=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,e=['<div class="form-group note-form-group row-fluid">','<label for="note-dialog-video-url-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.video.url,' <small class="text-muted">').concat(this.lang.video.providers,"</small></label>"),'<input id="note-dialog-video-url-'.concat(this.options.id,'" class="note-video-url form-control note-form-control note-input" type="text"/>'),"</div>"].join(""),n='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-video-btn",'" value="').concat(this.lang.video.insert,'" disabled>');this.$dialog=this.ui.dialog({title:this.lang.video.insert,fade:this.options.dialogsFade,body:e,footer:n}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"createVideoNode",value:function(t){var n,o=t.match(/\/\/(?:(?:www|m)\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))([\w|-]{11})(?:(?:[\?&]t=)(\S+))?$/),i=t.match(/(?:\.|\/\/)drive\.google\.com\/file\/d\/(.[a-zA-Z0-9_-]*)\/view/),r=t.match(/(?:www\.|\/\/)instagram\.com\/p\/(.[a-zA-Z0-9_-]*)/),a=t.match(/\/\/vine\.co\/v\/([a-zA-Z0-9]+)/),s=t.match(/\/\/(player\.)?vimeo\.com\/([a-z]*\/)*(\d+)[?]?.*/),l=t.match(/.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/),c=t.match(/\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/),u=t.match(/\/\/(.*)\/videos\/watch\/([^?]*)(?:\?(?:start=(\w*))?(?:&stop=(\w*))?(?:&loop=([10]))?(?:&autoplay=([10]))?(?:&muted=([10]))?)?/),d=t.match(/\/\/v\.qq\.com.*?vid=(.+)/),h=t.match(/\/\/v\.qq\.com\/x?\/?(page|cover).*?\/([^\/]+)\.html\??.*/),f=t.match(/^.+.(mp4|m4v)$/),p=t.match(/^.+.(ogg|ogv)$/),m=t.match(/^.+.(webm)$/),v=t.match(/(?:www\.|\/\/)facebook\.com\/([^\/]+)\/videos\/([0-9]+)/);if(o&&11===o[1].length){var g=o[1],b=0;if(void 0!==o[2]){var y=o[2].match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/);if(y)for(var k=[3600,60,1],w=0,C=k.length;w<C;w++)b+=void 0!==y[w+1]?k[w]*parseInt(y[w+1],10):0}n=e()("<iframe>").attr("frameborder",0).attr("src","//www.youtube.com/embed/"+g+(b>0?"?start="+b:"")).attr("width","640").attr("height","360")}else if(i&&i[0].length)n=e()("<iframe>").attr("frameborder",0).attr("src","https://drive.google.com/file/d/"+i[1]+"/preview").attr("width","640").attr("height","480");else if(r&&r[0].length)n=e()("<iframe>").attr("frameborder",0).attr("src","https://instagram.com/p/"+r[1]+"/embed/").attr("width","612").attr("height","710").attr("scrolling","no").attr("allowtransparency","true");else if(a&&a[0].length)n=e()("<iframe>").attr("frameborder",0).attr("src",a[0]+"/embed/simple").attr("width","600").attr("height","600").attr("class","vine-embed");else if(s&&s[3].length)n=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("src","//player.vimeo.com/video/"+s[3]).attr("width","640").attr("height","360");else if(l&&l[2].length)n=e()("<iframe>").attr("frameborder",0).attr("src","//www.dailymotion.com/embed/video/"+l[2]).attr("width","640").attr("height","360");else if(c&&c[1].length)n=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("height","498").attr("width","510").attr("src","//player.youku.com/embed/"+c[1]);else if(u&&u[0].length){var x=0;"undefined"!==u[2]&&(x=u[2]);var S=0;"undefined"!==u[3]&&(S=u[3]);var T=0;"undefined"!==u[4]&&(T=u[4]);var E=0;"undefined"!==u[5]&&(E=u[5]);var I=0;"undefined"!==u[6]&&(I=u[6]),n=e()('<iframe allowfullscreen sandbox="allow-same-origin allow-scripts allow-popups">').attr("frameborder",0).attr("src","//"+u[1]+"/videos/embed/"+u[2]+"?loop="+T+"&autoplay="+E+"&muted="+I+(x>0?"&start="+x:"")+(S>0?"&end="+b:"")).attr("width","560").attr("height","315")}else if(d&&d[1].length||h&&h[2].length){var $=d&&d[1].length?d[1]:h[2];n=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("height","310").attr("width","500").attr("src","https://v.qq.com/txp/iframe/player.html?vid="+$+"&amp;auto=0")}else if(f||p||m)n=e()("<video controls>").attr("src",t).attr("width","640").attr("height","360");else{if(!v||!v[0].length)return!1;n=e()("<iframe>").attr("frameborder",0).attr("src","https://www.facebook.com/plugins/video.php?href="+encodeURIComponent(v[0])+"&show_text=0&width=560").attr("width","560").attr("height","301").attr("scrolling","no").attr("allowtransparency","true")}return n.addClass("note-video-clip"),n[0]}},{key:"show",value:function(){var t=this,e=this.context.invoke("editor.getSelectedText");this.context.invoke("editor.saveRange"),this.showVideoDialog(e).then((function(e){t.ui.hideDialog(t.$dialog),t.context.invoke("editor.restoreRange");var n=t.createVideoNode(e);n&&t.context.invoke("editor.insertNode",n)})).fail((function(){t.context.invoke("editor.restoreRange")}))}},{key:"showVideoDialog",value:function(){var t=this;return e().Deferred((function(e){var n=t.$dialog.find(".note-video-url"),o=t.$dialog.find(".note-video-btn");t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),n.on("input paste propertychange",(function(){t.ui.toggleBtn(o,n.val())})),f.isSupportTouch||n.trigger("focus"),o.click((function(t){t.preventDefault(),e.resolve(n.val())})),t.bindEnterKey(n,o)})),t.ui.onDialogHidden(t.$dialog,(function(){n.off(),o.off(),"pending"===e.state()&&e.reject()})),t.ui.showDialog(t.$dialog)}))}}])&&be(n.prototype,o),i&&be(n,i),t}();function ke(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var we=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo}var n,o,i;return n=t,o=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,e=['<p class="text-center">','<a href="http://summernote.org/" target="_blank" rel="noopener noreferrer">Summernote 0.8.20</a> · ','<a href="https://github.com/summernote/summernote" target="_blank" rel="noopener noreferrer">Project</a> · ','<a href="https://github.com/summernote/summernote/issues" target="_blank" rel="noopener noreferrer">Issues</a>',"</p>"].join("");this.$dialog=this.ui.dialog({title:this.lang.options.help,fade:this.options.dialogsFade,body:this.createShortcutList(),footer:e,callback:function(t){t.find(".modal-body,.note-modal-body").css({"max-height":300,overflow:"scroll"})}}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"createShortcutList",value:function(){var t=this,n=this.options.keyMap[f.isMac?"mac":"pc"];return Object.keys(n).map((function(o){var i=n[o],r=e()('<div><div class="help-list-item"></div></div>');return r.append(e()("<label><kbd>"+o+"</kdb></label>").css({width:180,"margin-right":10})).append(e()("<span></span>").html(t.context.memo("help."+i)||i)),r.html()})).join("")}},{key:"showHelpDialog",value:function(){var t=this;return e().Deferred((function(e){t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),e.resolve()})),t.ui.showDialog(t.$dialog)})).promise()}},{key:"show",value:function(){var t=this;this.context.invoke("editor.saveRange"),this.showHelpDialog().then((function(){t.context.invoke("editor.restoreRange")}))}}],o&&ke(n.prototype,o),i&&ke(n,i),t}();function Ce(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var xe=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.options=n.options,this.hidable=!0,this.onContextmenu=!1,this.pageX=null,this.pageY=null,this.events={"summernote.contextmenu":function(t){o.options.editing&&(t.preventDefault(),t.stopPropagation(),o.onContextmenu=!0,o.update(!0))},"summernote.mousedown":function(t,e){o.pageX=e.pageX,o.pageY=e.pageY},"summernote.keyup summernote.mouseup summernote.scroll":function(t,e){o.options.editing&&!o.onContextmenu&&(o.pageX=e.pageX,o.pageY=e.pageY,o.update()),o.onContextmenu=!1},"summernote.disable summernote.change summernote.dialog.shown summernote.blur":function(){o.hide()},"summernote.focusout":function(){o.$popover.is(":active,:focus")||o.hide()}}}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return this.options.airMode&&!k.isEmpty(this.options.popover.air)}},{key:"initialize",value:function(){var t=this;this.$popover=this.ui.popover({className:"note-air-popover"}).render().appendTo(this.options.container);var e=this.$popover.find(".popover-content");this.context.invoke("buttons.build",e,this.options.popover.air),this.$popover.on("mousedown",(function(){t.hidable=!1})),this.$popover.on("mouseup",(function(){t.hidable=!0}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t){var n=this.context.invoke("editor.currentStyle");if(!n.range||n.range.isCollapsed()&&!t)this.hide();else{var o={left:this.pageX,top:this.pageY},i=e()(this.options.container).offset();o.top-=i.top,o.left-=i.left,this.$popover.css({display:"block",left:Math.max(o.left,0)+-5,top:o.top+5}),this.context.invoke("buttons.updateCurrentStyle",this.$popover)}}},{key:"updateCodeview",value:function(t){this.ui.toggleBtnActive(this.$popover.find(".btn-codeview"),t),t&&this.hide()}},{key:"hide",value:function(){this.hidable&&this.$popover.hide()}}])&&Ce(n.prototype,o),i&&Ce(n,i),t}();function Se(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Te=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$editable=n.layoutInfo.editable,this.options=n.options,this.hint=this.options.hint||[],this.direction=this.options.hintDirection||"bottom",this.hints=Array.isArray(this.hint)?this.hint:[this.hint],this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||o.handleKeyup(e)},"summernote.keydown":function(t,e){o.handleKeydown(e)},"summernote.disable summernote.dialog.shown summernote.blur":function(){o.hide()}}}var n,o,i;return n=t,o=[{key:"shouldInitialize",value:function(){return this.hints.length>0}},{key:"initialize",value:function(){var t=this;this.lastWordRange=null,this.matchingWord=null,this.$popover=this.ui.popover({className:"note-hint-popover",hideArrow:!0,direction:""}).render().appendTo(this.options.container),this.$popover.hide(),this.$content=this.$popover.find(".popover-content,.note-popover-content"),this.$content.on("click",".note-hint-item",(function(n){t.$content.find(".active").removeClass("active"),e()(n.currentTarget).addClass("active"),t.replace()})),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"selectItem",value:function(t){this.$content.find(".active").removeClass("active"),t.addClass("active"),this.$content[0].scrollTop=t[0].offsetTop-this.$content.innerHeight()/2}},{key:"moveDown",value:function(){var t=this.$content.find(".note-hint-item.active"),e=t.next();if(e.length)this.selectItem(e);else{var n=t.parent().next();n.length||(n=this.$content.find(".note-hint-group").first()),this.selectItem(n.find(".note-hint-item").first())}}},{key:"moveUp",value:function(){var t=this.$content.find(".note-hint-item.active"),e=t.prev();if(e.length)this.selectItem(e);else{var n=t.parent().prev();n.length||(n=this.$content.find(".note-hint-group").last()),this.selectItem(n.find(".note-hint-item").last())}}},{key:"replace",value:function(){var t=this.$content.find(".note-hint-item.active");if(t.length){var n=this.nodeFromItem(t);if(null!==this.matchingWord&&0===this.matchingWord.length)this.lastWordRange.so=this.lastWordRange.eo;else if(null!==this.matchingWord&&this.matchingWord.length>0&&!this.lastWordRange.isCollapsed()){var o=this.lastWordRange.eo-this.lastWordRange.so-this.matchingWord.length;o>0&&(this.lastWordRange.so+=o)}if(this.lastWordRange.insertNode(n),"next"===this.options.hintSelect){var i=document.createTextNode("");e()(n).after(i),yt.createFromNodeBefore(i).select()}else yt.createFromNodeAfter(n).select();this.lastWordRange=null,this.hide(),this.context.invoke("editor.focus"),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}}},{key:"nodeFromItem",value:function(t){var e=this.hints[t.data("index")],n=t.data("item"),o=e.content?e.content(n):n;return"string"==typeof o&&(o=ht.createText(o)),o}},{key:"createItemTemplates",value:function(t,n){var o=this.hints[t];return n.map((function(n){var i=e()('<div class="note-hint-item"></div>');return i.append(o.template?o.template(n):n+""),i.data({index:t,item:n}),i}))}},{key:"handleKeydown",value:function(t){this.$popover.is(":visible")&&(t.keyCode===wt.code.ENTER?(t.preventDefault(),this.replace()):t.keyCode===wt.code.UP?(t.preventDefault(),this.moveUp()):t.keyCode===wt.code.DOWN&&(t.preventDefault(),this.moveDown()))}},{key:"searchKeyword",value:function(t,e,n){var o=this.hints[t];if(o&&o.match.test(e)&&o.search){var i=o.match.exec(e);this.matchingWord=i[0],o.search(i[1],n)}else n()}},{key:"createGroup",value:function(t,n){var o=this,i=e()('<div class="note-hint-group note-hint-group-'+t+'"></div>');return this.searchKeyword(t,n,(function(e){(e=e||[]).length&&(i.html(o.createItemTemplates(t,e)),o.show())})),i}},{key:"handleKeyup",value:function(t){var n=this;if(!k.contains([wt.code.ENTER,wt.code.UP,wt.code.DOWN],t.keyCode)){var o,i,r=this.context.invoke("editor.getLastRange");if("words"===this.options.hintMode){if(o=r.getWordsRange(r),i=o.toString(),this.hints.forEach((function(t){if(t.match.test(i))return o=r.getWordsMatchRange(t.match),!1})),!o)return void this.hide();i=o.toString()}else o=r.getWordRange(),i=o.toString();if(this.hints.length&&i){this.$content.empty();var a=m.rect2bnd(k.last(o.getClientRects())),s=e()(this.options.container).offset();a&&(a.top-=s.top,a.left-=s.left,this.$popover.hide(),this.lastWordRange=o,this.hints.forEach((function(t,e){t.match.test(i)&&n.createGroup(e,i).appendTo(n.$content)})),this.$content.find(".note-hint-item:first").addClass("active"),"top"===this.direction?this.$popover.css({left:a.left,top:a.top-this.$popover.outerHeight()-5}):this.$popover.css({left:a.left,top:a.top+a.height+5}))}else this.hide()}}},{key:"show",value:function(){this.$popover.show()}},{key:"hide",value:function(){this.$popover.hide()}}],o&&Se(n.prototype,o),i&&Se(n,i),t}();function Ee(t){return Ee="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ee(t)}function Ie(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}e().summernote=e().extend(e().summernote,{version:"0.8.20",plugins:{},dom:ht,range:yt,lists:k,options:{langInfo:e().summernote.lang["en-US"],editing:!0,modules:{editor:Ft,clipboard:Ht,dropzone:Bt,codeview:jt,statusbar:Kt,fullscreen:qt,handle:Gt,hintPopover:Te,autoLink:Qt,autoSync:Jt,autoReplace:ee,placeholder:oe,buttons:re,toolbar:se,linkDialog:ce,linkPopover:de,imageDialog:fe,imagePopover:me,tablePopover:ge,videoDialog:ye,helpDialog:we,airPopover:xe},buttons:{},lang:"en-US",followingToolbar:!1,toolbarPosition:"top",otherStaticBar:"",codeviewKeepButton:!1,toolbar:[["style",["style"]],["font",["bold","underline","clear"]],["fontname",["fontname"]],["color",["color"]],["para",["ul","ol","paragraph"]],["table",["table"]],["insert",["link","picture","video"]],["view",["fullscreen","codeview","help"]]],popatmouse:!0,popover:{image:[["resize",["resizeFull","resizeHalf","resizeQuarter","resizeNone"]],["float",["floatLeft","floatRight","floatNone"]],["remove",["removeMedia"]]],link:[["link",["linkDialogShow","unlink"]]],table:[["add",["addRowDown","addRowUp","addColLeft","addColRight"]],["delete",["deleteRow","deleteCol","deleteTable"]]],air:[["color",["color"]],["font",["bold","underline","clear"]],["para",["ul","paragraph"]],["table",["table"]],["insert",["link","picture"]],["view",["fullscreen","codeview"]]]},airMode:!1,overrideContextMenu:!1,width:null,height:null,linkTargetBlank:!0,useProtocol:!0,defaultProtocol:"http://",focus:!1,tabDisabled:!1,tabSize:4,styleWithCSS:!1,shortcuts:!0,textareaAutoSync:!0,tooltip:"auto",container:null,maxTextLength:0,blockquoteBreakingLevel:2,spellCheck:!0,disableGrammar:!1,placeholder:null,inheritPlaceholder:!1,recordEveryKeystroke:!1,historyLimit:200,showDomainOnlyForAutolink:!1,hintMode:"word",hintSelect:"after",hintDirection:"bottom",styleTags:["p","blockquote","pre","h1","h2","h3","h4","h5","h6"],fontNames:["Arial","Arial Black","Comic Sans MS","Courier New","Helvetica Neue","Helvetica","Impact","Lucida Grande","Tahoma","Times New Roman","Verdana"],fontNamesIgnoreCheck:[],addDefaultFonts:!0,fontSizes:["8","9","10","11","12","14","18","24","36"],fontSizeUnits:["px","pt"],colors:[["#000000","#424242","#636363","#9C9C94","#CEC6CE","#EFEFEF","#F7F7F7","#FFFFFF"],["#FF0000","#FF9C00","#FFFF00","#00FF00","#00FFFF","#0000FF","#9C00FF","#FF00FF"],["#F7C6CE","#FFE7CE","#FFEFC6","#D6EFD6","#CEDEE7","#CEE7F7","#D6D6E7","#E7D6DE"],["#E79C9C","#FFC69C","#FFE79C","#B5D6A5","#A5C6CE","#9CC6EF","#B5A5D6","#D6A5BD"],["#E76363","#F7AD6B","#FFD663","#94BD7B","#73A5AD","#6BADDE","#8C7BC6","#C67BA5"],["#CE0000","#E79439","#EFC631","#6BA54A","#4A7B8C","#3984C6","#634AA5","#A54A7B"],["#9C0000","#B56308","#BD9400","#397B21","#104A5A","#085294","#311873","#731842"],["#630000","#7B3900","#846300","#295218","#083139","#003163","#21104A","#4A1031"]],colorsName:[["Black","Tundora","Dove Gray","Star Dust","Pale Slate","Gallery","Alabaster","White"],["Red","Orange Peel","Yellow","Green","Cyan","Blue","Electric Violet","Magenta"],["Azalea","Karry","Egg White","Zanah","Botticelli","Tropical Blue","Mischka","Twilight"],["Tonys Pink","Peach Orange","Cream Brulee","Sprout","Casper","Perano","Cold Purple","Careys Pink"],["Mandy","Rajah","Dandelion","Olivine","Gulf Stream","Viking","Blue Marguerite","Puce"],["Guardsman Red","Fire Bush","Golden Dream","Chelsea Cucumber","Smalt Blue","Boston Blue","Butterfly Bush","Cadillac"],["Sangria","Mai Tai","Buddha Gold","Forest Green","Eden","Venice Blue","Meteorite","Claret"],["Rosewood","Cinnamon","Olive","Parsley","Tiber","Midnight Blue","Valentino","Loulou"]],colorButton:{foreColor:"#000000",backColor:"#FFFF00"},lineHeights:["1.0","1.2","1.4","1.5","1.6","1.8","2.0","3.0"],tableClassName:"table table-bordered",insertTableMaxSize:{col:10,row:10},dialogsInBody:!1,dialogsFade:!1,maximumImageFileSize:null,acceptImageFileTypes:"image/*",callbacks:{onBeforeCommand:null,onBlur:null,onBlurCodeview:null,onChange:null,onChangeCodeview:null,onDialogShown:null,onEnter:null,onFocus:null,onImageLinkInsert:null,onImageUpload:null,onImageUploadError:null,onInit:null,onKeydown:null,onKeyup:null,onMousedown:null,onMouseup:null,onPaste:null,onScroll:null},codemirror:{mode:"text/html",htmlMode:!0,lineNumbers:!0},codeviewFilter:!0,codeviewFilterRegex:/<\/*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|ilayer|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|t(?:itle|extarea)|xml)[^>]*?>/gi,codeviewIframeFilter:!0,codeviewIframeWhitelistSrc:[],codeviewIframeWhitelistSrcBase:["www.youtube.com","www.youtube-nocookie.com","www.facebook.com","vine.co","instagram.com","player.vimeo.com","www.dailymotion.com","player.youku.com","jumpingbean.tv","v.qq.com"],keyMap:{pc:{ESC:"escape",ENTER:"insertParagraph","CTRL+Z":"undo","CTRL+Y":"redo",TAB:"tab","SHIFT+TAB":"untab","CTRL+B":"bold","CTRL+I":"italic","CTRL+U":"underline","CTRL+SHIFT+S":"strikethrough","CTRL+BACKSLASH":"removeFormat","CTRL+SHIFT+L":"justifyLeft","CTRL+SHIFT+E":"justifyCenter","CTRL+SHIFT+R":"justifyRight","CTRL+SHIFT+J":"justifyFull","CTRL+SHIFT+NUM7":"insertUnorderedList","CTRL+SHIFT+NUM8":"insertOrderedList","CTRL+LEFTBRACKET":"outdent","CTRL+RIGHTBRACKET":"indent","CTRL+NUM0":"formatPara","CTRL+NUM1":"formatH1","CTRL+NUM2":"formatH2","CTRL+NUM3":"formatH3","CTRL+NUM4":"formatH4","CTRL+NUM5":"formatH5","CTRL+NUM6":"formatH6","CTRL+ENTER":"insertHorizontalRule","CTRL+K":"linkDialog.show"},mac:{ESC:"escape",ENTER:"insertParagraph","CMD+Z":"undo","CMD+SHIFT+Z":"redo",TAB:"tab","SHIFT+TAB":"untab","CMD+B":"bold","CMD+I":"italic","CMD+U":"underline","CMD+SHIFT+S":"strikethrough","CMD+BACKSLASH":"removeFormat","CMD+SHIFT+L":"justifyLeft","CMD+SHIFT+E":"justifyCenter","CMD+SHIFT+R":"justifyRight","CMD+SHIFT+J":"justifyFull","CMD+SHIFT+NUM7":"insertUnorderedList","CMD+SHIFT+NUM8":"insertOrderedList","CMD+LEFTBRACKET":"outdent","CMD+RIGHTBRACKET":"indent","CMD+NUM0":"formatPara","CMD+NUM1":"formatH1","CMD+NUM2":"formatH2","CMD+NUM3":"formatH3","CMD+NUM4":"formatH4","CMD+NUM5":"formatH5","CMD+NUM6":"formatH6","CMD+ENTER":"insertHorizontalRule","CMD+K":"linkDialog.show"}},icons:{align:"note-icon-align",alignCenter:"note-icon-align-center",alignJustify:"note-icon-align-justify",alignLeft:"note-icon-align-left",alignRight:"note-icon-align-right",rowBelow:"note-icon-row-below",colBefore:"note-icon-col-before",colAfter:"note-icon-col-after",rowAbove:"note-icon-row-above",rowRemove:"note-icon-row-remove",colRemove:"note-icon-col-remove",indent:"note-icon-align-indent",outdent:"note-icon-align-outdent",arrowsAlt:"note-icon-arrows-alt",bold:"note-icon-bold",caret:"note-icon-caret",circle:"note-icon-circle",close:"note-icon-close",code:"note-icon-code",eraser:"note-icon-eraser",floatLeft:"note-icon-float-left",floatRight:"note-icon-float-right",font:"note-icon-font",frame:"note-icon-frame",italic:"note-icon-italic",link:"note-icon-link",unlink:"note-icon-chain-broken",magic:"note-icon-magic",menuCheck:"note-icon-menu-check",minus:"note-icon-minus",orderedlist:"note-icon-orderedlist",pencil:"note-icon-pencil",picture:"note-icon-picture",question:"note-icon-question",redo:"note-icon-redo",rollback:"note-icon-rollback",square:"note-icon-square",strikethrough:"note-icon-strikethrough",subscript:"note-icon-subscript",superscript:"note-icon-superscript",table:"note-icon-table",textHeight:"note-icon-text-height",trash:"note-icon-trash",underline:"note-icon-underline",undo:"note-icon-undo",unorderedlist:"note-icon-unorderedlist",video:"note-icon-video"}}});var $e=function(){function t(e,n,o,i){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.markup=e,this.children=n,this.options=o,this.callback=i}var n,o,i;return n=t,(o=[{key:"render",value:function(t){var n=e()(this.markup);if(this.options&&this.options.contents&&n.html(this.options.contents),this.options&&this.options.className&&n.addClass(this.options.className),this.options&&this.options.data&&e().each(this.options.data,(function(t,e){n.attr("data-"+t,e)})),this.options&&this.options.click&&n.on("click",this.options.click),this.children){var o=n.find(".note-children-container");this.children.forEach((function(t){t.render(o.length?o:n)}))}return this.callback&&this.callback(n,this.options),this.options&&this.options.callback&&this.options.callback(n),t&&t.append(n),n}}])&&Ie(n.prototype,o),i&&Ie(n,i),t}();const Ne=function(t,e){return function(){var n="object"===Ee(arguments[1])?arguments[1]:arguments[0],o=Array.isArray(arguments[0])?arguments[0]:[];return n&&n.children&&(o=n.children),new $e(t,o,n,e)}};function Pe(t){return Pe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Pe(t)}var Re=Ne('<div class="note-editor note-frame card"></div>'),Le=Ne('<div class="note-toolbar card-header" role="toolbar"></div>'),Ae=Ne('<div class="note-editing-area"></div>'),Fe=Ne('<textarea class="note-codable" aria-multiline="true"></textarea>'),De=Ne('<div class="note-editable card-block" contentEditable="true" role="textbox" aria-multiline="true"></div>'),He=Ne(['<output class="note-status-output" role="status" aria-live="polite"></output>','<div class="note-statusbar" role="status">','<div class="note-resizebar" aria-label="Resize">','<div class="note-icon-bar"></div>','<div class="note-icon-bar"></div>','<div class="note-icon-bar"></div>',"</div>","</div>"].join("")),ze=Ne('<div class="note-editor note-airframe"></div>'),Be=Ne(['<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>','<output class="note-status-output" role="status" aria-live="polite"></output>'].join("")),Me=Ne('<div class="note-btn-group btn-group"></div>'),Oe=Ne('<div class="note-dropdown-menu dropdown-menu" role="list"></div>',(function(t,e){var n=Array.isArray(e.items)?e.items.map((function(t){var n="string"==typeof t?t:t.value||"",o=e.template?e.template(t):t,i="object"===Pe(t)?t.option:void 0;return'<a class="dropdown-item" href="#" '+('data-value="'+n+'"'+(void 0!==i?' data-option="'+i+'"':""))+' role="listitem" aria-label="'+n+'">'+o+"</a>"})).join(""):e.items;t.html(n).attr({"aria-label":e.title}),e&&e.codeviewKeepButton&&t.addClass("note-codeview-keep")})),Ue=function(t){return t},je=Ne('<div class="note-dropdown-menu dropdown-menu note-check" role="list"></div>',(function(t,e){var n=Array.isArray(e.items)?e.items.map((function(t){var n="string"==typeof t?t:t.value||"",o=e.template?e.template(t):t;return'<a class="dropdown-item" href="#" data-value="'+n+'" role="listitem" aria-label="'+t+'">'+qe(e.checkClassName)+" "+o+"</a>"})).join(""):e.items;t.html(n).attr({"aria-label":e.title}),e&&e.codeviewKeepButton&&t.addClass("note-codeview-keep")})),We=Ne('<div class="modal note-modal" aria-hidden="false" tabindex="-1" role="dialog"></div>',(function(t,e){e.fade&&t.addClass("fade"),t.attr({"aria-label":e.title}),t.html(['<div class="modal-dialog">','<div class="modal-content">',e.title?'<div class="modal-header"><h4 class="modal-title">'+e.title+'</h4><button type="button" class="close" data-dismiss="modal" aria-label="Close" aria-hidden="true">&times;</button></div>':"",'<div class="modal-body">'+e.body+"</div>",e.footer?'<div class="modal-footer">'+e.footer+"</div>":"","</div>","</div>"].join(""))})),Ke=Ne(['<div class="note-popover popover in">','<div class="arrow"></div>','<div class="popover-content note-children-container"></div>',"</div>"].join(""),(function(t,e){var n=void 0!==e.direction?e.direction:"bottom";t.addClass(n),e.hideArrow&&t.find(".arrow").hide()})),Ve=Ne('<div class="form-check"></div>',(function(t,e){t.html(['<label class="form-check-label"'+(e.id?' for="note-'+e.id+'"':"")+">",'<input type="checkbox" class="form-check-input"'+(e.id?' id="note-'+e.id+'"':""),e.checked?" checked":"",' aria-label="'+(e.text?e.text:"")+'"',' aria-checked="'+(e.checked?"true":"false")+'"/>'," "+(e.text?e.text:"")+"</label>"].join(""))})),qe=function(t,e){return t.match(/^</)?t:"<"+(e=e||"i")+' class="'+t+'"></'+e+">"};e().summernote=e().extend(e().summernote,{ui_template:function(t){return{editor:Re,toolbar:Le,editingArea:Ae,codable:Fe,editable:De,statusbar:He,airEditor:ze,airEditable:Be,buttonGroup:Me,dropdown:Oe,dropdownButtonContents:Ue,dropdownCheck:je,dialog:We,popover:Ke,icon:qe,checkbox:Ve,options:t,palette:function(e,n){return Ne('<div class="note-color-palette"></div>',(function(e,n){for(var o=[],i=0,r=n.colors.length;i<r;i++){for(var a=n.eventName,s=n.colors[i],l=n.colorsName[i],c=[],u=0,d=s.length;u<d;u++){var h=s[u],f=l[u];c.push(['<button type="button" class="note-color-btn"','style="background-color:',h,'" ','data-event="',a,'" ','data-value="',h,'" ','title="',f,'" ','aria-label="',f,'" ','data-toggle="button" tabindex="-1"></button>'].join(""))}o.push('<div class="note-color-row">'+c.join("")+"</div>")}e.html(o.join("")),n.tooltip&&e.find(".note-color-btn").tooltip({container:n.container||t.container,trigger:"hover",placement:"bottom"})}))(e,n)},button:function(n,o){return Ne('<button type="button" class="note-btn btn btn-light btn-sm" tabindex="-1"></button>',(function(n,o){o&&o.tooltip&&n.attr({title:o.tooltip,"aria-label":o.tooltip}).tooltip({container:o.container||t.container,trigger:"hover",placement:"bottom"}).on("click",(function(t){e()(t.currentTarget).tooltip("hide")})),o&&o.codeviewButton&&n.addClass("note-codeview-keep")}))(n,o)},toggleBtn:function(t,e){t.toggleClass("disabled",!e),t.attr("disabled",!e)},toggleBtnActive:function(t,e){t.toggleClass("active",e)},onDialogShown:function(t,e){t.one("shown.bs.modal",e)},onDialogHidden:function(t,e){t.one("hidden.bs.modal",e)},showDialog:function(t){t.modal("show")},hideDialog:function(t){t.modal("hide")},createLayout:function(e){var n=(t.airMode?ze([Ae([Fe(),Be()])]):"bottom"===t.toolbarPosition?Re([Ae([Fe(),De()]),Le(),He()]):Re([Le(),Ae([Fe(),De()]),He()])).render();return n.insertAfter(e),{note:e,editor:n,toolbar:n.find(".note-toolbar"),editingArea:n.find(".note-editing-area"),editable:n.find(".note-editable"),codable:n.find(".note-codable"),statusbar:n.find(".note-statusbar")}},removeLayout:function(t,e){t.html(e.editable.html()),e.editor.remove(),t.show()}}},interface:"bs4"}),e().summernote.options.styleTags=["p",{title:"Blockquote",tag:"blockquote",className:"blockquote",value:"blockquote"},"pre","h1","h2","h3","h4","h5","h6"]})(),i})()}));
294coder/Efficient-MIF
5,674
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/linesearch/linesearch_adaptive.m
function [stepsize, newx, newkey, lsstats] = ... linesearch_adaptive(problem, x, d, f0, df0, options, storedb, key) % Adaptive line search algorithm (step size selection) for descent methods. % % function [stepsize, newx, newkey, lsstats] = % linesearch_adaptive(problem, x, d, f0, df0, options, storedb, key) % % Adaptive linesearch algorithm for descent methods, based on a simple % backtracking method. Contrary to linesearch.m, this function is not % invariant under rescaling of the search direction d. These two line % search methods vary mainly in their strategy to pick the initial step % size. % % Below, the step is constructed as alpha*d, and the step size is the norm % of that vector, thus: stepsize = alpha*norm_d. The step is executed by % retracting the vector alpha*d from the current point x, giving newx. % % This line-search may create and maintain a structure called lsmem inside % storedb.internal. This gives the linesearch the opportunity to remember % what happened in the previous calls. This is typically used to make a % first guess at the step size, based on previous events. % % Inputs/Outputs : see help for linesearch % % See also: steepestdescent conjugategradients linesearch % This file is part of Manopt: www.manopt.org. % Original author: Bamdev Mishra, Dec. 30, 2012. % Contributors: Nicolas Boumal % Change log: % % Sept. 13, 2013 (NB) : % The automatic direction reversal feature was removed (it triggered % when df0 > 0). Direction reversal is a decision that needs to be % made by the solver, so it can know about it. % % Nov. 7, 2013 (NB) : % The whole function has been recoded to mimick more closely the new % version of linesearch.m. The parameters are available through the % options structure passed to the solver and have the same names and % same meaning as for the base linesearch. The information is logged % more reliably. % % April 3, 2015 (NB): % Works with the new StoreDB class system. % % April 8, 2015 (NB): % Got rid of lsmem input/output: now maintained in storedb.internal. % Allow omission of the key, and even of storedb. if ~exist('key', 'var') if ~exist('storedb', 'var') storedb = StoreDB(); end key = storedb.getNewKey(); end % Backtracking default parameters. These can be overwritten in the % options structure which is passed to the solver. default_options.ls_contraction_factor = .5; default_options.ls_suff_decr = .5; default_options.ls_max_steps = 10; default_options.ls_initial_stepsize = 1; if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(default_options, options); contraction_factor = options.ls_contraction_factor; suff_decr = options.ls_suff_decr; max_ls_steps = options.ls_max_steps; initial_stepsize = options.ls_initial_stepsize; % Compute the norm of the search direction. norm_d = problem.M.norm(x, d); % If this is not the first iteration, then lsmem should have been % filled with a suggestion for the initial step. if isfield(storedb.internal, 'lsmem') lsmem = storedb.internal.lsmem; if isfield(lsmem, 'init_alpha') % Pick initial step size based on where we were last time, alpha = lsmem.init_alpha; end % Otherwise, fall back to a user supplied suggestion. else alpha = initial_stepsize / norm_d; end % Make the chosen step and compute the cost there. newx = problem.M.retr(x, d, alpha); newkey = storedb.getNewKey(); newf = getCost(problem, newx, storedb, newkey); cost_evaluations = 1; % Backtrack while the Armijo criterion is not satisfied while newf > f0 + suff_decr*alpha*df0 % Reduce the step size, alpha = contraction_factor * alpha; % and look closer down the line newx = problem.M.retr(x, d, alpha); newkey = storedb.getNewKey(); newf = getCost(problem, newx, storedb, newkey); cost_evaluations = cost_evaluations + 1; % Make sure we don't run out of budget if cost_evaluations >= max_ls_steps break; end end % If we got here without obtaining a decrease, we reject the step. if newf > f0 alpha = 0; newx = x; newkey = key; newf = f0; %#ok<NASGU> end % As seen outside this function, stepsize is the size of the vector we % retract to make the step from x to newx. Since the step is alpha*d: stepsize = alpha * norm_d; % Fill lsmem with a suggestion for what the next initial step size % trial should be. On average we intend to do only one extra cost % evaluation. Notice how the suggestion is not about stepsize but about % alpha. This is the reason why this line search is not invariant under % rescaling of the search direction d. switch cost_evaluations case 1 % If things go very well, push your luck. init_alpha = 2 * alpha; case 2 % If things go reasonably well, try to keep pace. init_alpha = alpha; otherwise % If we backtracked a lot, the new stepsize is probably quite % small: try to recover. init_alpha = 2 * alpha; end storedb.internal.lsmem.init_alpha = init_alpha; % Return some statistics also, for possible analysis. lsstats.costevals = cost_evaluations; lsstats.stepsize = stepsize; lsstats.alpha = alpha; end
2881099/FreeSql.AdminLTE
38,067
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-lite.css
/*! * * Super simple WYSIWYG editor v0.8.20 * https://summernote.org * * * Copyright 2013- Alan Hong and contributors * Summernote may be freely distributed under the MIT license. * * Date: 2021-10-14T21:15Z * */ @font-face { font-family: "summernote"; font-style: normal; font-weight: 400; font-display: auto; src: url("./font/summernote.eot?#iefix") format("embedded-opentype"), url("./font/summernote.woff2") format("woff2"), url("./font/summernote.woff") format("woff"), url("./font/summernote.ttf") format("truetype"); } [class^=note-icon]:before, [class*=" note-icon"]:before { display: inline-block; font-family: "summernote"; font-style: normal; font-size: inherit; text-decoration: inherit; text-rendering: auto; text-transform: none; vertical-align: middle; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; speak: none; } .note-icon-fw { text-align: center; width: 1.25em; } .note-icon-border { border: solid 0.08em #eee; border-radius: 0.1em; padding: 0.2em 0.25em 0.15em; } .note-icon-pull-left { float: left; } .note-icon-pull-right { float: right; } .note-icon.note-icon-pull-left { margin-right: 0.3em; } .note-icon.note-icon-pull-right { margin-left: 0.3em; } .note-icon-align::before { content: "\ea01"; } .note-icon-align-center::before { content: "\ea02"; } .note-icon-align-indent::before { content: "\ea03"; } .note-icon-align-justify::before { content: "\ea04"; } .note-icon-align-left::before { content: "\ea05"; } .note-icon-align-outdent::before { content: "\ea06"; } .note-icon-align-right::before { content: "\ea07"; } .note-icon-arrow-circle-down::before { content: "\ea08"; } .note-icon-arrow-circle-left::before { content: "\ea09"; } .note-icon-arrow-circle-right::before { content: "\ea0a"; } .note-icon-arrow-circle-up::before { content: "\ea0b"; } .note-icon-arrows-alt::before { content: "\ea0c"; } .note-icon-arrows-h::before { content: "\ea0d"; } .note-icon-arrows-v::before { content: "\ea0e"; } .note-icon-bold::before { content: "\ea0f"; } .note-icon-caret::before { content: "\ea10"; } .note-icon-chain-broken::before { content: "\ea11"; } .note-icon-circle::before { content: "\ea12"; } .note-icon-close::before { content: "\ea13"; } .note-icon-code::before { content: "\ea14"; } .note-icon-col-after::before { content: "\ea15"; } .note-icon-col-before::before { content: "\ea16"; } .note-icon-col-remove::before { content: "\ea17"; } .note-icon-eraser::before { content: "\ea18"; } .note-icon-float-left::before { content: "\ea19"; } .note-icon-float-none::before { content: "\ea1a"; } .note-icon-float-right::before { content: "\ea1b"; } .note-icon-font::before { content: "\ea1c"; } .note-icon-frame::before { content: "\ea1d"; } .note-icon-italic::before { content: "\ea1e"; } .note-icon-link::before { content: "\ea1f"; } .note-icon-magic::before { content: "\ea20"; } .note-icon-menu-check::before { content: "\ea21"; } .note-icon-minus::before { content: "\ea22"; } .note-icon-orderedlist::before { content: "\ea23"; } .note-icon-pencil::before { content: "\ea24"; } .note-icon-picture::before { content: "\ea25"; } .note-icon-question::before { content: "\ea26"; } .note-icon-redo::before { content: "\ea27"; } .note-icon-rollback::before { content: "\ea28"; } .note-icon-row-above::before { content: "\ea29"; } .note-icon-row-below::before { content: "\ea2a"; } .note-icon-row-remove::before { content: "\ea2b"; } .note-icon-special-character::before { content: "\ea2c"; } .note-icon-square::before { content: "\ea2d"; } .note-icon-strikethrough::before { content: "\ea2e"; } .note-icon-subscript::before { content: "\ea2f"; } .note-icon-summernote::before { content: "\ea30"; } .note-icon-superscript::before { content: "\ea31"; } .note-icon-table::before { content: "\ea32"; } .note-icon-text-height::before { content: "\ea33"; } .note-icon-trash::before { content: "\ea34"; } .note-icon-underline::before { content: "\ea35"; } .note-icon-undo::before { content: "\ea36"; } .note-icon-unorderedlist::before { content: "\ea37"; } .note-icon-video::before { content: "\ea38"; } .note-frame { -ms-box-sizing: border-box; box-sizing: border-box; color: #000; font-family: sans-serif; border-radius: 4px; } .note-toolbar { padding: 10px 5px; border-bottom: 1px solid #e2e2e2; color: #333; background-color: #f5f5f5; border-color: #ddd; border-top-left-radius: 3px; border-top-right-radius: 3px; } .note-btn-group { position: relative; display: inline-block; margin-right: 8px; } .note-btn-group > .note-btn-group { margin-right: 0; } .note-btn-group > .note-btn:first-child { margin-left: 0; } .note-btn-group .note-btn + .note-btn, .note-btn-group .note-btn + .note-btn-group, .note-btn-group .note-btn-group + .note-btn, .note-btn-group .note-btn-group + .note-btn-group { margin-left: -1px; } .note-btn-group > .note-btn:not(:first-child), .note-btn-group > .note-btn-group:not(:first-child) > .note-btn { border-top-left-radius: 0; border-bottom-left-radius: 0; } .note-btn-group > .note-btn:not(:last-child):not(.dropdown-toggle), .note-btn-group > .note-btn-group:not(:last-child) > .note-btn { border-top-right-radius: 0; border-bottom-right-radius: 0; } .note-btn-group.open > .note-dropdown { display: block; } .note-btn { display: inline-block; font-weight: 400; margin-bottom: 0; text-align: center; vertical-align: middle; touch-action: manipulation; cursor: pointer; background-image: none; border: 1px solid #dae0e5; white-space: nowrap; outline: 0; color: #333; background-color: #fff; border-color: #dae0e5; padding: 5px 10px; font-size: 14px; line-height: 1.4; border-radius: 3px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .note-btn:focus, .note-btn.focus { color: #333; background-color: #ebebeb; border-color: #dae0e5; } .note-btn:hover { color: #333; background-color: #ebebeb; border-color: #dae0e5; } .note-btn.disabled:focus, .note-btn.disabled.focus, .note-btn[disabled]:focus, .note-btn[disabled].focus, fieldset[disabled] .note-btn:focus, fieldset[disabled] .note-btn.focus { background-color: #fff; border-color: #dae0e5; } .note-btn:hover, .note-btn:focus, .note-btn.focus { color: #333; text-decoration: none; border: 1px solid #dae0e5; background-color: #ebebeb; outline: 0; border-radius: 1px; } .note-btn:active, .note-btn.active { outline: 0; background-image: none; color: #333; text-decoration: none; border: 1px solid #dae0e5; background-color: #ebebeb; outline: 0; border-radius: 1px; box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .note-btn.disabled, .note-btn[disabled], fieldset[disabled] .note-btn { cursor: not-allowed; -webkit-opacity: 0.65; -khtml-opacity: 0.65; -moz-opacity: 0.65; opacity: 0.65; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=65); filter: alpha(opacity=65); box-shadow: none; } .note-btn > span.note-icon-caret:first-child { margin-left: -1px; } .note-btn > span.note-icon-caret:nth-child(2) { padding-left: 3px; margin-right: -5px; } .note-btn-primary { background: #fa6362; color: #fff; } .note-btn-primary:hover, .note-btn-primary:focus, .note-btn-primary.focus { color: #fff; text-decoration: none; border: 1px solid #dae0e5; background-color: #fa6362; border-radius: 1px; } .note-btn-block { display: block; width: 100%; } .note-btn-block + .note-btn-block { margin-top: 5px; } input[type=submit].note-btn-block, input[type=reset].note-btn-block, input[type=button].note-btn-block { width: 100%; } button.close { padding: 0; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; } .close { float: right; font-size: 21px; line-height: 1; color: #000; opacity: 0.2; } .close:hover { -webkit-opacity: 1; -khtml-opacity: 1; -moz-opacity: 1; -ms-filter: alpha(opacity=100); filter: alpha(opacity=100); opacity: 1; } .note-dropdown { position: relative; } .note-color .dropdown-toggle { width: 30px; padding-left: 5px; } .note-dropdown-menu { display: none; min-width: 100px; position: absolute; top: 100%; left: 0; z-index: 1000; float: left; text-align: left; background: #fff; border: 1px solid #e2e2e2; padding: 5px; background-clip: padding-box; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.06); } .note-dropdown-menu > *:last-child { margin-right: 0; } .note-btn-group.open .note-dropdown-menu { display: block; } .note-dropdown-item { display: block; } .note-dropdown-item:hover { background-color: #ebebeb; } a.note-dropdown-item, a.note-dropdown-item:hover { margin: 5px 0; color: #000; text-decoration: none; } .note-modal { position: fixed; left: 0; right: 0; top: 0; bottom: 0; z-index: 1050; -webkit-opacity: 1; -khtml-opacity: 1; -moz-opacity: 1; opacity: 1; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=100); filter: alpha(opacity=100); display: none; } .note-modal.open { display: block; } .note-modal-content { position: relative; width: auto; margin: 30px 20px; border: 1px solid rgba(0, 0, 0, 0.2); background: #fff; background-clip: border-box; outline: 0; border-radius: 5px; box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5); } .note-modal-header { padding: 10px 20px; border: 1px solid #ededef; } .note-modal-body { position: relative; padding: 20px 30px; } .note-modal-body kbd { border-radius: 2px; background-color: #000; color: #fff; padding: 3px 5px; font-weight: 700; -ms-box-sizing: border-box; box-sizing: border-box; } .note-modal-footer { height: 40px; padding: 10px; text-align: center; } .note-modal-footer a { color: #337ab7; text-decoration: none; } .note-modal-footer a:hover, .note-modal-footer a:focus { color: #23527c; text-decoration: underline; } .note-modal-footer .note-btn { float: right; } .note-modal-title { font-size: 20px; color: #42515f; margin: 0; line-height: 1.4; } .note-modal-backdrop { position: fixed; left: 0; right: 0; bottom: 0; top: 0; z-index: 1040; background: #000; -webkit-opacity: 0.5; -khtml-opacity: 0.5; -moz-opacity: 0.5; opacity: 0.5; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=50); filter: alpha(opacity=50); display: none; } .note-modal-backdrop.open { display: block; } @media (min-width: 768px) { .note-modal-content { width: 600px; margin: 30px auto; } } @media (min-width: 992px) { .note-modal-content-large { width: 900px; } } .note-modal .note-help-block { display: block; margin-top: 5px; margin-bottom: 10px; color: #737373; } .note-modal .note-nav { display: flex; flex-wrap: wrap; padding-left: 0; margin-bottom: 0; list-style: none; } .note-modal .note-nav-link { display: block; padding: 0.5rem 1rem; color: #007bff; text-decoration: none; background-color: transparent; -webkit-text-decoration-skip: objects; } .note-modal .note-nav-link:focus, .note-modal .note-nav-link:hover { color: #0056b3; text-decoration: none; } .note-modal .note-nav-link.disabled { color: #868e96; } .note-modal .note-nav-tabs { border-bottom: 1px solid #ddd; } .note-modal .note-nav-tabs .note-nav-item { margin-bottom: -1px; } .note-modal .note-nav-tabs .note-nav-link { border: 1px solid transparent; border-top-left-radius: 0.25rem; border-top-right-radius: 0.25rem; } .note-modal .note-nav-tabs .note-nav-link:focus, .note-modal .note-nav-tabs .note-nav-link:hover { border-color: #e9ecef #e9ecef #ddd; } .note-modal .note-nav-tabs .note-nav-link.disabled { color: #868e96; background-color: transparent; border-color: transparent; } .note-modal .note-nav-tabs .note-nav-item.show .note-nav-link { color: #495057; background-color: #fff; border-color: #ddd #ddd #fff; } .note-modal .note-tab-content { margin: 15px auto; } .note-modal .note-tab-content > .note-tab-pane:target ~ .note-tab-pane:last-child, .note-modal .note-tab-content > .note-tab-pane { display: none; } .note-modal .note-tab-content > :last-child, .note-modal .note-tab-content > .note-tab-pane:target { display: block; } .note-form-group { padding-bottom: 20px; } .note-form-group:last-child { padding-bottom: 0; } .note-form-label { display: block; width: 100%; font-size: 16px; color: #42515f; margin-bottom: 10px; font-weight: 700; } .note-input { width: 100%; display: block; border: 1px solid #ededef; background: #fff; outline: 0; padding: 6px 4px; font-size: 14px; -ms-box-sizing: border-box; box-sizing: border-box; } .note-input::-webkit-input-placeholder { color: #eeeeee; } .note-input:-moz-placeholder { /* Firefox 18- */ color: #eeeeee; } .note-input::-moz-placeholder { /* Firefox 19+ */ color: #eeeeee; } .note-input:-ms-input-placeholder { color: #eeeeee; } .note-tooltip { position: absolute; z-index: 1070; display: block; font-size: 13px; transition: opacity 0.15s; -webkit-opacity: 0; -khtml-opacity: 0; -moz-opacity: 0; opacity: 0; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0); filter: alpha(opacity=0); } .note-tooltip.in { -webkit-opacity: 0.9; -khtml-opacity: 0.9; -moz-opacity: 0.9; opacity: 0.9; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=90); filter: alpha(opacity=90); } .note-tooltip.top { margin-top: -3px; padding: 5px 0; } .note-tooltip.right { margin-left: 3px; padding: 0 5px; } .note-tooltip.bottom { margin-top: 3px; padding: 5px 0; } .note-tooltip.left { margin-left: -3px; padding: 0 5px; } .note-tooltip.bottom .note-tooltip-arrow { top: 0; left: 50%; margin-left: -5px; border-width: 0 5px 5px; border-bottom-color: #000; } .note-tooltip.top .note-tooltip-arrow { bottom: 0; left: 50%; margin-left: -5px; border-width: 5px 5px 0; border-top-color: #000; } .note-tooltip.right .note-tooltip-arrow { top: 50%; left: 0; margin-top: -5px; border-width: 5px 5px 5px 0; border-right-color: #000; } .note-tooltip.left .note-tooltip-arrow { top: 50%; right: 0; margin-top: -5px; border-width: 5px 0 5px 5px; border-left-color: #000; } .note-tooltip-arrow { position: absolute; width: 0; height: 0; border-color: transparent; border-style: solid; } .note-tooltip-content { max-width: 200px; font-family: sans-serif; padding: 3px 8px; color: #fff; text-align: center; background-color: #000; } .note-popover { position: absolute; z-index: 1060; display: block; font-size: 13px; font-family: sans-serif; display: none; background: #ffffff; border: 1px solid rgba(0, 0, 0, 0.2); border: 1px solid #ccc; } .note-popover.in { display: block; } .note-popover.top { margin-top: -10px; padding: 5px 0; } .note-popover.right { margin-left: 10px; padding: 0 5px; } .note-popover.bottom { margin-top: 10px; padding: 5px 0; } .note-popover.left { margin-left: -10px; padding: 0 5px; } .note-popover.bottom .note-popover-arrow { top: -11px; left: 20px; margin-left: -10px; border-top-width: 0; border-bottom-color: #999999; border-bottom-color: rgba(0, 0, 0, 0.25); } .note-popover.bottom .note-popover-arrow::after { top: 1px; margin-left: -10px; content: "\0020"; border-top-width: 0; border-bottom-color: #fff; } .note-popover.top .note-popover-arrow { bottom: -11px; left: 20px; margin-left: -10px; border-bottom-width: 0; border-top-color: #999999; border-top-color: rgba(0, 0, 0, 0.25); } .note-popover.top .note-popover-arrow::after { bottom: 1px; margin-left: -10px; content: "\0020"; border-bottom-width: 0; border-top-color: #fff; } .note-popover.right .note-popover-arrow { top: 50%; left: -11px; margin-top: -10px; border-left-width: 0; border-right-color: #999999; border-right-color: rgba(0, 0, 0, 0.25); } .note-popover.right .note-popover-arrow::after { left: 1px; margin-top: -10px; content: "\0020"; border-left-width: 0; border-right-color: #fff; } .note-popover.left .note-popover-arrow { top: 50%; right: -11px; margin-top: -10px; border-right-width: 0; border-left-color: #999999; border-left-color: rgba(0, 0, 0, 0.25); } .note-popover.left .note-popover-arrow::after { right: 1px; margin-top: -10px; content: "\0020"; border-right-width: 0; border-left-color: #fff; } .note-popover-arrow { position: absolute; width: 0; height: 0; border: 11px solid transparent; } .note-popover-arrow::after { position: absolute; display: block; width: 0; height: 0; border-color: transparent; border-style: solid; content: "\0020"; border-width: 10px; } .note-popover-content { /*max-width: $popover-max-width;*/ padding: 3px 8px; color: #000; text-align: center; background-color: #ffffff; min-width: 100px; min-height: 30px; } /* Theme Variables ------------------------------------------ */ /* Layout ------------------------------------------ */ .note-editor { position: relative; } .note-editor .note-dropzone { position: absolute; display: none; z-index: 100; color: lightskyblue; background-color: #fff; opacity: 0.95; } .note-editor .note-dropzone .note-dropzone-message { display: table-cell; vertical-align: middle; text-align: center; font-size: 28px; font-weight: 700; } .note-editor .note-dropzone.hover { color: #098ddf; } .note-editor.dragover .note-dropzone { display: table; } .note-editor .note-editing-area { position: relative; } .note-editor .note-editing-area .note-editable { outline: none; } .note-editor .note-editing-area .note-editable sup { vertical-align: super; } .note-editor .note-editing-area .note-editable sub { vertical-align: sub; } .note-editor .note-editing-area .note-editable img.note-float-left { margin-right: 10px; } .note-editor .note-editing-area .note-editable img.note-float-right { margin-left: 10px; } /* Frame mode layout ------------------------------------------ */ .note-editor.note-frame, .note-editor.note-airframe { border: 1px solid #00000032; } .note-editor.note-frame.codeview .note-editing-area .note-editable, .note-editor.note-airframe.codeview .note-editing-area .note-editable { display: none; } .note-editor.note-frame.codeview .note-editing-area .note-codable, .note-editor.note-airframe.codeview .note-editing-area .note-codable { display: block; } .note-editor.note-frame .note-editing-area, .note-editor.note-airframe .note-editing-area { overflow: hidden; } .note-editor.note-frame .note-editing-area .note-editable, .note-editor.note-airframe .note-editing-area .note-editable { padding: 10px; overflow: auto; word-wrap: break-word; } .note-editor.note-frame .note-editing-area .note-editable[contenteditable=false], .note-editor.note-airframe .note-editing-area .note-editable[contenteditable=false] { background-color: #8080801d; } .note-editor.note-frame .note-editing-area .note-codable, .note-editor.note-airframe .note-editing-area .note-codable { display: none; width: 100%; padding: 10px; border: none; box-shadow: none; font-family: Menlo, Monaco, monospace, sans-serif; font-size: 14px; color: #ccc; background-color: #222; resize: none; outline: none; -ms-box-sizing: border-box; box-sizing: border-box; border-radius: 0; margin-bottom: 0; } .note-editor.note-frame.fullscreen, .note-editor.note-airframe.fullscreen { position: fixed; top: 0; left: 0; width: 100% !important; z-index: 1050; } .note-editor.note-frame.fullscreen .note-resizebar, .note-editor.note-airframe.fullscreen .note-resizebar { display: none; } .note-editor.note-frame .note-status-output, .note-editor.note-airframe .note-status-output { display: block; width: 100%; font-size: 14px; line-height: 1.42857143; height: 20px; margin-bottom: 0; color: #000; border: 0; border-top: 1px solid #e2e2e2; } .note-editor.note-frame .note-status-output:empty, .note-editor.note-airframe .note-status-output:empty { height: 0; border-top: 0 solid transparent; } .note-editor.note-frame .note-status-output .pull-right, .note-editor.note-airframe .note-status-output .pull-right { float: right !important; } .note-editor.note-frame .note-status-output .text-muted, .note-editor.note-airframe .note-status-output .text-muted { color: #777; } .note-editor.note-frame .note-status-output .text-primary, .note-editor.note-airframe .note-status-output .text-primary { color: #286090; } .note-editor.note-frame .note-status-output .text-success, .note-editor.note-airframe .note-status-output .text-success { color: #3c763d; } .note-editor.note-frame .note-status-output .text-info, .note-editor.note-airframe .note-status-output .text-info { color: #31708f; } .note-editor.note-frame .note-status-output .text-warning, .note-editor.note-airframe .note-status-output .text-warning { color: #8a6d3b; } .note-editor.note-frame .note-status-output .text-danger, .note-editor.note-airframe .note-status-output .text-danger { color: #a94442; } .note-editor.note-frame .note-status-output .alert, .note-editor.note-airframe .note-status-output .alert { margin: -7px 0 0 0; padding: 7px 10px 2px 10px; border-radius: 0; color: #000; background-color: #f5f5f5; } .note-editor.note-frame .note-status-output .alert .note-icon, .note-editor.note-airframe .note-status-output .alert .note-icon { margin-right: 5px; } .note-editor.note-frame .note-status-output .alert-success, .note-editor.note-airframe .note-status-output .alert-success { color: #3c763d !important; background-color: #dff0d8 !important; } .note-editor.note-frame .note-status-output .alert-info, .note-editor.note-airframe .note-status-output .alert-info { color: #31708f !important; background-color: #d9edf7 !important; } .note-editor.note-frame .note-status-output .alert-warning, .note-editor.note-airframe .note-status-output .alert-warning { color: #8a6d3b !important; background-color: #fcf8e3 !important; } .note-editor.note-frame .note-status-output .alert-danger, .note-editor.note-airframe .note-status-output .alert-danger { color: #a94442 !important; background-color: #f2dede !important; } .note-editor.note-frame .note-statusbar, .note-editor.note-airframe .note-statusbar { background-color: #8080801d; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top: 1px solid #00000032; } .note-editor.note-frame .note-statusbar .note-resizebar, .note-editor.note-airframe .note-statusbar .note-resizebar { padding-top: 1px; height: 9px; width: 100%; cursor: ns-resize; } .note-editor.note-frame .note-statusbar .note-resizebar .note-icon-bar, .note-editor.note-airframe .note-statusbar .note-resizebar .note-icon-bar { width: 20px; margin: 1px auto; border-top: 1px solid #00000032; } .note-editor.note-frame .note-statusbar.locked .note-resizebar, .note-editor.note-airframe .note-statusbar.locked .note-resizebar { cursor: default; } .note-editor.note-frame .note-statusbar.locked .note-resizebar .note-icon-bar, .note-editor.note-airframe .note-statusbar.locked .note-resizebar .note-icon-bar { display: none; } .note-editor.note-frame .note-placeholder, .note-editor.note-airframe .note-placeholder { padding: 10px; } .note-editor.note-airframe { border: 0; } .note-editor.note-airframe .note-editing-area .note-editable { padding: 0; } /* Popover ------------------------------------------ */ .note-popover.popover { display: none; max-width: none; } .note-popover.popover .popover-content a { display: inline-block; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle; } .note-popover.popover .arrow { left: 20px !important; } /* Popover and Toolbar (Button container) ------------------------------------------ */ .note-toolbar { position: relative; } .note-popover .popover-content, .note-editor .note-toolbar { margin: 0; padding: 0 0 5px 5px; } .note-popover .popover-content > .note-btn-group, .note-editor .note-toolbar > .note-btn-group { margin-top: 5px; margin-left: 0; margin-right: 5px; } .note-popover .popover-content .note-btn-group .note-table, .note-editor .note-toolbar .note-btn-group .note-table { min-width: 0; padding: 5px; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker { font-size: 18px; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher { position: absolute !important; z-index: 3; width: 10em; height: 10em; cursor: pointer; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted { position: relative !important; z-index: 1; width: 5em; height: 5em; background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIj4+Pjp6ekKlAqjAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKhmnaJzPAAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted { position: absolute !important; z-index: 2; width: 1em; height: 1em; background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIjd6vvD2f9LKLW+AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKwNDEVT0AAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat; } .note-popover .popover-content .note-style .dropdown-style blockquote, .note-popover .popover-content .note-style .dropdown-style pre, .note-editor .note-toolbar .note-style .dropdown-style blockquote, .note-editor .note-toolbar .note-style .dropdown-style pre { margin: 0; padding: 5px 10px; } .note-popover .popover-content .note-style .dropdown-style h1, .note-popover .popover-content .note-style .dropdown-style h2, .note-popover .popover-content .note-style .dropdown-style h3, .note-popover .popover-content .note-style .dropdown-style h4, .note-popover .popover-content .note-style .dropdown-style h5, .note-popover .popover-content .note-style .dropdown-style h6, .note-popover .popover-content .note-style .dropdown-style p, .note-editor .note-toolbar .note-style .dropdown-style h1, .note-editor .note-toolbar .note-style .dropdown-style h2, .note-editor .note-toolbar .note-style .dropdown-style h3, .note-editor .note-toolbar .note-style .dropdown-style h4, .note-editor .note-toolbar .note-style .dropdown-style h5, .note-editor .note-toolbar .note-style .dropdown-style h6, .note-editor .note-toolbar .note-style .dropdown-style p { margin: 0; padding: 0; } .note-popover .popover-content .note-color-all .note-dropdown-menu, .note-editor .note-toolbar .note-color-all .note-dropdown-menu { min-width: 337px; } .note-popover .popover-content .note-color .dropdown-toggle, .note-editor .note-toolbar .note-color .dropdown-toggle { width: 20px; padding-left: 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette { display: inline-block; margin: 0; width: 160px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette:first-child, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette:first-child { margin: 0 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-palette-title, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-palette-title { font-size: 12px; margin: 2px 7px; text-align: center; border-bottom: 1px solid #eee; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset, .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select { font-size: 11px; margin: 3px; padding: 0 3px; cursor: pointer; width: 100%; border-radius: 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset:hover, .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select:hover, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset:hover, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select:hover { background: #eee; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-row, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-row { height: 20px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select-btn, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select-btn { display: none; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn { border: 1px solid #eee; } .note-popover .popover-content .note-para .note-dropdown-menu, .note-editor .note-toolbar .note-para .note-dropdown-menu { min-width: 228px; padding: 5px; } .note-popover .popover-content .note-para .note-dropdown-menu > div + div, .note-editor .note-toolbar .note-para .note-dropdown-menu > div + div { margin-left: 5px; } .note-popover .popover-content .note-dropdown-menu, .note-editor .note-toolbar .note-dropdown-menu { min-width: 160px; } .note-popover .popover-content .note-dropdown-menu.right, .note-editor .note-toolbar .note-dropdown-menu.right { right: 0; left: auto; } .note-popover .popover-content .note-dropdown-menu.right::before, .note-editor .note-toolbar .note-dropdown-menu.right::before { right: 9px; left: auto !important; } .note-popover .popover-content .note-dropdown-menu.right::after, .note-editor .note-toolbar .note-dropdown-menu.right::after { right: 10px; left: auto !important; } .note-popover .popover-content .note-dropdown-menu.note-check a i, .note-editor .note-toolbar .note-dropdown-menu.note-check a i { color: deepskyblue; visibility: hidden; } .note-popover .popover-content .note-dropdown-menu.note-check a.checked i, .note-editor .note-toolbar .note-dropdown-menu.note-check a.checked i { visibility: visible; } .note-popover .popover-content .note-fontsize-10, .note-editor .note-toolbar .note-fontsize-10 { font-size: 10px; } .note-popover .popover-content .note-color-palette, .note-editor .note-toolbar .note-color-palette { line-height: 1; } .note-popover .popover-content .note-color-palette div .note-color-btn, .note-editor .note-toolbar .note-color-palette div .note-color-btn { width: 20px; height: 20px; padding: 0; margin: 0; border: 0; border-radius: 0; } .note-popover .popover-content .note-color-palette div .note-color-btn:hover, .note-editor .note-toolbar .note-color-palette div .note-color-btn:hover { transform: scale(1.2); transition: all 0.2s; } /* Dialog ------------------------------------------ */ .note-modal .modal-dialog { outline: 0; border-radius: 5px; box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5); } .note-modal .form-group { margin-left: 0; margin-right: 0; } .note-modal .note-modal-form { margin: 0; } .note-modal .note-image-dialog .note-dropzone { min-height: 100px; font-size: 30px; line-height: 4; color: lightgray; text-align: center; border: 4px dashed lightgray; margin-bottom: 10px; } @-moz-document url-prefix() { .note-modal .note-image-input { height: auto; } } /* Placeholder ------------------------------------------ */ .note-placeholder { position: absolute; display: none; color: gray; } /* Handle ------------------------------------------ */ .note-handle .note-control-selection { position: absolute; display: none; border: 1px solid #000; } .note-handle .note-control-selection > div { position: absolute; } .note-handle .note-control-selection .note-control-selection-bg { width: 100%; height: 100%; background-color: #000; -webkit-opacity: 0.3; -khtml-opacity: 0.3; -moz-opacity: 0.3; opacity: 0.3; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=30); filter: alpha(opacity=30); } .note-handle .note-control-selection .note-control-handle, .note-handle .note-control-selection .note-control-sizing, .note-handle .note-control-selection .note-control-holder { width: 7px; height: 7px; border: 1px solid #000; } .note-handle .note-control-selection .note-control-sizing { background-color: #000; } .note-handle .note-control-selection .note-control-nw { top: -5px; left: -5px; border-right: none; border-bottom: none; } .note-handle .note-control-selection .note-control-ne { top: -5px; right: -5px; border-bottom: none; border-left: none; } .note-handle .note-control-selection .note-control-sw { bottom: -5px; left: -5px; border-top: none; border-right: none; } .note-handle .note-control-selection .note-control-se { right: -5px; bottom: -5px; cursor: se-resize; } .note-handle .note-control-selection .note-control-se.note-control-holder { cursor: default; border-top: none; border-left: none; } .note-handle .note-control-selection .note-control-selection-info { right: 0; bottom: 0; padding: 5px; margin: 5px; color: #fff; background-color: #000; font-size: 12px; border-radius: 5px; -webkit-opacity: 0.7; -khtml-opacity: 0.7; -moz-opacity: 0.7; opacity: 0.7; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=70); filter: alpha(opacity=70); } .note-hint-popover { min-width: 100px; padding: 2px; } .note-hint-popover .popover-content { padding: 3px; max-height: 150px; overflow: auto; } .note-hint-popover .popover-content .note-hint-group .note-hint-item { display: block !important; padding: 3px; } .note-hint-popover .popover-content .note-hint-group .note-hint-item.active, .note-hint-popover .popover-content .note-hint-group .note-hint-item:hover { display: block; clear: both; font-weight: 400; line-height: 1.4; color: white; white-space: nowrap; text-decoration: none; background-color: #428bca; outline: 0; cursor: pointer; } /* Handle ------------------------------------------ */ html .note-fullscreen-body, body .note-fullscreen-body { overflow: hidden !important; } .note-editor .note-editing-area .note-editable table { width: 100%; border-collapse: collapse; } .note-editor .note-editing-area .note-editable table td, .note-editor .note-editing-area .note-editable table th { border: 1px solid #ececec; padding: 5px 3px; } .note-editor .note-editing-area .note-editable a { background-color: inherit; text-decoration: inherit; font-family: inherit; font-weight: inherit; color: #337ab7; } .note-editor .note-editing-area .note-editable a:hover, .note-editor .note-editing-area .note-editable a:focus { color: #23527c; text-decoration: underline; outline: 0; } .note-editor .note-editing-area .note-editable figure { margin: 0; } /* Dialog ------------------------------------------*/ .note-modal .note-modal-body label { margin-bottom: 2px; padding: 2px 5px; display: inline-block; } .note-modal .note-modal-body .help-list-item:hover { background-color: #e0e0e0; } @-moz-document url-prefix() { .note-modal .note-image-input { height: auto; } } .help-list-item label { margin-bottom: 5px; display: inline-block; } /*# sourceMappingURL=summernote-lite.css.map*/
2881099/FreeSql.AdminLTE
23,275
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote.css
/*! * * Super simple WYSIWYG editor v0.8.20 * https://summernote.org * * * Copyright 2013- Alan Hong and contributors * Summernote may be freely distributed under the MIT license. * * Date: 2021-10-14T21:15Z * */ @font-face { font-family: "summernote"; font-style: normal; font-weight: 400; font-display: auto; src: url("./font/summernote.eot?#iefix") format("embedded-opentype"), url("./font/summernote.woff2") format("woff2"), url("./font/summernote.woff") format("woff"), url("./font/summernote.ttf") format("truetype"); } [class^=note-icon]:before, [class*=" note-icon"]:before { display: inline-block; font-family: "summernote"; font-style: normal; font-size: inherit; text-decoration: inherit; text-rendering: auto; text-transform: none; vertical-align: middle; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; speak: none; } .note-icon-fw { text-align: center; width: 1.25em; } .note-icon-border { border: solid 0.08em #eee; border-radius: 0.1em; padding: 0.2em 0.25em 0.15em; } .note-icon-pull-left { float: left; } .note-icon-pull-right { float: right; } .note-icon.note-icon-pull-left { margin-right: 0.3em; } .note-icon.note-icon-pull-right { margin-left: 0.3em; } .note-icon-align::before { content: "\ea01"; } .note-icon-align-center::before { content: "\ea02"; } .note-icon-align-indent::before { content: "\ea03"; } .note-icon-align-justify::before { content: "\ea04"; } .note-icon-align-left::before { content: "\ea05"; } .note-icon-align-outdent::before { content: "\ea06"; } .note-icon-align-right::before { content: "\ea07"; } .note-icon-arrow-circle-down::before { content: "\ea08"; } .note-icon-arrow-circle-left::before { content: "\ea09"; } .note-icon-arrow-circle-right::before { content: "\ea0a"; } .note-icon-arrow-circle-up::before { content: "\ea0b"; } .note-icon-arrows-alt::before { content: "\ea0c"; } .note-icon-arrows-h::before { content: "\ea0d"; } .note-icon-arrows-v::before { content: "\ea0e"; } .note-icon-bold::before { content: "\ea0f"; } .note-icon-caret::before { content: "\ea10"; } .note-icon-chain-broken::before { content: "\ea11"; } .note-icon-circle::before { content: "\ea12"; } .note-icon-close::before { content: "\ea13"; } .note-icon-code::before { content: "\ea14"; } .note-icon-col-after::before { content: "\ea15"; } .note-icon-col-before::before { content: "\ea16"; } .note-icon-col-remove::before { content: "\ea17"; } .note-icon-eraser::before { content: "\ea18"; } .note-icon-float-left::before { content: "\ea19"; } .note-icon-float-none::before { content: "\ea1a"; } .note-icon-float-right::before { content: "\ea1b"; } .note-icon-font::before { content: "\ea1c"; } .note-icon-frame::before { content: "\ea1d"; } .note-icon-italic::before { content: "\ea1e"; } .note-icon-link::before { content: "\ea1f"; } .note-icon-magic::before { content: "\ea20"; } .note-icon-menu-check::before { content: "\ea21"; } .note-icon-minus::before { content: "\ea22"; } .note-icon-orderedlist::before { content: "\ea23"; } .note-icon-pencil::before { content: "\ea24"; } .note-icon-picture::before { content: "\ea25"; } .note-icon-question::before { content: "\ea26"; } .note-icon-redo::before { content: "\ea27"; } .note-icon-rollback::before { content: "\ea28"; } .note-icon-row-above::before { content: "\ea29"; } .note-icon-row-below::before { content: "\ea2a"; } .note-icon-row-remove::before { content: "\ea2b"; } .note-icon-special-character::before { content: "\ea2c"; } .note-icon-square::before { content: "\ea2d"; } .note-icon-strikethrough::before { content: "\ea2e"; } .note-icon-subscript::before { content: "\ea2f"; } .note-icon-summernote::before { content: "\ea30"; } .note-icon-superscript::before { content: "\ea31"; } .note-icon-table::before { content: "\ea32"; } .note-icon-text-height::before { content: "\ea33"; } .note-icon-trash::before { content: "\ea34"; } .note-icon-underline::before { content: "\ea35"; } .note-icon-undo::before { content: "\ea36"; } .note-icon-unorderedlist::before { content: "\ea37"; } .note-icon-video::before { content: "\ea38"; } /* Theme Variables ------------------------------------------ */ /* Layout ------------------------------------------ */ .note-editor { position: relative; } .note-editor .note-dropzone { position: absolute; display: none; z-index: 100; color: lightskyblue; background-color: #fff; opacity: 0.95; } .note-editor .note-dropzone .note-dropzone-message { display: table-cell; vertical-align: middle; text-align: center; font-size: 28px; font-weight: 700; } .note-editor .note-dropzone.hover { color: #098ddf; } .note-editor.dragover .note-dropzone { display: table; } .note-editor .note-editing-area { position: relative; } .note-editor .note-editing-area .note-editable { outline: none; } .note-editor .note-editing-area .note-editable sup { vertical-align: super; } .note-editor .note-editing-area .note-editable sub { vertical-align: sub; } .note-editor .note-editing-area .note-editable img.note-float-left { margin-right: 10px; } .note-editor .note-editing-area .note-editable img.note-float-right { margin-left: 10px; } /* Frame mode layout ------------------------------------------ */ .note-editor.note-frame, .note-editor.note-airframe { border: 1px solid #00000032; } .note-editor.note-frame.codeview .note-editing-area .note-editable, .note-editor.note-airframe.codeview .note-editing-area .note-editable { display: none; } .note-editor.note-frame.codeview .note-editing-area .note-codable, .note-editor.note-airframe.codeview .note-editing-area .note-codable { display: block; } .note-editor.note-frame .note-editing-area, .note-editor.note-airframe .note-editing-area { overflow: hidden; } .note-editor.note-frame .note-editing-area .note-editable, .note-editor.note-airframe .note-editing-area .note-editable { padding: 10px; overflow: auto; word-wrap: break-word; } .note-editor.note-frame .note-editing-area .note-editable[contenteditable=false], .note-editor.note-airframe .note-editing-area .note-editable[contenteditable=false] { background-color: #8080801d; } .note-editor.note-frame .note-editing-area .note-codable, .note-editor.note-airframe .note-editing-area .note-codable { display: none; width: 100%; padding: 10px; border: none; box-shadow: none; font-family: Menlo, Monaco, monospace, sans-serif; font-size: 14px; color: #ccc; background-color: #222; resize: none; outline: none; -ms-box-sizing: border-box; box-sizing: border-box; border-radius: 0; margin-bottom: 0; } .note-editor.note-frame.fullscreen, .note-editor.note-airframe.fullscreen { position: fixed; top: 0; left: 0; width: 100% !important; z-index: 1050; } .note-editor.note-frame.fullscreen .note-resizebar, .note-editor.note-airframe.fullscreen .note-resizebar { display: none; } .note-editor.note-frame .note-status-output, .note-editor.note-airframe .note-status-output { display: block; width: 100%; font-size: 14px; line-height: 1.42857143; height: 20px; margin-bottom: 0; color: #000; border: 0; border-top: 1px solid #e2e2e2; } .note-editor.note-frame .note-status-output:empty, .note-editor.note-airframe .note-status-output:empty { height: 0; border-top: 0 solid transparent; } .note-editor.note-frame .note-status-output .pull-right, .note-editor.note-airframe .note-status-output .pull-right { float: right !important; } .note-editor.note-frame .note-status-output .text-muted, .note-editor.note-airframe .note-status-output .text-muted { color: #777; } .note-editor.note-frame .note-status-output .text-primary, .note-editor.note-airframe .note-status-output .text-primary { color: #286090; } .note-editor.note-frame .note-status-output .text-success, .note-editor.note-airframe .note-status-output .text-success { color: #3c763d; } .note-editor.note-frame .note-status-output .text-info, .note-editor.note-airframe .note-status-output .text-info { color: #31708f; } .note-editor.note-frame .note-status-output .text-warning, .note-editor.note-airframe .note-status-output .text-warning { color: #8a6d3b; } .note-editor.note-frame .note-status-output .text-danger, .note-editor.note-airframe .note-status-output .text-danger { color: #a94442; } .note-editor.note-frame .note-status-output .alert, .note-editor.note-airframe .note-status-output .alert { margin: -7px 0 0 0; padding: 7px 10px 2px 10px; border-radius: 0; color: #000; background-color: #f5f5f5; } .note-editor.note-frame .note-status-output .alert .note-icon, .note-editor.note-airframe .note-status-output .alert .note-icon { margin-right: 5px; } .note-editor.note-frame .note-status-output .alert-success, .note-editor.note-airframe .note-status-output .alert-success { color: #3c763d !important; background-color: #dff0d8 !important; } .note-editor.note-frame .note-status-output .alert-info, .note-editor.note-airframe .note-status-output .alert-info { color: #31708f !important; background-color: #d9edf7 !important; } .note-editor.note-frame .note-status-output .alert-warning, .note-editor.note-airframe .note-status-output .alert-warning { color: #8a6d3b !important; background-color: #fcf8e3 !important; } .note-editor.note-frame .note-status-output .alert-danger, .note-editor.note-airframe .note-status-output .alert-danger { color: #a94442 !important; background-color: #f2dede !important; } .note-editor.note-frame .note-statusbar, .note-editor.note-airframe .note-statusbar { background-color: #8080801d; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top: 1px solid #00000032; } .note-editor.note-frame .note-statusbar .note-resizebar, .note-editor.note-airframe .note-statusbar .note-resizebar { padding-top: 1px; height: 9px; width: 100%; cursor: ns-resize; } .note-editor.note-frame .note-statusbar .note-resizebar .note-icon-bar, .note-editor.note-airframe .note-statusbar .note-resizebar .note-icon-bar { width: 20px; margin: 1px auto; border-top: 1px solid #00000032; } .note-editor.note-frame .note-statusbar.locked .note-resizebar, .note-editor.note-airframe .note-statusbar.locked .note-resizebar { cursor: default; } .note-editor.note-frame .note-statusbar.locked .note-resizebar .note-icon-bar, .note-editor.note-airframe .note-statusbar.locked .note-resizebar .note-icon-bar { display: none; } .note-editor.note-frame .note-placeholder, .note-editor.note-airframe .note-placeholder { padding: 10px; } .note-editor.note-airframe { border: 0; } .note-editor.note-airframe .note-editing-area .note-editable { padding: 0; } /* Popover ------------------------------------------ */ .note-popover.popover { display: none; max-width: none; } .note-popover.popover .popover-content a { display: inline-block; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle; } .note-popover.popover .arrow { left: 20px !important; } /* Popover and Toolbar (Button container) ------------------------------------------ */ .note-toolbar { position: relative; } .note-popover .popover-content, .note-editor .note-toolbar { margin: 0; padding: 0 0 5px 5px; } .note-popover .popover-content > .note-btn-group, .note-editor .note-toolbar > .note-btn-group { margin-top: 5px; margin-left: 0; margin-right: 5px; } .note-popover .popover-content .note-btn-group .note-table, .note-editor .note-toolbar .note-btn-group .note-table { min-width: 0; padding: 5px; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker { font-size: 18px; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher { position: absolute !important; z-index: 3; width: 10em; height: 10em; cursor: pointer; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted { position: relative !important; z-index: 1; width: 5em; height: 5em; background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIj4+Pjp6ekKlAqjAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKhmnaJzPAAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted { position: absolute !important; z-index: 2; width: 1em; height: 1em; background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIjd6vvD2f9LKLW+AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKwNDEVT0AAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat; } .note-popover .popover-content .note-style .dropdown-style blockquote, .note-popover .popover-content .note-style .dropdown-style pre, .note-editor .note-toolbar .note-style .dropdown-style blockquote, .note-editor .note-toolbar .note-style .dropdown-style pre { margin: 0; padding: 5px 10px; } .note-popover .popover-content .note-style .dropdown-style h1, .note-popover .popover-content .note-style .dropdown-style h2, .note-popover .popover-content .note-style .dropdown-style h3, .note-popover .popover-content .note-style .dropdown-style h4, .note-popover .popover-content .note-style .dropdown-style h5, .note-popover .popover-content .note-style .dropdown-style h6, .note-popover .popover-content .note-style .dropdown-style p, .note-editor .note-toolbar .note-style .dropdown-style h1, .note-editor .note-toolbar .note-style .dropdown-style h2, .note-editor .note-toolbar .note-style .dropdown-style h3, .note-editor .note-toolbar .note-style .dropdown-style h4, .note-editor .note-toolbar .note-style .dropdown-style h5, .note-editor .note-toolbar .note-style .dropdown-style h6, .note-editor .note-toolbar .note-style .dropdown-style p { margin: 0; padding: 0; } .note-popover .popover-content .note-color-all .note-dropdown-menu, .note-editor .note-toolbar .note-color-all .note-dropdown-menu { min-width: 337px; } .note-popover .popover-content .note-color .dropdown-toggle, .note-editor .note-toolbar .note-color .dropdown-toggle { width: 20px; padding-left: 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette { display: inline-block; margin: 0; width: 160px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette:first-child, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette:first-child { margin: 0 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-palette-title, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-palette-title { font-size: 12px; margin: 2px 7px; text-align: center; border-bottom: 1px solid #eee; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset, .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select { font-size: 11px; margin: 3px; padding: 0 3px; cursor: pointer; width: 100%; border-radius: 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset:hover, .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select:hover, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset:hover, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select:hover { background: #eee; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-row, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-row { height: 20px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select-btn, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select-btn { display: none; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn { border: 1px solid #eee; } .note-popover .popover-content .note-para .note-dropdown-menu, .note-editor .note-toolbar .note-para .note-dropdown-menu { min-width: 228px; padding: 5px; } .note-popover .popover-content .note-para .note-dropdown-menu > div + div, .note-editor .note-toolbar .note-para .note-dropdown-menu > div + div { margin-left: 5px; } .note-popover .popover-content .note-dropdown-menu, .note-editor .note-toolbar .note-dropdown-menu { min-width: 160px; } .note-popover .popover-content .note-dropdown-menu.right, .note-editor .note-toolbar .note-dropdown-menu.right { right: 0; left: auto; } .note-popover .popover-content .note-dropdown-menu.right::before, .note-editor .note-toolbar .note-dropdown-menu.right::before { right: 9px; left: auto !important; } .note-popover .popover-content .note-dropdown-menu.right::after, .note-editor .note-toolbar .note-dropdown-menu.right::after { right: 10px; left: auto !important; } .note-popover .popover-content .note-dropdown-menu.note-check a i, .note-editor .note-toolbar .note-dropdown-menu.note-check a i { color: deepskyblue; visibility: hidden; } .note-popover .popover-content .note-dropdown-menu.note-check a.checked i, .note-editor .note-toolbar .note-dropdown-menu.note-check a.checked i { visibility: visible; } .note-popover .popover-content .note-fontsize-10, .note-editor .note-toolbar .note-fontsize-10 { font-size: 10px; } .note-popover .popover-content .note-color-palette, .note-editor .note-toolbar .note-color-palette { line-height: 1; } .note-popover .popover-content .note-color-palette div .note-color-btn, .note-editor .note-toolbar .note-color-palette div .note-color-btn { width: 20px; height: 20px; padding: 0; margin: 0; border: 0; border-radius: 0; } .note-popover .popover-content .note-color-palette div .note-color-btn:hover, .note-editor .note-toolbar .note-color-palette div .note-color-btn:hover { transform: scale(1.2); transition: all 0.2s; } /* Dialog ------------------------------------------ */ .note-modal .modal-dialog { outline: 0; border-radius: 5px; box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5); } .note-modal .form-group { margin-left: 0; margin-right: 0; } .note-modal .note-modal-form { margin: 0; } .note-modal .note-image-dialog .note-dropzone { min-height: 100px; font-size: 30px; line-height: 4; color: lightgray; text-align: center; border: 4px dashed lightgray; margin-bottom: 10px; } @-moz-document url-prefix() { .note-modal .note-image-input { height: auto; } } /* Placeholder ------------------------------------------ */ .note-placeholder { position: absolute; display: none; color: gray; } /* Handle ------------------------------------------ */ .note-handle .note-control-selection { position: absolute; display: none; border: 1px solid #000; } .note-handle .note-control-selection > div { position: absolute; } .note-handle .note-control-selection .note-control-selection-bg { width: 100%; height: 100%; background-color: #000; -webkit-opacity: 0.3; -khtml-opacity: 0.3; -moz-opacity: 0.3; opacity: 0.3; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=30); filter: alpha(opacity=30); } .note-handle .note-control-selection .note-control-handle, .note-handle .note-control-selection .note-control-sizing, .note-handle .note-control-selection .note-control-holder { width: 7px; height: 7px; border: 1px solid #000; } .note-handle .note-control-selection .note-control-sizing { background-color: #000; } .note-handle .note-control-selection .note-control-nw { top: -5px; left: -5px; border-right: none; border-bottom: none; } .note-handle .note-control-selection .note-control-ne { top: -5px; right: -5px; border-bottom: none; border-left: none; } .note-handle .note-control-selection .note-control-sw { bottom: -5px; left: -5px; border-top: none; border-right: none; } .note-handle .note-control-selection .note-control-se { right: -5px; bottom: -5px; cursor: se-resize; } .note-handle .note-control-selection .note-control-se.note-control-holder { cursor: default; border-top: none; border-left: none; } .note-handle .note-control-selection .note-control-selection-info { right: 0; bottom: 0; padding: 5px; margin: 5px; color: #fff; background-color: #000; font-size: 12px; border-radius: 5px; -webkit-opacity: 0.7; -khtml-opacity: 0.7; -moz-opacity: 0.7; opacity: 0.7; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=70); filter: alpha(opacity=70); } .note-hint-popover { min-width: 100px; padding: 2px; } .note-hint-popover .popover-content { padding: 3px; max-height: 150px; overflow: auto; } .note-hint-popover .popover-content .note-hint-group .note-hint-item { display: block !important; padding: 3px; } .note-hint-popover .popover-content .note-hint-group .note-hint-item.active, .note-hint-popover .popover-content .note-hint-group .note-hint-item:hover { display: block; clear: both; font-weight: 400; line-height: 1.4; color: white; white-space: nowrap; text-decoration: none; background-color: #428bca; outline: 0; cursor: pointer; } /* Handle ------------------------------------------ */ html .note-fullscreen-body, body .note-fullscreen-body { overflow: hidden !important; } /*# sourceMappingURL=summernote.css.map*/
294coder/Efficient-MIF
4,335
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/linesearch/linesearch_decrease.m
function [stepsize, newx, newkey, lsstats] = ... linesearch_decrease(problem, x, d, f0, ~, options, storedb, key) % Backtracking line-search aiming merely for a decrease in cost value. % % function [stepsize, newx, newkey, lsstats] = % linesearch_decrease(problem, x, d, f0, df0, options, storedb, key) % % Line-search algorithm based on a simple backtracking method. The search % direction provided has to be a descent direction, but needs not be a % first-order descent, i.e.: this line-search can be used even if x is a % critical point, as long as the cost function is strictly decreasing % along the direction d. % % The line-search merely guarantees a decrease in the cost (unless a % stopping criterion triggers first, such as exceeding a maximal number of % iterations). This is typically useful to escape saddle points (critical % points admitting descent directions at the second order). Escape % directions can be computed using hessianextreme, for example. % % Below, the step is constructed as alpha*d, and the step size is the norm % of that vector, thus: stepsize = alpha*norm_d. The step is executed by % retracting the vector alpha*d from the current point x, giving newx. % An initial stepsize of norm_d thus means the first candidate x is % obtained by retracting d at x, as is. % % Options: % options.ls_max_steps (25): maximum number of cost evaluations. % options.ls_initial_stepsize (norm_d): first stepsize trial. % options.ls_contraction_factor (0.5): stepsize reduction per iteration. % % % Inputs/Outputs : see help for linesearch. % f0 is the cost at x. % df0 is unused. % options, storedb and key are optional. % Thus, a simplified calling pattern is (with all outputs still % available): linesearch_decrease(problem, x, d, f0) % % See also: steepestdescent linesearch hessianextreme % This file is part of Manopt: www.manopt.org. % Original author: Nicolas Boumal, April 8, 2015. % Contributors: % Change log: % Allow omission of the key, and even of storedb. if ~exist('key', 'var') if ~exist('storedb', 'var') storedb = StoreDB(); end key = storedb.getNewKey(); end norm_d = problem.M.norm(x, d); % Backtracking default parameters. These can be overwritten in the % options structure which is passed to the solver. default_options.ls_contraction_factor = .5; default_options.ls_initial_stepsize = norm_d; default_options.ls_max_steps = 25; if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(default_options, options); contraction_factor = options.ls_contraction_factor; initial_stepsize = options.ls_initial_stepsize; max_ls_steps = options.ls_max_steps; % Initial step size as a mutliplier of d. alpha = initial_stepsize / norm_d; % Make the chosen step and compute the cost there. newx = problem.M.retr(x, d, alpha); newkey = storedb.getNewKey(); newf = getCost(problem, newx, storedb, newkey); cost_evaluations = 1; % Backtrack while no cost decrease is obtained. while newf >= f0 % Reduce the step size, alpha = contraction_factor * alpha; % and look closer down the line newx = problem.M.retr(x, d, alpha); newkey = storedb.getNewKey(); newf = getCost(problem, newx, storedb, newkey); cost_evaluations = cost_evaluations + 1; % Make sure we don't run out of budget if cost_evaluations >= max_ls_steps break; end end % If we got here without obtaining a decrease, we reject the step. % Equal cost is accepted, since if x is critical, it is important to % move away from x more than it is important to decrease the cost. if newf > f0 alpha = 0; newx = x; newkey = key; newf = f0; %#ok<NASGU> end % As seen outside this function, stepsize is the size of the vector we % retract to make the step from x to newx. Since the step is alpha*d: stepsize = alpha * norm_d; % Return some statistics also, for possible analysis. lsstats.costevals = cost_evaluations; lsstats.stepsize = stepsize; lsstats.alpha = alpha; end
294coder/Efficient-MIF
4,552
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/linesearch/linesearch_hint.m
function [stepsize, newx, newkey, lsstats] = ... linesearch_hint(problem, x, d, f0, df0, options, storedb, key) % Armijo line-search based on the line-search hint in the problem structure. % % function [stepsize, newx, newkey, lsstats] = % linesearch_hint(problem, x, d, f0, df0, options, storedb, key) % % Base line-search algorithm for descent methods, based on a simple % backtracking method. The search direction provided has to be a descent % direction, as indicated by a negative df0 = directional derivative of f % at x along d. % % The algorithm obtains an initial step size candidate from the problem % structure, typically through the problem.linesearch function. If that % step does not fulfill the Armijo sufficient decrease criterion, that step % size is reduced geometrically until a satisfactory step size is obtained % or until a failure criterion triggers. If the problem structure does not % provide an initial alpha, then alpha = 1 is tried first. % % Below, the step is constructed as alpha*d, and the step size is the norm % of that vector, thus: stepsize = alpha*norm_d. The step is executed by % retracting the vector alpha*d from the current point x, giving newx. % % Inputs/Outputs : see help for linesearch % % See also: steepestdescent conjugategradients linesearch % This file is part of Manopt: www.manopt.org. % Original author: Nicolas Boumal, July 17, 2014. % Contributors: % Change log: % % April 3, 2015 (NB): % Works with the new StoreDB class system. % % April 8, 2015 (NB): % Got rid of lsmem input/output. % % July 20, 2017 (NB): % Now using alpha = 1 by default. % % Aug. 28, 2017 (NB): % Adding two options: ls_backtrack and ls_force_decrease, both true % by default. Setting them to false can disable parts of the line % search that, respectively, execute an Armijo backtracking and % reject a cost increasing step. % Allow omission of the key, and even of storedb. if ~exist('key', 'var') if ~exist('storedb', 'var') storedb = StoreDB(); end key = storedb.getNewKey(); end % Backtracking default parameters. These can be overwritten in the % options structure which is passed to the solver. default_options.ls_contraction_factor = .5; default_options.ls_suff_decr = 1e-4; default_options.ls_max_steps = 25; default_options.ls_backtrack = true; default_options.ls_force_decrease = true; if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(default_options, options); contraction_factor = options.ls_contraction_factor; suff_decr = options.ls_suff_decr; max_ls_steps = options.ls_max_steps; % Obtain an initial guess at alpha from the problem structure. It is % assumed that the present line-search is only called when the problem % structure provides enough information for the call here to work. if canGetLinesearch(problem) alpha = getLinesearch(problem, x, d, storedb, key); else alpha = 1; end % Make the chosen step and compute the cost there. newx = problem.M.retr(x, d, alpha); newkey = storedb.getNewKey(); newf = getCost(problem, newx, storedb, newkey); cost_evaluations = 1; % Backtrack while the Armijo criterion is not satisfied while options.ls_backtrack && newf > f0 + suff_decr*alpha*df0 % Reduce the step size, alpha = contraction_factor * alpha; % and look closer down the line newx = problem.M.retr(x, d, alpha); newkey = storedb.getNewKey(); newf = getCost(problem, newx, storedb, newkey); cost_evaluations = cost_evaluations + 1; % Make sure we don't run out of budget if cost_evaluations >= max_ls_steps break; end end % If we got here without obtaining a decrease, we reject the step. if options.ls_force_decrease && newf > f0 alpha = 0; newx = x; newkey = key; newf = f0; %#ok<NASGU> end % As seen outside this function, stepsize is the size of the vector we % retract to make the step from x to newx. Since the step is alpha*d: norm_d = problem.M.norm(x, d); stepsize = alpha * norm_d; % Return some statistics also, for possible analysis. lsstats.costevals = cost_evaluations; lsstats.stepsize = stepsize; lsstats.alpha = alpha; end
281677160/openwrt-package
1,928
luci-app-pppoe-server/luasrc/model/cbi/pppoe-server/settings.lua
local sys = require "luci.sys" local ifaces = sys.net:devices() local net = require "luci.model.network".init() m = Map("pppoe-server", translate("PPPoE Server")) m.description = translate("The PPPoE server is a broadband access authentication server that prevents ARP spoofing.") m.template = "pppoe-server/index" s = m:section(TypedSection, "service") s.anonymous = true o = s:option(DummyValue, "_status", translate("Current Condition")) o.template = "pppoe-server/status" o.value = translate("Collecting data...") o = s:option(Flag, "enabled", translate("Enable")) o.rmempty = false o = s:option(ListValue, "client_interface", translate("Client Interface"), translate("Listen in this interface")) for _, iface in ipairs(ifaces) do if (iface:match("^br") or iface:match("^eth*") or iface:match("^pppoe*") or iface:match("wlan*")) then local nets = net:get_interface(iface) nets = nets and nets:get_networks() or {} for k, v in pairs(nets) do nets[k] = nets[k].sid end nets = table.concat(nets, ",") o:value(iface, ((#nets > 0) and "%s (%s)" % {iface, nets} or iface)) end end o = s:option(Value, "localip", translate("Server IP"), translate("PPPoE Server IP address.default: 10.0.1.1")) o.datatype = "ipaddr" o.placeholder = "10.0.1.1" o.default = o.placeholder o = s:option(Value, "remoteip", translate("Client IP"), translate("PPPoE Client IP address.default: 10.0.1.100-254")) o.placeholder = "10.0.1.100-254" o.default = o.placeholder o = s:option(Value, "count", translate("Client upper limit"), translate("Specify how many clients can connect to the server simultaneously.")) o.placeholder = "50" o.default = o.placeholder o = s:option(Value, "dns1", translate("Preferred DNS server")) o.placeholder = "10.0.1.1" o.datatype = "ipaddr" o = s:option(Value, "dns2", translate("Alternate DNS server")) o.datatype = "ipaddr" o.placeholder = "119.29.29.29" return m
294coder/Efficient-MIF
8,118
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/linesearch/linesearch.m
function [stepsize, newx, newkey, lsstats] = ... linesearch(problem, x, d, f0, df0, options, storedb, key) % Standard line-search algorithm (step size selection) for descent methods. % % function [stepsize, newx, newkey, lsstats] = % linesearch(problem, x, d, f0, df0, options, storedb, key) % % Base line-search algorithm for descent methods, based on a simple % backtracking method. The search direction provided has to be a descent % direction, as indicated by a negative df0 = directional derivative of f % at x along d. % % The algorithm is invariant under positive scaling of the cost function % and under offsetting, that is: if the cost function f is replaced by % 8*f+3 for example, the returned step size will be the same. Furthermore, % the returned step size is independent of the norm of the search direction % vector d: only the direction of d is important. % % Below, the step is constructed as alpha*d, and the step size is the norm % of that vector, thus: stepsize = alpha*norm_d. The step is executed by % retracting the vector alpha*d from the current point x, giving newx. % % This line-search may create and maintain a structure called lsmem inside % storedb.internal. This gives the linesearch the opportunity to remember % what happened in the previous calls. This is typically used to make a % first guess at the step size, based on previous events. % % Inputs % % problem : structure holding the description of the optimization problem % x : current point on the manifold problem.M % d : tangent vector at x (descent direction) -- its norm is irrelevant % f0 : cost value at x % df0 : directional derivative at x along d % options : options structure (see in code for usage) % storedb : StoreDB object (handle class: passed by reference) for caching % key : key associated to point x in storedb % % options, storedb and key are optional. % % Outputs % % stepsize : norm of the vector retracted to reach newx from x. % newx : next iterate suggested by the line-search algorithm, such that % the retraction at x of the vector alpha*d reaches newx. % newkey : key associated to newx in storedb % lsstats : statistics about the line-search procedure % (stepsize, number of trials etc). % % See also: steepestdescent conjugategradients linesearch_adaptive % This file is part of Manopt: www.manopt.org. % Original author: Nicolas Boumal, Dec. 30, 2012. % Contributors: % Change log: % % Sept. 13, 2013 (NB): % User control over the parameters of the linesearch via the options % ls_contraction_factor, ls_optimism, ls_suff_decr and ls_max_steps. % See in code for the effect of those. % % Sept. 13, 2013 (NB): % The automatic direction reversal feature was removed (it triggered % when df0 > 0). Direction reversal is a decision that needs to be % made by the solver, so it can know about it. % % Sept. 13, 2013 (NB): % The linesearch is now invariant under rescaling of the cost % function f. That is, if f is replaced by 8*f (and hence the % directional derivatives of f are scaled accordingly), the % stepsizes computed will not change. % % Nov. 7, 2013 (NB): % The linesearch is now invariant under rescaling of the search % direction d. The meaning of stepsize is also more clear in the % comments. Added a parameter ls_initial_stepsize to give users % control over the first step size trial. % % April 3, 2015 (NB): % Works with the new StoreDB class system. % % April 8, 2015 (NB): % Got rid of lsmem input/output: now maintained in storedb.internal. % % Oct. 7, 2016 (NB): % Thanks to Wen Huang, a bug was corrected in the logic around % lsmem handling. Specifically, lsmem = storedb.internal.lsmem; % was erroneously coded as lsmem = storedb.internal; % Allow omission of the key, and even of storedb. if ~exist('key', 'var') if ~exist('storedb', 'var') storedb = StoreDB(); end key = storedb.getNewKey(); end % Backtracking default parameters. These can be overwritten in the % options structure which is passed to the solver. default_options.ls_contraction_factor = .5; default_options.ls_optimism = 1/.5; default_options.ls_suff_decr = 1e-4; default_options.ls_max_steps = 25; default_options.ls_initial_stepsize = 1; if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(default_options, options); contraction_factor = options.ls_contraction_factor; optimism = options.ls_optimism; suff_decr = options.ls_suff_decr; max_ls_steps = options.ls_max_steps; initial_stepsize = options.ls_initial_stepsize; % Compute the norm of the search direction. % This is useful to make the linesearch algorithm invariant under the % scaling of d. The rationale is that the important information is the % search direction, not the size of that vector. The question of how % far we should go is precisely what the linesearch algorithm is % supposed to answer: the calling algorithm should not need to care. norm_d = problem.M.norm(x, d); % At first, we have no idea of what the step size should be. alpha = NaN; % If we know about what happened at the previous step, we can leverage % that to compute an initial guess for the step size, as inspired from % Nocedal&Wright, p59. if isfield(storedb.internal, 'lsmem') lsmem = storedb.internal.lsmem; if isfield(lsmem, 'f0') % Pick initial step size based on where we were last time, alpha = 2*(f0 - lsmem.f0) / df0; % and go look a little further (or less far), just in case. alpha = optimism*alpha; end end % If we have no information about the previous iteration (maybe this is % the first one?) or if the above formula gave a too small step size % (perhaps it is even negative), then fall back to a user supplied % suggestion for the first step size (the "a priori"). % At any rate, the choice should be invariant under rescaling of the % cost function f and of the search direction d, and it should be % bounded away from zero for convergence guarantees. We must allow it % to be close to zero though, for fine convergence. if isnan(alpha) || alpha*norm_d <= eps alpha = initial_stepsize/norm_d; end % Make the chosen step and compute the cost there. newx = problem.M.retr(x, d, alpha); newkey = storedb.getNewKey(); newf = getCost(problem, newx, storedb, newkey); cost_evaluations = 1; % Backtrack while the Armijo criterion is not satisfied while newf > f0 + suff_decr*alpha*df0 % Reduce the step size, alpha = contraction_factor * alpha; % and look closer down the line newx = problem.M.retr(x, d, alpha); newkey = storedb.getNewKey(); newf = getCost(problem, newx, storedb, newkey); cost_evaluations = cost_evaluations + 1; % Make sure we don't run out of budget if cost_evaluations >= max_ls_steps break; end end % If we got here without obtaining a decrease, we reject the step. if newf > f0 alpha = 0; newx = x; newkey = key; newf = f0; %#ok<NASGU> end % As seen outside this function, stepsize is the size of the vector we % retract to make the step from x to newx. Since the step is alpha*d: stepsize = alpha * norm_d; % Save the situtation faced now so that, at the next iteration, % we will know something about the previous decision. storedb.internal.lsmem.f0 = f0; storedb.internal.lsmem.df0 = df0; storedb.internal.lsmem.stepsize = stepsize; % Return some statistics also, for possible analysis. lsstats.costevals = cost_evaluations; lsstats.stepsize = stepsize; lsstats.alpha = alpha; end
2881099/FreeSql.AdminLTE
324,327
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote.js
/*! * * Super simple WYSIWYG editor v0.8.20 * https://summernote.org * * * Copyright 2013- Alan Hong and contributors * Summernote may be freely distributed under the MIT license. * * Date: 2021-10-14T21:15Z * */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("jQuery")); else if(typeof define === 'function' && define.amd) define(["jQuery"], factory); else { var a = typeof exports === 'object' ? factory(require("jQuery")) : factory(root["jQuery"]); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(self, function(__WEBPACK_EXTERNAL_MODULE__1145__) { return /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ 9770: /***/ ((__unused_webpack_module, __unused_webpack___webpack_exports__, __webpack_require__) => { /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1145); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__); (jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote) = (jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote) || { lang: {} }; jquery__WEBPACK_IMPORTED_MODULE_0___default().extend((jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote.lang), { 'en-US': { font: { bold: 'Bold', italic: 'Italic', underline: 'Underline', clear: 'Remove Font Style', height: 'Line Height', name: 'Font Family', strikethrough: 'Strikethrough', subscript: 'Subscript', superscript: 'Superscript', size: 'Font Size', sizeunit: 'Font Size Unit' }, image: { image: 'Picture', insert: 'Insert Image', resizeFull: 'Resize full', resizeHalf: 'Resize half', resizeQuarter: 'Resize quarter', resizeNone: 'Original size', floatLeft: 'Float Left', floatRight: 'Float Right', floatNone: 'Remove float', shapeRounded: 'Shape: Rounded', shapeCircle: 'Shape: Circle', shapeThumbnail: 'Shape: Thumbnail', shapeNone: 'Shape: None', dragImageHere: 'Drag image or text here', dropImage: 'Drop image or Text', selectFromFiles: 'Select from files', maximumFileSize: 'Maximum file size', maximumFileSizeError: 'Maximum file size exceeded.', url: 'Image URL', remove: 'Remove Image', original: 'Original' }, video: { video: 'Video', videoLink: 'Video Link', insert: 'Insert Video', url: 'Video URL', providers: '(YouTube, Google Drive, Vimeo, Vine, Instagram, DailyMotion, Youku, Peertube)' }, link: { link: 'Link', insert: 'Insert Link', unlink: 'Unlink', edit: 'Edit', textToDisplay: 'Text to display', url: 'To what URL should this link go?', openInNewWindow: 'Open in new window', useProtocol: 'Use default protocol' }, table: { table: 'Table', addRowAbove: 'Add row above', addRowBelow: 'Add row below', addColLeft: 'Add column left', addColRight: 'Add column right', delRow: 'Delete row', delCol: 'Delete column', delTable: 'Delete table' }, hr: { insert: 'Insert Horizontal Rule' }, style: { style: 'Style', p: 'Normal', blockquote: 'Quote', pre: 'Code', h1: 'Header 1', h2: 'Header 2', h3: 'Header 3', h4: 'Header 4', h5: 'Header 5', h6: 'Header 6' }, lists: { unordered: 'Unordered list', ordered: 'Ordered list' }, options: { help: 'Help', fullscreen: 'Full Screen', codeview: 'Code View' }, paragraph: { paragraph: 'Paragraph', outdent: 'Outdent', indent: 'Indent', left: 'Align left', center: 'Align center', right: 'Align right', justify: 'Justify full' }, color: { recent: 'Recent Color', more: 'More Color', background: 'Background Color', foreground: 'Text Color', transparent: 'Transparent', setTransparent: 'Set transparent', reset: 'Reset', resetToDefault: 'Reset to default', cpSelect: 'Select' }, shortcut: { shortcuts: 'Keyboard shortcuts', close: 'Close', textFormatting: 'Text formatting', action: 'Action', paragraphFormatting: 'Paragraph formatting', documentStyle: 'Document Style', extraKeys: 'Extra keys' }, help: { 'escape': 'Escape', 'insertParagraph': 'Insert Paragraph', 'undo': 'Undo the last command', 'redo': 'Redo the last command', 'tab': 'Tab', 'untab': 'Untab', 'bold': 'Set a bold style', 'italic': 'Set a italic style', 'underline': 'Set a underline style', 'strikethrough': 'Set a strikethrough style', 'removeFormat': 'Clean a style', 'justifyLeft': 'Set left align', 'justifyCenter': 'Set center align', 'justifyRight': 'Set right align', 'justifyFull': 'Set full align', 'insertUnorderedList': 'Toggle unordered list', 'insertOrderedList': 'Toggle ordered list', 'outdent': 'Outdent on current paragraph', 'indent': 'Indent on current paragraph', 'formatPara': 'Change current block\'s format as a paragraph(P tag)', 'formatH1': 'Change current block\'s format as H1', 'formatH2': 'Change current block\'s format as H2', 'formatH3': 'Change current block\'s format as H3', 'formatH4': 'Change current block\'s format as H4', 'formatH5': 'Change current block\'s format as H5', 'formatH6': 'Change current block\'s format as H6', 'insertHorizontalRule': 'Insert horizontal rule', 'linkDialog.show': 'Show Link Dialog' }, history: { undo: 'Undo', redo: 'Redo' }, specialChar: { specialChar: 'SPECIAL CHARACTERS', select: 'Select Special characters' }, output: { noSelection: 'No Selection Made!' } } }); /***/ }), /***/ 1145: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_MODULE__1145__; /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. (() => { // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXTERNAL MODULE: external "jQuery" var external_jQuery_ = __webpack_require__(1145); var external_jQuery_default = /*#__PURE__*/__webpack_require__.n(external_jQuery_); // EXTERNAL MODULE: ./src/lang/summernote-en-US.js var summernote_en_US = __webpack_require__(9770); ;// CONCATENATED MODULE: ./src/js/core/env.js /** * returns whether font is installed or not. * * @param {String} fontName * @return {Boolean} */ var genericFontFamilies = ['sans-serif', 'serif', 'monospace', 'cursive', 'fantasy']; function validFontName(fontName) { return external_jQuery_default().inArray(fontName.toLowerCase(), genericFontFamilies) === -1 ? "'".concat(fontName, "'") : fontName; } function isFontInstalled(fontName) { var testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS'; var testText = 'mmmmmmmmmmwwwww'; var testSize = '200px'; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); context.font = testSize + " '" + testFontName + "'"; var originalWidth = context.measureText(testText).width; context.font = testSize + ' ' + validFontName(fontName) + ', "' + testFontName + '"'; var width = context.measureText(testText).width; return originalWidth !== width; } var userAgent = navigator.userAgent; var isMSIE = /MSIE|Trident/i.test(userAgent); var browserVersion; if (isMSIE) { var matches = /MSIE (\d+[.]\d+)/.exec(userAgent); if (matches) { browserVersion = parseFloat(matches[1]); } matches = /Trident\/.*rv:([0-9]{1,}[.0-9]{0,})/.exec(userAgent); if (matches) { browserVersion = parseFloat(matches[1]); } } var isEdge = /Edge\/\d+/.test(userAgent); var isSupportTouch = 'ontouchstart' in window || navigator.MaxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; // [workaround] IE doesn't have input events for contentEditable // - see: https://goo.gl/4bfIvA var inputEventName = isMSIE ? 'DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted' : 'input'; /** * @class core.env * * Object which check platform and agent * * @singleton * @alternateClassName env */ /* harmony default export */ const env = ({ isMac: navigator.appVersion.indexOf('Mac') > -1, isMSIE: isMSIE, isEdge: isEdge, isFF: !isEdge && /firefox/i.test(userAgent), isPhantom: /PhantomJS/i.test(userAgent), isWebkit: !isEdge && /webkit/i.test(userAgent), isChrome: !isEdge && /chrome/i.test(userAgent), isSafari: !isEdge && /safari/i.test(userAgent) && !/chrome/i.test(userAgent), browserVersion: browserVersion, isSupportTouch: isSupportTouch, isFontInstalled: isFontInstalled, isW3CRangeSupport: !!document.createRange, inputEventName: inputEventName, genericFontFamilies: genericFontFamilies, validFontName: validFontName }); ;// CONCATENATED MODULE: ./src/js/core/func.js /** * @class core.func * * func utils (for high-order func's arg) * * @singleton * @alternateClassName func */ function eq(itemA) { return function (itemB) { return itemA === itemB; }; } function eq2(itemA, itemB) { return itemA === itemB; } function peq2(propName) { return function (itemA, itemB) { return itemA[propName] === itemB[propName]; }; } function ok() { return true; } function fail() { return false; } function not(f) { return function () { return !f.apply(f, arguments); }; } function and(fA, fB) { return function (item) { return fA(item) && fB(item); }; } function func_self(a) { return a; } function invoke(obj, method) { return function () { return obj[method].apply(obj, arguments); }; } var idCounter = 0; /** * reset globally-unique id * */ function resetUniqueId() { idCounter = 0; } /** * generate a globally-unique id * * @param {String} [prefix] */ function uniqueId(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 */ function rect2bnd(rect) { var $document = external_jQuery_default()(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} */ function invertObject(obj) { var inverted = {}; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { inverted[obj[key]] = key; } } return inverted; } /** * @param {String} namespace * @param {String} [prefix] * @return {String} */ function namespaceToCamel(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} */ function debounce(func, wait, immediate) { var timeout; return function () { var context = this; var args = arguments; var later = function later() { timeout = null; if (!immediate) { func.apply(context, args); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; } /** * * @param {String} url * @return {Boolean} */ function isValidUrl(url) { var expression = /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/gi; return expression.test(url); } /* harmony default export */ const func = ({ eq: eq, eq2: eq2, peq2: peq2, ok: ok, fail: fail, self: func_self, not: not, and: and, invoke: invoke, resetUniqueId: resetUniqueId, uniqueId: uniqueId, rect2bnd: rect2bnd, invertObject: invertObject, namespaceToCamel: namespaceToCamel, debounce: debounce, isValidUrl: isValidUrl }); ;// CONCATENATED MODULE: ./src/js/core/lists.js /** * returns the first item of an array. * * @param {Array} array */ function head(array) { return array[0]; } /** * returns the last item of an array. * * @param {Array} array */ function last(array) { return array[array.length - 1]; } /** * returns everything but the last entry of the array. * * @param {Array} array */ function initial(array) { return array.slice(0, array.length - 1); } /** * returns the rest of the items in an array. * * @param {Array} array */ function tail(array) { return array.slice(1); } /** * returns item of array */ function find(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. */ function lists_all(array, pred) { for (var idx = 0, len = array.length; idx < len; idx++) { if (!pred(array[idx])) { return false; } } return true; } /** * returns true if the value is present in the list. */ function contains(array, item) { if (array && array.length && item) { if (array.indexOf) { return array.indexOf(item) !== -1; } else if (array.contains) { // `DOMTokenList` doesn't implement `.indexOf`, but it implements `.contains` return array.contains(item); } } return false; } /** * get sum from a list * * @param {Array} array - array * @param {Function} fn - iterator */ function sum(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, ... */ function from(collection) { var result = []; var length = collection.length; var idx = -1; while (++idx < length) { result[idx] = collection[idx]; } return result; } /** * returns whether list is empty or not */ function isEmpty(array) { return !array || !array.length; } /** * cluster elements by predicate function. * * @param {Array} array - array * @param {Function} fn - predicate function for cluster rule * @param {Array[]} */ function clusterBy(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 */ function compact(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 */ function unique(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 */ function next(array, item) { if (array && array.length && item) { var idx = array.indexOf(item); return idx === -1 ? null : array[idx + 1]; } return null; } /** * returns prev item. * @param {Array} array */ function prev(array, item) { if (array && array.length && item) { var idx = array.indexOf(item); return idx === -1 ? null : array[idx - 1]; } return null; } /** * @class core.list * * list utils * * @singleton * @alternateClassName list */ /* harmony default export */ const lists = ({ head: head, last: last, initial: initial, tail: tail, prev: prev, next: next, find: find, contains: contains, all: lists_all, sum: sum, from: from, isEmpty: isEmpty, clusterBy: clusterBy, compact: compact, unique: unique }); ;// CONCATENATED MODULE: ./src/js/core/dom.js var NBSP_CHAR = String.fromCharCode(160); var ZERO_WIDTH_NBSP_CHAR = "\uFEFF"; /** * @method isEditable * * returns whether node is `note-editable` or not. * * @param {Node} node * @return {Boolean} */ function isEditable(node) { return node && external_jQuery_default()(node).hasClass('note-editable'); } /** * @method isControlSizing * * returns whether node is `note-control-sizing` or not. * * @param {Node} node * @return {Boolean} */ function isControlSizing(node) { return node && external_jQuery_default()(node).hasClass('note-control-sizing'); } /** * @method makePredByNodeName * * returns predicate which judge whether nodeName is same * * @param {String} nodeName * @return {Function} */ function makePredByNodeName(nodeName) { nodeName = nodeName.toUpperCase(); return function (node) { return node && node.nodeName.toUpperCase() === nodeName; }; } /** * @method isText * * * * @param {Node} node * @return {Boolean} true if node's type is text(3) */ function isText(node) { return node && node.nodeType === 3; } /** * @method isElement * * * * @param {Node} node * @return {Boolean} true if node's type is element(1) */ function isElement(node) { return node && node.nodeType === 1; } /** * ex) br, col, embed, hr, img, input, ... * @see http://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements */ function isVoid(node) { return node && /^BR|^IMG|^HR|^IFRAME|^BUTTON|^INPUT|^AUDIO|^VIDEO|^EMBED/.test(node.nodeName.toUpperCase()); } function isPara(node) { if (isEditable(node)) { return false; } // Chrome(v31.0), FF(v25.0.1) use DIV for paragraph return node && /^DIV|^P|^LI|^H[1-7]/.test(node.nodeName.toUpperCase()); } function isHeading(node) { return node && /^H[1-7]/.test(node.nodeName.toUpperCase()); } var isPre = makePredByNodeName('PRE'); var isLi = makePredByNodeName('LI'); function isPurePara(node) { return isPara(node) && !isLi(node); } var isTable = makePredByNodeName('TABLE'); var isData = makePredByNodeName('DATA'); function isInline(node) { return !isBodyContainer(node) && !isList(node) && !isHr(node) && !isPara(node) && !isTable(node) && !isBlockquote(node) && !isData(node); } function isList(node) { return node && /^UL|^OL/.test(node.nodeName.toUpperCase()); } var isHr = makePredByNodeName('HR'); function isCell(node) { return node && /^TD|^TH/.test(node.nodeName.toUpperCase()); } var isBlockquote = makePredByNodeName('BLOCKQUOTE'); function isBodyContainer(node) { return isCell(node) || isBlockquote(node) || isEditable(node); } var isAnchor = makePredByNodeName('A'); function isParaInline(node) { return isInline(node) && !!ancestor(node, isPara); } function isBodyInline(node) { return isInline(node) && !ancestor(node, isPara); } var isBody = makePredByNodeName('BODY'); /** * returns whether nodeB is closest sibling of nodeA * * @param {Node} nodeA * @param {Node} nodeB * @return {Boolean} */ function isClosestSibling(nodeA, nodeB) { return nodeA.nextSibling === nodeB || nodeA.previousSibling === nodeB; } /** * returns array of closest siblings with node * * @param {Node} node * @param {function} [pred] - predicate function * @return {Node[]} */ function withClosestSiblings(node, pred) { pred = pred || func.ok; var siblings = []; if (node.previousSibling && pred(node.previousSibling)) { siblings.push(node.previousSibling); } siblings.push(node); if (node.nextSibling && pred(node.nextSibling)) { siblings.push(node.nextSibling); } return siblings; } /** * blank HTML for cursor position * - [workaround] old IE only works with &nbsp; * - [workaround] IE11 and other browser works with bogus br */ var blankHTML = env.isMSIE && env.browserVersion < 11 ? '&nbsp;' : '<br>'; /** * @method nodeLength * * returns #text's text size or element's childNodes size * * @param {Node} node */ function nodeLength(node) { if (isText(node)) { return node.nodeValue.length; } if (node) { return node.childNodes.length; } return 0; } /** * returns whether deepest child node is empty or not. * * @param {Node} node * @return {Boolean} */ function deepestChildIsEmpty(node) { do { if (node.firstElementChild === null || node.firstElementChild.innerHTML === '') break; } while (node = node.firstElementChild); return dom_isEmpty(node); } /** * returns whether node is empty or not. * * @param {Node} node * @return {Boolean} */ function dom_isEmpty(node) { var len = nodeLength(node); if (len === 0) { return true; } else if (!isText(node) && len === 1 && node.innerHTML === blankHTML) { // ex) <p><br></p>, <span><br></span> return true; } else if (lists.all(node.childNodes, isText) && node.innerHTML === '') { // ex) <p></p>, <span></span> return true; } return false; } /** * padding blankHTML if node is empty (for cursor position) */ function paddingBlankHTML(node) { if (!isVoid(node) && !nodeLength(node)) { node.innerHTML = blankHTML; } } /** * find nearest ancestor predicate hit * * @param {Node} node * @param {Function} pred - predicate function */ function ancestor(node, pred) { while (node) { if (pred(node)) { return node; } if (isEditable(node)) { break; } node = node.parentNode; } return null; } /** * find nearest ancestor only single child blood line and predicate hit * * @param {Node} node * @param {Function} pred - predicate function */ function singleChildAncestor(node, pred) { node = node.parentNode; while (node) { if (nodeLength(node) !== 1) { break; } if (pred(node)) { return node; } if (isEditable(node)) { break; } node = node.parentNode; } return null; } /** * returns new array of ancestor nodes (until predicate hit). * * @param {Node} node * @param {Function} [optional] pred - predicate function */ function listAncestor(node, pred) { pred = pred || func.fail; var ancestors = []; ancestor(node, function (el) { if (!isEditable(el)) { ancestors.push(el); } return pred(el); }); return ancestors; } /** * find farthest ancestor predicate hit */ function lastAncestor(node, pred) { var ancestors = listAncestor(node); return lists.last(ancestors.filter(pred)); } /** * returns common ancestor node between two nodes. * * @param {Node} nodeA * @param {Node} nodeB */ function commonAncestor(nodeA, nodeB) { var ancestors = listAncestor(nodeA); for (var n = nodeB; n; n = n.parentNode) { if (ancestors.indexOf(n) > -1) return n; } return null; // difference document area } /** * listing all previous siblings (until predicate hit). * * @param {Node} node * @param {Function} [optional] pred - predicate function */ function listPrev(node, pred) { pred = pred || func.fail; var nodes = []; while (node) { if (pred(node)) { break; } nodes.push(node); node = node.previousSibling; } return nodes; } /** * listing next siblings (until predicate hit). * * @param {Node} node * @param {Function} [pred] - predicate function */ function listNext(node, pred) { pred = pred || func.fail; var nodes = []; while (node) { if (pred(node)) { break; } nodes.push(node); node = node.nextSibling; } return nodes; } /** * listing descendant nodes * * @param {Node} node * @param {Function} [pred] - predicate function */ function listDescendant(node, pred) { var descendants = []; pred = pred || func.ok; // start DFS(depth first search) with node (function fnWalk(current) { if (node !== current && pred(current)) { descendants.push(current); } for (var idx = 0, len = current.childNodes.length; idx < len; idx++) { fnWalk(current.childNodes[idx]); } })(node); return descendants; } /** * wrap node with new tag. * * @param {Node} node * @param {Node} tagName of wrapper * @return {Node} - wrapper */ function wrap(node, wrapperName) { var parent = node.parentNode; var wrapper = external_jQuery_default()('<' + wrapperName + '>')[0]; parent.insertBefore(wrapper, node); wrapper.appendChild(node); return wrapper; } /** * insert node after preceding * * @param {Node} node * @param {Node} preceding - predicate function */ function insertAfter(node, preceding) { var next = preceding.nextSibling; var parent = preceding.parentNode; if (next) { parent.insertBefore(node, next); } else { parent.appendChild(node); } return node; } /** * append elements. * * @param {Node} node * @param {Collection} aChild */ function appendChildNodes(node, aChild) { external_jQuery_default().each(aChild, function (idx, child) { node.appendChild(child); }); return node; } /** * returns whether boundaryPoint is left edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isLeftEdgePoint(point) { return point.offset === 0; } /** * returns whether boundaryPoint is right edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isRightEdgePoint(point) { return point.offset === nodeLength(point.node); } /** * returns whether boundaryPoint is edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isEdgePoint(point) { return isLeftEdgePoint(point) || isRightEdgePoint(point); } /** * returns whether node is left edge of ancestor or not. * * @param {Node} node * @param {Node} ancestor * @return {Boolean} */ function isLeftEdgeOf(node, ancestor) { while (node && node !== ancestor) { if (position(node) !== 0) { return false; } node = node.parentNode; } return true; } /** * returns whether node is right edge of ancestor or not. * * @param {Node} node * @param {Node} ancestor * @return {Boolean} */ function isRightEdgeOf(node, ancestor) { if (!ancestor) { return false; } while (node && node !== ancestor) { if (position(node) !== nodeLength(node.parentNode) - 1) { return false; } node = node.parentNode; } return true; } /** * returns whether point is left edge of ancestor or not. * @param {BoundaryPoint} point * @param {Node} ancestor * @return {Boolean} */ function isLeftEdgePointOf(point, ancestor) { return isLeftEdgePoint(point) && isLeftEdgeOf(point.node, ancestor); } /** * returns whether point is right edge of ancestor or not. * @param {BoundaryPoint} point * @param {Node} ancestor * @return {Boolean} */ function isRightEdgePointOf(point, ancestor) { return isRightEdgePoint(point) && isRightEdgeOf(point.node, ancestor); } /** * returns offset from parent. * * @param {Node} node */ function position(node) { var offset = 0; while (node = node.previousSibling) { offset += 1; } return offset; } function hasChildren(node) { return !!(node && node.childNodes && node.childNodes.length); } /** * returns previous boundaryPoint * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function prevPoint(point, isSkipInnerOffset) { var node; var offset; if (point.offset === 0) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node); } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset - 1]; offset = nodeLength(node); } else { node = point.node; offset = isSkipInnerOffset ? 0 : point.offset - 1; } return { node: node, offset: offset }; } /** * returns next boundaryPoint * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function nextPoint(point, isSkipInnerOffset) { var node, offset; if (nodeLength(point.node) === point.offset) { if (isEditable(point.node)) { return null; } var nextTextNode = getNextTextNode(point.node); if (nextTextNode) { node = nextTextNode; offset = 0; } else { node = point.node.parentNode; offset = position(point.node) + 1; } } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset]; offset = 0; } else { node = point.node; offset = isSkipInnerOffset ? nodeLength(point.node) : point.offset + 1; } return { node: node, offset: offset }; } /** * returns next boundaryPoint with empty node * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function nextPointWithEmptyNode(point, isSkipInnerOffset) { var node, offset = 0; // if node is empty string node, return current node's sibling. if (dom_isEmpty(point.node)) { if (point.node === null) { return null; } node = point.node.nextSibling; offset = 0; return { node: node, offset: offset }; } if (nodeLength(point.node) === point.offset) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node) + 1; // if next node is editable , return current node's sibling node. if (isEditable(node)) { node = point.node.nextSibling; offset = 0; } } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset]; offset = 0; if (dom_isEmpty(node)) { if (!dom_isEmpty(point.node.nextSibling)) { return { node: point.node.nextSibling, offset: offset }; } return null; } } else { node = point.node; offset = isSkipInnerOffset ? nodeLength(point.node) : point.offset + 1; if (dom_isEmpty(node)) { return null; } } return { node: node, offset: offset }; } /* * returns the next Text node index or 0 if not found. */ function getNextTextNode(actual) { if (!actual.nextSibling) return undefined; if (actual.parent !== actual.nextSibling.parent) return undefined; if (isText(actual.nextSibling)) return actual.nextSibling;else return getNextTextNode(actual.nextSibling); } /** * returns whether pointA and pointB is same or not. * * @param {BoundaryPoint} pointA * @param {BoundaryPoint} pointB * @return {Boolean} */ function isSamePoint(pointA, pointB) { return pointA.node === pointB.node && pointA.offset === pointB.offset; } /** * returns whether point is visible (can set cursor) or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isVisiblePoint(point) { if (isText(point.node) || !hasChildren(point.node) || dom_isEmpty(point.node)) { return true; } var leftNode = point.node.childNodes[point.offset - 1]; var rightNode = point.node.childNodes[point.offset]; if ((!leftNode || isVoid(leftNode)) && (!rightNode || isVoid(rightNode)) || isTable(rightNode)) { return true; } return false; } /** * @method prevPointUtil * * @param {BoundaryPoint} point * @param {Function} pred * @return {BoundaryPoint} */ function prevPointUntil(point, pred) { while (point) { if (pred(point)) { return point; } point = prevPoint(point); } return null; } /** * @method nextPointUntil * * @param {BoundaryPoint} point * @param {Function} pred * @return {BoundaryPoint} */ function nextPointUntil(point, pred) { while (point) { if (pred(point)) { return point; } point = nextPoint(point); } return null; } /** * returns whether point has character or not. * * @param {Point} point * @return {Boolean} */ function isCharPoint(point) { if (!isText(point.node)) { return false; } var ch = point.node.nodeValue.charAt(point.offset - 1); return ch && ch !== ' ' && ch !== NBSP_CHAR; } /** * returns whether point has space or not. * * @param {Point} point * @return {Boolean} */ function isSpacePoint(point) { if (!isText(point.node)) { return false; } var ch = point.node.nodeValue.charAt(point.offset - 1); return ch === ' ' || ch === NBSP_CHAR; } /** * @method walkPoint * * @param {BoundaryPoint} startPoint * @param {BoundaryPoint} endPoint * @param {Function} handler * @param {Boolean} isSkipInnerOffset */ function walkPoint(startPoint, endPoint, handler, isSkipInnerOffset) { var point = startPoint; while (point) { handler(point); if (isSamePoint(point, endPoint)) { break; } var isSkipOffset = isSkipInnerOffset && startPoint.node !== point.node && endPoint.node !== point.node; point = nextPointWithEmptyNode(point, isSkipOffset); } } /** * @method makeOffsetPath * * return offsetPath(array of offset) from ancestor * * @param {Node} ancestor - ancestor node * @param {Node} node */ function makeOffsetPath(ancestor, node) { var ancestors = listAncestor(node, func.eq(ancestor)); return ancestors.map(position).reverse(); } /** * @method fromOffsetPath * * return element from offsetPath(array of offset) * * @param {Node} ancestor - ancestor node * @param {array} offsets - offsetPath */ function fromOffsetPath(ancestor, offsets) { var current = ancestor; for (var i = 0, len = offsets.length; i < len; i++) { if (current.childNodes.length <= offsets[i]) { current = current.childNodes[current.childNodes.length - 1]; } else { current = current.childNodes[offsets[i]]; } } return current; } /** * @method splitNode * * split element or #text * * @param {BoundaryPoint} point * @param {Object} [options] * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false * @param {Boolean} [options.isNotSplitEdgePoint] - default: false * @param {Boolean} [options.isDiscardEmptySplits] - default: false * @return {Node} right node of boundaryPoint */ function splitNode(point, options) { var isSkipPaddingBlankHTML = options && options.isSkipPaddingBlankHTML; var isNotSplitEdgePoint = options && options.isNotSplitEdgePoint; var isDiscardEmptySplits = options && options.isDiscardEmptySplits; if (isDiscardEmptySplits) { isSkipPaddingBlankHTML = true; } // edge case if (isEdgePoint(point) && (isText(point.node) || isNotSplitEdgePoint)) { if (isLeftEdgePoint(point)) { return point.node; } else if (isRightEdgePoint(point)) { return point.node.nextSibling; } } // split #text if (isText(point.node)) { return point.node.splitText(point.offset); } else { var childNode = point.node.childNodes[point.offset]; var clone = insertAfter(point.node.cloneNode(false), point.node); appendChildNodes(clone, listNext(childNode)); if (!isSkipPaddingBlankHTML) { paddingBlankHTML(point.node); paddingBlankHTML(clone); } if (isDiscardEmptySplits) { if (dom_isEmpty(point.node)) { remove(point.node); } if (dom_isEmpty(clone)) { remove(clone); return point.node.nextSibling; } } return clone; } } /** * @method splitTree * * split tree by point * * @param {Node} root - split root * @param {BoundaryPoint} point * @param {Object} [options] * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false * @param {Boolean} [options.isNotSplitEdgePoint] - default: false * @return {Node} right node of boundaryPoint */ function splitTree(root, point, options) { // ex) [#text, <span>, <p>] 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 ? position(node) : nodeLength(parent) }, options); }); } /** * split point * * @param {Point} point * @param {Boolean} isInline * @return {Object} */ function splitPoint(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 = lists.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 }; } function create(nodeName) { return document.createElement(nodeName); } function createText(text) { return document.createTextNode(text); } /** * @method remove * * remove node, (isRemoveChild: remove child or not) * * @param {Node} node * @param {Boolean} isRemoveChild */ function remove(node, isRemoveChild) { if (!node || !node.parentNode) { return; } if (node.removeNode) { return node.removeNode(isRemoveChild); } var parent = node.parentNode; if (!isRemoveChild) { var nodes = []; for (var i = 0, len = node.childNodes.length; i < len; i++) { nodes.push(node.childNodes[i]); } for (var _i = 0, _len = nodes.length; _i < _len; _i++) { parent.insertBefore(nodes[_i], node); } } parent.removeChild(node); } /** * @method removeWhile * * @param {Node} node * @param {Function} pred */ function removeWhile(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 */ function replace(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, lists.from(node.childNodes)); insertAfter(newNode, node); remove(node); return newNode; } var isTextarea = makePredByNodeName('TEXTAREA'); /** * @param {jQuery} $node * @param {Boolean} [stripLinebreaks] - default: false */ function value($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] */ function html($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 = markup.trim(); } return markup; } function posFromPlaceholder(placeholder) { var $placeholder = external_jQuery_default()(placeholder); var pos = $placeholder.offset(); var height = $placeholder.outerHeight(true); // include margin return { left: pos.left, top: pos.top + height }; } function attachEvents($node, events) { Object.keys(events).forEach(function (key) { $node.on(key, events[key]); }); } function detachEvents($node, events) { Object.keys(events).forEach(function (key) { $node.off(key, events[key]); }); } /** * @method isCustomStyleTag * * assert if a node contains a "note-styletag" class, * which implies that's a custom-made style tag node * * @param {Node} an HTML DOM node */ function isCustomStyleTag(node) { return node && !isText(node) && lists.contains(node.classList, 'note-styletag'); } /* harmony default export */ const dom = ({ /** @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: "<p>".concat(blankHTML, "</p>"), 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, deepestChildIsEmpty: deepestChildIsEmpty, isEmpty: dom_isEmpty, isEmptyAnchor: func.and(isAnchor, dom_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, nextPointWithEmptyNode: nextPointWithEmptyNode, isSamePoint: isSamePoint, isVisiblePoint: isVisiblePoint, prevPointUntil: prevPointUntil, nextPointUntil: nextPointUntil, isCharPoint: isCharPoint, isSpacePoint: isSpacePoint, 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, isCustomStyleTag: isCustomStyleTag }); ;// CONCATENATED MODULE: ./src/js/Context.js function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var Context = /*#__PURE__*/function () { /** * @param {jQuery} $note * @param {Object} options */ function Context($note, options) { _classCallCheck(this, Context); this.$note = $note; this.memos = {}; this.modules = {}; this.layoutInfo = {}; this.options = external_jQuery_default().extend(true, {}, options); // init ui with options (external_jQuery_default()).summernote.ui = external_jQuery_default().summernote.ui_template(this.options); this.ui = (external_jQuery_default()).summernote.ui; this.initialize(); } /** * create layout and initialize modules and other resources */ _createClass(Context, [{ key: "initialize", value: function initialize() { this.layoutInfo = this.ui.createLayout(this.$note); this._initialize(); this.$note.hide(); return this; } /** * destroy modules and other resources and remove layout */ }, { key: "destroy", value: function destroy() { this._destroy(); this.$note.removeData('summernote'); this.ui.removeLayout(this.$note, this.layoutInfo); } /** * destory modules and other resources and initialize it again */ }, { key: "reset", value: function reset() { var disabled = this.isDisabled(); this.code(dom.emptyPara); this._destroy(); this._initialize(); if (disabled) { this.disable(); } } }, { key: "_initialize", value: function _initialize() { var _this = this; // set own id this.options.id = func.uniqueId(external_jQuery_default().now()); // set default container for tooltips, popovers, and dialogs this.options.container = this.options.container || this.layoutInfo.editor; // add optional buttons var buttons = external_jQuery_default().extend({}, this.options.buttons); Object.keys(buttons).forEach(function (key) { _this.memo('button.' + key, buttons[key]); }); var modules = external_jQuery_default().extend({}, this.options.modules, (external_jQuery_default()).summernote.plugins || {}); // add and initialize modules Object.keys(modules).forEach(function (key) { _this.module(key, modules[key], true); }); Object.keys(this.modules).forEach(function (key) { _this.initializeModule(key); }); } }, { key: "_destroy", value: function _destroy() { var _this2 = this; // destroy modules with reversed order Object.keys(this.modules).reverse().forEach(function (key) { _this2.removeModule(key); }); Object.keys(this.memos).forEach(function (key) { _this2.removeMemo(key); }); // trigger custom onDestroy callback this.triggerEvent('destroy', this); } }, { key: "code", value: function code(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.invoke('codeview.sync', html); } else { this.layoutInfo.editable.html(html); } this.$note.val(html); this.triggerEvent('change', html, this.layoutInfo.editable); } } }, { key: "isDisabled", value: function isDisabled() { return this.layoutInfo.editable.attr('contenteditable') === 'false'; } }, { key: "enable", value: function enable() { this.layoutInfo.editable.attr('contenteditable', true); this.invoke('toolbar.activate', true); this.triggerEvent('disable', false); this.options.editing = true; } }, { key: "disable", value: function disable() { // close codeview if codeview is opend if (this.invoke('codeview.isActivated')) { this.invoke('codeview.deactivate'); } this.layoutInfo.editable.attr('contenteditable', false); this.options.editing = false; this.invoke('toolbar.deactivate', true); this.triggerEvent('disable', true); } }, { key: "triggerEvent", value: function triggerEvent() { var namespace = lists.head(arguments); var args = lists.tail(lists.from(arguments)); var callback = this.options.callbacks[func.namespaceToCamel(namespace, 'on')]; if (callback) { callback.apply(this.$note[0], args); } this.$note.trigger('summernote.' + namespace, args); } }, { key: "initializeModule", value: function initializeModule(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(this.$note, module.events); } } }, { key: "module", value: function module(key, ModuleClass, withoutIntialize) { if (arguments.length === 1) { return this.modules[key]; } this.modules[key] = new ModuleClass(this); if (!withoutIntialize) { this.initializeModule(key); } } }, { key: "removeModule", value: function removeModule(key) { var module = this.modules[key]; if (module.shouldInitialize()) { if (module.events) { dom.detachEvents(this.$note, module.events); } if (module.destroy) { module.destroy(); } } delete this.modules[key]; } }, { key: "memo", value: function memo(key, obj) { if (arguments.length === 1) { return this.memos[key]; } this.memos[key] = obj; } }, { key: "removeMemo", value: function removeMemo(key) { if (this.memos[key] && this.memos[key].destroy) { this.memos[key].destroy(); } delete this.memos[key]; } /** * Some buttons need to change their visual style immediately once they get pressed */ }, { key: "createInvokeHandlerAndUpdateState", value: function createInvokeHandlerAndUpdateState(namespace, value) { var _this3 = this; return function (event) { _this3.createInvokeHandler(namespace, value)(event); _this3.invoke('buttons.updateCurrentStyle'); }; } }, { key: "createInvokeHandler", value: function createInvokeHandler(namespace, value) { var _this4 = this; return function (event) { event.preventDefault(); var $target = external_jQuery_default()(event.target); _this4.invoke(namespace, value || $target.closest('[data-value]').data('value'), $target); }; } }, { key: "invoke", value: function invoke() { var namespace = lists.head(arguments); var args = lists.tail(lists.from(arguments)); var splits = namespace.split('.'); var hasSeparator = splits.length > 1; var moduleName = hasSeparator && lists.head(splits); var methodName = hasSeparator ? lists.last(splits) : lists.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 Context; }(); ;// CONCATENATED MODULE: ./src/js/summernote.js external_jQuery_default().fn.extend({ /** * Summernote API * * @param {Object|String} * @return {this} */ summernote: function summernote() { var type = external_jQuery_default().type(lists.head(arguments)); var isExternalAPICalled = type === 'string'; var hasInitOptions = type === 'object'; var options = external_jQuery_default().extend({}, (external_jQuery_default()).summernote.options, hasInitOptions ? lists.head(arguments) : {}); // Update options options.langInfo = external_jQuery_default().extend(true, {}, (external_jQuery_default()).summernote.lang["en-US"], (external_jQuery_default()).summernote.lang[options.lang]); options.icons = external_jQuery_default().extend(true, {}, (external_jQuery_default()).summernote.options.icons, options.icons); options.tooltip = options.tooltip === 'auto' ? !env.isSupportTouch : options.tooltip; this.each(function (idx, note) { var $note = external_jQuery_default()(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, lists.from(arguments)); } else if (options.focus) { context.invoke('editor.focus'); } } return this; } }); ;// CONCATENATED MODULE: ./src/js/core/range.js function range_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function range_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function range_createClass(Constructor, protoProps, staticProps) { if (protoProps) range_defineProperties(Constructor.prototype, protoProps); if (staticProps) range_defineProperties(Constructor, staticProps); return Constructor; } /** * return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js * * @param {TextRange} textRange * @param {Boolean} isStart * @return {BoundaryPoint} * * @see http://msdn.microsoft.com/en-us/library/ie/ms535872(v=vs.85).aspx */ function textRangeToPoint(textRange, isStart) { var container = textRange.parentElement(); var offset; var tester = document.body.createTextRange(); var prevContainer; var childNodes = lists.from(container.childNodes); for (offset = 0; offset < childNodes.length; offset++) { if (dom.isText(childNodes[offset])) { continue; } tester.moveToElementText(childNodes[offset]); if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; } prevContainer = childNodes[offset]; } if (offset !== 0 && dom.isText(childNodes[offset - 1])) { var textRangeStart = document.body.createTextRange(); var curTextNode = null; textRangeStart.moveToElementText(prevContainer || container); textRangeStart.collapse(!prevContainer); curTextNode = prevContainer ? prevContainer.nextSibling : container.firstChild; var pointTester = textRange.duplicate(); pointTester.setEndPoint('StartToStart', textRangeStart); var textCount = pointTester.text.replace(/[\r\n]/g, '').length; while (textCount > curTextNode.nodeValue.length && curTextNode.nextSibling) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } // [workaround] enforce IE to re-reference curTextNode, hack var dummy = curTextNode.nodeValue; // eslint-disable-line if (isStart && curTextNode.nextSibling && dom.isText(curTextNode.nextSibling) && textCount === curTextNode.nodeValue.length) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } container = curTextNode; offset = textCount; } return { cont: container, offset: offset }; } /** * return TextRange from boundary point (inspired by google closure-library) * @param {BoundaryPoint} point * @return {TextRange} */ function pointToTextRange(point) { var textRangeInfo = function textRangeInfo(container, offset) { var node, isCollapseToStart; if (dom.isText(container)) { var prevTextNodes = dom.listPrev(container, func.not(dom.isText)); var prevContainer = lists.last(prevTextNodes).previousSibling; node = prevContainer || container.parentNode; offset += lists.sum(lists.tail(prevTextNodes), dom.nodeLength); isCollapseToStart = !prevContainer; } else { node = container.childNodes[offset] || container; if (dom.isText(node)) { return textRangeInfo(node, 0); } offset = 0; isCollapseToStart = false; } return { node: node, collapseToStart: isCollapseToStart, offset: offset }; }; var textRange = document.body.createTextRange(); var info = textRangeInfo(point.node, point.offset); textRange.moveToElementText(info.node); textRange.collapse(info.collapseToStart); textRange.moveStart('character', info.offset); return textRange; } /** * Wrapped Range * * @constructor * @param {Node} sc - start container * @param {Number} so - start offset * @param {Node} ec - end container * @param {Number} eo - end offset */ var WrappedRange = /*#__PURE__*/function () { function WrappedRange(sc, so, ec, eo) { range_classCallCheck(this, WrappedRange); this.sc = sc; this.so = so; this.ec = ec; this.eo = eo; // isOnEditable: judge whether range is on editable or not this.isOnEditable = this.makeIsOn(dom.isEditable); // isOnList: judge whether range is on list node or not this.isOnList = this.makeIsOn(dom.isList); // isOnAnchor: judge whether range is on anchor node or not this.isOnAnchor = this.makeIsOn(dom.isAnchor); // isOnCell: judge whether range is on cell node or not this.isOnCell = this.makeIsOn(dom.isCell); // isOnData: judge whether range is on data node or not this.isOnData = this.makeIsOn(dom.isData); } // nativeRange: get nativeRange from sc, so, ec, eo range_createClass(WrappedRange, [{ key: "nativeRange", value: function nativeRange() { if (env.isW3CRangeSupport) { var w3cRange = document.createRange(); w3cRange.setStart(this.sc, this.so); w3cRange.setEnd(this.ec, this.eo); return w3cRange; } else { var textRange = pointToTextRange({ node: this.sc, offset: this.so }); textRange.setEndPoint('EndToEnd', pointToTextRange({ node: this.ec, offset: this.eo })); return textRange; } } }, { key: "getPoints", value: function getPoints() { return { sc: this.sc, so: this.so, ec: this.ec, eo: this.eo }; } }, { key: "getStartPoint", value: function getStartPoint() { return { node: this.sc, offset: this.so }; } }, { key: "getEndPoint", value: function getEndPoint() { return { node: this.ec, offset: this.eo }; } /** * select update visible range */ }, { key: "select", value: function select() { var nativeRng = this.nativeRange(); if (env.isW3CRangeSupport) { var selection = document.getSelection(); if (selection.rangeCount > 0) { selection.removeAllRanges(); } selection.addRange(nativeRng); } else { nativeRng.select(); } return this; } /** * Moves the scrollbar to start container(sc) of current range * * @return {WrappedRange} */ }, { key: "scrollIntoView", value: function scrollIntoView(container) { var height = external_jQuery_default()(container).height(); if (container.scrollTop + height < this.sc.offsetTop) { container.scrollTop += Math.abs(container.scrollTop + height - this.sc.offsetTop); } return this; } /** * @return {WrappedRange} */ }, { key: "normalize", value: function normalize() { /** * @param {BoundaryPoint} point * @param {Boolean} isLeftToRight - true: prefer to choose right node * - false: prefer to choose left node * @return {BoundaryPoint} */ var getVisiblePoint = function getVisiblePoint(point, isLeftToRight) { if (!point) { return point; } // Just use the given point [XXX:Adhoc] // - case 01. if the point is on the middle of the node // - case 02. if the point is on the right edge and prefer to choose left node // - case 03. if the point is on the left edge and prefer to choose right node // - case 04. if the point is on the right edge and prefer to choose right node but the node is void // - case 05. if the point is on the left edge and prefer to choose left node but the node is void // - case 06. if the point is on the block node and there is no children if (dom.isVisiblePoint(point)) { if (!dom.isEdgePoint(point) || dom.isRightEdgePoint(point) && !isLeftToRight || dom.isLeftEdgePoint(point) && isLeftToRight || dom.isRightEdgePoint(point) && isLeftToRight && dom.isVoid(point.node.nextSibling) || dom.isLeftEdgePoint(point) && !isLeftToRight && dom.isVoid(point.node.previousSibling) || dom.isBlock(point.node) && dom.isEmpty(point.node)) { return point; } } // point on block's edge var block = dom.ancestor(point.node, dom.isBlock); var hasRightNode = false; if (!hasRightNode) { var prevPoint = dom.prevPoint(point) || { node: null }; hasRightNode = (dom.isLeftEdgePointOf(point, block) || dom.isVoid(prevPoint.node)) && !isLeftToRight; } var hasLeftNode = false; if (!hasLeftNode) { var _nextPoint = dom.nextPoint(point) || { node: null }; hasLeftNode = (dom.isRightEdgePointOf(point, block) || dom.isVoid(_nextPoint.node)) && isLeftToRight; } if (hasRightNode || hasLeftNode) { // returns point already on visible point if (dom.isVisiblePoint(point)) { return point; } // reverse direction isLeftToRight = !isLeftToRight; } var nextPoint = isLeftToRight ? dom.nextPointUntil(dom.nextPoint(point), dom.isVisiblePoint) : dom.prevPointUntil(dom.prevPoint(point), dom.isVisiblePoint); return nextPoint || point; }; var endPoint = getVisiblePoint(this.getEndPoint(), false); var startPoint = this.isCollapsed() ? endPoint : getVisiblePoint(this.getStartPoint(), true); return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns matched nodes on range * * @param {Function} [pred] - predicate function * @param {Object} [options] * @param {Boolean} [options.includeAncestor] * @param {Boolean} [options.fullyContains] * @return {Node[]} */ }, { key: "nodes", value: function nodes(pred, options) { pred = pred || func.ok; var includeAncestor = options && options.includeAncestor; var fullyContains = options && options.fullyContains; // TODO compare points and sort var startPoint = this.getStartPoint(); var endPoint = this.getEndPoint(); var nodes = []; var leftEdgeNodes = []; dom.walkPoint(startPoint, endPoint, function (point) { if (dom.isEditable(point.node)) { return; } var node; if (fullyContains) { if (dom.isLeftEdgePoint(point)) { leftEdgeNodes.push(point.node); } if (dom.isRightEdgePoint(point) && lists.contains(leftEdgeNodes, point.node)) { node = point.node; } } else if (includeAncestor) { node = dom.ancestor(point.node, pred); } else { node = point.node; } if (node && pred(node)) { nodes.push(node); } }, true); return lists.unique(nodes); } /** * returns commonAncestor of range * @return {Element} - commonAncestor */ }, { key: "commonAncestor", value: function commonAncestor() { return dom.commonAncestor(this.sc, this.ec); } /** * returns expanded range by pred * * @param {Function} pred - predicate function * @return {WrappedRange} */ }, { key: "expand", value: function expand(pred) { var startAncestor = dom.ancestor(this.sc, pred); var endAncestor = dom.ancestor(this.ec, pred); if (!startAncestor && !endAncestor) { return new WrappedRange(this.sc, this.so, this.ec, this.eo); } var boundaryPoints = this.getPoints(); if (startAncestor) { boundaryPoints.sc = startAncestor; boundaryPoints.so = 0; } if (endAncestor) { boundaryPoints.ec = endAncestor; boundaryPoints.eo = dom.nodeLength(endAncestor); } return new WrappedRange(boundaryPoints.sc, boundaryPoints.so, boundaryPoints.ec, boundaryPoints.eo); } /** * @param {Boolean} isCollapseToStart * @return {WrappedRange} */ }, { key: "collapse", value: function collapse(isCollapseToStart) { if (isCollapseToStart) { return new WrappedRange(this.sc, this.so, this.sc, this.so); } else { return new WrappedRange(this.ec, this.eo, this.ec, this.eo); } } /** * splitText on range */ }, { key: "splitText", value: function splitText() { var isSameContainer = this.sc === this.ec; var boundaryPoints = this.getPoints(); if (dom.isText(this.ec) && !dom.isEdgePoint(this.getEndPoint())) { this.ec.splitText(this.eo); } if (dom.isText(this.sc) && !dom.isEdgePoint(this.getStartPoint())) { boundaryPoints.sc = this.sc.splitText(this.so); boundaryPoints.so = 0; if (isSameContainer) { boundaryPoints.ec = boundaryPoints.sc; boundaryPoints.eo = this.eo - this.so; } } return new WrappedRange(boundaryPoints.sc, boundaryPoints.so, boundaryPoints.ec, boundaryPoints.eo); } /** * delete contents on range * @return {WrappedRange} */ }, { key: "deleteContents", value: function deleteContents() { if (this.isCollapsed()) { return this; } var rng = this.splitText(); var nodes = rng.nodes(null, { fullyContains: true }); // find new cursor point var point = dom.prevPointUntil(rng.getStartPoint(), function (point) { return !lists.contains(nodes, point.node); }); var emptyParents = []; external_jQuery_default().each(nodes, function (idx, node) { // find empty parents var parent = node.parentNode; if (point.node !== parent && dom.nodeLength(parent) === 1) { emptyParents.push(parent); } dom.remove(node, false); }); // remove empty parents external_jQuery_default().each(emptyParents, function (idx, node) { dom.remove(node, false); }); return new WrappedRange(point.node, point.offset, point.node, point.offset).normalize(); } /** * makeIsOn: return isOn(pred) function */ }, { key: "makeIsOn", value: function makeIsOn(pred) { return function () { var ancestor = dom.ancestor(this.sc, pred); return !!ancestor && ancestor === dom.ancestor(this.ec, pred); }; } /** * @param {Function} pred * @return {Boolean} */ }, { key: "isLeftEdgeOf", value: function isLeftEdgeOf(pred) { if (!dom.isLeftEdgePoint(this.getStartPoint())) { return false; } var node = dom.ancestor(this.sc, pred); return node && dom.isLeftEdgeOf(this.sc, node); } /** * returns whether range was collapsed or not */ }, { key: "isCollapsed", value: function isCollapsed() { return this.sc === this.ec && this.so === this.eo; } /** * wrap inline nodes which children of body with paragraph * * @return {WrappedRange} */ }, { key: "wrapBodyInlineWithPara", value: function wrapBodyInlineWithPara() { if (dom.isBodyContainer(this.sc) && dom.isEmpty(this.sc)) { this.sc.innerHTML = dom.emptyPara; return new WrappedRange(this.sc.firstChild, 0, this.sc.firstChild, 0); } /** * [workaround] firefox often create range on not visible point. so normalize here. * - firefox: |<p>text</p>| * - chrome: <p>|text|</p> */ var rng = this.normalize(); if (dom.isParaInline(this.sc) || dom.isPara(this.sc)) { return rng; } // find inline top ancestor var topAncestor; if (dom.isInline(rng.sc)) { var ancestors = dom.listAncestor(rng.sc, func.not(dom.isInline)); topAncestor = lists.last(ancestors); if (!dom.isInline(topAncestor)) { topAncestor = ancestors[ancestors.length - 2] || rng.sc.childNodes[rng.so]; } } else { topAncestor = rng.sc.childNodes[rng.so > 0 ? rng.so - 1 : 0]; } if (topAncestor) { // siblings not in paragraph var inlineSiblings = dom.listPrev(topAncestor, dom.isParaInline).reverse(); inlineSiblings = inlineSiblings.concat(dom.listNext(topAncestor.nextSibling, dom.isParaInline)); // wrap with paragraph if (inlineSiblings.length) { var para = dom.wrap(lists.head(inlineSiblings), 'p'); dom.appendChildNodes(para, lists.tail(inlineSiblings)); } } return this.normalize(); } /** * insert node at current cursor * * @param {Node} node * @return {Node} */ }, { key: "insertNode", value: function insertNode(node) { var rng = this; if (dom.isText(node) || dom.isInline(node)) { rng = this.wrapBodyInlineWithPara().deleteContents(); } var info = dom.splitPoint(rng.getStartPoint(), dom.isInline(node)); if (info.rightNode) { info.rightNode.parentNode.insertBefore(node, info.rightNode); if (dom.isEmpty(info.rightNode) && dom.isPara(node)) { info.rightNode.parentNode.removeChild(info.rightNode); } } else { info.container.appendChild(node); } return node; } /** * insert html at current cursor */ }, { key: "pasteHTML", value: function pasteHTML(markup) { markup = external_jQuery_default().trim(markup); var contentsContainer = external_jQuery_default()('<div></div>').html(markup)[0]; var childNodes = lists.from(contentsContainer.childNodes); // const rng = this.wrapBodyInlineWithPara().deleteContents(); var rng = this; var reversed = false; if (rng.so >= 0) { childNodes = childNodes.reverse(); reversed = true; } childNodes = childNodes.map(function (childNode) { return rng.insertNode(childNode); }); if (reversed) { childNodes = childNodes.reverse(); } return childNodes; } /** * returns text in range * * @return {String} */ }, { key: "toString", value: function toString() { var nativeRng = this.nativeRange(); return env.isW3CRangeSupport ? nativeRng.toString() : nativeRng.text; } /** * returns range for word before cursor * * @param {Boolean} [findAfter] - find after cursor, default: false * @return {WrappedRange} */ }, { key: "getWordRange", value: function getWordRange(findAfter) { var endPoint = this.getEndPoint(); if (!dom.isCharPoint(endPoint)) { return this; } var startPoint = dom.prevPointUntil(endPoint, function (point) { return !dom.isCharPoint(point); }); if (findAfter) { endPoint = dom.nextPointUntil(endPoint, function (point) { return !dom.isCharPoint(point); }); } return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns range for words before cursor * * @param {Boolean} [findAfter] - find after cursor, default: false * @return {WrappedRange} */ }, { key: "getWordsRange", value: function getWordsRange(findAfter) { var endPoint = this.getEndPoint(); var isNotTextPoint = function isNotTextPoint(point) { return !dom.isCharPoint(point) && !dom.isSpacePoint(point); }; if (isNotTextPoint(endPoint)) { return this; } var startPoint = dom.prevPointUntil(endPoint, isNotTextPoint); if (findAfter) { endPoint = dom.nextPointUntil(endPoint, isNotTextPoint); } return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns range for words before cursor that match with a Regex * * example: * range: 'hi @Peter Pan' * regex: '/@[a-z ]+/i' * return range: '@Peter Pan' * * @param {RegExp} [regex] * @return {WrappedRange|null} */ }, { key: "getWordsMatchRange", value: function getWordsMatchRange(regex) { var endPoint = this.getEndPoint(); var startPoint = dom.prevPointUntil(endPoint, function (point) { if (!dom.isCharPoint(point) && !dom.isSpacePoint(point)) { return true; } var rng = new WrappedRange(point.node, point.offset, endPoint.node, endPoint.offset); var result = regex.exec(rng.toString()); return result && result.index === 0; }); var rng = new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); var text = rng.toString(); var result = regex.exec(text); if (result && result[0].length === text.length) { return rng; } else { return null; } } /** * create offsetPath bookmark * * @param {Node} editable */ }, { key: "bookmark", value: function bookmark(editable) { return { s: { path: dom.makeOffsetPath(editable, this.sc), offset: this.so }, e: { path: dom.makeOffsetPath(editable, this.ec), offset: this.eo } }; } /** * create offsetPath bookmark base on paragraph * * @param {Node[]} paras */ }, { key: "paraBookmark", value: function paraBookmark(paras) { return { s: { path: lists.tail(dom.makeOffsetPath(lists.head(paras), this.sc)), offset: this.so }, e: { path: lists.tail(dom.makeOffsetPath(lists.last(paras), this.ec)), offset: this.eo } }; } /** * getClientRects * @return {Rect[]} */ }, { key: "getClientRects", value: function getClientRects() { var nativeRng = this.nativeRange(); return nativeRng.getClientRects(); } }]); return WrappedRange; }(); /** * Data structure * * BoundaryPoint: a point of dom tree * * BoundaryPoints: two boundaryPoints corresponding to the start and the end of the Range * * See to http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Position */ /* harmony default export */ const range = ({ /** * create Range Object From arguments or Browser Selection * * @param {Node} sc - start container * @param {Number} so - start offset * @param {Node} ec - end container * @param {Number} eo - end offset * @return {WrappedRange} */ create: function create(sc, so, ec, eo) { if (arguments.length === 4) { return new WrappedRange(sc, so, ec, eo); } else if (arguments.length === 2) { // collapsed ec = sc; eo = so; return new WrappedRange(sc, so, ec, eo); } else { var wrappedRange = this.createFromSelection(); if (!wrappedRange && arguments.length === 1) { var bodyElement = arguments[0]; if (dom.isEditable(bodyElement)) { bodyElement = bodyElement.lastChild; } return this.createFromBodyElement(bodyElement, dom.emptyPara === arguments[0].innerHTML); } return wrappedRange; } }, createFromBodyElement: function createFromBodyElement(bodyElement) { var isCollapseToStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var wrappedRange = this.createFromNode(bodyElement); return wrappedRange.collapse(isCollapseToStart); }, createFromSelection: function createFromSelection() { var sc, so, ec, eo; if (env.isW3CRangeSupport) { var selection = document.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } else if (dom.isBody(selection.anchorNode)) { // Firefox: returns entire body as range on initialization. // We won't never need it. return null; } var nativeRng = selection.getRangeAt(0); sc = nativeRng.startContainer; so = nativeRng.startOffset; ec = nativeRng.endContainer; eo = nativeRng.endOffset; } else { // IE8: TextRange var textRange = document.selection.createRange(); var textRangeEnd = textRange.duplicate(); textRangeEnd.collapse(false); var textRangeStart = textRange; textRangeStart.collapse(true); var startPoint = textRangeToPoint(textRangeStart, true); var endPoint = textRangeToPoint(textRangeEnd, false); // same visible point case: range was collapsed. if (dom.isText(startPoint.node) && dom.isLeftEdgePoint(startPoint) && dom.isTextNode(endPoint.node) && dom.isRightEdgePoint(endPoint) && endPoint.node.nextSibling === startPoint.node) { startPoint = endPoint; } sc = startPoint.cont; so = startPoint.offset; ec = endPoint.cont; eo = endPoint.offset; } return new WrappedRange(sc, so, ec, eo); }, /** * @method * * create WrappedRange from node * * @param {Node} node * @return {WrappedRange} */ createFromNode: function createFromNode(node) { var sc = node; var so = 0; var ec = node; var eo = dom.nodeLength(ec); // browsers can't target a picture or void node if (dom.isVoid(sc)) { so = dom.listPrev(sc).length - 1; sc = sc.parentNode; } if (dom.isBR(ec)) { eo = dom.listPrev(ec).length - 1; ec = ec.parentNode; } else if (dom.isVoid(ec)) { eo = dom.listPrev(ec).length; ec = ec.parentNode; } return this.create(sc, so, ec, eo); }, /** * create WrappedRange from node after position * * @param {Node} node * @return {WrappedRange} */ createFromNodeBefore: function createFromNodeBefore(node) { return this.createFromNode(node).collapse(true); }, /** * create WrappedRange from node after position * * @param {Node} node * @return {WrappedRange} */ createFromNodeAfter: function createFromNodeAfter(node) { return this.createFromNode(node).collapse(); }, /** * @method * * create WrappedRange from bookmark * * @param {Node} editable * @param {Object} bookmark * @return {WrappedRange} */ createFromBookmark: function createFromBookmark(editable, bookmark) { var sc = dom.fromOffsetPath(editable, bookmark.s.path); var so = bookmark.s.offset; var ec = dom.fromOffsetPath(editable, bookmark.e.path); var eo = bookmark.e.offset; return new WrappedRange(sc, so, ec, eo); }, /** * @method * * create WrappedRange from paraBookmark * * @param {Object} bookmark * @param {Node[]} paras * @return {WrappedRange} */ createFromParaBookmark: function createFromParaBookmark(bookmark, paras) { var so = bookmark.s.offset; var eo = bookmark.e.offset; var sc = dom.fromOffsetPath(lists.head(paras), bookmark.s.path); var ec = dom.fromOffsetPath(lists.last(paras), bookmark.e.path); return new WrappedRange(sc, so, ec, eo); } }); ;// CONCATENATED MODULE: ./src/js/core/key.js var KEY_MAP = { 'BACKSPACE': 8, 'TAB': 9, 'ENTER': 13, 'ESCAPE': 27, 'SPACE': 32, 'DELETE': 46, // Arrow 'LEFT': 37, 'UP': 38, 'RIGHT': 39, 'DOWN': 40, // Number: 0-9 'NUM0': 48, 'NUM1': 49, 'NUM2': 50, 'NUM3': 51, 'NUM4': 52, 'NUM5': 53, 'NUM6': 54, 'NUM7': 55, 'NUM8': 56, // Alphabet: a-z 'B': 66, 'E': 69, 'I': 73, 'J': 74, 'K': 75, 'L': 76, 'R': 82, 'S': 83, 'U': 85, 'V': 86, 'Y': 89, 'Z': 90, 'SLASH': 191, 'LEFTBRACKET': 219, 'BACKSLASH': 220, 'RIGHTBRACKET': 221, // Navigation 'HOME': 36, 'END': 35, 'PAGEUP': 33, 'PAGEDOWN': 34 }; /** * @class core.key * * Object for keycodes. * * @singleton * @alternateClassName key */ /* harmony default export */ const key = ({ /** * @method isEdit * * @param {Number} keyCode * @return {Boolean} */ isEdit: function isEdit(keyCode) { return lists.contains([KEY_MAP.BACKSPACE, KEY_MAP.TAB, KEY_MAP.ENTER, KEY_MAP.SPACE, KEY_MAP.DELETE], keyCode); }, /** * @method isMove * * @param {Number} keyCode * @return {Boolean} */ isMove: function isMove(keyCode) { return lists.contains([KEY_MAP.LEFT, KEY_MAP.UP, KEY_MAP.RIGHT, KEY_MAP.DOWN], keyCode); }, /** * @method isNavigation * * @param {Number} keyCode * @return {Boolean} */ isNavigation: function isNavigation(keyCode) { return lists.contains([KEY_MAP.HOME, KEY_MAP.END, KEY_MAP.PAGEUP, KEY_MAP.PAGEDOWN], keyCode); }, /** * @property {Object} nameFromCode * @property {String} nameFromCode.8 "BACKSPACE" */ nameFromCode: func.invertObject(KEY_MAP), code: KEY_MAP }); ;// CONCATENATED MODULE: ./src/js/core/async.js /** * @method readFileAsDataURL * * read contents of file as representing URL * * @param {File} file * @return {Promise} - then: dataUrl */ function readFileAsDataURL(file) { return external_jQuery_default().Deferred(function (deferred) { external_jQuery_default().extend(new FileReader(), { onload: function onload(e) { var dataURL = e.target.result; deferred.resolve(dataURL); }, onerror: function onerror(err) { deferred.reject(err); } }).readAsDataURL(file); }).promise(); } /** * @method createImage * * create `<image>` from url string * * @param {String} url * @return {Promise} - then: $image */ function createImage(url) { return external_jQuery_default().Deferred(function (deferred) { var $img = external_jQuery_default()('<img>'); $img.one('load', function () { $img.off('error abort'); deferred.resolve($img); }).one('error abort', function () { $img.off('load').detach(); deferred.reject($img); }).css({ display: 'none' }).appendTo(document.body).attr('src', url); }).promise(); } ;// CONCATENATED MODULE: ./src/js/editing/History.js function History_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function History_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function History_createClass(Constructor, protoProps, staticProps) { if (protoProps) History_defineProperties(Constructor.prototype, protoProps); if (staticProps) History_defineProperties(Constructor, staticProps); return Constructor; } var History = /*#__PURE__*/function () { function History(context) { History_classCallCheck(this, History); this.stack = []; this.stackOffset = -1; this.context = context; this.$editable = context.layoutInfo.editable; this.editable = this.$editable[0]; } History_createClass(History, [{ key: "makeSnapshot", value: function makeSnapshot() { var rng = range.create(this.editable); var emptyBookmark = { s: { path: [], offset: 0 }, e: { path: [], offset: 0 } }; return { contents: this.$editable.html(), bookmark: rng && rng.isOnEditable() ? rng.bookmark(this.editable) : emptyBookmark }; } }, { key: "applySnapshot", value: function applySnapshot(snapshot) { if (snapshot.contents !== null) { this.$editable.html(snapshot.contents); } if (snapshot.bookmark !== null) { range.createFromBookmark(this.editable, snapshot.bookmark).select(); } } /** * @method rewind * Rewinds the history stack back to the first snapshot taken. * Leaves the stack intact, so that "Redo" can still be used. */ }, { key: "rewind", value: function rewind() { // Create snap shot if not yet recorded if (this.$editable.html() !== this.stack[this.stackOffset].contents) { this.recordUndo(); } // Return to the first available snapshot. this.stackOffset = 0; // Apply that snapshot. this.applySnapshot(this.stack[this.stackOffset]); } /** * @method commit * Resets history stack, but keeps current editor's content. */ }, { key: "commit", value: function commit() { // Clear the stack. this.stack = []; // Restore stackOffset to its original value. this.stackOffset = -1; // Record our first snapshot (of nothing). this.recordUndo(); } /** * @method reset * Resets the history stack completely; reverting to an empty editor. */ }, { key: "reset", value: function reset() { // Clear the stack. this.stack = []; // Restore stackOffset to its original value. this.stackOffset = -1; // Clear the editable area. this.$editable.html(''); // Record our first snapshot (of nothing). this.recordUndo(); } /** * undo */ }, { key: "undo", value: function undo() { // Create snap shot if not yet recorded if (this.$editable.html() !== this.stack[this.stackOffset].contents) { this.recordUndo(); } if (this.stackOffset > 0) { this.stackOffset--; this.applySnapshot(this.stack[this.stackOffset]); } } /** * redo */ }, { key: "redo", value: function redo() { if (this.stack.length - 1 > this.stackOffset) { this.stackOffset++; this.applySnapshot(this.stack[this.stackOffset]); } } /** * recorded undo */ }, { key: "recordUndo", value: function recordUndo() { this.stackOffset++; // Wash out stack after stackOffset if (this.stack.length > this.stackOffset) { this.stack = this.stack.slice(0, this.stackOffset); } // Create new snapshot and push it to the end this.stack.push(this.makeSnapshot()); // If the stack size reachs to the limit, then slice it if (this.stack.length > this.context.options.historyLimit) { this.stack.shift(); this.stackOffset -= 1; } } }]); return History; }(); ;// CONCATENATED MODULE: ./src/js/editing/Style.js function Style_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Style_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Style_createClass(Constructor, protoProps, staticProps) { if (protoProps) Style_defineProperties(Constructor.prototype, protoProps); if (staticProps) Style_defineProperties(Constructor, staticProps); return Constructor; } var Style = /*#__PURE__*/function () { function Style() { Style_classCallCheck(this, Style); } Style_createClass(Style, [{ key: "jQueryCSS", value: /** * @method jQueryCSS * * [workaround] for old jQuery * passing an array of style properties to .css() * will result in an object of property-value pairs. * (compability with version < 1.9) * * @private * @param {jQuery} $obj * @param {Array} propertyNames - An array of one or more CSS properties. * @return {Object} */ function jQueryCSS($obj, propertyNames) { var result = {}; external_jQuery_default().each(propertyNames, function (idx, propertyName) { result[propertyName] = $obj.css(propertyName); }); return result; } /** * returns style object from node * * @param {jQuery} $node * @return {Object} */ }, { key: "fromNode", value: function fromNode($node) { var properties = ['font-family', 'font-size', 'text-align', 'list-style-type', 'line-height']; var styleInfo = this.jQueryCSS($node, properties) || {}; var fontSize = $node[0].style.fontSize || styleInfo['font-size']; styleInfo['font-size'] = parseInt(fontSize, 10); styleInfo['font-size-unit'] = fontSize.match(/[a-z%]+$/); return styleInfo; } /** * paragraph level style * * @param {WrappedRange} rng * @param {Object} styleInfo */ }, { key: "stylePara", value: function stylePara(rng, styleInfo) { external_jQuery_default().each(rng.nodes(dom.isPara, { includeAncestor: true }), function (idx, para) { external_jQuery_default()(para).css(styleInfo); }); } /** * insert and returns styleNodes on range. * * @param {WrappedRange} rng * @param {Object} [options] - options for styleNodes * @param {String} [options.nodeName] - default: `SPAN` * @param {Boolean} [options.expandClosestSibling] - default: `false` * @param {Boolean} [options.onlyPartialContains] - default: `false` * @return {Node[]} */ }, { key: "styleNodes", value: function styleNodes(rng, options) { rng = rng.splitText(); var nodeName = options && options.nodeName || 'SPAN'; var expandClosestSibling = !!(options && options.expandClosestSibling); var onlyPartialContains = !!(options && options.onlyPartialContains); if (rng.isCollapsed()) { return [rng.insertNode(dom.create(nodeName))]; } var pred = dom.makePredByNodeName(nodeName); var nodes = rng.nodes(dom.isText, { fullyContains: true }).map(function (text) { return dom.singleChildAncestor(text, pred) || dom.wrap(text, nodeName); }); if (expandClosestSibling) { if (onlyPartialContains) { var nodesInRange = rng.nodes(); // compose with partial contains predication pred = func.and(pred, function (node) { return lists.contains(nodesInRange, node); }); } return nodes.map(function (node) { var siblings = dom.withClosestSiblings(node, pred); var head = lists.head(siblings); var tails = lists.tail(siblings); external_jQuery_default().each(tails, function (idx, elem) { dom.appendChildNodes(head, elem.childNodes); dom.remove(elem); }); return lists.head(siblings); }); } else { return nodes; } } /** * get current style on cursor * * @param {WrappedRange} rng * @return {Object} - object contains style properties. */ }, { key: "current", value: function current(rng) { var $cont = external_jQuery_default()(!dom.isElement(rng.sc) ? rng.sc.parentNode : rng.sc); var styleInfo = this.fromNode($cont); // document.queryCommandState for toggle state // [workaround] prevent Firefox nsresult: "0x80004005 (NS_ERROR_FAILURE)" try { styleInfo = external_jQuery_default().extend(styleInfo, { 'font-bold': document.queryCommandState('bold') ? 'bold' : 'normal', 'font-italic': document.queryCommandState('italic') ? 'italic' : 'normal', 'font-underline': document.queryCommandState('underline') ? 'underline' : 'normal', 'font-subscript': document.queryCommandState('subscript') ? 'subscript' : 'normal', 'font-superscript': document.queryCommandState('superscript') ? 'superscript' : 'normal', 'font-strikethrough': document.queryCommandState('strikethrough') ? 'strikethrough' : 'normal', 'font-family': document.queryCommandValue('fontname') || styleInfo['font-family'] }); } catch (e) {// eslint-disable-next-line } // list-style-type to list-style(unordered, ordered) if (!rng.isOnList()) { styleInfo['list-style'] = 'none'; } else { var orderedTypes = ['circle', 'disc', 'disc-leading-zero', 'square']; var isUnordered = orderedTypes.indexOf(styleInfo['list-style-type']) > -1; styleInfo['list-style'] = isUnordered ? 'unordered' : 'ordered'; } var para = dom.ancestor(rng.sc, dom.isPara); if (para && para.style['line-height']) { styleInfo['line-height'] = para.style.lineHeight; } else { var lineHeight = parseInt(styleInfo['line-height'], 10) / parseInt(styleInfo['font-size'], 10); styleInfo['line-height'] = lineHeight.toFixed(1); } styleInfo.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor); styleInfo.ancestors = dom.listAncestor(rng.sc, dom.isEditable); styleInfo.range = rng; return styleInfo; } }]); return Style; }(); ;// CONCATENATED MODULE: ./src/js/editing/Bullet.js function Bullet_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Bullet_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Bullet_createClass(Constructor, protoProps, staticProps) { if (protoProps) Bullet_defineProperties(Constructor.prototype, protoProps); if (staticProps) Bullet_defineProperties(Constructor, staticProps); return Constructor; } var Bullet = /*#__PURE__*/function () { function Bullet() { Bullet_classCallCheck(this, Bullet); } Bullet_createClass(Bullet, [{ key: "insertOrderedList", value: /** * toggle ordered list */ function insertOrderedList(editable) { this.toggleList('OL', editable); } /** * toggle unordered list */ }, { key: "insertUnorderedList", value: function insertUnorderedList(editable) { this.toggleList('UL', editable); } /** * indent */ }, { key: "indent", value: function indent(editable) { var _this = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); if (dom.isLi(head)) { var previousList = _this.findList(head.previousSibling); if (previousList) { paras.map(function (para) { return previousList.appendChild(para); }); } else { _this.wrapList(paras, head.parentNode.nodeName); paras.map(function (para) { return para.parentNode; }).map(function (para) { return _this.appendToPrevious(para); }); } } else { external_jQuery_default().each(paras, function (idx, para) { external_jQuery_default()(para).css('marginLeft', function (idx, val) { return (parseInt(val, 10) || 0) + 25; }); }); } }); rng.select(); } /** * outdent */ }, { key: "outdent", value: function outdent(editable) { var _this2 = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); if (dom.isLi(head)) { _this2.releaseList([paras]); } else { external_jQuery_default().each(paras, function (idx, para) { external_jQuery_default()(para).css('marginLeft', function (idx, val) { val = parseInt(val, 10) || 0; return val > 25 ? val - 25 : ''; }); }); } }); rng.select(); } /** * toggle list * * @param {String} listName - OL or UL */ }, { key: "toggleList", value: function toggleList(listName, editable) { var _this3 = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var bookmark = rng.paraBookmark(paras); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); // paragraph to list if (lists.find(paras, dom.isPurePara)) { var wrappedParas = []; external_jQuery_default().each(clustereds, function (idx, paras) { wrappedParas = wrappedParas.concat(_this3.wrapList(paras, listName)); }); paras = wrappedParas; // list to paragraph or change list style } else { var diffLists = rng.nodes(dom.isList, { includeAncestor: true }).filter(function (listNode) { return !external_jQuery_default().nodeName(listNode, listName); }); if (diffLists.length) { external_jQuery_default().each(diffLists, function (idx, listNode) { dom.replace(listNode, listName); }); } else { paras = this.releaseList(clustereds, true); } } range.createFromParaBookmark(bookmark, paras).select(); } /** * @param {Node[]} paras * @param {String} listName * @return {Node[]} */ }, { key: "wrapList", value: function wrapList(paras, listName) { var head = lists.head(paras); var last = lists.last(paras); var prevList = dom.isList(head.previousSibling) && head.previousSibling; var nextList = dom.isList(last.nextSibling) && last.nextSibling; var listNode = prevList || dom.insertAfter(dom.create(listName || 'UL'), last); // P to LI paras = paras.map(function (para) { return dom.isPurePara(para) ? dom.replace(para, 'LI') : para; }); // append to list(<ul>, <ol>) dom.appendChildNodes(listNode, paras); if (nextList) { dom.appendChildNodes(listNode, lists.from(nextList.childNodes)); dom.remove(nextList); } return paras; } /** * @method releaseList * * @param {Array[]} clustereds * @param {Boolean} isEscapseToBody * @return {Node[]} */ }, { key: "releaseList", value: function releaseList(clustereds, isEscapseToBody) { var _this4 = this; var releasedParas = []; external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); var last = lists.last(paras); var headList = isEscapseToBody ? dom.lastAncestor(head, dom.isList) : head.parentNode; var parentItem = headList.parentNode; if (headList.parentNode.nodeName === 'LI') { paras.map(function (para) { var newList = _this4.findNextSiblings(para); if (parentItem.nextSibling) { parentItem.parentNode.insertBefore(para, parentItem.nextSibling); } else { parentItem.parentNode.appendChild(para); } if (newList.length) { _this4.wrapList(newList, headList.nodeName); para.appendChild(newList[0].parentNode); } }); if (headList.children.length === 0) { parentItem.removeChild(headList); } if (parentItem.childNodes.length === 0) { parentItem.parentNode.removeChild(parentItem); } } else { var lastList = headList.childNodes.length > 1 ? dom.splitTree(headList, { node: last.parentNode, offset: dom.position(last) + 1 }, { isSkipPaddingBlankHTML: true }) : null; var middleList = dom.splitTree(headList, { node: head.parentNode, offset: dom.position(head) }, { isSkipPaddingBlankHTML: true }); paras = isEscapseToBody ? dom.listDescendant(middleList, dom.isLi) : lists.from(middleList.childNodes).filter(dom.isLi); // LI to P if (isEscapseToBody || !dom.isList(headList.parentNode)) { paras = paras.map(function (para) { return dom.replace(para, 'P'); }); } external_jQuery_default().each(lists.from(paras).reverse(), function (idx, para) { dom.insertAfter(para, headList); }); // remove empty lists var rootLists = lists.compact([headList, middleList, lastList]); external_jQuery_default().each(rootLists, function (idx, rootList) { var listNodes = [rootList].concat(dom.listDescendant(rootList, dom.isList)); external_jQuery_default().each(listNodes.reverse(), function (idx, listNode) { if (!dom.nodeLength(listNode)) { dom.remove(listNode, true); } }); }); } releasedParas = releasedParas.concat(paras); }); return releasedParas; } /** * @method appendToPrevious * * Appends list to previous list item, if * none exist it wraps the list in a new list item. * * @param {HTMLNode} ListItem * @return {HTMLNode} */ }, { key: "appendToPrevious", value: function appendToPrevious(node) { return node.previousSibling ? dom.appendChildNodes(node.previousSibling, [node]) : this.wrapList([node], 'LI'); } /** * @method findList * * Finds an existing list in list item * * @param {HTMLNode} ListItem * @return {Array[]} */ }, { key: "findList", value: function findList(node) { return node ? lists.find(node.children, function (child) { return ['OL', 'UL'].indexOf(child.nodeName) > -1; }) : null; } /** * @method findNextSiblings * * Finds all list item siblings that follow it * * @param {HTMLNode} ListItem * @return {HTMLNode} */ }, { key: "findNextSiblings", value: function findNextSiblings(node) { var siblings = []; while (node.nextSibling) { siblings.push(node.nextSibling); node = node.nextSibling; } return siblings; } }]); return Bullet; }(); ;// CONCATENATED MODULE: ./src/js/editing/Typing.js function Typing_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Typing_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Typing_createClass(Constructor, protoProps, staticProps) { if (protoProps) Typing_defineProperties(Constructor.prototype, protoProps); if (staticProps) Typing_defineProperties(Constructor, staticProps); return Constructor; } /** * @class editing.Typing * * Typing * */ var Typing = /*#__PURE__*/function () { function Typing(context) { Typing_classCallCheck(this, Typing); // a Bullet instance to toggle lists off this.bullet = new Bullet(); this.options = context.options; } /** * insert tab * * @param {WrappedRange} rng * @param {Number} tabsize */ Typing_createClass(Typing, [{ key: "insertTab", value: function insertTab(rng, tabsize) { var tab = dom.createText(new Array(tabsize + 1).join(dom.NBSP_CHAR)); rng = rng.deleteContents(); rng.insertNode(tab, true); rng = range.create(tab, tabsize); rng.select(); } /** * insert paragraph * * @param {jQuery} $editable * @param {WrappedRange} rng Can be used in unit tests to "mock" the range * * blockquoteBreakingLevel * 0 - No break, the new paragraph remains inside the quote * 1 - Break the first blockquote in the ancestors list * 2 - Break all blockquotes, so that the new paragraph is not quoted (this is the default) */ }, { key: "insertParagraph", value: function insertParagraph(editable, rng) { rng = rng || range.create(editable); // deleteContents on range. rng = rng.deleteContents(); // Wrap range if it needs to be wrapped by paragraph rng = rng.wrapBodyInlineWithPara(); // finding paragraph var splitRoot = dom.ancestor(rng.sc, dom.isPara); var nextPara; // on paragraph: split paragraph if (splitRoot) { // if it is an empty line with li if (dom.isLi(splitRoot) && (dom.isEmpty(splitRoot) || dom.deepestChildIsEmpty(splitRoot))) { // toggle UL/OL and escape this.bullet.toggleList(splitRoot.parentNode.nodeName); return; } else { var blockquote = null; if (this.options.blockquoteBreakingLevel === 1) { blockquote = dom.ancestor(splitRoot, dom.isBlockquote); } else if (this.options.blockquoteBreakingLevel === 2) { blockquote = dom.lastAncestor(splitRoot, dom.isBlockquote); } if (blockquote) { // We're inside a blockquote and options ask us to break it nextPara = external_jQuery_default()(dom.emptyPara)[0]; // If the split is right before a <br>, remove it so that there's no "empty line" // after the split in the new blockquote created if (dom.isRightEdgePoint(rng.getStartPoint()) && dom.isBR(rng.sc.nextSibling)) { external_jQuery_default()(rng.sc.nextSibling).remove(); } var split = dom.splitTree(blockquote, rng.getStartPoint(), { isDiscardEmptySplits: true }); if (split) { split.parentNode.insertBefore(nextPara, split); } else { dom.insertAfter(nextPara, blockquote); // There's no split if we were at the end of the blockquote } } else { nextPara = dom.splitTree(splitRoot, rng.getStartPoint()); // not a blockquote, just insert the paragraph var emptyAnchors = dom.listDescendant(splitRoot, dom.isEmptyAnchor); emptyAnchors = emptyAnchors.concat(dom.listDescendant(nextPara, dom.isEmptyAnchor)); external_jQuery_default().each(emptyAnchors, function (idx, anchor) { dom.remove(anchor); }); // replace empty heading, pre or custom-made styleTag with P tag if ((dom.isHeading(nextPara) || dom.isPre(nextPara) || dom.isCustomStyleTag(nextPara)) && dom.isEmpty(nextPara)) { nextPara = dom.replace(nextPara, 'p'); } } } // no paragraph: insert empty paragraph } else { var next = rng.sc.childNodes[rng.so]; nextPara = external_jQuery_default()(dom.emptyPara)[0]; if (next) { rng.sc.insertBefore(nextPara, next); } else { rng.sc.appendChild(nextPara); } } range.create(nextPara, 0).normalize().select().scrollIntoView(editable); } }]); return Typing; }(); ;// CONCATENATED MODULE: ./src/js/editing/Table.js function Table_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Table_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Table_createClass(Constructor, protoProps, staticProps) { if (protoProps) Table_defineProperties(Constructor.prototype, protoProps); if (staticProps) Table_defineProperties(Constructor, staticProps); return Constructor; } /** * @class Create a virtual table to create what actions to do in change. * @param {object} startPoint Cell selected to apply change. * @param {enum} where Where change will be applied Row or Col. Use enum: TableResultAction.where * @param {enum} action Action to be applied. Use enum: TableResultAction.requestAction * @param {object} domTable Dom element of table to make changes. */ var TableResultAction = function TableResultAction(startPoint, where, action, domTable) { var _startPoint = { 'colPos': 0, 'rowPos': 0 }; var _virtualTable = []; var _actionCellList = []; /// /////////////////////////////////////////// // Private functions /// /////////////////////////////////////////// /** * Set the startPoint of action. */ function setStartPoint() { if (!startPoint || !startPoint.tagName || startPoint.tagName.toLowerCase() !== 'td' && startPoint.tagName.toLowerCase() !== 'th') { // Impossible to identify start Cell point return; } _startPoint.colPos = startPoint.cellIndex; if (!startPoint.parentElement || !startPoint.parentElement.tagName || startPoint.parentElement.tagName.toLowerCase() !== 'tr') { // Impossible to identify start Row point return; } _startPoint.rowPos = startPoint.parentElement.rowIndex; } /** * Define virtual table position info object. * * @param {int} rowIndex Index position in line of virtual table. * @param {int} cellIndex Index position in column of virtual table. * @param {object} baseRow Row affected by this position. * @param {object} baseCell Cell affected by this position. * @param {bool} isSpan Inform if it is an span cell/row. */ function setVirtualTablePosition(rowIndex, cellIndex, baseRow, baseCell, isRowSpan, isColSpan, isVirtualCell) { var objPosition = { 'baseRow': baseRow, 'baseCell': baseCell, 'isRowSpan': isRowSpan, 'isColSpan': isColSpan, 'isVirtual': isVirtualCell }; if (!_virtualTable[rowIndex]) { _virtualTable[rowIndex] = []; } _virtualTable[rowIndex][cellIndex] = objPosition; } /** * Create action cell object. * * @param {object} virtualTableCellObj Object of specific position on virtual table. * @param {enum} resultAction Action to be applied in that item. */ function getActionCell(virtualTableCellObj, resultAction, virtualRowPosition, virtualColPosition) { return { 'baseCell': virtualTableCellObj.baseCell, 'action': resultAction, 'virtualTable': { 'rowIndex': virtualRowPosition, 'cellIndex': virtualColPosition } }; } /** * Recover free index of row to append Cell. * * @param {int} rowIndex Index of row to find free space. * @param {int} cellIndex Index of cell to find free space in table. */ function recoverCellIndex(rowIndex, cellIndex) { if (!_virtualTable[rowIndex]) { return cellIndex; } if (!_virtualTable[rowIndex][cellIndex]) { return cellIndex; } var newCellIndex = cellIndex; while (_virtualTable[rowIndex][newCellIndex]) { newCellIndex++; if (!_virtualTable[rowIndex][newCellIndex]) { return newCellIndex; } } } /** * Recover info about row and cell and add information to virtual table. * * @param {object} row Row to recover information. * @param {object} cell Cell to recover information. */ function addCellInfoToVirtual(row, cell) { var cellIndex = recoverCellIndex(row.rowIndex, cell.cellIndex); var cellHasColspan = cell.colSpan > 1; var cellHasRowspan = cell.rowSpan > 1; var isThisSelectedCell = row.rowIndex === _startPoint.rowPos && cell.cellIndex === _startPoint.colPos; setVirtualTablePosition(row.rowIndex, cellIndex, row, cell, cellHasRowspan, cellHasColspan, false); // Add span rows to virtual Table. var rowspanNumber = cell.attributes.rowSpan ? parseInt(cell.attributes.rowSpan.value, 10) : 0; if (rowspanNumber > 1) { for (var rp = 1; rp < rowspanNumber; rp++) { var rowspanIndex = row.rowIndex + rp; adjustStartPoint(rowspanIndex, cellIndex, cell, isThisSelectedCell); setVirtualTablePosition(rowspanIndex, cellIndex, row, cell, true, cellHasColspan, true); } } // Add span cols to virtual table. var colspanNumber = cell.attributes.colSpan ? parseInt(cell.attributes.colSpan.value, 10) : 0; if (colspanNumber > 1) { for (var cp = 1; cp < colspanNumber; cp++) { var cellspanIndex = recoverCellIndex(row.rowIndex, cellIndex + cp); adjustStartPoint(row.rowIndex, cellspanIndex, cell, isThisSelectedCell); setVirtualTablePosition(row.rowIndex, cellspanIndex, row, cell, cellHasRowspan, true, true); } } } /** * Process validation and adjust of start point if needed * * @param {int} rowIndex * @param {int} cellIndex * @param {object} cell * @param {bool} isSelectedCell */ function adjustStartPoint(rowIndex, cellIndex, cell, isSelectedCell) { if (rowIndex === _startPoint.rowPos && _startPoint.colPos >= cell.cellIndex && cell.cellIndex <= cellIndex && !isSelectedCell) { _startPoint.colPos++; } } /** * Create virtual table of cells with all cells, including span cells. */ function createVirtualTable() { var rows = domTable.rows; for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) { var cells = rows[rowIndex].cells; for (var cellIndex = 0; cellIndex < cells.length; cellIndex++) { addCellInfoToVirtual(rows[rowIndex], cells[cellIndex]); } } } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getDeleteResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; case TableResultAction.where.Row: if (!cell.isVirtual && cell.isRowSpan) { return TableResultAction.resultAction.AddCell; } else if (cell.isRowSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; } return TableResultAction.resultAction.RemoveCell; } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getAddResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isRowSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; case TableResultAction.where.Row: if (cell.isRowSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isColSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; } return TableResultAction.resultAction.AddCell; } function init() { setStartPoint(); createVirtualTable(); } /// /////////////////////////////////////////// // Public functions /// /////////////////////////////////////////// /** * Recover array os what to do in table. */ this.getActionList = function () { var fixedRow = where === TableResultAction.where.Row ? _startPoint.rowPos : -1; var fixedCol = where === TableResultAction.where.Column ? _startPoint.colPos : -1; var actualPosition = 0; var canContinue = true; while (canContinue) { var rowPosition = fixedRow >= 0 ? fixedRow : actualPosition; var colPosition = fixedCol >= 0 ? fixedCol : actualPosition; var row = _virtualTable[rowPosition]; if (!row) { canContinue = false; return _actionCellList; } var cell = row[colPosition]; if (!cell) { canContinue = false; return _actionCellList; } // Define action to be applied in this cell var resultAction = TableResultAction.resultAction.Ignore; switch (action) { case TableResultAction.requestAction.Add: resultAction = getAddResultActionToCell(cell); break; case TableResultAction.requestAction.Delete: resultAction = getDeleteResultActionToCell(cell); break; } _actionCellList.push(getActionCell(cell, resultAction, rowPosition, colPosition)); actualPosition++; } return _actionCellList; }; init(); }; /** * * Where action occours enum. */ TableResultAction.where = { 'Row': 0, 'Column': 1 }; /** * * Requested action to apply enum. */ TableResultAction.requestAction = { 'Add': 0, 'Delete': 1 }; /** * * Result action to be executed enum. */ TableResultAction.resultAction = { 'Ignore': 0, 'SubtractSpanCount': 1, 'RemoveCell': 2, 'AddCell': 3, 'SumSpanCount': 4 }; /** * * @class editing.Table * * Table * */ var Table = /*#__PURE__*/function () { function Table() { Table_classCallCheck(this, Table); } Table_createClass(Table, [{ key: "tab", value: /** * handle tab key * * @param {WrappedRange} rng * @param {Boolean} isShift */ function tab(rng, isShift) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var table = dom.ancestor(cell, dom.isTable); var cells = dom.listDescendant(table, dom.isCell); var nextCell = lists[isShift ? 'prev' : 'next'](cells, cell); if (nextCell) { range.create(nextCell, 0).select(); } } /** * Add a new row * * @param {WrappedRange} rng * @param {String} position (top/bottom) * @return {Node} */ }, { key: "addRow", value: function addRow(rng, position) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var currentTr = external_jQuery_default()(cell).closest('tr'); var trAttributes = this.recoverAttributes(currentTr); var html = external_jQuery_default()('<tr' + trAttributes + '></tr>'); var vTable = new TableResultAction(cell, TableResultAction.where.Row, TableResultAction.requestAction.Add, external_jQuery_default()(currentTr).closest('table')[0]); var actions = vTable.getActionList(); for (var idCell = 0; idCell < actions.length; idCell++) { var currentCell = actions[idCell]; var tdAttributes = this.recoverAttributes(currentCell.baseCell); switch (currentCell.action) { case TableResultAction.resultAction.AddCell: html.append('<td' + tdAttributes + '>' + dom.blank + '</td>'); break; case TableResultAction.resultAction.SumSpanCount: { if (position === 'top') { var baseCellTr = currentCell.baseCell.parent; var isTopFromRowSpan = (!baseCellTr ? 0 : currentCell.baseCell.closest('tr').rowIndex) <= currentTr[0].rowIndex; if (isTopFromRowSpan) { var newTd = external_jQuery_default()('<div></div>').append(external_jQuery_default()('<td' + tdAttributes + '>' + dom.blank + '</td>').removeAttr('rowspan')).html(); html.append(newTd); break; } } var rowspanNumber = parseInt(currentCell.baseCell.rowSpan, 10); rowspanNumber++; currentCell.baseCell.setAttribute('rowSpan', rowspanNumber); } break; } } if (position === 'top') { currentTr.before(html); } else { var cellHasRowspan = cell.rowSpan > 1; if (cellHasRowspan) { var lastTrIndex = currentTr[0].rowIndex + (cell.rowSpan - 2); external_jQuery_default()(external_jQuery_default()(currentTr).parent().find('tr')[lastTrIndex]).after(external_jQuery_default()(html)); return; } currentTr.after(html); } } /** * Add a new col * * @param {WrappedRange} rng * @param {String} position (left/right) * @return {Node} */ }, { key: "addCol", value: function addCol(rng, position) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var rowsGroup = external_jQuery_default()(row).siblings(); rowsGroup.push(row); var vTable = new TableResultAction(cell, TableResultAction.where.Column, TableResultAction.requestAction.Add, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { var currentCell = actions[actionIndex]; var tdAttributes = this.recoverAttributes(currentCell.baseCell); switch (currentCell.action) { case TableResultAction.resultAction.AddCell: if (position === 'right') { external_jQuery_default()(currentCell.baseCell).after('<td' + tdAttributes + '>' + dom.blank + '</td>'); } else { external_jQuery_default()(currentCell.baseCell).before('<td' + tdAttributes + '>' + dom.blank + '</td>'); } break; case TableResultAction.resultAction.SumSpanCount: if (position === 'right') { var colspanNumber = parseInt(currentCell.baseCell.colSpan, 10); colspanNumber++; currentCell.baseCell.setAttribute('colSpan', colspanNumber); } else { external_jQuery_default()(currentCell.baseCell).before('<td' + tdAttributes + '>' + dom.blank + '</td>'); } break; } } } /* * Copy attributes from element. * * @param {object} Element to recover attributes. * @return {string} Copied string elements. */ }, { key: "recoverAttributes", value: function recoverAttributes(el) { var resultStr = ''; if (!el) { return resultStr; } var attrList = el.attributes || []; for (var i = 0; i < attrList.length; i++) { if (attrList[i].name.toLowerCase() === 'id') { continue; } if (attrList[i].specified) { resultStr += ' ' + attrList[i].name + '=\'' + attrList[i].value + '\''; } } return resultStr; } /** * Delete current row * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteRow", value: function deleteRow(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var cellPos = row.children('td, th').index(external_jQuery_default()(cell)); var rowPos = row[0].rowIndex; var vTable = new TableResultAction(cell, TableResultAction.where.Row, TableResultAction.requestAction.Delete, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { if (!actions[actionIndex]) { continue; } var baseCell = actions[actionIndex].baseCell; var virtualPosition = actions[actionIndex].virtualTable; var hasRowspan = baseCell.rowSpan && baseCell.rowSpan > 1; var rowspanNumber = hasRowspan ? parseInt(baseCell.rowSpan, 10) : 0; switch (actions[actionIndex].action) { case TableResultAction.resultAction.Ignore: continue; case TableResultAction.resultAction.AddCell: { var nextRow = row.next('tr')[0]; if (!nextRow) { continue; } var cloneRow = row[0].cells[cellPos]; if (hasRowspan) { if (rowspanNumber > 2) { rowspanNumber--; nextRow.insertBefore(cloneRow, nextRow.cells[cellPos]); nextRow.cells[cellPos].setAttribute('rowSpan', rowspanNumber); nextRow.cells[cellPos].innerHTML = ''; } else if (rowspanNumber === 2) { nextRow.insertBefore(cloneRow, nextRow.cells[cellPos]); nextRow.cells[cellPos].removeAttribute('rowSpan'); nextRow.cells[cellPos].innerHTML = ''; } } } continue; case TableResultAction.resultAction.SubtractSpanCount: if (hasRowspan) { if (rowspanNumber > 2) { rowspanNumber--; baseCell.setAttribute('rowSpan', rowspanNumber); if (virtualPosition.rowIndex !== rowPos && baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } else if (rowspanNumber === 2) { baseCell.removeAttribute('rowSpan'); if (virtualPosition.rowIndex !== rowPos && baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } } continue; case TableResultAction.resultAction.RemoveCell: // Do not need remove cell because row will be deleted. continue; } } row.remove(); } /** * Delete current col * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteCol", value: function deleteCol(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var cellPos = row.children('td, th').index(external_jQuery_default()(cell)); var vTable = new TableResultAction(cell, TableResultAction.where.Column, TableResultAction.requestAction.Delete, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { if (!actions[actionIndex]) { continue; } switch (actions[actionIndex].action) { case TableResultAction.resultAction.Ignore: continue; case TableResultAction.resultAction.SubtractSpanCount: { var baseCell = actions[actionIndex].baseCell; var hasColspan = baseCell.colSpan && baseCell.colSpan > 1; if (hasColspan) { var colspanNumber = baseCell.colSpan ? parseInt(baseCell.colSpan, 10) : 0; if (colspanNumber > 2) { colspanNumber--; baseCell.setAttribute('colSpan', colspanNumber); if (baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } else if (colspanNumber === 2) { baseCell.removeAttribute('colSpan'); if (baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } } } continue; case TableResultAction.resultAction.RemoveCell: dom.remove(actions[actionIndex].baseCell, true); continue; } } } /** * create empty table element * * @param {Number} rowCount * @param {Number} colCount * @return {Node} */ }, { key: "createTable", value: function createTable(colCount, rowCount, options) { var tds = []; var tdHTML; for (var idxCol = 0; idxCol < colCount; idxCol++) { tds.push('<td>' + dom.blank + '</td>'); } tdHTML = tds.join(''); var trs = []; var trHTML; for (var idxRow = 0; idxRow < rowCount; idxRow++) { trs.push('<tr>' + tdHTML + '</tr>'); } trHTML = trs.join(''); var $table = external_jQuery_default()('<table>' + trHTML + '</table>'); if (options && options.tableClassName) { $table.addClass(options.tableClassName); } return $table[0]; } /** * Delete current table * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteTable", value: function deleteTable(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); external_jQuery_default()(cell).closest('table').remove(); } }]); return Table; }(); ;// CONCATENATED MODULE: ./src/js/module/Editor.js function Editor_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Editor_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Editor_createClass(Constructor, protoProps, staticProps) { if (protoProps) Editor_defineProperties(Constructor.prototype, protoProps); if (staticProps) Editor_defineProperties(Constructor, staticProps); return Constructor; } var KEY_BOGUS = 'bogus'; /** * @class Editor */ var Editor = /*#__PURE__*/function () { function Editor(context) { var _this = this; Editor_classCallCheck(this, Editor); this.context = context; this.$note = context.layoutInfo.note; this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.options = context.options; this.lang = this.options.langInfo; this.editable = this.$editable[0]; this.lastRange = null; this.snapshot = null; this.style = new Style(); this.table = new Table(); this.typing = new Typing(context); this.bullet = new Bullet(); this.history = new History(context); this.context.memo('help.escape', this.lang.help.escape); this.context.memo('help.undo', this.lang.help.undo); this.context.memo('help.redo', this.lang.help.redo); this.context.memo('help.tab', this.lang.help.tab); this.context.memo('help.untab', this.lang.help.untab); this.context.memo('help.insertParagraph', this.lang.help.insertParagraph); this.context.memo('help.insertOrderedList', this.lang.help.insertOrderedList); this.context.memo('help.insertUnorderedList', this.lang.help.insertUnorderedList); this.context.memo('help.indent', this.lang.help.indent); this.context.memo('help.outdent', this.lang.help.outdent); this.context.memo('help.formatPara', this.lang.help.formatPara); this.context.memo('help.insertHorizontalRule', this.lang.help.insertHorizontalRule); this.context.memo('help.fontName', this.lang.help.fontName); // native commands(with execCommand), generate function for execCommand var commands = ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull', 'formatBlock', 'removeFormat', 'backColor']; for (var idx = 0, len = commands.length; idx < len; idx++) { this[commands[idx]] = function (sCmd) { return function (value) { _this.beforeCommand(); document.execCommand(sCmd, false, value); _this.afterCommand(true); }; }(commands[idx]); this.context.memo('help.' + commands[idx], this.lang.help[commands[idx]]); } this.fontName = this.wrapCommand(function (value) { return _this.fontStyling('font-family', env.validFontName(value)); }); this.fontSize = this.wrapCommand(function (value) { var unit = _this.currentStyle()['font-size-unit']; return _this.fontStyling('font-size', value + unit); }); this.fontSizeUnit = this.wrapCommand(function (value) { var size = _this.currentStyle()['font-size']; return _this.fontStyling('font-size', size + value); }); for (var _idx = 1; _idx <= 6; _idx++) { this['formatH' + _idx] = function (idx) { return function () { _this.formatBlock('H' + idx); }; }(_idx); this.context.memo('help.formatH' + _idx, this.lang.help['formatH' + _idx]); } this.insertParagraph = this.wrapCommand(function () { _this.typing.insertParagraph(_this.editable); }); this.insertOrderedList = this.wrapCommand(function () { _this.bullet.insertOrderedList(_this.editable); }); this.insertUnorderedList = this.wrapCommand(function () { _this.bullet.insertUnorderedList(_this.editable); }); this.indent = this.wrapCommand(function () { _this.bullet.indent(_this.editable); }); this.outdent = this.wrapCommand(function () { _this.bullet.outdent(_this.editable); }); /** * insertNode * insert node * @param {Node} node */ this.insertNode = this.wrapCommand(function (node) { if (_this.isLimited(external_jQuery_default()(node).text().length)) { return; } var rng = _this.getLastRange(); rng.insertNode(node); _this.setLastRange(range.createFromNodeAfter(node).select()); }); /** * insert text * @param {String} text */ this.insertText = this.wrapCommand(function (text) { if (_this.isLimited(text.length)) { return; } var rng = _this.getLastRange(); var textNode = rng.insertNode(dom.createText(text)); _this.setLastRange(range.create(textNode, dom.nodeLength(textNode)).select()); }); /** * paste HTML * @param {String} markup */ this.pasteHTML = this.wrapCommand(function (markup) { if (_this.isLimited(markup.length)) { return; } markup = _this.context.invoke('codeview.purify', markup); var contents = _this.getLastRange().pasteHTML(markup); _this.setLastRange(range.createFromNodeAfter(lists.last(contents)).select()); }); /** * formatBlock * * @param {String} tagName */ this.formatBlock = this.wrapCommand(function (tagName, $target) { var onApplyCustomStyle = _this.options.callbacks.onApplyCustomStyle; if (onApplyCustomStyle) { onApplyCustomStyle.call(_this, $target, _this.context, _this.onFormatBlock); } else { _this.onFormatBlock(tagName, $target); } }); /** * insert horizontal rule */ this.insertHorizontalRule = this.wrapCommand(function () { var hrNode = _this.getLastRange().insertNode(dom.create('HR')); if (hrNode.nextSibling) { _this.setLastRange(range.create(hrNode.nextSibling, 0).normalize().select()); } }); /** * lineHeight * @param {String} value */ this.lineHeight = this.wrapCommand(function (value) { _this.style.stylePara(_this.getLastRange(), { lineHeight: value }); }); /** * create link (command) * * @param {Object} linkInfo */ this.createLink = this.wrapCommand(function (linkInfo) { var linkUrl = linkInfo.url; var linkText = linkInfo.text; var isNewWindow = linkInfo.isNewWindow; var checkProtocol = linkInfo.checkProtocol; var rng = linkInfo.range || _this.getLastRange(); var additionalTextLength = linkText.length - rng.toString().length; if (additionalTextLength > 0 && _this.isLimited(additionalTextLength)) { return; } var isTextChanged = rng.toString() !== linkText; // handle spaced urls from input if (typeof linkUrl === 'string') { linkUrl = linkUrl.trim(); } if (_this.options.onCreateLink) { linkUrl = _this.options.onCreateLink(linkUrl); } else if (checkProtocol) { // if url doesn't have any protocol and not even a relative or a label, use http:// as default linkUrl = /^([A-Za-z][A-Za-z0-9+-.]*\:|#|\/)/.test(linkUrl) ? linkUrl : _this.options.defaultProtocol + linkUrl; } var anchors = []; if (isTextChanged) { rng = rng.deleteContents(); var anchor = rng.insertNode(external_jQuery_default()('<A>' + linkText + '</A>')[0]); anchors.push(anchor); } else { anchors = _this.style.styleNodes(rng, { nodeName: 'A', expandClosestSibling: true, onlyPartialContains: true }); } external_jQuery_default().each(anchors, function (idx, anchor) { external_jQuery_default()(anchor).attr('href', linkUrl); if (isNewWindow) { external_jQuery_default()(anchor).attr('target', '_blank'); } else { external_jQuery_default()(anchor).removeAttr('target'); } }); _this.setLastRange(_this.createRangeFromList(anchors).select()); }); /** * setting color * * @param {Object} sObjColor color code * @param {String} sObjColor.foreColor foreground color * @param {String} sObjColor.backColor background color */ this.color = this.wrapCommand(function (colorInfo) { var foreColor = colorInfo.foreColor; var backColor = colorInfo.backColor; if (foreColor) { document.execCommand('foreColor', false, foreColor); } if (backColor) { document.execCommand('backColor', false, backColor); } }); /** * Set foreground color * * @param {String} colorCode foreground color code */ this.foreColor = this.wrapCommand(function (colorInfo) { document.execCommand('foreColor', false, colorInfo); }); /** * insert Table * * @param {String} dimension of table (ex : "5x5") */ this.insertTable = this.wrapCommand(function (dim) { var dimension = dim.split('x'); var rng = _this.getLastRange().deleteContents(); rng.insertNode(_this.table.createTable(dimension[0], dimension[1], _this.options)); }); /** * remove media object and Figure Elements if media object is img with Figure. */ this.removeMedia = this.wrapCommand(function () { var $target = external_jQuery_default()(_this.restoreTarget()).parent(); if ($target.closest('figure').length) { $target.closest('figure').remove(); } else { $target = external_jQuery_default()(_this.restoreTarget()).detach(); } _this.context.triggerEvent('media.delete', $target, _this.$editable); }); /** * float me * * @param {String} value */ this.floatMe = this.wrapCommand(function (value) { var $target = external_jQuery_default()(_this.restoreTarget()); $target.toggleClass('note-float-left', value === 'left'); $target.toggleClass('note-float-right', value === 'right'); $target.css('float', value === 'none' ? '' : value); }); /** * resize overlay element * @param {String} value */ this.resize = this.wrapCommand(function (value) { var $target = external_jQuery_default()(_this.restoreTarget()); value = parseFloat(value); if (value === 0) { $target.css('width', ''); } else { $target.css({ width: value * 100 + '%', height: '' }); } }); } Editor_createClass(Editor, [{ key: "initialize", value: function initialize() { var _this2 = this; // bind custom events this.$editable.on('keydown', function (event) { if (event.keyCode === key.code.ENTER) { _this2.context.triggerEvent('enter', event); } _this2.context.triggerEvent('keydown', event); // keep a snapshot to limit text on input event _this2.snapshot = _this2.history.makeSnapshot(); _this2.hasKeyShortCut = false; if (!event.isDefaultPrevented()) { if (_this2.options.shortcuts) { _this2.hasKeyShortCut = _this2.handleKeyMap(event); } else { _this2.preventDefaultEditableShortCuts(event); } } if (_this2.isLimited(1, event)) { var lastRange = _this2.getLastRange(); if (lastRange.eo - lastRange.so === 0) { return false; } } _this2.setLastRange(); // record undo in the key event except keyMap. if (_this2.options.recordEveryKeystroke) { if (_this2.hasKeyShortCut === false) { _this2.history.recordUndo(); } } }).on('keyup', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('keyup', event); }).on('focus', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('focus', event); }).on('blur', function (event) { _this2.context.triggerEvent('blur', event); }).on('mousedown', function (event) { _this2.context.triggerEvent('mousedown', event); }).on('mouseup', function (event) { _this2.setLastRange(); _this2.history.recordUndo(); _this2.context.triggerEvent('mouseup', event); }).on('scroll', function (event) { _this2.context.triggerEvent('scroll', event); }).on('paste', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('paste', event); }).on('input', function () { // To limit composition characters (e.g. Korean) if (_this2.isLimited(0) && _this2.snapshot) { _this2.history.applySnapshot(_this2.snapshot); } }); this.$editable.attr('spellcheck', this.options.spellCheck); this.$editable.attr('autocorrect', this.options.spellCheck); if (this.options.disableGrammar) { this.$editable.attr('data-gramm', false); } // init content before set event this.$editable.html(dom.html(this.$note) || dom.emptyPara); this.$editable.on(env.inputEventName, func.debounce(function () { _this2.context.triggerEvent('change', _this2.$editable.html(), _this2.$editable); }, 10)); this.$editable.on('focusin', function (event) { _this2.context.triggerEvent('focusin', event); }).on('focusout', function (event) { _this2.context.triggerEvent('focusout', event); }); if (this.options.airMode) { if (this.options.overrideContextMenu) { this.$editor.on('contextmenu', function (event) { _this2.context.triggerEvent('contextmenu', event); return false; }); } } else { if (this.options.width) { this.$editor.outerWidth(this.options.width); } if (this.options.height) { this.$editable.outerHeight(this.options.height); } if (this.options.maxHeight) { this.$editable.css('max-height', this.options.maxHeight); } if (this.options.minHeight) { this.$editable.css('min-height', this.options.minHeight); } } this.history.recordUndo(); this.setLastRange(); } }, { key: "destroy", value: function destroy() { this.$editable.off(); } }, { key: "handleKeyMap", value: function handleKeyMap(event) { var keyMap = this.options.keyMap[env.isMac ? 'mac' : 'pc']; var keys = []; if (event.metaKey) { keys.push('CMD'); } if (event.ctrlKey && !event.altKey) { keys.push('CTRL'); } if (event.shiftKey) { keys.push('SHIFT'); } var keyName = key.nameFromCode[event.keyCode]; if (keyName) { keys.push(keyName); } var eventName = keyMap[keys.join('+')]; if (keyName === 'TAB' && !this.options.tabDisable) { this.afterCommand(); } else if (eventName) { if (this.context.invoke(eventName) !== false) { event.preventDefault(); // if keyMap action was invoked return true; } } else if (key.isEdit(event.keyCode)) { this.afterCommand(); } return false; } }, { key: "preventDefaultEditableShortCuts", value: function preventDefaultEditableShortCuts(event) { // B(Bold, 66) / I(Italic, 73) / U(Underline, 85) if ((event.ctrlKey || event.metaKey) && lists.contains([66, 73, 85], event.keyCode)) { event.preventDefault(); } } }, { key: "isLimited", value: function isLimited(pad, event) { pad = pad || 0; if (typeof event !== 'undefined') { if (key.isMove(event.keyCode) || key.isNavigation(event.keyCode) || event.ctrlKey || event.metaKey || lists.contains([key.code.BACKSPACE, key.code.DELETE], event.keyCode)) { return false; } } if (this.options.maxTextLength > 0) { if (this.$editable.text().length + pad > this.options.maxTextLength) { return true; } } return false; } /** * create range * @return {WrappedRange} */ }, { key: "createRange", value: function createRange() { this.focus(); this.setLastRange(); return this.getLastRange(); } /** * create a new range from the list of elements * * @param {list} dom element list * @return {WrappedRange} */ }, { key: "createRangeFromList", value: function createRangeFromList(lst) { var startRange = range.createFromNodeBefore(lists.head(lst)); var startPoint = startRange.getStartPoint(); var endRange = range.createFromNodeAfter(lists.last(lst)); var endPoint = endRange.getEndPoint(); return range.create(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * set the last range * * if given rng is exist, set rng as the last range * or create a new range at the end of the document * * @param {WrappedRange} rng */ }, { key: "setLastRange", value: function setLastRange(rng) { if (rng) { this.lastRange = rng; } else { this.lastRange = range.create(this.editable); if (external_jQuery_default()(this.lastRange.sc).closest('.note-editable').length === 0) { this.lastRange = range.createFromBodyElement(this.editable); } } } /** * get the last range * * if there is a saved last range, return it * or create a new range and return it * * @return {WrappedRange} */ }, { key: "getLastRange", value: function getLastRange() { if (!this.lastRange) { this.setLastRange(); } return this.lastRange; } /** * saveRange * * save current range * * @param {Boolean} [thenCollapse=false] */ }, { key: "saveRange", value: function saveRange(thenCollapse) { if (thenCollapse) { this.getLastRange().collapse().select(); } } /** * restoreRange * * restore lately range */ }, { key: "restoreRange", value: function restoreRange() { if (this.lastRange) { this.lastRange.select(); this.focus(); } } }, { key: "saveTarget", value: function saveTarget(node) { this.$editable.data('target', node); } }, { key: "clearTarget", value: function clearTarget() { this.$editable.removeData('target'); } }, { key: "restoreTarget", value: function restoreTarget() { return this.$editable.data('target'); } /** * currentStyle * * current style * @return {Object|Boolean} unfocus */ }, { key: "currentStyle", value: function currentStyle() { var rng = range.create(); if (rng) { rng = rng.normalize(); } return rng ? this.style.current(rng) : this.style.fromNode(this.$editable); } /** * style from node * * @param {jQuery} $node * @return {Object} */ }, { key: "styleFromNode", value: function styleFromNode($node) { return this.style.fromNode($node); } /** * undo */ }, { key: "undo", value: function undo() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.undo(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /* * commit */ }, { key: "commit", value: function commit() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.commit(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /** * redo */ }, { key: "redo", value: function redo() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.redo(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /** * before command */ }, { key: "beforeCommand", value: function beforeCommand() { this.context.triggerEvent('before.command', this.$editable.html()); // Set styleWithCSS before run a command document.execCommand('styleWithCSS', false, this.options.styleWithCSS); // keep focus on editable before command execution this.focus(); } /** * after command * @param {Boolean} isPreventTrigger */ }, { key: "afterCommand", value: function afterCommand(isPreventTrigger) { this.normalizeContent(); this.history.recordUndo(); if (!isPreventTrigger) { this.context.triggerEvent('change', this.$editable.html(), this.$editable); } } /** * handle tab key */ }, { key: "tab", value: function tab() { var rng = this.getLastRange(); if (rng.isCollapsed() && rng.isOnCell()) { this.table.tab(rng); } else { if (this.options.tabSize === 0) { return false; } if (!this.isLimited(this.options.tabSize)) { this.beforeCommand(); this.typing.insertTab(rng, this.options.tabSize); this.afterCommand(); } } } /** * handle shift+tab key */ }, { key: "untab", value: function untab() { var rng = this.getLastRange(); if (rng.isCollapsed() && rng.isOnCell()) { this.table.tab(rng, true); } else { if (this.options.tabSize === 0) { return false; } } } /** * run given function between beforeCommand and afterCommand */ }, { key: "wrapCommand", value: function wrapCommand(fn) { return function () { this.beforeCommand(); fn.apply(this, arguments); this.afterCommand(); }; } /** * insert image * * @param {String} src * @param {String|Function} param * @return {Promise} */ }, { key: "insertImage", value: function insertImage(src, param) { var _this3 = this; return createImage(src, param).then(function ($image) { _this3.beforeCommand(); if (typeof param === 'function') { param($image); } else { if (typeof param === 'string') { $image.attr('data-filename', param); } $image.css('width', Math.min(_this3.$editable.width(), $image.width())); } $image.show(); _this3.getLastRange().insertNode($image[0]); _this3.setLastRange(range.createFromNodeAfter($image[0]).select()); _this3.afterCommand(); }).fail(function (e) { _this3.context.triggerEvent('image.upload.error', e); }); } /** * insertImages * @param {File[]} files */ }, { key: "insertImagesAsDataURL", value: function insertImagesAsDataURL(files) { var _this4 = this; external_jQuery_default().each(files, function (idx, file) { var filename = file.name; if (_this4.options.maximumImageFileSize && _this4.options.maximumImageFileSize < file.size) { _this4.context.triggerEvent('image.upload.error', _this4.lang.image.maximumFileSizeError); } else { readFileAsDataURL(file).then(function (dataURL) { return _this4.insertImage(dataURL, filename); }).fail(function () { _this4.context.triggerEvent('image.upload.error'); }); } }); } /** * insertImagesOrCallback * @param {File[]} files */ }, { key: "insertImagesOrCallback", value: function insertImagesOrCallback(files) { var callbacks = this.options.callbacks; // If onImageUpload set, if (callbacks.onImageUpload) { this.context.triggerEvent('image.upload', files); // else insert Image as dataURL } else { this.insertImagesAsDataURL(files); } } /** * return selected plain text * @return {String} text */ }, { key: "getSelectedText", value: function getSelectedText() { var rng = this.getLastRange(); // if range on anchor, expand range with anchor if (rng.isOnAnchor()) { rng = range.createFromNode(dom.ancestor(rng.sc, dom.isAnchor)); } return rng.toString(); } }, { key: "onFormatBlock", value: function onFormatBlock(tagName, $target) { // [workaround] for MSIE, IE need `<` document.execCommand('FormatBlock', false, env.isMSIE ? '<' + tagName + '>' : tagName); // support custom class if ($target && $target.length) { // find the exact element has given tagName if ($target[0].tagName.toUpperCase() !== tagName.toUpperCase()) { $target = $target.find(tagName); } if ($target && $target.length) { var currentRange = this.createRange(); var $parent = external_jQuery_default()([currentRange.sc, currentRange.ec]).closest(tagName); // remove class added for current block $parent.removeClass(); var className = $target[0].className || ''; if (className) { $parent.addClass(className); } } } } }, { key: "formatPara", value: function formatPara() { this.formatBlock('P'); } }, { key: "fontStyling", value: function fontStyling(target, value) { var rng = this.getLastRange(); if (rng !== '') { var spans = this.style.styleNodes(rng); this.$editor.find('.note-status-output').html(''); external_jQuery_default()(spans).css(target, value); // [workaround] added styled bogus span for style // - also bogus character needed for cursor position if (rng.isCollapsed()) { var firstSpan = lists.head(spans); if (firstSpan && !dom.nodeLength(firstSpan)) { firstSpan.innerHTML = dom.ZERO_WIDTH_NBSP_CHAR; range.createFromNode(firstSpan.firstChild).select(); this.setLastRange(); this.$editable.data(KEY_BOGUS, firstSpan); } } else { this.setLastRange(this.createRangeFromList(spans).select()); } } else { var noteStatusOutput = external_jQuery_default().now(); this.$editor.find('.note-status-output').html('<div id="note-status-output-' + noteStatusOutput + '" class="alert alert-info">' + this.lang.output.noSelection + '</div>'); setTimeout(function () { external_jQuery_default()('#note-status-output-' + noteStatusOutput).remove(); }, 5000); } } /** * unlink * * @type command */ }, { key: "unlink", value: function unlink() { var rng = this.getLastRange(); if (rng.isOnAnchor()) { var anchor = dom.ancestor(rng.sc, dom.isAnchor); rng = range.createFromNode(anchor); rng.select(); this.setLastRange(); this.beforeCommand(); document.execCommand('unlink'); this.afterCommand(); } } /** * returns link info * * @return {Object} * @return {WrappedRange} return.range * @return {String} return.text * @return {Boolean} [return.isNewWindow=true] * @return {String} [return.url=""] */ }, { key: "getLinkInfo", value: function getLinkInfo() { var rng = this.getLastRange().expand(dom.isAnchor); // Get the first anchor on range(for edit). var $anchor = external_jQuery_default()(lists.head(rng.nodes(dom.isAnchor))); var linkInfo = { range: rng, text: rng.toString(), url: $anchor.length ? $anchor.attr('href') : '' }; // When anchor exists, if ($anchor.length) { // Set isNewWindow by checking its target. linkInfo.isNewWindow = $anchor.attr('target') === '_blank'; } return linkInfo; } }, { key: "addRow", value: function addRow(position) { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.addRow(rng, position); this.afterCommand(); } } }, { key: "addCol", value: function addCol(position) { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.addCol(rng, position); this.afterCommand(); } } }, { key: "deleteRow", value: function deleteRow() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteRow(rng); this.afterCommand(); } } }, { key: "deleteCol", value: function deleteCol() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteCol(rng); this.afterCommand(); } } }, { key: "deleteTable", value: function deleteTable() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteTable(rng); this.afterCommand(); } } /** * @param {Position} pos * @param {jQuery} $target - target element * @param {Boolean} [bKeepRatio] - keep ratio */ }, { key: "resizeTo", value: function resizeTo(pos, $target, bKeepRatio) { var imageSize; if (bKeepRatio) { var newRatio = pos.y / pos.x; var ratio = $target.data('ratio'); imageSize = { width: ratio > newRatio ? pos.x : pos.y / ratio, height: ratio > newRatio ? pos.x * ratio : pos.y }; } else { imageSize = { width: pos.x, height: pos.y }; } $target.css(imageSize); } /** * returns whether editable area has focus or not. */ }, { key: "hasFocus", value: function hasFocus() { return this.$editable.is(':focus'); } /** * set focus */ }, { key: "focus", value: function focus() { // [workaround] Screen will move when page is scolled in IE. // - do focus when not focused if (!this.hasFocus()) { this.$editable.focus(); } } /** * returns whether contents is empty or not. * @return {Boolean} */ }, { key: "isEmpty", value: function isEmpty() { return dom.isEmpty(this.$editable[0]) || dom.emptyPara === this.$editable.html(); } /** * Removes all contents and restores the editable instance to an _emptyPara_. */ }, { key: "empty", value: function empty() { this.context.invoke('code', dom.emptyPara); } /** * normalize content */ }, { key: "normalizeContent", value: function normalizeContent() { this.$editable[0].normalize(); } }]); return Editor; }(); ;// CONCATENATED MODULE: ./src/js/module/Clipboard.js function Clipboard_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Clipboard_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Clipboard_createClass(Constructor, protoProps, staticProps) { if (protoProps) Clipboard_defineProperties(Constructor.prototype, protoProps); if (staticProps) Clipboard_defineProperties(Constructor, staticProps); return Constructor; } var Clipboard = /*#__PURE__*/function () { function Clipboard(context) { Clipboard_classCallCheck(this, Clipboard); this.context = context; this.$editable = context.layoutInfo.editable; } Clipboard_createClass(Clipboard, [{ key: "initialize", value: function initialize() { this.$editable.on('paste', this.pasteByEvent.bind(this)); } /** * paste by clipboard event * * @param {Event} event */ }, { key: "pasteByEvent", value: function pasteByEvent(event) { var _this = this; var clipboardData = event.originalEvent.clipboardData; if (clipboardData && clipboardData.items && clipboardData.items.length) { var item = clipboardData.items.length > 1 ? clipboardData.items[1] : lists.head(clipboardData.items); if (item.kind === 'file' && item.type.indexOf('image/') !== -1) { // paste img file this.context.invoke('editor.insertImagesOrCallback', [item.getAsFile()]); event.preventDefault(); } else if (item.kind === 'string') { // paste text with maxTextLength check if (this.context.invoke('editor.isLimited', clipboardData.getData('Text').length)) { event.preventDefault(); } } } else if (window.clipboardData) { // for IE var text = window.clipboardData.getData('text'); if (this.context.invoke('editor.isLimited', text.length)) { event.preventDefault(); } } // Call editor.afterCommand after proceeding default event handler setTimeout(function () { _this.context.invoke('editor.afterCommand'); }, 10); } }]); return Clipboard; }(); ;// CONCATENATED MODULE: ./src/js/module/Dropzone.js function Dropzone_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Dropzone_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Dropzone_createClass(Constructor, protoProps, staticProps) { if (protoProps) Dropzone_defineProperties(Constructor.prototype, protoProps); if (staticProps) Dropzone_defineProperties(Constructor, staticProps); return Constructor; } var Dropzone = /*#__PURE__*/function () { function Dropzone(context) { Dropzone_classCallCheck(this, Dropzone); this.context = context; this.$eventListener = external_jQuery_default()(document); this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.options = context.options; this.lang = this.options.langInfo; this.documentEventHandlers = {}; this.$dropzone = external_jQuery_default()(['<div class="note-dropzone">', '<div class="note-dropzone-message"></div>', '</div>'].join('')).prependTo(this.$editor); } /** * attach Drag and Drop Events */ Dropzone_createClass(Dropzone, [{ key: "initialize", value: function initialize() { if (this.options.disableDragAndDrop) { // prevent default drop event this.documentEventHandlers.onDrop = function (e) { e.preventDefault(); }; // do not consider outside of dropzone this.$eventListener = this.$dropzone; this.$eventListener.on('drop', this.documentEventHandlers.onDrop); } else { this.attachDragAndDropEvent(); } } /** * attach Drag and Drop Events */ }, { key: "attachDragAndDropEvent", value: function attachDragAndDropEvent() { var _this = this; var collection = external_jQuery_default()(); var $dropzoneMessage = this.$dropzone.find('.note-dropzone-message'); this.documentEventHandlers.onDragenter = function (e) { var isCodeview = _this.context.invoke('codeview.isActivated'); var hasEditorSize = _this.$editor.width() > 0 && _this.$editor.height() > 0; if (!isCodeview && !collection.length && hasEditorSize) { _this.$editor.addClass('dragover'); _this.$dropzone.width(_this.$editor.width()); _this.$dropzone.height(_this.$editor.height()); $dropzoneMessage.text(_this.lang.image.dragImageHere); } collection = collection.add(e.target); }; this.documentEventHandlers.onDragleave = function (e) { collection = collection.not(e.target); // If nodeName is BODY, then just make it over (fix for IE) if (!collection.length || e.target.nodeName === 'BODY') { collection = external_jQuery_default()(); _this.$editor.removeClass('dragover'); } }; this.documentEventHandlers.onDrop = function () { collection = external_jQuery_default()(); _this.$editor.removeClass('dragover'); }; // show dropzone on dragenter when dragging a object to document // -but only if the editor is visible, i.e. has a positive width and height this.$eventListener.on('dragenter', this.documentEventHandlers.onDragenter).on('dragleave', this.documentEventHandlers.onDragleave).on('drop', this.documentEventHandlers.onDrop); // change dropzone's message on hover. this.$dropzone.on('dragenter', function () { _this.$dropzone.addClass('hover'); $dropzoneMessage.text(_this.lang.image.dropImage); }).on('dragleave', function () { _this.$dropzone.removeClass('hover'); $dropzoneMessage.text(_this.lang.image.dragImageHere); }); // attach dropImage this.$dropzone.on('drop', function (event) { var dataTransfer = event.originalEvent.dataTransfer; // stop the browser from opening the dropped content event.preventDefault(); if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { _this.$editable.focus(); _this.context.invoke('editor.insertImagesOrCallback', dataTransfer.files); } else { external_jQuery_default().each(dataTransfer.types, function (idx, type) { // skip moz-specific types if (type.toLowerCase().indexOf('_moz_') > -1) { return; } var content = dataTransfer.getData(type); if (type.toLowerCase().indexOf('text') > -1) { _this.context.invoke('editor.pasteHTML', content); } else { external_jQuery_default()(content).each(function (idx, item) { _this.context.invoke('editor.insertNode', item); }); } }); } }).on('dragover', false); // prevent default dragover event } }, { key: "destroy", value: function destroy() { var _this2 = this; Object.keys(this.documentEventHandlers).forEach(function (key) { _this2.$eventListener.off(key.substr(2).toLowerCase(), _this2.documentEventHandlers[key]); }); this.documentEventHandlers = {}; } }]); return Dropzone; }(); ;// CONCATENATED MODULE: ./src/js/module/Codeview.js function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function Codeview_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Codeview_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Codeview_createClass(Constructor, protoProps, staticProps) { if (protoProps) Codeview_defineProperties(Constructor.prototype, protoProps); if (staticProps) Codeview_defineProperties(Constructor, staticProps); return Constructor; } /** * @class Codeview */ var CodeView = /*#__PURE__*/function () { function CodeView(context) { Codeview_classCallCheck(this, CodeView); this.context = context; this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.options = context.options; this.CodeMirrorConstructor = window.CodeMirror; if (this.options.codemirror.CodeMirrorConstructor) { this.CodeMirrorConstructor = this.options.codemirror.CodeMirrorConstructor; } } Codeview_createClass(CodeView, [{ key: "sync", value: function sync(html) { var isCodeview = this.isActivated(); var CodeMirror = this.CodeMirrorConstructor; if (isCodeview) { if (html) { if (CodeMirror) { this.$codable.data('cmEditor').getDoc().setValue(html); } else { this.$codable.val(html); } } else { if (CodeMirror) { this.$codable.data('cmEditor').save(); } } } } }, { key: "initialize", value: function initialize() { var _this = this; this.$codable.on('keyup', function (event) { if (event.keyCode === key.code.ESCAPE) { _this.deactivate(); } }); } /** * @return {Boolean} */ }, { key: "isActivated", value: function isActivated() { return this.$editor.hasClass('codeview'); } /** * toggle codeview */ }, { key: "toggle", value: function toggle() { if (this.isActivated()) { this.deactivate(); } else { this.activate(); } this.context.triggerEvent('codeview.toggled'); } /** * purify input value * @param value * @returns {*} */ }, { key: "purify", value: function purify(value) { if (this.options.codeviewFilter) { // filter code view regex value = value.replace(this.options.codeviewFilterRegex, ''); // allow specific iframe tag if (this.options.codeviewIframeFilter) { var whitelist = this.options.codeviewIframeWhitelistSrc.concat(this.options.codeviewIframeWhitelistSrcBase); value = value.replace(/(<iframe.*?>.*?(?:<\/iframe>)?)/gi, function (tag) { // remove if src attribute is duplicated if (/<.+src(?==?('|"|\s)?)[\s\S]+src(?=('|"|\s)?)[^>]*?>/i.test(tag)) { return ''; } var _iterator = _createForOfIteratorHelper(whitelist), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var src = _step.value; // pass if src is trusted if (new RegExp('src="(https?:)?\/\/' + src.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '\/(.+)"').test(tag)) { return tag; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return ''; }); } } return value; } /** * activate code view */ }, { key: "activate", value: function activate() { var _this2 = this; var CodeMirror = this.CodeMirrorConstructor; this.$codable.val(dom.html(this.$editable, this.options.prettifyHtml)); this.$codable.height(this.$editable.height()); this.context.invoke('toolbar.updateCodeview', true); this.context.invoke('airPopover.updateCodeview', true); this.$editor.addClass('codeview'); this.$codable.focus(); // activate CodeMirror as codable if (CodeMirror) { var cmEditor = CodeMirror.fromTextArea(this.$codable[0], this.options.codemirror); // CodeMirror TernServer if (this.options.codemirror.tern) { var server = new CodeMirror.TernServer(this.options.codemirror.tern); cmEditor.ternServer = server; cmEditor.on('cursorActivity', function (cm) { server.updateArgHints(cm); }); } cmEditor.on('blur', function (event) { _this2.context.triggerEvent('blur.codeview', cmEditor.getValue(), event); }); cmEditor.on('change', function () { _this2.context.triggerEvent('change.codeview', cmEditor.getValue(), cmEditor); }); // CodeMirror hasn't Padding. cmEditor.setSize(null, this.$editable.outerHeight()); this.$codable.data('cmEditor', cmEditor); } else { this.$codable.on('blur', function (event) { _this2.context.triggerEvent('blur.codeview', _this2.$codable.val(), event); }); this.$codable.on('input', function () { _this2.context.triggerEvent('change.codeview', _this2.$codable.val(), _this2.$codable); }); } } /** * deactivate code view */ }, { key: "deactivate", value: function deactivate() { var CodeMirror = this.CodeMirrorConstructor; // deactivate CodeMirror as codable if (CodeMirror) { var cmEditor = this.$codable.data('cmEditor'); this.$codable.val(cmEditor.getValue()); cmEditor.toTextArea(); } var value = this.purify(dom.value(this.$codable, this.options.prettifyHtml) || dom.emptyPara); var isChange = this.$editable.html() !== value; this.$editable.html(value); this.$editable.height(this.options.height ? this.$codable.height() : 'auto'); this.$editor.removeClass('codeview'); if (isChange) { this.context.triggerEvent('change', this.$editable.html(), this.$editable); } this.$editable.focus(); this.context.invoke('toolbar.updateCodeview', false); this.context.invoke('airPopover.updateCodeview', false); } }, { key: "destroy", value: function destroy() { if (this.isActivated()) { this.deactivate(); } } }]); return CodeView; }(); ;// CONCATENATED MODULE: ./src/js/module/Statusbar.js function Statusbar_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Statusbar_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Statusbar_createClass(Constructor, protoProps, staticProps) { if (protoProps) Statusbar_defineProperties(Constructor.prototype, protoProps); if (staticProps) Statusbar_defineProperties(Constructor, staticProps); return Constructor; } var EDITABLE_PADDING = 24; var Statusbar = /*#__PURE__*/function () { function Statusbar(context) { Statusbar_classCallCheck(this, Statusbar); this.$document = external_jQuery_default()(document); this.$statusbar = context.layoutInfo.statusbar; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.options = context.options; } Statusbar_createClass(Statusbar, [{ key: "initialize", value: function initialize() { var _this = this; if (this.options.airMode || this.options.disableResizeEditor) { this.destroy(); return; } this.$statusbar.on('mousedown', function (event) { event.preventDefault(); event.stopPropagation(); var editableTop = _this.$editable.offset().top - _this.$document.scrollTop(); var editableCodeTop = _this.$codable.offset().top - _this.$document.scrollTop(); var onMouseMove = function onMouseMove(event) { var height = event.clientY - (editableTop + EDITABLE_PADDING); var heightCode = event.clientY - (editableCodeTop + EDITABLE_PADDING); height = _this.options.minheight > 0 ? Math.max(height, _this.options.minheight) : height; height = _this.options.maxHeight > 0 ? Math.min(height, _this.options.maxHeight) : height; heightCode = _this.options.minheight > 0 ? Math.max(heightCode, _this.options.minheight) : heightCode; heightCode = _this.options.maxHeight > 0 ? Math.min(heightCode, _this.options.maxHeight) : heightCode; _this.$editable.height(height); _this.$codable.height(heightCode); }; _this.$document.on('mousemove', onMouseMove).one('mouseup', function () { _this.$document.off('mousemove', onMouseMove); }); }); } }, { key: "destroy", value: function destroy() { this.$statusbar.off(); this.$statusbar.addClass('locked'); } }]); return Statusbar; }(); ;// CONCATENATED MODULE: ./src/js/module/Fullscreen.js function Fullscreen_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Fullscreen_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Fullscreen_createClass(Constructor, protoProps, staticProps) { if (protoProps) Fullscreen_defineProperties(Constructor.prototype, protoProps); if (staticProps) Fullscreen_defineProperties(Constructor, staticProps); return Constructor; } var Fullscreen = /*#__PURE__*/function () { function Fullscreen(context) { var _this = this; Fullscreen_classCallCheck(this, Fullscreen); this.context = context; this.$editor = context.layoutInfo.editor; this.$toolbar = context.layoutInfo.toolbar; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.$window = external_jQuery_default()(window); this.$scrollbar = external_jQuery_default()('html, body'); this.scrollbarClassName = 'note-fullscreen-body'; this.onResize = function () { _this.resizeTo({ h: _this.$window.height() - _this.$toolbar.outerHeight() }); }; } Fullscreen_createClass(Fullscreen, [{ key: "resizeTo", value: function resizeTo(size) { this.$editable.css('height', size.h); this.$codable.css('height', size.h); if (this.$codable.data('cmeditor')) { this.$codable.data('cmeditor').setsize(null, size.h); } } /** * toggle fullscreen */ }, { key: "toggle", value: function toggle() { this.$editor.toggleClass('fullscreen'); var isFullscreen = this.isFullscreen(); this.$scrollbar.toggleClass(this.scrollbarClassName, isFullscreen); if (isFullscreen) { this.$editable.data('orgHeight', this.$editable.css('height')); this.$editable.data('orgMaxHeight', this.$editable.css('maxHeight')); this.$editable.css('maxHeight', ''); this.$window.on('resize', this.onResize).trigger('resize'); } else { this.$window.off('resize', this.onResize); this.resizeTo({ h: this.$editable.data('orgHeight') }); this.$editable.css('maxHeight', this.$editable.css('orgMaxHeight')); } this.context.invoke('toolbar.updateFullscreen', isFullscreen); } }, { key: "isFullscreen", value: function isFullscreen() { return this.$editor.hasClass('fullscreen'); } }, { key: "destroy", value: function destroy() { this.$scrollbar.removeClass(this.scrollbarClassName); } }]); return Fullscreen; }(); ;// CONCATENATED MODULE: ./src/js/module/Handle.js function Handle_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Handle_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Handle_createClass(Constructor, protoProps, staticProps) { if (protoProps) Handle_defineProperties(Constructor.prototype, protoProps); if (staticProps) Handle_defineProperties(Constructor, staticProps); return Constructor; } var Handle = /*#__PURE__*/function () { function Handle(context) { var _this = this; Handle_classCallCheck(this, Handle); this.context = context; this.$document = external_jQuery_default()(document); this.$editingArea = context.layoutInfo.editingArea; this.options = context.options; this.lang = this.options.langInfo; this.events = { 'summernote.mousedown': function summernoteMousedown(we, e) { if (_this.update(e.target, e)) { e.preventDefault(); } }, 'summernote.keyup summernote.scroll summernote.change summernote.dialog.shown': function summernoteKeyupSummernoteScrollSummernoteChangeSummernoteDialogShown() { _this.update(); }, 'summernote.disable summernote.blur': function summernoteDisableSummernoteBlur() { _this.hide(); }, 'summernote.codeview.toggled': function summernoteCodeviewToggled() { _this.update(); } }; } Handle_createClass(Handle, [{ key: "initialize", value: function initialize() { var _this2 = this; this.$handle = external_jQuery_default()(['<div class="note-handle">', '<div class="note-control-selection">', '<div class="note-control-selection-bg"></div>', '<div class="note-control-holder note-control-nw"></div>', '<div class="note-control-holder note-control-ne"></div>', '<div class="note-control-holder note-control-sw"></div>', '<div class="', this.options.disableResizeImage ? 'note-control-holder' : 'note-control-sizing', ' note-control-se"></div>', this.options.disableResizeImage ? '' : '<div class="note-control-selection-info"></div>', '</div>', '</div>'].join('')).prependTo(this.$editingArea); this.$handle.on('mousedown', function (event) { if (dom.isControlSizing(event.target)) { event.preventDefault(); event.stopPropagation(); var $target = _this2.$handle.find('.note-control-selection').data('target'); var posStart = $target.offset(); var scrollTop = _this2.$document.scrollTop(); var onMouseMove = function onMouseMove(event) { _this2.context.invoke('editor.resizeTo', { x: event.clientX - posStart.left, y: event.clientY - (posStart.top - scrollTop) }, $target, !event.shiftKey); _this2.update($target[0], event); }; _this2.$document.on('mousemove', onMouseMove).one('mouseup', function (e) { e.preventDefault(); _this2.$document.off('mousemove', onMouseMove); _this2.context.invoke('editor.afterCommand'); }); if (!$target.data('ratio')) { // original ratio. $target.data('ratio', $target.height() / $target.width()); } } }); // Listen for scrolling on the handle overlay. this.$handle.on('wheel', function (e) { e.preventDefault(); _this2.update(); }); } }, { key: "destroy", value: function destroy() { this.$handle.remove(); } }, { key: "update", value: function update(target, event) { if (this.context.isDisabled()) { return false; } var isImage = dom.isImg(target); var $selection = this.$handle.find('.note-control-selection'); this.context.invoke('imagePopover.update', target, event); if (isImage) { var $image = external_jQuery_default()(target); var position = $image.position(); var pos = { left: position.left + parseInt($image.css('marginLeft'), 10), top: position.top + parseInt($image.css('marginTop'), 10) }; // exclude margin var imageSize = { w: $image.outerWidth(false), h: $image.outerHeight(false) }; $selection.css({ display: 'block', left: pos.left, top: pos.top, width: imageSize.w, height: imageSize.h }).data('target', $image); // save current image element. var origImageObj = new Image(); origImageObj.src = $image.attr('src'); var sizingText = imageSize.w + 'x' + imageSize.h + ' (' + this.lang.image.original + ': ' + origImageObj.width + 'x' + origImageObj.height + ')'; $selection.find('.note-control-selection-info').text(sizingText); this.context.invoke('editor.saveTarget', target); } else { this.hide(); } return isImage; } /** * hide * * @param {jQuery} $handle */ }, { key: "hide", value: function hide() { this.context.invoke('editor.clearTarget'); this.$handle.children().hide(); } }]); return Handle; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoLink.js function AutoLink_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoLink_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoLink_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoLink_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoLink_defineProperties(Constructor, staticProps); return Constructor; } var defaultScheme = 'http://'; var linkPattern = /^([A-Za-z][A-Za-z0-9+-.]*\:[\/]{2}|tel:|mailto:[A-Z0-9._%+-]+@|xmpp:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i; var AutoLink = /*#__PURE__*/function () { function AutoLink(context) { var _this = this; AutoLink_classCallCheck(this, AutoLink); this.context = context; this.options = context.options; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); } }; } AutoLink_createClass(AutoLink, [{ key: "initialize", value: function initialize() { this.lastWordRange = null; } }, { key: "destroy", value: function destroy() { this.lastWordRange = null; } }, { key: "replace", value: function replace() { if (!this.lastWordRange) { return; } var keyword = this.lastWordRange.toString(); var match = keyword.match(linkPattern); if (match && (match[1] || match[2])) { var link = match[1] ? keyword : defaultScheme + keyword; var urlText = this.options.showDomainOnlyForAutolink ? keyword.replace(/^(?:https?:\/\/)?(?:tel?:?)?(?:mailto?:?)?(?:xmpp?:?)?(?:www\.)?/i, '').split('/')[0] : keyword; var node = external_jQuery_default()('<a></a>').html(urlText).attr('href', link)[0]; if (this.context.options.linkTargetBlank) { external_jQuery_default()(node).attr('target', '_blank'); } this.lastWordRange.insertNode(node); this.lastWordRange = null; this.context.invoke('editor.focus'); } } }, { key: "handleKeydown", value: function handleKeydown(e) { if (lists.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) { var wordRange = this.context.invoke('editor.createRange').getWordRange(); this.lastWordRange = wordRange; } } }, { key: "handleKeyup", value: function handleKeyup(e) { if (lists.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) { this.replace(); } } }]); return AutoLink; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoSync.js function AutoSync_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoSync_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoSync_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoSync_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoSync_defineProperties(Constructor, staticProps); return Constructor; } /** * textarea auto sync. */ var AutoSync = /*#__PURE__*/function () { function AutoSync(context) { var _this = this; AutoSync_classCallCheck(this, AutoSync); this.$note = context.layoutInfo.note; this.events = { 'summernote.change': function summernoteChange() { _this.$note.val(context.invoke('code')); } }; } AutoSync_createClass(AutoSync, [{ key: "shouldInitialize", value: function shouldInitialize() { return dom.isTextarea(this.$note[0]); } }]); return AutoSync; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoReplace.js function AutoReplace_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoReplace_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoReplace_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoReplace_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoReplace_defineProperties(Constructor, staticProps); return Constructor; } var AutoReplace = /*#__PURE__*/function () { function AutoReplace(context) { var _this = this; AutoReplace_classCallCheck(this, AutoReplace); this.context = context; this.options = context.options.replace || {}; this.keys = [key.code.ENTER, key.code.SPACE, key.code.PERIOD, key.code.COMMA, key.code.SEMICOLON, key.code.SLASH]; this.previousKeydownCode = null; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); } }; } AutoReplace_createClass(AutoReplace, [{ key: "shouldInitialize", value: function shouldInitialize() { return !!this.options.match; } }, { key: "initialize", value: function initialize() { this.lastWord = null; } }, { key: "destroy", value: function destroy() { this.lastWord = null; } }, { key: "replace", value: function replace() { if (!this.lastWord) { return; } var self = this; var keyword = this.lastWord.toString(); this.options.match(keyword, function (match) { if (match) { var node = ''; if (typeof match === 'string') { node = dom.createText(match); } else if (match instanceof jQuery) { node = match[0]; } else if (match instanceof Node) { node = match; } if (!node) return; self.lastWord.insertNode(node); self.lastWord = null; self.context.invoke('editor.focus'); } }); } }, { key: "handleKeydown", value: function handleKeydown(e) { // this forces it to remember the last whole word, even if multiple termination keys are pressed // before the previous key is let go. if (this.previousKeydownCode && lists.contains(this.keys, this.previousKeydownCode)) { this.previousKeydownCode = e.keyCode; return; } if (lists.contains(this.keys, e.keyCode)) { var wordRange = this.context.invoke('editor.createRange').getWordRange(); this.lastWord = wordRange; } this.previousKeydownCode = e.keyCode; } }, { key: "handleKeyup", value: function handleKeyup(e) { if (lists.contains(this.keys, e.keyCode)) { this.replace(); } } }]); return AutoReplace; }(); ;// CONCATENATED MODULE: ./src/js/module/Placeholder.js function Placeholder_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Placeholder_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Placeholder_createClass(Constructor, protoProps, staticProps) { if (protoProps) Placeholder_defineProperties(Constructor.prototype, protoProps); if (staticProps) Placeholder_defineProperties(Constructor, staticProps); return Constructor; } var Placeholder = /*#__PURE__*/function () { function Placeholder(context) { var _this = this; Placeholder_classCallCheck(this, Placeholder); this.context = context; this.$editingArea = context.layoutInfo.editingArea; this.options = context.options; if (this.options.inheritPlaceholder === true) { // get placeholder value from the original element this.options.placeholder = this.context.$note.attr('placeholder') || this.options.placeholder; } this.events = { 'summernote.init summernote.change': function summernoteInitSummernoteChange() { _this.update(); }, 'summernote.codeview.toggled': function summernoteCodeviewToggled() { _this.update(); } }; } Placeholder_createClass(Placeholder, [{ key: "shouldInitialize", value: function shouldInitialize() { return !!this.options.placeholder; } }, { key: "initialize", value: function initialize() { var _this2 = this; this.$placeholder = external_jQuery_default()('<div class="note-placeholder"></div>'); this.$placeholder.on('click', function () { _this2.context.invoke('focus'); }).html(this.options.placeholder).prependTo(this.$editingArea); this.update(); } }, { key: "destroy", value: function destroy() { this.$placeholder.remove(); } }, { key: "update", value: function update() { var isShow = !this.context.invoke('codeview.isActivated') && this.context.invoke('editor.isEmpty'); this.$placeholder.toggle(isShow); } }]); return Placeholder; }(); ;// CONCATENATED MODULE: ./src/js/module/Buttons.js function Buttons_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Buttons_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Buttons_createClass(Constructor, protoProps, staticProps) { if (protoProps) Buttons_defineProperties(Constructor.prototype, protoProps); if (staticProps) Buttons_defineProperties(Constructor, staticProps); return Constructor; } var Buttons = /*#__PURE__*/function () { function Buttons(context) { Buttons_classCallCheck(this, Buttons); this.ui = (external_jQuery_default()).summernote.ui; this.context = context; this.$toolbar = context.layoutInfo.toolbar; this.options = context.options; this.lang = this.options.langInfo; this.invertedKeyMap = func.invertObject(this.options.keyMap[env.isMac ? 'mac' : 'pc']); } Buttons_createClass(Buttons, [{ key: "representShortcut", value: function representShortcut(editorMethod) { var shortcut = this.invertedKeyMap[editorMethod]; if (!this.options.shortcuts || !shortcut) { return ''; } if (env.isMac) { shortcut = shortcut.replace('CMD', '⌘').replace('SHIFT', '⇧'); } shortcut = shortcut.replace('BACKSLASH', '\\').replace('SLASH', '/').replace('LEFTBRACKET', '[').replace('RIGHTBRACKET', ']'); return ' (' + shortcut + ')'; } }, { key: "button", value: function button(o) { if (!this.options.tooltip && o.tooltip) { delete o.tooltip; } o.container = this.options.container; return this.ui.button(o); } }, { key: "initialize", value: function initialize() { this.addToolbarButtons(); this.addImagePopoverButtons(); this.addLinkPopoverButtons(); this.addTablePopoverButtons(); this.fontInstalledMap = {}; } }, { key: "destroy", value: function destroy() { delete this.fontInstalledMap; } }, { key: "isFontInstalled", value: function isFontInstalled(name) { if (!Object.prototype.hasOwnProperty.call(this.fontInstalledMap, name)) { this.fontInstalledMap[name] = env.isFontInstalled(name) || lists.contains(this.options.fontNamesIgnoreCheck, name); } return this.fontInstalledMap[name]; } }, { key: "isFontDeservedToAdd", value: function isFontDeservedToAdd(name) { name = name.toLowerCase(); return name !== '' && this.isFontInstalled(name) && env.genericFontFamilies.indexOf(name) === -1; } }, { key: "colorPalette", value: function colorPalette(className, tooltip, backColor, foreColor) { var _this = this; return this.ui.buttonGroup({ className: 'note-color ' + className, children: [this.button({ className: 'note-current-color-button', contents: this.ui.icon(this.options.icons.font + ' note-recent-color'), tooltip: tooltip, click: function click(e) { var $button = external_jQuery_default()(e.currentTarget); if (backColor && foreColor) { _this.context.invoke('editor.color', { backColor: $button.attr('data-backColor'), foreColor: $button.attr('data-foreColor') }); } else if (backColor) { _this.context.invoke('editor.color', { backColor: $button.attr('data-backColor') }); } else if (foreColor) { _this.context.invoke('editor.color', { foreColor: $button.attr('data-foreColor') }); } }, callback: function callback($button) { var $recentColor = $button.find('.note-recent-color'); if (backColor) { $recentColor.css('background-color', _this.options.colorButton.backColor); $button.attr('data-backColor', _this.options.colorButton.backColor); } if (foreColor) { $recentColor.css('color', _this.options.colorButton.foreColor); $button.attr('data-foreColor', _this.options.colorButton.foreColor); } else { $recentColor.css('color', 'transparent'); } } }), this.button({ className: 'dropdown-toggle', contents: this.ui.dropdownButtonContents('', this.options), tooltip: this.lang.color.more, data: { toggle: 'dropdown' } }), this.ui.dropdown({ items: (backColor ? ['<div class="note-palette">', '<div class="note-palette-title">' + this.lang.color.background + '</div>', '<div>', '<button type="button" class="note-color-reset btn btn-light btn-default" data-event="backColor" data-value="transparent">', this.lang.color.transparent, '</button>', '</div>', '<div class="note-holder" data-event="backColor"><!-- back colors --></div>', '<div>', '<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="backColorPicker-' + this.options.id + '">', this.lang.color.cpSelect, '</button>', '<input type="color" id="backColorPicker-' + this.options.id + '" class="note-btn note-color-select-btn" value="' + this.options.colorButton.backColor + '" data-event="backColorPalette-' + this.options.id + '">', '</div>', '<div class="note-holder-custom" id="backColorPalette-' + this.options.id + '" data-event="backColor"></div>', '</div>'].join('') : '') + (foreColor ? ['<div class="note-palette">', '<div class="note-palette-title">' + this.lang.color.foreground + '</div>', '<div>', '<button type="button" class="note-color-reset btn btn-light btn-default" data-event="removeFormat" data-value="foreColor">', this.lang.color.resetToDefault, '</button>', '</div>', '<div class="note-holder" data-event="foreColor"><!-- fore colors --></div>', '<div>', '<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="foreColorPicker-' + this.options.id + '">', this.lang.color.cpSelect, '</button>', '<input type="color" id="foreColorPicker-' + this.options.id + '" class="note-btn note-color-select-btn" value="' + this.options.colorButton.foreColor + '" data-event="foreColorPalette-' + this.options.id + '">', '</div>', // Fix missing Div, Commented to find easily if it's wrong '<div class="note-holder-custom" id="foreColorPalette-' + this.options.id + '" data-event="foreColor"></div>', '</div>'].join('') : ''), callback: function callback($dropdown) { $dropdown.find('.note-holder').each(function (idx, item) { var $holder = external_jQuery_default()(item); $holder.append(_this.ui.palette({ colors: _this.options.colors, colorsName: _this.options.colorsName, eventName: $holder.data('event'), container: _this.options.container, tooltip: _this.options.tooltip }).render()); }); /* TODO: do we have to record recent custom colors within cookies? */ var customColors = [['#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF']]; $dropdown.find('.note-holder-custom').each(function (idx, item) { var $holder = external_jQuery_default()(item); $holder.append(_this.ui.palette({ colors: customColors, colorsName: customColors, eventName: $holder.data('event'), container: _this.options.container, tooltip: _this.options.tooltip }).render()); }); $dropdown.find('input[type=color]').each(function (idx, item) { external_jQuery_default()(item).change(function () { var $chip = $dropdown.find('#' + external_jQuery_default()(this).data('event')).find('.note-color-btn').first(); var color = this.value.toUpperCase(); $chip.css('background-color', color).attr('aria-label', color).attr('data-value', color).attr('data-original-title', color); $chip.click(); }); }); }, click: function click(event) { event.stopPropagation(); var $parent = external_jQuery_default()('.' + className).find('.note-dropdown-menu'); var $button = external_jQuery_default()(event.target); var eventName = $button.data('event'); var value = $button.attr('data-value'); if (eventName === 'openPalette') { var $picker = $parent.find('#' + value); var $palette = external_jQuery_default()($parent.find('#' + $picker.data('event')).find('.note-color-row')[0]); // Shift palette chips var $chip = $palette.find('.note-color-btn').last().detach(); // Set chip attributes var color = $picker.val(); $chip.css('background-color', color).attr('aria-label', color).attr('data-value', color).attr('data-original-title', color); $palette.prepend($chip); $picker.click(); } else { if (lists.contains(['backColor', 'foreColor'], eventName)) { var key = eventName === 'backColor' ? 'background-color' : 'color'; var $color = $button.closest('.note-color').find('.note-recent-color'); var $currentButton = $button.closest('.note-color').find('.note-current-color-button'); $color.css(key, value); $currentButton.attr('data-' + eventName, value); } _this.context.invoke('editor.' + eventName, value); } } })] }).render(); } }, { key: "addToolbarButtons", value: function addToolbarButtons() { var _this2 = this; this.context.memo('button.style', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.magic), _this2.options), tooltip: _this2.lang.style.style, data: { toggle: 'dropdown' } }), _this2.ui.dropdown({ className: 'dropdown-style', items: _this2.options.styleTags, title: _this2.lang.style.style, template: function template(item) { // TBD: need to be simplified if (typeof item === 'string') { item = { tag: item, title: Object.prototype.hasOwnProperty.call(_this2.lang.style, item) ? _this2.lang.style[item] : item }; } var tag = item.tag; var title = item.title; var style = item.style ? ' style="' + item.style + '" ' : ''; var className = item.className ? ' class="' + item.className + '"' : ''; return '<' + tag + style + className + '>' + title + '</' + tag + '>'; }, click: _this2.context.createInvokeHandler('editor.formatBlock') })]).render(); }); var _loop = function _loop(styleIdx, styleLen) { var item = _this2.options.styleTags[styleIdx]; _this2.context.memo('button.style.' + item, function () { return _this2.button({ className: 'note-btn-style-' + item, contents: '<div data-value="' + item + '">' + item.toUpperCase() + '</div>', tooltip: _this2.lang.style[item], click: _this2.context.createInvokeHandler('editor.formatBlock') }).render(); }); }; for (var styleIdx = 0, styleLen = this.options.styleTags.length; styleIdx < styleLen; styleIdx++) { _loop(styleIdx, styleLen); } this.context.memo('button.bold', function () { return _this2.button({ className: 'note-btn-bold', contents: _this2.ui.icon(_this2.options.icons.bold), tooltip: _this2.lang.font.bold + _this2.representShortcut('bold'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.bold') }).render(); }); this.context.memo('button.italic', function () { return _this2.button({ className: 'note-btn-italic', contents: _this2.ui.icon(_this2.options.icons.italic), tooltip: _this2.lang.font.italic + _this2.representShortcut('italic'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.italic') }).render(); }); this.context.memo('button.underline', function () { return _this2.button({ className: 'note-btn-underline', contents: _this2.ui.icon(_this2.options.icons.underline), tooltip: _this2.lang.font.underline + _this2.representShortcut('underline'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.underline') }).render(); }); this.context.memo('button.clear', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.eraser), tooltip: _this2.lang.font.clear + _this2.representShortcut('removeFormat'), click: _this2.context.createInvokeHandler('editor.removeFormat') }).render(); }); this.context.memo('button.strikethrough', function () { return _this2.button({ className: 'note-btn-strikethrough', contents: _this2.ui.icon(_this2.options.icons.strikethrough), tooltip: _this2.lang.font.strikethrough + _this2.representShortcut('strikethrough'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.strikethrough') }).render(); }); this.context.memo('button.superscript', function () { return _this2.button({ className: 'note-btn-superscript', contents: _this2.ui.icon(_this2.options.icons.superscript), tooltip: _this2.lang.font.superscript, click: _this2.context.createInvokeHandlerAndUpdateState('editor.superscript') }).render(); }); this.context.memo('button.subscript', function () { return _this2.button({ className: 'note-btn-subscript', contents: _this2.ui.icon(_this2.options.icons.subscript), tooltip: _this2.lang.font.subscript, click: _this2.context.createInvokeHandlerAndUpdateState('editor.subscript') }).render(); }); this.context.memo('button.fontname', function () { var styleInfo = _this2.context.invoke('editor.currentStyle'); if (_this2.options.addDefaultFonts) { // Add 'default' fonts into the fontnames array if not exist external_jQuery_default().each(styleInfo['font-family'].split(','), function (idx, fontname) { fontname = fontname.trim().replace(/['"]+/g, ''); if (_this2.isFontDeservedToAdd(fontname)) { if (_this2.options.fontNames.indexOf(fontname) === -1) { _this2.options.fontNames.push(fontname); } } }); } return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontname"></span>', _this2.options), tooltip: _this2.lang.font.name, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontname', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontNames.filter(_this2.isFontInstalled.bind(_this2)), title: _this2.lang.font.name, template: function template(item) { return '<span style="font-family: ' + env.validFontName(item) + '">' + item + '</span>'; }, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontName') })]).render(); }); this.context.memo('button.fontsize', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontsize"></span>', _this2.options), tooltip: _this2.lang.font.size, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontsize', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontSizes, title: _this2.lang.font.size, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontSize') })]).render(); }); this.context.memo('button.fontsizeunit', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontsizeunit"></span>', _this2.options), tooltip: _this2.lang.font.sizeunit, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontsizeunit', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontSizeUnits, title: _this2.lang.font.sizeunit, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontSizeUnit') })]).render(); }); this.context.memo('button.color', function () { return _this2.colorPalette('note-color-all', _this2.lang.color.recent, true, true); }); this.context.memo('button.forecolor', function () { return _this2.colorPalette('note-color-fore', _this2.lang.color.foreground, false, true); }); this.context.memo('button.backcolor', function () { return _this2.colorPalette('note-color-back', _this2.lang.color.background, true, false); }); this.context.memo('button.ul', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.unorderedlist), tooltip: _this2.lang.lists.unordered + _this2.representShortcut('insertUnorderedList'), click: _this2.context.createInvokeHandler('editor.insertUnorderedList') }).render(); }); this.context.memo('button.ol', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.orderedlist), tooltip: _this2.lang.lists.ordered + _this2.representShortcut('insertOrderedList'), click: _this2.context.createInvokeHandler('editor.insertOrderedList') }).render(); }); var justifyLeft = this.button({ contents: this.ui.icon(this.options.icons.alignLeft), tooltip: this.lang.paragraph.left + this.representShortcut('justifyLeft'), click: this.context.createInvokeHandler('editor.justifyLeft') }); var justifyCenter = this.button({ contents: this.ui.icon(this.options.icons.alignCenter), tooltip: this.lang.paragraph.center + this.representShortcut('justifyCenter'), click: this.context.createInvokeHandler('editor.justifyCenter') }); var justifyRight = this.button({ contents: this.ui.icon(this.options.icons.alignRight), tooltip: this.lang.paragraph.right + this.representShortcut('justifyRight'), click: this.context.createInvokeHandler('editor.justifyRight') }); var justifyFull = this.button({ contents: this.ui.icon(this.options.icons.alignJustify), tooltip: this.lang.paragraph.justify + this.representShortcut('justifyFull'), click: this.context.createInvokeHandler('editor.justifyFull') }); var outdent = this.button({ contents: this.ui.icon(this.options.icons.outdent), tooltip: this.lang.paragraph.outdent + this.representShortcut('outdent'), click: this.context.createInvokeHandler('editor.outdent') }); var indent = this.button({ contents: this.ui.icon(this.options.icons.indent), tooltip: this.lang.paragraph.indent + this.representShortcut('indent'), click: this.context.createInvokeHandler('editor.indent') }); this.context.memo('button.justifyLeft', func.invoke(justifyLeft, 'render')); this.context.memo('button.justifyCenter', func.invoke(justifyCenter, 'render')); this.context.memo('button.justifyRight', func.invoke(justifyRight, 'render')); this.context.memo('button.justifyFull', func.invoke(justifyFull, 'render')); this.context.memo('button.outdent', func.invoke(outdent, 'render')); this.context.memo('button.indent', func.invoke(indent, 'render')); this.context.memo('button.paragraph', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.alignLeft), _this2.options), tooltip: _this2.lang.paragraph.paragraph, data: { toggle: 'dropdown' } }), _this2.ui.dropdown([_this2.ui.buttonGroup({ className: 'note-align', children: [justifyLeft, justifyCenter, justifyRight, justifyFull] }), _this2.ui.buttonGroup({ className: 'note-list', children: [outdent, indent] })])]).render(); }); this.context.memo('button.height', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.textHeight), _this2.options), tooltip: _this2.lang.font.height, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ items: _this2.options.lineHeights, checkClassName: _this2.options.icons.menuCheck, className: 'dropdown-line-height', title: _this2.lang.font.height, click: _this2.context.createInvokeHandler('editor.lineHeight') })]).render(); }); this.context.memo('button.table', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.table), _this2.options), tooltip: _this2.lang.table.table, data: { toggle: 'dropdown' } }), _this2.ui.dropdown({ title: _this2.lang.table.table, className: 'note-table', items: ['<div class="note-dimension-picker">', '<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>', '<div class="note-dimension-picker-highlighted"></div>', '<div class="note-dimension-picker-unhighlighted"></div>', '</div>', '<div class="note-dimension-display">1 x 1</div>'].join('') })], { callback: function callback($node) { var $catcher = $node.find('.note-dimension-picker-mousecatcher'); $catcher.css({ width: _this2.options.insertTableMaxSize.col + 'em', height: _this2.options.insertTableMaxSize.row + 'em' }).mouseup(_this2.context.createInvokeHandler('editor.insertTable')).on('mousemove', _this2.tableMoveHandler.bind(_this2)); } }).render(); }); this.context.memo('button.link', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.link), tooltip: _this2.lang.link.link + _this2.representShortcut('linkDialog.show'), click: _this2.context.createInvokeHandler('linkDialog.show') }).render(); }); this.context.memo('button.picture', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.picture), tooltip: _this2.lang.image.image, click: _this2.context.createInvokeHandler('imageDialog.show') }).render(); }); this.context.memo('button.video', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.video), tooltip: _this2.lang.video.video, click: _this2.context.createInvokeHandler('videoDialog.show') }).render(); }); this.context.memo('button.hr', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.minus), tooltip: _this2.lang.hr.insert + _this2.representShortcut('insertHorizontalRule'), click: _this2.context.createInvokeHandler('editor.insertHorizontalRule') }).render(); }); this.context.memo('button.fullscreen', function () { return _this2.button({ className: 'btn-fullscreen note-codeview-keep', contents: _this2.ui.icon(_this2.options.icons.arrowsAlt), tooltip: _this2.lang.options.fullscreen, click: _this2.context.createInvokeHandler('fullscreen.toggle') }).render(); }); this.context.memo('button.codeview', function () { return _this2.button({ className: 'btn-codeview note-codeview-keep', contents: _this2.ui.icon(_this2.options.icons.code), tooltip: _this2.lang.options.codeview, click: _this2.context.createInvokeHandler('codeview.toggle') }).render(); }); this.context.memo('button.redo', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.redo), tooltip: _this2.lang.history.redo + _this2.representShortcut('redo'), click: _this2.context.createInvokeHandler('editor.redo') }).render(); }); this.context.memo('button.undo', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.undo), tooltip: _this2.lang.history.undo + _this2.representShortcut('undo'), click: _this2.context.createInvokeHandler('editor.undo') }).render(); }); this.context.memo('button.help', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.question), tooltip: _this2.lang.options.help, click: _this2.context.createInvokeHandler('helpDialog.show') }).render(); }); } /** * image: [ * ['imageResize', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']], * ['float', ['floatLeft', 'floatRight', 'floatNone']], * ['remove', ['removeMedia']], * ], */ }, { key: "addImagePopoverButtons", value: function addImagePopoverButtons() { var _this3 = this; // Image Size Buttons this.context.memo('button.resizeFull', function () { return _this3.button({ contents: '<span class="note-fontsize-10">100%</span>', tooltip: _this3.lang.image.resizeFull, click: _this3.context.createInvokeHandler('editor.resize', '1') }).render(); }); this.context.memo('button.resizeHalf', function () { return _this3.button({ contents: '<span class="note-fontsize-10">50%</span>', tooltip: _this3.lang.image.resizeHalf, click: _this3.context.createInvokeHandler('editor.resize', '0.5') }).render(); }); this.context.memo('button.resizeQuarter', function () { return _this3.button({ contents: '<span class="note-fontsize-10">25%</span>', tooltip: _this3.lang.image.resizeQuarter, click: _this3.context.createInvokeHandler('editor.resize', '0.25') }).render(); }); this.context.memo('button.resizeNone', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.rollback), tooltip: _this3.lang.image.resizeNone, click: _this3.context.createInvokeHandler('editor.resize', '0') }).render(); }); // Float Buttons this.context.memo('button.floatLeft', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.floatLeft), tooltip: _this3.lang.image.floatLeft, click: _this3.context.createInvokeHandler('editor.floatMe', 'left') }).render(); }); this.context.memo('button.floatRight', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.floatRight), tooltip: _this3.lang.image.floatRight, click: _this3.context.createInvokeHandler('editor.floatMe', 'right') }).render(); }); this.context.memo('button.floatNone', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.rollback), tooltip: _this3.lang.image.floatNone, click: _this3.context.createInvokeHandler('editor.floatMe', 'none') }).render(); }); // Remove Buttons this.context.memo('button.removeMedia', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.trash), tooltip: _this3.lang.image.remove, click: _this3.context.createInvokeHandler('editor.removeMedia') }).render(); }); } }, { key: "addLinkPopoverButtons", value: function addLinkPopoverButtons() { var _this4 = this; this.context.memo('button.linkDialogShow', function () { return _this4.button({ contents: _this4.ui.icon(_this4.options.icons.link), tooltip: _this4.lang.link.edit, click: _this4.context.createInvokeHandler('linkDialog.show') }).render(); }); this.context.memo('button.unlink', function () { return _this4.button({ contents: _this4.ui.icon(_this4.options.icons.unlink), tooltip: _this4.lang.link.unlink, click: _this4.context.createInvokeHandler('editor.unlink') }).render(); }); } /** * table : [ * ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']], * ['delete', ['deleteRow', 'deleteCol', 'deleteTable']] * ], */ }, { key: "addTablePopoverButtons", value: function addTablePopoverButtons() { var _this5 = this; this.context.memo('button.addRowUp', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowAbove), tooltip: _this5.lang.table.addRowAbove, click: _this5.context.createInvokeHandler('editor.addRow', 'top') }).render(); }); this.context.memo('button.addRowDown', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowBelow), tooltip: _this5.lang.table.addRowBelow, click: _this5.context.createInvokeHandler('editor.addRow', 'bottom') }).render(); }); this.context.memo('button.addColLeft', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colBefore), tooltip: _this5.lang.table.addColLeft, click: _this5.context.createInvokeHandler('editor.addCol', 'left') }).render(); }); this.context.memo('button.addColRight', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colAfter), tooltip: _this5.lang.table.addColRight, click: _this5.context.createInvokeHandler('editor.addCol', 'right') }).render(); }); this.context.memo('button.deleteRow', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowRemove), tooltip: _this5.lang.table.delRow, click: _this5.context.createInvokeHandler('editor.deleteRow') }).render(); }); this.context.memo('button.deleteCol', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colRemove), tooltip: _this5.lang.table.delCol, click: _this5.context.createInvokeHandler('editor.deleteCol') }).render(); }); this.context.memo('button.deleteTable', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.trash), tooltip: _this5.lang.table.delTable, click: _this5.context.createInvokeHandler('editor.deleteTable') }).render(); }); } }, { key: "build", value: function build($container, groups) { for (var groupIdx = 0, groupLen = groups.length; groupIdx < groupLen; groupIdx++) { var group = groups[groupIdx]; var groupName = Array.isArray(group) ? group[0] : group; var buttons = Array.isArray(group) ? group.length === 1 ? [group[0]] : group[1] : [group]; var $group = this.ui.buttonGroup({ className: 'note-' + groupName }).render(); for (var idx = 0, len = buttons.length; idx < len; idx++) { var btn = this.context.memo('button.' + buttons[idx]); if (btn) { $group.append(typeof btn === 'function' ? btn(this.context) : btn); } } $group.appendTo($container); } } /** * @param {jQuery} [$container] */ }, { key: "updateCurrentStyle", value: function updateCurrentStyle($container) { var $cont = $container || this.$toolbar; var styleInfo = this.context.invoke('editor.currentStyle'); this.updateBtnStates($cont, { '.note-btn-bold': function noteBtnBold() { return styleInfo['font-bold'] === 'bold'; }, '.note-btn-italic': function noteBtnItalic() { return styleInfo['font-italic'] === 'italic'; }, '.note-btn-underline': function noteBtnUnderline() { return styleInfo['font-underline'] === 'underline'; }, '.note-btn-subscript': function noteBtnSubscript() { return styleInfo['font-subscript'] === 'subscript'; }, '.note-btn-superscript': function noteBtnSuperscript() { return styleInfo['font-superscript'] === 'superscript'; }, '.note-btn-strikethrough': function noteBtnStrikethrough() { return styleInfo['font-strikethrough'] === 'strikethrough'; } }); if (styleInfo['font-family']) { var fontNames = styleInfo['font-family'].split(',').map(function (name) { return name.replace(/[\'\"]/g, '').replace(/\s+$/, '').replace(/^\s+/, ''); }); var fontName = lists.find(fontNames, this.isFontInstalled.bind(this)); $cont.find('.dropdown-fontname a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare string to avoid creating another func. var isChecked = $item.data('value') + '' === fontName + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontname').text(fontName).css('font-family', fontName); } if (styleInfo['font-size']) { var fontSize = styleInfo['font-size']; $cont.find('.dropdown-fontsize a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare with string to avoid creating another func. var isChecked = $item.data('value') + '' === fontSize + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontsize').text(fontSize); var fontSizeUnit = styleInfo['font-size-unit']; $cont.find('.dropdown-fontsizeunit a').each(function (idx, item) { var $item = external_jQuery_default()(item); var isChecked = $item.data('value') + '' === fontSizeUnit + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontsizeunit').text(fontSizeUnit); } if (styleInfo['line-height']) { var lineHeight = styleInfo['line-height']; $cont.find('.dropdown-line-height a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare with string to avoid creating another func. var isChecked = external_jQuery_default()(item).data('value') + '' === lineHeight + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-line-height').text(lineHeight); } } }, { key: "updateBtnStates", value: function updateBtnStates($container, infos) { var _this6 = this; external_jQuery_default().each(infos, function (selector, pred) { _this6.ui.toggleBtnActive($container.find(selector), pred()); }); } }, { key: "tableMoveHandler", value: function tableMoveHandler(event) { var PX_PER_EM = 18; var $picker = external_jQuery_default()(event.target.parentNode); // target is mousecatcher var $dimensionDisplay = $picker.next(); var $catcher = $picker.find('.note-dimension-picker-mousecatcher'); var $highlighted = $picker.find('.note-dimension-picker-highlighted'); var $unhighlighted = $picker.find('.note-dimension-picker-unhighlighted'); var posOffset; // HTML5 with jQuery - e.offsetX is undefined in Firefox if (event.offsetX === undefined) { var posCatcher = external_jQuery_default()(event.target).offset(); posOffset = { x: event.pageX - posCatcher.left, y: event.pageY - posCatcher.top }; } else { posOffset = { x: event.offsetX, y: event.offsetY }; } var dim = { c: Math.ceil(posOffset.x / PX_PER_EM) || 1, r: Math.ceil(posOffset.y / PX_PER_EM) || 1 }; $highlighted.css({ width: dim.c + 'em', height: dim.r + 'em' }); $catcher.data('value', dim.c + 'x' + dim.r); if (dim.c > 3 && dim.c < this.options.insertTableMaxSize.col) { $unhighlighted.css({ width: dim.c + 1 + 'em' }); } if (dim.r > 3 && dim.r < this.options.insertTableMaxSize.row) { $unhighlighted.css({ height: dim.r + 1 + 'em' }); } $dimensionDisplay.html(dim.c + ' x ' + dim.r); } }]); return Buttons; }(); ;// CONCATENATED MODULE: ./src/js/module/Toolbar.js function Toolbar_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Toolbar_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Toolbar_createClass(Constructor, protoProps, staticProps) { if (protoProps) Toolbar_defineProperties(Constructor.prototype, protoProps); if (staticProps) Toolbar_defineProperties(Constructor, staticProps); return Constructor; } var Toolbar = /*#__PURE__*/function () { function Toolbar(context) { Toolbar_classCallCheck(this, Toolbar); this.context = context; this.$window = external_jQuery_default()(window); this.$document = external_jQuery_default()(document); this.ui = (external_jQuery_default()).summernote.ui; this.$note = context.layoutInfo.note; this.$editor = context.layoutInfo.editor; this.$toolbar = context.layoutInfo.toolbar; this.$editable = context.layoutInfo.editable; this.$statusbar = context.layoutInfo.statusbar; this.options = context.options; this.isFollowing = false; this.followScroll = this.followScroll.bind(this); } Toolbar_createClass(Toolbar, [{ key: "shouldInitialize", value: function shouldInitialize() { return !this.options.airMode; } }, { key: "initialize", value: function initialize() { var _this = this; this.options.toolbar = this.options.toolbar || []; if (!this.options.toolbar.length) { this.$toolbar.hide(); } else { this.context.invoke('buttons.build', this.$toolbar, this.options.toolbar); } if (this.options.toolbarContainer) { this.$toolbar.appendTo(this.options.toolbarContainer); } this.changeContainer(false); this.$note.on('summernote.keyup summernote.mouseup summernote.change', function () { _this.context.invoke('buttons.updateCurrentStyle'); }); this.context.invoke('buttons.updateCurrentStyle'); if (this.options.followingToolbar) { this.$window.on('scroll resize', this.followScroll); } } }, { key: "destroy", value: function destroy() { this.$toolbar.children().remove(); if (this.options.followingToolbar) { this.$window.off('scroll resize', this.followScroll); } } }, { key: "followScroll", value: function followScroll() { if (this.$editor.hasClass('fullscreen')) { return false; } var editorHeight = this.$editor.outerHeight(); var editorWidth = this.$editor.width(); var toolbarHeight = this.$toolbar.height(); var statusbarHeight = this.$statusbar.height(); // check if the web app is currently using another static bar var otherBarHeight = 0; if (this.options.otherStaticBar) { otherBarHeight = external_jQuery_default()(this.options.otherStaticBar).outerHeight(); } var currentOffset = this.$document.scrollTop(); var editorOffsetTop = this.$editor.offset().top; var editorOffsetBottom = editorOffsetTop + editorHeight; var activateOffset = editorOffsetTop - otherBarHeight; var deactivateOffsetBottom = editorOffsetBottom - otherBarHeight - toolbarHeight - statusbarHeight; if (!this.isFollowing && currentOffset > activateOffset && currentOffset < deactivateOffsetBottom - toolbarHeight) { this.isFollowing = true; this.$editable.css({ marginTop: this.$toolbar.outerHeight() }); this.$toolbar.css({ position: 'fixed', top: otherBarHeight, width: editorWidth, zIndex: 1000 }); } else if (this.isFollowing && (currentOffset < activateOffset || currentOffset > deactivateOffsetBottom)) { this.isFollowing = false; this.$toolbar.css({ position: 'relative', top: 0, width: '100%', zIndex: 'auto' }); this.$editable.css({ marginTop: '' }); } } }, { key: "changeContainer", value: function changeContainer(isFullscreen) { if (isFullscreen) { this.$toolbar.prependTo(this.$editor); } else { if (this.options.toolbarContainer) { this.$toolbar.appendTo(this.options.toolbarContainer); } } if (this.options.followingToolbar) { this.followScroll(); } } }, { key: "updateFullscreen", value: function updateFullscreen(isFullscreen) { this.ui.toggleBtnActive(this.$toolbar.find('.btn-fullscreen'), isFullscreen); this.changeContainer(isFullscreen); } }, { key: "updateCodeview", value: function updateCodeview(isCodeview) { this.ui.toggleBtnActive(this.$toolbar.find('.btn-codeview'), isCodeview); if (isCodeview) { this.deactivate(); } else { this.activate(); } } }, { key: "activate", value: function activate(isIncludeCodeview) { var $btn = this.$toolbar.find('button'); if (!isIncludeCodeview) { $btn = $btn.not('.note-codeview-keep'); } this.ui.toggleBtn($btn, true); } }, { key: "deactivate", value: function deactivate(isIncludeCodeview) { var $btn = this.$toolbar.find('button'); if (!isIncludeCodeview) { $btn = $btn.not('.note-codeview-keep'); } this.ui.toggleBtn($btn, false); } }]); return Toolbar; }(); ;// CONCATENATED MODULE: ./src/js/module/LinkDialog.js function LinkDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function LinkDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function LinkDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) LinkDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) LinkDialog_defineProperties(Constructor, staticProps); return Constructor; } var LinkDialog = /*#__PURE__*/function () { function LinkDialog(context) { LinkDialog_classCallCheck(this, LinkDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; context.memo('help.linkDialog.show', this.options.langInfo.help['linkDialog.show']); } LinkDialog_createClass(LinkDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group">', "<label for=\"note-dialog-link-txt-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.link.textToDisplay, "</label>"), "<input id=\"note-dialog-link-txt-".concat(this.options.id, "\" class=\"note-link-text form-control note-form-control note-input\" type=\"text\"/>"), '</div>', '<div class="form-group note-form-group">', "<label for=\"note-dialog-link-url-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.link.url, "</label>"), "<input id=\"note-dialog-link-url-".concat(this.options.id, "\" class=\"note-link-url form-control note-form-control note-input\" type=\"text\" value=\"http://\"/>"), '</div>', !this.options.disableLinkTarget ? external_jQuery_default()('<div></div>').append(this.ui.checkbox({ className: 'sn-checkbox-open-in-new-window', text: this.lang.link.openInNewWindow, checked: true }).render()).html() : '', external_jQuery_default()('<div></div>').append(this.ui.checkbox({ className: 'sn-checkbox-use-protocol', text: this.lang.link.useProtocol, checked: true }).render()).html()].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-link-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.link.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ className: 'link-dialog', title: this.lang.link.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } /** * toggle update button */ }, { key: "toggleLinkBtn", value: function toggleLinkBtn($linkBtn, $linkText, $linkUrl) { this.ui.toggleBtn($linkBtn, $linkText.val() && $linkUrl.val()); } /** * Show link dialog and set event handlers on dialog controls. * * @param {Object} linkInfo * @return {Promise} */ }, { key: "showLinkDialog", value: function showLinkDialog(linkInfo) { var _this = this; return external_jQuery_default().Deferred(function (deferred) { var $linkText = _this.$dialog.find('.note-link-text'); var $linkUrl = _this.$dialog.find('.note-link-url'); var $linkBtn = _this.$dialog.find('.note-link-btn'); var $openInNewWindow = _this.$dialog.find('.sn-checkbox-open-in-new-window input[type=checkbox]'); var $useProtocol = _this.$dialog.find('.sn-checkbox-use-protocol input[type=checkbox]'); _this.ui.onDialogShown(_this.$dialog, function () { _this.context.triggerEvent('dialog.shown'); // If no url was given and given text is valid URL then copy that into URL Field if (!linkInfo.url && func.isValidUrl(linkInfo.text)) { linkInfo.url = linkInfo.text; } $linkText.on('input paste propertychange', function () { // If linktext was modified by input events, // cloning text from linkUrl will be stopped. linkInfo.text = $linkText.val(); _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); }).val(linkInfo.text); $linkUrl.on('input paste propertychange', function () { // Display same text on `Text to display` as default // when linktext has no text if (!linkInfo.text) { $linkText.val($linkUrl.val()); } _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); }).val(linkInfo.url); if (!env.isSupportTouch) { $linkUrl.trigger('focus'); } _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); _this.bindEnterKey($linkUrl, $linkBtn); _this.bindEnterKey($linkText, $linkBtn); var isNewWindowChecked = linkInfo.isNewWindow !== undefined ? linkInfo.isNewWindow : _this.context.options.linkTargetBlank; $openInNewWindow.prop('checked', isNewWindowChecked); var useProtocolChecked = linkInfo.url ? false : _this.context.options.useProtocol; $useProtocol.prop('checked', useProtocolChecked); $linkBtn.one('click', function (event) { event.preventDefault(); deferred.resolve({ range: linkInfo.range, url: $linkUrl.val(), text: $linkText.val(), isNewWindow: $openInNewWindow.is(':checked'), checkProtocol: $useProtocol.is(':checked') }); _this.ui.hideDialog(_this.$dialog); }); }); _this.ui.onDialogHidden(_this.$dialog, function () { // detach events $linkText.off(); $linkUrl.off(); $linkBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this.ui.showDialog(_this.$dialog); }).promise(); } /** * @param {Object} layoutInfo */ }, { key: "show", value: function show() { var _this2 = this; var linkInfo = this.context.invoke('editor.getLinkInfo'); this.context.invoke('editor.saveRange'); this.showLinkDialog(linkInfo).then(function (linkInfo) { _this2.context.invoke('editor.restoreRange'); _this2.context.invoke('editor.createLink', linkInfo); }).fail(function () { _this2.context.invoke('editor.restoreRange'); }); } }]); return LinkDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/LinkPopover.js function LinkPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function LinkPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function LinkPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) LinkPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) LinkPopover_defineProperties(Constructor, staticProps); return Constructor; } var LinkPopover = /*#__PURE__*/function () { function LinkPopover(context) { var _this = this; LinkPopover_classCallCheck(this, LinkPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.events = { 'summernote.keyup summernote.mouseup summernote.change summernote.scroll': function summernoteKeyupSummernoteMouseupSummernoteChangeSummernoteScroll() { _this.update(); }, 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } LinkPopover_createClass(LinkPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.link); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-link-popover', callback: function callback($node) { var $content = $node.find('.popover-content,.note-popover-content'); $content.prepend('<span><a target="_blank"></a>&nbsp;</span>'); } }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.link); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update() { // Prevent focusing on editable when invoke('code') is executed if (!this.context.invoke('editor.hasFocus')) { this.hide(); return; } var rng = this.context.invoke('editor.getLastRange'); if (rng.isCollapsed() && rng.isOnAnchor()) { var anchor = dom.ancestor(rng.sc, dom.isAnchor); var href = external_jQuery_default()(anchor).attr('href'); this.$popover.find('a').attr('href', href).text(href); var pos = dom.posFromPlaceholder(anchor); var containerOffset = external_jQuery_default()(this.options.container).offset(); pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return LinkPopover; }(); ;// CONCATENATED MODULE: ./src/js/module/ImageDialog.js function ImageDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function ImageDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function ImageDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) ImageDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) ImageDialog_defineProperties(Constructor, staticProps); return Constructor; } var ImageDialog = /*#__PURE__*/function () { function ImageDialog(context) { ImageDialog_classCallCheck(this, ImageDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } ImageDialog_createClass(ImageDialog, [{ key: "initialize", value: function initialize() { var imageLimitation = ''; if (this.options.maximumImageFileSize) { var unit = Math.floor(Math.log(this.options.maximumImageFileSize) / Math.log(1024)); var readableSize = (this.options.maximumImageFileSize / Math.pow(1024, unit)).toFixed(2) * 1 + ' ' + ' KMGTP'[unit] + 'B'; imageLimitation = "<small>".concat(this.lang.image.maximumFileSize + ' : ' + readableSize, "</small>"); } var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group note-group-select-from-files">', '<label for="note-dialog-image-file-' + this.options.id + '" class="note-form-label">' + this.lang.image.selectFromFiles + '</label>', '<input id="note-dialog-image-file-' + this.options.id + '" class="note-image-input form-control-file note-form-control note-input" ', ' type="file" name="files" accept="' + this.options.acceptImageFileTypes + '" multiple="multiple"/>', imageLimitation, '</div>', '<div class="form-group note-group-image-url">', '<label for="note-dialog-image-url-' + this.options.id + '" class="note-form-label">' + this.lang.image.url + '</label>', '<input id="note-dialog-image-url-' + this.options.id + '" class="note-image-url form-control note-form-control note-input" type="text"/>', '</div>'].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-image-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.image.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ title: this.lang.image.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } }, { key: "show", value: function show() { var _this = this; this.context.invoke('editor.saveRange'); this.showImageDialog().then(function (data) { // [workaround] hide dialog before restore range for IE range focus _this.ui.hideDialog(_this.$dialog); _this.context.invoke('editor.restoreRange'); if (typeof data === 'string') { // image url // If onImageLinkInsert set, if (_this.options.callbacks.onImageLinkInsert) { _this.context.triggerEvent('image.link.insert', data); } else { _this.context.invoke('editor.insertImage', data); } } else { // array of files _this.context.invoke('editor.insertImagesOrCallback', data); } }).fail(function () { _this.context.invoke('editor.restoreRange'); }); } /** * show image dialog * * @param {jQuery} $dialog * @return {Promise} */ }, { key: "showImageDialog", value: function showImageDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { var $imageInput = _this2.$dialog.find('.note-image-input'); var $imageUrl = _this2.$dialog.find('.note-image-url'); var $imageBtn = _this2.$dialog.find('.note-image-btn'); _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); // Cloning imageInput to clear element. $imageInput.replaceWith($imageInput.clone().on('change', function (event) { deferred.resolve(event.target.files || event.target.value); }).val('')); $imageUrl.on('input paste propertychange', function () { _this2.ui.toggleBtn($imageBtn, $imageUrl.val()); }).val(''); if (!env.isSupportTouch) { $imageUrl.trigger('focus'); } $imageBtn.click(function (event) { event.preventDefault(); deferred.resolve($imageUrl.val()); }); _this2.bindEnterKey($imageUrl, $imageBtn); }); _this2.ui.onDialogHidden(_this2.$dialog, function () { $imageInput.off(); $imageUrl.off(); $imageBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this2.ui.showDialog(_this2.$dialog); }); } }]); return ImageDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/ImagePopover.js function ImagePopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function ImagePopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function ImagePopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) ImagePopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) ImagePopover_defineProperties(Constructor, staticProps); return Constructor; } /** * Image popover module * mouse events that show/hide popover will be handled by Handle.js. * Handle.js will receive the events and invoke 'imagePopover.update'. */ var ImagePopover = /*#__PURE__*/function () { function ImagePopover(context) { var _this = this; ImagePopover_classCallCheck(this, ImagePopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.editable = context.layoutInfo.editable[0]; this.options = context.options; this.events = { 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } ImagePopover_createClass(ImagePopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.image); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-image-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.image); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(target, event) { if (dom.isImg(target)) { var position = external_jQuery_default()(target).offset(); var containerOffset = external_jQuery_default()(this.options.container).offset(); var pos = {}; if (this.options.popatmouse) { pos.left = event.pageX - 20; pos.top = event.pageY; } else { pos = position; } pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return ImagePopover; }(); ;// CONCATENATED MODULE: ./src/js/module/TablePopover.js function TablePopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function TablePopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function TablePopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) TablePopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) TablePopover_defineProperties(Constructor, staticProps); return Constructor; } var TablePopover = /*#__PURE__*/function () { function TablePopover(context) { var _this = this; TablePopover_classCallCheck(this, TablePopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.events = { 'summernote.mousedown': function summernoteMousedown(we, e) { _this.update(e.target); }, 'summernote.keyup summernote.scroll summernote.change': function summernoteKeyupSummernoteScrollSummernoteChange() { _this.update(); }, 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } TablePopover_createClass(TablePopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.table); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-table-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.table); // [workaround] Disable Firefox's default table editor if (env.isFF) { document.execCommand('enableInlineTableEditing', false, false); } this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(target) { if (this.context.isDisabled()) { return false; } var isCell = dom.isCell(target) || dom.isCell(target === null || target === void 0 ? void 0 : target.parentElement); if (isCell) { var pos = dom.posFromPlaceholder(target); var containerOffset = external_jQuery_default()(this.options.container).offset(); pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } return isCell; } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return TablePopover; }(); ;// CONCATENATED MODULE: ./src/js/module/VideoDialog.js function VideoDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function VideoDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function VideoDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) VideoDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) VideoDialog_defineProperties(Constructor, staticProps); return Constructor; } var VideoDialog = /*#__PURE__*/function () { function VideoDialog(context) { VideoDialog_classCallCheck(this, VideoDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } VideoDialog_createClass(VideoDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group row-fluid">', "<label for=\"note-dialog-video-url-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.video.url, " <small class=\"text-muted\">").concat(this.lang.video.providers, "</small></label>"), "<input id=\"note-dialog-video-url-".concat(this.options.id, "\" class=\"note-video-url form-control note-form-control note-input\" type=\"text\"/>"), '</div>'].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-video-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.video.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ title: this.lang.video.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } }, { key: "createVideoNode", value: function createVideoNode(url) { // video url patterns(youtube, instagram, vimeo, dailymotion, youku, peertube, mp4, ogg, webm) var ytRegExp = /\/\/(?:(?:www|m)\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))([\w|-]{11})(?:(?:[\?&]t=)(\S+))?$/; var ytRegExpForStart = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/; var ytMatch = url.match(ytRegExp); var gdRegExp = /(?:\.|\/\/)drive\.google\.com\/file\/d\/(.[a-zA-Z0-9_-]*)\/view/; var gdMatch = url.match(gdRegExp); var igRegExp = /(?:www\.|\/\/)instagram\.com\/p\/(.[a-zA-Z0-9_-]*)/; var igMatch = url.match(igRegExp); var vRegExp = /\/\/vine\.co\/v\/([a-zA-Z0-9]+)/; var vMatch = url.match(vRegExp); var vimRegExp = /\/\/(player\.)?vimeo\.com\/([a-z]*\/)*(\d+)[?]?.*/; var vimMatch = url.match(vimRegExp); var dmRegExp = /.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/; var dmMatch = url.match(dmRegExp); var youkuRegExp = /\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/; var youkuMatch = url.match(youkuRegExp); var peerTubeRegExp = /\/\/(.*)\/videos\/watch\/([^?]*)(?:\?(?:start=(\w*))?(?:&stop=(\w*))?(?:&loop=([10]))?(?:&autoplay=([10]))?(?:&muted=([10]))?)?/; var peerTubeMatch = url.match(peerTubeRegExp); var qqRegExp = /\/\/v\.qq\.com.*?vid=(.+)/; var qqMatch = url.match(qqRegExp); var qqRegExp2 = /\/\/v\.qq\.com\/x?\/?(page|cover).*?\/([^\/]+)\.html\??.*/; var qqMatch2 = url.match(qqRegExp2); var mp4RegExp = /^.+.(mp4|m4v)$/; var mp4Match = url.match(mp4RegExp); var oggRegExp = /^.+.(ogg|ogv)$/; var oggMatch = url.match(oggRegExp); var webmRegExp = /^.+.(webm)$/; var webmMatch = url.match(webmRegExp); var fbRegExp = /(?:www\.|\/\/)facebook\.com\/([^\/]+)\/videos\/([0-9]+)/; var fbMatch = url.match(fbRegExp); var $video; if (ytMatch && ytMatch[1].length === 11) { var youtubeId = ytMatch[1]; var start = 0; if (typeof ytMatch[2] !== 'undefined') { var ytMatchForStart = ytMatch[2].match(ytRegExpForStart); if (ytMatchForStart) { for (var n = [3600, 60, 1], i = 0, r = n.length; i < r; i++) { start += typeof ytMatchForStart[i + 1] !== 'undefined' ? n[i] * parseInt(ytMatchForStart[i + 1], 10) : 0; } } } $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', '//www.youtube.com/embed/' + youtubeId + (start > 0 ? '?start=' + start : '')).attr('width', '640').attr('height', '360'); } else if (gdMatch && gdMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://drive.google.com/file/d/' + gdMatch[1] + '/preview').attr('width', '640').attr('height', '480'); } else if (igMatch && igMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://instagram.com/p/' + igMatch[1] + '/embed/').attr('width', '612').attr('height', '710').attr('scrolling', 'no').attr('allowtransparency', 'true'); } else if (vMatch && vMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', vMatch[0] + '/embed/simple').attr('width', '600').attr('height', '600').attr('class', 'vine-embed'); } else if (vimMatch && vimMatch[3].length) { $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('src', '//player.vimeo.com/video/' + vimMatch[3]).attr('width', '640').attr('height', '360'); } else if (dmMatch && dmMatch[2].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', '//www.dailymotion.com/embed/video/' + dmMatch[2]).attr('width', '640').attr('height', '360'); } else if (youkuMatch && youkuMatch[1].length) { $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('height', '498').attr('width', '510').attr('src', '//player.youku.com/embed/' + youkuMatch[1]); } else if (peerTubeMatch && peerTubeMatch[0].length) { var begin = 0; if (peerTubeMatch[2] !== 'undefined') begin = peerTubeMatch[2]; var end = 0; if (peerTubeMatch[3] !== 'undefined') end = peerTubeMatch[3]; var loop = 0; if (peerTubeMatch[4] !== 'undefined') loop = peerTubeMatch[4]; var autoplay = 0; if (peerTubeMatch[5] !== 'undefined') autoplay = peerTubeMatch[5]; var muted = 0; if (peerTubeMatch[6] !== 'undefined') muted = peerTubeMatch[6]; $video = external_jQuery_default()('<iframe allowfullscreen sandbox="allow-same-origin allow-scripts allow-popups">').attr('frameborder', 0).attr('src', '//' + peerTubeMatch[1] + '/videos/embed/' + peerTubeMatch[2] + "?loop=" + loop + "&autoplay=" + autoplay + "&muted=" + muted + (begin > 0 ? '&start=' + begin : '') + (end > 0 ? '&end=' + start : '')).attr('width', '560').attr('height', '315'); } else if (qqMatch && qqMatch[1].length || qqMatch2 && qqMatch2[2].length) { var vid = qqMatch && qqMatch[1].length ? qqMatch[1] : qqMatch2[2]; $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('height', '310').attr('width', '500').attr('src', 'https://v.qq.com/txp/iframe/player.html?vid=' + vid + '&amp;auto=0'); } else if (mp4Match || oggMatch || webmMatch) { $video = external_jQuery_default()('<video controls>').attr('src', url).attr('width', '640').attr('height', '360'); } else if (fbMatch && fbMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://www.facebook.com/plugins/video.php?href=' + encodeURIComponent(fbMatch[0]) + '&show_text=0&width=560').attr('width', '560').attr('height', '301').attr('scrolling', 'no').attr('allowtransparency', 'true'); } else { // this is not a known video link. Now what, Cat? Now what? return false; } $video.addClass('note-video-clip'); return $video[0]; } }, { key: "show", value: function show() { var _this = this; var text = this.context.invoke('editor.getSelectedText'); this.context.invoke('editor.saveRange'); this.showVideoDialog(text).then(function (url) { // [workaround] hide dialog before restore range for IE range focus _this.ui.hideDialog(_this.$dialog); _this.context.invoke('editor.restoreRange'); // build node var $node = _this.createVideoNode(url); if ($node) { // insert video node _this.context.invoke('editor.insertNode', $node); } }).fail(function () { _this.context.invoke('editor.restoreRange'); }); } /** * show video dialog * * @param {jQuery} $dialog * @return {Promise} */ }, { key: "showVideoDialog", value: function showVideoDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { var $videoUrl = _this2.$dialog.find('.note-video-url'); var $videoBtn = _this2.$dialog.find('.note-video-btn'); _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); $videoUrl.on('input paste propertychange', function () { _this2.ui.toggleBtn($videoBtn, $videoUrl.val()); }); if (!env.isSupportTouch) { $videoUrl.trigger('focus'); } $videoBtn.click(function (event) { event.preventDefault(); deferred.resolve($videoUrl.val()); }); _this2.bindEnterKey($videoUrl, $videoBtn); }); _this2.ui.onDialogHidden(_this2.$dialog, function () { $videoUrl.off(); $videoBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this2.ui.showDialog(_this2.$dialog); }); } }]); return VideoDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/HelpDialog.js function HelpDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function HelpDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function HelpDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) HelpDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) HelpDialog_defineProperties(Constructor, staticProps); return Constructor; } var HelpDialog = /*#__PURE__*/function () { function HelpDialog(context) { HelpDialog_classCallCheck(this, HelpDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } HelpDialog_createClass(HelpDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<p class="text-center">', '<a href="http://summernote.org/" target="_blank" rel="noopener noreferrer">Summernote 0.8.20</a> · ', '<a href="https://github.com/summernote/summernote" target="_blank" rel="noopener noreferrer">Project</a> · ', '<a href="https://github.com/summernote/summernote/issues" target="_blank" rel="noopener noreferrer">Issues</a>', '</p>'].join(''); this.$dialog = this.ui.dialog({ title: this.lang.options.help, fade: this.options.dialogsFade, body: this.createShortcutList(), footer: body, callback: function callback($node) { $node.find('.modal-body,.note-modal-body').css({ 'max-height': 300, 'overflow': 'scroll' }); } }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "createShortcutList", value: function createShortcutList() { var _this = this; var keyMap = this.options.keyMap[env.isMac ? 'mac' : 'pc']; return Object.keys(keyMap).map(function (key) { var command = keyMap[key]; var $row = external_jQuery_default()('<div><div class="help-list-item"></div></div>'); $row.append(external_jQuery_default()('<label><kbd>' + key + '</kdb></label>').css({ 'width': 180, 'margin-right': 10 })).append(external_jQuery_default()('<span></span>').html(_this.context.memo('help.' + command) || command)); return $row.html(); }).join(''); } /** * show help dialog * * @return {Promise} */ }, { key: "showHelpDialog", value: function showHelpDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); deferred.resolve(); }); _this2.ui.showDialog(_this2.$dialog); }).promise(); } }, { key: "show", value: function show() { var _this3 = this; this.context.invoke('editor.saveRange'); this.showHelpDialog().then(function () { _this3.context.invoke('editor.restoreRange'); }); } }]); return HelpDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/AirPopover.js function AirPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AirPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AirPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) AirPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) AirPopover_defineProperties(Constructor, staticProps); return Constructor; } var AIRMODE_POPOVER_X_OFFSET = -5; var AIRMODE_POPOVER_Y_OFFSET = 5; var AirPopover = /*#__PURE__*/function () { function AirPopover(context) { var _this = this; AirPopover_classCallCheck(this, AirPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.hidable = true; this.onContextmenu = false; this.pageX = null; this.pageY = null; this.events = { 'summernote.contextmenu': function summernoteContextmenu(e) { if (_this.options.editing) { e.preventDefault(); e.stopPropagation(); _this.onContextmenu = true; _this.update(true); } }, 'summernote.mousedown': function summernoteMousedown(we, e) { _this.pageX = e.pageX; _this.pageY = e.pageY; }, 'summernote.keyup summernote.mouseup summernote.scroll': function summernoteKeyupSummernoteMouseupSummernoteScroll(we, e) { if (_this.options.editing && !_this.onContextmenu) { _this.pageX = e.pageX; _this.pageY = e.pageY; _this.update(); } _this.onContextmenu = false; }, 'summernote.disable summernote.change summernote.dialog.shown summernote.blur': function summernoteDisableSummernoteChangeSummernoteDialogShownSummernoteBlur() { _this.hide(); }, 'summernote.focusout': function summernoteFocusout() { if (!_this.$popover.is(':active,:focus')) { _this.hide(); } } }; } AirPopover_createClass(AirPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return this.options.airMode && !lists.isEmpty(this.options.popover.air); } }, { key: "initialize", value: function initialize() { var _this2 = this; this.$popover = this.ui.popover({ className: 'note-air-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.air); // disable hiding this popover preemptively by 'summernote.blur' event. this.$popover.on('mousedown', function () { _this2.hidable = false; }); // (re-)enable hiding after 'summernote.blur' has been handled (aka. ignored). this.$popover.on('mouseup', function () { _this2.hidable = true; }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(forcelyOpen) { var styleInfo = this.context.invoke('editor.currentStyle'); if (styleInfo.range && (!styleInfo.range.isCollapsed() || forcelyOpen)) { var rect = { left: this.pageX, top: this.pageY }; var containerOffset = external_jQuery_default()(this.options.container).offset(); rect.top -= containerOffset.top; rect.left -= containerOffset.left; this.$popover.css({ display: 'block', left: Math.max(rect.left, 0) + AIRMODE_POPOVER_X_OFFSET, top: rect.top + AIRMODE_POPOVER_Y_OFFSET }); this.context.invoke('buttons.updateCurrentStyle', this.$popover); } else { this.hide(); } } }, { key: "updateCodeview", value: function updateCodeview(isCodeview) { this.ui.toggleBtnActive(this.$popover.find('.btn-codeview'), isCodeview); if (isCodeview) { this.hide(); } } }, { key: "hide", value: function hide() { if (this.hidable) { this.$popover.hide(); } } }]); return AirPopover; }(); ;// CONCATENATED MODULE: ./src/js/module/HintPopover.js function HintPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function HintPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function HintPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) HintPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) HintPopover_defineProperties(Constructor, staticProps); return Constructor; } var POPOVER_DIST = 5; var HintPopover = /*#__PURE__*/function () { function HintPopover(context) { var _this = this; HintPopover_classCallCheck(this, HintPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$editable = context.layoutInfo.editable; this.options = context.options; this.hint = this.options.hint || []; this.direction = this.options.hintDirection || 'bottom'; this.hints = Array.isArray(this.hint) ? this.hint : [this.hint]; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); }, 'summernote.disable summernote.dialog.shown summernote.blur': function summernoteDisableSummernoteDialogShownSummernoteBlur() { _this.hide(); } }; } HintPopover_createClass(HintPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return this.hints.length > 0; } }, { key: "initialize", value: function initialize() { var _this2 = this; this.lastWordRange = null; this.matchingWord = null; this.$popover = this.ui.popover({ className: 'note-hint-popover', hideArrow: true, direction: '' }).render().appendTo(this.options.container); this.$popover.hide(); this.$content = this.$popover.find('.popover-content,.note-popover-content'); this.$content.on('click', '.note-hint-item', function (e) { _this2.$content.find('.active').removeClass('active'); external_jQuery_default()(e.currentTarget).addClass('active'); _this2.replace(); }); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "selectItem", value: function selectItem($item) { this.$content.find('.active').removeClass('active'); $item.addClass('active'); this.$content[0].scrollTop = $item[0].offsetTop - this.$content.innerHeight() / 2; } }, { key: "moveDown", value: function moveDown() { var $current = this.$content.find('.note-hint-item.active'); var $next = $current.next(); if ($next.length) { this.selectItem($next); } else { var $nextGroup = $current.parent().next(); if (!$nextGroup.length) { $nextGroup = this.$content.find('.note-hint-group').first(); } this.selectItem($nextGroup.find('.note-hint-item').first()); } } }, { key: "moveUp", value: function moveUp() { var $current = this.$content.find('.note-hint-item.active'); var $prev = $current.prev(); if ($prev.length) { this.selectItem($prev); } else { var $prevGroup = $current.parent().prev(); if (!$prevGroup.length) { $prevGroup = this.$content.find('.note-hint-group').last(); } this.selectItem($prevGroup.find('.note-hint-item').last()); } } }, { key: "replace", value: function replace() { var $item = this.$content.find('.note-hint-item.active'); if ($item.length) { var node = this.nodeFromItem($item); // If matchingWord length = 0 -> capture OK / open hint / but as mention capture "" (\w*) if (this.matchingWord !== null && this.matchingWord.length === 0) { this.lastWordRange.so = this.lastWordRange.eo; // Else si > 0 and normal case -> adjust range "before" for correct position of insertion } else if (this.matchingWord !== null && this.matchingWord.length > 0 && !this.lastWordRange.isCollapsed()) { var rangeCompute = this.lastWordRange.eo - this.lastWordRange.so - this.matchingWord.length; if (rangeCompute > 0) { this.lastWordRange.so += rangeCompute; } } this.lastWordRange.insertNode(node); if (this.options.hintSelect === 'next') { var blank = document.createTextNode(''); external_jQuery_default()(node).after(blank); range.createFromNodeBefore(blank).select(); } else { range.createFromNodeAfter(node).select(); } this.lastWordRange = null; this.hide(); this.context.invoke('editor.focus'); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } } }, { key: "nodeFromItem", value: function nodeFromItem($item) { var hint = this.hints[$item.data('index')]; var item = $item.data('item'); var node = hint.content ? hint.content(item) : item; if (typeof node === 'string') { node = dom.createText(node); } return node; } }, { key: "createItemTemplates", value: function createItemTemplates(hintIdx, items) { var hint = this.hints[hintIdx]; return items.map(function (item /*, idx */ ) { var $item = external_jQuery_default()('<div class="note-hint-item"></div>'); $item.append(hint.template ? hint.template(item) : item + ''); $item.data({ 'index': hintIdx, 'item': item }); return $item; }); } }, { key: "handleKeydown", value: function handleKeydown(e) { if (!this.$popover.is(':visible')) { return; } if (e.keyCode === key.code.ENTER) { e.preventDefault(); this.replace(); } else if (e.keyCode === key.code.UP) { e.preventDefault(); this.moveUp(); } else if (e.keyCode === key.code.DOWN) { e.preventDefault(); this.moveDown(); } } }, { key: "searchKeyword", value: function searchKeyword(index, keyword, callback) { var hint = this.hints[index]; if (hint && hint.match.test(keyword) && hint.search) { var matches = hint.match.exec(keyword); this.matchingWord = matches[0]; hint.search(matches[1], callback); } else { callback(); } } }, { key: "createGroup", value: function createGroup(idx, keyword) { var _this3 = this; var $group = external_jQuery_default()('<div class="note-hint-group note-hint-group-' + idx + '"></div>'); this.searchKeyword(idx, keyword, function (items) { items = items || []; if (items.length) { $group.html(_this3.createItemTemplates(idx, items)); _this3.show(); } }); return $group; } }, { key: "handleKeyup", value: function handleKeyup(e) { var _this4 = this; if (!lists.contains([key.code.ENTER, key.code.UP, key.code.DOWN], e.keyCode)) { var _range = this.context.invoke('editor.getLastRange'); var wordRange, keyword; if (this.options.hintMode === 'words') { wordRange = _range.getWordsRange(_range); keyword = wordRange.toString(); this.hints.forEach(function (hint) { if (hint.match.test(keyword)) { wordRange = _range.getWordsMatchRange(hint.match); return false; } }); if (!wordRange) { this.hide(); return; } keyword = wordRange.toString(); } else { wordRange = _range.getWordRange(); keyword = wordRange.toString(); } if (this.hints.length && keyword) { this.$content.empty(); var bnd = func.rect2bnd(lists.last(wordRange.getClientRects())); var containerOffset = external_jQuery_default()(this.options.container).offset(); if (bnd) { bnd.top -= containerOffset.top; bnd.left -= containerOffset.left; this.$popover.hide(); this.lastWordRange = wordRange; this.hints.forEach(function (hint, idx) { if (hint.match.test(keyword)) { _this4.createGroup(idx, keyword).appendTo(_this4.$content); } }); // select first .note-hint-item this.$content.find('.note-hint-item:first').addClass('active'); // set position for popover after group is created if (this.direction === 'top') { this.$popover.css({ left: bnd.left, top: bnd.top - this.$popover.outerHeight() - POPOVER_DIST }); } else { this.$popover.css({ left: bnd.left, top: bnd.top + bnd.height + POPOVER_DIST }); } } } else { this.hide(); } } } }, { key: "show", value: function show() { this.$popover.show(); } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return HintPopover; }(); ;// CONCATENATED MODULE: ./src/js/settings.js (external_jQuery_default()).summernote = external_jQuery_default().extend((external_jQuery_default()).summernote, { version: '0.8.20', plugins: {}, dom: dom, range: range, lists: lists, options: { langInfo: (external_jQuery_default()).summernote.lang["en-US"], editing: true, modules: { 'editor': Editor, 'clipboard': Clipboard, 'dropzone': Dropzone, 'codeview': CodeView, 'statusbar': Statusbar, 'fullscreen': Fullscreen, 'handle': Handle, // FIXME: HintPopover must be front of autolink // - Script error about range when Enter key is pressed on hint popover 'hintPopover': HintPopover, 'autoLink': AutoLink, 'autoSync': AutoSync, 'autoReplace': AutoReplace, 'placeholder': Placeholder, 'buttons': Buttons, 'toolbar': Toolbar, 'linkDialog': LinkDialog, 'linkPopover': LinkPopover, 'imageDialog': ImageDialog, 'imagePopover': ImagePopover, 'tablePopover': TablePopover, 'videoDialog': VideoDialog, 'helpDialog': HelpDialog, 'airPopover': AirPopover }, buttons: {}, lang: 'en-US', followingToolbar: false, toolbarPosition: 'top', otherStaticBar: '', // toolbar codeviewKeepButton: false, toolbar: [['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['fontname', ['fontname']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture', 'video']], ['view', ['fullscreen', 'codeview', 'help']]], // popover popatmouse: true, popover: { image: [['resize', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']], ['float', ['floatLeft', 'floatRight', 'floatNone']], ['remove', ['removeMedia']]], link: [['link', ['linkDialogShow', 'unlink']]], table: [['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']], ['delete', ['deleteRow', 'deleteCol', 'deleteTable']]], air: [['color', ['color']], ['font', ['bold', 'underline', 'clear']], ['para', ['ul', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture']], ['view', ['fullscreen', 'codeview']]] }, // air mode: inline editor airMode: false, overrideContextMenu: false, // TBD width: null, height: null, linkTargetBlank: true, useProtocol: true, defaultProtocol: 'http://', focus: false, tabDisabled: false, tabSize: 4, styleWithCSS: false, shortcuts: true, textareaAutoSync: true, tooltip: 'auto', container: null, maxTextLength: 0, blockquoteBreakingLevel: 2, spellCheck: true, disableGrammar: false, placeholder: null, inheritPlaceholder: false, // TODO: need to be documented recordEveryKeystroke: false, historyLimit: 200, // TODO: need to be documented showDomainOnlyForAutolink: false, // TODO: need to be documented hintMode: 'word', hintSelect: 'after', hintDirection: 'bottom', styleTags: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'], fontNames: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande', 'Tahoma', 'Times New Roman', 'Verdana'], fontNamesIgnoreCheck: [], addDefaultFonts: true, fontSizes: ['8', '9', '10', '11', '12', '14', '18', '24', '36'], fontSizeUnits: ['px', 'pt'], // pallete colors(n x n) colors: [['#000000', '#424242', '#636363', '#9C9C94', '#CEC6CE', '#EFEFEF', '#F7F7F7', '#FFFFFF'], ['#FF0000', '#FF9C00', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#9C00FF', '#FF00FF'], ['#F7C6CE', '#FFE7CE', '#FFEFC6', '#D6EFD6', '#CEDEE7', '#CEE7F7', '#D6D6E7', '#E7D6DE'], ['#E79C9C', '#FFC69C', '#FFE79C', '#B5D6A5', '#A5C6CE', '#9CC6EF', '#B5A5D6', '#D6A5BD'], ['#E76363', '#F7AD6B', '#FFD663', '#94BD7B', '#73A5AD', '#6BADDE', '#8C7BC6', '#C67BA5'], ['#CE0000', '#E79439', '#EFC631', '#6BA54A', '#4A7B8C', '#3984C6', '#634AA5', '#A54A7B'], ['#9C0000', '#B56308', '#BD9400', '#397B21', '#104A5A', '#085294', '#311873', '#731842'], ['#630000', '#7B3900', '#846300', '#295218', '#083139', '#003163', '#21104A', '#4A1031']], // http://chir.ag/projects/name-that-color/ colorsName: [['Black', 'Tundora', 'Dove Gray', 'Star Dust', 'Pale Slate', 'Gallery', 'Alabaster', 'White'], ['Red', 'Orange Peel', 'Yellow', 'Green', 'Cyan', 'Blue', 'Electric Violet', 'Magenta'], ['Azalea', 'Karry', 'Egg White', 'Zanah', 'Botticelli', 'Tropical Blue', 'Mischka', 'Twilight'], ['Tonys Pink', 'Peach Orange', 'Cream Brulee', 'Sprout', 'Casper', 'Perano', 'Cold Purple', 'Careys Pink'], ['Mandy', 'Rajah', 'Dandelion', 'Olivine', 'Gulf Stream', 'Viking', 'Blue Marguerite', 'Puce'], ['Guardsman Red', 'Fire Bush', 'Golden Dream', 'Chelsea Cucumber', 'Smalt Blue', 'Boston Blue', 'Butterfly Bush', 'Cadillac'], ['Sangria', 'Mai Tai', 'Buddha Gold', 'Forest Green', 'Eden', 'Venice Blue', 'Meteorite', 'Claret'], ['Rosewood', 'Cinnamon', 'Olive', 'Parsley', 'Tiber', 'Midnight Blue', 'Valentino', 'Loulou']], colorButton: { foreColor: '#000000', backColor: '#FFFF00' }, lineHeights: ['1.0', '1.2', '1.4', '1.5', '1.6', '1.8', '2.0', '3.0'], tableClassName: 'table table-bordered', insertTableMaxSize: { col: 10, row: 10 }, // By default, dialogs are attached in container. dialogsInBody: false, dialogsFade: false, maximumImageFileSize: null, acceptImageFileTypes: "image/*", callbacks: { onBeforeCommand: null, onBlur: null, onBlurCodeview: null, onChange: null, onChangeCodeview: null, onDialogShown: null, onEnter: null, onFocus: null, onImageLinkInsert: null, onImageUpload: null, onImageUploadError: null, onInit: null, onKeydown: null, onKeyup: null, onMousedown: null, onMouseup: null, onPaste: null, onScroll: null }, codemirror: { mode: 'text/html', htmlMode: true, lineNumbers: true }, codeviewFilter: true, codeviewFilterRegex: /<\/*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|ilayer|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|t(?:itle|extarea)|xml)[^>]*?>/gi, codeviewIframeFilter: true, codeviewIframeWhitelistSrc: [], codeviewIframeWhitelistSrcBase: ['www.youtube.com', 'www.youtube-nocookie.com', 'www.facebook.com', 'vine.co', 'instagram.com', 'player.vimeo.com', 'www.dailymotion.com', 'player.youku.com', 'jumpingbean.tv', 'v.qq.com'], keyMap: { pc: { 'ESC': 'escape', 'ENTER': 'insertParagraph', 'CTRL+Z': 'undo', 'CTRL+Y': 'redo', 'TAB': 'tab', 'SHIFT+TAB': 'untab', 'CTRL+B': 'bold', 'CTRL+I': 'italic', 'CTRL+U': 'underline', 'CTRL+SHIFT+S': 'strikethrough', 'CTRL+BACKSLASH': 'removeFormat', 'CTRL+SHIFT+L': 'justifyLeft', 'CTRL+SHIFT+E': 'justifyCenter', 'CTRL+SHIFT+R': 'justifyRight', 'CTRL+SHIFT+J': 'justifyFull', 'CTRL+SHIFT+NUM7': 'insertUnorderedList', 'CTRL+SHIFT+NUM8': 'insertOrderedList', 'CTRL+LEFTBRACKET': 'outdent', 'CTRL+RIGHTBRACKET': 'indent', 'CTRL+NUM0': 'formatPara', 'CTRL+NUM1': 'formatH1', 'CTRL+NUM2': 'formatH2', 'CTRL+NUM3': 'formatH3', 'CTRL+NUM4': 'formatH4', 'CTRL+NUM5': 'formatH5', 'CTRL+NUM6': 'formatH6', 'CTRL+ENTER': 'insertHorizontalRule', 'CTRL+K': 'linkDialog.show' }, mac: { 'ESC': 'escape', 'ENTER': 'insertParagraph', 'CMD+Z': 'undo', 'CMD+SHIFT+Z': 'redo', 'TAB': 'tab', 'SHIFT+TAB': 'untab', 'CMD+B': 'bold', 'CMD+I': 'italic', 'CMD+U': 'underline', 'CMD+SHIFT+S': 'strikethrough', 'CMD+BACKSLASH': 'removeFormat', 'CMD+SHIFT+L': 'justifyLeft', 'CMD+SHIFT+E': 'justifyCenter', 'CMD+SHIFT+R': 'justifyRight', 'CMD+SHIFT+J': 'justifyFull', 'CMD+SHIFT+NUM7': 'insertUnorderedList', 'CMD+SHIFT+NUM8': 'insertOrderedList', 'CMD+LEFTBRACKET': 'outdent', 'CMD+RIGHTBRACKET': 'indent', 'CMD+NUM0': 'formatPara', 'CMD+NUM1': 'formatH1', 'CMD+NUM2': 'formatH2', 'CMD+NUM3': 'formatH3', 'CMD+NUM4': 'formatH4', 'CMD+NUM5': 'formatH5', 'CMD+NUM6': 'formatH6', 'CMD+ENTER': 'insertHorizontalRule', 'CMD+K': 'linkDialog.show' } }, icons: { 'align': 'note-icon-align', 'alignCenter': 'note-icon-align-center', 'alignJustify': 'note-icon-align-justify', 'alignLeft': 'note-icon-align-left', 'alignRight': 'note-icon-align-right', 'rowBelow': 'note-icon-row-below', 'colBefore': 'note-icon-col-before', 'colAfter': 'note-icon-col-after', 'rowAbove': 'note-icon-row-above', 'rowRemove': 'note-icon-row-remove', 'colRemove': 'note-icon-col-remove', 'indent': 'note-icon-align-indent', 'outdent': 'note-icon-align-outdent', 'arrowsAlt': 'note-icon-arrows-alt', 'bold': 'note-icon-bold', 'caret': 'note-icon-caret', 'circle': 'note-icon-circle', 'close': 'note-icon-close', 'code': 'note-icon-code', 'eraser': 'note-icon-eraser', 'floatLeft': 'note-icon-float-left', 'floatRight': 'note-icon-float-right', 'font': 'note-icon-font', 'frame': 'note-icon-frame', 'italic': 'note-icon-italic', 'link': 'note-icon-link', 'unlink': 'note-icon-chain-broken', 'magic': 'note-icon-magic', 'menuCheck': 'note-icon-menu-check', 'minus': 'note-icon-minus', 'orderedlist': 'note-icon-orderedlist', 'pencil': 'note-icon-pencil', 'picture': 'note-icon-picture', 'question': 'note-icon-question', 'redo': 'note-icon-redo', 'rollback': 'note-icon-rollback', 'square': 'note-icon-square', 'strikethrough': 'note-icon-strikethrough', 'subscript': 'note-icon-subscript', 'superscript': 'note-icon-superscript', 'table': 'note-icon-table', 'textHeight': 'note-icon-text-height', 'trash': 'note-icon-trash', 'underline': 'note-icon-underline', 'undo': 'note-icon-undo', 'unorderedlist': 'note-icon-unorderedlist', 'video': 'note-icon-video' } } }); ;// CONCATENATED MODULE: ./src/js/renderer.js function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function renderer_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function renderer_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function renderer_createClass(Constructor, protoProps, staticProps) { if (protoProps) renderer_defineProperties(Constructor.prototype, protoProps); if (staticProps) renderer_defineProperties(Constructor, staticProps); return Constructor; } var Renderer = /*#__PURE__*/function () { function Renderer(markup, children, options, callback) { renderer_classCallCheck(this, Renderer); this.markup = markup; this.children = children; this.options = options; this.callback = callback; } renderer_createClass(Renderer, [{ key: "render", value: function render($parent) { var $node = external_jQuery_default()(this.markup); if (this.options && this.options.contents) { $node.html(this.options.contents); } if (this.options && this.options.className) { $node.addClass(this.options.className); } if (this.options && this.options.data) { external_jQuery_default().each(this.options.data, function (k, v) { $node.attr('data-' + k, v); }); } if (this.options && this.options.click) { $node.on('click', this.options.click); } if (this.children) { var $container = $node.find('.note-children-container'); this.children.forEach(function (child) { child.render($container.length ? $container : $node); }); } if (this.callback) { this.callback($node, this.options); } if (this.options && this.options.callback) { this.options.callback($node); } if ($parent) { $parent.append($node); } return $node; } }]); return Renderer; }(); /* harmony default export */ const renderer = ({ create: function create(markup, callback) { return function () { var options = _typeof(arguments[1]) === 'object' ? arguments[1] : arguments[0]; var children = Array.isArray(arguments[0]) ? arguments[0] : []; if (options && options.children) { children = options.children; } return new Renderer(markup, children, options, callback); }; } }); ;// CONCATENATED MODULE: ./src/styles/bs3/summernote-bs3.js function summernote_bs3_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { summernote_bs3_typeof = function _typeof(obj) { return typeof obj; }; } else { summernote_bs3_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return summernote_bs3_typeof(obj); } var editor = renderer.create('<div class="note-editor note-frame panel panel-default"></div>'); var toolbar = renderer.create('<div class="panel-heading note-toolbar" role="toolbar"></div>'); var editingArea = renderer.create('<div class="note-editing-area"></div>'); var codable = renderer.create('<textarea class="note-codable" aria-multiline="true"></textarea>'); var editable = renderer.create('<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>'); var statusbar = renderer.create(['<output class="note-status-output" role="status" aria-live="polite"></output>', '<div class="note-statusbar" role="status">', '<div class="note-resizebar" aria-label="Resize">', '<div class="note-icon-bar"></div>', '<div class="note-icon-bar"></div>', '<div class="note-icon-bar"></div>', '</div>', '</div>'].join('')); var airEditor = renderer.create('<div class="note-editor note-airframe"></div>'); var airEditable = renderer.create(['<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>', '<output class="note-status-output" role="status" aria-live="polite"></output>'].join('')); var buttonGroup = renderer.create('<div class="note-btn-group btn-group"></div>'); var dropdown = renderer.create('<ul class="note-dropdown-menu dropdown-menu"></ul>', function ($node, options) { var markup = Array.isArray(options.items) ? options.items.map(function (item) { var value = typeof item === 'string' ? item : item.value || ''; var content = options.template ? options.template(item) : item; var option = summernote_bs3_typeof(item) === 'object' ? item.option : undefined; var dataValue = 'data-value="' + value + '"'; var dataOption = option !== undefined ? ' data-option="' + option + '"' : ''; return '<li aria-label="' + value + '"><a href="#" ' + (dataValue + dataOption) + '>' + content + '</a></li>'; }).join('') : options.items; $node.html(markup).attr({ 'aria-label': options.title }); if (options && options.codeviewKeepButton) { $node.addClass('note-codeview-keep'); } }); var dropdownButtonContents = function dropdownButtonContents(contents, options) { return contents + ' ' + icon(options.icons.caret, 'span'); }; var dropdownCheck = renderer.create('<ul class="note-dropdown-menu dropdown-menu note-check"></ul>', function ($node, options) { var markup = Array.isArray(options.items) ? options.items.map(function (item) { var value = typeof item === 'string' ? item : item.value || ''; var content = options.template ? options.template(item) : item; return '<li aria-label="' + item + '"><a href="#" data-value="' + value + '">' + icon(options.checkClassName) + ' ' + content + '</a></li>'; }).join('') : options.items; $node.html(markup).attr({ 'aria-label': options.title }); if (options && options.codeviewKeepButton) { $node.addClass('note-codeview-keep'); } }); var dialog = renderer.create('<div class="modal note-modal" aria-hidden="false" tabindex="-1" role="dialog"></div>', function ($node, options) { if (options.fade) { $node.addClass('fade'); } $node.attr({ 'aria-label': options.title }); $node.html(['<div class="modal-dialog">', '<div class="modal-content">', options.title ? '<div class="modal-header">' + '<button type="button" class="close" data-dismiss="modal" aria-label="Close" aria-hidden="true">&times;</button>' + '<h4 class="modal-title">' + options.title + '</h4>' + '</div>' : '', '<div class="modal-body">' + options.body + '</div>', options.footer ? '<div class="modal-footer">' + options.footer + '</div>' : '', '</div>', '</div>'].join('')); }); var popover = renderer.create(['<div class="note-popover popover in">', '<div class="arrow"></div>', '<div class="popover-content note-children-container"></div>', '</div>'].join(''), function ($node, options) { var direction = typeof options.direction !== 'undefined' ? options.direction : 'bottom'; $node.addClass(direction); if (options.hideArrow) { $node.find('.arrow').hide(); } }); var summernote_bs3_checkbox = renderer.create('<div class="checkbox"></div>', function ($node, options) { $node.html(['<label' + (options.id ? ' for="note-' + options.id + '"' : '') + '>', '<input type="checkbox"' + (options.id ? ' id="note-' + options.id + '"' : ''), options.checked ? ' checked' : '', ' aria-checked="' + (options.checked ? 'true' : 'false') + '"/>', options.text ? options.text : '', '</label>'].join('')); }); var icon = function icon(iconClassName, tagName) { if (iconClassName.match(/^</)) { return iconClassName; } tagName = tagName || 'i'; return '<' + tagName + ' class="' + iconClassName + '"></' + tagName + '>'; }; var ui = function ui(editorOptions) { return { editor: editor, toolbar: toolbar, editingArea: editingArea, codable: codable, editable: editable, statusbar: statusbar, airEditor: airEditor, airEditable: airEditable, buttonGroup: buttonGroup, dropdown: dropdown, dropdownButtonContents: dropdownButtonContents, dropdownCheck: dropdownCheck, dialog: dialog, popover: popover, checkbox: summernote_bs3_checkbox, icon: icon, options: editorOptions, palette: function palette($node, options) { return renderer.create('<div class="note-color-palette"></div>', function ($node, options) { var contents = []; for (var row = 0, rowSize = options.colors.length; row < rowSize; row++) { var eventName = options.eventName; var colors = options.colors[row]; var colorsName = options.colorsName[row]; var buttons = []; for (var col = 0, colSize = colors.length; col < colSize; col++) { var color = colors[col]; var colorName = colorsName[col]; buttons.push(['<button type="button" class="note-color-btn"', 'style="background-color:', color, '" ', 'data-event="', eventName, '" ', 'data-value="', color, '" ', 'title="', colorName, '" ', 'aria-label="', colorName, '" ', 'data-toggle="button" tabindex="-1"></button>'].join('')); } contents.push('<div class="note-color-row">' + buttons.join('') + '</div>'); } $node.html(contents.join('')); if (options.tooltip) { $node.find('.note-color-btn').tooltip({ container: options.container || editorOptions.container, trigger: 'hover', placement: 'bottom' }); } })($node, options); }, button: function button($node, options) { return renderer.create('<button type="button" class="note-btn btn btn-default btn-sm" tabindex="-1"></button>', function ($node, options) { if (options && options.tooltip) { $node.attr({ title: options.tooltip, 'aria-label': options.tooltip }).tooltip({ container: options.container || editorOptions.container, trigger: 'hover', placement: 'bottom' }).on('click', function (e) { external_jQuery_default()(e.currentTarget).tooltip('hide'); }); } if (options && options.codeviewButton) { $node.addClass('note-codeview-keep'); } })($node, options); }, toggleBtn: function toggleBtn($btn, isEnable) { $btn.toggleClass('disabled', !isEnable); $btn.attr('disabled', !isEnable); }, toggleBtnActive: function toggleBtnActive($btn, isActive) { $btn.toggleClass('active', isActive); }, onDialogShown: function onDialogShown($dialog, handler) { $dialog.one('shown.bs.modal', handler); }, onDialogHidden: function onDialogHidden($dialog, handler) { $dialog.one('hidden.bs.modal', handler); }, showDialog: function showDialog($dialog) { $dialog.modal('show'); }, hideDialog: function hideDialog($dialog) { $dialog.modal('hide'); }, createLayout: function createLayout($note) { var $editor = (editorOptions.airMode ? airEditor([editingArea([codable(), airEditable()])]) : editorOptions.toolbarPosition === 'bottom' ? editor([editingArea([codable(), editable()]), toolbar(), statusbar()]) : editor([toolbar(), editingArea([codable(), editable()]), statusbar()])).render(); $editor.insertAfter($note); return { note: $note, editor: $editor, toolbar: $editor.find('.note-toolbar'), editingArea: $editor.find('.note-editing-area'), editable: $editor.find('.note-editable'), codable: $editor.find('.note-codable'), statusbar: $editor.find('.note-statusbar') }; }, removeLayout: function removeLayout($note, layoutInfo) { $note.html(layoutInfo.editable.html()); layoutInfo.editor.remove(); $note.show(); } }; }; (external_jQuery_default()).summernote = external_jQuery_default().extend((external_jQuery_default()).summernote, { ui_template: ui, "interface": 'bs3' }); })(); /******/ return __webpack_exports__; /******/ })() ; }); //# sourceMappingURL=summernote.js.map
281677160/openwrt-package
1,425
luci-app-pppoe-server/luasrc/model/cbi/pppoe-server/online.lua
local o = require "luci.dispatcher" local fs = require "nixio.fs" local jsonc = require "luci.jsonc" local sessions = {} local session_path = "/var/etc/pppoe-server/session" if fs.access(session_path) then for filename in fs.dir(session_path) do local session_file = session_path .. "/" .. filename local file = io.open(session_file, "r") local t = jsonc.parse(file:read("*a")) if t then t.session_file = session_file sessions[#sessions + 1] = t end file:close() end end f = SimpleForm("processes", translate("PPPoE Server"), translate("The PPPoE server is a broadband access authentication server that prevents ARP spoofing.")) f.reset = false f.submit = false t = f:section(Table, sessions, translate("Online Users")) t:option(DummyValue, "username", translate("Username")) t:option(DummyValue, "interface", translate("Interface")) t:option(DummyValue, "ip", translate("Client IP")) t:option(DummyValue, "mac", translate("MAC address")) t:option(DummyValue, "login_time", translate("Login Time")) _kill = t:option(Button, "_kill", translate("Forced offline")) _kill.inputstyle = "reset" function _kill.write(t, s) luci.util.execi("rm -f " .. t.map:get(s, "session_file")) null, t.tag_error[t] = luci.sys.process.signal(t.map:get(s, "pid"), 9) luci.http.redirect(o.build_url("admin/services/pppoe-server/online")) end return f
294coder/Efficient-MIF
20,750
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/bfgs/rlbfgs.m
function [x, cost, info, options] = rlbfgs(problem, x0, options) % Riemannian limited memory BFGS solver for smooth objective functions. % % function [x, cost, info, options] = rlbfgs(problem) % function [x, cost, info, options] = rlbfgs(problem, x0) % function [x, cost, info, options] = rlbfgs(problem, x0, options) % function [x, cost, info, options] = rlbfgs(problem, [], options) % % % This is a Riemannian limited memory BFGS solver (quasi-Newton method), % which aims to minimize the cost function in the given problem structure. % It requires access to the gradient of the cost function. % % Parameter options.memory can be used to specify the number of iterations % the algorithm remembers and uses to approximate the inverse Hessian of % the cost. Default value is 30. % For unlimited memory, set options.memory = Inf. % % % For a description of the algorithm and theorems offering convergence % guarantees, see the references below. % % The initial iterate is x0 if it is provided. Otherwise, a random point on % the manifold is picked. To specify options whilst not specifying an % initial iterate, give x0 as [] (the empty matrix). % % The two outputs 'x' and 'cost' are the last reached point on the manifold % and its cost. % % The output 'info' is a struct-array which contains information about the % iterations: % iter (integer) % The iteration number. The initial guess is 0. % cost (double) % The corresponding cost value. % gradnorm (double) % The (Riemannian) norm of the gradient. % time (double) % The total elapsed time in seconds to reach the corresponding cost. % stepsize (double) % The size of the step from the previous to the new iterate. % accepted (Boolean) % true if step is accepted in the cautious update. 0 otherwise. % And possibly additional information logged by options.statsfun. % For example, type [info.gradnorm] to obtain a vector of the successive % gradient norms reached at each iteration. % % The options structure is used to overwrite the default values. All % options have a default value and are hence optional. To force an option % value, pass an options structure with a field options.optionname, where % optionname is one of the following and the default value is indicated % between parentheses: % % tolgradnorm (1e-6) % The algorithm terminates if the norm of the gradient drops below % this. For well-scaled problems, a rule of thumb is that you can % expect to reduce the gradient norm by 8 orders of magnitude % (sqrt(eps)) compared to the gradient norm at a "typical" point (a % rough initial iterate for example). Further decrease is sometimes % possible, but inexact floating point arithmetic will eventually % limit the final accuracy. If tolgradnorm is set too low, the % algorithm may end up iterating forever (or at least until another % stopping criterion triggers). % maxiter (1000) % The algorithm terminates if maxiter iterations were executed. % maxtime (Inf) % The algorithm terminates if maxtime seconds elapsed. % minstepsize (1e-10) % The minimum norm of the tangent vector that points from the current % point to the next point. If the norm is less than minstepsize, the % program will terminate. % memory (30) % The number of previous iterations the program remembers. This is used % to approximate the inverse Hessian at the current point. Because of % difficulty of maintaining a representation of operators in terms of % coordinates, a recursive method is used. The number of steps in the % recursion is at most options.memory. This parameter can take any % integer value >= 0, or Inf, which is taken to be options.maxiter. If % options.maxiter has value Inf, then it will take value 10000 and a % warning will be displayed. % linesearch (@linesearch_hint) % Function handle to a line search function. The options structure is % passed to the line search too, so you can pass it parameters. See % each line search's documentation for info. % By default, the intial multiplier tried is alpha = 1. This can be % changed with options.linesearch: see help of linesearch_hint. % strict_inc_func (@(t) t) % The Cautious step needs a real function that has value 0 at t = 0, % and is strictly increasing. See details in Wen Huang's paper % "A Riemannian BFGS Method without Differentiated Retraction for % Nonconvex Optimization Problems" % statsfun (none) % Function handle to a function that will be called after each % iteration to provide the opportunity to log additional statistics. % They will be returned in the info struct. See the generic Manopt % documentation about solvers for further information. statsfun is % called with the point x that was reached last. % stopfun (none) % Function handle to a function that will be called at each iteration % to provide the opportunity to specify additional stopping criteria. % See the generic Manopt documentation about solvers for further % information. % verbosity (2) % Integer number used to tune the amount of output the algorithm % generates during execution (mostly as text in the command window). % The higher, the more output. 0 means silent. 3 and above includes a % display of the options structure at the beginning of the execution. % debug (false) % Set to true to allow the algorithm to perform additional % computations for debugging purposes. If a debugging test fails, you % will be informed of it, usually via the command window. Be aware % that these additional computations appear in the algorithm timings % too, and may interfere with operations such as counting the number % of cost evaluations, etc. (the debug calls get storedb too). % storedepth (30) % Maximum number of different points x of the manifold for which a % store structure will be kept in memory in the storedb. If the % caching features of Manopt are not used, this is irrelevant. If % memory usage is an issue, you may try to lower this number. % Profiling may then help to investigate if a performance hit was % incurred as a result. % % % Please cite the Manopt paper as well as the research paper: % @InBook{Huang2016, % title = {A {R}iemannian {BFGS} Method for Nonconvex Optimization Problems}, % author = {Huang, W. and Absil, P.-A. and Gallivan, K.A.}, % year = {2016}, % publisher = {Springer International Publishing}, % editor = {Karas{\"o}zen, B{\"u}lent and Manguo{\u{g}}lu, Murat and Tezer-Sezgin, M{\"u}nevver and G{\"o}ktepe, Serdar and U{\u{g}}ur, {\"O}m{\"u}r}, % address = {Cham}, % booktitle = {Numerical Mathematics and Advanced Applications ENUMATH 2015}, % pages = {627--634}, % doi = {10.1007/978-3-319-39929-4_60} % } % % This file is part of Manopt: www.manopt.org. % Original author: Changshuo Liu, July 19, 2017. % Contributors: Nicolas Boumal % Change log: % Verify that the problem description is sufficient for the solver. if ~canGetCost(problem) warning('manopt:getCost', ... 'No cost provided. The algorithm will likely abort.'); end if ~canGetGradient(problem) && ~canGetApproxGradient(problem) % Note: we do not give a warning if an approximate gradient is % explicitly given in the problem description, as in that case the user % seems to be aware of the issue. warning('manopt:getGradient:approx', ... ['No gradient provided. Using an FD approximation instead (slow).\n' ... 'It may be necessary to increase options.tolgradnorm.\n' ... 'To disable this warning: warning(''off'', ''manopt:getGradient:approx'')']); problem.approxgrad = approxgradientFD(problem); end % Local defaults for the program localdefaults.minstepsize = 1e-10; localdefaults.maxiter = 1000; localdefaults.tolgradnorm = 1e-6; localdefaults.memory = 30; localdefaults.strict_inc_func = @(t) t; localdefaults.ls_max_steps = 25; localdefaults.storedepth = 30; localdefaults.linesearch = @linesearch_hint; % Merge global and local defaults, then merge w/ user options, if any. localdefaults = mergeOptions(getGlobalDefaults(), localdefaults); if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(localdefaults, options); % To make sure memory in range [0, Inf) options.memory = max(options.memory, 0); if options.memory == Inf if isinf(options.maxiter) options.memory = 10000; warning('rlbfgs:memory', ['options.memory and options.maxiter' ... ' are both Inf; options.memory has been changed to 10000.']); else options.memory = options.maxiter; end end M = problem.M; % Create a random starting point if no starting point is provided. if ~exist('x0', 'var')|| isempty(x0) xCur = M.rand(); else xCur = x0; end timetic = tic(); % Create a store database and get a key for the current x storedb = StoreDB(options.storedepth); key = storedb.getNewKey(); % __________Initialization of variables______________ % Number of iterations since the last restart k = 0; % Total number of BFGS iterations iter = 0; % This cell stores step vectors which point from x_{t} to x_{t+1} for t % indexing the last iterations, capped at options.memory. % That is, it stores up to options.memory of the most recent step % vectors. However, the implementation below does not need step vectors % in their respective tangent spaces at x_{t}'s. Rather, it requires % them transported to the current point's tangent space by vector % tranport. For details regarding the requirements on the the vector % tranport, see the reference paper by Huang et al. % In this implementation, those step vectors are iteratively % transported to the current point's tangent space after every % iteration. Thus, at every iteration, vectors in sHistory are in the % current point's tangent space. sHistory = cell(1, options.memory); % This cell stores the differences for latest t's of the gradient at % x_{t+1} and the gradient at x_{t}, transported to x_{t+1}'s tangent % space. The memory is also capped at options.memory. yHistory = cell(1, options.memory); % rhoHistory{t} stores the reciprocal of the inner product between % sHistory{t} and yHistory{t}. rhoHistory = cell(1, options.memory); % Scaling of direction given by getDirection for acceptable step alpha = 1; % Scaling of initial matrix, Barzilai-Borwein. scaleFactor = 1; % Norm of the step stepsize = 1; % Stores whether the step is accepted by the cautious update check. accepted = true; % Query the cost function and its gradient [xCurCost, xCurGradient] = getCostGrad(problem, xCur, storedb, key); xCurGradNorm = M.norm(xCur, xCurGradient); % Line-search statistics for recording in info. lsstats = []; % Flag to control restarting scheme to avoid infinite loops (see below) ultimatum = false; % Save stats in a struct array info, and preallocate. stats = savestats(); info(1) = stats; info(min(10000, options.maxiter+1)).iter = []; if options.verbosity >= 2 fprintf(' iter cost val grad. norm alpha\n'); end % Main iteration while true % Display iteration information if options.verbosity >= 2 fprintf('%5d %+.16e %.8e %.4e\n', ... iter, xCurCost, xCurGradNorm, alpha); end % Start timing this iteration timetic = tic(); % Run standard stopping criterion checks [stop, reason] = stoppingcriterion(problem, xCur, options, ... info, iter+1); % If none triggered, run specific stopping criterion check if ~stop if stats.stepsize < options.minstepsize % To avoid infinite loop and to push the search further % in case BFGS approximation of Hessian is off towards % the end, we erase the memory by setting k = 0; % In this way, it starts off like a steepest descent. % If even steepest descent does not work, then it is % hopeless and we will terminate. if ~ultimatum if options.verbosity >= 2 fprintf(['stepsize is too small, restarting ' ... 'the bfgs procedure at the current point.\n']); end k = 0; ultimatum = true; else stop = true; reason = sprintf(['Last stepsize smaller than ' ... 'minimum allowed; options.minstepsize = %g.'], ... options.minstepsize); end else % We are not in trouble: lift the ultimatum if it was on. ultimatum = false; end end if stop if options.verbosity >= 1 fprintf([reason '\n']); end break; end % Compute BFGS direction p = getDirection(M, xCur, xCurGradient, sHistory,... yHistory, rhoHistory, scaleFactor, min(k, options.memory)); % Execute line-search [stepsize, xNext, newkey, lsstats] = ... linesearch_hint(problem, xCur, p, xCurCost, ... M.inner(xCur, xCurGradient, p), ... options, storedb, key); % Record the BFGS step-multiplier alpha which as effectively % selected. Toward convergence, we hope to see alpha = 1. alpha = stepsize/M.norm(xCur, p); step = M.lincomb(xCur, alpha, p); % Query cost and gradient at the candidate new point. [xNextCost, xNextGrad] = getCostGrad(problem, xNext, storedb, newkey); % Compute sk and yk sk = M.transp(xCur, xNext, step); yk = M.lincomb(xNext, 1, xNextGrad, ... -1, M.transp(xCur, xNext, xCurGradient)); % Computation of the BFGS step is invariant under scaling of sk and % yk by a common factor. For numerical reasons, we scale sk and yk % so that sk is a unit norm vector. norm_sk = M.norm(xNext, sk); sk = M.lincomb(xNext, 1/norm_sk, sk); yk = M.lincomb(xNext, 1/norm_sk, yk); inner_sk_yk = M.inner(xNext, sk, yk); inner_sk_sk = M.norm(xNext, sk)^2; % ensures nonnegativity % If the cautious step is accepted (which is the intended % behavior), we record sk, yk and rhok and need to do some % housekeeping. If the cautious step is rejected, these are not % recorded. In all cases, xNext is the next iterate: the notion of % accept/reject here is limited to whether or not we keep track of % sk, yk, rhok to update the BFGS operator. cap = options.strict_inc_func(xCurGradNorm); if inner_sk_sk ~= 0 && (inner_sk_yk / inner_sk_sk) >= cap accepted = true; rhok = 1/inner_sk_yk; scaleFactor = inner_sk_yk / M.norm(xNext, yk)^2; % Time to store the vectors sk, yk and the scalar rhok. % Remember: we need to transport all vectors to the most % current tangent space. % If we are out of memory if k >= options.memory % sk and yk are saved from 1 to the end with the most % current recorded to the rightmost hand side of the cells % that are occupied. When memory is full, do a shift so % that the rightmost is earliest and replace it with the % most recent sk, yk. for i = 2 : options.memory sHistory{i} = M.transp(xCur, xNext, sHistory{i}); yHistory{i} = M.transp(xCur, xNext, yHistory{i}); end if options.memory > 1 sHistory = sHistory([2:end, 1]); yHistory = yHistory([2:end, 1]); rhoHistory = rhoHistory([2:end 1]); end if options.memory > 0 sHistory{options.memory} = sk; yHistory{options.memory} = yk; rhoHistory{options.memory} = rhok; end % If we are not out of memory else for i = 1:k sHistory{i} = M.transp(xCur, xNext, sHistory{i}); yHistory{i} = M.transp(xCur, xNext, yHistory{i}); end sHistory{k+1} = sk; yHistory{k+1} = yk; rhoHistory{k+1} = rhok; end k = k + 1; % The cautious step is rejected: we do not store sk, yk, rhok but % we still need to transport stored vectors to the new tangent % space. else accepted = false; for i = 1 : min(k, options.memory) sHistory{i} = M.transp(xCur, xNext, sHistory{i}); yHistory{i} = M.transp(xCur, xNext, yHistory{i}); end end % Update variables to new iterate iter = iter + 1; xCur = xNext; key = newkey; xCurGradient = xNextGrad; xCurGradNorm = M.norm(xNext, xNextGrad); xCurCost = xNextCost; % Make sure we don't use too much memory for the store database % (this is independent from the BFGS memory.) storedb.purge(); % Log statistics for freshly executed iteration stats = savestats(); info(iter+1) = stats; end % Housekeeping before we return info = info(1:iter+1); x = xCur; cost = xCurCost; if options.verbosity >= 1 fprintf('Total time is %f [s] (excludes statsfun)\n', ... info(end).time); end % Routine in charge of collecting the current iteration stats function stats = savestats() stats.iter = iter; stats.cost = xCurCost; stats.gradnorm = xCurGradNorm; if iter == 0 stats.stepsize = NaN; stats.time = toc(timetic); stats.accepted = NaN; else stats.stepsize = stepsize; stats.time = info(iter).time + toc(timetic); stats.accepted = accepted; end stats.linesearch = lsstats; stats = applyStatsfun(problem, xCur, storedb, key, options, stats); end end % BFGS step, see Wen's paper for details. This functon takes in a tangent % vector g, and applies an approximate inverse Hessian P to it to get Pg. % Then, -Pg is returned. % % Theory requires the vector transport to be isometric and to satisfy the % locking condition (see paper), but these properties do not seem to be % crucial in practice. If your manifold provides M.isotransp, it may be % good to do M.transp = M.isotransp; after loading M with a factory. % % This implementation operates in the tangent space of the most recent % point since all vectors in sHistory and yHistory have been transported % there. function dir = getDirection(M, xCur, xCurGradient, sHistory, yHistory, ... rhoHistory, scaleFactor, k) q = xCurGradient; inner_s_q = zeros(1, k); for i = k : -1 : 1 inner_s_q(1, i) = rhoHistory{i} * M.inner(xCur, sHistory{i}, q); q = M.lincomb(xCur, 1, q, -inner_s_q(1, i), yHistory{i}); end r = M.lincomb(xCur, scaleFactor, q); for i = 1 : k omega = rhoHistory{i} * M.inner(xCur, yHistory{i}, r); r = M.lincomb(xCur, 1, r, inner_s_q(1, i)-omega, sHistory{i}); end dir = M.lincomb(xCur, -1, r); end
281677160/openwrt-package
1,233
luci-app-pppoe-server/po/zh_Hans/pppoe-server.po
msgid "PPPoE Server" msgstr "PPPoE 服务器" msgid "The PPPoE server is a broadband access authentication server that prevents ARP spoofing." msgstr "PPPoE服务器是一个宽带接入认证服务器,可以防止ARP欺骗." msgid "Current Condition" msgstr "当前状态" msgid "General settings" msgstr "基本设置" msgid "Client Interface" msgstr "客户端接口" msgid "Listen in this interface" msgstr "监听客户端接口" msgid "Server IP" msgstr "服务器 IP 地址" msgid "PPPoE Server IP address.default: 10.0.1.1" msgstr "PPPoE 服务器远程地址。默认:10.0.1.1" msgid "Client IP" msgstr "客户端 IP 地址" msgid "PPPoE Client IP address.default: 10.0.1.100-254" msgstr "分配给客户端的 IP 地址范围。默认:10.0.1.100-254" msgid "Preferred DNS server" msgstr "首选 DNS 服务器" msgid "Alternate DNS server" msgstr "备用 DNS 服务器" msgid "Client upper limit" msgstr "客户端上限数" msgid "Specify how many clients can connect to the server simultaneously." msgstr "指定有多少客户端可以同时连接到服务器" msgid "Users Manager" msgstr "用户管理" msgid "Enabled" msgstr "启用" msgid "User name" msgstr "用户名" msgid "Password" msgstr "密码" msgid "IP address" msgstr "IP 地址" msgid "Automatically" msgstr "自动分配" msgid "Online Users" msgstr "在线用户" msgid "Login Time" msgstr "登录时间" msgid "Forced offline" msgstr "强制下线" msgid "NOT RUNNING" msgstr "未运行" msgid "RUNNING" msgstr "运行中"
2881099/FreeSql.AdminLTE
324,646
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-bs5.js
/*! * * Super simple WYSIWYG editor v0.8.20 * https://summernote.org * * * Copyright 2013- Alan Hong and contributors * Summernote may be freely distributed under the MIT license. * * Date: 2021-10-14T21:15Z * */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("jQuery")); else if(typeof define === 'function' && define.amd) define(["jQuery"], factory); else { var a = typeof exports === 'object' ? factory(require("jQuery")) : factory(root["jQuery"]); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(self, function(__WEBPACK_EXTERNAL_MODULE__1145__) { return /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ 9770: /***/ ((__unused_webpack_module, __unused_webpack___webpack_exports__, __webpack_require__) => { /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1145); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__); (jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote) = (jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote) || { lang: {} }; jquery__WEBPACK_IMPORTED_MODULE_0___default().extend((jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote.lang), { 'en-US': { font: { bold: 'Bold', italic: 'Italic', underline: 'Underline', clear: 'Remove Font Style', height: 'Line Height', name: 'Font Family', strikethrough: 'Strikethrough', subscript: 'Subscript', superscript: 'Superscript', size: 'Font Size', sizeunit: 'Font Size Unit' }, image: { image: 'Picture', insert: 'Insert Image', resizeFull: 'Resize full', resizeHalf: 'Resize half', resizeQuarter: 'Resize quarter', resizeNone: 'Original size', floatLeft: 'Float Left', floatRight: 'Float Right', floatNone: 'Remove float', shapeRounded: 'Shape: Rounded', shapeCircle: 'Shape: Circle', shapeThumbnail: 'Shape: Thumbnail', shapeNone: 'Shape: None', dragImageHere: 'Drag image or text here', dropImage: 'Drop image or Text', selectFromFiles: 'Select from files', maximumFileSize: 'Maximum file size', maximumFileSizeError: 'Maximum file size exceeded.', url: 'Image URL', remove: 'Remove Image', original: 'Original' }, video: { video: 'Video', videoLink: 'Video Link', insert: 'Insert Video', url: 'Video URL', providers: '(YouTube, Google Drive, Vimeo, Vine, Instagram, DailyMotion, Youku, Peertube)' }, link: { link: 'Link', insert: 'Insert Link', unlink: 'Unlink', edit: 'Edit', textToDisplay: 'Text to display', url: 'To what URL should this link go?', openInNewWindow: 'Open in new window', useProtocol: 'Use default protocol' }, table: { table: 'Table', addRowAbove: 'Add row above', addRowBelow: 'Add row below', addColLeft: 'Add column left', addColRight: 'Add column right', delRow: 'Delete row', delCol: 'Delete column', delTable: 'Delete table' }, hr: { insert: 'Insert Horizontal Rule' }, style: { style: 'Style', p: 'Normal', blockquote: 'Quote', pre: 'Code', h1: 'Header 1', h2: 'Header 2', h3: 'Header 3', h4: 'Header 4', h5: 'Header 5', h6: 'Header 6' }, lists: { unordered: 'Unordered list', ordered: 'Ordered list' }, options: { help: 'Help', fullscreen: 'Full Screen', codeview: 'Code View' }, paragraph: { paragraph: 'Paragraph', outdent: 'Outdent', indent: 'Indent', left: 'Align left', center: 'Align center', right: 'Align right', justify: 'Justify full' }, color: { recent: 'Recent Color', more: 'More Color', background: 'Background Color', foreground: 'Text Color', transparent: 'Transparent', setTransparent: 'Set transparent', reset: 'Reset', resetToDefault: 'Reset to default', cpSelect: 'Select' }, shortcut: { shortcuts: 'Keyboard shortcuts', close: 'Close', textFormatting: 'Text formatting', action: 'Action', paragraphFormatting: 'Paragraph formatting', documentStyle: 'Document Style', extraKeys: 'Extra keys' }, help: { 'escape': 'Escape', 'insertParagraph': 'Insert Paragraph', 'undo': 'Undo the last command', 'redo': 'Redo the last command', 'tab': 'Tab', 'untab': 'Untab', 'bold': 'Set a bold style', 'italic': 'Set a italic style', 'underline': 'Set a underline style', 'strikethrough': 'Set a strikethrough style', 'removeFormat': 'Clean a style', 'justifyLeft': 'Set left align', 'justifyCenter': 'Set center align', 'justifyRight': 'Set right align', 'justifyFull': 'Set full align', 'insertUnorderedList': 'Toggle unordered list', 'insertOrderedList': 'Toggle ordered list', 'outdent': 'Outdent on current paragraph', 'indent': 'Indent on current paragraph', 'formatPara': 'Change current block\'s format as a paragraph(P tag)', 'formatH1': 'Change current block\'s format as H1', 'formatH2': 'Change current block\'s format as H2', 'formatH3': 'Change current block\'s format as H3', 'formatH4': 'Change current block\'s format as H4', 'formatH5': 'Change current block\'s format as H5', 'formatH6': 'Change current block\'s format as H6', 'insertHorizontalRule': 'Insert horizontal rule', 'linkDialog.show': 'Show Link Dialog' }, history: { undo: 'Undo', redo: 'Redo' }, specialChar: { specialChar: 'SPECIAL CHARACTERS', select: 'Select Special characters' }, output: { noSelection: 'No Selection Made!' } } }); /***/ }), /***/ 1145: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_MODULE__1145__; /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. (() => { // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXTERNAL MODULE: external "jQuery" var external_jQuery_ = __webpack_require__(1145); var external_jQuery_default = /*#__PURE__*/__webpack_require__.n(external_jQuery_); // EXTERNAL MODULE: ./src/lang/summernote-en-US.js var summernote_en_US = __webpack_require__(9770); ;// CONCATENATED MODULE: ./src/js/core/env.js /** * returns whether font is installed or not. * * @param {String} fontName * @return {Boolean} */ var genericFontFamilies = ['sans-serif', 'serif', 'monospace', 'cursive', 'fantasy']; function validFontName(fontName) { return external_jQuery_default().inArray(fontName.toLowerCase(), genericFontFamilies) === -1 ? "'".concat(fontName, "'") : fontName; } function isFontInstalled(fontName) { var testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS'; var testText = 'mmmmmmmmmmwwwww'; var testSize = '200px'; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); context.font = testSize + " '" + testFontName + "'"; var originalWidth = context.measureText(testText).width; context.font = testSize + ' ' + validFontName(fontName) + ', "' + testFontName + '"'; var width = context.measureText(testText).width; return originalWidth !== width; } var userAgent = navigator.userAgent; var isMSIE = /MSIE|Trident/i.test(userAgent); var browserVersion; if (isMSIE) { var matches = /MSIE (\d+[.]\d+)/.exec(userAgent); if (matches) { browserVersion = parseFloat(matches[1]); } matches = /Trident\/.*rv:([0-9]{1,}[.0-9]{0,})/.exec(userAgent); if (matches) { browserVersion = parseFloat(matches[1]); } } var isEdge = /Edge\/\d+/.test(userAgent); var isSupportTouch = 'ontouchstart' in window || navigator.MaxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; // [workaround] IE doesn't have input events for contentEditable // - see: https://goo.gl/4bfIvA var inputEventName = isMSIE ? 'DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted' : 'input'; /** * @class core.env * * Object which check platform and agent * * @singleton * @alternateClassName env */ /* harmony default export */ const env = ({ isMac: navigator.appVersion.indexOf('Mac') > -1, isMSIE: isMSIE, isEdge: isEdge, isFF: !isEdge && /firefox/i.test(userAgent), isPhantom: /PhantomJS/i.test(userAgent), isWebkit: !isEdge && /webkit/i.test(userAgent), isChrome: !isEdge && /chrome/i.test(userAgent), isSafari: !isEdge && /safari/i.test(userAgent) && !/chrome/i.test(userAgent), browserVersion: browserVersion, isSupportTouch: isSupportTouch, isFontInstalled: isFontInstalled, isW3CRangeSupport: !!document.createRange, inputEventName: inputEventName, genericFontFamilies: genericFontFamilies, validFontName: validFontName }); ;// CONCATENATED MODULE: ./src/js/core/func.js /** * @class core.func * * func utils (for high-order func's arg) * * @singleton * @alternateClassName func */ function eq(itemA) { return function (itemB) { return itemA === itemB; }; } function eq2(itemA, itemB) { return itemA === itemB; } function peq2(propName) { return function (itemA, itemB) { return itemA[propName] === itemB[propName]; }; } function ok() { return true; } function fail() { return false; } function not(f) { return function () { return !f.apply(f, arguments); }; } function and(fA, fB) { return function (item) { return fA(item) && fB(item); }; } function func_self(a) { return a; } function invoke(obj, method) { return function () { return obj[method].apply(obj, arguments); }; } var idCounter = 0; /** * reset globally-unique id * */ function resetUniqueId() { idCounter = 0; } /** * generate a globally-unique id * * @param {String} [prefix] */ function uniqueId(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 */ function rect2bnd(rect) { var $document = external_jQuery_default()(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} */ function invertObject(obj) { var inverted = {}; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { inverted[obj[key]] = key; } } return inverted; } /** * @param {String} namespace * @param {String} [prefix] * @return {String} */ function namespaceToCamel(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} */ function debounce(func, wait, immediate) { var timeout; return function () { var context = this; var args = arguments; var later = function later() { timeout = null; if (!immediate) { func.apply(context, args); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; } /** * * @param {String} url * @return {Boolean} */ function isValidUrl(url) { var expression = /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/gi; return expression.test(url); } /* harmony default export */ const func = ({ eq: eq, eq2: eq2, peq2: peq2, ok: ok, fail: fail, self: func_self, not: not, and: and, invoke: invoke, resetUniqueId: resetUniqueId, uniqueId: uniqueId, rect2bnd: rect2bnd, invertObject: invertObject, namespaceToCamel: namespaceToCamel, debounce: debounce, isValidUrl: isValidUrl }); ;// CONCATENATED MODULE: ./src/js/core/lists.js /** * returns the first item of an array. * * @param {Array} array */ function head(array) { return array[0]; } /** * returns the last item of an array. * * @param {Array} array */ function last(array) { return array[array.length - 1]; } /** * returns everything but the last entry of the array. * * @param {Array} array */ function initial(array) { return array.slice(0, array.length - 1); } /** * returns the rest of the items in an array. * * @param {Array} array */ function tail(array) { return array.slice(1); } /** * returns item of array */ function find(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. */ function lists_all(array, pred) { for (var idx = 0, len = array.length; idx < len; idx++) { if (!pred(array[idx])) { return false; } } return true; } /** * returns true if the value is present in the list. */ function contains(array, item) { if (array && array.length && item) { if (array.indexOf) { return array.indexOf(item) !== -1; } else if (array.contains) { // `DOMTokenList` doesn't implement `.indexOf`, but it implements `.contains` return array.contains(item); } } return false; } /** * get sum from a list * * @param {Array} array - array * @param {Function} fn - iterator */ function sum(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, ... */ function from(collection) { var result = []; var length = collection.length; var idx = -1; while (++idx < length) { result[idx] = collection[idx]; } return result; } /** * returns whether list is empty or not */ function isEmpty(array) { return !array || !array.length; } /** * cluster elements by predicate function. * * @param {Array} array - array * @param {Function} fn - predicate function for cluster rule * @param {Array[]} */ function clusterBy(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 */ function compact(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 */ function unique(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 */ function next(array, item) { if (array && array.length && item) { var idx = array.indexOf(item); return idx === -1 ? null : array[idx + 1]; } return null; } /** * returns prev item. * @param {Array} array */ function prev(array, item) { if (array && array.length && item) { var idx = array.indexOf(item); return idx === -1 ? null : array[idx - 1]; } return null; } /** * @class core.list * * list utils * * @singleton * @alternateClassName list */ /* harmony default export */ const lists = ({ head: head, last: last, initial: initial, tail: tail, prev: prev, next: next, find: find, contains: contains, all: lists_all, sum: sum, from: from, isEmpty: isEmpty, clusterBy: clusterBy, compact: compact, unique: unique }); ;// CONCATENATED MODULE: ./src/js/core/dom.js var NBSP_CHAR = String.fromCharCode(160); var ZERO_WIDTH_NBSP_CHAR = "\uFEFF"; /** * @method isEditable * * returns whether node is `note-editable` or not. * * @param {Node} node * @return {Boolean} */ function isEditable(node) { return node && external_jQuery_default()(node).hasClass('note-editable'); } /** * @method isControlSizing * * returns whether node is `note-control-sizing` or not. * * @param {Node} node * @return {Boolean} */ function isControlSizing(node) { return node && external_jQuery_default()(node).hasClass('note-control-sizing'); } /** * @method makePredByNodeName * * returns predicate which judge whether nodeName is same * * @param {String} nodeName * @return {Function} */ function makePredByNodeName(nodeName) { nodeName = nodeName.toUpperCase(); return function (node) { return node && node.nodeName.toUpperCase() === nodeName; }; } /** * @method isText * * * * @param {Node} node * @return {Boolean} true if node's type is text(3) */ function isText(node) { return node && node.nodeType === 3; } /** * @method isElement * * * * @param {Node} node * @return {Boolean} true if node's type is element(1) */ function isElement(node) { return node && node.nodeType === 1; } /** * ex) br, col, embed, hr, img, input, ... * @see http://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements */ function isVoid(node) { return node && /^BR|^IMG|^HR|^IFRAME|^BUTTON|^INPUT|^AUDIO|^VIDEO|^EMBED/.test(node.nodeName.toUpperCase()); } function isPara(node) { if (isEditable(node)) { return false; } // Chrome(v31.0), FF(v25.0.1) use DIV for paragraph return node && /^DIV|^P|^LI|^H[1-7]/.test(node.nodeName.toUpperCase()); } function isHeading(node) { return node && /^H[1-7]/.test(node.nodeName.toUpperCase()); } var isPre = makePredByNodeName('PRE'); var isLi = makePredByNodeName('LI'); function isPurePara(node) { return isPara(node) && !isLi(node); } var isTable = makePredByNodeName('TABLE'); var isData = makePredByNodeName('DATA'); function isInline(node) { return !isBodyContainer(node) && !isList(node) && !isHr(node) && !isPara(node) && !isTable(node) && !isBlockquote(node) && !isData(node); } function isList(node) { return node && /^UL|^OL/.test(node.nodeName.toUpperCase()); } var isHr = makePredByNodeName('HR'); function isCell(node) { return node && /^TD|^TH/.test(node.nodeName.toUpperCase()); } var isBlockquote = makePredByNodeName('BLOCKQUOTE'); function isBodyContainer(node) { return isCell(node) || isBlockquote(node) || isEditable(node); } var isAnchor = makePredByNodeName('A'); function isParaInline(node) { return isInline(node) && !!ancestor(node, isPara); } function isBodyInline(node) { return isInline(node) && !ancestor(node, isPara); } var isBody = makePredByNodeName('BODY'); /** * returns whether nodeB is closest sibling of nodeA * * @param {Node} nodeA * @param {Node} nodeB * @return {Boolean} */ function isClosestSibling(nodeA, nodeB) { return nodeA.nextSibling === nodeB || nodeA.previousSibling === nodeB; } /** * returns array of closest siblings with node * * @param {Node} node * @param {function} [pred] - predicate function * @return {Node[]} */ function withClosestSiblings(node, pred) { pred = pred || func.ok; var siblings = []; if (node.previousSibling && pred(node.previousSibling)) { siblings.push(node.previousSibling); } siblings.push(node); if (node.nextSibling && pred(node.nextSibling)) { siblings.push(node.nextSibling); } return siblings; } /** * blank HTML for cursor position * - [workaround] old IE only works with &nbsp; * - [workaround] IE11 and other browser works with bogus br */ var blankHTML = env.isMSIE && env.browserVersion < 11 ? '&nbsp;' : '<br>'; /** * @method nodeLength * * returns #text's text size or element's childNodes size * * @param {Node} node */ function nodeLength(node) { if (isText(node)) { return node.nodeValue.length; } if (node) { return node.childNodes.length; } return 0; } /** * returns whether deepest child node is empty or not. * * @param {Node} node * @return {Boolean} */ function deepestChildIsEmpty(node) { do { if (node.firstElementChild === null || node.firstElementChild.innerHTML === '') break; } while (node = node.firstElementChild); return dom_isEmpty(node); } /** * returns whether node is empty or not. * * @param {Node} node * @return {Boolean} */ function dom_isEmpty(node) { var len = nodeLength(node); if (len === 0) { return true; } else if (!isText(node) && len === 1 && node.innerHTML === blankHTML) { // ex) <p><br></p>, <span><br></span> return true; } else if (lists.all(node.childNodes, isText) && node.innerHTML === '') { // ex) <p></p>, <span></span> return true; } return false; } /** * padding blankHTML if node is empty (for cursor position) */ function paddingBlankHTML(node) { if (!isVoid(node) && !nodeLength(node)) { node.innerHTML = blankHTML; } } /** * find nearest ancestor predicate hit * * @param {Node} node * @param {Function} pred - predicate function */ function ancestor(node, pred) { while (node) { if (pred(node)) { return node; } if (isEditable(node)) { break; } node = node.parentNode; } return null; } /** * find nearest ancestor only single child blood line and predicate hit * * @param {Node} node * @param {Function} pred - predicate function */ function singleChildAncestor(node, pred) { node = node.parentNode; while (node) { if (nodeLength(node) !== 1) { break; } if (pred(node)) { return node; } if (isEditable(node)) { break; } node = node.parentNode; } return null; } /** * returns new array of ancestor nodes (until predicate hit). * * @param {Node} node * @param {Function} [optional] pred - predicate function */ function listAncestor(node, pred) { pred = pred || func.fail; var ancestors = []; ancestor(node, function (el) { if (!isEditable(el)) { ancestors.push(el); } return pred(el); }); return ancestors; } /** * find farthest ancestor predicate hit */ function lastAncestor(node, pred) { var ancestors = listAncestor(node); return lists.last(ancestors.filter(pred)); } /** * returns common ancestor node between two nodes. * * @param {Node} nodeA * @param {Node} nodeB */ function commonAncestor(nodeA, nodeB) { var ancestors = listAncestor(nodeA); for (var n = nodeB; n; n = n.parentNode) { if (ancestors.indexOf(n) > -1) return n; } return null; // difference document area } /** * listing all previous siblings (until predicate hit). * * @param {Node} node * @param {Function} [optional] pred - predicate function */ function listPrev(node, pred) { pred = pred || func.fail; var nodes = []; while (node) { if (pred(node)) { break; } nodes.push(node); node = node.previousSibling; } return nodes; } /** * listing next siblings (until predicate hit). * * @param {Node} node * @param {Function} [pred] - predicate function */ function listNext(node, pred) { pred = pred || func.fail; var nodes = []; while (node) { if (pred(node)) { break; } nodes.push(node); node = node.nextSibling; } return nodes; } /** * listing descendant nodes * * @param {Node} node * @param {Function} [pred] - predicate function */ function listDescendant(node, pred) { var descendants = []; pred = pred || func.ok; // start DFS(depth first search) with node (function fnWalk(current) { if (node !== current && pred(current)) { descendants.push(current); } for (var idx = 0, len = current.childNodes.length; idx < len; idx++) { fnWalk(current.childNodes[idx]); } })(node); return descendants; } /** * wrap node with new tag. * * @param {Node} node * @param {Node} tagName of wrapper * @return {Node} - wrapper */ function wrap(node, wrapperName) { var parent = node.parentNode; var wrapper = external_jQuery_default()('<' + wrapperName + '>')[0]; parent.insertBefore(wrapper, node); wrapper.appendChild(node); return wrapper; } /** * insert node after preceding * * @param {Node} node * @param {Node} preceding - predicate function */ function insertAfter(node, preceding) { var next = preceding.nextSibling; var parent = preceding.parentNode; if (next) { parent.insertBefore(node, next); } else { parent.appendChild(node); } return node; } /** * append elements. * * @param {Node} node * @param {Collection} aChild */ function appendChildNodes(node, aChild) { external_jQuery_default().each(aChild, function (idx, child) { node.appendChild(child); }); return node; } /** * returns whether boundaryPoint is left edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isLeftEdgePoint(point) { return point.offset === 0; } /** * returns whether boundaryPoint is right edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isRightEdgePoint(point) { return point.offset === nodeLength(point.node); } /** * returns whether boundaryPoint is edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isEdgePoint(point) { return isLeftEdgePoint(point) || isRightEdgePoint(point); } /** * returns whether node is left edge of ancestor or not. * * @param {Node} node * @param {Node} ancestor * @return {Boolean} */ function isLeftEdgeOf(node, ancestor) { while (node && node !== ancestor) { if (position(node) !== 0) { return false; } node = node.parentNode; } return true; } /** * returns whether node is right edge of ancestor or not. * * @param {Node} node * @param {Node} ancestor * @return {Boolean} */ function isRightEdgeOf(node, ancestor) { if (!ancestor) { return false; } while (node && node !== ancestor) { if (position(node) !== nodeLength(node.parentNode) - 1) { return false; } node = node.parentNode; } return true; } /** * returns whether point is left edge of ancestor or not. * @param {BoundaryPoint} point * @param {Node} ancestor * @return {Boolean} */ function isLeftEdgePointOf(point, ancestor) { return isLeftEdgePoint(point) && isLeftEdgeOf(point.node, ancestor); } /** * returns whether point is right edge of ancestor or not. * @param {BoundaryPoint} point * @param {Node} ancestor * @return {Boolean} */ function isRightEdgePointOf(point, ancestor) { return isRightEdgePoint(point) && isRightEdgeOf(point.node, ancestor); } /** * returns offset from parent. * * @param {Node} node */ function position(node) { var offset = 0; while (node = node.previousSibling) { offset += 1; } return offset; } function hasChildren(node) { return !!(node && node.childNodes && node.childNodes.length); } /** * returns previous boundaryPoint * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function prevPoint(point, isSkipInnerOffset) { var node; var offset; if (point.offset === 0) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node); } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset - 1]; offset = nodeLength(node); } else { node = point.node; offset = isSkipInnerOffset ? 0 : point.offset - 1; } return { node: node, offset: offset }; } /** * returns next boundaryPoint * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function nextPoint(point, isSkipInnerOffset) { var node, offset; if (nodeLength(point.node) === point.offset) { if (isEditable(point.node)) { return null; } var nextTextNode = getNextTextNode(point.node); if (nextTextNode) { node = nextTextNode; offset = 0; } else { node = point.node.parentNode; offset = position(point.node) + 1; } } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset]; offset = 0; } else { node = point.node; offset = isSkipInnerOffset ? nodeLength(point.node) : point.offset + 1; } return { node: node, offset: offset }; } /** * returns next boundaryPoint with empty node * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function nextPointWithEmptyNode(point, isSkipInnerOffset) { var node, offset = 0; // if node is empty string node, return current node's sibling. if (dom_isEmpty(point.node)) { if (point.node === null) { return null; } node = point.node.nextSibling; offset = 0; return { node: node, offset: offset }; } if (nodeLength(point.node) === point.offset) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node) + 1; // if next node is editable , return current node's sibling node. if (isEditable(node)) { node = point.node.nextSibling; offset = 0; } } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset]; offset = 0; if (dom_isEmpty(node)) { if (!dom_isEmpty(point.node.nextSibling)) { return { node: point.node.nextSibling, offset: offset }; } return null; } } else { node = point.node; offset = isSkipInnerOffset ? nodeLength(point.node) : point.offset + 1; if (dom_isEmpty(node)) { return null; } } return { node: node, offset: offset }; } /* * returns the next Text node index or 0 if not found. */ function getNextTextNode(actual) { if (!actual.nextSibling) return undefined; if (actual.parent !== actual.nextSibling.parent) return undefined; if (isText(actual.nextSibling)) return actual.nextSibling;else return getNextTextNode(actual.nextSibling); } /** * returns whether pointA and pointB is same or not. * * @param {BoundaryPoint} pointA * @param {BoundaryPoint} pointB * @return {Boolean} */ function isSamePoint(pointA, pointB) { return pointA.node === pointB.node && pointA.offset === pointB.offset; } /** * returns whether point is visible (can set cursor) or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isVisiblePoint(point) { if (isText(point.node) || !hasChildren(point.node) || dom_isEmpty(point.node)) { return true; } var leftNode = point.node.childNodes[point.offset - 1]; var rightNode = point.node.childNodes[point.offset]; if ((!leftNode || isVoid(leftNode)) && (!rightNode || isVoid(rightNode)) || isTable(rightNode)) { return true; } return false; } /** * @method prevPointUtil * * @param {BoundaryPoint} point * @param {Function} pred * @return {BoundaryPoint} */ function prevPointUntil(point, pred) { while (point) { if (pred(point)) { return point; } point = prevPoint(point); } return null; } /** * @method nextPointUntil * * @param {BoundaryPoint} point * @param {Function} pred * @return {BoundaryPoint} */ function nextPointUntil(point, pred) { while (point) { if (pred(point)) { return point; } point = nextPoint(point); } return null; } /** * returns whether point has character or not. * * @param {Point} point * @return {Boolean} */ function isCharPoint(point) { if (!isText(point.node)) { return false; } var ch = point.node.nodeValue.charAt(point.offset - 1); return ch && ch !== ' ' && ch !== NBSP_CHAR; } /** * returns whether point has space or not. * * @param {Point} point * @return {Boolean} */ function isSpacePoint(point) { if (!isText(point.node)) { return false; } var ch = point.node.nodeValue.charAt(point.offset - 1); return ch === ' ' || ch === NBSP_CHAR; } /** * @method walkPoint * * @param {BoundaryPoint} startPoint * @param {BoundaryPoint} endPoint * @param {Function} handler * @param {Boolean} isSkipInnerOffset */ function walkPoint(startPoint, endPoint, handler, isSkipInnerOffset) { var point = startPoint; while (point) { handler(point); if (isSamePoint(point, endPoint)) { break; } var isSkipOffset = isSkipInnerOffset && startPoint.node !== point.node && endPoint.node !== point.node; point = nextPointWithEmptyNode(point, isSkipOffset); } } /** * @method makeOffsetPath * * return offsetPath(array of offset) from ancestor * * @param {Node} ancestor - ancestor node * @param {Node} node */ function makeOffsetPath(ancestor, node) { var ancestors = listAncestor(node, func.eq(ancestor)); return ancestors.map(position).reverse(); } /** * @method fromOffsetPath * * return element from offsetPath(array of offset) * * @param {Node} ancestor - ancestor node * @param {array} offsets - offsetPath */ function fromOffsetPath(ancestor, offsets) { var current = ancestor; for (var i = 0, len = offsets.length; i < len; i++) { if (current.childNodes.length <= offsets[i]) { current = current.childNodes[current.childNodes.length - 1]; } else { current = current.childNodes[offsets[i]]; } } return current; } /** * @method splitNode * * split element or #text * * @param {BoundaryPoint} point * @param {Object} [options] * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false * @param {Boolean} [options.isNotSplitEdgePoint] - default: false * @param {Boolean} [options.isDiscardEmptySplits] - default: false * @return {Node} right node of boundaryPoint */ function splitNode(point, options) { var isSkipPaddingBlankHTML = options && options.isSkipPaddingBlankHTML; var isNotSplitEdgePoint = options && options.isNotSplitEdgePoint; var isDiscardEmptySplits = options && options.isDiscardEmptySplits; if (isDiscardEmptySplits) { isSkipPaddingBlankHTML = true; } // edge case if (isEdgePoint(point) && (isText(point.node) || isNotSplitEdgePoint)) { if (isLeftEdgePoint(point)) { return point.node; } else if (isRightEdgePoint(point)) { return point.node.nextSibling; } } // split #text if (isText(point.node)) { return point.node.splitText(point.offset); } else { var childNode = point.node.childNodes[point.offset]; var clone = insertAfter(point.node.cloneNode(false), point.node); appendChildNodes(clone, listNext(childNode)); if (!isSkipPaddingBlankHTML) { paddingBlankHTML(point.node); paddingBlankHTML(clone); } if (isDiscardEmptySplits) { if (dom_isEmpty(point.node)) { remove(point.node); } if (dom_isEmpty(clone)) { remove(clone); return point.node.nextSibling; } } return clone; } } /** * @method splitTree * * split tree by point * * @param {Node} root - split root * @param {BoundaryPoint} point * @param {Object} [options] * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false * @param {Boolean} [options.isNotSplitEdgePoint] - default: false * @return {Node} right node of boundaryPoint */ function splitTree(root, point, options) { // ex) [#text, <span>, <p>] 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 ? position(node) : nodeLength(parent) }, options); }); } /** * split point * * @param {Point} point * @param {Boolean} isInline * @return {Object} */ function splitPoint(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 = lists.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 }; } function create(nodeName) { return document.createElement(nodeName); } function createText(text) { return document.createTextNode(text); } /** * @method remove * * remove node, (isRemoveChild: remove child or not) * * @param {Node} node * @param {Boolean} isRemoveChild */ function remove(node, isRemoveChild) { if (!node || !node.parentNode) { return; } if (node.removeNode) { return node.removeNode(isRemoveChild); } var parent = node.parentNode; if (!isRemoveChild) { var nodes = []; for (var i = 0, len = node.childNodes.length; i < len; i++) { nodes.push(node.childNodes[i]); } for (var _i = 0, _len = nodes.length; _i < _len; _i++) { parent.insertBefore(nodes[_i], node); } } parent.removeChild(node); } /** * @method removeWhile * * @param {Node} node * @param {Function} pred */ function removeWhile(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 */ function replace(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, lists.from(node.childNodes)); insertAfter(newNode, node); remove(node); return newNode; } var isTextarea = makePredByNodeName('TEXTAREA'); /** * @param {jQuery} $node * @param {Boolean} [stripLinebreaks] - default: false */ function value($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] */ function html($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 = markup.trim(); } return markup; } function posFromPlaceholder(placeholder) { var $placeholder = external_jQuery_default()(placeholder); var pos = $placeholder.offset(); var height = $placeholder.outerHeight(true); // include margin return { left: pos.left, top: pos.top + height }; } function attachEvents($node, events) { Object.keys(events).forEach(function (key) { $node.on(key, events[key]); }); } function detachEvents($node, events) { Object.keys(events).forEach(function (key) { $node.off(key, events[key]); }); } /** * @method isCustomStyleTag * * assert if a node contains a "note-styletag" class, * which implies that's a custom-made style tag node * * @param {Node} an HTML DOM node */ function isCustomStyleTag(node) { return node && !isText(node) && lists.contains(node.classList, 'note-styletag'); } /* harmony default export */ const dom = ({ /** @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: "<p>".concat(blankHTML, "</p>"), 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, deepestChildIsEmpty: deepestChildIsEmpty, isEmpty: dom_isEmpty, isEmptyAnchor: func.and(isAnchor, dom_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, nextPointWithEmptyNode: nextPointWithEmptyNode, isSamePoint: isSamePoint, isVisiblePoint: isVisiblePoint, prevPointUntil: prevPointUntil, nextPointUntil: nextPointUntil, isCharPoint: isCharPoint, isSpacePoint: isSpacePoint, 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, isCustomStyleTag: isCustomStyleTag }); ;// CONCATENATED MODULE: ./src/js/Context.js function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var Context = /*#__PURE__*/function () { /** * @param {jQuery} $note * @param {Object} options */ function Context($note, options) { _classCallCheck(this, Context); this.$note = $note; this.memos = {}; this.modules = {}; this.layoutInfo = {}; this.options = external_jQuery_default().extend(true, {}, options); // init ui with options (external_jQuery_default()).summernote.ui = external_jQuery_default().summernote.ui_template(this.options); this.ui = (external_jQuery_default()).summernote.ui; this.initialize(); } /** * create layout and initialize modules and other resources */ _createClass(Context, [{ key: "initialize", value: function initialize() { this.layoutInfo = this.ui.createLayout(this.$note); this._initialize(); this.$note.hide(); return this; } /** * destroy modules and other resources and remove layout */ }, { key: "destroy", value: function destroy() { this._destroy(); this.$note.removeData('summernote'); this.ui.removeLayout(this.$note, this.layoutInfo); } /** * destory modules and other resources and initialize it again */ }, { key: "reset", value: function reset() { var disabled = this.isDisabled(); this.code(dom.emptyPara); this._destroy(); this._initialize(); if (disabled) { this.disable(); } } }, { key: "_initialize", value: function _initialize() { var _this = this; // set own id this.options.id = func.uniqueId(external_jQuery_default().now()); // set default container for tooltips, popovers, and dialogs this.options.container = this.options.container || this.layoutInfo.editor; // add optional buttons var buttons = external_jQuery_default().extend({}, this.options.buttons); Object.keys(buttons).forEach(function (key) { _this.memo('button.' + key, buttons[key]); }); var modules = external_jQuery_default().extend({}, this.options.modules, (external_jQuery_default()).summernote.plugins || {}); // add and initialize modules Object.keys(modules).forEach(function (key) { _this.module(key, modules[key], true); }); Object.keys(this.modules).forEach(function (key) { _this.initializeModule(key); }); } }, { key: "_destroy", value: function _destroy() { var _this2 = this; // destroy modules with reversed order Object.keys(this.modules).reverse().forEach(function (key) { _this2.removeModule(key); }); Object.keys(this.memos).forEach(function (key) { _this2.removeMemo(key); }); // trigger custom onDestroy callback this.triggerEvent('destroy', this); } }, { key: "code", value: function code(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.invoke('codeview.sync', html); } else { this.layoutInfo.editable.html(html); } this.$note.val(html); this.triggerEvent('change', html, this.layoutInfo.editable); } } }, { key: "isDisabled", value: function isDisabled() { return this.layoutInfo.editable.attr('contenteditable') === 'false'; } }, { key: "enable", value: function enable() { this.layoutInfo.editable.attr('contenteditable', true); this.invoke('toolbar.activate', true); this.triggerEvent('disable', false); this.options.editing = true; } }, { key: "disable", value: function disable() { // close codeview if codeview is opend if (this.invoke('codeview.isActivated')) { this.invoke('codeview.deactivate'); } this.layoutInfo.editable.attr('contenteditable', false); this.options.editing = false; this.invoke('toolbar.deactivate', true); this.triggerEvent('disable', true); } }, { key: "triggerEvent", value: function triggerEvent() { var namespace = lists.head(arguments); var args = lists.tail(lists.from(arguments)); var callback = this.options.callbacks[func.namespaceToCamel(namespace, 'on')]; if (callback) { callback.apply(this.$note[0], args); } this.$note.trigger('summernote.' + namespace, args); } }, { key: "initializeModule", value: function initializeModule(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(this.$note, module.events); } } }, { key: "module", value: function module(key, ModuleClass, withoutIntialize) { if (arguments.length === 1) { return this.modules[key]; } this.modules[key] = new ModuleClass(this); if (!withoutIntialize) { this.initializeModule(key); } } }, { key: "removeModule", value: function removeModule(key) { var module = this.modules[key]; if (module.shouldInitialize()) { if (module.events) { dom.detachEvents(this.$note, module.events); } if (module.destroy) { module.destroy(); } } delete this.modules[key]; } }, { key: "memo", value: function memo(key, obj) { if (arguments.length === 1) { return this.memos[key]; } this.memos[key] = obj; } }, { key: "removeMemo", value: function removeMemo(key) { if (this.memos[key] && this.memos[key].destroy) { this.memos[key].destroy(); } delete this.memos[key]; } /** * Some buttons need to change their visual style immediately once they get pressed */ }, { key: "createInvokeHandlerAndUpdateState", value: function createInvokeHandlerAndUpdateState(namespace, value) { var _this3 = this; return function (event) { _this3.createInvokeHandler(namespace, value)(event); _this3.invoke('buttons.updateCurrentStyle'); }; } }, { key: "createInvokeHandler", value: function createInvokeHandler(namespace, value) { var _this4 = this; return function (event) { event.preventDefault(); var $target = external_jQuery_default()(event.target); _this4.invoke(namespace, value || $target.closest('[data-value]').data('value'), $target); }; } }, { key: "invoke", value: function invoke() { var namespace = lists.head(arguments); var args = lists.tail(lists.from(arguments)); var splits = namespace.split('.'); var hasSeparator = splits.length > 1; var moduleName = hasSeparator && lists.head(splits); var methodName = hasSeparator ? lists.last(splits) : lists.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 Context; }(); ;// CONCATENATED MODULE: ./src/js/summernote.js external_jQuery_default().fn.extend({ /** * Summernote API * * @param {Object|String} * @return {this} */ summernote: function summernote() { var type = external_jQuery_default().type(lists.head(arguments)); var isExternalAPICalled = type === 'string'; var hasInitOptions = type === 'object'; var options = external_jQuery_default().extend({}, (external_jQuery_default()).summernote.options, hasInitOptions ? lists.head(arguments) : {}); // Update options options.langInfo = external_jQuery_default().extend(true, {}, (external_jQuery_default()).summernote.lang["en-US"], (external_jQuery_default()).summernote.lang[options.lang]); options.icons = external_jQuery_default().extend(true, {}, (external_jQuery_default()).summernote.options.icons, options.icons); options.tooltip = options.tooltip === 'auto' ? !env.isSupportTouch : options.tooltip; this.each(function (idx, note) { var $note = external_jQuery_default()(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, lists.from(arguments)); } else if (options.focus) { context.invoke('editor.focus'); } } return this; } }); ;// CONCATENATED MODULE: ./src/js/core/range.js function range_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function range_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function range_createClass(Constructor, protoProps, staticProps) { if (protoProps) range_defineProperties(Constructor.prototype, protoProps); if (staticProps) range_defineProperties(Constructor, staticProps); return Constructor; } /** * return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js * * @param {TextRange} textRange * @param {Boolean} isStart * @return {BoundaryPoint} * * @see http://msdn.microsoft.com/en-us/library/ie/ms535872(v=vs.85).aspx */ function textRangeToPoint(textRange, isStart) { var container = textRange.parentElement(); var offset; var tester = document.body.createTextRange(); var prevContainer; var childNodes = lists.from(container.childNodes); for (offset = 0; offset < childNodes.length; offset++) { if (dom.isText(childNodes[offset])) { continue; } tester.moveToElementText(childNodes[offset]); if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; } prevContainer = childNodes[offset]; } if (offset !== 0 && dom.isText(childNodes[offset - 1])) { var textRangeStart = document.body.createTextRange(); var curTextNode = null; textRangeStart.moveToElementText(prevContainer || container); textRangeStart.collapse(!prevContainer); curTextNode = prevContainer ? prevContainer.nextSibling : container.firstChild; var pointTester = textRange.duplicate(); pointTester.setEndPoint('StartToStart', textRangeStart); var textCount = pointTester.text.replace(/[\r\n]/g, '').length; while (textCount > curTextNode.nodeValue.length && curTextNode.nextSibling) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } // [workaround] enforce IE to re-reference curTextNode, hack var dummy = curTextNode.nodeValue; // eslint-disable-line if (isStart && curTextNode.nextSibling && dom.isText(curTextNode.nextSibling) && textCount === curTextNode.nodeValue.length) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } container = curTextNode; offset = textCount; } return { cont: container, offset: offset }; } /** * return TextRange from boundary point (inspired by google closure-library) * @param {BoundaryPoint} point * @return {TextRange} */ function pointToTextRange(point) { var textRangeInfo = function textRangeInfo(container, offset) { var node, isCollapseToStart; if (dom.isText(container)) { var prevTextNodes = dom.listPrev(container, func.not(dom.isText)); var prevContainer = lists.last(prevTextNodes).previousSibling; node = prevContainer || container.parentNode; offset += lists.sum(lists.tail(prevTextNodes), dom.nodeLength); isCollapseToStart = !prevContainer; } else { node = container.childNodes[offset] || container; if (dom.isText(node)) { return textRangeInfo(node, 0); } offset = 0; isCollapseToStart = false; } return { node: node, collapseToStart: isCollapseToStart, offset: offset }; }; var textRange = document.body.createTextRange(); var info = textRangeInfo(point.node, point.offset); textRange.moveToElementText(info.node); textRange.collapse(info.collapseToStart); textRange.moveStart('character', info.offset); return textRange; } /** * Wrapped Range * * @constructor * @param {Node} sc - start container * @param {Number} so - start offset * @param {Node} ec - end container * @param {Number} eo - end offset */ var WrappedRange = /*#__PURE__*/function () { function WrappedRange(sc, so, ec, eo) { range_classCallCheck(this, WrappedRange); this.sc = sc; this.so = so; this.ec = ec; this.eo = eo; // isOnEditable: judge whether range is on editable or not this.isOnEditable = this.makeIsOn(dom.isEditable); // isOnList: judge whether range is on list node or not this.isOnList = this.makeIsOn(dom.isList); // isOnAnchor: judge whether range is on anchor node or not this.isOnAnchor = this.makeIsOn(dom.isAnchor); // isOnCell: judge whether range is on cell node or not this.isOnCell = this.makeIsOn(dom.isCell); // isOnData: judge whether range is on data node or not this.isOnData = this.makeIsOn(dom.isData); } // nativeRange: get nativeRange from sc, so, ec, eo range_createClass(WrappedRange, [{ key: "nativeRange", value: function nativeRange() { if (env.isW3CRangeSupport) { var w3cRange = document.createRange(); w3cRange.setStart(this.sc, this.so); w3cRange.setEnd(this.ec, this.eo); return w3cRange; } else { var textRange = pointToTextRange({ node: this.sc, offset: this.so }); textRange.setEndPoint('EndToEnd', pointToTextRange({ node: this.ec, offset: this.eo })); return textRange; } } }, { key: "getPoints", value: function getPoints() { return { sc: this.sc, so: this.so, ec: this.ec, eo: this.eo }; } }, { key: "getStartPoint", value: function getStartPoint() { return { node: this.sc, offset: this.so }; } }, { key: "getEndPoint", value: function getEndPoint() { return { node: this.ec, offset: this.eo }; } /** * select update visible range */ }, { key: "select", value: function select() { var nativeRng = this.nativeRange(); if (env.isW3CRangeSupport) { var selection = document.getSelection(); if (selection.rangeCount > 0) { selection.removeAllRanges(); } selection.addRange(nativeRng); } else { nativeRng.select(); } return this; } /** * Moves the scrollbar to start container(sc) of current range * * @return {WrappedRange} */ }, { key: "scrollIntoView", value: function scrollIntoView(container) { var height = external_jQuery_default()(container).height(); if (container.scrollTop + height < this.sc.offsetTop) { container.scrollTop += Math.abs(container.scrollTop + height - this.sc.offsetTop); } return this; } /** * @return {WrappedRange} */ }, { key: "normalize", value: function normalize() { /** * @param {BoundaryPoint} point * @param {Boolean} isLeftToRight - true: prefer to choose right node * - false: prefer to choose left node * @return {BoundaryPoint} */ var getVisiblePoint = function getVisiblePoint(point, isLeftToRight) { if (!point) { return point; } // Just use the given point [XXX:Adhoc] // - case 01. if the point is on the middle of the node // - case 02. if the point is on the right edge and prefer to choose left node // - case 03. if the point is on the left edge and prefer to choose right node // - case 04. if the point is on the right edge and prefer to choose right node but the node is void // - case 05. if the point is on the left edge and prefer to choose left node but the node is void // - case 06. if the point is on the block node and there is no children if (dom.isVisiblePoint(point)) { if (!dom.isEdgePoint(point) || dom.isRightEdgePoint(point) && !isLeftToRight || dom.isLeftEdgePoint(point) && isLeftToRight || dom.isRightEdgePoint(point) && isLeftToRight && dom.isVoid(point.node.nextSibling) || dom.isLeftEdgePoint(point) && !isLeftToRight && dom.isVoid(point.node.previousSibling) || dom.isBlock(point.node) && dom.isEmpty(point.node)) { return point; } } // point on block's edge var block = dom.ancestor(point.node, dom.isBlock); var hasRightNode = false; if (!hasRightNode) { var prevPoint = dom.prevPoint(point) || { node: null }; hasRightNode = (dom.isLeftEdgePointOf(point, block) || dom.isVoid(prevPoint.node)) && !isLeftToRight; } var hasLeftNode = false; if (!hasLeftNode) { var _nextPoint = dom.nextPoint(point) || { node: null }; hasLeftNode = (dom.isRightEdgePointOf(point, block) || dom.isVoid(_nextPoint.node)) && isLeftToRight; } if (hasRightNode || hasLeftNode) { // returns point already on visible point if (dom.isVisiblePoint(point)) { return point; } // reverse direction isLeftToRight = !isLeftToRight; } var nextPoint = isLeftToRight ? dom.nextPointUntil(dom.nextPoint(point), dom.isVisiblePoint) : dom.prevPointUntil(dom.prevPoint(point), dom.isVisiblePoint); return nextPoint || point; }; var endPoint = getVisiblePoint(this.getEndPoint(), false); var startPoint = this.isCollapsed() ? endPoint : getVisiblePoint(this.getStartPoint(), true); return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns matched nodes on range * * @param {Function} [pred] - predicate function * @param {Object} [options] * @param {Boolean} [options.includeAncestor] * @param {Boolean} [options.fullyContains] * @return {Node[]} */ }, { key: "nodes", value: function nodes(pred, options) { pred = pred || func.ok; var includeAncestor = options && options.includeAncestor; var fullyContains = options && options.fullyContains; // TODO compare points and sort var startPoint = this.getStartPoint(); var endPoint = this.getEndPoint(); var nodes = []; var leftEdgeNodes = []; dom.walkPoint(startPoint, endPoint, function (point) { if (dom.isEditable(point.node)) { return; } var node; if (fullyContains) { if (dom.isLeftEdgePoint(point)) { leftEdgeNodes.push(point.node); } if (dom.isRightEdgePoint(point) && lists.contains(leftEdgeNodes, point.node)) { node = point.node; } } else if (includeAncestor) { node = dom.ancestor(point.node, pred); } else { node = point.node; } if (node && pred(node)) { nodes.push(node); } }, true); return lists.unique(nodes); } /** * returns commonAncestor of range * @return {Element} - commonAncestor */ }, { key: "commonAncestor", value: function commonAncestor() { return dom.commonAncestor(this.sc, this.ec); } /** * returns expanded range by pred * * @param {Function} pred - predicate function * @return {WrappedRange} */ }, { key: "expand", value: function expand(pred) { var startAncestor = dom.ancestor(this.sc, pred); var endAncestor = dom.ancestor(this.ec, pred); if (!startAncestor && !endAncestor) { return new WrappedRange(this.sc, this.so, this.ec, this.eo); } var boundaryPoints = this.getPoints(); if (startAncestor) { boundaryPoints.sc = startAncestor; boundaryPoints.so = 0; } if (endAncestor) { boundaryPoints.ec = endAncestor; boundaryPoints.eo = dom.nodeLength(endAncestor); } return new WrappedRange(boundaryPoints.sc, boundaryPoints.so, boundaryPoints.ec, boundaryPoints.eo); } /** * @param {Boolean} isCollapseToStart * @return {WrappedRange} */ }, { key: "collapse", value: function collapse(isCollapseToStart) { if (isCollapseToStart) { return new WrappedRange(this.sc, this.so, this.sc, this.so); } else { return new WrappedRange(this.ec, this.eo, this.ec, this.eo); } } /** * splitText on range */ }, { key: "splitText", value: function splitText() { var isSameContainer = this.sc === this.ec; var boundaryPoints = this.getPoints(); if (dom.isText(this.ec) && !dom.isEdgePoint(this.getEndPoint())) { this.ec.splitText(this.eo); } if (dom.isText(this.sc) && !dom.isEdgePoint(this.getStartPoint())) { boundaryPoints.sc = this.sc.splitText(this.so); boundaryPoints.so = 0; if (isSameContainer) { boundaryPoints.ec = boundaryPoints.sc; boundaryPoints.eo = this.eo - this.so; } } return new WrappedRange(boundaryPoints.sc, boundaryPoints.so, boundaryPoints.ec, boundaryPoints.eo); } /** * delete contents on range * @return {WrappedRange} */ }, { key: "deleteContents", value: function deleteContents() { if (this.isCollapsed()) { return this; } var rng = this.splitText(); var nodes = rng.nodes(null, { fullyContains: true }); // find new cursor point var point = dom.prevPointUntil(rng.getStartPoint(), function (point) { return !lists.contains(nodes, point.node); }); var emptyParents = []; external_jQuery_default().each(nodes, function (idx, node) { // find empty parents var parent = node.parentNode; if (point.node !== parent && dom.nodeLength(parent) === 1) { emptyParents.push(parent); } dom.remove(node, false); }); // remove empty parents external_jQuery_default().each(emptyParents, function (idx, node) { dom.remove(node, false); }); return new WrappedRange(point.node, point.offset, point.node, point.offset).normalize(); } /** * makeIsOn: return isOn(pred) function */ }, { key: "makeIsOn", value: function makeIsOn(pred) { return function () { var ancestor = dom.ancestor(this.sc, pred); return !!ancestor && ancestor === dom.ancestor(this.ec, pred); }; } /** * @param {Function} pred * @return {Boolean} */ }, { key: "isLeftEdgeOf", value: function isLeftEdgeOf(pred) { if (!dom.isLeftEdgePoint(this.getStartPoint())) { return false; } var node = dom.ancestor(this.sc, pred); return node && dom.isLeftEdgeOf(this.sc, node); } /** * returns whether range was collapsed or not */ }, { key: "isCollapsed", value: function isCollapsed() { return this.sc === this.ec && this.so === this.eo; } /** * wrap inline nodes which children of body with paragraph * * @return {WrappedRange} */ }, { key: "wrapBodyInlineWithPara", value: function wrapBodyInlineWithPara() { if (dom.isBodyContainer(this.sc) && dom.isEmpty(this.sc)) { this.sc.innerHTML = dom.emptyPara; return new WrappedRange(this.sc.firstChild, 0, this.sc.firstChild, 0); } /** * [workaround] firefox often create range on not visible point. so normalize here. * - firefox: |<p>text</p>| * - chrome: <p>|text|</p> */ var rng = this.normalize(); if (dom.isParaInline(this.sc) || dom.isPara(this.sc)) { return rng; } // find inline top ancestor var topAncestor; if (dom.isInline(rng.sc)) { var ancestors = dom.listAncestor(rng.sc, func.not(dom.isInline)); topAncestor = lists.last(ancestors); if (!dom.isInline(topAncestor)) { topAncestor = ancestors[ancestors.length - 2] || rng.sc.childNodes[rng.so]; } } else { topAncestor = rng.sc.childNodes[rng.so > 0 ? rng.so - 1 : 0]; } if (topAncestor) { // siblings not in paragraph var inlineSiblings = dom.listPrev(topAncestor, dom.isParaInline).reverse(); inlineSiblings = inlineSiblings.concat(dom.listNext(topAncestor.nextSibling, dom.isParaInline)); // wrap with paragraph if (inlineSiblings.length) { var para = dom.wrap(lists.head(inlineSiblings), 'p'); dom.appendChildNodes(para, lists.tail(inlineSiblings)); } } return this.normalize(); } /** * insert node at current cursor * * @param {Node} node * @return {Node} */ }, { key: "insertNode", value: function insertNode(node) { var rng = this; if (dom.isText(node) || dom.isInline(node)) { rng = this.wrapBodyInlineWithPara().deleteContents(); } var info = dom.splitPoint(rng.getStartPoint(), dom.isInline(node)); if (info.rightNode) { info.rightNode.parentNode.insertBefore(node, info.rightNode); if (dom.isEmpty(info.rightNode) && dom.isPara(node)) { info.rightNode.parentNode.removeChild(info.rightNode); } } else { info.container.appendChild(node); } return node; } /** * insert html at current cursor */ }, { key: "pasteHTML", value: function pasteHTML(markup) { markup = external_jQuery_default().trim(markup); var contentsContainer = external_jQuery_default()('<div></div>').html(markup)[0]; var childNodes = lists.from(contentsContainer.childNodes); // const rng = this.wrapBodyInlineWithPara().deleteContents(); var rng = this; var reversed = false; if (rng.so >= 0) { childNodes = childNodes.reverse(); reversed = true; } childNodes = childNodes.map(function (childNode) { return rng.insertNode(childNode); }); if (reversed) { childNodes = childNodes.reverse(); } return childNodes; } /** * returns text in range * * @return {String} */ }, { key: "toString", value: function toString() { var nativeRng = this.nativeRange(); return env.isW3CRangeSupport ? nativeRng.toString() : nativeRng.text; } /** * returns range for word before cursor * * @param {Boolean} [findAfter] - find after cursor, default: false * @return {WrappedRange} */ }, { key: "getWordRange", value: function getWordRange(findAfter) { var endPoint = this.getEndPoint(); if (!dom.isCharPoint(endPoint)) { return this; } var startPoint = dom.prevPointUntil(endPoint, function (point) { return !dom.isCharPoint(point); }); if (findAfter) { endPoint = dom.nextPointUntil(endPoint, function (point) { return !dom.isCharPoint(point); }); } return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns range for words before cursor * * @param {Boolean} [findAfter] - find after cursor, default: false * @return {WrappedRange} */ }, { key: "getWordsRange", value: function getWordsRange(findAfter) { var endPoint = this.getEndPoint(); var isNotTextPoint = function isNotTextPoint(point) { return !dom.isCharPoint(point) && !dom.isSpacePoint(point); }; if (isNotTextPoint(endPoint)) { return this; } var startPoint = dom.prevPointUntil(endPoint, isNotTextPoint); if (findAfter) { endPoint = dom.nextPointUntil(endPoint, isNotTextPoint); } return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns range for words before cursor that match with a Regex * * example: * range: 'hi @Peter Pan' * regex: '/@[a-z ]+/i' * return range: '@Peter Pan' * * @param {RegExp} [regex] * @return {WrappedRange|null} */ }, { key: "getWordsMatchRange", value: function getWordsMatchRange(regex) { var endPoint = this.getEndPoint(); var startPoint = dom.prevPointUntil(endPoint, function (point) { if (!dom.isCharPoint(point) && !dom.isSpacePoint(point)) { return true; } var rng = new WrappedRange(point.node, point.offset, endPoint.node, endPoint.offset); var result = regex.exec(rng.toString()); return result && result.index === 0; }); var rng = new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); var text = rng.toString(); var result = regex.exec(text); if (result && result[0].length === text.length) { return rng; } else { return null; } } /** * create offsetPath bookmark * * @param {Node} editable */ }, { key: "bookmark", value: function bookmark(editable) { return { s: { path: dom.makeOffsetPath(editable, this.sc), offset: this.so }, e: { path: dom.makeOffsetPath(editable, this.ec), offset: this.eo } }; } /** * create offsetPath bookmark base on paragraph * * @param {Node[]} paras */ }, { key: "paraBookmark", value: function paraBookmark(paras) { return { s: { path: lists.tail(dom.makeOffsetPath(lists.head(paras), this.sc)), offset: this.so }, e: { path: lists.tail(dom.makeOffsetPath(lists.last(paras), this.ec)), offset: this.eo } }; } /** * getClientRects * @return {Rect[]} */ }, { key: "getClientRects", value: function getClientRects() { var nativeRng = this.nativeRange(); return nativeRng.getClientRects(); } }]); return WrappedRange; }(); /** * Data structure * * BoundaryPoint: a point of dom tree * * BoundaryPoints: two boundaryPoints corresponding to the start and the end of the Range * * See to http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Position */ /* harmony default export */ const range = ({ /** * create Range Object From arguments or Browser Selection * * @param {Node} sc - start container * @param {Number} so - start offset * @param {Node} ec - end container * @param {Number} eo - end offset * @return {WrappedRange} */ create: function create(sc, so, ec, eo) { if (arguments.length === 4) { return new WrappedRange(sc, so, ec, eo); } else if (arguments.length === 2) { // collapsed ec = sc; eo = so; return new WrappedRange(sc, so, ec, eo); } else { var wrappedRange = this.createFromSelection(); if (!wrappedRange && arguments.length === 1) { var bodyElement = arguments[0]; if (dom.isEditable(bodyElement)) { bodyElement = bodyElement.lastChild; } return this.createFromBodyElement(bodyElement, dom.emptyPara === arguments[0].innerHTML); } return wrappedRange; } }, createFromBodyElement: function createFromBodyElement(bodyElement) { var isCollapseToStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var wrappedRange = this.createFromNode(bodyElement); return wrappedRange.collapse(isCollapseToStart); }, createFromSelection: function createFromSelection() { var sc, so, ec, eo; if (env.isW3CRangeSupport) { var selection = document.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } else if (dom.isBody(selection.anchorNode)) { // Firefox: returns entire body as range on initialization. // We won't never need it. return null; } var nativeRng = selection.getRangeAt(0); sc = nativeRng.startContainer; so = nativeRng.startOffset; ec = nativeRng.endContainer; eo = nativeRng.endOffset; } else { // IE8: TextRange var textRange = document.selection.createRange(); var textRangeEnd = textRange.duplicate(); textRangeEnd.collapse(false); var textRangeStart = textRange; textRangeStart.collapse(true); var startPoint = textRangeToPoint(textRangeStart, true); var endPoint = textRangeToPoint(textRangeEnd, false); // same visible point case: range was collapsed. if (dom.isText(startPoint.node) && dom.isLeftEdgePoint(startPoint) && dom.isTextNode(endPoint.node) && dom.isRightEdgePoint(endPoint) && endPoint.node.nextSibling === startPoint.node) { startPoint = endPoint; } sc = startPoint.cont; so = startPoint.offset; ec = endPoint.cont; eo = endPoint.offset; } return new WrappedRange(sc, so, ec, eo); }, /** * @method * * create WrappedRange from node * * @param {Node} node * @return {WrappedRange} */ createFromNode: function createFromNode(node) { var sc = node; var so = 0; var ec = node; var eo = dom.nodeLength(ec); // browsers can't target a picture or void node if (dom.isVoid(sc)) { so = dom.listPrev(sc).length - 1; sc = sc.parentNode; } if (dom.isBR(ec)) { eo = dom.listPrev(ec).length - 1; ec = ec.parentNode; } else if (dom.isVoid(ec)) { eo = dom.listPrev(ec).length; ec = ec.parentNode; } return this.create(sc, so, ec, eo); }, /** * create WrappedRange from node after position * * @param {Node} node * @return {WrappedRange} */ createFromNodeBefore: function createFromNodeBefore(node) { return this.createFromNode(node).collapse(true); }, /** * create WrappedRange from node after position * * @param {Node} node * @return {WrappedRange} */ createFromNodeAfter: function createFromNodeAfter(node) { return this.createFromNode(node).collapse(); }, /** * @method * * create WrappedRange from bookmark * * @param {Node} editable * @param {Object} bookmark * @return {WrappedRange} */ createFromBookmark: function createFromBookmark(editable, bookmark) { var sc = dom.fromOffsetPath(editable, bookmark.s.path); var so = bookmark.s.offset; var ec = dom.fromOffsetPath(editable, bookmark.e.path); var eo = bookmark.e.offset; return new WrappedRange(sc, so, ec, eo); }, /** * @method * * create WrappedRange from paraBookmark * * @param {Object} bookmark * @param {Node[]} paras * @return {WrappedRange} */ createFromParaBookmark: function createFromParaBookmark(bookmark, paras) { var so = bookmark.s.offset; var eo = bookmark.e.offset; var sc = dom.fromOffsetPath(lists.head(paras), bookmark.s.path); var ec = dom.fromOffsetPath(lists.last(paras), bookmark.e.path); return new WrappedRange(sc, so, ec, eo); } }); ;// CONCATENATED MODULE: ./src/js/core/key.js var KEY_MAP = { 'BACKSPACE': 8, 'TAB': 9, 'ENTER': 13, 'ESCAPE': 27, 'SPACE': 32, 'DELETE': 46, // Arrow 'LEFT': 37, 'UP': 38, 'RIGHT': 39, 'DOWN': 40, // Number: 0-9 'NUM0': 48, 'NUM1': 49, 'NUM2': 50, 'NUM3': 51, 'NUM4': 52, 'NUM5': 53, 'NUM6': 54, 'NUM7': 55, 'NUM8': 56, // Alphabet: a-z 'B': 66, 'E': 69, 'I': 73, 'J': 74, 'K': 75, 'L': 76, 'R': 82, 'S': 83, 'U': 85, 'V': 86, 'Y': 89, 'Z': 90, 'SLASH': 191, 'LEFTBRACKET': 219, 'BACKSLASH': 220, 'RIGHTBRACKET': 221, // Navigation 'HOME': 36, 'END': 35, 'PAGEUP': 33, 'PAGEDOWN': 34 }; /** * @class core.key * * Object for keycodes. * * @singleton * @alternateClassName key */ /* harmony default export */ const key = ({ /** * @method isEdit * * @param {Number} keyCode * @return {Boolean} */ isEdit: function isEdit(keyCode) { return lists.contains([KEY_MAP.BACKSPACE, KEY_MAP.TAB, KEY_MAP.ENTER, KEY_MAP.SPACE, KEY_MAP.DELETE], keyCode); }, /** * @method isMove * * @param {Number} keyCode * @return {Boolean} */ isMove: function isMove(keyCode) { return lists.contains([KEY_MAP.LEFT, KEY_MAP.UP, KEY_MAP.RIGHT, KEY_MAP.DOWN], keyCode); }, /** * @method isNavigation * * @param {Number} keyCode * @return {Boolean} */ isNavigation: function isNavigation(keyCode) { return lists.contains([KEY_MAP.HOME, KEY_MAP.END, KEY_MAP.PAGEUP, KEY_MAP.PAGEDOWN], keyCode); }, /** * @property {Object} nameFromCode * @property {String} nameFromCode.8 "BACKSPACE" */ nameFromCode: func.invertObject(KEY_MAP), code: KEY_MAP }); ;// CONCATENATED MODULE: ./src/js/core/async.js /** * @method readFileAsDataURL * * read contents of file as representing URL * * @param {File} file * @return {Promise} - then: dataUrl */ function readFileAsDataURL(file) { return external_jQuery_default().Deferred(function (deferred) { external_jQuery_default().extend(new FileReader(), { onload: function onload(e) { var dataURL = e.target.result; deferred.resolve(dataURL); }, onerror: function onerror(err) { deferred.reject(err); } }).readAsDataURL(file); }).promise(); } /** * @method createImage * * create `<image>` from url string * * @param {String} url * @return {Promise} - then: $image */ function createImage(url) { return external_jQuery_default().Deferred(function (deferred) { var $img = external_jQuery_default()('<img>'); $img.one('load', function () { $img.off('error abort'); deferred.resolve($img); }).one('error abort', function () { $img.off('load').detach(); deferred.reject($img); }).css({ display: 'none' }).appendTo(document.body).attr('src', url); }).promise(); } ;// CONCATENATED MODULE: ./src/js/editing/History.js function History_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function History_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function History_createClass(Constructor, protoProps, staticProps) { if (protoProps) History_defineProperties(Constructor.prototype, protoProps); if (staticProps) History_defineProperties(Constructor, staticProps); return Constructor; } var History = /*#__PURE__*/function () { function History(context) { History_classCallCheck(this, History); this.stack = []; this.stackOffset = -1; this.context = context; this.$editable = context.layoutInfo.editable; this.editable = this.$editable[0]; } History_createClass(History, [{ key: "makeSnapshot", value: function makeSnapshot() { var rng = range.create(this.editable); var emptyBookmark = { s: { path: [], offset: 0 }, e: { path: [], offset: 0 } }; return { contents: this.$editable.html(), bookmark: rng && rng.isOnEditable() ? rng.bookmark(this.editable) : emptyBookmark }; } }, { key: "applySnapshot", value: function applySnapshot(snapshot) { if (snapshot.contents !== null) { this.$editable.html(snapshot.contents); } if (snapshot.bookmark !== null) { range.createFromBookmark(this.editable, snapshot.bookmark).select(); } } /** * @method rewind * Rewinds the history stack back to the first snapshot taken. * Leaves the stack intact, so that "Redo" can still be used. */ }, { key: "rewind", value: function rewind() { // Create snap shot if not yet recorded if (this.$editable.html() !== this.stack[this.stackOffset].contents) { this.recordUndo(); } // Return to the first available snapshot. this.stackOffset = 0; // Apply that snapshot. this.applySnapshot(this.stack[this.stackOffset]); } /** * @method commit * Resets history stack, but keeps current editor's content. */ }, { key: "commit", value: function commit() { // Clear the stack. this.stack = []; // Restore stackOffset to its original value. this.stackOffset = -1; // Record our first snapshot (of nothing). this.recordUndo(); } /** * @method reset * Resets the history stack completely; reverting to an empty editor. */ }, { key: "reset", value: function reset() { // Clear the stack. this.stack = []; // Restore stackOffset to its original value. this.stackOffset = -1; // Clear the editable area. this.$editable.html(''); // Record our first snapshot (of nothing). this.recordUndo(); } /** * undo */ }, { key: "undo", value: function undo() { // Create snap shot if not yet recorded if (this.$editable.html() !== this.stack[this.stackOffset].contents) { this.recordUndo(); } if (this.stackOffset > 0) { this.stackOffset--; this.applySnapshot(this.stack[this.stackOffset]); } } /** * redo */ }, { key: "redo", value: function redo() { if (this.stack.length - 1 > this.stackOffset) { this.stackOffset++; this.applySnapshot(this.stack[this.stackOffset]); } } /** * recorded undo */ }, { key: "recordUndo", value: function recordUndo() { this.stackOffset++; // Wash out stack after stackOffset if (this.stack.length > this.stackOffset) { this.stack = this.stack.slice(0, this.stackOffset); } // Create new snapshot and push it to the end this.stack.push(this.makeSnapshot()); // If the stack size reachs to the limit, then slice it if (this.stack.length > this.context.options.historyLimit) { this.stack.shift(); this.stackOffset -= 1; } } }]); return History; }(); ;// CONCATENATED MODULE: ./src/js/editing/Style.js function Style_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Style_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Style_createClass(Constructor, protoProps, staticProps) { if (protoProps) Style_defineProperties(Constructor.prototype, protoProps); if (staticProps) Style_defineProperties(Constructor, staticProps); return Constructor; } var Style = /*#__PURE__*/function () { function Style() { Style_classCallCheck(this, Style); } Style_createClass(Style, [{ key: "jQueryCSS", value: /** * @method jQueryCSS * * [workaround] for old jQuery * passing an array of style properties to .css() * will result in an object of property-value pairs. * (compability with version < 1.9) * * @private * @param {jQuery} $obj * @param {Array} propertyNames - An array of one or more CSS properties. * @return {Object} */ function jQueryCSS($obj, propertyNames) { var result = {}; external_jQuery_default().each(propertyNames, function (idx, propertyName) { result[propertyName] = $obj.css(propertyName); }); return result; } /** * returns style object from node * * @param {jQuery} $node * @return {Object} */ }, { key: "fromNode", value: function fromNode($node) { var properties = ['font-family', 'font-size', 'text-align', 'list-style-type', 'line-height']; var styleInfo = this.jQueryCSS($node, properties) || {}; var fontSize = $node[0].style.fontSize || styleInfo['font-size']; styleInfo['font-size'] = parseInt(fontSize, 10); styleInfo['font-size-unit'] = fontSize.match(/[a-z%]+$/); return styleInfo; } /** * paragraph level style * * @param {WrappedRange} rng * @param {Object} styleInfo */ }, { key: "stylePara", value: function stylePara(rng, styleInfo) { external_jQuery_default().each(rng.nodes(dom.isPara, { includeAncestor: true }), function (idx, para) { external_jQuery_default()(para).css(styleInfo); }); } /** * insert and returns styleNodes on range. * * @param {WrappedRange} rng * @param {Object} [options] - options for styleNodes * @param {String} [options.nodeName] - default: `SPAN` * @param {Boolean} [options.expandClosestSibling] - default: `false` * @param {Boolean} [options.onlyPartialContains] - default: `false` * @return {Node[]} */ }, { key: "styleNodes", value: function styleNodes(rng, options) { rng = rng.splitText(); var nodeName = options && options.nodeName || 'SPAN'; var expandClosestSibling = !!(options && options.expandClosestSibling); var onlyPartialContains = !!(options && options.onlyPartialContains); if (rng.isCollapsed()) { return [rng.insertNode(dom.create(nodeName))]; } var pred = dom.makePredByNodeName(nodeName); var nodes = rng.nodes(dom.isText, { fullyContains: true }).map(function (text) { return dom.singleChildAncestor(text, pred) || dom.wrap(text, nodeName); }); if (expandClosestSibling) { if (onlyPartialContains) { var nodesInRange = rng.nodes(); // compose with partial contains predication pred = func.and(pred, function (node) { return lists.contains(nodesInRange, node); }); } return nodes.map(function (node) { var siblings = dom.withClosestSiblings(node, pred); var head = lists.head(siblings); var tails = lists.tail(siblings); external_jQuery_default().each(tails, function (idx, elem) { dom.appendChildNodes(head, elem.childNodes); dom.remove(elem); }); return lists.head(siblings); }); } else { return nodes; } } /** * get current style on cursor * * @param {WrappedRange} rng * @return {Object} - object contains style properties. */ }, { key: "current", value: function current(rng) { var $cont = external_jQuery_default()(!dom.isElement(rng.sc) ? rng.sc.parentNode : rng.sc); var styleInfo = this.fromNode($cont); // document.queryCommandState for toggle state // [workaround] prevent Firefox nsresult: "0x80004005 (NS_ERROR_FAILURE)" try { styleInfo = external_jQuery_default().extend(styleInfo, { 'font-bold': document.queryCommandState('bold') ? 'bold' : 'normal', 'font-italic': document.queryCommandState('italic') ? 'italic' : 'normal', 'font-underline': document.queryCommandState('underline') ? 'underline' : 'normal', 'font-subscript': document.queryCommandState('subscript') ? 'subscript' : 'normal', 'font-superscript': document.queryCommandState('superscript') ? 'superscript' : 'normal', 'font-strikethrough': document.queryCommandState('strikethrough') ? 'strikethrough' : 'normal', 'font-family': document.queryCommandValue('fontname') || styleInfo['font-family'] }); } catch (e) {// eslint-disable-next-line } // list-style-type to list-style(unordered, ordered) if (!rng.isOnList()) { styleInfo['list-style'] = 'none'; } else { var orderedTypes = ['circle', 'disc', 'disc-leading-zero', 'square']; var isUnordered = orderedTypes.indexOf(styleInfo['list-style-type']) > -1; styleInfo['list-style'] = isUnordered ? 'unordered' : 'ordered'; } var para = dom.ancestor(rng.sc, dom.isPara); if (para && para.style['line-height']) { styleInfo['line-height'] = para.style.lineHeight; } else { var lineHeight = parseInt(styleInfo['line-height'], 10) / parseInt(styleInfo['font-size'], 10); styleInfo['line-height'] = lineHeight.toFixed(1); } styleInfo.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor); styleInfo.ancestors = dom.listAncestor(rng.sc, dom.isEditable); styleInfo.range = rng; return styleInfo; } }]); return Style; }(); ;// CONCATENATED MODULE: ./src/js/editing/Bullet.js function Bullet_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Bullet_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Bullet_createClass(Constructor, protoProps, staticProps) { if (protoProps) Bullet_defineProperties(Constructor.prototype, protoProps); if (staticProps) Bullet_defineProperties(Constructor, staticProps); return Constructor; } var Bullet = /*#__PURE__*/function () { function Bullet() { Bullet_classCallCheck(this, Bullet); } Bullet_createClass(Bullet, [{ key: "insertOrderedList", value: /** * toggle ordered list */ function insertOrderedList(editable) { this.toggleList('OL', editable); } /** * toggle unordered list */ }, { key: "insertUnorderedList", value: function insertUnorderedList(editable) { this.toggleList('UL', editable); } /** * indent */ }, { key: "indent", value: function indent(editable) { var _this = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); if (dom.isLi(head)) { var previousList = _this.findList(head.previousSibling); if (previousList) { paras.map(function (para) { return previousList.appendChild(para); }); } else { _this.wrapList(paras, head.parentNode.nodeName); paras.map(function (para) { return para.parentNode; }).map(function (para) { return _this.appendToPrevious(para); }); } } else { external_jQuery_default().each(paras, function (idx, para) { external_jQuery_default()(para).css('marginLeft', function (idx, val) { return (parseInt(val, 10) || 0) + 25; }); }); } }); rng.select(); } /** * outdent */ }, { key: "outdent", value: function outdent(editable) { var _this2 = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); if (dom.isLi(head)) { _this2.releaseList([paras]); } else { external_jQuery_default().each(paras, function (idx, para) { external_jQuery_default()(para).css('marginLeft', function (idx, val) { val = parseInt(val, 10) || 0; return val > 25 ? val - 25 : ''; }); }); } }); rng.select(); } /** * toggle list * * @param {String} listName - OL or UL */ }, { key: "toggleList", value: function toggleList(listName, editable) { var _this3 = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var bookmark = rng.paraBookmark(paras); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); // paragraph to list if (lists.find(paras, dom.isPurePara)) { var wrappedParas = []; external_jQuery_default().each(clustereds, function (idx, paras) { wrappedParas = wrappedParas.concat(_this3.wrapList(paras, listName)); }); paras = wrappedParas; // list to paragraph or change list style } else { var diffLists = rng.nodes(dom.isList, { includeAncestor: true }).filter(function (listNode) { return !external_jQuery_default().nodeName(listNode, listName); }); if (diffLists.length) { external_jQuery_default().each(diffLists, function (idx, listNode) { dom.replace(listNode, listName); }); } else { paras = this.releaseList(clustereds, true); } } range.createFromParaBookmark(bookmark, paras).select(); } /** * @param {Node[]} paras * @param {String} listName * @return {Node[]} */ }, { key: "wrapList", value: function wrapList(paras, listName) { var head = lists.head(paras); var last = lists.last(paras); var prevList = dom.isList(head.previousSibling) && head.previousSibling; var nextList = dom.isList(last.nextSibling) && last.nextSibling; var listNode = prevList || dom.insertAfter(dom.create(listName || 'UL'), last); // P to LI paras = paras.map(function (para) { return dom.isPurePara(para) ? dom.replace(para, 'LI') : para; }); // append to list(<ul>, <ol>) dom.appendChildNodes(listNode, paras); if (nextList) { dom.appendChildNodes(listNode, lists.from(nextList.childNodes)); dom.remove(nextList); } return paras; } /** * @method releaseList * * @param {Array[]} clustereds * @param {Boolean} isEscapseToBody * @return {Node[]} */ }, { key: "releaseList", value: function releaseList(clustereds, isEscapseToBody) { var _this4 = this; var releasedParas = []; external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); var last = lists.last(paras); var headList = isEscapseToBody ? dom.lastAncestor(head, dom.isList) : head.parentNode; var parentItem = headList.parentNode; if (headList.parentNode.nodeName === 'LI') { paras.map(function (para) { var newList = _this4.findNextSiblings(para); if (parentItem.nextSibling) { parentItem.parentNode.insertBefore(para, parentItem.nextSibling); } else { parentItem.parentNode.appendChild(para); } if (newList.length) { _this4.wrapList(newList, headList.nodeName); para.appendChild(newList[0].parentNode); } }); if (headList.children.length === 0) { parentItem.removeChild(headList); } if (parentItem.childNodes.length === 0) { parentItem.parentNode.removeChild(parentItem); } } else { var lastList = headList.childNodes.length > 1 ? dom.splitTree(headList, { node: last.parentNode, offset: dom.position(last) + 1 }, { isSkipPaddingBlankHTML: true }) : null; var middleList = dom.splitTree(headList, { node: head.parentNode, offset: dom.position(head) }, { isSkipPaddingBlankHTML: true }); paras = isEscapseToBody ? dom.listDescendant(middleList, dom.isLi) : lists.from(middleList.childNodes).filter(dom.isLi); // LI to P if (isEscapseToBody || !dom.isList(headList.parentNode)) { paras = paras.map(function (para) { return dom.replace(para, 'P'); }); } external_jQuery_default().each(lists.from(paras).reverse(), function (idx, para) { dom.insertAfter(para, headList); }); // remove empty lists var rootLists = lists.compact([headList, middleList, lastList]); external_jQuery_default().each(rootLists, function (idx, rootList) { var listNodes = [rootList].concat(dom.listDescendant(rootList, dom.isList)); external_jQuery_default().each(listNodes.reverse(), function (idx, listNode) { if (!dom.nodeLength(listNode)) { dom.remove(listNode, true); } }); }); } releasedParas = releasedParas.concat(paras); }); return releasedParas; } /** * @method appendToPrevious * * Appends list to previous list item, if * none exist it wraps the list in a new list item. * * @param {HTMLNode} ListItem * @return {HTMLNode} */ }, { key: "appendToPrevious", value: function appendToPrevious(node) { return node.previousSibling ? dom.appendChildNodes(node.previousSibling, [node]) : this.wrapList([node], 'LI'); } /** * @method findList * * Finds an existing list in list item * * @param {HTMLNode} ListItem * @return {Array[]} */ }, { key: "findList", value: function findList(node) { return node ? lists.find(node.children, function (child) { return ['OL', 'UL'].indexOf(child.nodeName) > -1; }) : null; } /** * @method findNextSiblings * * Finds all list item siblings that follow it * * @param {HTMLNode} ListItem * @return {HTMLNode} */ }, { key: "findNextSiblings", value: function findNextSiblings(node) { var siblings = []; while (node.nextSibling) { siblings.push(node.nextSibling); node = node.nextSibling; } return siblings; } }]); return Bullet; }(); ;// CONCATENATED MODULE: ./src/js/editing/Typing.js function Typing_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Typing_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Typing_createClass(Constructor, protoProps, staticProps) { if (protoProps) Typing_defineProperties(Constructor.prototype, protoProps); if (staticProps) Typing_defineProperties(Constructor, staticProps); return Constructor; } /** * @class editing.Typing * * Typing * */ var Typing = /*#__PURE__*/function () { function Typing(context) { Typing_classCallCheck(this, Typing); // a Bullet instance to toggle lists off this.bullet = new Bullet(); this.options = context.options; } /** * insert tab * * @param {WrappedRange} rng * @param {Number} tabsize */ Typing_createClass(Typing, [{ key: "insertTab", value: function insertTab(rng, tabsize) { var tab = dom.createText(new Array(tabsize + 1).join(dom.NBSP_CHAR)); rng = rng.deleteContents(); rng.insertNode(tab, true); rng = range.create(tab, tabsize); rng.select(); } /** * insert paragraph * * @param {jQuery} $editable * @param {WrappedRange} rng Can be used in unit tests to "mock" the range * * blockquoteBreakingLevel * 0 - No break, the new paragraph remains inside the quote * 1 - Break the first blockquote in the ancestors list * 2 - Break all blockquotes, so that the new paragraph is not quoted (this is the default) */ }, { key: "insertParagraph", value: function insertParagraph(editable, rng) { rng = rng || range.create(editable); // deleteContents on range. rng = rng.deleteContents(); // Wrap range if it needs to be wrapped by paragraph rng = rng.wrapBodyInlineWithPara(); // finding paragraph var splitRoot = dom.ancestor(rng.sc, dom.isPara); var nextPara; // on paragraph: split paragraph if (splitRoot) { // if it is an empty line with li if (dom.isLi(splitRoot) && (dom.isEmpty(splitRoot) || dom.deepestChildIsEmpty(splitRoot))) { // toggle UL/OL and escape this.bullet.toggleList(splitRoot.parentNode.nodeName); return; } else { var blockquote = null; if (this.options.blockquoteBreakingLevel === 1) { blockquote = dom.ancestor(splitRoot, dom.isBlockquote); } else if (this.options.blockquoteBreakingLevel === 2) { blockquote = dom.lastAncestor(splitRoot, dom.isBlockquote); } if (blockquote) { // We're inside a blockquote and options ask us to break it nextPara = external_jQuery_default()(dom.emptyPara)[0]; // If the split is right before a <br>, remove it so that there's no "empty line" // after the split in the new blockquote created if (dom.isRightEdgePoint(rng.getStartPoint()) && dom.isBR(rng.sc.nextSibling)) { external_jQuery_default()(rng.sc.nextSibling).remove(); } var split = dom.splitTree(blockquote, rng.getStartPoint(), { isDiscardEmptySplits: true }); if (split) { split.parentNode.insertBefore(nextPara, split); } else { dom.insertAfter(nextPara, blockquote); // There's no split if we were at the end of the blockquote } } else { nextPara = dom.splitTree(splitRoot, rng.getStartPoint()); // not a blockquote, just insert the paragraph var emptyAnchors = dom.listDescendant(splitRoot, dom.isEmptyAnchor); emptyAnchors = emptyAnchors.concat(dom.listDescendant(nextPara, dom.isEmptyAnchor)); external_jQuery_default().each(emptyAnchors, function (idx, anchor) { dom.remove(anchor); }); // replace empty heading, pre or custom-made styleTag with P tag if ((dom.isHeading(nextPara) || dom.isPre(nextPara) || dom.isCustomStyleTag(nextPara)) && dom.isEmpty(nextPara)) { nextPara = dom.replace(nextPara, 'p'); } } } // no paragraph: insert empty paragraph } else { var next = rng.sc.childNodes[rng.so]; nextPara = external_jQuery_default()(dom.emptyPara)[0]; if (next) { rng.sc.insertBefore(nextPara, next); } else { rng.sc.appendChild(nextPara); } } range.create(nextPara, 0).normalize().select().scrollIntoView(editable); } }]); return Typing; }(); ;// CONCATENATED MODULE: ./src/js/editing/Table.js function Table_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Table_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Table_createClass(Constructor, protoProps, staticProps) { if (protoProps) Table_defineProperties(Constructor.prototype, protoProps); if (staticProps) Table_defineProperties(Constructor, staticProps); return Constructor; } /** * @class Create a virtual table to create what actions to do in change. * @param {object} startPoint Cell selected to apply change. * @param {enum} where Where change will be applied Row or Col. Use enum: TableResultAction.where * @param {enum} action Action to be applied. Use enum: TableResultAction.requestAction * @param {object} domTable Dom element of table to make changes. */ var TableResultAction = function TableResultAction(startPoint, where, action, domTable) { var _startPoint = { 'colPos': 0, 'rowPos': 0 }; var _virtualTable = []; var _actionCellList = []; /// /////////////////////////////////////////// // Private functions /// /////////////////////////////////////////// /** * Set the startPoint of action. */ function setStartPoint() { if (!startPoint || !startPoint.tagName || startPoint.tagName.toLowerCase() !== 'td' && startPoint.tagName.toLowerCase() !== 'th') { // Impossible to identify start Cell point return; } _startPoint.colPos = startPoint.cellIndex; if (!startPoint.parentElement || !startPoint.parentElement.tagName || startPoint.parentElement.tagName.toLowerCase() !== 'tr') { // Impossible to identify start Row point return; } _startPoint.rowPos = startPoint.parentElement.rowIndex; } /** * Define virtual table position info object. * * @param {int} rowIndex Index position in line of virtual table. * @param {int} cellIndex Index position in column of virtual table. * @param {object} baseRow Row affected by this position. * @param {object} baseCell Cell affected by this position. * @param {bool} isSpan Inform if it is an span cell/row. */ function setVirtualTablePosition(rowIndex, cellIndex, baseRow, baseCell, isRowSpan, isColSpan, isVirtualCell) { var objPosition = { 'baseRow': baseRow, 'baseCell': baseCell, 'isRowSpan': isRowSpan, 'isColSpan': isColSpan, 'isVirtual': isVirtualCell }; if (!_virtualTable[rowIndex]) { _virtualTable[rowIndex] = []; } _virtualTable[rowIndex][cellIndex] = objPosition; } /** * Create action cell object. * * @param {object} virtualTableCellObj Object of specific position on virtual table. * @param {enum} resultAction Action to be applied in that item. */ function getActionCell(virtualTableCellObj, resultAction, virtualRowPosition, virtualColPosition) { return { 'baseCell': virtualTableCellObj.baseCell, 'action': resultAction, 'virtualTable': { 'rowIndex': virtualRowPosition, 'cellIndex': virtualColPosition } }; } /** * Recover free index of row to append Cell. * * @param {int} rowIndex Index of row to find free space. * @param {int} cellIndex Index of cell to find free space in table. */ function recoverCellIndex(rowIndex, cellIndex) { if (!_virtualTable[rowIndex]) { return cellIndex; } if (!_virtualTable[rowIndex][cellIndex]) { return cellIndex; } var newCellIndex = cellIndex; while (_virtualTable[rowIndex][newCellIndex]) { newCellIndex++; if (!_virtualTable[rowIndex][newCellIndex]) { return newCellIndex; } } } /** * Recover info about row and cell and add information to virtual table. * * @param {object} row Row to recover information. * @param {object} cell Cell to recover information. */ function addCellInfoToVirtual(row, cell) { var cellIndex = recoverCellIndex(row.rowIndex, cell.cellIndex); var cellHasColspan = cell.colSpan > 1; var cellHasRowspan = cell.rowSpan > 1; var isThisSelectedCell = row.rowIndex === _startPoint.rowPos && cell.cellIndex === _startPoint.colPos; setVirtualTablePosition(row.rowIndex, cellIndex, row, cell, cellHasRowspan, cellHasColspan, false); // Add span rows to virtual Table. var rowspanNumber = cell.attributes.rowSpan ? parseInt(cell.attributes.rowSpan.value, 10) : 0; if (rowspanNumber > 1) { for (var rp = 1; rp < rowspanNumber; rp++) { var rowspanIndex = row.rowIndex + rp; adjustStartPoint(rowspanIndex, cellIndex, cell, isThisSelectedCell); setVirtualTablePosition(rowspanIndex, cellIndex, row, cell, true, cellHasColspan, true); } } // Add span cols to virtual table. var colspanNumber = cell.attributes.colSpan ? parseInt(cell.attributes.colSpan.value, 10) : 0; if (colspanNumber > 1) { for (var cp = 1; cp < colspanNumber; cp++) { var cellspanIndex = recoverCellIndex(row.rowIndex, cellIndex + cp); adjustStartPoint(row.rowIndex, cellspanIndex, cell, isThisSelectedCell); setVirtualTablePosition(row.rowIndex, cellspanIndex, row, cell, cellHasRowspan, true, true); } } } /** * Process validation and adjust of start point if needed * * @param {int} rowIndex * @param {int} cellIndex * @param {object} cell * @param {bool} isSelectedCell */ function adjustStartPoint(rowIndex, cellIndex, cell, isSelectedCell) { if (rowIndex === _startPoint.rowPos && _startPoint.colPos >= cell.cellIndex && cell.cellIndex <= cellIndex && !isSelectedCell) { _startPoint.colPos++; } } /** * Create virtual table of cells with all cells, including span cells. */ function createVirtualTable() { var rows = domTable.rows; for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) { var cells = rows[rowIndex].cells; for (var cellIndex = 0; cellIndex < cells.length; cellIndex++) { addCellInfoToVirtual(rows[rowIndex], cells[cellIndex]); } } } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getDeleteResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; case TableResultAction.where.Row: if (!cell.isVirtual && cell.isRowSpan) { return TableResultAction.resultAction.AddCell; } else if (cell.isRowSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; } return TableResultAction.resultAction.RemoveCell; } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getAddResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isRowSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; case TableResultAction.where.Row: if (cell.isRowSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isColSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; } return TableResultAction.resultAction.AddCell; } function init() { setStartPoint(); createVirtualTable(); } /// /////////////////////////////////////////// // Public functions /// /////////////////////////////////////////// /** * Recover array os what to do in table. */ this.getActionList = function () { var fixedRow = where === TableResultAction.where.Row ? _startPoint.rowPos : -1; var fixedCol = where === TableResultAction.where.Column ? _startPoint.colPos : -1; var actualPosition = 0; var canContinue = true; while (canContinue) { var rowPosition = fixedRow >= 0 ? fixedRow : actualPosition; var colPosition = fixedCol >= 0 ? fixedCol : actualPosition; var row = _virtualTable[rowPosition]; if (!row) { canContinue = false; return _actionCellList; } var cell = row[colPosition]; if (!cell) { canContinue = false; return _actionCellList; } // Define action to be applied in this cell var resultAction = TableResultAction.resultAction.Ignore; switch (action) { case TableResultAction.requestAction.Add: resultAction = getAddResultActionToCell(cell); break; case TableResultAction.requestAction.Delete: resultAction = getDeleteResultActionToCell(cell); break; } _actionCellList.push(getActionCell(cell, resultAction, rowPosition, colPosition)); actualPosition++; } return _actionCellList; }; init(); }; /** * * Where action occours enum. */ TableResultAction.where = { 'Row': 0, 'Column': 1 }; /** * * Requested action to apply enum. */ TableResultAction.requestAction = { 'Add': 0, 'Delete': 1 }; /** * * Result action to be executed enum. */ TableResultAction.resultAction = { 'Ignore': 0, 'SubtractSpanCount': 1, 'RemoveCell': 2, 'AddCell': 3, 'SumSpanCount': 4 }; /** * * @class editing.Table * * Table * */ var Table = /*#__PURE__*/function () { function Table() { Table_classCallCheck(this, Table); } Table_createClass(Table, [{ key: "tab", value: /** * handle tab key * * @param {WrappedRange} rng * @param {Boolean} isShift */ function tab(rng, isShift) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var table = dom.ancestor(cell, dom.isTable); var cells = dom.listDescendant(table, dom.isCell); var nextCell = lists[isShift ? 'prev' : 'next'](cells, cell); if (nextCell) { range.create(nextCell, 0).select(); } } /** * Add a new row * * @param {WrappedRange} rng * @param {String} position (top/bottom) * @return {Node} */ }, { key: "addRow", value: function addRow(rng, position) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var currentTr = external_jQuery_default()(cell).closest('tr'); var trAttributes = this.recoverAttributes(currentTr); var html = external_jQuery_default()('<tr' + trAttributes + '></tr>'); var vTable = new TableResultAction(cell, TableResultAction.where.Row, TableResultAction.requestAction.Add, external_jQuery_default()(currentTr).closest('table')[0]); var actions = vTable.getActionList(); for (var idCell = 0; idCell < actions.length; idCell++) { var currentCell = actions[idCell]; var tdAttributes = this.recoverAttributes(currentCell.baseCell); switch (currentCell.action) { case TableResultAction.resultAction.AddCell: html.append('<td' + tdAttributes + '>' + dom.blank + '</td>'); break; case TableResultAction.resultAction.SumSpanCount: { if (position === 'top') { var baseCellTr = currentCell.baseCell.parent; var isTopFromRowSpan = (!baseCellTr ? 0 : currentCell.baseCell.closest('tr').rowIndex) <= currentTr[0].rowIndex; if (isTopFromRowSpan) { var newTd = external_jQuery_default()('<div></div>').append(external_jQuery_default()('<td' + tdAttributes + '>' + dom.blank + '</td>').removeAttr('rowspan')).html(); html.append(newTd); break; } } var rowspanNumber = parseInt(currentCell.baseCell.rowSpan, 10); rowspanNumber++; currentCell.baseCell.setAttribute('rowSpan', rowspanNumber); } break; } } if (position === 'top') { currentTr.before(html); } else { var cellHasRowspan = cell.rowSpan > 1; if (cellHasRowspan) { var lastTrIndex = currentTr[0].rowIndex + (cell.rowSpan - 2); external_jQuery_default()(external_jQuery_default()(currentTr).parent().find('tr')[lastTrIndex]).after(external_jQuery_default()(html)); return; } currentTr.after(html); } } /** * Add a new col * * @param {WrappedRange} rng * @param {String} position (left/right) * @return {Node} */ }, { key: "addCol", value: function addCol(rng, position) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var rowsGroup = external_jQuery_default()(row).siblings(); rowsGroup.push(row); var vTable = new TableResultAction(cell, TableResultAction.where.Column, TableResultAction.requestAction.Add, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { var currentCell = actions[actionIndex]; var tdAttributes = this.recoverAttributes(currentCell.baseCell); switch (currentCell.action) { case TableResultAction.resultAction.AddCell: if (position === 'right') { external_jQuery_default()(currentCell.baseCell).after('<td' + tdAttributes + '>' + dom.blank + '</td>'); } else { external_jQuery_default()(currentCell.baseCell).before('<td' + tdAttributes + '>' + dom.blank + '</td>'); } break; case TableResultAction.resultAction.SumSpanCount: if (position === 'right') { var colspanNumber = parseInt(currentCell.baseCell.colSpan, 10); colspanNumber++; currentCell.baseCell.setAttribute('colSpan', colspanNumber); } else { external_jQuery_default()(currentCell.baseCell).before('<td' + tdAttributes + '>' + dom.blank + '</td>'); } break; } } } /* * Copy attributes from element. * * @param {object} Element to recover attributes. * @return {string} Copied string elements. */ }, { key: "recoverAttributes", value: function recoverAttributes(el) { var resultStr = ''; if (!el) { return resultStr; } var attrList = el.attributes || []; for (var i = 0; i < attrList.length; i++) { if (attrList[i].name.toLowerCase() === 'id') { continue; } if (attrList[i].specified) { resultStr += ' ' + attrList[i].name + '=\'' + attrList[i].value + '\''; } } return resultStr; } /** * Delete current row * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteRow", value: function deleteRow(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var cellPos = row.children('td, th').index(external_jQuery_default()(cell)); var rowPos = row[0].rowIndex; var vTable = new TableResultAction(cell, TableResultAction.where.Row, TableResultAction.requestAction.Delete, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { if (!actions[actionIndex]) { continue; } var baseCell = actions[actionIndex].baseCell; var virtualPosition = actions[actionIndex].virtualTable; var hasRowspan = baseCell.rowSpan && baseCell.rowSpan > 1; var rowspanNumber = hasRowspan ? parseInt(baseCell.rowSpan, 10) : 0; switch (actions[actionIndex].action) { case TableResultAction.resultAction.Ignore: continue; case TableResultAction.resultAction.AddCell: { var nextRow = row.next('tr')[0]; if (!nextRow) { continue; } var cloneRow = row[0].cells[cellPos]; if (hasRowspan) { if (rowspanNumber > 2) { rowspanNumber--; nextRow.insertBefore(cloneRow, nextRow.cells[cellPos]); nextRow.cells[cellPos].setAttribute('rowSpan', rowspanNumber); nextRow.cells[cellPos].innerHTML = ''; } else if (rowspanNumber === 2) { nextRow.insertBefore(cloneRow, nextRow.cells[cellPos]); nextRow.cells[cellPos].removeAttribute('rowSpan'); nextRow.cells[cellPos].innerHTML = ''; } } } continue; case TableResultAction.resultAction.SubtractSpanCount: if (hasRowspan) { if (rowspanNumber > 2) { rowspanNumber--; baseCell.setAttribute('rowSpan', rowspanNumber); if (virtualPosition.rowIndex !== rowPos && baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } else if (rowspanNumber === 2) { baseCell.removeAttribute('rowSpan'); if (virtualPosition.rowIndex !== rowPos && baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } } continue; case TableResultAction.resultAction.RemoveCell: // Do not need remove cell because row will be deleted. continue; } } row.remove(); } /** * Delete current col * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteCol", value: function deleteCol(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var cellPos = row.children('td, th').index(external_jQuery_default()(cell)); var vTable = new TableResultAction(cell, TableResultAction.where.Column, TableResultAction.requestAction.Delete, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { if (!actions[actionIndex]) { continue; } switch (actions[actionIndex].action) { case TableResultAction.resultAction.Ignore: continue; case TableResultAction.resultAction.SubtractSpanCount: { var baseCell = actions[actionIndex].baseCell; var hasColspan = baseCell.colSpan && baseCell.colSpan > 1; if (hasColspan) { var colspanNumber = baseCell.colSpan ? parseInt(baseCell.colSpan, 10) : 0; if (colspanNumber > 2) { colspanNumber--; baseCell.setAttribute('colSpan', colspanNumber); if (baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } else if (colspanNumber === 2) { baseCell.removeAttribute('colSpan'); if (baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } } } continue; case TableResultAction.resultAction.RemoveCell: dom.remove(actions[actionIndex].baseCell, true); continue; } } } /** * create empty table element * * @param {Number} rowCount * @param {Number} colCount * @return {Node} */ }, { key: "createTable", value: function createTable(colCount, rowCount, options) { var tds = []; var tdHTML; for (var idxCol = 0; idxCol < colCount; idxCol++) { tds.push('<td>' + dom.blank + '</td>'); } tdHTML = tds.join(''); var trs = []; var trHTML; for (var idxRow = 0; idxRow < rowCount; idxRow++) { trs.push('<tr>' + tdHTML + '</tr>'); } trHTML = trs.join(''); var $table = external_jQuery_default()('<table>' + trHTML + '</table>'); if (options && options.tableClassName) { $table.addClass(options.tableClassName); } return $table[0]; } /** * Delete current table * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteTable", value: function deleteTable(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); external_jQuery_default()(cell).closest('table').remove(); } }]); return Table; }(); ;// CONCATENATED MODULE: ./src/js/module/Editor.js function Editor_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Editor_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Editor_createClass(Constructor, protoProps, staticProps) { if (protoProps) Editor_defineProperties(Constructor.prototype, protoProps); if (staticProps) Editor_defineProperties(Constructor, staticProps); return Constructor; } var KEY_BOGUS = 'bogus'; /** * @class Editor */ var Editor = /*#__PURE__*/function () { function Editor(context) { var _this = this; Editor_classCallCheck(this, Editor); this.context = context; this.$note = context.layoutInfo.note; this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.options = context.options; this.lang = this.options.langInfo; this.editable = this.$editable[0]; this.lastRange = null; this.snapshot = null; this.style = new Style(); this.table = new Table(); this.typing = new Typing(context); this.bullet = new Bullet(); this.history = new History(context); this.context.memo('help.escape', this.lang.help.escape); this.context.memo('help.undo', this.lang.help.undo); this.context.memo('help.redo', this.lang.help.redo); this.context.memo('help.tab', this.lang.help.tab); this.context.memo('help.untab', this.lang.help.untab); this.context.memo('help.insertParagraph', this.lang.help.insertParagraph); this.context.memo('help.insertOrderedList', this.lang.help.insertOrderedList); this.context.memo('help.insertUnorderedList', this.lang.help.insertUnorderedList); this.context.memo('help.indent', this.lang.help.indent); this.context.memo('help.outdent', this.lang.help.outdent); this.context.memo('help.formatPara', this.lang.help.formatPara); this.context.memo('help.insertHorizontalRule', this.lang.help.insertHorizontalRule); this.context.memo('help.fontName', this.lang.help.fontName); // native commands(with execCommand), generate function for execCommand var commands = ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull', 'formatBlock', 'removeFormat', 'backColor']; for (var idx = 0, len = commands.length; idx < len; idx++) { this[commands[idx]] = function (sCmd) { return function (value) { _this.beforeCommand(); document.execCommand(sCmd, false, value); _this.afterCommand(true); }; }(commands[idx]); this.context.memo('help.' + commands[idx], this.lang.help[commands[idx]]); } this.fontName = this.wrapCommand(function (value) { return _this.fontStyling('font-family', env.validFontName(value)); }); this.fontSize = this.wrapCommand(function (value) { var unit = _this.currentStyle()['font-size-unit']; return _this.fontStyling('font-size', value + unit); }); this.fontSizeUnit = this.wrapCommand(function (value) { var size = _this.currentStyle()['font-size']; return _this.fontStyling('font-size', size + value); }); for (var _idx = 1; _idx <= 6; _idx++) { this['formatH' + _idx] = function (idx) { return function () { _this.formatBlock('H' + idx); }; }(_idx); this.context.memo('help.formatH' + _idx, this.lang.help['formatH' + _idx]); } this.insertParagraph = this.wrapCommand(function () { _this.typing.insertParagraph(_this.editable); }); this.insertOrderedList = this.wrapCommand(function () { _this.bullet.insertOrderedList(_this.editable); }); this.insertUnorderedList = this.wrapCommand(function () { _this.bullet.insertUnorderedList(_this.editable); }); this.indent = this.wrapCommand(function () { _this.bullet.indent(_this.editable); }); this.outdent = this.wrapCommand(function () { _this.bullet.outdent(_this.editable); }); /** * insertNode * insert node * @param {Node} node */ this.insertNode = this.wrapCommand(function (node) { if (_this.isLimited(external_jQuery_default()(node).text().length)) { return; } var rng = _this.getLastRange(); rng.insertNode(node); _this.setLastRange(range.createFromNodeAfter(node).select()); }); /** * insert text * @param {String} text */ this.insertText = this.wrapCommand(function (text) { if (_this.isLimited(text.length)) { return; } var rng = _this.getLastRange(); var textNode = rng.insertNode(dom.createText(text)); _this.setLastRange(range.create(textNode, dom.nodeLength(textNode)).select()); }); /** * paste HTML * @param {String} markup */ this.pasteHTML = this.wrapCommand(function (markup) { if (_this.isLimited(markup.length)) { return; } markup = _this.context.invoke('codeview.purify', markup); var contents = _this.getLastRange().pasteHTML(markup); _this.setLastRange(range.createFromNodeAfter(lists.last(contents)).select()); }); /** * formatBlock * * @param {String} tagName */ this.formatBlock = this.wrapCommand(function (tagName, $target) { var onApplyCustomStyle = _this.options.callbacks.onApplyCustomStyle; if (onApplyCustomStyle) { onApplyCustomStyle.call(_this, $target, _this.context, _this.onFormatBlock); } else { _this.onFormatBlock(tagName, $target); } }); /** * insert horizontal rule */ this.insertHorizontalRule = this.wrapCommand(function () { var hrNode = _this.getLastRange().insertNode(dom.create('HR')); if (hrNode.nextSibling) { _this.setLastRange(range.create(hrNode.nextSibling, 0).normalize().select()); } }); /** * lineHeight * @param {String} value */ this.lineHeight = this.wrapCommand(function (value) { _this.style.stylePara(_this.getLastRange(), { lineHeight: value }); }); /** * create link (command) * * @param {Object} linkInfo */ this.createLink = this.wrapCommand(function (linkInfo) { var linkUrl = linkInfo.url; var linkText = linkInfo.text; var isNewWindow = linkInfo.isNewWindow; var checkProtocol = linkInfo.checkProtocol; var rng = linkInfo.range || _this.getLastRange(); var additionalTextLength = linkText.length - rng.toString().length; if (additionalTextLength > 0 && _this.isLimited(additionalTextLength)) { return; } var isTextChanged = rng.toString() !== linkText; // handle spaced urls from input if (typeof linkUrl === 'string') { linkUrl = linkUrl.trim(); } if (_this.options.onCreateLink) { linkUrl = _this.options.onCreateLink(linkUrl); } else if (checkProtocol) { // if url doesn't have any protocol and not even a relative or a label, use http:// as default linkUrl = /^([A-Za-z][A-Za-z0-9+-.]*\:|#|\/)/.test(linkUrl) ? linkUrl : _this.options.defaultProtocol + linkUrl; } var anchors = []; if (isTextChanged) { rng = rng.deleteContents(); var anchor = rng.insertNode(external_jQuery_default()('<A>' + linkText + '</A>')[0]); anchors.push(anchor); } else { anchors = _this.style.styleNodes(rng, { nodeName: 'A', expandClosestSibling: true, onlyPartialContains: true }); } external_jQuery_default().each(anchors, function (idx, anchor) { external_jQuery_default()(anchor).attr('href', linkUrl); if (isNewWindow) { external_jQuery_default()(anchor).attr('target', '_blank'); } else { external_jQuery_default()(anchor).removeAttr('target'); } }); _this.setLastRange(_this.createRangeFromList(anchors).select()); }); /** * setting color * * @param {Object} sObjColor color code * @param {String} sObjColor.foreColor foreground color * @param {String} sObjColor.backColor background color */ this.color = this.wrapCommand(function (colorInfo) { var foreColor = colorInfo.foreColor; var backColor = colorInfo.backColor; if (foreColor) { document.execCommand('foreColor', false, foreColor); } if (backColor) { document.execCommand('backColor', false, backColor); } }); /** * Set foreground color * * @param {String} colorCode foreground color code */ this.foreColor = this.wrapCommand(function (colorInfo) { document.execCommand('foreColor', false, colorInfo); }); /** * insert Table * * @param {String} dimension of table (ex : "5x5") */ this.insertTable = this.wrapCommand(function (dim) { var dimension = dim.split('x'); var rng = _this.getLastRange().deleteContents(); rng.insertNode(_this.table.createTable(dimension[0], dimension[1], _this.options)); }); /** * remove media object and Figure Elements if media object is img with Figure. */ this.removeMedia = this.wrapCommand(function () { var $target = external_jQuery_default()(_this.restoreTarget()).parent(); if ($target.closest('figure').length) { $target.closest('figure').remove(); } else { $target = external_jQuery_default()(_this.restoreTarget()).detach(); } _this.context.triggerEvent('media.delete', $target, _this.$editable); }); /** * float me * * @param {String} value */ this.floatMe = this.wrapCommand(function (value) { var $target = external_jQuery_default()(_this.restoreTarget()); $target.toggleClass('note-float-left', value === 'left'); $target.toggleClass('note-float-right', value === 'right'); $target.css('float', value === 'none' ? '' : value); }); /** * resize overlay element * @param {String} value */ this.resize = this.wrapCommand(function (value) { var $target = external_jQuery_default()(_this.restoreTarget()); value = parseFloat(value); if (value === 0) { $target.css('width', ''); } else { $target.css({ width: value * 100 + '%', height: '' }); } }); } Editor_createClass(Editor, [{ key: "initialize", value: function initialize() { var _this2 = this; // bind custom events this.$editable.on('keydown', function (event) { if (event.keyCode === key.code.ENTER) { _this2.context.triggerEvent('enter', event); } _this2.context.triggerEvent('keydown', event); // keep a snapshot to limit text on input event _this2.snapshot = _this2.history.makeSnapshot(); _this2.hasKeyShortCut = false; if (!event.isDefaultPrevented()) { if (_this2.options.shortcuts) { _this2.hasKeyShortCut = _this2.handleKeyMap(event); } else { _this2.preventDefaultEditableShortCuts(event); } } if (_this2.isLimited(1, event)) { var lastRange = _this2.getLastRange(); if (lastRange.eo - lastRange.so === 0) { return false; } } _this2.setLastRange(); // record undo in the key event except keyMap. if (_this2.options.recordEveryKeystroke) { if (_this2.hasKeyShortCut === false) { _this2.history.recordUndo(); } } }).on('keyup', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('keyup', event); }).on('focus', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('focus', event); }).on('blur', function (event) { _this2.context.triggerEvent('blur', event); }).on('mousedown', function (event) { _this2.context.triggerEvent('mousedown', event); }).on('mouseup', function (event) { _this2.setLastRange(); _this2.history.recordUndo(); _this2.context.triggerEvent('mouseup', event); }).on('scroll', function (event) { _this2.context.triggerEvent('scroll', event); }).on('paste', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('paste', event); }).on('input', function () { // To limit composition characters (e.g. Korean) if (_this2.isLimited(0) && _this2.snapshot) { _this2.history.applySnapshot(_this2.snapshot); } }); this.$editable.attr('spellcheck', this.options.spellCheck); this.$editable.attr('autocorrect', this.options.spellCheck); if (this.options.disableGrammar) { this.$editable.attr('data-gramm', false); } // init content before set event this.$editable.html(dom.html(this.$note) || dom.emptyPara); this.$editable.on(env.inputEventName, func.debounce(function () { _this2.context.triggerEvent('change', _this2.$editable.html(), _this2.$editable); }, 10)); this.$editable.on('focusin', function (event) { _this2.context.triggerEvent('focusin', event); }).on('focusout', function (event) { _this2.context.triggerEvent('focusout', event); }); if (this.options.airMode) { if (this.options.overrideContextMenu) { this.$editor.on('contextmenu', function (event) { _this2.context.triggerEvent('contextmenu', event); return false; }); } } else { if (this.options.width) { this.$editor.outerWidth(this.options.width); } if (this.options.height) { this.$editable.outerHeight(this.options.height); } if (this.options.maxHeight) { this.$editable.css('max-height', this.options.maxHeight); } if (this.options.minHeight) { this.$editable.css('min-height', this.options.minHeight); } } this.history.recordUndo(); this.setLastRange(); } }, { key: "destroy", value: function destroy() { this.$editable.off(); } }, { key: "handleKeyMap", value: function handleKeyMap(event) { var keyMap = this.options.keyMap[env.isMac ? 'mac' : 'pc']; var keys = []; if (event.metaKey) { keys.push('CMD'); } if (event.ctrlKey && !event.altKey) { keys.push('CTRL'); } if (event.shiftKey) { keys.push('SHIFT'); } var keyName = key.nameFromCode[event.keyCode]; if (keyName) { keys.push(keyName); } var eventName = keyMap[keys.join('+')]; if (keyName === 'TAB' && !this.options.tabDisable) { this.afterCommand(); } else if (eventName) { if (this.context.invoke(eventName) !== false) { event.preventDefault(); // if keyMap action was invoked return true; } } else if (key.isEdit(event.keyCode)) { this.afterCommand(); } return false; } }, { key: "preventDefaultEditableShortCuts", value: function preventDefaultEditableShortCuts(event) { // B(Bold, 66) / I(Italic, 73) / U(Underline, 85) if ((event.ctrlKey || event.metaKey) && lists.contains([66, 73, 85], event.keyCode)) { event.preventDefault(); } } }, { key: "isLimited", value: function isLimited(pad, event) { pad = pad || 0; if (typeof event !== 'undefined') { if (key.isMove(event.keyCode) || key.isNavigation(event.keyCode) || event.ctrlKey || event.metaKey || lists.contains([key.code.BACKSPACE, key.code.DELETE], event.keyCode)) { return false; } } if (this.options.maxTextLength > 0) { if (this.$editable.text().length + pad > this.options.maxTextLength) { return true; } } return false; } /** * create range * @return {WrappedRange} */ }, { key: "createRange", value: function createRange() { this.focus(); this.setLastRange(); return this.getLastRange(); } /** * create a new range from the list of elements * * @param {list} dom element list * @return {WrappedRange} */ }, { key: "createRangeFromList", value: function createRangeFromList(lst) { var startRange = range.createFromNodeBefore(lists.head(lst)); var startPoint = startRange.getStartPoint(); var endRange = range.createFromNodeAfter(lists.last(lst)); var endPoint = endRange.getEndPoint(); return range.create(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * set the last range * * if given rng is exist, set rng as the last range * or create a new range at the end of the document * * @param {WrappedRange} rng */ }, { key: "setLastRange", value: function setLastRange(rng) { if (rng) { this.lastRange = rng; } else { this.lastRange = range.create(this.editable); if (external_jQuery_default()(this.lastRange.sc).closest('.note-editable').length === 0) { this.lastRange = range.createFromBodyElement(this.editable); } } } /** * get the last range * * if there is a saved last range, return it * or create a new range and return it * * @return {WrappedRange} */ }, { key: "getLastRange", value: function getLastRange() { if (!this.lastRange) { this.setLastRange(); } return this.lastRange; } /** * saveRange * * save current range * * @param {Boolean} [thenCollapse=false] */ }, { key: "saveRange", value: function saveRange(thenCollapse) { if (thenCollapse) { this.getLastRange().collapse().select(); } } /** * restoreRange * * restore lately range */ }, { key: "restoreRange", value: function restoreRange() { if (this.lastRange) { this.lastRange.select(); this.focus(); } } }, { key: "saveTarget", value: function saveTarget(node) { this.$editable.data('target', node); } }, { key: "clearTarget", value: function clearTarget() { this.$editable.removeData('target'); } }, { key: "restoreTarget", value: function restoreTarget() { return this.$editable.data('target'); } /** * currentStyle * * current style * @return {Object|Boolean} unfocus */ }, { key: "currentStyle", value: function currentStyle() { var rng = range.create(); if (rng) { rng = rng.normalize(); } return rng ? this.style.current(rng) : this.style.fromNode(this.$editable); } /** * style from node * * @param {jQuery} $node * @return {Object} */ }, { key: "styleFromNode", value: function styleFromNode($node) { return this.style.fromNode($node); } /** * undo */ }, { key: "undo", value: function undo() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.undo(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /* * commit */ }, { key: "commit", value: function commit() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.commit(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /** * redo */ }, { key: "redo", value: function redo() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.redo(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /** * before command */ }, { key: "beforeCommand", value: function beforeCommand() { this.context.triggerEvent('before.command', this.$editable.html()); // Set styleWithCSS before run a command document.execCommand('styleWithCSS', false, this.options.styleWithCSS); // keep focus on editable before command execution this.focus(); } /** * after command * @param {Boolean} isPreventTrigger */ }, { key: "afterCommand", value: function afterCommand(isPreventTrigger) { this.normalizeContent(); this.history.recordUndo(); if (!isPreventTrigger) { this.context.triggerEvent('change', this.$editable.html(), this.$editable); } } /** * handle tab key */ }, { key: "tab", value: function tab() { var rng = this.getLastRange(); if (rng.isCollapsed() && rng.isOnCell()) { this.table.tab(rng); } else { if (this.options.tabSize === 0) { return false; } if (!this.isLimited(this.options.tabSize)) { this.beforeCommand(); this.typing.insertTab(rng, this.options.tabSize); this.afterCommand(); } } } /** * handle shift+tab key */ }, { key: "untab", value: function untab() { var rng = this.getLastRange(); if (rng.isCollapsed() && rng.isOnCell()) { this.table.tab(rng, true); } else { if (this.options.tabSize === 0) { return false; } } } /** * run given function between beforeCommand and afterCommand */ }, { key: "wrapCommand", value: function wrapCommand(fn) { return function () { this.beforeCommand(); fn.apply(this, arguments); this.afterCommand(); }; } /** * insert image * * @param {String} src * @param {String|Function} param * @return {Promise} */ }, { key: "insertImage", value: function insertImage(src, param) { var _this3 = this; return createImage(src, param).then(function ($image) { _this3.beforeCommand(); if (typeof param === 'function') { param($image); } else { if (typeof param === 'string') { $image.attr('data-filename', param); } $image.css('width', Math.min(_this3.$editable.width(), $image.width())); } $image.show(); _this3.getLastRange().insertNode($image[0]); _this3.setLastRange(range.createFromNodeAfter($image[0]).select()); _this3.afterCommand(); }).fail(function (e) { _this3.context.triggerEvent('image.upload.error', e); }); } /** * insertImages * @param {File[]} files */ }, { key: "insertImagesAsDataURL", value: function insertImagesAsDataURL(files) { var _this4 = this; external_jQuery_default().each(files, function (idx, file) { var filename = file.name; if (_this4.options.maximumImageFileSize && _this4.options.maximumImageFileSize < file.size) { _this4.context.triggerEvent('image.upload.error', _this4.lang.image.maximumFileSizeError); } else { readFileAsDataURL(file).then(function (dataURL) { return _this4.insertImage(dataURL, filename); }).fail(function () { _this4.context.triggerEvent('image.upload.error'); }); } }); } /** * insertImagesOrCallback * @param {File[]} files */ }, { key: "insertImagesOrCallback", value: function insertImagesOrCallback(files) { var callbacks = this.options.callbacks; // If onImageUpload set, if (callbacks.onImageUpload) { this.context.triggerEvent('image.upload', files); // else insert Image as dataURL } else { this.insertImagesAsDataURL(files); } } /** * return selected plain text * @return {String} text */ }, { key: "getSelectedText", value: function getSelectedText() { var rng = this.getLastRange(); // if range on anchor, expand range with anchor if (rng.isOnAnchor()) { rng = range.createFromNode(dom.ancestor(rng.sc, dom.isAnchor)); } return rng.toString(); } }, { key: "onFormatBlock", value: function onFormatBlock(tagName, $target) { // [workaround] for MSIE, IE need `<` document.execCommand('FormatBlock', false, env.isMSIE ? '<' + tagName + '>' : tagName); // support custom class if ($target && $target.length) { // find the exact element has given tagName if ($target[0].tagName.toUpperCase() !== tagName.toUpperCase()) { $target = $target.find(tagName); } if ($target && $target.length) { var currentRange = this.createRange(); var $parent = external_jQuery_default()([currentRange.sc, currentRange.ec]).closest(tagName); // remove class added for current block $parent.removeClass(); var className = $target[0].className || ''; if (className) { $parent.addClass(className); } } } } }, { key: "formatPara", value: function formatPara() { this.formatBlock('P'); } }, { key: "fontStyling", value: function fontStyling(target, value) { var rng = this.getLastRange(); if (rng !== '') { var spans = this.style.styleNodes(rng); this.$editor.find('.note-status-output').html(''); external_jQuery_default()(spans).css(target, value); // [workaround] added styled bogus span for style // - also bogus character needed for cursor position if (rng.isCollapsed()) { var firstSpan = lists.head(spans); if (firstSpan && !dom.nodeLength(firstSpan)) { firstSpan.innerHTML = dom.ZERO_WIDTH_NBSP_CHAR; range.createFromNode(firstSpan.firstChild).select(); this.setLastRange(); this.$editable.data(KEY_BOGUS, firstSpan); } } else { this.setLastRange(this.createRangeFromList(spans).select()); } } else { var noteStatusOutput = external_jQuery_default().now(); this.$editor.find('.note-status-output').html('<div id="note-status-output-' + noteStatusOutput + '" class="alert alert-info">' + this.lang.output.noSelection + '</div>'); setTimeout(function () { external_jQuery_default()('#note-status-output-' + noteStatusOutput).remove(); }, 5000); } } /** * unlink * * @type command */ }, { key: "unlink", value: function unlink() { var rng = this.getLastRange(); if (rng.isOnAnchor()) { var anchor = dom.ancestor(rng.sc, dom.isAnchor); rng = range.createFromNode(anchor); rng.select(); this.setLastRange(); this.beforeCommand(); document.execCommand('unlink'); this.afterCommand(); } } /** * returns link info * * @return {Object} * @return {WrappedRange} return.range * @return {String} return.text * @return {Boolean} [return.isNewWindow=true] * @return {String} [return.url=""] */ }, { key: "getLinkInfo", value: function getLinkInfo() { var rng = this.getLastRange().expand(dom.isAnchor); // Get the first anchor on range(for edit). var $anchor = external_jQuery_default()(lists.head(rng.nodes(dom.isAnchor))); var linkInfo = { range: rng, text: rng.toString(), url: $anchor.length ? $anchor.attr('href') : '' }; // When anchor exists, if ($anchor.length) { // Set isNewWindow by checking its target. linkInfo.isNewWindow = $anchor.attr('target') === '_blank'; } return linkInfo; } }, { key: "addRow", value: function addRow(position) { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.addRow(rng, position); this.afterCommand(); } } }, { key: "addCol", value: function addCol(position) { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.addCol(rng, position); this.afterCommand(); } } }, { key: "deleteRow", value: function deleteRow() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteRow(rng); this.afterCommand(); } } }, { key: "deleteCol", value: function deleteCol() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteCol(rng); this.afterCommand(); } } }, { key: "deleteTable", value: function deleteTable() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteTable(rng); this.afterCommand(); } } /** * @param {Position} pos * @param {jQuery} $target - target element * @param {Boolean} [bKeepRatio] - keep ratio */ }, { key: "resizeTo", value: function resizeTo(pos, $target, bKeepRatio) { var imageSize; if (bKeepRatio) { var newRatio = pos.y / pos.x; var ratio = $target.data('ratio'); imageSize = { width: ratio > newRatio ? pos.x : pos.y / ratio, height: ratio > newRatio ? pos.x * ratio : pos.y }; } else { imageSize = { width: pos.x, height: pos.y }; } $target.css(imageSize); } /** * returns whether editable area has focus or not. */ }, { key: "hasFocus", value: function hasFocus() { return this.$editable.is(':focus'); } /** * set focus */ }, { key: "focus", value: function focus() { // [workaround] Screen will move when page is scolled in IE. // - do focus when not focused if (!this.hasFocus()) { this.$editable.focus(); } } /** * returns whether contents is empty or not. * @return {Boolean} */ }, { key: "isEmpty", value: function isEmpty() { return dom.isEmpty(this.$editable[0]) || dom.emptyPara === this.$editable.html(); } /** * Removes all contents and restores the editable instance to an _emptyPara_. */ }, { key: "empty", value: function empty() { this.context.invoke('code', dom.emptyPara); } /** * normalize content */ }, { key: "normalizeContent", value: function normalizeContent() { this.$editable[0].normalize(); } }]); return Editor; }(); ;// CONCATENATED MODULE: ./src/js/module/Clipboard.js function Clipboard_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Clipboard_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Clipboard_createClass(Constructor, protoProps, staticProps) { if (protoProps) Clipboard_defineProperties(Constructor.prototype, protoProps); if (staticProps) Clipboard_defineProperties(Constructor, staticProps); return Constructor; } var Clipboard = /*#__PURE__*/function () { function Clipboard(context) { Clipboard_classCallCheck(this, Clipboard); this.context = context; this.$editable = context.layoutInfo.editable; } Clipboard_createClass(Clipboard, [{ key: "initialize", value: function initialize() { this.$editable.on('paste', this.pasteByEvent.bind(this)); } /** * paste by clipboard event * * @param {Event} event */ }, { key: "pasteByEvent", value: function pasteByEvent(event) { var _this = this; var clipboardData = event.originalEvent.clipboardData; if (clipboardData && clipboardData.items && clipboardData.items.length) { var item = clipboardData.items.length > 1 ? clipboardData.items[1] : lists.head(clipboardData.items); if (item.kind === 'file' && item.type.indexOf('image/') !== -1) { // paste img file this.context.invoke('editor.insertImagesOrCallback', [item.getAsFile()]); event.preventDefault(); } else if (item.kind === 'string') { // paste text with maxTextLength check if (this.context.invoke('editor.isLimited', clipboardData.getData('Text').length)) { event.preventDefault(); } } } else if (window.clipboardData) { // for IE var text = window.clipboardData.getData('text'); if (this.context.invoke('editor.isLimited', text.length)) { event.preventDefault(); } } // Call editor.afterCommand after proceeding default event handler setTimeout(function () { _this.context.invoke('editor.afterCommand'); }, 10); } }]); return Clipboard; }(); ;// CONCATENATED MODULE: ./src/js/module/Dropzone.js function Dropzone_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Dropzone_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Dropzone_createClass(Constructor, protoProps, staticProps) { if (protoProps) Dropzone_defineProperties(Constructor.prototype, protoProps); if (staticProps) Dropzone_defineProperties(Constructor, staticProps); return Constructor; } var Dropzone = /*#__PURE__*/function () { function Dropzone(context) { Dropzone_classCallCheck(this, Dropzone); this.context = context; this.$eventListener = external_jQuery_default()(document); this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.options = context.options; this.lang = this.options.langInfo; this.documentEventHandlers = {}; this.$dropzone = external_jQuery_default()(['<div class="note-dropzone">', '<div class="note-dropzone-message"></div>', '</div>'].join('')).prependTo(this.$editor); } /** * attach Drag and Drop Events */ Dropzone_createClass(Dropzone, [{ key: "initialize", value: function initialize() { if (this.options.disableDragAndDrop) { // prevent default drop event this.documentEventHandlers.onDrop = function (e) { e.preventDefault(); }; // do not consider outside of dropzone this.$eventListener = this.$dropzone; this.$eventListener.on('drop', this.documentEventHandlers.onDrop); } else { this.attachDragAndDropEvent(); } } /** * attach Drag and Drop Events */ }, { key: "attachDragAndDropEvent", value: function attachDragAndDropEvent() { var _this = this; var collection = external_jQuery_default()(); var $dropzoneMessage = this.$dropzone.find('.note-dropzone-message'); this.documentEventHandlers.onDragenter = function (e) { var isCodeview = _this.context.invoke('codeview.isActivated'); var hasEditorSize = _this.$editor.width() > 0 && _this.$editor.height() > 0; if (!isCodeview && !collection.length && hasEditorSize) { _this.$editor.addClass('dragover'); _this.$dropzone.width(_this.$editor.width()); _this.$dropzone.height(_this.$editor.height()); $dropzoneMessage.text(_this.lang.image.dragImageHere); } collection = collection.add(e.target); }; this.documentEventHandlers.onDragleave = function (e) { collection = collection.not(e.target); // If nodeName is BODY, then just make it over (fix for IE) if (!collection.length || e.target.nodeName === 'BODY') { collection = external_jQuery_default()(); _this.$editor.removeClass('dragover'); } }; this.documentEventHandlers.onDrop = function () { collection = external_jQuery_default()(); _this.$editor.removeClass('dragover'); }; // show dropzone on dragenter when dragging a object to document // -but only if the editor is visible, i.e. has a positive width and height this.$eventListener.on('dragenter', this.documentEventHandlers.onDragenter).on('dragleave', this.documentEventHandlers.onDragleave).on('drop', this.documentEventHandlers.onDrop); // change dropzone's message on hover. this.$dropzone.on('dragenter', function () { _this.$dropzone.addClass('hover'); $dropzoneMessage.text(_this.lang.image.dropImage); }).on('dragleave', function () { _this.$dropzone.removeClass('hover'); $dropzoneMessage.text(_this.lang.image.dragImageHere); }); // attach dropImage this.$dropzone.on('drop', function (event) { var dataTransfer = event.originalEvent.dataTransfer; // stop the browser from opening the dropped content event.preventDefault(); if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { _this.$editable.focus(); _this.context.invoke('editor.insertImagesOrCallback', dataTransfer.files); } else { external_jQuery_default().each(dataTransfer.types, function (idx, type) { // skip moz-specific types if (type.toLowerCase().indexOf('_moz_') > -1) { return; } var content = dataTransfer.getData(type); if (type.toLowerCase().indexOf('text') > -1) { _this.context.invoke('editor.pasteHTML', content); } else { external_jQuery_default()(content).each(function (idx, item) { _this.context.invoke('editor.insertNode', item); }); } }); } }).on('dragover', false); // prevent default dragover event } }, { key: "destroy", value: function destroy() { var _this2 = this; Object.keys(this.documentEventHandlers).forEach(function (key) { _this2.$eventListener.off(key.substr(2).toLowerCase(), _this2.documentEventHandlers[key]); }); this.documentEventHandlers = {}; } }]); return Dropzone; }(); ;// CONCATENATED MODULE: ./src/js/module/Codeview.js function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function Codeview_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Codeview_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Codeview_createClass(Constructor, protoProps, staticProps) { if (protoProps) Codeview_defineProperties(Constructor.prototype, protoProps); if (staticProps) Codeview_defineProperties(Constructor, staticProps); return Constructor; } /** * @class Codeview */ var CodeView = /*#__PURE__*/function () { function CodeView(context) { Codeview_classCallCheck(this, CodeView); this.context = context; this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.options = context.options; this.CodeMirrorConstructor = window.CodeMirror; if (this.options.codemirror.CodeMirrorConstructor) { this.CodeMirrorConstructor = this.options.codemirror.CodeMirrorConstructor; } } Codeview_createClass(CodeView, [{ key: "sync", value: function sync(html) { var isCodeview = this.isActivated(); var CodeMirror = this.CodeMirrorConstructor; if (isCodeview) { if (html) { if (CodeMirror) { this.$codable.data('cmEditor').getDoc().setValue(html); } else { this.$codable.val(html); } } else { if (CodeMirror) { this.$codable.data('cmEditor').save(); } } } } }, { key: "initialize", value: function initialize() { var _this = this; this.$codable.on('keyup', function (event) { if (event.keyCode === key.code.ESCAPE) { _this.deactivate(); } }); } /** * @return {Boolean} */ }, { key: "isActivated", value: function isActivated() { return this.$editor.hasClass('codeview'); } /** * toggle codeview */ }, { key: "toggle", value: function toggle() { if (this.isActivated()) { this.deactivate(); } else { this.activate(); } this.context.triggerEvent('codeview.toggled'); } /** * purify input value * @param value * @returns {*} */ }, { key: "purify", value: function purify(value) { if (this.options.codeviewFilter) { // filter code view regex value = value.replace(this.options.codeviewFilterRegex, ''); // allow specific iframe tag if (this.options.codeviewIframeFilter) { var whitelist = this.options.codeviewIframeWhitelistSrc.concat(this.options.codeviewIframeWhitelistSrcBase); value = value.replace(/(<iframe.*?>.*?(?:<\/iframe>)?)/gi, function (tag) { // remove if src attribute is duplicated if (/<.+src(?==?('|"|\s)?)[\s\S]+src(?=('|"|\s)?)[^>]*?>/i.test(tag)) { return ''; } var _iterator = _createForOfIteratorHelper(whitelist), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var src = _step.value; // pass if src is trusted if (new RegExp('src="(https?:)?\/\/' + src.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '\/(.+)"').test(tag)) { return tag; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return ''; }); } } return value; } /** * activate code view */ }, { key: "activate", value: function activate() { var _this2 = this; var CodeMirror = this.CodeMirrorConstructor; this.$codable.val(dom.html(this.$editable, this.options.prettifyHtml)); this.$codable.height(this.$editable.height()); this.context.invoke('toolbar.updateCodeview', true); this.context.invoke('airPopover.updateCodeview', true); this.$editor.addClass('codeview'); this.$codable.focus(); // activate CodeMirror as codable if (CodeMirror) { var cmEditor = CodeMirror.fromTextArea(this.$codable[0], this.options.codemirror); // CodeMirror TernServer if (this.options.codemirror.tern) { var server = new CodeMirror.TernServer(this.options.codemirror.tern); cmEditor.ternServer = server; cmEditor.on('cursorActivity', function (cm) { server.updateArgHints(cm); }); } cmEditor.on('blur', function (event) { _this2.context.triggerEvent('blur.codeview', cmEditor.getValue(), event); }); cmEditor.on('change', function () { _this2.context.triggerEvent('change.codeview', cmEditor.getValue(), cmEditor); }); // CodeMirror hasn't Padding. cmEditor.setSize(null, this.$editable.outerHeight()); this.$codable.data('cmEditor', cmEditor); } else { this.$codable.on('blur', function (event) { _this2.context.triggerEvent('blur.codeview', _this2.$codable.val(), event); }); this.$codable.on('input', function () { _this2.context.triggerEvent('change.codeview', _this2.$codable.val(), _this2.$codable); }); } } /** * deactivate code view */ }, { key: "deactivate", value: function deactivate() { var CodeMirror = this.CodeMirrorConstructor; // deactivate CodeMirror as codable if (CodeMirror) { var cmEditor = this.$codable.data('cmEditor'); this.$codable.val(cmEditor.getValue()); cmEditor.toTextArea(); } var value = this.purify(dom.value(this.$codable, this.options.prettifyHtml) || dom.emptyPara); var isChange = this.$editable.html() !== value; this.$editable.html(value); this.$editable.height(this.options.height ? this.$codable.height() : 'auto'); this.$editor.removeClass('codeview'); if (isChange) { this.context.triggerEvent('change', this.$editable.html(), this.$editable); } this.$editable.focus(); this.context.invoke('toolbar.updateCodeview', false); this.context.invoke('airPopover.updateCodeview', false); } }, { key: "destroy", value: function destroy() { if (this.isActivated()) { this.deactivate(); } } }]); return CodeView; }(); ;// CONCATENATED MODULE: ./src/js/module/Statusbar.js function Statusbar_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Statusbar_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Statusbar_createClass(Constructor, protoProps, staticProps) { if (protoProps) Statusbar_defineProperties(Constructor.prototype, protoProps); if (staticProps) Statusbar_defineProperties(Constructor, staticProps); return Constructor; } var EDITABLE_PADDING = 24; var Statusbar = /*#__PURE__*/function () { function Statusbar(context) { Statusbar_classCallCheck(this, Statusbar); this.$document = external_jQuery_default()(document); this.$statusbar = context.layoutInfo.statusbar; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.options = context.options; } Statusbar_createClass(Statusbar, [{ key: "initialize", value: function initialize() { var _this = this; if (this.options.airMode || this.options.disableResizeEditor) { this.destroy(); return; } this.$statusbar.on('mousedown', function (event) { event.preventDefault(); event.stopPropagation(); var editableTop = _this.$editable.offset().top - _this.$document.scrollTop(); var editableCodeTop = _this.$codable.offset().top - _this.$document.scrollTop(); var onMouseMove = function onMouseMove(event) { var height = event.clientY - (editableTop + EDITABLE_PADDING); var heightCode = event.clientY - (editableCodeTop + EDITABLE_PADDING); height = _this.options.minheight > 0 ? Math.max(height, _this.options.minheight) : height; height = _this.options.maxHeight > 0 ? Math.min(height, _this.options.maxHeight) : height; heightCode = _this.options.minheight > 0 ? Math.max(heightCode, _this.options.minheight) : heightCode; heightCode = _this.options.maxHeight > 0 ? Math.min(heightCode, _this.options.maxHeight) : heightCode; _this.$editable.height(height); _this.$codable.height(heightCode); }; _this.$document.on('mousemove', onMouseMove).one('mouseup', function () { _this.$document.off('mousemove', onMouseMove); }); }); } }, { key: "destroy", value: function destroy() { this.$statusbar.off(); this.$statusbar.addClass('locked'); } }]); return Statusbar; }(); ;// CONCATENATED MODULE: ./src/js/module/Fullscreen.js function Fullscreen_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Fullscreen_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Fullscreen_createClass(Constructor, protoProps, staticProps) { if (protoProps) Fullscreen_defineProperties(Constructor.prototype, protoProps); if (staticProps) Fullscreen_defineProperties(Constructor, staticProps); return Constructor; } var Fullscreen = /*#__PURE__*/function () { function Fullscreen(context) { var _this = this; Fullscreen_classCallCheck(this, Fullscreen); this.context = context; this.$editor = context.layoutInfo.editor; this.$toolbar = context.layoutInfo.toolbar; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.$window = external_jQuery_default()(window); this.$scrollbar = external_jQuery_default()('html, body'); this.scrollbarClassName = 'note-fullscreen-body'; this.onResize = function () { _this.resizeTo({ h: _this.$window.height() - _this.$toolbar.outerHeight() }); }; } Fullscreen_createClass(Fullscreen, [{ key: "resizeTo", value: function resizeTo(size) { this.$editable.css('height', size.h); this.$codable.css('height', size.h); if (this.$codable.data('cmeditor')) { this.$codable.data('cmeditor').setsize(null, size.h); } } /** * toggle fullscreen */ }, { key: "toggle", value: function toggle() { this.$editor.toggleClass('fullscreen'); var isFullscreen = this.isFullscreen(); this.$scrollbar.toggleClass(this.scrollbarClassName, isFullscreen); if (isFullscreen) { this.$editable.data('orgHeight', this.$editable.css('height')); this.$editable.data('orgMaxHeight', this.$editable.css('maxHeight')); this.$editable.css('maxHeight', ''); this.$window.on('resize', this.onResize).trigger('resize'); } else { this.$window.off('resize', this.onResize); this.resizeTo({ h: this.$editable.data('orgHeight') }); this.$editable.css('maxHeight', this.$editable.css('orgMaxHeight')); } this.context.invoke('toolbar.updateFullscreen', isFullscreen); } }, { key: "isFullscreen", value: function isFullscreen() { return this.$editor.hasClass('fullscreen'); } }, { key: "destroy", value: function destroy() { this.$scrollbar.removeClass(this.scrollbarClassName); } }]); return Fullscreen; }(); ;// CONCATENATED MODULE: ./src/js/module/Handle.js function Handle_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Handle_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Handle_createClass(Constructor, protoProps, staticProps) { if (protoProps) Handle_defineProperties(Constructor.prototype, protoProps); if (staticProps) Handle_defineProperties(Constructor, staticProps); return Constructor; } var Handle = /*#__PURE__*/function () { function Handle(context) { var _this = this; Handle_classCallCheck(this, Handle); this.context = context; this.$document = external_jQuery_default()(document); this.$editingArea = context.layoutInfo.editingArea; this.options = context.options; this.lang = this.options.langInfo; this.events = { 'summernote.mousedown': function summernoteMousedown(we, e) { if (_this.update(e.target, e)) { e.preventDefault(); } }, 'summernote.keyup summernote.scroll summernote.change summernote.dialog.shown': function summernoteKeyupSummernoteScrollSummernoteChangeSummernoteDialogShown() { _this.update(); }, 'summernote.disable summernote.blur': function summernoteDisableSummernoteBlur() { _this.hide(); }, 'summernote.codeview.toggled': function summernoteCodeviewToggled() { _this.update(); } }; } Handle_createClass(Handle, [{ key: "initialize", value: function initialize() { var _this2 = this; this.$handle = external_jQuery_default()(['<div class="note-handle">', '<div class="note-control-selection">', '<div class="note-control-selection-bg"></div>', '<div class="note-control-holder note-control-nw"></div>', '<div class="note-control-holder note-control-ne"></div>', '<div class="note-control-holder note-control-sw"></div>', '<div class="', this.options.disableResizeImage ? 'note-control-holder' : 'note-control-sizing', ' note-control-se"></div>', this.options.disableResizeImage ? '' : '<div class="note-control-selection-info"></div>', '</div>', '</div>'].join('')).prependTo(this.$editingArea); this.$handle.on('mousedown', function (event) { if (dom.isControlSizing(event.target)) { event.preventDefault(); event.stopPropagation(); var $target = _this2.$handle.find('.note-control-selection').data('target'); var posStart = $target.offset(); var scrollTop = _this2.$document.scrollTop(); var onMouseMove = function onMouseMove(event) { _this2.context.invoke('editor.resizeTo', { x: event.clientX - posStart.left, y: event.clientY - (posStart.top - scrollTop) }, $target, !event.shiftKey); _this2.update($target[0], event); }; _this2.$document.on('mousemove', onMouseMove).one('mouseup', function (e) { e.preventDefault(); _this2.$document.off('mousemove', onMouseMove); _this2.context.invoke('editor.afterCommand'); }); if (!$target.data('ratio')) { // original ratio. $target.data('ratio', $target.height() / $target.width()); } } }); // Listen for scrolling on the handle overlay. this.$handle.on('wheel', function (e) { e.preventDefault(); _this2.update(); }); } }, { key: "destroy", value: function destroy() { this.$handle.remove(); } }, { key: "update", value: function update(target, event) { if (this.context.isDisabled()) { return false; } var isImage = dom.isImg(target); var $selection = this.$handle.find('.note-control-selection'); this.context.invoke('imagePopover.update', target, event); if (isImage) { var $image = external_jQuery_default()(target); var position = $image.position(); var pos = { left: position.left + parseInt($image.css('marginLeft'), 10), top: position.top + parseInt($image.css('marginTop'), 10) }; // exclude margin var imageSize = { w: $image.outerWidth(false), h: $image.outerHeight(false) }; $selection.css({ display: 'block', left: pos.left, top: pos.top, width: imageSize.w, height: imageSize.h }).data('target', $image); // save current image element. var origImageObj = new Image(); origImageObj.src = $image.attr('src'); var sizingText = imageSize.w + 'x' + imageSize.h + ' (' + this.lang.image.original + ': ' + origImageObj.width + 'x' + origImageObj.height + ')'; $selection.find('.note-control-selection-info').text(sizingText); this.context.invoke('editor.saveTarget', target); } else { this.hide(); } return isImage; } /** * hide * * @param {jQuery} $handle */ }, { key: "hide", value: function hide() { this.context.invoke('editor.clearTarget'); this.$handle.children().hide(); } }]); return Handle; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoLink.js function AutoLink_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoLink_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoLink_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoLink_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoLink_defineProperties(Constructor, staticProps); return Constructor; } var defaultScheme = 'http://'; var linkPattern = /^([A-Za-z][A-Za-z0-9+-.]*\:[\/]{2}|tel:|mailto:[A-Z0-9._%+-]+@|xmpp:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i; var AutoLink = /*#__PURE__*/function () { function AutoLink(context) { var _this = this; AutoLink_classCallCheck(this, AutoLink); this.context = context; this.options = context.options; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); } }; } AutoLink_createClass(AutoLink, [{ key: "initialize", value: function initialize() { this.lastWordRange = null; } }, { key: "destroy", value: function destroy() { this.lastWordRange = null; } }, { key: "replace", value: function replace() { if (!this.lastWordRange) { return; } var keyword = this.lastWordRange.toString(); var match = keyword.match(linkPattern); if (match && (match[1] || match[2])) { var link = match[1] ? keyword : defaultScheme + keyword; var urlText = this.options.showDomainOnlyForAutolink ? keyword.replace(/^(?:https?:\/\/)?(?:tel?:?)?(?:mailto?:?)?(?:xmpp?:?)?(?:www\.)?/i, '').split('/')[0] : keyword; var node = external_jQuery_default()('<a></a>').html(urlText).attr('href', link)[0]; if (this.context.options.linkTargetBlank) { external_jQuery_default()(node).attr('target', '_blank'); } this.lastWordRange.insertNode(node); this.lastWordRange = null; this.context.invoke('editor.focus'); } } }, { key: "handleKeydown", value: function handleKeydown(e) { if (lists.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) { var wordRange = this.context.invoke('editor.createRange').getWordRange(); this.lastWordRange = wordRange; } } }, { key: "handleKeyup", value: function handleKeyup(e) { if (lists.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) { this.replace(); } } }]); return AutoLink; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoSync.js function AutoSync_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoSync_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoSync_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoSync_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoSync_defineProperties(Constructor, staticProps); return Constructor; } /** * textarea auto sync. */ var AutoSync = /*#__PURE__*/function () { function AutoSync(context) { var _this = this; AutoSync_classCallCheck(this, AutoSync); this.$note = context.layoutInfo.note; this.events = { 'summernote.change': function summernoteChange() { _this.$note.val(context.invoke('code')); } }; } AutoSync_createClass(AutoSync, [{ key: "shouldInitialize", value: function shouldInitialize() { return dom.isTextarea(this.$note[0]); } }]); return AutoSync; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoReplace.js function AutoReplace_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoReplace_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoReplace_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoReplace_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoReplace_defineProperties(Constructor, staticProps); return Constructor; } var AutoReplace = /*#__PURE__*/function () { function AutoReplace(context) { var _this = this; AutoReplace_classCallCheck(this, AutoReplace); this.context = context; this.options = context.options.replace || {}; this.keys = [key.code.ENTER, key.code.SPACE, key.code.PERIOD, key.code.COMMA, key.code.SEMICOLON, key.code.SLASH]; this.previousKeydownCode = null; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); } }; } AutoReplace_createClass(AutoReplace, [{ key: "shouldInitialize", value: function shouldInitialize() { return !!this.options.match; } }, { key: "initialize", value: function initialize() { this.lastWord = null; } }, { key: "destroy", value: function destroy() { this.lastWord = null; } }, { key: "replace", value: function replace() { if (!this.lastWord) { return; } var self = this; var keyword = this.lastWord.toString(); this.options.match(keyword, function (match) { if (match) { var node = ''; if (typeof match === 'string') { node = dom.createText(match); } else if (match instanceof jQuery) { node = match[0]; } else if (match instanceof Node) { node = match; } if (!node) return; self.lastWord.insertNode(node); self.lastWord = null; self.context.invoke('editor.focus'); } }); } }, { key: "handleKeydown", value: function handleKeydown(e) { // this forces it to remember the last whole word, even if multiple termination keys are pressed // before the previous key is let go. if (this.previousKeydownCode && lists.contains(this.keys, this.previousKeydownCode)) { this.previousKeydownCode = e.keyCode; return; } if (lists.contains(this.keys, e.keyCode)) { var wordRange = this.context.invoke('editor.createRange').getWordRange(); this.lastWord = wordRange; } this.previousKeydownCode = e.keyCode; } }, { key: "handleKeyup", value: function handleKeyup(e) { if (lists.contains(this.keys, e.keyCode)) { this.replace(); } } }]); return AutoReplace; }(); ;// CONCATENATED MODULE: ./src/js/module/Placeholder.js function Placeholder_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Placeholder_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Placeholder_createClass(Constructor, protoProps, staticProps) { if (protoProps) Placeholder_defineProperties(Constructor.prototype, protoProps); if (staticProps) Placeholder_defineProperties(Constructor, staticProps); return Constructor; } var Placeholder = /*#__PURE__*/function () { function Placeholder(context) { var _this = this; Placeholder_classCallCheck(this, Placeholder); this.context = context; this.$editingArea = context.layoutInfo.editingArea; this.options = context.options; if (this.options.inheritPlaceholder === true) { // get placeholder value from the original element this.options.placeholder = this.context.$note.attr('placeholder') || this.options.placeholder; } this.events = { 'summernote.init summernote.change': function summernoteInitSummernoteChange() { _this.update(); }, 'summernote.codeview.toggled': function summernoteCodeviewToggled() { _this.update(); } }; } Placeholder_createClass(Placeholder, [{ key: "shouldInitialize", value: function shouldInitialize() { return !!this.options.placeholder; } }, { key: "initialize", value: function initialize() { var _this2 = this; this.$placeholder = external_jQuery_default()('<div class="note-placeholder"></div>'); this.$placeholder.on('click', function () { _this2.context.invoke('focus'); }).html(this.options.placeholder).prependTo(this.$editingArea); this.update(); } }, { key: "destroy", value: function destroy() { this.$placeholder.remove(); } }, { key: "update", value: function update() { var isShow = !this.context.invoke('codeview.isActivated') && this.context.invoke('editor.isEmpty'); this.$placeholder.toggle(isShow); } }]); return Placeholder; }(); ;// CONCATENATED MODULE: ./src/js/module/Buttons.js function Buttons_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Buttons_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Buttons_createClass(Constructor, protoProps, staticProps) { if (protoProps) Buttons_defineProperties(Constructor.prototype, protoProps); if (staticProps) Buttons_defineProperties(Constructor, staticProps); return Constructor; } var Buttons = /*#__PURE__*/function () { function Buttons(context) { Buttons_classCallCheck(this, Buttons); this.ui = (external_jQuery_default()).summernote.ui; this.context = context; this.$toolbar = context.layoutInfo.toolbar; this.options = context.options; this.lang = this.options.langInfo; this.invertedKeyMap = func.invertObject(this.options.keyMap[env.isMac ? 'mac' : 'pc']); } Buttons_createClass(Buttons, [{ key: "representShortcut", value: function representShortcut(editorMethod) { var shortcut = this.invertedKeyMap[editorMethod]; if (!this.options.shortcuts || !shortcut) { return ''; } if (env.isMac) { shortcut = shortcut.replace('CMD', '⌘').replace('SHIFT', '⇧'); } shortcut = shortcut.replace('BACKSLASH', '\\').replace('SLASH', '/').replace('LEFTBRACKET', '[').replace('RIGHTBRACKET', ']'); return ' (' + shortcut + ')'; } }, { key: "button", value: function button(o) { if (!this.options.tooltip && o.tooltip) { delete o.tooltip; } o.container = this.options.container; return this.ui.button(o); } }, { key: "initialize", value: function initialize() { this.addToolbarButtons(); this.addImagePopoverButtons(); this.addLinkPopoverButtons(); this.addTablePopoverButtons(); this.fontInstalledMap = {}; } }, { key: "destroy", value: function destroy() { delete this.fontInstalledMap; } }, { key: "isFontInstalled", value: function isFontInstalled(name) { if (!Object.prototype.hasOwnProperty.call(this.fontInstalledMap, name)) { this.fontInstalledMap[name] = env.isFontInstalled(name) || lists.contains(this.options.fontNamesIgnoreCheck, name); } return this.fontInstalledMap[name]; } }, { key: "isFontDeservedToAdd", value: function isFontDeservedToAdd(name) { name = name.toLowerCase(); return name !== '' && this.isFontInstalled(name) && env.genericFontFamilies.indexOf(name) === -1; } }, { key: "colorPalette", value: function colorPalette(className, tooltip, backColor, foreColor) { var _this = this; return this.ui.buttonGroup({ className: 'note-color ' + className, children: [this.button({ className: 'note-current-color-button', contents: this.ui.icon(this.options.icons.font + ' note-recent-color'), tooltip: tooltip, click: function click(e) { var $button = external_jQuery_default()(e.currentTarget); if (backColor && foreColor) { _this.context.invoke('editor.color', { backColor: $button.attr('data-backColor'), foreColor: $button.attr('data-foreColor') }); } else if (backColor) { _this.context.invoke('editor.color', { backColor: $button.attr('data-backColor') }); } else if (foreColor) { _this.context.invoke('editor.color', { foreColor: $button.attr('data-foreColor') }); } }, callback: function callback($button) { var $recentColor = $button.find('.note-recent-color'); if (backColor) { $recentColor.css('background-color', _this.options.colorButton.backColor); $button.attr('data-backColor', _this.options.colorButton.backColor); } if (foreColor) { $recentColor.css('color', _this.options.colorButton.foreColor); $button.attr('data-foreColor', _this.options.colorButton.foreColor); } else { $recentColor.css('color', 'transparent'); } } }), this.button({ className: 'dropdown-toggle', contents: this.ui.dropdownButtonContents('', this.options), tooltip: this.lang.color.more, data: { toggle: 'dropdown' } }), this.ui.dropdown({ items: (backColor ? ['<div class="note-palette">', '<div class="note-palette-title">' + this.lang.color.background + '</div>', '<div>', '<button type="button" class="note-color-reset btn btn-light btn-default" data-event="backColor" data-value="transparent">', this.lang.color.transparent, '</button>', '</div>', '<div class="note-holder" data-event="backColor"><!-- back colors --></div>', '<div>', '<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="backColorPicker-' + this.options.id + '">', this.lang.color.cpSelect, '</button>', '<input type="color" id="backColorPicker-' + this.options.id + '" class="note-btn note-color-select-btn" value="' + this.options.colorButton.backColor + '" data-event="backColorPalette-' + this.options.id + '">', '</div>', '<div class="note-holder-custom" id="backColorPalette-' + this.options.id + '" data-event="backColor"></div>', '</div>'].join('') : '') + (foreColor ? ['<div class="note-palette">', '<div class="note-palette-title">' + this.lang.color.foreground + '</div>', '<div>', '<button type="button" class="note-color-reset btn btn-light btn-default" data-event="removeFormat" data-value="foreColor">', this.lang.color.resetToDefault, '</button>', '</div>', '<div class="note-holder" data-event="foreColor"><!-- fore colors --></div>', '<div>', '<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="foreColorPicker-' + this.options.id + '">', this.lang.color.cpSelect, '</button>', '<input type="color" id="foreColorPicker-' + this.options.id + '" class="note-btn note-color-select-btn" value="' + this.options.colorButton.foreColor + '" data-event="foreColorPalette-' + this.options.id + '">', '</div>', // Fix missing Div, Commented to find easily if it's wrong '<div class="note-holder-custom" id="foreColorPalette-' + this.options.id + '" data-event="foreColor"></div>', '</div>'].join('') : ''), callback: function callback($dropdown) { $dropdown.find('.note-holder').each(function (idx, item) { var $holder = external_jQuery_default()(item); $holder.append(_this.ui.palette({ colors: _this.options.colors, colorsName: _this.options.colorsName, eventName: $holder.data('event'), container: _this.options.container, tooltip: _this.options.tooltip }).render()); }); /* TODO: do we have to record recent custom colors within cookies? */ var customColors = [['#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF']]; $dropdown.find('.note-holder-custom').each(function (idx, item) { var $holder = external_jQuery_default()(item); $holder.append(_this.ui.palette({ colors: customColors, colorsName: customColors, eventName: $holder.data('event'), container: _this.options.container, tooltip: _this.options.tooltip }).render()); }); $dropdown.find('input[type=color]').each(function (idx, item) { external_jQuery_default()(item).change(function () { var $chip = $dropdown.find('#' + external_jQuery_default()(this).data('event')).find('.note-color-btn').first(); var color = this.value.toUpperCase(); $chip.css('background-color', color).attr('aria-label', color).attr('data-value', color).attr('data-original-title', color); $chip.click(); }); }); }, click: function click(event) { event.stopPropagation(); var $parent = external_jQuery_default()('.' + className).find('.note-dropdown-menu'); var $button = external_jQuery_default()(event.target); var eventName = $button.data('event'); var value = $button.attr('data-value'); if (eventName === 'openPalette') { var $picker = $parent.find('#' + value); var $palette = external_jQuery_default()($parent.find('#' + $picker.data('event')).find('.note-color-row')[0]); // Shift palette chips var $chip = $palette.find('.note-color-btn').last().detach(); // Set chip attributes var color = $picker.val(); $chip.css('background-color', color).attr('aria-label', color).attr('data-value', color).attr('data-original-title', color); $palette.prepend($chip); $picker.click(); } else { if (lists.contains(['backColor', 'foreColor'], eventName)) { var key = eventName === 'backColor' ? 'background-color' : 'color'; var $color = $button.closest('.note-color').find('.note-recent-color'); var $currentButton = $button.closest('.note-color').find('.note-current-color-button'); $color.css(key, value); $currentButton.attr('data-' + eventName, value); } _this.context.invoke('editor.' + eventName, value); } } })] }).render(); } }, { key: "addToolbarButtons", value: function addToolbarButtons() { var _this2 = this; this.context.memo('button.style', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.magic), _this2.options), tooltip: _this2.lang.style.style, data: { toggle: 'dropdown' } }), _this2.ui.dropdown({ className: 'dropdown-style', items: _this2.options.styleTags, title: _this2.lang.style.style, template: function template(item) { // TBD: need to be simplified if (typeof item === 'string') { item = { tag: item, title: Object.prototype.hasOwnProperty.call(_this2.lang.style, item) ? _this2.lang.style[item] : item }; } var tag = item.tag; var title = item.title; var style = item.style ? ' style="' + item.style + '" ' : ''; var className = item.className ? ' class="' + item.className + '"' : ''; return '<' + tag + style + className + '>' + title + '</' + tag + '>'; }, click: _this2.context.createInvokeHandler('editor.formatBlock') })]).render(); }); var _loop = function _loop(styleIdx, styleLen) { var item = _this2.options.styleTags[styleIdx]; _this2.context.memo('button.style.' + item, function () { return _this2.button({ className: 'note-btn-style-' + item, contents: '<div data-value="' + item + '">' + item.toUpperCase() + '</div>', tooltip: _this2.lang.style[item], click: _this2.context.createInvokeHandler('editor.formatBlock') }).render(); }); }; for (var styleIdx = 0, styleLen = this.options.styleTags.length; styleIdx < styleLen; styleIdx++) { _loop(styleIdx, styleLen); } this.context.memo('button.bold', function () { return _this2.button({ className: 'note-btn-bold', contents: _this2.ui.icon(_this2.options.icons.bold), tooltip: _this2.lang.font.bold + _this2.representShortcut('bold'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.bold') }).render(); }); this.context.memo('button.italic', function () { return _this2.button({ className: 'note-btn-italic', contents: _this2.ui.icon(_this2.options.icons.italic), tooltip: _this2.lang.font.italic + _this2.representShortcut('italic'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.italic') }).render(); }); this.context.memo('button.underline', function () { return _this2.button({ className: 'note-btn-underline', contents: _this2.ui.icon(_this2.options.icons.underline), tooltip: _this2.lang.font.underline + _this2.representShortcut('underline'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.underline') }).render(); }); this.context.memo('button.clear', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.eraser), tooltip: _this2.lang.font.clear + _this2.representShortcut('removeFormat'), click: _this2.context.createInvokeHandler('editor.removeFormat') }).render(); }); this.context.memo('button.strikethrough', function () { return _this2.button({ className: 'note-btn-strikethrough', contents: _this2.ui.icon(_this2.options.icons.strikethrough), tooltip: _this2.lang.font.strikethrough + _this2.representShortcut('strikethrough'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.strikethrough') }).render(); }); this.context.memo('button.superscript', function () { return _this2.button({ className: 'note-btn-superscript', contents: _this2.ui.icon(_this2.options.icons.superscript), tooltip: _this2.lang.font.superscript, click: _this2.context.createInvokeHandlerAndUpdateState('editor.superscript') }).render(); }); this.context.memo('button.subscript', function () { return _this2.button({ className: 'note-btn-subscript', contents: _this2.ui.icon(_this2.options.icons.subscript), tooltip: _this2.lang.font.subscript, click: _this2.context.createInvokeHandlerAndUpdateState('editor.subscript') }).render(); }); this.context.memo('button.fontname', function () { var styleInfo = _this2.context.invoke('editor.currentStyle'); if (_this2.options.addDefaultFonts) { // Add 'default' fonts into the fontnames array if not exist external_jQuery_default().each(styleInfo['font-family'].split(','), function (idx, fontname) { fontname = fontname.trim().replace(/['"]+/g, ''); if (_this2.isFontDeservedToAdd(fontname)) { if (_this2.options.fontNames.indexOf(fontname) === -1) { _this2.options.fontNames.push(fontname); } } }); } return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontname"></span>', _this2.options), tooltip: _this2.lang.font.name, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontname', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontNames.filter(_this2.isFontInstalled.bind(_this2)), title: _this2.lang.font.name, template: function template(item) { return '<span style="font-family: ' + env.validFontName(item) + '">' + item + '</span>'; }, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontName') })]).render(); }); this.context.memo('button.fontsize', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontsize"></span>', _this2.options), tooltip: _this2.lang.font.size, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontsize', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontSizes, title: _this2.lang.font.size, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontSize') })]).render(); }); this.context.memo('button.fontsizeunit', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontsizeunit"></span>', _this2.options), tooltip: _this2.lang.font.sizeunit, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontsizeunit', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontSizeUnits, title: _this2.lang.font.sizeunit, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontSizeUnit') })]).render(); }); this.context.memo('button.color', function () { return _this2.colorPalette('note-color-all', _this2.lang.color.recent, true, true); }); this.context.memo('button.forecolor', function () { return _this2.colorPalette('note-color-fore', _this2.lang.color.foreground, false, true); }); this.context.memo('button.backcolor', function () { return _this2.colorPalette('note-color-back', _this2.lang.color.background, true, false); }); this.context.memo('button.ul', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.unorderedlist), tooltip: _this2.lang.lists.unordered + _this2.representShortcut('insertUnorderedList'), click: _this2.context.createInvokeHandler('editor.insertUnorderedList') }).render(); }); this.context.memo('button.ol', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.orderedlist), tooltip: _this2.lang.lists.ordered + _this2.representShortcut('insertOrderedList'), click: _this2.context.createInvokeHandler('editor.insertOrderedList') }).render(); }); var justifyLeft = this.button({ contents: this.ui.icon(this.options.icons.alignLeft), tooltip: this.lang.paragraph.left + this.representShortcut('justifyLeft'), click: this.context.createInvokeHandler('editor.justifyLeft') }); var justifyCenter = this.button({ contents: this.ui.icon(this.options.icons.alignCenter), tooltip: this.lang.paragraph.center + this.representShortcut('justifyCenter'), click: this.context.createInvokeHandler('editor.justifyCenter') }); var justifyRight = this.button({ contents: this.ui.icon(this.options.icons.alignRight), tooltip: this.lang.paragraph.right + this.representShortcut('justifyRight'), click: this.context.createInvokeHandler('editor.justifyRight') }); var justifyFull = this.button({ contents: this.ui.icon(this.options.icons.alignJustify), tooltip: this.lang.paragraph.justify + this.representShortcut('justifyFull'), click: this.context.createInvokeHandler('editor.justifyFull') }); var outdent = this.button({ contents: this.ui.icon(this.options.icons.outdent), tooltip: this.lang.paragraph.outdent + this.representShortcut('outdent'), click: this.context.createInvokeHandler('editor.outdent') }); var indent = this.button({ contents: this.ui.icon(this.options.icons.indent), tooltip: this.lang.paragraph.indent + this.representShortcut('indent'), click: this.context.createInvokeHandler('editor.indent') }); this.context.memo('button.justifyLeft', func.invoke(justifyLeft, 'render')); this.context.memo('button.justifyCenter', func.invoke(justifyCenter, 'render')); this.context.memo('button.justifyRight', func.invoke(justifyRight, 'render')); this.context.memo('button.justifyFull', func.invoke(justifyFull, 'render')); this.context.memo('button.outdent', func.invoke(outdent, 'render')); this.context.memo('button.indent', func.invoke(indent, 'render')); this.context.memo('button.paragraph', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.alignLeft), _this2.options), tooltip: _this2.lang.paragraph.paragraph, data: { toggle: 'dropdown' } }), _this2.ui.dropdown([_this2.ui.buttonGroup({ className: 'note-align', children: [justifyLeft, justifyCenter, justifyRight, justifyFull] }), _this2.ui.buttonGroup({ className: 'note-list', children: [outdent, indent] })])]).render(); }); this.context.memo('button.height', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.textHeight), _this2.options), tooltip: _this2.lang.font.height, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ items: _this2.options.lineHeights, checkClassName: _this2.options.icons.menuCheck, className: 'dropdown-line-height', title: _this2.lang.font.height, click: _this2.context.createInvokeHandler('editor.lineHeight') })]).render(); }); this.context.memo('button.table', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.table), _this2.options), tooltip: _this2.lang.table.table, data: { toggle: 'dropdown' } }), _this2.ui.dropdown({ title: _this2.lang.table.table, className: 'note-table', items: ['<div class="note-dimension-picker">', '<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>', '<div class="note-dimension-picker-highlighted"></div>', '<div class="note-dimension-picker-unhighlighted"></div>', '</div>', '<div class="note-dimension-display">1 x 1</div>'].join('') })], { callback: function callback($node) { var $catcher = $node.find('.note-dimension-picker-mousecatcher'); $catcher.css({ width: _this2.options.insertTableMaxSize.col + 'em', height: _this2.options.insertTableMaxSize.row + 'em' }).mouseup(_this2.context.createInvokeHandler('editor.insertTable')).on('mousemove', _this2.tableMoveHandler.bind(_this2)); } }).render(); }); this.context.memo('button.link', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.link), tooltip: _this2.lang.link.link + _this2.representShortcut('linkDialog.show'), click: _this2.context.createInvokeHandler('linkDialog.show') }).render(); }); this.context.memo('button.picture', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.picture), tooltip: _this2.lang.image.image, click: _this2.context.createInvokeHandler('imageDialog.show') }).render(); }); this.context.memo('button.video', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.video), tooltip: _this2.lang.video.video, click: _this2.context.createInvokeHandler('videoDialog.show') }).render(); }); this.context.memo('button.hr', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.minus), tooltip: _this2.lang.hr.insert + _this2.representShortcut('insertHorizontalRule'), click: _this2.context.createInvokeHandler('editor.insertHorizontalRule') }).render(); }); this.context.memo('button.fullscreen', function () { return _this2.button({ className: 'btn-fullscreen note-codeview-keep', contents: _this2.ui.icon(_this2.options.icons.arrowsAlt), tooltip: _this2.lang.options.fullscreen, click: _this2.context.createInvokeHandler('fullscreen.toggle') }).render(); }); this.context.memo('button.codeview', function () { return _this2.button({ className: 'btn-codeview note-codeview-keep', contents: _this2.ui.icon(_this2.options.icons.code), tooltip: _this2.lang.options.codeview, click: _this2.context.createInvokeHandler('codeview.toggle') }).render(); }); this.context.memo('button.redo', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.redo), tooltip: _this2.lang.history.redo + _this2.representShortcut('redo'), click: _this2.context.createInvokeHandler('editor.redo') }).render(); }); this.context.memo('button.undo', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.undo), tooltip: _this2.lang.history.undo + _this2.representShortcut('undo'), click: _this2.context.createInvokeHandler('editor.undo') }).render(); }); this.context.memo('button.help', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.question), tooltip: _this2.lang.options.help, click: _this2.context.createInvokeHandler('helpDialog.show') }).render(); }); } /** * image: [ * ['imageResize', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']], * ['float', ['floatLeft', 'floatRight', 'floatNone']], * ['remove', ['removeMedia']], * ], */ }, { key: "addImagePopoverButtons", value: function addImagePopoverButtons() { var _this3 = this; // Image Size Buttons this.context.memo('button.resizeFull', function () { return _this3.button({ contents: '<span class="note-fontsize-10">100%</span>', tooltip: _this3.lang.image.resizeFull, click: _this3.context.createInvokeHandler('editor.resize', '1') }).render(); }); this.context.memo('button.resizeHalf', function () { return _this3.button({ contents: '<span class="note-fontsize-10">50%</span>', tooltip: _this3.lang.image.resizeHalf, click: _this3.context.createInvokeHandler('editor.resize', '0.5') }).render(); }); this.context.memo('button.resizeQuarter', function () { return _this3.button({ contents: '<span class="note-fontsize-10">25%</span>', tooltip: _this3.lang.image.resizeQuarter, click: _this3.context.createInvokeHandler('editor.resize', '0.25') }).render(); }); this.context.memo('button.resizeNone', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.rollback), tooltip: _this3.lang.image.resizeNone, click: _this3.context.createInvokeHandler('editor.resize', '0') }).render(); }); // Float Buttons this.context.memo('button.floatLeft', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.floatLeft), tooltip: _this3.lang.image.floatLeft, click: _this3.context.createInvokeHandler('editor.floatMe', 'left') }).render(); }); this.context.memo('button.floatRight', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.floatRight), tooltip: _this3.lang.image.floatRight, click: _this3.context.createInvokeHandler('editor.floatMe', 'right') }).render(); }); this.context.memo('button.floatNone', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.rollback), tooltip: _this3.lang.image.floatNone, click: _this3.context.createInvokeHandler('editor.floatMe', 'none') }).render(); }); // Remove Buttons this.context.memo('button.removeMedia', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.trash), tooltip: _this3.lang.image.remove, click: _this3.context.createInvokeHandler('editor.removeMedia') }).render(); }); } }, { key: "addLinkPopoverButtons", value: function addLinkPopoverButtons() { var _this4 = this; this.context.memo('button.linkDialogShow', function () { return _this4.button({ contents: _this4.ui.icon(_this4.options.icons.link), tooltip: _this4.lang.link.edit, click: _this4.context.createInvokeHandler('linkDialog.show') }).render(); }); this.context.memo('button.unlink', function () { return _this4.button({ contents: _this4.ui.icon(_this4.options.icons.unlink), tooltip: _this4.lang.link.unlink, click: _this4.context.createInvokeHandler('editor.unlink') }).render(); }); } /** * table : [ * ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']], * ['delete', ['deleteRow', 'deleteCol', 'deleteTable']] * ], */ }, { key: "addTablePopoverButtons", value: function addTablePopoverButtons() { var _this5 = this; this.context.memo('button.addRowUp', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowAbove), tooltip: _this5.lang.table.addRowAbove, click: _this5.context.createInvokeHandler('editor.addRow', 'top') }).render(); }); this.context.memo('button.addRowDown', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowBelow), tooltip: _this5.lang.table.addRowBelow, click: _this5.context.createInvokeHandler('editor.addRow', 'bottom') }).render(); }); this.context.memo('button.addColLeft', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colBefore), tooltip: _this5.lang.table.addColLeft, click: _this5.context.createInvokeHandler('editor.addCol', 'left') }).render(); }); this.context.memo('button.addColRight', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colAfter), tooltip: _this5.lang.table.addColRight, click: _this5.context.createInvokeHandler('editor.addCol', 'right') }).render(); }); this.context.memo('button.deleteRow', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowRemove), tooltip: _this5.lang.table.delRow, click: _this5.context.createInvokeHandler('editor.deleteRow') }).render(); }); this.context.memo('button.deleteCol', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colRemove), tooltip: _this5.lang.table.delCol, click: _this5.context.createInvokeHandler('editor.deleteCol') }).render(); }); this.context.memo('button.deleteTable', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.trash), tooltip: _this5.lang.table.delTable, click: _this5.context.createInvokeHandler('editor.deleteTable') }).render(); }); } }, { key: "build", value: function build($container, groups) { for (var groupIdx = 0, groupLen = groups.length; groupIdx < groupLen; groupIdx++) { var group = groups[groupIdx]; var groupName = Array.isArray(group) ? group[0] : group; var buttons = Array.isArray(group) ? group.length === 1 ? [group[0]] : group[1] : [group]; var $group = this.ui.buttonGroup({ className: 'note-' + groupName }).render(); for (var idx = 0, len = buttons.length; idx < len; idx++) { var btn = this.context.memo('button.' + buttons[idx]); if (btn) { $group.append(typeof btn === 'function' ? btn(this.context) : btn); } } $group.appendTo($container); } } /** * @param {jQuery} [$container] */ }, { key: "updateCurrentStyle", value: function updateCurrentStyle($container) { var $cont = $container || this.$toolbar; var styleInfo = this.context.invoke('editor.currentStyle'); this.updateBtnStates($cont, { '.note-btn-bold': function noteBtnBold() { return styleInfo['font-bold'] === 'bold'; }, '.note-btn-italic': function noteBtnItalic() { return styleInfo['font-italic'] === 'italic'; }, '.note-btn-underline': function noteBtnUnderline() { return styleInfo['font-underline'] === 'underline'; }, '.note-btn-subscript': function noteBtnSubscript() { return styleInfo['font-subscript'] === 'subscript'; }, '.note-btn-superscript': function noteBtnSuperscript() { return styleInfo['font-superscript'] === 'superscript'; }, '.note-btn-strikethrough': function noteBtnStrikethrough() { return styleInfo['font-strikethrough'] === 'strikethrough'; } }); if (styleInfo['font-family']) { var fontNames = styleInfo['font-family'].split(',').map(function (name) { return name.replace(/[\'\"]/g, '').replace(/\s+$/, '').replace(/^\s+/, ''); }); var fontName = lists.find(fontNames, this.isFontInstalled.bind(this)); $cont.find('.dropdown-fontname a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare string to avoid creating another func. var isChecked = $item.data('value') + '' === fontName + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontname').text(fontName).css('font-family', fontName); } if (styleInfo['font-size']) { var fontSize = styleInfo['font-size']; $cont.find('.dropdown-fontsize a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare with string to avoid creating another func. var isChecked = $item.data('value') + '' === fontSize + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontsize').text(fontSize); var fontSizeUnit = styleInfo['font-size-unit']; $cont.find('.dropdown-fontsizeunit a').each(function (idx, item) { var $item = external_jQuery_default()(item); var isChecked = $item.data('value') + '' === fontSizeUnit + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontsizeunit').text(fontSizeUnit); } if (styleInfo['line-height']) { var lineHeight = styleInfo['line-height']; $cont.find('.dropdown-line-height a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare with string to avoid creating another func. var isChecked = external_jQuery_default()(item).data('value') + '' === lineHeight + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-line-height').text(lineHeight); } } }, { key: "updateBtnStates", value: function updateBtnStates($container, infos) { var _this6 = this; external_jQuery_default().each(infos, function (selector, pred) { _this6.ui.toggleBtnActive($container.find(selector), pred()); }); } }, { key: "tableMoveHandler", value: function tableMoveHandler(event) { var PX_PER_EM = 18; var $picker = external_jQuery_default()(event.target.parentNode); // target is mousecatcher var $dimensionDisplay = $picker.next(); var $catcher = $picker.find('.note-dimension-picker-mousecatcher'); var $highlighted = $picker.find('.note-dimension-picker-highlighted'); var $unhighlighted = $picker.find('.note-dimension-picker-unhighlighted'); var posOffset; // HTML5 with jQuery - e.offsetX is undefined in Firefox if (event.offsetX === undefined) { var posCatcher = external_jQuery_default()(event.target).offset(); posOffset = { x: event.pageX - posCatcher.left, y: event.pageY - posCatcher.top }; } else { posOffset = { x: event.offsetX, y: event.offsetY }; } var dim = { c: Math.ceil(posOffset.x / PX_PER_EM) || 1, r: Math.ceil(posOffset.y / PX_PER_EM) || 1 }; $highlighted.css({ width: dim.c + 'em', height: dim.r + 'em' }); $catcher.data('value', dim.c + 'x' + dim.r); if (dim.c > 3 && dim.c < this.options.insertTableMaxSize.col) { $unhighlighted.css({ width: dim.c + 1 + 'em' }); } if (dim.r > 3 && dim.r < this.options.insertTableMaxSize.row) { $unhighlighted.css({ height: dim.r + 1 + 'em' }); } $dimensionDisplay.html(dim.c + ' x ' + dim.r); } }]); return Buttons; }(); ;// CONCATENATED MODULE: ./src/js/module/Toolbar.js function Toolbar_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Toolbar_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Toolbar_createClass(Constructor, protoProps, staticProps) { if (protoProps) Toolbar_defineProperties(Constructor.prototype, protoProps); if (staticProps) Toolbar_defineProperties(Constructor, staticProps); return Constructor; } var Toolbar = /*#__PURE__*/function () { function Toolbar(context) { Toolbar_classCallCheck(this, Toolbar); this.context = context; this.$window = external_jQuery_default()(window); this.$document = external_jQuery_default()(document); this.ui = (external_jQuery_default()).summernote.ui; this.$note = context.layoutInfo.note; this.$editor = context.layoutInfo.editor; this.$toolbar = context.layoutInfo.toolbar; this.$editable = context.layoutInfo.editable; this.$statusbar = context.layoutInfo.statusbar; this.options = context.options; this.isFollowing = false; this.followScroll = this.followScroll.bind(this); } Toolbar_createClass(Toolbar, [{ key: "shouldInitialize", value: function shouldInitialize() { return !this.options.airMode; } }, { key: "initialize", value: function initialize() { var _this = this; this.options.toolbar = this.options.toolbar || []; if (!this.options.toolbar.length) { this.$toolbar.hide(); } else { this.context.invoke('buttons.build', this.$toolbar, this.options.toolbar); } if (this.options.toolbarContainer) { this.$toolbar.appendTo(this.options.toolbarContainer); } this.changeContainer(false); this.$note.on('summernote.keyup summernote.mouseup summernote.change', function () { _this.context.invoke('buttons.updateCurrentStyle'); }); this.context.invoke('buttons.updateCurrentStyle'); if (this.options.followingToolbar) { this.$window.on('scroll resize', this.followScroll); } } }, { key: "destroy", value: function destroy() { this.$toolbar.children().remove(); if (this.options.followingToolbar) { this.$window.off('scroll resize', this.followScroll); } } }, { key: "followScroll", value: function followScroll() { if (this.$editor.hasClass('fullscreen')) { return false; } var editorHeight = this.$editor.outerHeight(); var editorWidth = this.$editor.width(); var toolbarHeight = this.$toolbar.height(); var statusbarHeight = this.$statusbar.height(); // check if the web app is currently using another static bar var otherBarHeight = 0; if (this.options.otherStaticBar) { otherBarHeight = external_jQuery_default()(this.options.otherStaticBar).outerHeight(); } var currentOffset = this.$document.scrollTop(); var editorOffsetTop = this.$editor.offset().top; var editorOffsetBottom = editorOffsetTop + editorHeight; var activateOffset = editorOffsetTop - otherBarHeight; var deactivateOffsetBottom = editorOffsetBottom - otherBarHeight - toolbarHeight - statusbarHeight; if (!this.isFollowing && currentOffset > activateOffset && currentOffset < deactivateOffsetBottom - toolbarHeight) { this.isFollowing = true; this.$editable.css({ marginTop: this.$toolbar.outerHeight() }); this.$toolbar.css({ position: 'fixed', top: otherBarHeight, width: editorWidth, zIndex: 1000 }); } else if (this.isFollowing && (currentOffset < activateOffset || currentOffset > deactivateOffsetBottom)) { this.isFollowing = false; this.$toolbar.css({ position: 'relative', top: 0, width: '100%', zIndex: 'auto' }); this.$editable.css({ marginTop: '' }); } } }, { key: "changeContainer", value: function changeContainer(isFullscreen) { if (isFullscreen) { this.$toolbar.prependTo(this.$editor); } else { if (this.options.toolbarContainer) { this.$toolbar.appendTo(this.options.toolbarContainer); } } if (this.options.followingToolbar) { this.followScroll(); } } }, { key: "updateFullscreen", value: function updateFullscreen(isFullscreen) { this.ui.toggleBtnActive(this.$toolbar.find('.btn-fullscreen'), isFullscreen); this.changeContainer(isFullscreen); } }, { key: "updateCodeview", value: function updateCodeview(isCodeview) { this.ui.toggleBtnActive(this.$toolbar.find('.btn-codeview'), isCodeview); if (isCodeview) { this.deactivate(); } else { this.activate(); } } }, { key: "activate", value: function activate(isIncludeCodeview) { var $btn = this.$toolbar.find('button'); if (!isIncludeCodeview) { $btn = $btn.not('.note-codeview-keep'); } this.ui.toggleBtn($btn, true); } }, { key: "deactivate", value: function deactivate(isIncludeCodeview) { var $btn = this.$toolbar.find('button'); if (!isIncludeCodeview) { $btn = $btn.not('.note-codeview-keep'); } this.ui.toggleBtn($btn, false); } }]); return Toolbar; }(); ;// CONCATENATED MODULE: ./src/js/module/LinkDialog.js function LinkDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function LinkDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function LinkDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) LinkDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) LinkDialog_defineProperties(Constructor, staticProps); return Constructor; } var LinkDialog = /*#__PURE__*/function () { function LinkDialog(context) { LinkDialog_classCallCheck(this, LinkDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; context.memo('help.linkDialog.show', this.options.langInfo.help['linkDialog.show']); } LinkDialog_createClass(LinkDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group">', "<label for=\"note-dialog-link-txt-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.link.textToDisplay, "</label>"), "<input id=\"note-dialog-link-txt-".concat(this.options.id, "\" class=\"note-link-text form-control note-form-control note-input\" type=\"text\"/>"), '</div>', '<div class="form-group note-form-group">', "<label for=\"note-dialog-link-url-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.link.url, "</label>"), "<input id=\"note-dialog-link-url-".concat(this.options.id, "\" class=\"note-link-url form-control note-form-control note-input\" type=\"text\" value=\"http://\"/>"), '</div>', !this.options.disableLinkTarget ? external_jQuery_default()('<div></div>').append(this.ui.checkbox({ className: 'sn-checkbox-open-in-new-window', text: this.lang.link.openInNewWindow, checked: true }).render()).html() : '', external_jQuery_default()('<div></div>').append(this.ui.checkbox({ className: 'sn-checkbox-use-protocol', text: this.lang.link.useProtocol, checked: true }).render()).html()].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-link-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.link.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ className: 'link-dialog', title: this.lang.link.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } /** * toggle update button */ }, { key: "toggleLinkBtn", value: function toggleLinkBtn($linkBtn, $linkText, $linkUrl) { this.ui.toggleBtn($linkBtn, $linkText.val() && $linkUrl.val()); } /** * Show link dialog and set event handlers on dialog controls. * * @param {Object} linkInfo * @return {Promise} */ }, { key: "showLinkDialog", value: function showLinkDialog(linkInfo) { var _this = this; return external_jQuery_default().Deferred(function (deferred) { var $linkText = _this.$dialog.find('.note-link-text'); var $linkUrl = _this.$dialog.find('.note-link-url'); var $linkBtn = _this.$dialog.find('.note-link-btn'); var $openInNewWindow = _this.$dialog.find('.sn-checkbox-open-in-new-window input[type=checkbox]'); var $useProtocol = _this.$dialog.find('.sn-checkbox-use-protocol input[type=checkbox]'); _this.ui.onDialogShown(_this.$dialog, function () { _this.context.triggerEvent('dialog.shown'); // If no url was given and given text is valid URL then copy that into URL Field if (!linkInfo.url && func.isValidUrl(linkInfo.text)) { linkInfo.url = linkInfo.text; } $linkText.on('input paste propertychange', function () { // If linktext was modified by input events, // cloning text from linkUrl will be stopped. linkInfo.text = $linkText.val(); _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); }).val(linkInfo.text); $linkUrl.on('input paste propertychange', function () { // Display same text on `Text to display` as default // when linktext has no text if (!linkInfo.text) { $linkText.val($linkUrl.val()); } _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); }).val(linkInfo.url); if (!env.isSupportTouch) { $linkUrl.trigger('focus'); } _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); _this.bindEnterKey($linkUrl, $linkBtn); _this.bindEnterKey($linkText, $linkBtn); var isNewWindowChecked = linkInfo.isNewWindow !== undefined ? linkInfo.isNewWindow : _this.context.options.linkTargetBlank; $openInNewWindow.prop('checked', isNewWindowChecked); var useProtocolChecked = linkInfo.url ? false : _this.context.options.useProtocol; $useProtocol.prop('checked', useProtocolChecked); $linkBtn.one('click', function (event) { event.preventDefault(); deferred.resolve({ range: linkInfo.range, url: $linkUrl.val(), text: $linkText.val(), isNewWindow: $openInNewWindow.is(':checked'), checkProtocol: $useProtocol.is(':checked') }); _this.ui.hideDialog(_this.$dialog); }); }); _this.ui.onDialogHidden(_this.$dialog, function () { // detach events $linkText.off(); $linkUrl.off(); $linkBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this.ui.showDialog(_this.$dialog); }).promise(); } /** * @param {Object} layoutInfo */ }, { key: "show", value: function show() { var _this2 = this; var linkInfo = this.context.invoke('editor.getLinkInfo'); this.context.invoke('editor.saveRange'); this.showLinkDialog(linkInfo).then(function (linkInfo) { _this2.context.invoke('editor.restoreRange'); _this2.context.invoke('editor.createLink', linkInfo); }).fail(function () { _this2.context.invoke('editor.restoreRange'); }); } }]); return LinkDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/LinkPopover.js function LinkPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function LinkPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function LinkPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) LinkPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) LinkPopover_defineProperties(Constructor, staticProps); return Constructor; } var LinkPopover = /*#__PURE__*/function () { function LinkPopover(context) { var _this = this; LinkPopover_classCallCheck(this, LinkPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.events = { 'summernote.keyup summernote.mouseup summernote.change summernote.scroll': function summernoteKeyupSummernoteMouseupSummernoteChangeSummernoteScroll() { _this.update(); }, 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } LinkPopover_createClass(LinkPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.link); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-link-popover', callback: function callback($node) { var $content = $node.find('.popover-content,.note-popover-content'); $content.prepend('<span><a target="_blank"></a>&nbsp;</span>'); } }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.link); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update() { // Prevent focusing on editable when invoke('code') is executed if (!this.context.invoke('editor.hasFocus')) { this.hide(); return; } var rng = this.context.invoke('editor.getLastRange'); if (rng.isCollapsed() && rng.isOnAnchor()) { var anchor = dom.ancestor(rng.sc, dom.isAnchor); var href = external_jQuery_default()(anchor).attr('href'); this.$popover.find('a').attr('href', href).text(href); var pos = dom.posFromPlaceholder(anchor); var containerOffset = external_jQuery_default()(this.options.container).offset(); pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return LinkPopover; }(); ;// CONCATENATED MODULE: ./src/js/module/ImageDialog.js function ImageDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function ImageDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function ImageDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) ImageDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) ImageDialog_defineProperties(Constructor, staticProps); return Constructor; } var ImageDialog = /*#__PURE__*/function () { function ImageDialog(context) { ImageDialog_classCallCheck(this, ImageDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } ImageDialog_createClass(ImageDialog, [{ key: "initialize", value: function initialize() { var imageLimitation = ''; if (this.options.maximumImageFileSize) { var unit = Math.floor(Math.log(this.options.maximumImageFileSize) / Math.log(1024)); var readableSize = (this.options.maximumImageFileSize / Math.pow(1024, unit)).toFixed(2) * 1 + ' ' + ' KMGTP'[unit] + 'B'; imageLimitation = "<small>".concat(this.lang.image.maximumFileSize + ' : ' + readableSize, "</small>"); } var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group note-group-select-from-files">', '<label for="note-dialog-image-file-' + this.options.id + '" class="note-form-label">' + this.lang.image.selectFromFiles + '</label>', '<input id="note-dialog-image-file-' + this.options.id + '" class="note-image-input form-control-file note-form-control note-input" ', ' type="file" name="files" accept="' + this.options.acceptImageFileTypes + '" multiple="multiple"/>', imageLimitation, '</div>', '<div class="form-group note-group-image-url">', '<label for="note-dialog-image-url-' + this.options.id + '" class="note-form-label">' + this.lang.image.url + '</label>', '<input id="note-dialog-image-url-' + this.options.id + '" class="note-image-url form-control note-form-control note-input" type="text"/>', '</div>'].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-image-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.image.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ title: this.lang.image.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } }, { key: "show", value: function show() { var _this = this; this.context.invoke('editor.saveRange'); this.showImageDialog().then(function (data) { // [workaround] hide dialog before restore range for IE range focus _this.ui.hideDialog(_this.$dialog); _this.context.invoke('editor.restoreRange'); if (typeof data === 'string') { // image url // If onImageLinkInsert set, if (_this.options.callbacks.onImageLinkInsert) { _this.context.triggerEvent('image.link.insert', data); } else { _this.context.invoke('editor.insertImage', data); } } else { // array of files _this.context.invoke('editor.insertImagesOrCallback', data); } }).fail(function () { _this.context.invoke('editor.restoreRange'); }); } /** * show image dialog * * @param {jQuery} $dialog * @return {Promise} */ }, { key: "showImageDialog", value: function showImageDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { var $imageInput = _this2.$dialog.find('.note-image-input'); var $imageUrl = _this2.$dialog.find('.note-image-url'); var $imageBtn = _this2.$dialog.find('.note-image-btn'); _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); // Cloning imageInput to clear element. $imageInput.replaceWith($imageInput.clone().on('change', function (event) { deferred.resolve(event.target.files || event.target.value); }).val('')); $imageUrl.on('input paste propertychange', function () { _this2.ui.toggleBtn($imageBtn, $imageUrl.val()); }).val(''); if (!env.isSupportTouch) { $imageUrl.trigger('focus'); } $imageBtn.click(function (event) { event.preventDefault(); deferred.resolve($imageUrl.val()); }); _this2.bindEnterKey($imageUrl, $imageBtn); }); _this2.ui.onDialogHidden(_this2.$dialog, function () { $imageInput.off(); $imageUrl.off(); $imageBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this2.ui.showDialog(_this2.$dialog); }); } }]); return ImageDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/ImagePopover.js function ImagePopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function ImagePopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function ImagePopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) ImagePopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) ImagePopover_defineProperties(Constructor, staticProps); return Constructor; } /** * Image popover module * mouse events that show/hide popover will be handled by Handle.js. * Handle.js will receive the events and invoke 'imagePopover.update'. */ var ImagePopover = /*#__PURE__*/function () { function ImagePopover(context) { var _this = this; ImagePopover_classCallCheck(this, ImagePopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.editable = context.layoutInfo.editable[0]; this.options = context.options; this.events = { 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } ImagePopover_createClass(ImagePopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.image); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-image-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.image); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(target, event) { if (dom.isImg(target)) { var position = external_jQuery_default()(target).offset(); var containerOffset = external_jQuery_default()(this.options.container).offset(); var pos = {}; if (this.options.popatmouse) { pos.left = event.pageX - 20; pos.top = event.pageY; } else { pos = position; } pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return ImagePopover; }(); ;// CONCATENATED MODULE: ./src/js/module/TablePopover.js function TablePopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function TablePopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function TablePopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) TablePopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) TablePopover_defineProperties(Constructor, staticProps); return Constructor; } var TablePopover = /*#__PURE__*/function () { function TablePopover(context) { var _this = this; TablePopover_classCallCheck(this, TablePopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.events = { 'summernote.mousedown': function summernoteMousedown(we, e) { _this.update(e.target); }, 'summernote.keyup summernote.scroll summernote.change': function summernoteKeyupSummernoteScrollSummernoteChange() { _this.update(); }, 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } TablePopover_createClass(TablePopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.table); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-table-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.table); // [workaround] Disable Firefox's default table editor if (env.isFF) { document.execCommand('enableInlineTableEditing', false, false); } this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(target) { if (this.context.isDisabled()) { return false; } var isCell = dom.isCell(target) || dom.isCell(target === null || target === void 0 ? void 0 : target.parentElement); if (isCell) { var pos = dom.posFromPlaceholder(target); var containerOffset = external_jQuery_default()(this.options.container).offset(); pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } return isCell; } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return TablePopover; }(); ;// CONCATENATED MODULE: ./src/js/module/VideoDialog.js function VideoDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function VideoDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function VideoDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) VideoDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) VideoDialog_defineProperties(Constructor, staticProps); return Constructor; } var VideoDialog = /*#__PURE__*/function () { function VideoDialog(context) { VideoDialog_classCallCheck(this, VideoDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } VideoDialog_createClass(VideoDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group row-fluid">', "<label for=\"note-dialog-video-url-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.video.url, " <small class=\"text-muted\">").concat(this.lang.video.providers, "</small></label>"), "<input id=\"note-dialog-video-url-".concat(this.options.id, "\" class=\"note-video-url form-control note-form-control note-input\" type=\"text\"/>"), '</div>'].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-video-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.video.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ title: this.lang.video.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } }, { key: "createVideoNode", value: function createVideoNode(url) { // video url patterns(youtube, instagram, vimeo, dailymotion, youku, peertube, mp4, ogg, webm) var ytRegExp = /\/\/(?:(?:www|m)\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))([\w|-]{11})(?:(?:[\?&]t=)(\S+))?$/; var ytRegExpForStart = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/; var ytMatch = url.match(ytRegExp); var gdRegExp = /(?:\.|\/\/)drive\.google\.com\/file\/d\/(.[a-zA-Z0-9_-]*)\/view/; var gdMatch = url.match(gdRegExp); var igRegExp = /(?:www\.|\/\/)instagram\.com\/p\/(.[a-zA-Z0-9_-]*)/; var igMatch = url.match(igRegExp); var vRegExp = /\/\/vine\.co\/v\/([a-zA-Z0-9]+)/; var vMatch = url.match(vRegExp); var vimRegExp = /\/\/(player\.)?vimeo\.com\/([a-z]*\/)*(\d+)[?]?.*/; var vimMatch = url.match(vimRegExp); var dmRegExp = /.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/; var dmMatch = url.match(dmRegExp); var youkuRegExp = /\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/; var youkuMatch = url.match(youkuRegExp); var peerTubeRegExp = /\/\/(.*)\/videos\/watch\/([^?]*)(?:\?(?:start=(\w*))?(?:&stop=(\w*))?(?:&loop=([10]))?(?:&autoplay=([10]))?(?:&muted=([10]))?)?/; var peerTubeMatch = url.match(peerTubeRegExp); var qqRegExp = /\/\/v\.qq\.com.*?vid=(.+)/; var qqMatch = url.match(qqRegExp); var qqRegExp2 = /\/\/v\.qq\.com\/x?\/?(page|cover).*?\/([^\/]+)\.html\??.*/; var qqMatch2 = url.match(qqRegExp2); var mp4RegExp = /^.+.(mp4|m4v)$/; var mp4Match = url.match(mp4RegExp); var oggRegExp = /^.+.(ogg|ogv)$/; var oggMatch = url.match(oggRegExp); var webmRegExp = /^.+.(webm)$/; var webmMatch = url.match(webmRegExp); var fbRegExp = /(?:www\.|\/\/)facebook\.com\/([^\/]+)\/videos\/([0-9]+)/; var fbMatch = url.match(fbRegExp); var $video; if (ytMatch && ytMatch[1].length === 11) { var youtubeId = ytMatch[1]; var start = 0; if (typeof ytMatch[2] !== 'undefined') { var ytMatchForStart = ytMatch[2].match(ytRegExpForStart); if (ytMatchForStart) { for (var n = [3600, 60, 1], i = 0, r = n.length; i < r; i++) { start += typeof ytMatchForStart[i + 1] !== 'undefined' ? n[i] * parseInt(ytMatchForStart[i + 1], 10) : 0; } } } $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', '//www.youtube.com/embed/' + youtubeId + (start > 0 ? '?start=' + start : '')).attr('width', '640').attr('height', '360'); } else if (gdMatch && gdMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://drive.google.com/file/d/' + gdMatch[1] + '/preview').attr('width', '640').attr('height', '480'); } else if (igMatch && igMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://instagram.com/p/' + igMatch[1] + '/embed/').attr('width', '612').attr('height', '710').attr('scrolling', 'no').attr('allowtransparency', 'true'); } else if (vMatch && vMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', vMatch[0] + '/embed/simple').attr('width', '600').attr('height', '600').attr('class', 'vine-embed'); } else if (vimMatch && vimMatch[3].length) { $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('src', '//player.vimeo.com/video/' + vimMatch[3]).attr('width', '640').attr('height', '360'); } else if (dmMatch && dmMatch[2].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', '//www.dailymotion.com/embed/video/' + dmMatch[2]).attr('width', '640').attr('height', '360'); } else if (youkuMatch && youkuMatch[1].length) { $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('height', '498').attr('width', '510').attr('src', '//player.youku.com/embed/' + youkuMatch[1]); } else if (peerTubeMatch && peerTubeMatch[0].length) { var begin = 0; if (peerTubeMatch[2] !== 'undefined') begin = peerTubeMatch[2]; var end = 0; if (peerTubeMatch[3] !== 'undefined') end = peerTubeMatch[3]; var loop = 0; if (peerTubeMatch[4] !== 'undefined') loop = peerTubeMatch[4]; var autoplay = 0; if (peerTubeMatch[5] !== 'undefined') autoplay = peerTubeMatch[5]; var muted = 0; if (peerTubeMatch[6] !== 'undefined') muted = peerTubeMatch[6]; $video = external_jQuery_default()('<iframe allowfullscreen sandbox="allow-same-origin allow-scripts allow-popups">').attr('frameborder', 0).attr('src', '//' + peerTubeMatch[1] + '/videos/embed/' + peerTubeMatch[2] + "?loop=" + loop + "&autoplay=" + autoplay + "&muted=" + muted + (begin > 0 ? '&start=' + begin : '') + (end > 0 ? '&end=' + start : '')).attr('width', '560').attr('height', '315'); } else if (qqMatch && qqMatch[1].length || qqMatch2 && qqMatch2[2].length) { var vid = qqMatch && qqMatch[1].length ? qqMatch[1] : qqMatch2[2]; $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('height', '310').attr('width', '500').attr('src', 'https://v.qq.com/txp/iframe/player.html?vid=' + vid + '&amp;auto=0'); } else if (mp4Match || oggMatch || webmMatch) { $video = external_jQuery_default()('<video controls>').attr('src', url).attr('width', '640').attr('height', '360'); } else if (fbMatch && fbMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://www.facebook.com/plugins/video.php?href=' + encodeURIComponent(fbMatch[0]) + '&show_text=0&width=560').attr('width', '560').attr('height', '301').attr('scrolling', 'no').attr('allowtransparency', 'true'); } else { // this is not a known video link. Now what, Cat? Now what? return false; } $video.addClass('note-video-clip'); return $video[0]; } }, { key: "show", value: function show() { var _this = this; var text = this.context.invoke('editor.getSelectedText'); this.context.invoke('editor.saveRange'); this.showVideoDialog(text).then(function (url) { // [workaround] hide dialog before restore range for IE range focus _this.ui.hideDialog(_this.$dialog); _this.context.invoke('editor.restoreRange'); // build node var $node = _this.createVideoNode(url); if ($node) { // insert video node _this.context.invoke('editor.insertNode', $node); } }).fail(function () { _this.context.invoke('editor.restoreRange'); }); } /** * show video dialog * * @param {jQuery} $dialog * @return {Promise} */ }, { key: "showVideoDialog", value: function showVideoDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { var $videoUrl = _this2.$dialog.find('.note-video-url'); var $videoBtn = _this2.$dialog.find('.note-video-btn'); _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); $videoUrl.on('input paste propertychange', function () { _this2.ui.toggleBtn($videoBtn, $videoUrl.val()); }); if (!env.isSupportTouch) { $videoUrl.trigger('focus'); } $videoBtn.click(function (event) { event.preventDefault(); deferred.resolve($videoUrl.val()); }); _this2.bindEnterKey($videoUrl, $videoBtn); }); _this2.ui.onDialogHidden(_this2.$dialog, function () { $videoUrl.off(); $videoBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this2.ui.showDialog(_this2.$dialog); }); } }]); return VideoDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/HelpDialog.js function HelpDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function HelpDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function HelpDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) HelpDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) HelpDialog_defineProperties(Constructor, staticProps); return Constructor; } var HelpDialog = /*#__PURE__*/function () { function HelpDialog(context) { HelpDialog_classCallCheck(this, HelpDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } HelpDialog_createClass(HelpDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<p class="text-center">', '<a href="http://summernote.org/" target="_blank" rel="noopener noreferrer">Summernote 0.8.20</a> · ', '<a href="https://github.com/summernote/summernote" target="_blank" rel="noopener noreferrer">Project</a> · ', '<a href="https://github.com/summernote/summernote/issues" target="_blank" rel="noopener noreferrer">Issues</a>', '</p>'].join(''); this.$dialog = this.ui.dialog({ title: this.lang.options.help, fade: this.options.dialogsFade, body: this.createShortcutList(), footer: body, callback: function callback($node) { $node.find('.modal-body,.note-modal-body').css({ 'max-height': 300, 'overflow': 'scroll' }); } }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "createShortcutList", value: function createShortcutList() { var _this = this; var keyMap = this.options.keyMap[env.isMac ? 'mac' : 'pc']; return Object.keys(keyMap).map(function (key) { var command = keyMap[key]; var $row = external_jQuery_default()('<div><div class="help-list-item"></div></div>'); $row.append(external_jQuery_default()('<label><kbd>' + key + '</kdb></label>').css({ 'width': 180, 'margin-right': 10 })).append(external_jQuery_default()('<span></span>').html(_this.context.memo('help.' + command) || command)); return $row.html(); }).join(''); } /** * show help dialog * * @return {Promise} */ }, { key: "showHelpDialog", value: function showHelpDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); deferred.resolve(); }); _this2.ui.showDialog(_this2.$dialog); }).promise(); } }, { key: "show", value: function show() { var _this3 = this; this.context.invoke('editor.saveRange'); this.showHelpDialog().then(function () { _this3.context.invoke('editor.restoreRange'); }); } }]); return HelpDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/AirPopover.js function AirPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AirPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AirPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) AirPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) AirPopover_defineProperties(Constructor, staticProps); return Constructor; } var AIRMODE_POPOVER_X_OFFSET = -5; var AIRMODE_POPOVER_Y_OFFSET = 5; var AirPopover = /*#__PURE__*/function () { function AirPopover(context) { var _this = this; AirPopover_classCallCheck(this, AirPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.hidable = true; this.onContextmenu = false; this.pageX = null; this.pageY = null; this.events = { 'summernote.contextmenu': function summernoteContextmenu(e) { if (_this.options.editing) { e.preventDefault(); e.stopPropagation(); _this.onContextmenu = true; _this.update(true); } }, 'summernote.mousedown': function summernoteMousedown(we, e) { _this.pageX = e.pageX; _this.pageY = e.pageY; }, 'summernote.keyup summernote.mouseup summernote.scroll': function summernoteKeyupSummernoteMouseupSummernoteScroll(we, e) { if (_this.options.editing && !_this.onContextmenu) { _this.pageX = e.pageX; _this.pageY = e.pageY; _this.update(); } _this.onContextmenu = false; }, 'summernote.disable summernote.change summernote.dialog.shown summernote.blur': function summernoteDisableSummernoteChangeSummernoteDialogShownSummernoteBlur() { _this.hide(); }, 'summernote.focusout': function summernoteFocusout() { if (!_this.$popover.is(':active,:focus')) { _this.hide(); } } }; } AirPopover_createClass(AirPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return this.options.airMode && !lists.isEmpty(this.options.popover.air); } }, { key: "initialize", value: function initialize() { var _this2 = this; this.$popover = this.ui.popover({ className: 'note-air-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.air); // disable hiding this popover preemptively by 'summernote.blur' event. this.$popover.on('mousedown', function () { _this2.hidable = false; }); // (re-)enable hiding after 'summernote.blur' has been handled (aka. ignored). this.$popover.on('mouseup', function () { _this2.hidable = true; }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(forcelyOpen) { var styleInfo = this.context.invoke('editor.currentStyle'); if (styleInfo.range && (!styleInfo.range.isCollapsed() || forcelyOpen)) { var rect = { left: this.pageX, top: this.pageY }; var containerOffset = external_jQuery_default()(this.options.container).offset(); rect.top -= containerOffset.top; rect.left -= containerOffset.left; this.$popover.css({ display: 'block', left: Math.max(rect.left, 0) + AIRMODE_POPOVER_X_OFFSET, top: rect.top + AIRMODE_POPOVER_Y_OFFSET }); this.context.invoke('buttons.updateCurrentStyle', this.$popover); } else { this.hide(); } } }, { key: "updateCodeview", value: function updateCodeview(isCodeview) { this.ui.toggleBtnActive(this.$popover.find('.btn-codeview'), isCodeview); if (isCodeview) { this.hide(); } } }, { key: "hide", value: function hide() { if (this.hidable) { this.$popover.hide(); } } }]); return AirPopover; }(); ;// CONCATENATED MODULE: ./src/js/module/HintPopover.js function HintPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function HintPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function HintPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) HintPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) HintPopover_defineProperties(Constructor, staticProps); return Constructor; } var POPOVER_DIST = 5; var HintPopover = /*#__PURE__*/function () { function HintPopover(context) { var _this = this; HintPopover_classCallCheck(this, HintPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$editable = context.layoutInfo.editable; this.options = context.options; this.hint = this.options.hint || []; this.direction = this.options.hintDirection || 'bottom'; this.hints = Array.isArray(this.hint) ? this.hint : [this.hint]; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); }, 'summernote.disable summernote.dialog.shown summernote.blur': function summernoteDisableSummernoteDialogShownSummernoteBlur() { _this.hide(); } }; } HintPopover_createClass(HintPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return this.hints.length > 0; } }, { key: "initialize", value: function initialize() { var _this2 = this; this.lastWordRange = null; this.matchingWord = null; this.$popover = this.ui.popover({ className: 'note-hint-popover', hideArrow: true, direction: '' }).render().appendTo(this.options.container); this.$popover.hide(); this.$content = this.$popover.find('.popover-content,.note-popover-content'); this.$content.on('click', '.note-hint-item', function (e) { _this2.$content.find('.active').removeClass('active'); external_jQuery_default()(e.currentTarget).addClass('active'); _this2.replace(); }); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "selectItem", value: function selectItem($item) { this.$content.find('.active').removeClass('active'); $item.addClass('active'); this.$content[0].scrollTop = $item[0].offsetTop - this.$content.innerHeight() / 2; } }, { key: "moveDown", value: function moveDown() { var $current = this.$content.find('.note-hint-item.active'); var $next = $current.next(); if ($next.length) { this.selectItem($next); } else { var $nextGroup = $current.parent().next(); if (!$nextGroup.length) { $nextGroup = this.$content.find('.note-hint-group').first(); } this.selectItem($nextGroup.find('.note-hint-item').first()); } } }, { key: "moveUp", value: function moveUp() { var $current = this.$content.find('.note-hint-item.active'); var $prev = $current.prev(); if ($prev.length) { this.selectItem($prev); } else { var $prevGroup = $current.parent().prev(); if (!$prevGroup.length) { $prevGroup = this.$content.find('.note-hint-group').last(); } this.selectItem($prevGroup.find('.note-hint-item').last()); } } }, { key: "replace", value: function replace() { var $item = this.$content.find('.note-hint-item.active'); if ($item.length) { var node = this.nodeFromItem($item); // If matchingWord length = 0 -> capture OK / open hint / but as mention capture "" (\w*) if (this.matchingWord !== null && this.matchingWord.length === 0) { this.lastWordRange.so = this.lastWordRange.eo; // Else si > 0 and normal case -> adjust range "before" for correct position of insertion } else if (this.matchingWord !== null && this.matchingWord.length > 0 && !this.lastWordRange.isCollapsed()) { var rangeCompute = this.lastWordRange.eo - this.lastWordRange.so - this.matchingWord.length; if (rangeCompute > 0) { this.lastWordRange.so += rangeCompute; } } this.lastWordRange.insertNode(node); if (this.options.hintSelect === 'next') { var blank = document.createTextNode(''); external_jQuery_default()(node).after(blank); range.createFromNodeBefore(blank).select(); } else { range.createFromNodeAfter(node).select(); } this.lastWordRange = null; this.hide(); this.context.invoke('editor.focus'); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } } }, { key: "nodeFromItem", value: function nodeFromItem($item) { var hint = this.hints[$item.data('index')]; var item = $item.data('item'); var node = hint.content ? hint.content(item) : item; if (typeof node === 'string') { node = dom.createText(node); } return node; } }, { key: "createItemTemplates", value: function createItemTemplates(hintIdx, items) { var hint = this.hints[hintIdx]; return items.map(function (item /*, idx */ ) { var $item = external_jQuery_default()('<div class="note-hint-item"></div>'); $item.append(hint.template ? hint.template(item) : item + ''); $item.data({ 'index': hintIdx, 'item': item }); return $item; }); } }, { key: "handleKeydown", value: function handleKeydown(e) { if (!this.$popover.is(':visible')) { return; } if (e.keyCode === key.code.ENTER) { e.preventDefault(); this.replace(); } else if (e.keyCode === key.code.UP) { e.preventDefault(); this.moveUp(); } else if (e.keyCode === key.code.DOWN) { e.preventDefault(); this.moveDown(); } } }, { key: "searchKeyword", value: function searchKeyword(index, keyword, callback) { var hint = this.hints[index]; if (hint && hint.match.test(keyword) && hint.search) { var matches = hint.match.exec(keyword); this.matchingWord = matches[0]; hint.search(matches[1], callback); } else { callback(); } } }, { key: "createGroup", value: function createGroup(idx, keyword) { var _this3 = this; var $group = external_jQuery_default()('<div class="note-hint-group note-hint-group-' + idx + '"></div>'); this.searchKeyword(idx, keyword, function (items) { items = items || []; if (items.length) { $group.html(_this3.createItemTemplates(idx, items)); _this3.show(); } }); return $group; } }, { key: "handleKeyup", value: function handleKeyup(e) { var _this4 = this; if (!lists.contains([key.code.ENTER, key.code.UP, key.code.DOWN], e.keyCode)) { var _range = this.context.invoke('editor.getLastRange'); var wordRange, keyword; if (this.options.hintMode === 'words') { wordRange = _range.getWordsRange(_range); keyword = wordRange.toString(); this.hints.forEach(function (hint) { if (hint.match.test(keyword)) { wordRange = _range.getWordsMatchRange(hint.match); return false; } }); if (!wordRange) { this.hide(); return; } keyword = wordRange.toString(); } else { wordRange = _range.getWordRange(); keyword = wordRange.toString(); } if (this.hints.length && keyword) { this.$content.empty(); var bnd = func.rect2bnd(lists.last(wordRange.getClientRects())); var containerOffset = external_jQuery_default()(this.options.container).offset(); if (bnd) { bnd.top -= containerOffset.top; bnd.left -= containerOffset.left; this.$popover.hide(); this.lastWordRange = wordRange; this.hints.forEach(function (hint, idx) { if (hint.match.test(keyword)) { _this4.createGroup(idx, keyword).appendTo(_this4.$content); } }); // select first .note-hint-item this.$content.find('.note-hint-item:first').addClass('active'); // set position for popover after group is created if (this.direction === 'top') { this.$popover.css({ left: bnd.left, top: bnd.top - this.$popover.outerHeight() - POPOVER_DIST }); } else { this.$popover.css({ left: bnd.left, top: bnd.top + bnd.height + POPOVER_DIST }); } } } else { this.hide(); } } } }, { key: "show", value: function show() { this.$popover.show(); } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return HintPopover; }(); ;// CONCATENATED MODULE: ./src/js/settings.js (external_jQuery_default()).summernote = external_jQuery_default().extend((external_jQuery_default()).summernote, { version: '0.8.20', plugins: {}, dom: dom, range: range, lists: lists, options: { langInfo: (external_jQuery_default()).summernote.lang["en-US"], editing: true, modules: { 'editor': Editor, 'clipboard': Clipboard, 'dropzone': Dropzone, 'codeview': CodeView, 'statusbar': Statusbar, 'fullscreen': Fullscreen, 'handle': Handle, // FIXME: HintPopover must be front of autolink // - Script error about range when Enter key is pressed on hint popover 'hintPopover': HintPopover, 'autoLink': AutoLink, 'autoSync': AutoSync, 'autoReplace': AutoReplace, 'placeholder': Placeholder, 'buttons': Buttons, 'toolbar': Toolbar, 'linkDialog': LinkDialog, 'linkPopover': LinkPopover, 'imageDialog': ImageDialog, 'imagePopover': ImagePopover, 'tablePopover': TablePopover, 'videoDialog': VideoDialog, 'helpDialog': HelpDialog, 'airPopover': AirPopover }, buttons: {}, lang: 'en-US', followingToolbar: false, toolbarPosition: 'top', otherStaticBar: '', // toolbar codeviewKeepButton: false, toolbar: [['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['fontname', ['fontname']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture', 'video']], ['view', ['fullscreen', 'codeview', 'help']]], // popover popatmouse: true, popover: { image: [['resize', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']], ['float', ['floatLeft', 'floatRight', 'floatNone']], ['remove', ['removeMedia']]], link: [['link', ['linkDialogShow', 'unlink']]], table: [['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']], ['delete', ['deleteRow', 'deleteCol', 'deleteTable']]], air: [['color', ['color']], ['font', ['bold', 'underline', 'clear']], ['para', ['ul', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture']], ['view', ['fullscreen', 'codeview']]] }, // air mode: inline editor airMode: false, overrideContextMenu: false, // TBD width: null, height: null, linkTargetBlank: true, useProtocol: true, defaultProtocol: 'http://', focus: false, tabDisabled: false, tabSize: 4, styleWithCSS: false, shortcuts: true, textareaAutoSync: true, tooltip: 'auto', container: null, maxTextLength: 0, blockquoteBreakingLevel: 2, spellCheck: true, disableGrammar: false, placeholder: null, inheritPlaceholder: false, // TODO: need to be documented recordEveryKeystroke: false, historyLimit: 200, // TODO: need to be documented showDomainOnlyForAutolink: false, // TODO: need to be documented hintMode: 'word', hintSelect: 'after', hintDirection: 'bottom', styleTags: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'], fontNames: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande', 'Tahoma', 'Times New Roman', 'Verdana'], fontNamesIgnoreCheck: [], addDefaultFonts: true, fontSizes: ['8', '9', '10', '11', '12', '14', '18', '24', '36'], fontSizeUnits: ['px', 'pt'], // pallete colors(n x n) colors: [['#000000', '#424242', '#636363', '#9C9C94', '#CEC6CE', '#EFEFEF', '#F7F7F7', '#FFFFFF'], ['#FF0000', '#FF9C00', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#9C00FF', '#FF00FF'], ['#F7C6CE', '#FFE7CE', '#FFEFC6', '#D6EFD6', '#CEDEE7', '#CEE7F7', '#D6D6E7', '#E7D6DE'], ['#E79C9C', '#FFC69C', '#FFE79C', '#B5D6A5', '#A5C6CE', '#9CC6EF', '#B5A5D6', '#D6A5BD'], ['#E76363', '#F7AD6B', '#FFD663', '#94BD7B', '#73A5AD', '#6BADDE', '#8C7BC6', '#C67BA5'], ['#CE0000', '#E79439', '#EFC631', '#6BA54A', '#4A7B8C', '#3984C6', '#634AA5', '#A54A7B'], ['#9C0000', '#B56308', '#BD9400', '#397B21', '#104A5A', '#085294', '#311873', '#731842'], ['#630000', '#7B3900', '#846300', '#295218', '#083139', '#003163', '#21104A', '#4A1031']], // http://chir.ag/projects/name-that-color/ colorsName: [['Black', 'Tundora', 'Dove Gray', 'Star Dust', 'Pale Slate', 'Gallery', 'Alabaster', 'White'], ['Red', 'Orange Peel', 'Yellow', 'Green', 'Cyan', 'Blue', 'Electric Violet', 'Magenta'], ['Azalea', 'Karry', 'Egg White', 'Zanah', 'Botticelli', 'Tropical Blue', 'Mischka', 'Twilight'], ['Tonys Pink', 'Peach Orange', 'Cream Brulee', 'Sprout', 'Casper', 'Perano', 'Cold Purple', 'Careys Pink'], ['Mandy', 'Rajah', 'Dandelion', 'Olivine', 'Gulf Stream', 'Viking', 'Blue Marguerite', 'Puce'], ['Guardsman Red', 'Fire Bush', 'Golden Dream', 'Chelsea Cucumber', 'Smalt Blue', 'Boston Blue', 'Butterfly Bush', 'Cadillac'], ['Sangria', 'Mai Tai', 'Buddha Gold', 'Forest Green', 'Eden', 'Venice Blue', 'Meteorite', 'Claret'], ['Rosewood', 'Cinnamon', 'Olive', 'Parsley', 'Tiber', 'Midnight Blue', 'Valentino', 'Loulou']], colorButton: { foreColor: '#000000', backColor: '#FFFF00' }, lineHeights: ['1.0', '1.2', '1.4', '1.5', '1.6', '1.8', '2.0', '3.0'], tableClassName: 'table table-bordered', insertTableMaxSize: { col: 10, row: 10 }, // By default, dialogs are attached in container. dialogsInBody: false, dialogsFade: false, maximumImageFileSize: null, acceptImageFileTypes: "image/*", callbacks: { onBeforeCommand: null, onBlur: null, onBlurCodeview: null, onChange: null, onChangeCodeview: null, onDialogShown: null, onEnter: null, onFocus: null, onImageLinkInsert: null, onImageUpload: null, onImageUploadError: null, onInit: null, onKeydown: null, onKeyup: null, onMousedown: null, onMouseup: null, onPaste: null, onScroll: null }, codemirror: { mode: 'text/html', htmlMode: true, lineNumbers: true }, codeviewFilter: true, codeviewFilterRegex: /<\/*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|ilayer|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|t(?:itle|extarea)|xml)[^>]*?>/gi, codeviewIframeFilter: true, codeviewIframeWhitelistSrc: [], codeviewIframeWhitelistSrcBase: ['www.youtube.com', 'www.youtube-nocookie.com', 'www.facebook.com', 'vine.co', 'instagram.com', 'player.vimeo.com', 'www.dailymotion.com', 'player.youku.com', 'jumpingbean.tv', 'v.qq.com'], keyMap: { pc: { 'ESC': 'escape', 'ENTER': 'insertParagraph', 'CTRL+Z': 'undo', 'CTRL+Y': 'redo', 'TAB': 'tab', 'SHIFT+TAB': 'untab', 'CTRL+B': 'bold', 'CTRL+I': 'italic', 'CTRL+U': 'underline', 'CTRL+SHIFT+S': 'strikethrough', 'CTRL+BACKSLASH': 'removeFormat', 'CTRL+SHIFT+L': 'justifyLeft', 'CTRL+SHIFT+E': 'justifyCenter', 'CTRL+SHIFT+R': 'justifyRight', 'CTRL+SHIFT+J': 'justifyFull', 'CTRL+SHIFT+NUM7': 'insertUnorderedList', 'CTRL+SHIFT+NUM8': 'insertOrderedList', 'CTRL+LEFTBRACKET': 'outdent', 'CTRL+RIGHTBRACKET': 'indent', 'CTRL+NUM0': 'formatPara', 'CTRL+NUM1': 'formatH1', 'CTRL+NUM2': 'formatH2', 'CTRL+NUM3': 'formatH3', 'CTRL+NUM4': 'formatH4', 'CTRL+NUM5': 'formatH5', 'CTRL+NUM6': 'formatH6', 'CTRL+ENTER': 'insertHorizontalRule', 'CTRL+K': 'linkDialog.show' }, mac: { 'ESC': 'escape', 'ENTER': 'insertParagraph', 'CMD+Z': 'undo', 'CMD+SHIFT+Z': 'redo', 'TAB': 'tab', 'SHIFT+TAB': 'untab', 'CMD+B': 'bold', 'CMD+I': 'italic', 'CMD+U': 'underline', 'CMD+SHIFT+S': 'strikethrough', 'CMD+BACKSLASH': 'removeFormat', 'CMD+SHIFT+L': 'justifyLeft', 'CMD+SHIFT+E': 'justifyCenter', 'CMD+SHIFT+R': 'justifyRight', 'CMD+SHIFT+J': 'justifyFull', 'CMD+SHIFT+NUM7': 'insertUnorderedList', 'CMD+SHIFT+NUM8': 'insertOrderedList', 'CMD+LEFTBRACKET': 'outdent', 'CMD+RIGHTBRACKET': 'indent', 'CMD+NUM0': 'formatPara', 'CMD+NUM1': 'formatH1', 'CMD+NUM2': 'formatH2', 'CMD+NUM3': 'formatH3', 'CMD+NUM4': 'formatH4', 'CMD+NUM5': 'formatH5', 'CMD+NUM6': 'formatH6', 'CMD+ENTER': 'insertHorizontalRule', 'CMD+K': 'linkDialog.show' } }, icons: { 'align': 'note-icon-align', 'alignCenter': 'note-icon-align-center', 'alignJustify': 'note-icon-align-justify', 'alignLeft': 'note-icon-align-left', 'alignRight': 'note-icon-align-right', 'rowBelow': 'note-icon-row-below', 'colBefore': 'note-icon-col-before', 'colAfter': 'note-icon-col-after', 'rowAbove': 'note-icon-row-above', 'rowRemove': 'note-icon-row-remove', 'colRemove': 'note-icon-col-remove', 'indent': 'note-icon-align-indent', 'outdent': 'note-icon-align-outdent', 'arrowsAlt': 'note-icon-arrows-alt', 'bold': 'note-icon-bold', 'caret': 'note-icon-caret', 'circle': 'note-icon-circle', 'close': 'note-icon-close', 'code': 'note-icon-code', 'eraser': 'note-icon-eraser', 'floatLeft': 'note-icon-float-left', 'floatRight': 'note-icon-float-right', 'font': 'note-icon-font', 'frame': 'note-icon-frame', 'italic': 'note-icon-italic', 'link': 'note-icon-link', 'unlink': 'note-icon-chain-broken', 'magic': 'note-icon-magic', 'menuCheck': 'note-icon-menu-check', 'minus': 'note-icon-minus', 'orderedlist': 'note-icon-orderedlist', 'pencil': 'note-icon-pencil', 'picture': 'note-icon-picture', 'question': 'note-icon-question', 'redo': 'note-icon-redo', 'rollback': 'note-icon-rollback', 'square': 'note-icon-square', 'strikethrough': 'note-icon-strikethrough', 'subscript': 'note-icon-subscript', 'superscript': 'note-icon-superscript', 'table': 'note-icon-table', 'textHeight': 'note-icon-text-height', 'trash': 'note-icon-trash', 'underline': 'note-icon-underline', 'undo': 'note-icon-undo', 'unorderedlist': 'note-icon-unorderedlist', 'video': 'note-icon-video' } } }); ;// CONCATENATED MODULE: ./src/js/renderer.js function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function renderer_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function renderer_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function renderer_createClass(Constructor, protoProps, staticProps) { if (protoProps) renderer_defineProperties(Constructor.prototype, protoProps); if (staticProps) renderer_defineProperties(Constructor, staticProps); return Constructor; } var Renderer = /*#__PURE__*/function () { function Renderer(markup, children, options, callback) { renderer_classCallCheck(this, Renderer); this.markup = markup; this.children = children; this.options = options; this.callback = callback; } renderer_createClass(Renderer, [{ key: "render", value: function render($parent) { var $node = external_jQuery_default()(this.markup); if (this.options && this.options.contents) { $node.html(this.options.contents); } if (this.options && this.options.className) { $node.addClass(this.options.className); } if (this.options && this.options.data) { external_jQuery_default().each(this.options.data, function (k, v) { $node.attr('data-' + k, v); }); } if (this.options && this.options.click) { $node.on('click', this.options.click); } if (this.children) { var $container = $node.find('.note-children-container'); this.children.forEach(function (child) { child.render($container.length ? $container : $node); }); } if (this.callback) { this.callback($node, this.options); } if (this.options && this.options.callback) { this.options.callback($node); } if ($parent) { $parent.append($node); } return $node; } }]); return Renderer; }(); /* harmony default export */ const renderer = ({ create: function create(markup, callback) { return function () { var options = _typeof(arguments[1]) === 'object' ? arguments[1] : arguments[0]; var children = Array.isArray(arguments[0]) ? arguments[0] : []; if (options && options.children) { children = options.children; } return new Renderer(markup, children, options, callback); }; } }); ;// CONCATENATED MODULE: ./src/styles/bs5/summernote-bs5.js function summernote_bs5_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { summernote_bs5_typeof = function _typeof(obj) { return typeof obj; }; } else { summernote_bs5_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return summernote_bs5_typeof(obj); } var editor = renderer.create('<div class="note-editor note-frame card"/>'); var toolbar = renderer.create('<div class="note-toolbar card-header" role="toolbar"/>'); var editingArea = renderer.create('<div class="note-editing-area"/>'); var codable = renderer.create('<textarea class="note-codable" aria-multiline="true"/>'); var editable = renderer.create('<div class="note-editable card-block" contentEditable="true" role="textbox" aria-multiline="true"/>'); var statusbar = renderer.create(['<output class="note-status-output" role="status" aria-live="polite"></output>', '<div class="note-statusbar" role="status">', '<div class="note-resizebar" aria-label="Resize">', '<div class="note-icon-bar"></div>', '<div class="note-icon-bar"></div>', '<div class="note-icon-bar"></div>', '</div>', '</div>'].join('')); var airEditor = renderer.create('<div class="note-editor note-airframe"/>'); var airEditable = renderer.create(['<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>', '<output class="note-status-output" role="status" aria-live="polite"></output>'].join('')); var buttonGroup = renderer.create('<div class="note-btn-group btn-group">'); var dropdown = renderer.create('<div class="note-dropdown-menu dropdown-menu" role="list">', function ($node, options) { var markup = Array.isArray(options.items) ? options.items.map(function (item) { var value = typeof item === 'string' ? item : item.value || ''; var content = options.template ? options.template(item) : item; var option = summernote_bs5_typeof(item) === 'object' ? item.option : undefined; var dataValue = 'data-value="' + value + '"'; var dataOption = option !== undefined ? ' data-option="' + option + '"' : ''; return '<a class="dropdown-item" href="#" ' + (dataValue + dataOption) + ' role="listitem" aria-label="' + value + '">' + content + '</a>'; }).join('') : options.items; $node.html(markup).attr({ 'aria-label': options.title }); if (options && options.codeviewKeepButton) { $node.addClass('note-codeview-keep'); } }); var dropdownButtonContents = function dropdownButtonContents(contents) { return contents; }; var dropdownCheck = renderer.create('<div class="note-dropdown-menu dropdown-menu note-check" role="list">', function ($node, options) { var markup = Array.isArray(options.items) ? options.items.map(function (item) { var value = typeof item === 'string' ? item : item.value || ''; var content = options.template ? options.template(item) : item; return '<a class="dropdown-item" href="#" data-value="' + value + '" role="listitem" aria-label="' + item + '">' + icon(options.checkClassName) + ' ' + content + '</a>'; }).join('') : options.items; $node.html(markup).attr({ 'aria-label': options.title }); if (options && options.codeviewKeepButton) { $node.addClass('note-codeview-keep'); } }); var dialog = renderer.create('<div class="modal note-modal" aria-hidden="false" tabindex="-1" role="dialog"/>', function ($node, options) { if (options.fade) { $node.addClass('fade'); } $node.attr({ 'aria-label': options.title }); $node.html(['<div class="modal-dialog">', '<div class="modal-content">', options.title ? '<div class="modal-header">' + '<h4 class="modal-title">' + options.title + '</h4>' + '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" aria-hidden="true"></button>' + '</div>' : '', '<div class="modal-body">' + options.body + '</div>', options.footer ? '<div class="modal-footer">' + options.footer + '</div>' : '', '</div>', '</div>'].join('')); }); var popover = renderer.create(['<div class="note-popover popover show">', '<div class="popover-arrow"></div>', '<div class="popover-body note-children-container"></div>', '</div>'].join(''), function ($node, options) { var direction = typeof options.direction !== 'undefined' ? options.direction : 'bottom'; $node.attr('data-bs-placement', direction); if (options.hideArrow) { $node.find('.popover-arrow').hide(); } }); var summernote_bs5_checkbox = renderer.create('<div class="form-check"></div>', function ($node, options) { $node.html(['<label class="form-check-label"' + (options.id ? ' for="note-' + options.id + '"' : '') + '>', '<input type="checkbox" class="form-check-input"' + (options.id ? ' id="note-' + options.id + '"' : ''), options.checked ? ' checked' : '', ' aria-label="' + (options.text ? options.text : '') + '"', ' aria-checked="' + (options.checked ? 'true' : 'false') + '"/>', ' ' + (options.text ? options.text : '') + '</label>'].join('')); }); var icon = function icon(iconClassName, tagName) { if (iconClassName.match(/^</)) { return iconClassName; } tagName = tagName || 'i'; return '<' + tagName + ' class="' + iconClassName + '"></' + tagName + '>'; }; var ui = function ui(editorOptions) { return { editor: editor, toolbar: toolbar, editingArea: editingArea, codable: codable, editable: editable, statusbar: statusbar, airEditor: airEditor, airEditable: airEditable, buttonGroup: buttonGroup, dropdown: dropdown, dropdownButtonContents: dropdownButtonContents, dropdownCheck: dropdownCheck, dialog: dialog, popover: popover, icon: icon, checkbox: summernote_bs5_checkbox, options: editorOptions, palette: function palette($node, options) { return renderer.create('<div class="note-color-palette"/>', function ($node, options) { var contents = []; for (var row = 0, rowSize = options.colors.length; row < rowSize; row++) { var eventName = options.eventName; var colors = options.colors[row]; var colorsName = options.colorsName[row]; var buttons = []; for (var col = 0, colSize = colors.length; col < colSize; col++) { var color = colors[col]; var colorName = colorsName[col]; buttons.push(['<button type="button" class="note-color-btn"', 'style="background-color:', color, '" ', 'data-event="', eventName, '" ', 'data-value="', color, '" ', 'title="', colorName, '" ', 'aria-label="', colorName, '" ', 'data-toggle="button" tabindex="-1"></button>'].join('')); } contents.push('<div class="note-color-row">' + buttons.join('') + '</div>'); } $node.html(contents.join('')); if (options.tooltip) { $node.find('.note-color-btn').tooltip({ container: options.container || editorOptions.container, trigger: 'hover', placement: 'bottom' }); } })($node, options); }, button: function button($node, options) { return renderer.create('<button type="button" class="note-btn btn btn-light btn-sm" tabindex="-1">', function ($node, options) { if (options && options.tooltip) { $node.attr({ title: options.tooltip, 'aria-label': options.tooltip }).tooltip({ container: options.container || editorOptions.container, trigger: 'hover', placement: 'bottom' }).on('click', function (e) { external_jQuery_default()(e.currentTarget).tooltip('hide'); }); } if (options && options.codeviewButton) { $node.addClass('note-codeview-keep'); } })($node, options); }, toggleBtn: function toggleBtn($btn, isEnable) { $btn.toggleClass('disabled', !isEnable); $btn.attr('disabled', !isEnable); }, toggleBtnActive: function toggleBtnActive($btn, isActive) { $btn.toggleClass('active', isActive); }, onDialogShown: function onDialogShown($dialog, handler) { $dialog.one('shown.bs.modal', handler); }, onDialogHidden: function onDialogHidden($dialog, handler) { $dialog.one('hidden.bs.modal', handler); }, showDialog: function showDialog($dialog) { $dialog.modal('show'); }, hideDialog: function hideDialog($dialog) { $dialog.modal('hide'); }, createLayout: function createLayout($note) { var $editor = (editorOptions.airMode ? airEditor([editingArea([codable(), airEditable()])]) : editorOptions.toolbarPosition === 'bottom' ? editor([editingArea([codable(), editable()]), toolbar(), statusbar()]) : editor([toolbar(), editingArea([codable(), editable()]), statusbar()])).render(); $editor.insertAfter($note); return { note: $note, editor: $editor, toolbar: $editor.find('.note-toolbar'), editingArea: $editor.find('.note-editing-area'), editable: $editor.find('.note-editable'), codable: $editor.find('.note-codable'), statusbar: $editor.find('.note-statusbar') }; }, removeLayout: function removeLayout($note, layoutInfo) { $note.html(layoutInfo.editable.html()); layoutInfo.editor.remove(); $note.show(); } }; }; (external_jQuery_default()).summernote = external_jQuery_default().extend((external_jQuery_default()).summernote, { ui_template: ui, "interface": 'bs5' }); (external_jQuery_default()).summernote.options.styleTags = ['p', { title: 'Blockquote', tag: 'blockquote', className: 'blockquote', value: 'blockquote' }, 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']; })(); /******/ return __webpack_exports__; /******/ })() ; }); //# sourceMappingURL=summernote-bs5.js.map
281677160/openwrt-package
1,547
luci-app-pppoe-server/root/usr/share/pppoe-server/ip-up
#!/bin/sh _LOGIN_TIME="$(date "+%Y-%m-%d %H:%M:%S")" CONFIG="pppoe-server" CONFIG_PATH=/var/etc/${CONFIG} SESSION_PATH=${CONFIG_PATH}/session _USERNAME=${PEERNAME} _IFACE=${1} _TTY=${2} _SPEED=${3} _LOCALIP=${4} _PEERIP=${5} _REMOTEIP=${6} _PID="$(cat /var/run/${_IFACE}.pid 2>/dev/null)" _MAC=$(top -bn1 | grep -v grep | grep "${CONFIG}" | grep "${_PID}" | grep -E -o "[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}") mkdir -p ${SESSION_PATH} cat <<-EOF > ${SESSION_PATH}/${_USERNAME}.${_IFACE} { "username": "${_USERNAME}", "interface": "${_IFACE}", "tty": "${_TTY}", "speed": "${_SPEED}", "ip": "${_PEERIP}", "mac": "${_MAC}", "pid": "${_PID}", "login_time": "${_LOGIN_TIME}" } EOF #只能单用户使用 cfgid=$(uci show ${CONFIG} | grep "@user" | grep "\.username='${_USERNAME}'" | cut -d '.' -sf 2) [ -n "$cfgid" ] && { HAS_LOGIN=$(ls ${SESSION_PATH} | grep "^${_USERNAME}\.ppp" | grep -v "${_IFACE}") [ -n "$HAS_LOGIN" ] && { #踢出之前的用户 KO_IFACE=$(echo $HAS_LOGIN | awk -F '.' '{print $2}') KO_PID=$(cat /var/run/${KO_IFACE}.pid 2>/dev/null) [ -n "$KO_PID" ] && kill -9 ${KO_PID} >/dev/null 2>&1 rm -f ${SESSION_PATH}/${HAS_LOGIN} rm -f /var/run/${KO_IFACE}.pid } routes=$(uci -q get ${CONFIG}.${cfgid}.routes) [ -n "$routes" ] && { for router in ${routes}; do route add -net ${router} dev ${_IFACE} >/dev/null 2>&1 done } } #可根据登录的账号自定义脚本,如组网、日志、限速、权限等特殊待遇。 SCRIPT="/usr/share/${CONFIG}/ip-up.d/${_USERNAME}" [ -s "$SCRIPT" ] && { [ ! -x "$SCRIPT" ] && chmod 0755 "$SCRIPT" "$SCRIPT" "$@" }
294coder/Efficient-MIF
5,287
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/hessianapproximations/approxhessianFD.m
function hessfun = approxhessianFD(problem, options) % Hessian approx. fnctn handle based on finite differences of the gradient. % % function hessfun = approxhessianFD(problem) % function hessfun = approxhessianFD(problem, options) % % Input: % % A Manopt problem structure (already containing the manifold and enough % information to compute the cost gradient) and an options structure % (optional), containing one option: % options.stepsize (positive double; default: 2^-14). % % If the gradient cannot be computed or approximated on 'problem', % a warning is issued. % % Output: % % Returns a function handle, encapsulating a generic finite difference % approximation of the Hessian of the problem cost. The finite difference % is based on computations of the gradient. % % The returned hessfun has this calling pattern: % % function hessfd = hessfun(x, xdot) % function hessfd = hessfun(x, xdot, storedb) % function hessfd = hessfun(x, xdot, storedb, key) % % x is a point on the manifold problem.M, xdot is a tangent vector to that % manifold at x, storedb is a StoreDB object, and key is the StoreDB key to % point x. % % Usage: % % Typically, the user will set problem.M and other fields to define the % cost and the gradient (typically, problem.cost and problem.grad or % problem.egrad). Then, to use this generic purpose Hessian approximation: % % problem.approxhess = approxhessianFD(problem, options); % % See also: trustregions % The Riemannian Trust-Region method, used in combination with the present % Hessian approximation, is called RTR-FD. Some convergence theory for it % is available in this paper: % % @incollection{boumal2015rtrfd % author={Boumal, N.}, % title={Riemannian trust regions with finite-difference Hessian approximations are globally convergent}, % year={2015}, % booktitle={Geometric Science of Information} % } % This file is part of Manopt: www.manopt.org. % Original author: Nicolas Boumal, April 8, 2015. % Contributors: % Change log: % % Feb. 19, 2015 (NB): % It is sufficient to ensure positive radial linearity to guarantee % (together with other assumptions) that this approximation of the % Hessian will confer global convergence to the trust-regions method. % Formerly, in-code comments referred to the necessity of having % complete radial linearity, and that this was harder to achieve. % This appears not to be necessary after all, which simplifies the % code. % % April 3, 2015 (NB): % Works with the new StoreDB class system. % % April 8, 2015 (NB): % Changed to approxhessianFD, which now returns a function handle % that encapsulates the getHessianFD functionality. Will be better % aligned with the other Hessian approximations to come (which may % want to use storedb.internal), and now allows specifying the step % size. % This Hessian approximation is based on the gradient: % check availability. if ~canGetGradient(problem) && ~canGetApproxGradient(problem) warning('manopt:approxhessianFD:nogradient', ... 'approxhessianFD requires the gradient to be computable.'); end % Set local defaults here, and merge with user options, if any. localdefaults.stepsize = 2^-14; if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(localdefaults, options); % Finite-difference parameter: how far do we look? stepsize = options.stepsize; % Build and return the function handle here. This extra construct via % funhandle makes it possible to make storedb and key optional. hessfun = @funhandle; function hessfd = funhandle(x, xdot, storedb, key) % Allow omission of the key, and even of storedb. if ~exist('key', 'var') if ~exist('storedb', 'var') storedb = StoreDB(); end key = storedb.getNewKey(); end hessfd = hessianFD(stepsize, problem, x, xdot, storedb, key); end end function hessfd = hessianFD(stepsize, problem, x, xdot, storedb, key) % This function does the actual work. % % Original code: Dec. 30, 2012 (NB). % Extract the input vector norm. norm_xdot = problem.M.norm(x, xdot); % First, check whether the step xdot is not too small. if norm_xdot < eps hessfd = problem.M.zerovec(x); return; end % Determine how far to retract xdot, so that the point reached does not % depend on the norm of xdot. This is what ensures radial linearity of % this present Hessian approximation. c = stepsize / norm_xdot; % Compute the gradient at the current point. grad = getGradient(problem, x, storedb, key); % Compute a point a little further along xdot, and the gradient there. % Since this is a new point, we need a new key for it, for storedb. x1 = problem.M.retr(x, xdot, c); key1 = storedb.getNewKey(); grad1 = getGradient(problem, x1, storedb, key1); % Transport grad1 back from x1 to x. grad1 = problem.M.transp(x1, x, grad1); % Return the finite difference of them: (grad1 - grad)/c. hessfd = problem.M.lincomb(x, 1/c, grad1, -1/c, grad); end
281677160/openwrt-package
3,243
luci-app-pppoe-server/root/etc/init.d/pppoe-server
#!/bin/sh /etc/rc.common # Copyright (C) 2018-2021 Lienol <[email protected]> START=99 CONFIG="pppoe-server" CONFIG_PATH=/var/etc/${CONFIG} OPTIONS_FILE=${CONFIG_PATH}/options CHAP_SECRETS=/etc/ppp/chap-secrets ipt_flag="PPPoE Server" config_t_get() { local index=0 [ -n "$4" ] && index=$4 local ret=$(uci -q get ${CONFIG}.@$1[$index].$2 2>/dev/null) echo ${ret:=$3} } localip=$(config_t_get service localip 10.0.1.1) ipt_rule() { if [ "$1" = "add" ]; then iptables -t nat -I postrouting_rule -s ${localip%.*}.0/24 -m comment --comment "${ipt_flag}" -j MASQUERADE 2>/dev/null iptables -I forwarding_rule -s ${localip%.*}.0/24 -m comment --comment "${ipt_flag}" -j ACCEPT 2>/dev/null else ipt_del() { for i in $(seq 1 $($1 -nL $2 | grep -c "${ipt_flag}")); do local index=$($1 --line-number -nL $2 | grep "${ipt_flag}" | head -1 | awk '{print $1}') $1 -w -D $2 $index 2>/dev/null done } ipt_del "iptables" "forwarding_rule" ipt_del "iptables -t nat" "postrouting_rule" fi } gen_include() { echo '#!/bin/sh' > /var/etc/${CONFIG}.include extract_rules() { echo "*$1" iptables-save -t $1 | grep "${ipt_flag}" | \ sed -e "s/^-A \(INPUT\)/-I \1 1/" echo 'COMMIT' } cat <<-EOF >> /var/etc/${CONFIG}.include iptables-save -c | grep -v "${ipt_flag}" | iptables-restore -c iptables-restore -n <<-EOT $(extract_rules filter) $(extract_rules nat) EOT EOF return 0 } start() { local enabled=$(config_t_get service enabled) [ "$enabled" -eq 1 ] || return 1 touch ${CHAP_SECRETS} mkdir -p ${CONFIG_PATH} local ms_dns1="" local dns1=$(config_t_get service dns1) [ -n "${dns1}" ] && ms_dns1="ms-dns ${dns1}" local ms_dns2="" local dns2=$(config_t_get service dns2) [ -n "${dns2}" ] && ms_dns2="ms-dns ${dns2}" cat <<-EOF >> ${OPTIONS_FILE} # PPP options for the PPPoE server # LIC: GPL name $CONFIG login require-mschap-v2 refuse-chap require-pap lcp-echo-interval 10 lcp-echo-failure 2 mru 1492 mtu 1492 ${ms_dns1} ${ms_dns2} logfile ${CONFIG_PATH}/log.log ip-up-script /usr/share/pppoe-server/ip-up ip-down-script /usr/share/pppoe-server/ip-down EOF local _users=$(uci show ${CONFIG} | grep "=user" | cut -d '.' -sf 2 | cut -d '=' -sf 1) [ -n "${_users}" ] && { for _user in ${_users}; do local u_enabled=$(uci -q get ${CONFIG}.${_user}.enabled) [ "${u_enabled}" -eq 1 ] || continue local u_username=$(uci -q get ${CONFIG}.${_user}.username) [ -n "${u_username}" ] || continue local u_password=$(uci -q get ${CONFIG}.${_user}.password) [ -n "${u_password}" ] || continue local u_ipaddress=$(uci -q get ${CONFIG}.${_user}.ipaddress) [ -n "${u_ipaddress}" ] || u_ipaddress="*" echo "${u_username} ${CONFIG} ${u_password} ${u_ipaddress}" >> ${CHAP_SECRETS} done } /usr/sbin/pppoe-server -O ${OPTIONS_FILE} -k -I $(config_t_get service client_interface) -L ${localip} -R $(config_t_get service remoteip) -N $(config_t_get service count) ipt_rule add gen_include } stop() { sed -i "/${CONFIG}/d" ${CHAP_SECRETS} top -bn1 | grep "${CONFIG_PATH}" | grep -v "grep" | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 ipt_rule del rm -rf /var/etc/${CONFIG}.include rm -rf ${CONFIG_PATH} }
294coder/Efficient-MIF
16,238
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/conjugategradient/conjugategradient.m
function [x, cost, info, options] = conjugategradient(problem, x, options) % Conjugate gradient minimization algorithm for Manopt. % % function [x, cost, info, options] = conjugategradient(problem) % function [x, cost, info, options] = conjugategradient(problem, x0) % function [x, cost, info, options] = conjugategradient(problem, x0, options) % function [x, cost, info, options] = conjugategradient(problem, [], options) % % Apply the conjugate gradient minimization algorithm to the problem % defined in the problem structure, starting at x0 if it is provided % (otherwise, at a random point on the manifold). To specify options whilst % not specifying an initial guess, give x0 as [] (the empty matrix). % % The outputs x and cost are the best reached point on the manifold and its % cost. The struct-array info contains information about the iterations: % iter : the iteration number (0 for the initial guess) % cost : cost value % time : elapsed time in seconds % gradnorm : Riemannian norm of the gradient % stepsize : norm of the last tangent vector retracted % beta : value of the beta parameter (see options.beta_type) % linesearch : information logged by options.linesearch % And possibly additional information logged by options.statsfun. % For example, type [info.gradnorm] to obtain a vector of the successive % gradient norms reached. % % The options structure is used to overwrite the default values. All % options have a default value and are hence optional. To force an option % value, pass an options structure with a field options.optionname, where % optionname is one of the following and the default value is indicated % between parentheses: % % tolgradnorm (1e-6) % The algorithm terminates if the norm of the gradient drops below this. % maxiter (1000) % The algorithm terminates if maxiter iterations have been executed. % maxtime (Inf) % The algorithm terminates if maxtime seconds elapsed. % minstepsize (1e-10) % The algorithm terminates if the linesearch returns a displacement % vector (to be retracted) smaller in norm than this value. % beta_type ('H-S') % Conjugate gradient beta rule used to construct the new search % direction, based on a linear combination of the previous search % direction and the new (preconditioned) gradient. Possible values % for this parameter are: % 'S-D', 'steep' for beta = 0 (preconditioned steepest descent) % 'F-R' for Fletcher-Reeves's rule % 'P-R' for Polak-Ribiere's modified rule % 'H-S' for Hestenes-Stiefel's modified rule % 'H-Z' for Hager-Zhang's modified rule % See Hager and Zhang 2006, "A survey of nonlinear conjugate gradient % methods" for a description of these rules in the Euclidean case and % for an explanation of how to adapt them to the preconditioned case. % The adaption to the Riemannian case is straightforward: see in code % for details. Modified rules take the max between 0 and the computed % beta value, which provides automatic restart, except for H-Z which % uses a different modification. % orth_value (Inf) % Following Powell's restart strategy (Math. prog. 1977), restart CG % (that is, make a -preconditioned- gradient step) if two successive % -preconditioned- gradients are "too" parallel. See for example % Hager and Zhang 2006, "A survey of nonlinear conjugate gradient % methods", page 12. An infinite value disables this strategy. See in % code formula for the specific criterion used. % linesearch (@linesearch_adaptive or @linesearch_hint) % Function handle to a line search function. The options structure is % passed to the line search too, so you can pass it parameters. See % each line search's documentation for info. Another available line % search in manopt is @linesearch, in /manopt/linesearch/linesearch.m % If the problem structure includes a line search hint, then the % default line search used is @linesearch_hint. % statsfun (none) % Function handle to a function that will be called after each % iteration to provide the opportunity to log additional statistics. % They will be returned in the info struct. See the generic Manopt % documentation about solvers for further information. % stopfun (none) % Function handle to a function that will be called at each iteration % to provide the opportunity to specify additional stopping criteria. % See the generic Manopt documentation about solvers for further % information. % verbosity (3) % Integer number used to tune the amount of output the algorithm % generates during execution (mostly as text in the command window). % The higher, the more output. 0 means silent. % storedepth (2) % Maximum number of different points x of the manifold for which a % store structure will be kept in memory in the storedb. If the % caching features of Manopt are not used, this is irrelevant. For % the CG algorithm, a store depth of 2 should always be sufficient. % % % In most of the examples bundled with the toolbox (see link below), the % solver can be replaced by the present one if need be. % % See also: steepestdescent trustregions manopt/solvers/linesearch manopt/examples % An explicit, general listing of this algorithm, with preconditioning, % can be found in the following paper: % @Article{boumal2015lowrank, % Title = {Low-rank matrix completion via preconditioned optimization on the {G}rassmann manifold}, % Author = {Boumal, N. and Absil, P.-A.}, % Journal = {Linear Algebra and its Applications}, % Year = {2015}, % Pages = {200--239}, % Volume = {475}, % Doi = {10.1016/j.laa.2015.02.027}, % } % This file is part of Manopt: www.manopt.org. % Original author: Bamdev Mishra, Dec. 30, 2012. % Contributors: Nicolas Boumal % Change log: % % March 14, 2013, NB: % Added preconditioner support : see Section 8 in % https://www.math.lsu.edu/~hozhang/papers/cgsurvey.pdf % % Sept. 13, 2013, NB: % Now logging beta parameter too. % % Nov. 7, 2013, NB: % The search direction is no longer normalized before it is passed % to the linesearch. This way, it is up to the designers of the % linesearch to decide whether they want to use the norm of the % search direction in their algorithm or not. There are reasons % against it, but practical evidence that it may help too, so we % allow it. The default linesearch_adaptive used does exploit the % norm information. The base linesearch does not. You may select it % by setting options.linesearch = @linesearch; % % Nov. 29, 2013, NB: % Documentation improved: options are now explicitly described. % Removed the Daniel rule for beta: it was not appropriate for % preconditioned CG and I could not find a proper reference for it. % % April 3, 2015 (NB): % Works with the new StoreDB class system. % Verify that the problem description is sufficient for the solver. if ~canGetCost(problem) warning('manopt:getCost', ... 'No cost provided. The algorithm will likely abort.'); end if ~canGetGradient(problem) && ~canGetApproxGradient(problem) warning('manopt:getGradient:approx', ... ['No gradient provided. Using an FD approximation instead (slow).\n' ... 'It may be necessary to increase options.tolgradnorm.\n' ... 'To disable this warning: warning(''off'', ''manopt:getGradient:approx'')']); problem.approxgrad = approxgradientFD(problem); end % Set local defaults here localdefaults.minstepsize = 1e-10; localdefaults.maxiter = 1000; localdefaults.tolgradnorm = 1e-6; localdefaults.storedepth = 20; % Changed by NB : H-S has the "auto restart" property. % See Hager-Zhang 2005/2006 survey about CG methods. % The auto restart comes from the 'max(0, ...)', not so much from the % reason stated in Hager-Zhang I think. P-R also has auto restart. localdefaults.beta_type = 'H-S'; localdefaults.orth_value = Inf; % by BM as suggested in Nocedal and Wright % Depending on whether the problem structure specifies a hint for % line-search algorithms, choose a default line-search that works on % its own (typical) or that uses the hint. if ~canGetLinesearch(problem) localdefaults.linesearch = @linesearch_adaptive; else localdefaults.linesearch = @linesearch_hint; end % Merge global and local defaults, then merge w/ user options, if any. localdefaults = mergeOptions(getGlobalDefaults(), localdefaults); if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(localdefaults, options); % For convenience inner = problem.M.inner; lincomb = problem.M.lincomb; timetic = tic(); % If no initial point x is given by the user, generate one at random. if ~exist('x', 'var') || isempty(x) x = problem.M.rand(); end % Create a store database and generate a key for the current x storedb = StoreDB(options.storedepth); key = storedb.getNewKey(); % Compute cost-related quantities for x [cost, grad] = getCostGrad(problem, x, storedb, key); gradnorm = problem.M.norm(x, grad); Pgrad = getPrecon(problem, x, grad, storedb, key); gradPgrad = inner(x, grad, Pgrad); % Iteration counter (at any point, iter is the number of fully executed % iterations so far) iter = 0; % Save stats in a struct array info and preallocate. stats = savestats(); info(1) = stats; info(min(10000, options.maxiter+1)).iter = []; if options.verbosity >= 2 fprintf(' iter\t cost val\t grad. norm\n'); end % Compute a first descent direction (not normalized) desc_dir = lincomb(x, -1, Pgrad); % Start iterating until stopping criterion triggers while true % Display iteration information if options.verbosity >= 2 fprintf('%5d\t%+.16e\t%.8e\n', iter, cost, gradnorm); end % Start timing this iteration timetic = tic(); % Run standard stopping criterion checks [stop, reason] = stoppingcriterion(problem, x, options, info, iter+1); % Run specific stopping criterion check if ~stop && abs(stats.stepsize) < options.minstepsize stop = true; reason = sprintf(['Last stepsize smaller than minimum ' ... 'allowed; options.minstepsize = %g.'], ... options.minstepsize); end if stop if options.verbosity >= 1 fprintf([reason '\n']); end break; end % The line search algorithms require the directional derivative of the % cost at the current point x along the search direction. df0 = inner(x, grad, desc_dir); % If we didn't get a descent direction: restart, i.e., switch to the % negative gradient. Equivalent to resetting the CG direction to a % steepest descent step, which discards the past information. if df0 >= 0 % Or we switch to the negative gradient direction. if options.verbosity >= 3 fprintf(['Conjugate gradient info: got an ascent direction '... '(df0 = %2e), reset to the (preconditioned) '... 'steepest descent direction.\n'], df0); end % Reset to negative gradient: this discards the CG memory. desc_dir = lincomb(x, -1, Pgrad); df0 = -gradPgrad; end % Execute line search [stepsize, newx, newkey, lsstats] = options.linesearch( ... problem, x, desc_dir, cost, df0, options, storedb, key); % Compute the new cost-related quantities for newx [newcost, newgrad] = getCostGrad(problem, newx, storedb, newkey); newgradnorm = problem.M.norm(newx, newgrad); Pnewgrad = getPrecon(problem, newx, newgrad, storedb, newkey); newgradPnewgrad = inner(newx, newgrad, Pnewgrad); % Apply the CG scheme to compute the next search direction. % % This paper https://www.math.lsu.edu/~hozhang/papers/cgsurvey.pdf % by Hager and Zhang lists many known beta rules. The rules defined % here can be found in that paper (or are provided with additional % references), adapted to the Riemannian setting. % if strcmpi(options.beta_type, 'steep') || ... strcmpi(options.beta_type, 'S-D') % Gradient Descent beta = 0; desc_dir = lincomb(x, -1, Pnewgrad); else oldgrad = problem.M.transp(x, newx, grad); orth_grads = inner(newx, oldgrad, Pnewgrad) / newgradPnewgrad; % Powell's restart strategy (see page 12 of Hager and Zhang's % survey on conjugate gradient methods, for example) if abs(orth_grads) >= options.orth_value, beta = 0; desc_dir = lincomb(x, -1, Pnewgrad); else % Compute the CG modification desc_dir = problem.M.transp(x, newx, desc_dir); switch upper(options.beta_type) case 'F-R' % Fletcher-Reeves beta = newgradPnewgrad / gradPgrad; case 'P-R' % Polak-Ribiere+ % vector grad(new) - transported grad(current) diff = lincomb(newx, 1, newgrad, -1, oldgrad); ip_diff = inner(newx, Pnewgrad, diff); beta = ip_diff / gradPgrad; beta = max(0, beta); case 'H-S' % Hestenes-Stiefel+ diff = lincomb(newx, 1, newgrad, -1, oldgrad); ip_diff = inner(newx, Pnewgrad, diff); beta = ip_diff / inner(newx, diff, desc_dir); beta = max(0, beta); case 'H-Z' % Hager-Zhang+ diff = lincomb(newx, 1, newgrad, -1, oldgrad); Poldgrad = problem.M.transp(x, newx, Pgrad); Pdiff = lincomb(newx, 1, Pnewgrad, -1, Poldgrad); deno = inner(newx, diff, desc_dir); numo = inner(newx, diff, Pnewgrad); numo = numo - 2*inner(newx, diff, Pdiff)*... inner(newx, desc_dir, newgrad) / deno; beta = numo / deno; % Robustness (see Hager-Zhang paper mentioned above) desc_dir_norm = problem.M.norm(newx, desc_dir); eta_HZ = -1 / ( desc_dir_norm * min(0.01, gradnorm) ); beta = max(beta, eta_HZ); otherwise error(['Unknown options.beta_type. ' ... 'Should be steep, S-D, F-R, P-R, H-S or H-Z.']); end desc_dir = lincomb(newx, -1, Pnewgrad, beta, desc_dir); end end % Make sure we don't use too much memory for the store database storedb.purge(); % Transfer iterate info x = newx; key = newkey; cost = newcost; grad = newgrad; Pgrad = Pnewgrad; gradnorm = newgradnorm; gradPgrad = newgradPnewgrad; % iter is the number of iterations we have accomplished. iter = iter + 1; % Log statistics for freshly executed iteration stats = savestats(); info(iter+1) = stats; %#ok<AGROW> end info = info(1:iter+1); if options.verbosity >= 1 fprintf('Total time is %f [s] (excludes statsfun)\n', info(end).time); end % Routine in charge of collecting the current iteration stats function stats = savestats() stats.iter = iter; stats.cost = cost; stats.gradnorm = gradnorm; if iter == 0 stats.stepsize = nan; stats.time = toc(timetic); stats.linesearch = []; stats.beta = 0; else stats.stepsize = stepsize; stats.time = info(iter).time + toc(timetic); stats.linesearch = lsstats; stats.beta = beta; end stats = applyStatsfun(problem, x, storedb, key, options, stats); end end
2881099/FreeSql.AdminLTE
152,983
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-bs5.min.js
/*! Summernote v0.8.20 | (c) 2013- Alan Hong and contributors | MIT license */ !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e(require("jQuery"));else if("function"==typeof define&&define.amd)define(["jQuery"],e);else{var n="object"==typeof exports?e(require("jQuery")):e(t.jQuery);for(var o in n)("object"==typeof exports?exports:t)[o]=n[o]}}(self,(function(t){return(()=>{"use strict";var e={9770:(t,e,n)=>{var o=n(1145),i=n.n(o);i().summernote=i().summernote||{lang:{}},i().extend(i().summernote.lang,{"en-US":{font:{bold:"Bold",italic:"Italic",underline:"Underline",clear:"Remove Font Style",height:"Line Height",name:"Font Family",strikethrough:"Strikethrough",subscript:"Subscript",superscript:"Superscript",size:"Font Size",sizeunit:"Font Size Unit"},image:{image:"Picture",insert:"Insert Image",resizeFull:"Resize full",resizeHalf:"Resize half",resizeQuarter:"Resize quarter",resizeNone:"Original size",floatLeft:"Float Left",floatRight:"Float Right",floatNone:"Remove float",shapeRounded:"Shape: Rounded",shapeCircle:"Shape: Circle",shapeThumbnail:"Shape: Thumbnail",shapeNone:"Shape: None",dragImageHere:"Drag image or text here",dropImage:"Drop image or Text",selectFromFiles:"Select from files",maximumFileSize:"Maximum file size",maximumFileSizeError:"Maximum file size exceeded.",url:"Image URL",remove:"Remove Image",original:"Original"},video:{video:"Video",videoLink:"Video Link",insert:"Insert Video",url:"Video URL",providers:"(YouTube, Google Drive, Vimeo, Vine, Instagram, DailyMotion, Youku, Peertube)"},link:{link:"Link",insert:"Insert Link",unlink:"Unlink",edit:"Edit",textToDisplay:"Text to display",url:"To what URL should this link go?",openInNewWindow:"Open in new window",useProtocol:"Use default protocol"},table:{table:"Table",addRowAbove:"Add row above",addRowBelow:"Add row below",addColLeft:"Add column left",addColRight:"Add column right",delRow:"Delete row",delCol:"Delete column",delTable:"Delete table"},hr:{insert:"Insert Horizontal Rule"},style:{style:"Style",p:"Normal",blockquote:"Quote",pre:"Code",h1:"Header 1",h2:"Header 2",h3:"Header 3",h4:"Header 4",h5:"Header 5",h6:"Header 6"},lists:{unordered:"Unordered list",ordered:"Ordered list"},options:{help:"Help",fullscreen:"Full Screen",codeview:"Code View"},paragraph:{paragraph:"Paragraph",outdent:"Outdent",indent:"Indent",left:"Align left",center:"Align center",right:"Align right",justify:"Justify full"},color:{recent:"Recent Color",more:"More Color",background:"Background Color",foreground:"Text Color",transparent:"Transparent",setTransparent:"Set transparent",reset:"Reset",resetToDefault:"Reset to default",cpSelect:"Select"},shortcut:{shortcuts:"Keyboard shortcuts",close:"Close",textFormatting:"Text formatting",action:"Action",paragraphFormatting:"Paragraph formatting",documentStyle:"Document Style",extraKeys:"Extra keys"},help:{escape:"Escape",insertParagraph:"Insert Paragraph",undo:"Undo the last command",redo:"Redo the last command",tab:"Tab",untab:"Untab",bold:"Set a bold style",italic:"Set a italic style",underline:"Set a underline style",strikethrough:"Set a strikethrough style",removeFormat:"Clean a style",justifyLeft:"Set left align",justifyCenter:"Set center align",justifyRight:"Set right align",justifyFull:"Set full align",insertUnorderedList:"Toggle unordered list",insertOrderedList:"Toggle ordered list",outdent:"Outdent on current paragraph",indent:"Indent on current paragraph",formatPara:"Change current block's format as a paragraph(P tag)",formatH1:"Change current block's format as H1",formatH2:"Change current block's format as H2",formatH3:"Change current block's format as H3",formatH4:"Change current block's format as H4",formatH5:"Change current block's format as H5",formatH6:"Change current block's format as H6",insertHorizontalRule:"Insert horizontal rule","linkDialog.show":"Show Link Dialog"},history:{undo:"Undo",redo:"Redo"},specialChar:{specialChar:"SPECIAL CHARACTERS",select:"Select Special characters"},output:{noSelection:"No Selection Made!"}}})},1145:e=>{e.exports=t}},n={};function o(t){var i=n[t];if(void 0!==i)return i.exports;var r=n[t]={exports:{}};return e[t](r,r.exports,o),r.exports}o.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return o.d(e,{a:e}),e},o.d=(t,e)=>{for(var n in e)o.o(e,n)&&!o.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},o.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),o.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var i={};return(()=>{o.r(i);var t=o(1145),e=o.n(t),n=(o(9770),["sans-serif","serif","monospace","cursive","fantasy"]);function r(t){return-1===e().inArray(t.toLowerCase(),n)?"'".concat(t,"'"):t}var a,s=navigator.userAgent,l=/MSIE|Trident/i.test(s);if(l){var c=/MSIE (\d+[.]\d+)/.exec(s);c&&(a=parseFloat(c[1])),(c=/Trident\/.*rv:([0-9]{1,}[.0-9]{0,})/.exec(s))&&(a=parseFloat(c[1]))}var u=/Edge\/\d+/.test(s),d="ontouchstart"in window||navigator.MaxTouchPoints>0||navigator.msMaxTouchPoints>0,h=l?"DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted":"input";const f={isMac:navigator.appVersion.indexOf("Mac")>-1,isMSIE:l,isEdge:u,isFF:!u&&/firefox/i.test(s),isPhantom:/PhantomJS/i.test(s),isWebkit:!u&&/webkit/i.test(s),isChrome:!u&&/chrome/i.test(s),isSafari:!u&&/safari/i.test(s)&&!/chrome/i.test(s),browserVersion:a,isSupportTouch:d,isFontInstalled:function(t){var e="Comic Sans MS"===t?"Courier New":"Comic Sans MS",n="mmmmmmmmmmwwwww",o=document.createElement("canvas").getContext("2d");o.font="200px '"+e+"'";var i=o.measureText(n).width;return o.font="200px "+r(t)+', "'+e+'"',i!==o.measureText(n).width},isW3CRangeSupport:!!document.createRange,inputEventName:h,genericFontFamilies:n,validFontName:r};var p=0;const m={eq:function(t){return function(e){return t===e}},eq2:function(t,e){return t===e},peq2:function(t){return function(e,n){return e[t]===n[t]}},ok:function(){return!0},fail:function(){return!1},self:function(t){return t},not:function(t){return function(){return!t.apply(t,arguments)}},and:function(t,e){return function(n){return t(n)&&e(n)}},invoke:function(t,e){return function(){return t[e].apply(t,arguments)}},resetUniqueId:function(){p=0},uniqueId:function(t){var e=++p+"";return t?t+e:e},rect2bnd:function(t){var n=e()(document);return{top:t.top+n.scrollTop(),left:t.left+n.scrollLeft(),width:t.right-t.left,height:t.bottom-t.top}},invertObject:function(t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[t[n]]=n);return e},namespaceToCamel:function(t,e){return(e=e||"")+t.split(".").map((function(t){return t.substring(0,1).toUpperCase()+t.substring(1)})).join("")},debounce:function(t,e,n){var o;return function(){var i=this,r=arguments,a=function(){o=null,n||t.apply(i,r)},s=n&&!o;clearTimeout(o),o=setTimeout(a,e),s&&t.apply(i,r)}},isValidUrl:function(t){return/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/gi.test(t)}};function v(t){return t[0]}function g(t){return t[t.length-1]}function b(t){return t.slice(1)}function y(t,e){if(t&&t.length&&e){if(t.indexOf)return-1!==t.indexOf(e);if(t.contains)return t.contains(e)}return!1}const k={head:v,last:g,initial:function(t){return t.slice(0,t.length-1)},tail:b,prev:function(t,e){if(t&&t.length&&e){var n=t.indexOf(e);return-1===n?null:t[n-1]}return null},next:function(t,e){if(t&&t.length&&e){var n=t.indexOf(e);return-1===n?null:t[n+1]}return null},find:function(t,e){for(var n=0,o=t.length;n<o;n++){var i=t[n];if(e(i))return i}},contains:y,all:function(t,e){for(var n=0,o=t.length;n<o;n++)if(!e(t[n]))return!1;return!0},sum:function(t,e){return e=e||m.self,t.reduce((function(t,n){return t+e(n)}),0)},from:function(t){for(var e=[],n=t.length,o=-1;++o<n;)e[o]=t[o];return e},isEmpty:function(t){return!t||!t.length},clusterBy:function(t,e){return t.length?b(t).reduce((function(t,n){var o=g(t);return e(g(o),n)?o[o.length]=n:t[t.length]=[n],t}),[[v(t)]]):[]},compact:function(t){for(var e=[],n=0,o=t.length;n<o;n++)t[n]&&e.push(t[n]);return e},unique:function(t){for(var e=[],n=0,o=t.length;n<o;n++)y(e,t[n])||e.push(t[n]);return e}};var w=String.fromCharCode(160);function C(t){return t&&e()(t).hasClass("note-editable")}function x(t){return t=t.toUpperCase(),function(e){return e&&e.nodeName.toUpperCase()===t}}function S(t){return t&&3===t.nodeType}function T(t){return t&&/^BR|^IMG|^HR|^IFRAME|^BUTTON|^INPUT|^AUDIO|^VIDEO|^EMBED/.test(t.nodeName.toUpperCase())}function E(t){return!C(t)&&(t&&/^DIV|^P|^LI|^H[1-7]/.test(t.nodeName.toUpperCase()))}var I=x("PRE"),$=x("LI");var N=x("TABLE"),P=x("DATA");function R(t){return!(H(t)||L(t)||A(t)||E(t)||N(t)||D(t)||P(t))}function L(t){return t&&/^UL|^OL/.test(t.nodeName.toUpperCase())}var A=x("HR");function F(t){return t&&/^TD|^TH/.test(t.nodeName.toUpperCase())}var D=x("BLOCKQUOTE");function H(t){return F(t)||D(t)||C(t)}var z=x("A");var B=x("BODY");var M=f.isMSIE&&f.browserVersion<11?"&nbsp;":"<br>";function O(t){return S(t)?t.nodeValue.length:t?t.childNodes.length:0}function U(t){var e=O(t);return 0===e||(!S(t)&&1===e&&t.innerHTML===M||!(!k.all(t.childNodes,S)||""!==t.innerHTML))}function j(t){T(t)||O(t)||(t.innerHTML=M)}function W(t,e){for(;t;){if(e(t))return t;if(C(t))break;t=t.parentNode}return null}function K(t,e){e=e||m.fail;var n=[];return W(t,(function(t){return C(t)||n.push(t),e(t)})),n}function V(t,e){e=e||m.fail;for(var n=[];t&&!e(t);)n.push(t),t=t.nextSibling;return n}function q(t,e){var n=e.nextSibling,o=e.parentNode;return n?o.insertBefore(t,n):o.appendChild(t),t}function _(t,n){return e().each(n,(function(e,n){t.appendChild(n)})),t}function G(t){return 0===t.offset}function Y(t){return t.offset===O(t.node)}function Z(t){return G(t)||Y(t)}function Q(t,e){for(;t&&t!==e;){if(0!==J(t))return!1;t=t.parentNode}return!0}function X(t,e){if(!e)return!1;for(;t&&t!==e;){if(J(t)!==O(t.parentNode)-1)return!1;t=t.parentNode}return!0}function J(t){for(var e=0;t=t.previousSibling;)e+=1;return e}function tt(t){return!!(t&&t.childNodes&&t.childNodes.length)}function et(t,e){var n,o;if(0===t.offset){if(C(t.node))return null;n=t.node.parentNode,o=J(t.node)}else tt(t.node)?o=O(n=t.node.childNodes[t.offset-1]):(n=t.node,o=e?0:t.offset-1);return{node:n,offset:o}}function nt(t,e){var n,o;if(O(t.node)===t.offset){if(C(t.node))return null;var i=it(t.node);i?(n=i,o=0):(n=t.node.parentNode,o=J(t.node)+1)}else tt(t.node)?(n=t.node.childNodes[t.offset],o=0):(n=t.node,o=e?O(t.node):t.offset+1);return{node:n,offset:o}}function ot(t,e){var n,o=0;if(U(t.node))return null===t.node?null:{node:n=t.node.nextSibling,offset:o=0};if(O(t.node)===t.offset){if(C(t.node))return null;n=t.node.parentNode,o=J(t.node)+1,C(n)&&(n=t.node.nextSibling,o=0)}else if(tt(t.node)){if(o=0,U(n=t.node.childNodes[t.offset]))return U(t.node.nextSibling)?null:{node:t.node.nextSibling,offset:o}}else if(n=t.node,o=e?O(t.node):t.offset+1,U(n))return null;return{node:n,offset:o}}function it(t){if(t.nextSibling&&t.parent===t.nextSibling.parent)return S(t.nextSibling)?t.nextSibling:it(t.nextSibling)}function rt(t,e){return t.node===e.node&&t.offset===e.offset}function at(t,e){var n=e&&e.isSkipPaddingBlankHTML,o=e&&e.isNotSplitEdgePoint,i=e&&e.isDiscardEmptySplits;if(i&&(n=!0),Z(t)&&(S(t.node)||o)){if(G(t))return t.node;if(Y(t))return t.node.nextSibling}if(S(t.node))return t.node.splitText(t.offset);var r=t.node.childNodes[t.offset],a=q(t.node.cloneNode(!1),t.node);return _(a,V(r)),n||(j(t.node),j(a)),i&&(U(t.node)&&ct(t.node),U(a))?(ct(a),t.node.nextSibling):a}function st(t,e,n){var o=K(e.node,m.eq(t));return o.length?1===o.length?at(e,n):o.reduce((function(t,o){return t===e.node&&(t=at(e,n)),at({node:o,offset:t?J(t):O(o)},n)})):null}function lt(t){return document.createElement(t)}function ct(t,e){if(t&&t.parentNode){if(t.removeNode)return t.removeNode(e);var n=t.parentNode;if(!e){for(var o=[],i=0,r=t.childNodes.length;i<r;i++)o.push(t.childNodes[i]);for(var a=0,s=o.length;a<s;a++)n.insertBefore(o[a],t)}n.removeChild(t)}}var ut=x("TEXTAREA");function dt(t,e){var n=ut(t[0])?t.val():t.html();return e?n.replace(/[\n\r]/g,""):n}const ht={NBSP_CHAR:w,ZERO_WIDTH_NBSP_CHAR:"\ufeff",blank:M,emptyPara:"<p>".concat(M,"</p>"),makePredByNodeName:x,isEditable:C,isControlSizing:function(t){return t&&e()(t).hasClass("note-control-sizing")},isText:S,isElement:function(t){return t&&1===t.nodeType},isVoid:T,isPara:E,isPurePara:function(t){return E(t)&&!$(t)},isHeading:function(t){return t&&/^H[1-7]/.test(t.nodeName.toUpperCase())},isInline:R,isBlock:m.not(R),isBodyInline:function(t){return R(t)&&!W(t,E)},isBody:B,isParaInline:function(t){return R(t)&&!!W(t,E)},isPre:I,isList:L,isTable:N,isData:P,isCell:F,isBlockquote:D,isBodyContainer:H,isAnchor:z,isDiv:x("DIV"),isLi:$,isBR:x("BR"),isSpan:x("SPAN"),isB:x("B"),isU:x("U"),isS:x("S"),isI:x("I"),isImg:x("IMG"),isTextarea:ut,deepestChildIsEmpty:function(t){do{if(null===t.firstElementChild||""===t.firstElementChild.innerHTML)break}while(t=t.firstElementChild);return U(t)},isEmpty:U,isEmptyAnchor:m.and(z,U),isClosestSibling:function(t,e){return t.nextSibling===e||t.previousSibling===e},withClosestSiblings:function(t,e){e=e||m.ok;var n=[];return t.previousSibling&&e(t.previousSibling)&&n.push(t.previousSibling),n.push(t),t.nextSibling&&e(t.nextSibling)&&n.push(t.nextSibling),n},nodeLength:O,isLeftEdgePoint:G,isRightEdgePoint:Y,isEdgePoint:Z,isLeftEdgeOf:Q,isRightEdgeOf:X,isLeftEdgePointOf:function(t,e){return G(t)&&Q(t.node,e)},isRightEdgePointOf:function(t,e){return Y(t)&&X(t.node,e)},prevPoint:et,nextPoint:nt,nextPointWithEmptyNode:ot,isSamePoint:rt,isVisiblePoint:function(t){if(S(t.node)||!tt(t.node)||U(t.node))return!0;var e=t.node.childNodes[t.offset-1],n=t.node.childNodes[t.offset];return!((e&&!T(e)||n&&!T(n))&&!N(n))},prevPointUntil:function(t,e){for(;t;){if(e(t))return t;t=et(t)}return null},nextPointUntil:function(t,e){for(;t;){if(e(t))return t;t=nt(t)}return null},isCharPoint:function(t){if(!S(t.node))return!1;var e=t.node.nodeValue.charAt(t.offset-1);return e&&" "!==e&&e!==w},isSpacePoint:function(t){if(!S(t.node))return!1;var e=t.node.nodeValue.charAt(t.offset-1);return" "===e||e===w},walkPoint:function(t,e,n,o){for(var i=t;i&&(n(i),!rt(i,e));){i=ot(i,o&&t.node!==i.node&&e.node!==i.node)}},ancestor:W,singleChildAncestor:function(t,e){for(t=t.parentNode;t&&1===O(t);){if(e(t))return t;if(C(t))break;t=t.parentNode}return null},listAncestor:K,lastAncestor:function(t,e){var n=K(t);return k.last(n.filter(e))},listNext:V,listPrev:function(t,e){e=e||m.fail;for(var n=[];t&&!e(t);)n.push(t),t=t.previousSibling;return n},listDescendant:function(t,e){var n=[];return e=e||m.ok,function o(i){t!==i&&e(i)&&n.push(i);for(var r=0,a=i.childNodes.length;r<a;r++)o(i.childNodes[r])}(t),n},commonAncestor:function(t,e){for(var n=K(t),o=e;o;o=o.parentNode)if(n.indexOf(o)>-1)return o;return null},wrap:function(t,n){var o=t.parentNode,i=e()("<"+n+">")[0];return o.insertBefore(i,t),i.appendChild(t),i},insertAfter:q,appendChildNodes:_,position:J,hasChildren:tt,makeOffsetPath:function(t,e){return K(e,m.eq(t)).map(J).reverse()},fromOffsetPath:function(t,e){for(var n=t,o=0,i=e.length;o<i;o++)n=n.childNodes.length<=e[o]?n.childNodes[n.childNodes.length-1]:n.childNodes[e[o]];return n},splitTree:st,splitPoint:function(t,e){var n,o,i=e?E:H,r=K(t.node,i),a=k.last(r)||t.node;i(a)?(n=r[r.length-2],o=a):o=(n=a).parentNode;var s=n&&st(n,t,{isSkipPaddingBlankHTML:e,isNotSplitEdgePoint:e});return s||o!==t.node||(s=t.node.childNodes[t.offset]),{rightNode:s,container:o}},create:lt,createText:function(t){return document.createTextNode(t)},remove:ct,removeWhile:function(t,e){for(;t&&!C(t)&&e(t);){var n=t.parentNode;ct(t),t=n}},replace:function(t,e){if(t.nodeName.toUpperCase()===e.toUpperCase())return t;var n=lt(e);return t.style.cssText&&(n.style.cssText=t.style.cssText),_(n,k.from(t.childNodes)),q(n,t),ct(t),n},html:function(t,e){var n=dt(t);if(e){n=(n=n.replace(/<(\/?)(\b(?!!)[^>\s]*)(.*?)(\s*\/?>)/g,(function(t,e,n){n=n.toUpperCase();var o=/^DIV|^TD|^TH|^P|^LI|^H[1-7]/.test(n)&&!!e,i=/^BLOCKQUOTE|^TABLE|^TBODY|^TR|^HR|^UL|^OL/.test(n);return t+(o||i?"\n":"")}))).trim()}return n},value:dt,posFromPlaceholder:function(t){var n=e()(t),o=n.offset(),i=n.outerHeight(!0);return{left:o.left,top:o.top+i}},attachEvents:function(t,e){Object.keys(e).forEach((function(n){t.on(n,e[n])}))},detachEvents:function(t,e){Object.keys(e).forEach((function(n){t.off(n,e[n])}))},isCustomStyleTag:function(t){return t&&!S(t)&&k.contains(t.classList,"note-styletag")}};function ft(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var pt=function(){function t(n,o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$note=n,this.memos={},this.modules={},this.layoutInfo={},this.options=e().extend(!0,{},o),e().summernote.ui=e().summernote.ui_template(this.options),this.ui=e().summernote.ui,this.initialize()}var n,o,i;return n=t,o=[{key:"initialize",value:function(){return this.layoutInfo=this.ui.createLayout(this.$note),this._initialize(),this.$note.hide(),this}},{key:"destroy",value:function(){this._destroy(),this.$note.removeData("summernote"),this.ui.removeLayout(this.$note,this.layoutInfo)}},{key:"reset",value:function(){var t=this.isDisabled();this.code(ht.emptyPara),this._destroy(),this._initialize(),t&&this.disable()}},{key:"_initialize",value:function(){var t=this;this.options.id=m.uniqueId(e().now()),this.options.container=this.options.container||this.layoutInfo.editor;var n=e().extend({},this.options.buttons);Object.keys(n).forEach((function(e){t.memo("button."+e,n[e])}));var o=e().extend({},this.options.modules,e().summernote.plugins||{});Object.keys(o).forEach((function(e){t.module(e,o[e],!0)})),Object.keys(this.modules).forEach((function(e){t.initializeModule(e)}))}},{key:"_destroy",value:function(){var t=this;Object.keys(this.modules).reverse().forEach((function(e){t.removeModule(e)})),Object.keys(this.memos).forEach((function(e){t.removeMemo(e)})),this.triggerEvent("destroy",this)}},{key:"code",value:function(t){var e=this.invoke("codeview.isActivated");if(void 0===t)return this.invoke("codeview.sync"),e?this.layoutInfo.codable.val():this.layoutInfo.editable.html();e?this.invoke("codeview.sync",t):this.layoutInfo.editable.html(t),this.$note.val(t),this.triggerEvent("change",t,this.layoutInfo.editable)}},{key:"isDisabled",value:function(){return"false"===this.layoutInfo.editable.attr("contenteditable")}},{key:"enable",value:function(){this.layoutInfo.editable.attr("contenteditable",!0),this.invoke("toolbar.activate",!0),this.triggerEvent("disable",!1),this.options.editing=!0}},{key:"disable",value:function(){this.invoke("codeview.isActivated")&&this.invoke("codeview.deactivate"),this.layoutInfo.editable.attr("contenteditable",!1),this.options.editing=!1,this.invoke("toolbar.deactivate",!0),this.triggerEvent("disable",!0)}},{key:"triggerEvent",value:function(){var t=k.head(arguments),e=k.tail(k.from(arguments)),n=this.options.callbacks[m.namespaceToCamel(t,"on")];n&&n.apply(this.$note[0],e),this.$note.trigger("summernote."+t,e)}},{key:"initializeModule",value:function(t){var e=this.modules[t];e.shouldInitialize=e.shouldInitialize||m.ok,e.shouldInitialize()&&(e.initialize&&e.initialize(),e.events&&ht.attachEvents(this.$note,e.events))}},{key:"module",value:function(t,e,n){if(1===arguments.length)return this.modules[t];this.modules[t]=new e(this),n||this.initializeModule(t)}},{key:"removeModule",value:function(t){var e=this.modules[t];e.shouldInitialize()&&(e.events&&ht.detachEvents(this.$note,e.events),e.destroy&&e.destroy()),delete this.modules[t]}},{key:"memo",value:function(t,e){if(1===arguments.length)return this.memos[t];this.memos[t]=e}},{key:"removeMemo",value:function(t){this.memos[t]&&this.memos[t].destroy&&this.memos[t].destroy(),delete this.memos[t]}},{key:"createInvokeHandlerAndUpdateState",value:function(t,e){var n=this;return function(o){n.createInvokeHandler(t,e)(o),n.invoke("buttons.updateCurrentStyle")}}},{key:"createInvokeHandler",value:function(t,n){var o=this;return function(i){i.preventDefault();var r=e()(i.target);o.invoke(t,n||r.closest("[data-value]").data("value"),r)}}},{key:"invoke",value:function(){var t=k.head(arguments),e=k.tail(k.from(arguments)),n=t.split("."),o=n.length>1,i=o&&k.head(n),r=o?k.last(n):k.head(n),a=this.modules[i||"editor"];return!i&&this[r]?this[r].apply(this,e):a&&a[r]&&a.shouldInitialize()?a[r].apply(a,e):void 0}}],o&&ft(n.prototype,o),i&&ft(n,i),t}();function mt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}function vt(t,e){var n,o,i=t.parentElement(),r=document.body.createTextRange(),a=k.from(i.childNodes);for(n=0;n<a.length;n++)if(!ht.isText(a[n])){if(r.moveToElementText(a[n]),r.compareEndPoints("StartToStart",t)>=0)break;o=a[n]}if(0!==n&&ht.isText(a[n-1])){var s=document.body.createTextRange(),l=null;s.moveToElementText(o||i),s.collapse(!o),l=o?o.nextSibling:i.firstChild;var c=t.duplicate();c.setEndPoint("StartToStart",s);for(var u=c.text.replace(/[\r\n]/g,"").length;u>l.nodeValue.length&&l.nextSibling;)u-=l.nodeValue.length,l=l.nextSibling;l.nodeValue;e&&l.nextSibling&&ht.isText(l.nextSibling)&&u===l.nodeValue.length&&(u-=l.nodeValue.length,l=l.nextSibling),i=l,n=u}return{cont:i,offset:n}}function gt(t){var e=document.body.createTextRange(),n=function t(e,n){var o,i;if(ht.isText(e)){var r=ht.listPrev(e,m.not(ht.isText)),a=k.last(r).previousSibling;o=a||e.parentNode,n+=k.sum(k.tail(r),ht.nodeLength),i=!a}else{if(o=e.childNodes[n]||e,ht.isText(o))return t(o,0);n=0,i=!1}return{node:o,collapseToStart:i,offset:n}}(t.node,t.offset);return e.moveToElementText(n.node),e.collapse(n.collapseToStart),e.moveStart("character",n.offset),e}e().fn.extend({summernote:function(){var t=e().type(k.head(arguments)),n="string"===t,o="object"===t,i=e().extend({},e().summernote.options,o?k.head(arguments):{});i.langInfo=e().extend(!0,{},e().summernote.lang["en-US"],e().summernote.lang[i.lang]),i.icons=e().extend(!0,{},e().summernote.options.icons,i.icons),i.tooltip="auto"===i.tooltip?!f.isSupportTouch:i.tooltip,this.each((function(t,n){var o=e()(n);if(!o.data("summernote")){var r=new pt(o,i);o.data("summernote",r),o.data("summernote").triggerEvent("init",r.layoutInfo)}}));var r=this.first();if(r.length){var a=r.data("summernote");if(n)return a.invoke.apply(a,k.from(arguments));i.focus&&a.invoke("editor.focus")}return this}});var bt=function(){function t(e,n,o,i){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.sc=e,this.so=n,this.ec=o,this.eo=i,this.isOnEditable=this.makeIsOn(ht.isEditable),this.isOnList=this.makeIsOn(ht.isList),this.isOnAnchor=this.makeIsOn(ht.isAnchor),this.isOnCell=this.makeIsOn(ht.isCell),this.isOnData=this.makeIsOn(ht.isData)}var n,o,i;return n=t,o=[{key:"nativeRange",value:function(){if(f.isW3CRangeSupport){var t=document.createRange();return t.setStart(this.sc,this.so),t.setEnd(this.ec,this.eo),t}var e=gt({node:this.sc,offset:this.so});return e.setEndPoint("EndToEnd",gt({node:this.ec,offset:this.eo})),e}},{key:"getPoints",value:function(){return{sc:this.sc,so:this.so,ec:this.ec,eo:this.eo}}},{key:"getStartPoint",value:function(){return{node:this.sc,offset:this.so}}},{key:"getEndPoint",value:function(){return{node:this.ec,offset:this.eo}}},{key:"select",value:function(){var t=this.nativeRange();if(f.isW3CRangeSupport){var e=document.getSelection();e.rangeCount>0&&e.removeAllRanges(),e.addRange(t)}else t.select();return this}},{key:"scrollIntoView",value:function(t){var n=e()(t).height();return t.scrollTop+n<this.sc.offsetTop&&(t.scrollTop+=Math.abs(t.scrollTop+n-this.sc.offsetTop)),this}},{key:"normalize",value:function(){var e=function(t,e){if(!t)return t;if(ht.isVisiblePoint(t)&&(!ht.isEdgePoint(t)||ht.isRightEdgePoint(t)&&!e||ht.isLeftEdgePoint(t)&&e||ht.isRightEdgePoint(t)&&e&&ht.isVoid(t.node.nextSibling)||ht.isLeftEdgePoint(t)&&!e&&ht.isVoid(t.node.previousSibling)||ht.isBlock(t.node)&&ht.isEmpty(t.node)))return t;var n=ht.ancestor(t.node,ht.isBlock),o=!1;if(!o){var i=ht.prevPoint(t)||{node:null};o=(ht.isLeftEdgePointOf(t,n)||ht.isVoid(i.node))&&!e}var r=!1;if(!r){var a=ht.nextPoint(t)||{node:null};r=(ht.isRightEdgePointOf(t,n)||ht.isVoid(a.node))&&e}if(o||r){if(ht.isVisiblePoint(t))return t;e=!e}return(e?ht.nextPointUntil(ht.nextPoint(t),ht.isVisiblePoint):ht.prevPointUntil(ht.prevPoint(t),ht.isVisiblePoint))||t},n=e(this.getEndPoint(),!1),o=this.isCollapsed()?n:e(this.getStartPoint(),!0);return new t(o.node,o.offset,n.node,n.offset)}},{key:"nodes",value:function(t,e){t=t||m.ok;var n=e&&e.includeAncestor,o=e&&e.fullyContains,i=this.getStartPoint(),r=this.getEndPoint(),a=[],s=[];return ht.walkPoint(i,r,(function(e){var i;ht.isEditable(e.node)||(o?(ht.isLeftEdgePoint(e)&&s.push(e.node),ht.isRightEdgePoint(e)&&k.contains(s,e.node)&&(i=e.node)):i=n?ht.ancestor(e.node,t):e.node,i&&t(i)&&a.push(i))}),!0),k.unique(a)}},{key:"commonAncestor",value:function(){return ht.commonAncestor(this.sc,this.ec)}},{key:"expand",value:function(e){var n=ht.ancestor(this.sc,e),o=ht.ancestor(this.ec,e);if(!n&&!o)return new t(this.sc,this.so,this.ec,this.eo);var i=this.getPoints();return n&&(i.sc=n,i.so=0),o&&(i.ec=o,i.eo=ht.nodeLength(o)),new t(i.sc,i.so,i.ec,i.eo)}},{key:"collapse",value:function(e){return e?new t(this.sc,this.so,this.sc,this.so):new t(this.ec,this.eo,this.ec,this.eo)}},{key:"splitText",value:function(){var e=this.sc===this.ec,n=this.getPoints();return ht.isText(this.ec)&&!ht.isEdgePoint(this.getEndPoint())&&this.ec.splitText(this.eo),ht.isText(this.sc)&&!ht.isEdgePoint(this.getStartPoint())&&(n.sc=this.sc.splitText(this.so),n.so=0,e&&(n.ec=n.sc,n.eo=this.eo-this.so)),new t(n.sc,n.so,n.ec,n.eo)}},{key:"deleteContents",value:function(){if(this.isCollapsed())return this;var n=this.splitText(),o=n.nodes(null,{fullyContains:!0}),i=ht.prevPointUntil(n.getStartPoint(),(function(t){return!k.contains(o,t.node)})),r=[];return e().each(o,(function(t,e){var n=e.parentNode;i.node!==n&&1===ht.nodeLength(n)&&r.push(n),ht.remove(e,!1)})),e().each(r,(function(t,e){ht.remove(e,!1)})),new t(i.node,i.offset,i.node,i.offset).normalize()}},{key:"makeIsOn",value:function(t){return function(){var e=ht.ancestor(this.sc,t);return!!e&&e===ht.ancestor(this.ec,t)}}},{key:"isLeftEdgeOf",value:function(t){if(!ht.isLeftEdgePoint(this.getStartPoint()))return!1;var e=ht.ancestor(this.sc,t);return e&&ht.isLeftEdgeOf(this.sc,e)}},{key:"isCollapsed",value:function(){return this.sc===this.ec&&this.so===this.eo}},{key:"wrapBodyInlineWithPara",value:function(){if(ht.isBodyContainer(this.sc)&&ht.isEmpty(this.sc))return this.sc.innerHTML=ht.emptyPara,new t(this.sc.firstChild,0,this.sc.firstChild,0);var e,n=this.normalize();if(ht.isParaInline(this.sc)||ht.isPara(this.sc))return n;if(ht.isInline(n.sc)){var o=ht.listAncestor(n.sc,m.not(ht.isInline));e=k.last(o),ht.isInline(e)||(e=o[o.length-2]||n.sc.childNodes[n.so])}else e=n.sc.childNodes[n.so>0?n.so-1:0];if(e){var i=ht.listPrev(e,ht.isParaInline).reverse();if((i=i.concat(ht.listNext(e.nextSibling,ht.isParaInline))).length){var r=ht.wrap(k.head(i),"p");ht.appendChildNodes(r,k.tail(i))}}return this.normalize()}},{key:"insertNode",value:function(t){var e=this;(ht.isText(t)||ht.isInline(t))&&(e=this.wrapBodyInlineWithPara().deleteContents());var n=ht.splitPoint(e.getStartPoint(),ht.isInline(t));return n.rightNode?(n.rightNode.parentNode.insertBefore(t,n.rightNode),ht.isEmpty(n.rightNode)&&ht.isPara(t)&&n.rightNode.parentNode.removeChild(n.rightNode)):n.container.appendChild(t),t}},{key:"pasteHTML",value:function(t){t=e().trim(t);var n=e()("<div></div>").html(t)[0],o=k.from(n.childNodes),i=this,r=!1;return i.so>=0&&(o=o.reverse(),r=!0),o=o.map((function(t){return i.insertNode(t)})),r&&(o=o.reverse()),o}},{key:"toString",value:function(){var t=this.nativeRange();return f.isW3CRangeSupport?t.toString():t.text}},{key:"getWordRange",value:function(e){var n=this.getEndPoint();if(!ht.isCharPoint(n))return this;var o=ht.prevPointUntil(n,(function(t){return!ht.isCharPoint(t)}));return e&&(n=ht.nextPointUntil(n,(function(t){return!ht.isCharPoint(t)}))),new t(o.node,o.offset,n.node,n.offset)}},{key:"getWordsRange",value:function(e){var n=this.getEndPoint(),o=function(t){return!ht.isCharPoint(t)&&!ht.isSpacePoint(t)};if(o(n))return this;var i=ht.prevPointUntil(n,o);return e&&(n=ht.nextPointUntil(n,o)),new t(i.node,i.offset,n.node,n.offset)}},{key:"getWordsMatchRange",value:function(e){var n=this.getEndPoint(),o=ht.prevPointUntil(n,(function(o){if(!ht.isCharPoint(o)&&!ht.isSpacePoint(o))return!0;var i=new t(o.node,o.offset,n.node,n.offset),r=e.exec(i.toString());return r&&0===r.index})),i=new t(o.node,o.offset,n.node,n.offset),r=i.toString(),a=e.exec(r);return a&&a[0].length===r.length?i:null}},{key:"bookmark",value:function(t){return{s:{path:ht.makeOffsetPath(t,this.sc),offset:this.so},e:{path:ht.makeOffsetPath(t,this.ec),offset:this.eo}}}},{key:"paraBookmark",value:function(t){return{s:{path:k.tail(ht.makeOffsetPath(k.head(t),this.sc)),offset:this.so},e:{path:k.tail(ht.makeOffsetPath(k.last(t),this.ec)),offset:this.eo}}}},{key:"getClientRects",value:function(){return this.nativeRange().getClientRects()}}],o&&mt(n.prototype,o),i&&mt(n,i),t}();const yt={create:function(t,e,n,o){if(4===arguments.length)return new bt(t,e,n,o);if(2===arguments.length)return new bt(t,e,n=t,o=e);var i=this.createFromSelection();if(!i&&1===arguments.length){var r=arguments[0];return ht.isEditable(r)&&(r=r.lastChild),this.createFromBodyElement(r,ht.emptyPara===arguments[0].innerHTML)}return i},createFromBodyElement:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=this.createFromNode(t);return n.collapse(e)},createFromSelection:function(){var t,e,n,o;if(f.isW3CRangeSupport){var i=document.getSelection();if(!i||0===i.rangeCount)return null;if(ht.isBody(i.anchorNode))return null;var r=i.getRangeAt(0);t=r.startContainer,e=r.startOffset,n=r.endContainer,o=r.endOffset}else{var a=document.selection.createRange(),s=a.duplicate();s.collapse(!1);var l=a;l.collapse(!0);var c=vt(l,!0),u=vt(s,!1);ht.isText(c.node)&&ht.isLeftEdgePoint(c)&&ht.isTextNode(u.node)&&ht.isRightEdgePoint(u)&&u.node.nextSibling===c.node&&(c=u),t=c.cont,e=c.offset,n=u.cont,o=u.offset}return new bt(t,e,n,o)},createFromNode:function(t){var e=t,n=0,o=t,i=ht.nodeLength(o);return ht.isVoid(e)&&(n=ht.listPrev(e).length-1,e=e.parentNode),ht.isBR(o)?(i=ht.listPrev(o).length-1,o=o.parentNode):ht.isVoid(o)&&(i=ht.listPrev(o).length,o=o.parentNode),this.create(e,n,o,i)},createFromNodeBefore:function(t){return this.createFromNode(t).collapse(!0)},createFromNodeAfter:function(t){return this.createFromNode(t).collapse()},createFromBookmark:function(t,e){var n=ht.fromOffsetPath(t,e.s.path),o=e.s.offset,i=ht.fromOffsetPath(t,e.e.path),r=e.e.offset;return new bt(n,o,i,r)},createFromParaBookmark:function(t,e){var n=t.s.offset,o=t.e.offset,i=ht.fromOffsetPath(k.head(e),t.s.path),r=ht.fromOffsetPath(k.last(e),t.e.path);return new bt(i,n,r,o)}};var kt={BACKSPACE:8,TAB:9,ENTER:13,ESCAPE:27,SPACE:32,DELETE:46,LEFT:37,UP:38,RIGHT:39,DOWN:40,NUM0:48,NUM1:49,NUM2:50,NUM3:51,NUM4:52,NUM5:53,NUM6:54,NUM7:55,NUM8:56,B:66,E:69,I:73,J:74,K:75,L:76,R:82,S:83,U:85,V:86,Y:89,Z:90,SLASH:191,LEFTBRACKET:219,BACKSLASH:220,RIGHTBRACKET:221,HOME:36,END:35,PAGEUP:33,PAGEDOWN:34};const wt={isEdit:function(t){return k.contains([kt.BACKSPACE,kt.TAB,kt.ENTER,kt.SPACE,kt.DELETE],t)},isMove:function(t){return k.contains([kt.LEFT,kt.UP,kt.RIGHT,kt.DOWN],t)},isNavigation:function(t){return k.contains([kt.HOME,kt.END,kt.PAGEUP,kt.PAGEDOWN],t)},nameFromCode:m.invertObject(kt),code:kt};function Ct(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var xt=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.stack=[],this.stackOffset=-1,this.context=e,this.$editable=e.layoutInfo.editable,this.editable=this.$editable[0]}var e,n,o;return e=t,(n=[{key:"makeSnapshot",value:function(){var t=yt.create(this.editable);return{contents:this.$editable.html(),bookmark:t&&t.isOnEditable()?t.bookmark(this.editable):{s:{path:[],offset:0},e:{path:[],offset:0}}}}},{key:"applySnapshot",value:function(t){null!==t.contents&&this.$editable.html(t.contents),null!==t.bookmark&&yt.createFromBookmark(this.editable,t.bookmark).select()}},{key:"rewind",value:function(){this.$editable.html()!==this.stack[this.stackOffset].contents&&this.recordUndo(),this.stackOffset=0,this.applySnapshot(this.stack[this.stackOffset])}},{key:"commit",value:function(){this.stack=[],this.stackOffset=-1,this.recordUndo()}},{key:"reset",value:function(){this.stack=[],this.stackOffset=-1,this.$editable.html(""),this.recordUndo()}},{key:"undo",value:function(){this.$editable.html()!==this.stack[this.stackOffset].contents&&this.recordUndo(),this.stackOffset>0&&(this.stackOffset--,this.applySnapshot(this.stack[this.stackOffset]))}},{key:"redo",value:function(){this.stack.length-1>this.stackOffset&&(this.stackOffset++,this.applySnapshot(this.stack[this.stackOffset]))}},{key:"recordUndo",value:function(){this.stackOffset++,this.stack.length>this.stackOffset&&(this.stack=this.stack.slice(0,this.stackOffset)),this.stack.push(this.makeSnapshot()),this.stack.length>this.context.options.historyLimit&&(this.stack.shift(),this.stackOffset-=1)}}])&&Ct(e.prototype,n),o&&Ct(e,o),t}();function St(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Tt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var n,o,i;return n=t,o=[{key:"jQueryCSS",value:function(t,n){var o={};return e().each(n,(function(e,n){o[n]=t.css(n)})),o}},{key:"fromNode",value:function(t){var e=this.jQueryCSS(t,["font-family","font-size","text-align","list-style-type","line-height"])||{},n=t[0].style.fontSize||e["font-size"];return e["font-size"]=parseInt(n,10),e["font-size-unit"]=n.match(/[a-z%]+$/),e}},{key:"stylePara",value:function(t,n){e().each(t.nodes(ht.isPara,{includeAncestor:!0}),(function(t,o){e()(o).css(n)}))}},{key:"styleNodes",value:function(t,n){t=t.splitText();var o=n&&n.nodeName||"SPAN",i=!(!n||!n.expandClosestSibling),r=!(!n||!n.onlyPartialContains);if(t.isCollapsed())return[t.insertNode(ht.create(o))];var a=ht.makePredByNodeName(o),s=t.nodes(ht.isText,{fullyContains:!0}).map((function(t){return ht.singleChildAncestor(t,a)||ht.wrap(t,o)}));if(i){if(r){var l=t.nodes();a=m.and(a,(function(t){return k.contains(l,t)}))}return s.map((function(t){var n=ht.withClosestSiblings(t,a),o=k.head(n),i=k.tail(n);return e().each(i,(function(t,e){ht.appendChildNodes(o,e.childNodes),ht.remove(e)})),k.head(n)}))}return s}},{key:"current",value:function(t){var n=e()(ht.isElement(t.sc)?t.sc:t.sc.parentNode),o=this.fromNode(n);try{o=e().extend(o,{"font-bold":document.queryCommandState("bold")?"bold":"normal","font-italic":document.queryCommandState("italic")?"italic":"normal","font-underline":document.queryCommandState("underline")?"underline":"normal","font-subscript":document.queryCommandState("subscript")?"subscript":"normal","font-superscript":document.queryCommandState("superscript")?"superscript":"normal","font-strikethrough":document.queryCommandState("strikethrough")?"strikethrough":"normal","font-family":document.queryCommandValue("fontname")||o["font-family"]})}catch(t){}if(t.isOnList()){var i=["circle","disc","disc-leading-zero","square"].indexOf(o["list-style-type"])>-1;o["list-style"]=i?"unordered":"ordered"}else o["list-style"]="none";var r=ht.ancestor(t.sc,ht.isPara);if(r&&r.style["line-height"])o["line-height"]=r.style.lineHeight;else{var a=parseInt(o["line-height"],10)/parseInt(o["font-size"],10);o["line-height"]=a.toFixed(1)}return o.anchor=t.isOnAnchor()&&ht.ancestor(t.sc,ht.isAnchor),o.ancestors=ht.listAncestor(t.sc,ht.isEditable),o.range=t,o}}],o&&St(n.prototype,o),i&&St(n,i),t}();function Et(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var It=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var n,o,i;return n=t,o=[{key:"insertOrderedList",value:function(t){this.toggleList("OL",t)}},{key:"insertUnorderedList",value:function(t){this.toggleList("UL",t)}},{key:"indent",value:function(t){var n=this,o=yt.create(t).wrapBodyInlineWithPara(),i=o.nodes(ht.isPara,{includeAncestor:!0}),r=k.clusterBy(i,m.peq2("parentNode"));e().each(r,(function(t,o){var i=k.head(o);if(ht.isLi(i)){var r=n.findList(i.previousSibling);r?o.map((function(t){return r.appendChild(t)})):(n.wrapList(o,i.parentNode.nodeName),o.map((function(t){return t.parentNode})).map((function(t){return n.appendToPrevious(t)})))}else e().each(o,(function(t,n){e()(n).css("marginLeft",(function(t,e){return(parseInt(e,10)||0)+25}))}))})),o.select()}},{key:"outdent",value:function(t){var n=this,o=yt.create(t).wrapBodyInlineWithPara(),i=o.nodes(ht.isPara,{includeAncestor:!0}),r=k.clusterBy(i,m.peq2("parentNode"));e().each(r,(function(t,o){var i=k.head(o);ht.isLi(i)?n.releaseList([o]):e().each(o,(function(t,n){e()(n).css("marginLeft",(function(t,e){return(e=parseInt(e,10)||0)>25?e-25:""}))}))})),o.select()}},{key:"toggleList",value:function(t,n){var o=this,i=yt.create(n).wrapBodyInlineWithPara(),r=i.nodes(ht.isPara,{includeAncestor:!0}),a=i.paraBookmark(r),s=k.clusterBy(r,m.peq2("parentNode"));if(k.find(r,ht.isPurePara)){var l=[];e().each(s,(function(e,n){l=l.concat(o.wrapList(n,t))})),r=l}else{var c=i.nodes(ht.isList,{includeAncestor:!0}).filter((function(n){return!e().nodeName(n,t)}));c.length?e().each(c,(function(e,n){ht.replace(n,t)})):r=this.releaseList(s,!0)}yt.createFromParaBookmark(a,r).select()}},{key:"wrapList",value:function(t,e){var n=k.head(t),o=k.last(t),i=ht.isList(n.previousSibling)&&n.previousSibling,r=ht.isList(o.nextSibling)&&o.nextSibling,a=i||ht.insertAfter(ht.create(e||"UL"),o);return t=t.map((function(t){return ht.isPurePara(t)?ht.replace(t,"LI"):t})),ht.appendChildNodes(a,t),r&&(ht.appendChildNodes(a,k.from(r.childNodes)),ht.remove(r)),t}},{key:"releaseList",value:function(t,n){var o=this,i=[];return e().each(t,(function(t,r){var a=k.head(r),s=k.last(r),l=n?ht.lastAncestor(a,ht.isList):a.parentNode,c=l.parentNode;if("LI"===l.parentNode.nodeName)r.map((function(t){var e=o.findNextSiblings(t);c.nextSibling?c.parentNode.insertBefore(t,c.nextSibling):c.parentNode.appendChild(t),e.length&&(o.wrapList(e,l.nodeName),t.appendChild(e[0].parentNode))})),0===l.children.length&&c.removeChild(l),0===c.childNodes.length&&c.parentNode.removeChild(c);else{var u=l.childNodes.length>1?ht.splitTree(l,{node:s.parentNode,offset:ht.position(s)+1},{isSkipPaddingBlankHTML:!0}):null,d=ht.splitTree(l,{node:a.parentNode,offset:ht.position(a)},{isSkipPaddingBlankHTML:!0});r=n?ht.listDescendant(d,ht.isLi):k.from(d.childNodes).filter(ht.isLi),!n&&ht.isList(l.parentNode)||(r=r.map((function(t){return ht.replace(t,"P")}))),e().each(k.from(r).reverse(),(function(t,e){ht.insertAfter(e,l)}));var h=k.compact([l,d,u]);e().each(h,(function(t,n){var o=[n].concat(ht.listDescendant(n,ht.isList));e().each(o.reverse(),(function(t,e){ht.nodeLength(e)||ht.remove(e,!0)}))}))}i=i.concat(r)})),i}},{key:"appendToPrevious",value:function(t){return t.previousSibling?ht.appendChildNodes(t.previousSibling,[t]):this.wrapList([t],"LI")}},{key:"findList",value:function(t){return t?k.find(t.children,(function(t){return["OL","UL"].indexOf(t.nodeName)>-1})):null}},{key:"findNextSiblings",value:function(t){for(var e=[];t.nextSibling;)e.push(t.nextSibling),t=t.nextSibling;return e}}],o&&Et(n.prototype,o),i&&Et(n,i),t}();function $t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Nt=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.bullet=new It,this.options=e.options}var n,o,i;return n=t,o=[{key:"insertTab",value:function(t,e){var n=ht.createText(new Array(e+1).join(ht.NBSP_CHAR));(t=t.deleteContents()).insertNode(n,!0),(t=yt.create(n,e)).select()}},{key:"insertParagraph",value:function(t,n){n=(n=(n=n||yt.create(t)).deleteContents()).wrapBodyInlineWithPara();var o,i=ht.ancestor(n.sc,ht.isPara);if(i){if(ht.isLi(i)&&(ht.isEmpty(i)||ht.deepestChildIsEmpty(i)))return void this.bullet.toggleList(i.parentNode.nodeName);var r=null;if(1===this.options.blockquoteBreakingLevel?r=ht.ancestor(i,ht.isBlockquote):2===this.options.blockquoteBreakingLevel&&(r=ht.lastAncestor(i,ht.isBlockquote)),r){o=e()(ht.emptyPara)[0],ht.isRightEdgePoint(n.getStartPoint())&&ht.isBR(n.sc.nextSibling)&&e()(n.sc.nextSibling).remove();var a=ht.splitTree(r,n.getStartPoint(),{isDiscardEmptySplits:!0});a?a.parentNode.insertBefore(o,a):ht.insertAfter(o,r)}else{o=ht.splitTree(i,n.getStartPoint());var s=ht.listDescendant(i,ht.isEmptyAnchor);s=s.concat(ht.listDescendant(o,ht.isEmptyAnchor)),e().each(s,(function(t,e){ht.remove(e)})),(ht.isHeading(o)||ht.isPre(o)||ht.isCustomStyleTag(o))&&ht.isEmpty(o)&&(o=ht.replace(o,"p"))}}else{var l=n.sc.childNodes[n.so];o=e()(ht.emptyPara)[0],l?n.sc.insertBefore(o,l):n.sc.appendChild(o)}yt.create(o,0).normalize().select().scrollIntoView(t)}}],o&&$t(n.prototype,o),i&&$t(n,i),t}();function Pt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Rt=function t(e,n,o,i){var r={colPos:0,rowPos:0},a=[],s=[];function l(t,e,n,o,i,r,s){var l={baseRow:n,baseCell:o,isRowSpan:i,isColSpan:r,isVirtual:s};a[t]||(a[t]=[]),a[t][e]=l}function c(t,e,n,o){return{baseCell:t.baseCell,action:e,virtualTable:{rowIndex:n,cellIndex:o}}}function u(t,e){if(!a[t])return e;if(!a[t][e])return e;for(var n=e;a[t][n];)if(n++,!a[t][n])return n}function d(t,e){var n=u(t.rowIndex,e.cellIndex),o=e.colSpan>1,i=e.rowSpan>1,a=t.rowIndex===r.rowPos&&e.cellIndex===r.colPos;l(t.rowIndex,n,t,e,i,o,!1);var s=e.attributes.rowSpan?parseInt(e.attributes.rowSpan.value,10):0;if(s>1)for(var c=1;c<s;c++){var d=t.rowIndex+c;h(d,n,e,a),l(d,n,t,e,!0,o,!0)}var f=e.attributes.colSpan?parseInt(e.attributes.colSpan.value,10):0;if(f>1)for(var p=1;p<f;p++){var m=u(t.rowIndex,n+p);h(t.rowIndex,m,e,a),l(t.rowIndex,m,t,e,i,!0,!0)}}function h(t,e,n,o){t===r.rowPos&&r.colPos>=n.cellIndex&&n.cellIndex<=e&&!o&&r.colPos++}function f(e){switch(n){case t.where.Column:if(e.isColSpan)return t.resultAction.SubtractSpanCount;break;case t.where.Row:if(!e.isVirtual&&e.isRowSpan)return t.resultAction.AddCell;if(e.isRowSpan)return t.resultAction.SubtractSpanCount}return t.resultAction.RemoveCell}function p(e){switch(n){case t.where.Column:if(e.isColSpan)return t.resultAction.SumSpanCount;if(e.isRowSpan&&e.isVirtual)return t.resultAction.Ignore;break;case t.where.Row:if(e.isRowSpan)return t.resultAction.SumSpanCount;if(e.isColSpan&&e.isVirtual)return t.resultAction.Ignore}return t.resultAction.AddCell}this.getActionList=function(){for(var e=n===t.where.Row?r.rowPos:-1,i=n===t.where.Column?r.colPos:-1,l=0,u=!0;u;){var d=e>=0?e:l,h=i>=0?i:l,m=a[d];if(!m)return u=!1,s;var v=m[h];if(!v)return u=!1,s;var g=t.resultAction.Ignore;switch(o){case t.requestAction.Add:g=p(v);break;case t.requestAction.Delete:g=f(v)}s.push(c(v,g,d,h)),l++}return s},e&&e.tagName&&("td"===e.tagName.toLowerCase()||"th"===e.tagName.toLowerCase())&&(r.colPos=e.cellIndex,e.parentElement&&e.parentElement.tagName&&"tr"===e.parentElement.tagName.toLowerCase()&&(r.rowPos=e.parentElement.rowIndex)),function(){for(var t=i.rows,e=0;e<t.length;e++)for(var n=t[e].cells,o=0;o<n.length;o++)d(t[e],n[o])}()};Rt.where={Row:0,Column:1},Rt.requestAction={Add:0,Delete:1},Rt.resultAction={Ignore:0,SubtractSpanCount:1,RemoveCell:2,AddCell:3,SumSpanCount:4};var Lt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var n,o,i;return n=t,o=[{key:"tab",value:function(t,e){var n=ht.ancestor(t.commonAncestor(),ht.isCell),o=ht.ancestor(n,ht.isTable),i=ht.listDescendant(o,ht.isCell),r=k[e?"prev":"next"](i,n);r&&yt.create(r,0).select()}},{key:"addRow",value:function(t,n){for(var o=ht.ancestor(t.commonAncestor(),ht.isCell),i=e()(o).closest("tr"),r=this.recoverAttributes(i),a=e()("<tr"+r+"></tr>"),s=new Rt(o,Rt.where.Row,Rt.requestAction.Add,e()(i).closest("table")[0]).getActionList(),l=0;l<s.length;l++){var c=s[l],u=this.recoverAttributes(c.baseCell);switch(c.action){case Rt.resultAction.AddCell:a.append("<td"+u+">"+ht.blank+"</td>");break;case Rt.resultAction.SumSpanCount:if("top"===n&&(c.baseCell.parent?c.baseCell.closest("tr").rowIndex:0)<=i[0].rowIndex){var d=e()("<div></div>").append(e()("<td"+u+">"+ht.blank+"</td>").removeAttr("rowspan")).html();a.append(d);break}var h=parseInt(c.baseCell.rowSpan,10);h++,c.baseCell.setAttribute("rowSpan",h)}}if("top"===n)i.before(a);else{if(o.rowSpan>1){var f=i[0].rowIndex+(o.rowSpan-2);return void e()(e()(i).parent().find("tr")[f]).after(e()(a))}i.after(a)}}},{key:"addCol",value:function(t,n){var o=ht.ancestor(t.commonAncestor(),ht.isCell),i=e()(o).closest("tr");e()(i).siblings().push(i);for(var r=new Rt(o,Rt.where.Column,Rt.requestAction.Add,e()(i).closest("table")[0]).getActionList(),a=0;a<r.length;a++){var s=r[a],l=this.recoverAttributes(s.baseCell);switch(s.action){case Rt.resultAction.AddCell:"right"===n?e()(s.baseCell).after("<td"+l+">"+ht.blank+"</td>"):e()(s.baseCell).before("<td"+l+">"+ht.blank+"</td>");break;case Rt.resultAction.SumSpanCount:if("right"===n){var c=parseInt(s.baseCell.colSpan,10);c++,s.baseCell.setAttribute("colSpan",c)}else e()(s.baseCell).before("<td"+l+">"+ht.blank+"</td>")}}}},{key:"recoverAttributes",value:function(t){var e="";if(!t)return e;for(var n=t.attributes||[],o=0;o<n.length;o++)"id"!==n[o].name.toLowerCase()&&n[o].specified&&(e+=" "+n[o].name+"='"+n[o].value+"'");return e}},{key:"deleteRow",value:function(t){for(var n=ht.ancestor(t.commonAncestor(),ht.isCell),o=e()(n).closest("tr"),i=o.children("td, th").index(e()(n)),r=o[0].rowIndex,a=new Rt(n,Rt.where.Row,Rt.requestAction.Delete,e()(o).closest("table")[0]).getActionList(),s=0;s<a.length;s++)if(a[s]){var l=a[s].baseCell,c=a[s].virtualTable,u=l.rowSpan&&l.rowSpan>1,d=u?parseInt(l.rowSpan,10):0;switch(a[s].action){case Rt.resultAction.Ignore:continue;case Rt.resultAction.AddCell:var h=o.next("tr")[0];if(!h)continue;var f=o[0].cells[i];u&&(d>2?(d--,h.insertBefore(f,h.cells[i]),h.cells[i].setAttribute("rowSpan",d),h.cells[i].innerHTML=""):2===d&&(h.insertBefore(f,h.cells[i]),h.cells[i].removeAttribute("rowSpan"),h.cells[i].innerHTML=""));continue;case Rt.resultAction.SubtractSpanCount:u&&(d>2?(d--,l.setAttribute("rowSpan",d),c.rowIndex!==r&&l.cellIndex===i&&(l.innerHTML="")):2===d&&(l.removeAttribute("rowSpan"),c.rowIndex!==r&&l.cellIndex===i&&(l.innerHTML="")));continue;case Rt.resultAction.RemoveCell:continue}}o.remove()}},{key:"deleteCol",value:function(t){for(var n=ht.ancestor(t.commonAncestor(),ht.isCell),o=e()(n).closest("tr"),i=o.children("td, th").index(e()(n)),r=new Rt(n,Rt.where.Column,Rt.requestAction.Delete,e()(o).closest("table")[0]).getActionList(),a=0;a<r.length;a++)if(r[a])switch(r[a].action){case Rt.resultAction.Ignore:continue;case Rt.resultAction.SubtractSpanCount:var s=r[a].baseCell;if(s.colSpan&&s.colSpan>1){var l=s.colSpan?parseInt(s.colSpan,10):0;l>2?(l--,s.setAttribute("colSpan",l),s.cellIndex===i&&(s.innerHTML="")):2===l&&(s.removeAttribute("colSpan"),s.cellIndex===i&&(s.innerHTML=""))}continue;case Rt.resultAction.RemoveCell:ht.remove(r[a].baseCell,!0);continue}}},{key:"createTable",value:function(t,n,o){for(var i,r=[],a=0;a<t;a++)r.push("<td>"+ht.blank+"</td>");i=r.join("");for(var s,l=[],c=0;c<n;c++)l.push("<tr>"+i+"</tr>");s=l.join("");var u=e()("<table>"+s+"</table>");return o&&o.tableClassName&&u.addClass(o.tableClassName),u[0]}},{key:"deleteTable",value:function(t){var n=ht.ancestor(t.commonAncestor(),ht.isCell);e()(n).closest("table").remove()}}],o&&Pt(n.prototype,o),i&&Pt(n,i),t}();function At(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Ft=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$note=n.layoutInfo.note,this.$editor=n.layoutInfo.editor,this.$editable=n.layoutInfo.editable,this.options=n.options,this.lang=this.options.langInfo,this.editable=this.$editable[0],this.lastRange=null,this.snapshot=null,this.style=new Tt,this.table=new Lt,this.typing=new Nt(n),this.bullet=new It,this.history=new xt(n),this.context.memo("help.escape",this.lang.help.escape),this.context.memo("help.undo",this.lang.help.undo),this.context.memo("help.redo",this.lang.help.redo),this.context.memo("help.tab",this.lang.help.tab),this.context.memo("help.untab",this.lang.help.untab),this.context.memo("help.insertParagraph",this.lang.help.insertParagraph),this.context.memo("help.insertOrderedList",this.lang.help.insertOrderedList),this.context.memo("help.insertUnorderedList",this.lang.help.insertUnorderedList),this.context.memo("help.indent",this.lang.help.indent),this.context.memo("help.outdent",this.lang.help.outdent),this.context.memo("help.formatPara",this.lang.help.formatPara),this.context.memo("help.insertHorizontalRule",this.lang.help.insertHorizontalRule),this.context.memo("help.fontName",this.lang.help.fontName);for(var i=["bold","italic","underline","strikethrough","superscript","subscript","justifyLeft","justifyCenter","justifyRight","justifyFull","formatBlock","removeFormat","backColor"],r=0,a=i.length;r<a;r++)this[i[r]]=function(t){return function(e){o.beforeCommand(),document.execCommand(t,!1,e),o.afterCommand(!0)}}(i[r]),this.context.memo("help."+i[r],this.lang.help[i[r]]);this.fontName=this.wrapCommand((function(t){return o.fontStyling("font-family",f.validFontName(t))})),this.fontSize=this.wrapCommand((function(t){var e=o.currentStyle()["font-size-unit"];return o.fontStyling("font-size",t+e)})),this.fontSizeUnit=this.wrapCommand((function(t){var e=o.currentStyle()["font-size"];return o.fontStyling("font-size",e+t)}));for(var s=1;s<=6;s++)this["formatH"+s]=function(t){return function(){o.formatBlock("H"+t)}}(s),this.context.memo("help.formatH"+s,this.lang.help["formatH"+s]);this.insertParagraph=this.wrapCommand((function(){o.typing.insertParagraph(o.editable)})),this.insertOrderedList=this.wrapCommand((function(){o.bullet.insertOrderedList(o.editable)})),this.insertUnorderedList=this.wrapCommand((function(){o.bullet.insertUnorderedList(o.editable)})),this.indent=this.wrapCommand((function(){o.bullet.indent(o.editable)})),this.outdent=this.wrapCommand((function(){o.bullet.outdent(o.editable)})),this.insertNode=this.wrapCommand((function(t){o.isLimited(e()(t).text().length)||(o.getLastRange().insertNode(t),o.setLastRange(yt.createFromNodeAfter(t).select()))})),this.insertText=this.wrapCommand((function(t){if(!o.isLimited(t.length)){var e=o.getLastRange().insertNode(ht.createText(t));o.setLastRange(yt.create(e,ht.nodeLength(e)).select())}})),this.pasteHTML=this.wrapCommand((function(t){if(!o.isLimited(t.length)){t=o.context.invoke("codeview.purify",t);var e=o.getLastRange().pasteHTML(t);o.setLastRange(yt.createFromNodeAfter(k.last(e)).select())}})),this.formatBlock=this.wrapCommand((function(t,e){var n=o.options.callbacks.onApplyCustomStyle;n?n.call(o,e,o.context,o.onFormatBlock):o.onFormatBlock(t,e)})),this.insertHorizontalRule=this.wrapCommand((function(){var t=o.getLastRange().insertNode(ht.create("HR"));t.nextSibling&&o.setLastRange(yt.create(t.nextSibling,0).normalize().select())})),this.lineHeight=this.wrapCommand((function(t){o.style.stylePara(o.getLastRange(),{lineHeight:t})})),this.createLink=this.wrapCommand((function(t){var n=t.url,i=t.text,r=t.isNewWindow,a=t.checkProtocol,s=t.range||o.getLastRange(),l=i.length-s.toString().length;if(!(l>0&&o.isLimited(l))){var c=s.toString()!==i;"string"==typeof n&&(n=n.trim()),o.options.onCreateLink?n=o.options.onCreateLink(n):a&&(n=/^([A-Za-z][A-Za-z0-9+-.]*\:|#|\/)/.test(n)?n:o.options.defaultProtocol+n);var u=[];if(c){var d=(s=s.deleteContents()).insertNode(e()("<A>"+i+"</A>")[0]);u.push(d)}else u=o.style.styleNodes(s,{nodeName:"A",expandClosestSibling:!0,onlyPartialContains:!0});e().each(u,(function(t,o){e()(o).attr("href",n),r?e()(o).attr("target","_blank"):e()(o).removeAttr("target")})),o.setLastRange(o.createRangeFromList(u).select())}})),this.color=this.wrapCommand((function(t){var e=t.foreColor,n=t.backColor;e&&document.execCommand("foreColor",!1,e),n&&document.execCommand("backColor",!1,n)})),this.foreColor=this.wrapCommand((function(t){document.execCommand("foreColor",!1,t)})),this.insertTable=this.wrapCommand((function(t){var e=t.split("x");o.getLastRange().deleteContents().insertNode(o.table.createTable(e[0],e[1],o.options))})),this.removeMedia=this.wrapCommand((function(){var t=e()(o.restoreTarget()).parent();t.closest("figure").length?t.closest("figure").remove():t=e()(o.restoreTarget()).detach(),o.context.triggerEvent("media.delete",t,o.$editable)})),this.floatMe=this.wrapCommand((function(t){var n=e()(o.restoreTarget());n.toggleClass("note-float-left","left"===t),n.toggleClass("note-float-right","right"===t),n.css("float","none"===t?"":t)})),this.resize=this.wrapCommand((function(t){var n=e()(o.restoreTarget());0===(t=parseFloat(t))?n.css("width",""):n.css({width:100*t+"%",height:""})}))}var n,o,i;return n=t,o=[{key:"initialize",value:function(){var t=this;this.$editable.on("keydown",(function(e){if(e.keyCode===wt.code.ENTER&&t.context.triggerEvent("enter",e),t.context.triggerEvent("keydown",e),t.snapshot=t.history.makeSnapshot(),t.hasKeyShortCut=!1,e.isDefaultPrevented()||(t.options.shortcuts?t.hasKeyShortCut=t.handleKeyMap(e):t.preventDefaultEditableShortCuts(e)),t.isLimited(1,e)){var n=t.getLastRange();if(n.eo-n.so==0)return!1}t.setLastRange(),t.options.recordEveryKeystroke&&!1===t.hasKeyShortCut&&t.history.recordUndo()})).on("keyup",(function(e){t.setLastRange(),t.context.triggerEvent("keyup",e)})).on("focus",(function(e){t.setLastRange(),t.context.triggerEvent("focus",e)})).on("blur",(function(e){t.context.triggerEvent("blur",e)})).on("mousedown",(function(e){t.context.triggerEvent("mousedown",e)})).on("mouseup",(function(e){t.setLastRange(),t.history.recordUndo(),t.context.triggerEvent("mouseup",e)})).on("scroll",(function(e){t.context.triggerEvent("scroll",e)})).on("paste",(function(e){t.setLastRange(),t.context.triggerEvent("paste",e)})).on("input",(function(){t.isLimited(0)&&t.snapshot&&t.history.applySnapshot(t.snapshot)})),this.$editable.attr("spellcheck",this.options.spellCheck),this.$editable.attr("autocorrect",this.options.spellCheck),this.options.disableGrammar&&this.$editable.attr("data-gramm",!1),this.$editable.html(ht.html(this.$note)||ht.emptyPara),this.$editable.on(f.inputEventName,m.debounce((function(){t.context.triggerEvent("change",t.$editable.html(),t.$editable)}),10)),this.$editable.on("focusin",(function(e){t.context.triggerEvent("focusin",e)})).on("focusout",(function(e){t.context.triggerEvent("focusout",e)})),this.options.airMode?this.options.overrideContextMenu&&this.$editor.on("contextmenu",(function(e){return t.context.triggerEvent("contextmenu",e),!1})):(this.options.width&&this.$editor.outerWidth(this.options.width),this.options.height&&this.$editable.outerHeight(this.options.height),this.options.maxHeight&&this.$editable.css("max-height",this.options.maxHeight),this.options.minHeight&&this.$editable.css("min-height",this.options.minHeight)),this.history.recordUndo(),this.setLastRange()}},{key:"destroy",value:function(){this.$editable.off()}},{key:"handleKeyMap",value:function(t){var e=this.options.keyMap[f.isMac?"mac":"pc"],n=[];t.metaKey&&n.push("CMD"),t.ctrlKey&&!t.altKey&&n.push("CTRL"),t.shiftKey&&n.push("SHIFT");var o=wt.nameFromCode[t.keyCode];o&&n.push(o);var i=e[n.join("+")];if("TAB"!==o||this.options.tabDisable)if(i){if(!1!==this.context.invoke(i))return t.preventDefault(),!0}else wt.isEdit(t.keyCode)&&this.afterCommand();else this.afterCommand();return!1}},{key:"preventDefaultEditableShortCuts",value:function(t){(t.ctrlKey||t.metaKey)&&k.contains([66,73,85],t.keyCode)&&t.preventDefault()}},{key:"isLimited",value:function(t,e){return t=t||0,(void 0===e||!(wt.isMove(e.keyCode)||wt.isNavigation(e.keyCode)||e.ctrlKey||e.metaKey||k.contains([wt.code.BACKSPACE,wt.code.DELETE],e.keyCode)))&&this.options.maxTextLength>0&&this.$editable.text().length+t>this.options.maxTextLength}},{key:"createRange",value:function(){return this.focus(),this.setLastRange(),this.getLastRange()}},{key:"createRangeFromList",value:function(t){var e=yt.createFromNodeBefore(k.head(t)).getStartPoint(),n=yt.createFromNodeAfter(k.last(t)).getEndPoint();return yt.create(e.node,e.offset,n.node,n.offset)}},{key:"setLastRange",value:function(t){t?this.lastRange=t:(this.lastRange=yt.create(this.editable),0===e()(this.lastRange.sc).closest(".note-editable").length&&(this.lastRange=yt.createFromBodyElement(this.editable)))}},{key:"getLastRange",value:function(){return this.lastRange||this.setLastRange(),this.lastRange}},{key:"saveRange",value:function(t){t&&this.getLastRange().collapse().select()}},{key:"restoreRange",value:function(){this.lastRange&&(this.lastRange.select(),this.focus())}},{key:"saveTarget",value:function(t){this.$editable.data("target",t)}},{key:"clearTarget",value:function(){this.$editable.removeData("target")}},{key:"restoreTarget",value:function(){return this.$editable.data("target")}},{key:"currentStyle",value:function(){var t=yt.create();return t&&(t=t.normalize()),t?this.style.current(t):this.style.fromNode(this.$editable)}},{key:"styleFromNode",value:function(t){return this.style.fromNode(t)}},{key:"undo",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.undo(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"commit",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.commit(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"redo",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.redo(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"beforeCommand",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),document.execCommand("styleWithCSS",!1,this.options.styleWithCSS),this.focus()}},{key:"afterCommand",value:function(t){this.normalizeContent(),this.history.recordUndo(),t||this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"tab",value:function(){var t=this.getLastRange();if(t.isCollapsed()&&t.isOnCell())this.table.tab(t);else{if(0===this.options.tabSize)return!1;this.isLimited(this.options.tabSize)||(this.beforeCommand(),this.typing.insertTab(t,this.options.tabSize),this.afterCommand())}}},{key:"untab",value:function(){var t=this.getLastRange();if(t.isCollapsed()&&t.isOnCell())this.table.tab(t,!0);else if(0===this.options.tabSize)return!1}},{key:"wrapCommand",value:function(t){return function(){this.beforeCommand(),t.apply(this,arguments),this.afterCommand()}}},{key:"insertImage",value:function(t,n){var o,i=this;return(o=t,e().Deferred((function(t){var n=e()("<img>");n.one("load",(function(){n.off("error abort"),t.resolve(n)})).one("error abort",(function(){n.off("load").detach(),t.reject(n)})).css({display:"none"}).appendTo(document.body).attr("src",o)})).promise()).then((function(t){i.beforeCommand(),"function"==typeof n?n(t):("string"==typeof n&&t.attr("data-filename",n),t.css("width",Math.min(i.$editable.width(),t.width()))),t.show(),i.getLastRange().insertNode(t[0]),i.setLastRange(yt.createFromNodeAfter(t[0]).select()),i.afterCommand()})).fail((function(t){i.context.triggerEvent("image.upload.error",t)}))}},{key:"insertImagesAsDataURL",value:function(t){var n=this;e().each(t,(function(t,o){var i=o.name;n.options.maximumImageFileSize&&n.options.maximumImageFileSize<o.size?n.context.triggerEvent("image.upload.error",n.lang.image.maximumFileSizeError):function(t){return e().Deferred((function(n){e().extend(new FileReader,{onload:function(t){var e=t.target.result;n.resolve(e)},onerror:function(t){n.reject(t)}}).readAsDataURL(t)})).promise()}(o).then((function(t){return n.insertImage(t,i)})).fail((function(){n.context.triggerEvent("image.upload.error")}))}))}},{key:"insertImagesOrCallback",value:function(t){this.options.callbacks.onImageUpload?this.context.triggerEvent("image.upload",t):this.insertImagesAsDataURL(t)}},{key:"getSelectedText",value:function(){var t=this.getLastRange();return t.isOnAnchor()&&(t=yt.createFromNode(ht.ancestor(t.sc,ht.isAnchor))),t.toString()}},{key:"onFormatBlock",value:function(t,n){if(document.execCommand("FormatBlock",!1,f.isMSIE?"<"+t+">":t),n&&n.length&&(n[0].tagName.toUpperCase()!==t.toUpperCase()&&(n=n.find(t)),n&&n.length)){var o=this.createRange(),i=e()([o.sc,o.ec]).closest(t);i.removeClass();var r=n[0].className||"";r&&i.addClass(r)}}},{key:"formatPara",value:function(){this.formatBlock("P")}},{key:"fontStyling",value:function(t,n){var o=this.getLastRange();if(""!==o){var i=this.style.styleNodes(o);if(this.$editor.find(".note-status-output").html(""),e()(i).css(t,n),o.isCollapsed()){var r=k.head(i);r&&!ht.nodeLength(r)&&(r.innerHTML=ht.ZERO_WIDTH_NBSP_CHAR,yt.createFromNode(r.firstChild).select(),this.setLastRange(),this.$editable.data("bogus",r))}else this.setLastRange(this.createRangeFromList(i).select())}else{var a=e().now();this.$editor.find(".note-status-output").html('<div id="note-status-output-'+a+'" class="alert alert-info">'+this.lang.output.noSelection+"</div>"),setTimeout((function(){e()("#note-status-output-"+a).remove()}),5e3)}}},{key:"unlink",value:function(){var t=this.getLastRange();if(t.isOnAnchor()){var e=ht.ancestor(t.sc,ht.isAnchor);(t=yt.createFromNode(e)).select(),this.setLastRange(),this.beforeCommand(),document.execCommand("unlink"),this.afterCommand()}}},{key:"getLinkInfo",value:function(){var t=this.getLastRange().expand(ht.isAnchor),n=e()(k.head(t.nodes(ht.isAnchor))),o={range:t,text:t.toString(),url:n.length?n.attr("href"):""};return n.length&&(o.isNewWindow="_blank"===n.attr("target")),o}},{key:"addRow",value:function(t){var e=this.getLastRange(this.$editable);e.isCollapsed()&&e.isOnCell()&&(this.beforeCommand(),this.table.addRow(e,t),this.afterCommand())}},{key:"addCol",value:function(t){var e=this.getLastRange(this.$editable);e.isCollapsed()&&e.isOnCell()&&(this.beforeCommand(),this.table.addCol(e,t),this.afterCommand())}},{key:"deleteRow",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteRow(t),this.afterCommand())}},{key:"deleteCol",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteCol(t),this.afterCommand())}},{key:"deleteTable",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteTable(t),this.afterCommand())}},{key:"resizeTo",value:function(t,e,n){var o;if(n){var i=t.y/t.x,r=e.data("ratio");o={width:r>i?t.x:t.y/r,height:r>i?t.x*r:t.y}}else o={width:t.x,height:t.y};e.css(o)}},{key:"hasFocus",value:function(){return this.$editable.is(":focus")}},{key:"focus",value:function(){this.hasFocus()||this.$editable.focus()}},{key:"isEmpty",value:function(){return ht.isEmpty(this.$editable[0])||ht.emptyPara===this.$editable.html()}},{key:"empty",value:function(){this.context.invoke("code",ht.emptyPara)}},{key:"normalizeContent",value:function(){this.$editable[0].normalize()}}],o&&At(n.prototype,o),i&&At(n,i),t}();function Dt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Ht=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editable=e.layoutInfo.editable}var e,n,o;return e=t,(n=[{key:"initialize",value:function(){this.$editable.on("paste",this.pasteByEvent.bind(this))}},{key:"pasteByEvent",value:function(t){var e=this,n=t.originalEvent.clipboardData;if(n&&n.items&&n.items.length){var o=n.items.length>1?n.items[1]:k.head(n.items);"file"===o.kind&&-1!==o.type.indexOf("image/")?(this.context.invoke("editor.insertImagesOrCallback",[o.getAsFile()]),t.preventDefault()):"string"===o.kind&&this.context.invoke("editor.isLimited",n.getData("Text").length)&&t.preventDefault()}else if(window.clipboardData){var i=window.clipboardData.getData("text");this.context.invoke("editor.isLimited",i.length)&&t.preventDefault()}setTimeout((function(){e.context.invoke("editor.afterCommand")}),10)}}])&&Dt(e.prototype,n),o&&Dt(e,o),t}();function zt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Bt=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$eventListener=e()(document),this.$editor=n.layoutInfo.editor,this.$editable=n.layoutInfo.editable,this.options=n.options,this.lang=this.options.langInfo,this.documentEventHandlers={},this.$dropzone=e()(['<div class="note-dropzone">','<div class="note-dropzone-message"></div>',"</div>"].join("")).prependTo(this.$editor)}var n,o,i;return n=t,o=[{key:"initialize",value:function(){this.options.disableDragAndDrop?(this.documentEventHandlers.onDrop=function(t){t.preventDefault()},this.$eventListener=this.$dropzone,this.$eventListener.on("drop",this.documentEventHandlers.onDrop)):this.attachDragAndDropEvent()}},{key:"attachDragAndDropEvent",value:function(){var t=this,n=e()(),o=this.$dropzone.find(".note-dropzone-message");this.documentEventHandlers.onDragenter=function(e){var i=t.context.invoke("codeview.isActivated"),r=t.$editor.width()>0&&t.$editor.height()>0;i||n.length||!r||(t.$editor.addClass("dragover"),t.$dropzone.width(t.$editor.width()),t.$dropzone.height(t.$editor.height()),o.text(t.lang.image.dragImageHere)),n=n.add(e.target)},this.documentEventHandlers.onDragleave=function(o){(n=n.not(o.target)).length&&"BODY"!==o.target.nodeName||(n=e()(),t.$editor.removeClass("dragover"))},this.documentEventHandlers.onDrop=function(){n=e()(),t.$editor.removeClass("dragover")},this.$eventListener.on("dragenter",this.documentEventHandlers.onDragenter).on("dragleave",this.documentEventHandlers.onDragleave).on("drop",this.documentEventHandlers.onDrop),this.$dropzone.on("dragenter",(function(){t.$dropzone.addClass("hover"),o.text(t.lang.image.dropImage)})).on("dragleave",(function(){t.$dropzone.removeClass("hover"),o.text(t.lang.image.dragImageHere)})),this.$dropzone.on("drop",(function(n){var o=n.originalEvent.dataTransfer;n.preventDefault(),o&&o.files&&o.files.length?(t.$editable.focus(),t.context.invoke("editor.insertImagesOrCallback",o.files)):e().each(o.types,(function(n,i){if(!(i.toLowerCase().indexOf("_moz_")>-1)){var r=o.getData(i);i.toLowerCase().indexOf("text")>-1?t.context.invoke("editor.pasteHTML",r):e()(r).each((function(e,n){t.context.invoke("editor.insertNode",n)}))}}))})).on("dragover",!1)}},{key:"destroy",value:function(){var t=this;Object.keys(this.documentEventHandlers).forEach((function(e){t.$eventListener.off(e.substr(2).toLowerCase(),t.documentEventHandlers[e])})),this.documentEventHandlers={}}}],o&&zt(n.prototype,o),i&&zt(n,i),t}();function Mt(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(!t)return;if("string"==typeof t)return Ot(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Ot(t,e)}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,i=function(){};return{s:i,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,r=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw r}}}}function Ot(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=new Array(e);n<e;n++)o[n]=t[n];return o}function Ut(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var jt=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editor=e.layoutInfo.editor,this.$editable=e.layoutInfo.editable,this.$codable=e.layoutInfo.codable,this.options=e.options,this.CodeMirrorConstructor=window.CodeMirror,this.options.codemirror.CodeMirrorConstructor&&(this.CodeMirrorConstructor=this.options.codemirror.CodeMirrorConstructor)}var e,n,o;return e=t,n=[{key:"sync",value:function(t){var e=this.isActivated(),n=this.CodeMirrorConstructor;e&&(t?n?this.$codable.data("cmEditor").getDoc().setValue(t):this.$codable.val(t):n&&this.$codable.data("cmEditor").save())}},{key:"initialize",value:function(){var t=this;this.$codable.on("keyup",(function(e){e.keyCode===wt.code.ESCAPE&&t.deactivate()}))}},{key:"isActivated",value:function(){return this.$editor.hasClass("codeview")}},{key:"toggle",value:function(){this.isActivated()?this.deactivate():this.activate(),this.context.triggerEvent("codeview.toggled")}},{key:"purify",value:function(t){if(this.options.codeviewFilter&&(t=t.replace(this.options.codeviewFilterRegex,""),this.options.codeviewIframeFilter)){var e=this.options.codeviewIframeWhitelistSrc.concat(this.options.codeviewIframeWhitelistSrcBase);t=t.replace(/(<iframe.*?>.*?(?:<\/iframe>)?)/gi,(function(t){if(/<.+src(?==?('|"|\s)?)[\s\S]+src(?=('|"|\s)?)[^>]*?>/i.test(t))return"";var n,o=Mt(e);try{for(o.s();!(n=o.n()).done;){var i=n.value;if(new RegExp('src="(https?:)?//'+i.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")+'/(.+)"').test(t))return t}}catch(t){o.e(t)}finally{o.f()}return""}))}return t}},{key:"activate",value:function(){var t=this,e=this.CodeMirrorConstructor;if(this.$codable.val(ht.html(this.$editable,this.options.prettifyHtml)),this.$codable.height(this.$editable.height()),this.context.invoke("toolbar.updateCodeview",!0),this.context.invoke("airPopover.updateCodeview",!0),this.$editor.addClass("codeview"),this.$codable.focus(),e){var n=e.fromTextArea(this.$codable[0],this.options.codemirror);if(this.options.codemirror.tern){var o=new e.TernServer(this.options.codemirror.tern);n.ternServer=o,n.on("cursorActivity",(function(t){o.updateArgHints(t)}))}n.on("blur",(function(e){t.context.triggerEvent("blur.codeview",n.getValue(),e)})),n.on("change",(function(){t.context.triggerEvent("change.codeview",n.getValue(),n)})),n.setSize(null,this.$editable.outerHeight()),this.$codable.data("cmEditor",n)}else this.$codable.on("blur",(function(e){t.context.triggerEvent("blur.codeview",t.$codable.val(),e)})),this.$codable.on("input",(function(){t.context.triggerEvent("change.codeview",t.$codable.val(),t.$codable)}))}},{key:"deactivate",value:function(){if(this.CodeMirrorConstructor){var t=this.$codable.data("cmEditor");this.$codable.val(t.getValue()),t.toTextArea()}var e=this.purify(ht.value(this.$codable,this.options.prettifyHtml)||ht.emptyPara),n=this.$editable.html()!==e;this.$editable.html(e),this.$editable.height(this.options.height?this.$codable.height():"auto"),this.$editor.removeClass("codeview"),n&&this.context.triggerEvent("change",this.$editable.html(),this.$editable),this.$editable.focus(),this.context.invoke("toolbar.updateCodeview",!1),this.context.invoke("airPopover.updateCodeview",!1)}},{key:"destroy",value:function(){this.isActivated()&&this.deactivate()}}],n&&Ut(e.prototype,n),o&&Ut(e,o),t}();function Wt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Kt=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$document=e()(document),this.$statusbar=n.layoutInfo.statusbar,this.$editable=n.layoutInfo.editable,this.$codable=n.layoutInfo.codable,this.options=n.options}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t=this;this.options.airMode||this.options.disableResizeEditor?this.destroy():this.$statusbar.on("mousedown",(function(e){e.preventDefault(),e.stopPropagation();var n=t.$editable.offset().top-t.$document.scrollTop(),o=t.$codable.offset().top-t.$document.scrollTop(),i=function(e){var i=e.clientY-(n+24),r=e.clientY-(o+24);i=t.options.minheight>0?Math.max(i,t.options.minheight):i,i=t.options.maxHeight>0?Math.min(i,t.options.maxHeight):i,r=t.options.minheight>0?Math.max(r,t.options.minheight):r,r=t.options.maxHeight>0?Math.min(r,t.options.maxHeight):r,t.$editable.height(i),t.$codable.height(r)};t.$document.on("mousemove",i).one("mouseup",(function(){t.$document.off("mousemove",i)}))}))}},{key:"destroy",value:function(){this.$statusbar.off(),this.$statusbar.addClass("locked")}}])&&Wt(n.prototype,o),i&&Wt(n,i),t}();function Vt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var qt=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$editor=n.layoutInfo.editor,this.$toolbar=n.layoutInfo.toolbar,this.$editable=n.layoutInfo.editable,this.$codable=n.layoutInfo.codable,this.$window=e()(window),this.$scrollbar=e()("html, body"),this.scrollbarClassName="note-fullscreen-body",this.onResize=function(){o.resizeTo({h:o.$window.height()-o.$toolbar.outerHeight()})}}var n,o,i;return n=t,(o=[{key:"resizeTo",value:function(t){this.$editable.css("height",t.h),this.$codable.css("height",t.h),this.$codable.data("cmeditor")&&this.$codable.data("cmeditor").setsize(null,t.h)}},{key:"toggle",value:function(){this.$editor.toggleClass("fullscreen");var t=this.isFullscreen();this.$scrollbar.toggleClass(this.scrollbarClassName,t),t?(this.$editable.data("orgHeight",this.$editable.css("height")),this.$editable.data("orgMaxHeight",this.$editable.css("maxHeight")),this.$editable.css("maxHeight",""),this.$window.on("resize",this.onResize).trigger("resize")):(this.$window.off("resize",this.onResize),this.resizeTo({h:this.$editable.data("orgHeight")}),this.$editable.css("maxHeight",this.$editable.css("orgMaxHeight"))),this.context.invoke("toolbar.updateFullscreen",t)}},{key:"isFullscreen",value:function(){return this.$editor.hasClass("fullscreen")}},{key:"destroy",value:function(){this.$scrollbar.removeClass(this.scrollbarClassName)}}])&&Vt(n.prototype,o),i&&Vt(n,i),t}();function _t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Gt=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$document=e()(document),this.$editingArea=n.layoutInfo.editingArea,this.options=n.options,this.lang=this.options.langInfo,this.events={"summernote.mousedown":function(t,e){o.update(e.target,e)&&e.preventDefault()},"summernote.keyup summernote.scroll summernote.change summernote.dialog.shown":function(){o.update()},"summernote.disable summernote.blur":function(){o.hide()},"summernote.codeview.toggled":function(){o.update()}}}var n,o,i;return n=t,o=[{key:"initialize",value:function(){var t=this;this.$handle=e()(['<div class="note-handle">','<div class="note-control-selection">','<div class="note-control-selection-bg"></div>','<div class="note-control-holder note-control-nw"></div>','<div class="note-control-holder note-control-ne"></div>','<div class="note-control-holder note-control-sw"></div>','<div class="',this.options.disableResizeImage?"note-control-holder":"note-control-sizing",' note-control-se"></div>',this.options.disableResizeImage?"":'<div class="note-control-selection-info"></div>',"</div>","</div>"].join("")).prependTo(this.$editingArea),this.$handle.on("mousedown",(function(e){if(ht.isControlSizing(e.target)){e.preventDefault(),e.stopPropagation();var n=t.$handle.find(".note-control-selection").data("target"),o=n.offset(),i=t.$document.scrollTop(),r=function(e){t.context.invoke("editor.resizeTo",{x:e.clientX-o.left,y:e.clientY-(o.top-i)},n,!e.shiftKey),t.update(n[0],e)};t.$document.on("mousemove",r).one("mouseup",(function(e){e.preventDefault(),t.$document.off("mousemove",r),t.context.invoke("editor.afterCommand")})),n.data("ratio")||n.data("ratio",n.height()/n.width())}})),this.$handle.on("wheel",(function(e){e.preventDefault(),t.update()}))}},{key:"destroy",value:function(){this.$handle.remove()}},{key:"update",value:function(t,n){if(this.context.isDisabled())return!1;var o=ht.isImg(t),i=this.$handle.find(".note-control-selection");if(this.context.invoke("imagePopover.update",t,n),o){var r=e()(t),a=r.position(),s={left:a.left+parseInt(r.css("marginLeft"),10),top:a.top+parseInt(r.css("marginTop"),10)},l={w:r.outerWidth(!1),h:r.outerHeight(!1)};i.css({display:"block",left:s.left,top:s.top,width:l.w,height:l.h}).data("target",r);var c=new Image;c.src=r.attr("src");var u=l.w+"x"+l.h+" ("+this.lang.image.original+": "+c.width+"x"+c.height+")";i.find(".note-control-selection-info").text(u),this.context.invoke("editor.saveTarget",t)}else this.hide();return o}},{key:"hide",value:function(){this.context.invoke("editor.clearTarget"),this.$handle.children().hide()}}],o&&_t(n.prototype,o),i&&_t(n,i),t}();function Yt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Zt=/^([A-Za-z][A-Za-z0-9+-.]*\:[\/]{2}|tel:|mailto:[A-Z0-9._%+-]+@|xmpp:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i,Qt=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.options=e.options,this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||n.handleKeyup(e)},"summernote.keydown":function(t,e){n.handleKeydown(e)}}}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){this.lastWordRange=null}},{key:"destroy",value:function(){this.lastWordRange=null}},{key:"replace",value:function(){if(this.lastWordRange){var t=this.lastWordRange.toString(),n=t.match(Zt);if(n&&(n[1]||n[2])){var o=n[1]?t:"http://"+t,i=this.options.showDomainOnlyForAutolink?t.replace(/^(?:https?:\/\/)?(?:tel?:?)?(?:mailto?:?)?(?:xmpp?:?)?(?:www\.)?/i,"").split("/")[0]:t,r=e()("<a></a>").html(i).attr("href",o)[0];this.context.options.linkTargetBlank&&e()(r).attr("target","_blank"),this.lastWordRange.insertNode(r),this.lastWordRange=null,this.context.invoke("editor.focus")}}}},{key:"handleKeydown",value:function(t){if(k.contains([wt.code.ENTER,wt.code.SPACE],t.keyCode)){var e=this.context.invoke("editor.createRange").getWordRange();this.lastWordRange=e}}},{key:"handleKeyup",value:function(t){k.contains([wt.code.ENTER,wt.code.SPACE],t.keyCode)&&this.replace()}}])&&Yt(n.prototype,o),i&&Yt(n,i),t}();function Xt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Jt=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$note=e.layoutInfo.note,this.events={"summernote.change":function(){n.$note.val(e.invoke("code"))}}}var e,n,o;return e=t,(n=[{key:"shouldInitialize",value:function(){return ht.isTextarea(this.$note[0])}}])&&Xt(e.prototype,n),o&&Xt(e,o),t}();function te(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ee=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.options=e.options.replace||{},this.keys=[wt.code.ENTER,wt.code.SPACE,wt.code.PERIOD,wt.code.COMMA,wt.code.SEMICOLON,wt.code.SLASH],this.previousKeydownCode=null,this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||n.handleKeyup(e)},"summernote.keydown":function(t,e){n.handleKeydown(e)}}}var e,n,o;return e=t,(n=[{key:"shouldInitialize",value:function(){return!!this.options.match}},{key:"initialize",value:function(){this.lastWord=null}},{key:"destroy",value:function(){this.lastWord=null}},{key:"replace",value:function(){if(this.lastWord){var t=this,e=this.lastWord.toString();this.options.match(e,(function(e){if(e){var n="";if("string"==typeof e?n=ht.createText(e):e instanceof jQuery?n=e[0]:e instanceof Node&&(n=e),!n)return;t.lastWord.insertNode(n),t.lastWord=null,t.context.invoke("editor.focus")}}))}}},{key:"handleKeydown",value:function(t){if(this.previousKeydownCode&&k.contains(this.keys,this.previousKeydownCode))this.previousKeydownCode=t.keyCode;else{if(k.contains(this.keys,t.keyCode)){var e=this.context.invoke("editor.createRange").getWordRange();this.lastWord=e}this.previousKeydownCode=t.keyCode}}},{key:"handleKeyup",value:function(t){k.contains(this.keys,t.keyCode)&&this.replace()}}])&&te(e.prototype,n),o&&te(e,o),t}();function ne(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var oe=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editingArea=e.layoutInfo.editingArea,this.options=e.options,!0===this.options.inheritPlaceholder&&(this.options.placeholder=this.context.$note.attr("placeholder")||this.options.placeholder),this.events={"summernote.init summernote.change":function(){n.update()},"summernote.codeview.toggled":function(){n.update()}}}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return!!this.options.placeholder}},{key:"initialize",value:function(){var t=this;this.$placeholder=e()('<div class="note-placeholder"></div>'),this.$placeholder.on("click",(function(){t.context.invoke("focus")})).html(this.options.placeholder).prependTo(this.$editingArea),this.update()}},{key:"destroy",value:function(){this.$placeholder.remove()}},{key:"update",value:function(){var t=!this.context.invoke("codeview.isActivated")&&this.context.invoke("editor.isEmpty");this.$placeholder.toggle(t)}}])&&ne(n.prototype,o),i&&ne(n,i),t}();function ie(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var re=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.ui=e().summernote.ui,this.context=n,this.$toolbar=n.layoutInfo.toolbar,this.options=n.options,this.lang=this.options.langInfo,this.invertedKeyMap=m.invertObject(this.options.keyMap[f.isMac?"mac":"pc"])}var n,o,i;return n=t,o=[{key:"representShortcut",value:function(t){var e=this.invertedKeyMap[t];return this.options.shortcuts&&e?(f.isMac&&(e=e.replace("CMD","⌘").replace("SHIFT","⇧"))," ("+(e=e.replace("BACKSLASH","\\").replace("SLASH","/").replace("LEFTBRACKET","[").replace("RIGHTBRACKET","]"))+")"):""}},{key:"button",value:function(t){return!this.options.tooltip&&t.tooltip&&delete t.tooltip,t.container=this.options.container,this.ui.button(t)}},{key:"initialize",value:function(){this.addToolbarButtons(),this.addImagePopoverButtons(),this.addLinkPopoverButtons(),this.addTablePopoverButtons(),this.fontInstalledMap={}}},{key:"destroy",value:function(){delete this.fontInstalledMap}},{key:"isFontInstalled",value:function(t){return Object.prototype.hasOwnProperty.call(this.fontInstalledMap,t)||(this.fontInstalledMap[t]=f.isFontInstalled(t)||k.contains(this.options.fontNamesIgnoreCheck,t)),this.fontInstalledMap[t]}},{key:"isFontDeservedToAdd",value:function(t){return""!==(t=t.toLowerCase())&&this.isFontInstalled(t)&&-1===f.genericFontFamilies.indexOf(t)}},{key:"colorPalette",value:function(t,n,o,i){var r=this;return this.ui.buttonGroup({className:"note-color "+t,children:[this.button({className:"note-current-color-button",contents:this.ui.icon(this.options.icons.font+" note-recent-color"),tooltip:n,click:function(t){var n=e()(t.currentTarget);o&&i?r.context.invoke("editor.color",{backColor:n.attr("data-backColor"),foreColor:n.attr("data-foreColor")}):o?r.context.invoke("editor.color",{backColor:n.attr("data-backColor")}):i&&r.context.invoke("editor.color",{foreColor:n.attr("data-foreColor")})},callback:function(t){var e=t.find(".note-recent-color");o&&(e.css("background-color",r.options.colorButton.backColor),t.attr("data-backColor",r.options.colorButton.backColor)),i?(e.css("color",r.options.colorButton.foreColor),t.attr("data-foreColor",r.options.colorButton.foreColor)):e.css("color","transparent")}}),this.button({className:"dropdown-toggle",contents:this.ui.dropdownButtonContents("",this.options),tooltip:this.lang.color.more,data:{toggle:"dropdown"}}),this.ui.dropdown({items:(o?['<div class="note-palette">','<div class="note-palette-title">'+this.lang.color.background+"</div>","<div>",'<button type="button" class="note-color-reset btn btn-light btn-default" data-event="backColor" data-value="transparent">',this.lang.color.transparent,"</button>","</div>",'<div class="note-holder" data-event="backColor">\x3c!-- back colors --\x3e</div>',"<div>",'<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="backColorPicker-'+this.options.id+'">',this.lang.color.cpSelect,"</button>",'<input type="color" id="backColorPicker-'+this.options.id+'" class="note-btn note-color-select-btn" value="'+this.options.colorButton.backColor+'" data-event="backColorPalette-'+this.options.id+'">',"</div>",'<div class="note-holder-custom" id="backColorPalette-'+this.options.id+'" data-event="backColor"></div>',"</div>"].join(""):"")+(i?['<div class="note-palette">','<div class="note-palette-title">'+this.lang.color.foreground+"</div>","<div>",'<button type="button" class="note-color-reset btn btn-light btn-default" data-event="removeFormat" data-value="foreColor">',this.lang.color.resetToDefault,"</button>","</div>",'<div class="note-holder" data-event="foreColor">\x3c!-- fore colors --\x3e</div>',"<div>",'<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="foreColorPicker-'+this.options.id+'">',this.lang.color.cpSelect,"</button>",'<input type="color" id="foreColorPicker-'+this.options.id+'" class="note-btn note-color-select-btn" value="'+this.options.colorButton.foreColor+'" data-event="foreColorPalette-'+this.options.id+'">',"</div>",'<div class="note-holder-custom" id="foreColorPalette-'+this.options.id+'" data-event="foreColor"></div>',"</div>"].join(""):""),callback:function(t){t.find(".note-holder").each((function(t,n){var o=e()(n);o.append(r.ui.palette({colors:r.options.colors,colorsName:r.options.colorsName,eventName:o.data("event"),container:r.options.container,tooltip:r.options.tooltip}).render())}));var n=[["#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF"]];t.find(".note-holder-custom").each((function(t,o){var i=e()(o);i.append(r.ui.palette({colors:n,colorsName:n,eventName:i.data("event"),container:r.options.container,tooltip:r.options.tooltip}).render())})),t.find("input[type=color]").each((function(n,o){e()(o).change((function(){var n=t.find("#"+e()(this).data("event")).find(".note-color-btn").first(),o=this.value.toUpperCase();n.css("background-color",o).attr("aria-label",o).attr("data-value",o).attr("data-original-title",o),n.click()}))}))},click:function(n){n.stopPropagation();var o=e()("."+t).find(".note-dropdown-menu"),i=e()(n.target),a=i.data("event"),s=i.attr("data-value");if("openPalette"===a){var l=o.find("#"+s),c=e()(o.find("#"+l.data("event")).find(".note-color-row")[0]),u=c.find(".note-color-btn").last().detach(),d=l.val();u.css("background-color",d).attr("aria-label",d).attr("data-value",d).attr("data-original-title",d),c.prepend(u),l.click()}else{if(k.contains(["backColor","foreColor"],a)){var h="backColor"===a?"background-color":"color",f=i.closest(".note-color").find(".note-recent-color"),p=i.closest(".note-color").find(".note-current-color-button");f.css(h,s),p.attr("data-"+a,s)}r.context.invoke("editor."+a,s)}}})]}).render()}},{key:"addToolbarButtons",value:function(){var t=this;this.context.memo("button.style",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.magic),t.options),tooltip:t.lang.style.style,data:{toggle:"dropdown"}}),t.ui.dropdown({className:"dropdown-style",items:t.options.styleTags,title:t.lang.style.style,template:function(e){"string"==typeof e&&(e={tag:e,title:Object.prototype.hasOwnProperty.call(t.lang.style,e)?t.lang.style[e]:e});var n=e.tag,o=e.title;return"<"+n+(e.style?' style="'+e.style+'" ':"")+(e.className?' class="'+e.className+'"':"")+">"+o+"</"+n+">"},click:t.context.createInvokeHandler("editor.formatBlock")})]).render()}));for(var n=function(e,n){var o=t.options.styleTags[e];t.context.memo("button.style."+o,(function(){return t.button({className:"note-btn-style-"+o,contents:'<div data-value="'+o+'">'+o.toUpperCase()+"</div>",tooltip:t.lang.style[o],click:t.context.createInvokeHandler("editor.formatBlock")}).render()}))},o=0,i=this.options.styleTags.length;o<i;o++)n(o);this.context.memo("button.bold",(function(){return t.button({className:"note-btn-bold",contents:t.ui.icon(t.options.icons.bold),tooltip:t.lang.font.bold+t.representShortcut("bold"),click:t.context.createInvokeHandlerAndUpdateState("editor.bold")}).render()})),this.context.memo("button.italic",(function(){return t.button({className:"note-btn-italic",contents:t.ui.icon(t.options.icons.italic),tooltip:t.lang.font.italic+t.representShortcut("italic"),click:t.context.createInvokeHandlerAndUpdateState("editor.italic")}).render()})),this.context.memo("button.underline",(function(){return t.button({className:"note-btn-underline",contents:t.ui.icon(t.options.icons.underline),tooltip:t.lang.font.underline+t.representShortcut("underline"),click:t.context.createInvokeHandlerAndUpdateState("editor.underline")}).render()})),this.context.memo("button.clear",(function(){return t.button({contents:t.ui.icon(t.options.icons.eraser),tooltip:t.lang.font.clear+t.representShortcut("removeFormat"),click:t.context.createInvokeHandler("editor.removeFormat")}).render()})),this.context.memo("button.strikethrough",(function(){return t.button({className:"note-btn-strikethrough",contents:t.ui.icon(t.options.icons.strikethrough),tooltip:t.lang.font.strikethrough+t.representShortcut("strikethrough"),click:t.context.createInvokeHandlerAndUpdateState("editor.strikethrough")}).render()})),this.context.memo("button.superscript",(function(){return t.button({className:"note-btn-superscript",contents:t.ui.icon(t.options.icons.superscript),tooltip:t.lang.font.superscript,click:t.context.createInvokeHandlerAndUpdateState("editor.superscript")}).render()})),this.context.memo("button.subscript",(function(){return t.button({className:"note-btn-subscript",contents:t.ui.icon(t.options.icons.subscript),tooltip:t.lang.font.subscript,click:t.context.createInvokeHandlerAndUpdateState("editor.subscript")}).render()})),this.context.memo("button.fontname",(function(){var n=t.context.invoke("editor.currentStyle");return t.options.addDefaultFonts&&e().each(n["font-family"].split(","),(function(e,n){n=n.trim().replace(/['"]+/g,""),t.isFontDeservedToAdd(n)&&-1===t.options.fontNames.indexOf(n)&&t.options.fontNames.push(n)})),t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontname"></span>',t.options),tooltip:t.lang.font.name,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontname",checkClassName:t.options.icons.menuCheck,items:t.options.fontNames.filter(t.isFontInstalled.bind(t)),title:t.lang.font.name,template:function(t){return'<span style="font-family: '+f.validFontName(t)+'">'+t+"</span>"},click:t.context.createInvokeHandlerAndUpdateState("editor.fontName")})]).render()})),this.context.memo("button.fontsize",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontsize"></span>',t.options),tooltip:t.lang.font.size,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontsize",checkClassName:t.options.icons.menuCheck,items:t.options.fontSizes,title:t.lang.font.size,click:t.context.createInvokeHandlerAndUpdateState("editor.fontSize")})]).render()})),this.context.memo("button.fontsizeunit",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontsizeunit"></span>',t.options),tooltip:t.lang.font.sizeunit,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontsizeunit",checkClassName:t.options.icons.menuCheck,items:t.options.fontSizeUnits,title:t.lang.font.sizeunit,click:t.context.createInvokeHandlerAndUpdateState("editor.fontSizeUnit")})]).render()})),this.context.memo("button.color",(function(){return t.colorPalette("note-color-all",t.lang.color.recent,!0,!0)})),this.context.memo("button.forecolor",(function(){return t.colorPalette("note-color-fore",t.lang.color.foreground,!1,!0)})),this.context.memo("button.backcolor",(function(){return t.colorPalette("note-color-back",t.lang.color.background,!0,!1)})),this.context.memo("button.ul",(function(){return t.button({contents:t.ui.icon(t.options.icons.unorderedlist),tooltip:t.lang.lists.unordered+t.representShortcut("insertUnorderedList"),click:t.context.createInvokeHandler("editor.insertUnorderedList")}).render()})),this.context.memo("button.ol",(function(){return t.button({contents:t.ui.icon(t.options.icons.orderedlist),tooltip:t.lang.lists.ordered+t.representShortcut("insertOrderedList"),click:t.context.createInvokeHandler("editor.insertOrderedList")}).render()}));var r=this.button({contents:this.ui.icon(this.options.icons.alignLeft),tooltip:this.lang.paragraph.left+this.representShortcut("justifyLeft"),click:this.context.createInvokeHandler("editor.justifyLeft")}),a=this.button({contents:this.ui.icon(this.options.icons.alignCenter),tooltip:this.lang.paragraph.center+this.representShortcut("justifyCenter"),click:this.context.createInvokeHandler("editor.justifyCenter")}),s=this.button({contents:this.ui.icon(this.options.icons.alignRight),tooltip:this.lang.paragraph.right+this.representShortcut("justifyRight"),click:this.context.createInvokeHandler("editor.justifyRight")}),l=this.button({contents:this.ui.icon(this.options.icons.alignJustify),tooltip:this.lang.paragraph.justify+this.representShortcut("justifyFull"),click:this.context.createInvokeHandler("editor.justifyFull")}),c=this.button({contents:this.ui.icon(this.options.icons.outdent),tooltip:this.lang.paragraph.outdent+this.representShortcut("outdent"),click:this.context.createInvokeHandler("editor.outdent")}),u=this.button({contents:this.ui.icon(this.options.icons.indent),tooltip:this.lang.paragraph.indent+this.representShortcut("indent"),click:this.context.createInvokeHandler("editor.indent")});this.context.memo("button.justifyLeft",m.invoke(r,"render")),this.context.memo("button.justifyCenter",m.invoke(a,"render")),this.context.memo("button.justifyRight",m.invoke(s,"render")),this.context.memo("button.justifyFull",m.invoke(l,"render")),this.context.memo("button.outdent",m.invoke(c,"render")),this.context.memo("button.indent",m.invoke(u,"render")),this.context.memo("button.paragraph",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.alignLeft),t.options),tooltip:t.lang.paragraph.paragraph,data:{toggle:"dropdown"}}),t.ui.dropdown([t.ui.buttonGroup({className:"note-align",children:[r,a,s,l]}),t.ui.buttonGroup({className:"note-list",children:[c,u]})])]).render()})),this.context.memo("button.height",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.textHeight),t.options),tooltip:t.lang.font.height,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({items:t.options.lineHeights,checkClassName:t.options.icons.menuCheck,className:"dropdown-line-height",title:t.lang.font.height,click:t.context.createInvokeHandler("editor.lineHeight")})]).render()})),this.context.memo("button.table",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.table),t.options),tooltip:t.lang.table.table,data:{toggle:"dropdown"}}),t.ui.dropdown({title:t.lang.table.table,className:"note-table",items:['<div class="note-dimension-picker">','<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>','<div class="note-dimension-picker-highlighted"></div>','<div class="note-dimension-picker-unhighlighted"></div>',"</div>",'<div class="note-dimension-display">1 x 1</div>'].join("")})],{callback:function(e){e.find(".note-dimension-picker-mousecatcher").css({width:t.options.insertTableMaxSize.col+"em",height:t.options.insertTableMaxSize.row+"em"}).mouseup(t.context.createInvokeHandler("editor.insertTable")).on("mousemove",t.tableMoveHandler.bind(t))}}).render()})),this.context.memo("button.link",(function(){return t.button({contents:t.ui.icon(t.options.icons.link),tooltip:t.lang.link.link+t.representShortcut("linkDialog.show"),click:t.context.createInvokeHandler("linkDialog.show")}).render()})),this.context.memo("button.picture",(function(){return t.button({contents:t.ui.icon(t.options.icons.picture),tooltip:t.lang.image.image,click:t.context.createInvokeHandler("imageDialog.show")}).render()})),this.context.memo("button.video",(function(){return t.button({contents:t.ui.icon(t.options.icons.video),tooltip:t.lang.video.video,click:t.context.createInvokeHandler("videoDialog.show")}).render()})),this.context.memo("button.hr",(function(){return t.button({contents:t.ui.icon(t.options.icons.minus),tooltip:t.lang.hr.insert+t.representShortcut("insertHorizontalRule"),click:t.context.createInvokeHandler("editor.insertHorizontalRule")}).render()})),this.context.memo("button.fullscreen",(function(){return t.button({className:"btn-fullscreen note-codeview-keep",contents:t.ui.icon(t.options.icons.arrowsAlt),tooltip:t.lang.options.fullscreen,click:t.context.createInvokeHandler("fullscreen.toggle")}).render()})),this.context.memo("button.codeview",(function(){return t.button({className:"btn-codeview note-codeview-keep",contents:t.ui.icon(t.options.icons.code),tooltip:t.lang.options.codeview,click:t.context.createInvokeHandler("codeview.toggle")}).render()})),this.context.memo("button.redo",(function(){return t.button({contents:t.ui.icon(t.options.icons.redo),tooltip:t.lang.history.redo+t.representShortcut("redo"),click:t.context.createInvokeHandler("editor.redo")}).render()})),this.context.memo("button.undo",(function(){return t.button({contents:t.ui.icon(t.options.icons.undo),tooltip:t.lang.history.undo+t.representShortcut("undo"),click:t.context.createInvokeHandler("editor.undo")}).render()})),this.context.memo("button.help",(function(){return t.button({contents:t.ui.icon(t.options.icons.question),tooltip:t.lang.options.help,click:t.context.createInvokeHandler("helpDialog.show")}).render()}))}},{key:"addImagePopoverButtons",value:function(){var t=this;this.context.memo("button.resizeFull",(function(){return t.button({contents:'<span class="note-fontsize-10">100%</span>',tooltip:t.lang.image.resizeFull,click:t.context.createInvokeHandler("editor.resize","1")}).render()})),this.context.memo("button.resizeHalf",(function(){return t.button({contents:'<span class="note-fontsize-10">50%</span>',tooltip:t.lang.image.resizeHalf,click:t.context.createInvokeHandler("editor.resize","0.5")}).render()})),this.context.memo("button.resizeQuarter",(function(){return t.button({contents:'<span class="note-fontsize-10">25%</span>',tooltip:t.lang.image.resizeQuarter,click:t.context.createInvokeHandler("editor.resize","0.25")}).render()})),this.context.memo("button.resizeNone",(function(){return t.button({contents:t.ui.icon(t.options.icons.rollback),tooltip:t.lang.image.resizeNone,click:t.context.createInvokeHandler("editor.resize","0")}).render()})),this.context.memo("button.floatLeft",(function(){return t.button({contents:t.ui.icon(t.options.icons.floatLeft),tooltip:t.lang.image.floatLeft,click:t.context.createInvokeHandler("editor.floatMe","left")}).render()})),this.context.memo("button.floatRight",(function(){return t.button({contents:t.ui.icon(t.options.icons.floatRight),tooltip:t.lang.image.floatRight,click:t.context.createInvokeHandler("editor.floatMe","right")}).render()})),this.context.memo("button.floatNone",(function(){return t.button({contents:t.ui.icon(t.options.icons.rollback),tooltip:t.lang.image.floatNone,click:t.context.createInvokeHandler("editor.floatMe","none")}).render()})),this.context.memo("button.removeMedia",(function(){return t.button({contents:t.ui.icon(t.options.icons.trash),tooltip:t.lang.image.remove,click:t.context.createInvokeHandler("editor.removeMedia")}).render()}))}},{key:"addLinkPopoverButtons",value:function(){var t=this;this.context.memo("button.linkDialogShow",(function(){return t.button({contents:t.ui.icon(t.options.icons.link),tooltip:t.lang.link.edit,click:t.context.createInvokeHandler("linkDialog.show")}).render()})),this.context.memo("button.unlink",(function(){return t.button({contents:t.ui.icon(t.options.icons.unlink),tooltip:t.lang.link.unlink,click:t.context.createInvokeHandler("editor.unlink")}).render()}))}},{key:"addTablePopoverButtons",value:function(){var t=this;this.context.memo("button.addRowUp",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowAbove),tooltip:t.lang.table.addRowAbove,click:t.context.createInvokeHandler("editor.addRow","top")}).render()})),this.context.memo("button.addRowDown",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowBelow),tooltip:t.lang.table.addRowBelow,click:t.context.createInvokeHandler("editor.addRow","bottom")}).render()})),this.context.memo("button.addColLeft",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colBefore),tooltip:t.lang.table.addColLeft,click:t.context.createInvokeHandler("editor.addCol","left")}).render()})),this.context.memo("button.addColRight",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colAfter),tooltip:t.lang.table.addColRight,click:t.context.createInvokeHandler("editor.addCol","right")}).render()})),this.context.memo("button.deleteRow",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowRemove),tooltip:t.lang.table.delRow,click:t.context.createInvokeHandler("editor.deleteRow")}).render()})),this.context.memo("button.deleteCol",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colRemove),tooltip:t.lang.table.delCol,click:t.context.createInvokeHandler("editor.deleteCol")}).render()})),this.context.memo("button.deleteTable",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.trash),tooltip:t.lang.table.delTable,click:t.context.createInvokeHandler("editor.deleteTable")}).render()}))}},{key:"build",value:function(t,e){for(var n=0,o=e.length;n<o;n++){for(var i=e[n],r=Array.isArray(i)?i[0]:i,a=Array.isArray(i)?1===i.length?[i[0]]:i[1]:[i],s=this.ui.buttonGroup({className:"note-"+r}).render(),l=0,c=a.length;l<c;l++){var u=this.context.memo("button."+a[l]);u&&s.append("function"==typeof u?u(this.context):u)}s.appendTo(t)}}},{key:"updateCurrentStyle",value:function(t){var n=t||this.$toolbar,o=this.context.invoke("editor.currentStyle");if(this.updateBtnStates(n,{".note-btn-bold":function(){return"bold"===o["font-bold"]},".note-btn-italic":function(){return"italic"===o["font-italic"]},".note-btn-underline":function(){return"underline"===o["font-underline"]},".note-btn-subscript":function(){return"subscript"===o["font-subscript"]},".note-btn-superscript":function(){return"superscript"===o["font-superscript"]},".note-btn-strikethrough":function(){return"strikethrough"===o["font-strikethrough"]}}),o["font-family"]){var i=o["font-family"].split(",").map((function(t){return t.replace(/[\'\"]/g,"").replace(/\s+$/,"").replace(/^\s+/,"")})),r=k.find(i,this.isFontInstalled.bind(this));n.find(".dropdown-fontname a").each((function(t,n){var o=e()(n),i=o.data("value")+""==r+"";o.toggleClass("checked",i)})),n.find(".note-current-fontname").text(r).css("font-family",r)}if(o["font-size"]){var a=o["font-size"];n.find(".dropdown-fontsize a").each((function(t,n){var o=e()(n),i=o.data("value")+""==a+"";o.toggleClass("checked",i)})),n.find(".note-current-fontsize").text(a);var s=o["font-size-unit"];n.find(".dropdown-fontsizeunit a").each((function(t,n){var o=e()(n),i=o.data("value")+""==s+"";o.toggleClass("checked",i)})),n.find(".note-current-fontsizeunit").text(s)}if(o["line-height"]){var l=o["line-height"];n.find(".dropdown-line-height a").each((function(t,n){var o=e()(n),i=e()(n).data("value")+""==l+"";o.toggleClass("checked",i)})),n.find(".note-current-line-height").text(l)}}},{key:"updateBtnStates",value:function(t,n){var o=this;e().each(n,(function(e,n){o.ui.toggleBtnActive(t.find(e),n())}))}},{key:"tableMoveHandler",value:function(t){var n,o=e()(t.target.parentNode),i=o.next(),r=o.find(".note-dimension-picker-mousecatcher"),a=o.find(".note-dimension-picker-highlighted"),s=o.find(".note-dimension-picker-unhighlighted");if(void 0===t.offsetX){var l=e()(t.target).offset();n={x:t.pageX-l.left,y:t.pageY-l.top}}else n={x:t.offsetX,y:t.offsetY};var c=Math.ceil(n.x/18)||1,u=Math.ceil(n.y/18)||1;a.css({width:c+"em",height:u+"em"}),r.data("value",c+"x"+u),c>3&&c<this.options.insertTableMaxSize.col&&s.css({width:c+1+"em"}),u>3&&u<this.options.insertTableMaxSize.row&&s.css({height:u+1+"em"}),i.html(c+" x "+u)}}],o&&ie(n.prototype,o),i&&ie(n,i),t}();function ae(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var se=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.$window=e()(window),this.$document=e()(document),this.ui=e().summernote.ui,this.$note=n.layoutInfo.note,this.$editor=n.layoutInfo.editor,this.$toolbar=n.layoutInfo.toolbar,this.$editable=n.layoutInfo.editable,this.$statusbar=n.layoutInfo.statusbar,this.options=n.options,this.isFollowing=!1,this.followScroll=this.followScroll.bind(this)}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return!this.options.airMode}},{key:"initialize",value:function(){var t=this;this.options.toolbar=this.options.toolbar||[],this.options.toolbar.length?this.context.invoke("buttons.build",this.$toolbar,this.options.toolbar):this.$toolbar.hide(),this.options.toolbarContainer&&this.$toolbar.appendTo(this.options.toolbarContainer),this.changeContainer(!1),this.$note.on("summernote.keyup summernote.mouseup summernote.change",(function(){t.context.invoke("buttons.updateCurrentStyle")})),this.context.invoke("buttons.updateCurrentStyle"),this.options.followingToolbar&&this.$window.on("scroll resize",this.followScroll)}},{key:"destroy",value:function(){this.$toolbar.children().remove(),this.options.followingToolbar&&this.$window.off("scroll resize",this.followScroll)}},{key:"followScroll",value:function(){if(this.$editor.hasClass("fullscreen"))return!1;var t=this.$editor.outerHeight(),n=this.$editor.width(),o=this.$toolbar.height(),i=this.$statusbar.height(),r=0;this.options.otherStaticBar&&(r=e()(this.options.otherStaticBar).outerHeight());var a=this.$document.scrollTop(),s=this.$editor.offset().top,l=s-r,c=s+t-r-o-i;!this.isFollowing&&a>l&&a<c-o?(this.isFollowing=!0,this.$editable.css({marginTop:this.$toolbar.outerHeight()}),this.$toolbar.css({position:"fixed",top:r,width:n,zIndex:1e3})):this.isFollowing&&(a<l||a>c)&&(this.isFollowing=!1,this.$toolbar.css({position:"relative",top:0,width:"100%",zIndex:"auto"}),this.$editable.css({marginTop:""}))}},{key:"changeContainer",value:function(t){t?this.$toolbar.prependTo(this.$editor):this.options.toolbarContainer&&this.$toolbar.appendTo(this.options.toolbarContainer),this.options.followingToolbar&&this.followScroll()}},{key:"updateFullscreen",value:function(t){this.ui.toggleBtnActive(this.$toolbar.find(".btn-fullscreen"),t),this.changeContainer(t)}},{key:"updateCodeview",value:function(t){this.ui.toggleBtnActive(this.$toolbar.find(".btn-codeview"),t),t?this.deactivate():this.activate()}},{key:"activate",value:function(t){var e=this.$toolbar.find("button");t||(e=e.not(".note-codeview-keep")),this.ui.toggleBtn(e,!0)}},{key:"deactivate",value:function(t){var e=this.$toolbar.find("button");t||(e=e.not(".note-codeview-keep")),this.ui.toggleBtn(e,!1)}}])&&ae(n.prototype,o),i&&ae(n,i),t}();function le(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ce=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo,n.memo("help.linkDialog.show",this.options.langInfo.help["linkDialog.show"])}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,n=['<div class="form-group note-form-group">','<label for="note-dialog-link-txt-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.link.textToDisplay,"</label>"),'<input id="note-dialog-link-txt-'.concat(this.options.id,'" class="note-link-text form-control note-form-control note-input" type="text"/>'),"</div>",'<div class="form-group note-form-group">','<label for="note-dialog-link-url-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.link.url,"</label>"),'<input id="note-dialog-link-url-'.concat(this.options.id,'" class="note-link-url form-control note-form-control note-input" type="text" value="http://"/>'),"</div>",this.options.disableLinkTarget?"":e()("<div></div>").append(this.ui.checkbox({className:"sn-checkbox-open-in-new-window",text:this.lang.link.openInNewWindow,checked:!0}).render()).html(),e()("<div></div>").append(this.ui.checkbox({className:"sn-checkbox-use-protocol",text:this.lang.link.useProtocol,checked:!0}).render()).html()].join(""),o='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-link-btn",'" value="').concat(this.lang.link.insert,'" disabled>');this.$dialog=this.ui.dialog({className:"link-dialog",title:this.lang.link.insert,fade:this.options.dialogsFade,body:n,footer:o}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"toggleLinkBtn",value:function(t,e,n){this.ui.toggleBtn(t,e.val()&&n.val())}},{key:"showLinkDialog",value:function(t){var n=this;return e().Deferred((function(e){var o=n.$dialog.find(".note-link-text"),i=n.$dialog.find(".note-link-url"),r=n.$dialog.find(".note-link-btn"),a=n.$dialog.find(".sn-checkbox-open-in-new-window input[type=checkbox]"),s=n.$dialog.find(".sn-checkbox-use-protocol input[type=checkbox]");n.ui.onDialogShown(n.$dialog,(function(){n.context.triggerEvent("dialog.shown"),!t.url&&m.isValidUrl(t.text)&&(t.url=t.text),o.on("input paste propertychange",(function(){t.text=o.val(),n.toggleLinkBtn(r,o,i)})).val(t.text),i.on("input paste propertychange",(function(){t.text||o.val(i.val()),n.toggleLinkBtn(r,o,i)})).val(t.url),f.isSupportTouch||i.trigger("focus"),n.toggleLinkBtn(r,o,i),n.bindEnterKey(i,r),n.bindEnterKey(o,r);var l=void 0!==t.isNewWindow?t.isNewWindow:n.context.options.linkTargetBlank;a.prop("checked",l);var c=!t.url&&n.context.options.useProtocol;s.prop("checked",c),r.one("click",(function(r){r.preventDefault(),e.resolve({range:t.range,url:i.val(),text:o.val(),isNewWindow:a.is(":checked"),checkProtocol:s.is(":checked")}),n.ui.hideDialog(n.$dialog)}))})),n.ui.onDialogHidden(n.$dialog,(function(){o.off(),i.off(),r.off(),"pending"===e.state()&&e.reject()})),n.ui.showDialog(n.$dialog)})).promise()}},{key:"show",value:function(){var t=this,e=this.context.invoke("editor.getLinkInfo");this.context.invoke("editor.saveRange"),this.showLinkDialog(e).then((function(e){t.context.invoke("editor.restoreRange"),t.context.invoke("editor.createLink",e)})).fail((function(){t.context.invoke("editor.restoreRange")}))}}])&&le(n.prototype,o),i&&le(n,i),t}();function ue(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var de=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.options=n.options,this.events={"summernote.keyup summernote.mouseup summernote.change summernote.scroll":function(){o.update()},"summernote.disable summernote.dialog.shown":function(){o.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&o.$popover[0].contains(e.originalEvent.relatedTarget)||o.hide()}}}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return!k.isEmpty(this.options.popover.link)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-link-popover",callback:function(t){t.find(".popover-content,.note-popover-content").prepend('<span><a target="_blank"></a>&nbsp;</span>')}}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.link),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(){if(this.context.invoke("editor.hasFocus")){var t=this.context.invoke("editor.getLastRange");if(t.isCollapsed()&&t.isOnAnchor()){var n=ht.ancestor(t.sc,ht.isAnchor),o=e()(n).attr("href");this.$popover.find("a").attr("href",o).text(o);var i=ht.posFromPlaceholder(n),r=e()(this.options.container).offset();i.top-=r.top,i.left-=r.left,this.$popover.css({display:"block",left:i.left,top:i.top})}else this.hide()}else this.hide()}},{key:"hide",value:function(){this.$popover.hide()}}])&&ue(n.prototype,o),i&&ue(n,i),t}();function he(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var fe=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t="";if(this.options.maximumImageFileSize){var e=Math.floor(Math.log(this.options.maximumImageFileSize)/Math.log(1024)),n=1*(this.options.maximumImageFileSize/Math.pow(1024,e)).toFixed(2)+" "+" KMGTP"[e]+"B";t="<small>".concat(this.lang.image.maximumFileSize+" : "+n,"</small>")}var o=this.options.dialogsInBody?this.$body:this.options.container,i=['<div class="form-group note-form-group note-group-select-from-files">','<label for="note-dialog-image-file-'+this.options.id+'" class="note-form-label">'+this.lang.image.selectFromFiles+"</label>",'<input id="note-dialog-image-file-'+this.options.id+'" class="note-image-input form-control-file note-form-control note-input" ',' type="file" name="files" accept="'+this.options.acceptImageFileTypes+'" multiple="multiple"/>',t,"</div>",'<div class="form-group note-group-image-url">','<label for="note-dialog-image-url-'+this.options.id+'" class="note-form-label">'+this.lang.image.url+"</label>",'<input id="note-dialog-image-url-'+this.options.id+'" class="note-image-url form-control note-form-control note-input" type="text"/>',"</div>"].join(""),r='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-image-btn",'" value="').concat(this.lang.image.insert,'" disabled>');this.$dialog=this.ui.dialog({title:this.lang.image.insert,fade:this.options.dialogsFade,body:i,footer:r}).render().appendTo(o)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"show",value:function(){var t=this;this.context.invoke("editor.saveRange"),this.showImageDialog().then((function(e){t.ui.hideDialog(t.$dialog),t.context.invoke("editor.restoreRange"),"string"==typeof e?t.options.callbacks.onImageLinkInsert?t.context.triggerEvent("image.link.insert",e):t.context.invoke("editor.insertImage",e):t.context.invoke("editor.insertImagesOrCallback",e)})).fail((function(){t.context.invoke("editor.restoreRange")}))}},{key:"showImageDialog",value:function(){var t=this;return e().Deferred((function(e){var n=t.$dialog.find(".note-image-input"),o=t.$dialog.find(".note-image-url"),i=t.$dialog.find(".note-image-btn");t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),n.replaceWith(n.clone().on("change",(function(t){e.resolve(t.target.files||t.target.value)})).val("")),o.on("input paste propertychange",(function(){t.ui.toggleBtn(i,o.val())})).val(""),f.isSupportTouch||o.trigger("focus"),i.click((function(t){t.preventDefault(),e.resolve(o.val())})),t.bindEnterKey(o,i)})),t.ui.onDialogHidden(t.$dialog,(function(){n.off(),o.off(),i.off(),"pending"===e.state()&&e.reject()})),t.ui.showDialog(t.$dialog)}))}}])&&he(n.prototype,o),i&&he(n,i),t}();function pe(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var me=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.editable=n.layoutInfo.editable[0],this.options=n.options,this.events={"summernote.disable summernote.dialog.shown":function(){o.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&o.$popover[0].contains(e.originalEvent.relatedTarget)||o.hide()}}}var n,o,i;return n=t,o=[{key:"shouldInitialize",value:function(){return!k.isEmpty(this.options.popover.image)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-image-popover"}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.image),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t,n){if(ht.isImg(t)){var o=e()(t).offset(),i=e()(this.options.container).offset(),r={};this.options.popatmouse?(r.left=n.pageX-20,r.top=n.pageY):r=o,r.top-=i.top,r.left-=i.left,this.$popover.css({display:"block",left:r.left,top:r.top})}else this.hide()}},{key:"hide",value:function(){this.$popover.hide()}}],o&&pe(n.prototype,o),i&&pe(n,i),t}();function ve(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ge=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.options=n.options,this.events={"summernote.mousedown":function(t,e){o.update(e.target)},"summernote.keyup summernote.scroll summernote.change":function(){o.update()},"summernote.disable summernote.dialog.shown":function(){o.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&o.$popover[0].contains(e.originalEvent.relatedTarget)||o.hide()}}}var n,o,i;return n=t,o=[{key:"shouldInitialize",value:function(){return!k.isEmpty(this.options.popover.table)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-table-popover"}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.table),f.isFF&&document.execCommand("enableInlineTableEditing",!1,!1),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t){if(this.context.isDisabled())return!1;var n=ht.isCell(t)||ht.isCell(null==t?void 0:t.parentElement);if(n){var o=ht.posFromPlaceholder(t),i=e()(this.options.container).offset();o.top-=i.top,o.left-=i.left,this.$popover.css({display:"block",left:o.left,top:o.top})}else this.hide();return n}},{key:"hide",value:function(){this.$popover.hide()}}],o&&ve(n.prototype,o),i&&ve(n,i),t}();function be(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var ye=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo}var n,o,i;return n=t,(o=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,e=['<div class="form-group note-form-group row-fluid">','<label for="note-dialog-video-url-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.video.url,' <small class="text-muted">').concat(this.lang.video.providers,"</small></label>"),'<input id="note-dialog-video-url-'.concat(this.options.id,'" class="note-video-url form-control note-form-control note-input" type="text"/>'),"</div>"].join(""),n='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-video-btn",'" value="').concat(this.lang.video.insert,'" disabled>');this.$dialog=this.ui.dialog({title:this.lang.video.insert,fade:this.options.dialogsFade,body:e,footer:n}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"createVideoNode",value:function(t){var n,o=t.match(/\/\/(?:(?:www|m)\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))([\w|-]{11})(?:(?:[\?&]t=)(\S+))?$/),i=t.match(/(?:\.|\/\/)drive\.google\.com\/file\/d\/(.[a-zA-Z0-9_-]*)\/view/),r=t.match(/(?:www\.|\/\/)instagram\.com\/p\/(.[a-zA-Z0-9_-]*)/),a=t.match(/\/\/vine\.co\/v\/([a-zA-Z0-9]+)/),s=t.match(/\/\/(player\.)?vimeo\.com\/([a-z]*\/)*(\d+)[?]?.*/),l=t.match(/.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/),c=t.match(/\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/),u=t.match(/\/\/(.*)\/videos\/watch\/([^?]*)(?:\?(?:start=(\w*))?(?:&stop=(\w*))?(?:&loop=([10]))?(?:&autoplay=([10]))?(?:&muted=([10]))?)?/),d=t.match(/\/\/v\.qq\.com.*?vid=(.+)/),h=t.match(/\/\/v\.qq\.com\/x?\/?(page|cover).*?\/([^\/]+)\.html\??.*/),f=t.match(/^.+.(mp4|m4v)$/),p=t.match(/^.+.(ogg|ogv)$/),m=t.match(/^.+.(webm)$/),v=t.match(/(?:www\.|\/\/)facebook\.com\/([^\/]+)\/videos\/([0-9]+)/);if(o&&11===o[1].length){var g=o[1],b=0;if(void 0!==o[2]){var y=o[2].match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/);if(y)for(var k=[3600,60,1],w=0,C=k.length;w<C;w++)b+=void 0!==y[w+1]?k[w]*parseInt(y[w+1],10):0}n=e()("<iframe>").attr("frameborder",0).attr("src","//www.youtube.com/embed/"+g+(b>0?"?start="+b:"")).attr("width","640").attr("height","360")}else if(i&&i[0].length)n=e()("<iframe>").attr("frameborder",0).attr("src","https://drive.google.com/file/d/"+i[1]+"/preview").attr("width","640").attr("height","480");else if(r&&r[0].length)n=e()("<iframe>").attr("frameborder",0).attr("src","https://instagram.com/p/"+r[1]+"/embed/").attr("width","612").attr("height","710").attr("scrolling","no").attr("allowtransparency","true");else if(a&&a[0].length)n=e()("<iframe>").attr("frameborder",0).attr("src",a[0]+"/embed/simple").attr("width","600").attr("height","600").attr("class","vine-embed");else if(s&&s[3].length)n=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("src","//player.vimeo.com/video/"+s[3]).attr("width","640").attr("height","360");else if(l&&l[2].length)n=e()("<iframe>").attr("frameborder",0).attr("src","//www.dailymotion.com/embed/video/"+l[2]).attr("width","640").attr("height","360");else if(c&&c[1].length)n=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("height","498").attr("width","510").attr("src","//player.youku.com/embed/"+c[1]);else if(u&&u[0].length){var x=0;"undefined"!==u[2]&&(x=u[2]);var S=0;"undefined"!==u[3]&&(S=u[3]);var T=0;"undefined"!==u[4]&&(T=u[4]);var E=0;"undefined"!==u[5]&&(E=u[5]);var I=0;"undefined"!==u[6]&&(I=u[6]),n=e()('<iframe allowfullscreen sandbox="allow-same-origin allow-scripts allow-popups">').attr("frameborder",0).attr("src","//"+u[1]+"/videos/embed/"+u[2]+"?loop="+T+"&autoplay="+E+"&muted="+I+(x>0?"&start="+x:"")+(S>0?"&end="+b:"")).attr("width","560").attr("height","315")}else if(d&&d[1].length||h&&h[2].length){var $=d&&d[1].length?d[1]:h[2];n=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("height","310").attr("width","500").attr("src","https://v.qq.com/txp/iframe/player.html?vid="+$+"&amp;auto=0")}else if(f||p||m)n=e()("<video controls>").attr("src",t).attr("width","640").attr("height","360");else{if(!v||!v[0].length)return!1;n=e()("<iframe>").attr("frameborder",0).attr("src","https://www.facebook.com/plugins/video.php?href="+encodeURIComponent(v[0])+"&show_text=0&width=560").attr("width","560").attr("height","301").attr("scrolling","no").attr("allowtransparency","true")}return n.addClass("note-video-clip"),n[0]}},{key:"show",value:function(){var t=this,e=this.context.invoke("editor.getSelectedText");this.context.invoke("editor.saveRange"),this.showVideoDialog(e).then((function(e){t.ui.hideDialog(t.$dialog),t.context.invoke("editor.restoreRange");var n=t.createVideoNode(e);n&&t.context.invoke("editor.insertNode",n)})).fail((function(){t.context.invoke("editor.restoreRange")}))}},{key:"showVideoDialog",value:function(){var t=this;return e().Deferred((function(e){var n=t.$dialog.find(".note-video-url"),o=t.$dialog.find(".note-video-btn");t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),n.on("input paste propertychange",(function(){t.ui.toggleBtn(o,n.val())})),f.isSupportTouch||n.trigger("focus"),o.click((function(t){t.preventDefault(),e.resolve(n.val())})),t.bindEnterKey(n,o)})),t.ui.onDialogHidden(t.$dialog,(function(){n.off(),o.off(),"pending"===e.state()&&e.reject()})),t.ui.showDialog(t.$dialog)}))}}])&&be(n.prototype,o),i&&be(n,i),t}();function ke(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var we=function(){function t(n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=n.layoutInfo.editor,this.options=n.options,this.lang=this.options.langInfo}var n,o,i;return n=t,o=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,e=['<p class="text-center">','<a href="http://summernote.org/" target="_blank" rel="noopener noreferrer">Summernote 0.8.20</a> · ','<a href="https://github.com/summernote/summernote" target="_blank" rel="noopener noreferrer">Project</a> · ','<a href="https://github.com/summernote/summernote/issues" target="_blank" rel="noopener noreferrer">Issues</a>',"</p>"].join("");this.$dialog=this.ui.dialog({title:this.lang.options.help,fade:this.options.dialogsFade,body:this.createShortcutList(),footer:e,callback:function(t){t.find(".modal-body,.note-modal-body").css({"max-height":300,overflow:"scroll"})}}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"createShortcutList",value:function(){var t=this,n=this.options.keyMap[f.isMac?"mac":"pc"];return Object.keys(n).map((function(o){var i=n[o],r=e()('<div><div class="help-list-item"></div></div>');return r.append(e()("<label><kbd>"+o+"</kdb></label>").css({width:180,"margin-right":10})).append(e()("<span></span>").html(t.context.memo("help."+i)||i)),r.html()})).join("")}},{key:"showHelpDialog",value:function(){var t=this;return e().Deferred((function(e){t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),e.resolve()})),t.ui.showDialog(t.$dialog)})).promise()}},{key:"show",value:function(){var t=this;this.context.invoke("editor.saveRange"),this.showHelpDialog().then((function(){t.context.invoke("editor.restoreRange")}))}}],o&&ke(n.prototype,o),i&&ke(n,i),t}();function Ce(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var xe=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.options=n.options,this.hidable=!0,this.onContextmenu=!1,this.pageX=null,this.pageY=null,this.events={"summernote.contextmenu":function(t){o.options.editing&&(t.preventDefault(),t.stopPropagation(),o.onContextmenu=!0,o.update(!0))},"summernote.mousedown":function(t,e){o.pageX=e.pageX,o.pageY=e.pageY},"summernote.keyup summernote.mouseup summernote.scroll":function(t,e){o.options.editing&&!o.onContextmenu&&(o.pageX=e.pageX,o.pageY=e.pageY,o.update()),o.onContextmenu=!1},"summernote.disable summernote.change summernote.dialog.shown summernote.blur":function(){o.hide()},"summernote.focusout":function(){o.$popover.is(":active,:focus")||o.hide()}}}var n,o,i;return n=t,(o=[{key:"shouldInitialize",value:function(){return this.options.airMode&&!k.isEmpty(this.options.popover.air)}},{key:"initialize",value:function(){var t=this;this.$popover=this.ui.popover({className:"note-air-popover"}).render().appendTo(this.options.container);var e=this.$popover.find(".popover-content");this.context.invoke("buttons.build",e,this.options.popover.air),this.$popover.on("mousedown",(function(){t.hidable=!1})),this.$popover.on("mouseup",(function(){t.hidable=!0}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t){var n=this.context.invoke("editor.currentStyle");if(!n.range||n.range.isCollapsed()&&!t)this.hide();else{var o={left:this.pageX,top:this.pageY},i=e()(this.options.container).offset();o.top-=i.top,o.left-=i.left,this.$popover.css({display:"block",left:Math.max(o.left,0)+-5,top:o.top+5}),this.context.invoke("buttons.updateCurrentStyle",this.$popover)}}},{key:"updateCodeview",value:function(t){this.ui.toggleBtnActive(this.$popover.find(".btn-codeview"),t),t&&this.hide()}},{key:"hide",value:function(){this.hidable&&this.$popover.hide()}}])&&Ce(n.prototype,o),i&&Ce(n,i),t}();function Se(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var Te=function(){function t(n){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=n,this.ui=e().summernote.ui,this.$editable=n.layoutInfo.editable,this.options=n.options,this.hint=this.options.hint||[],this.direction=this.options.hintDirection||"bottom",this.hints=Array.isArray(this.hint)?this.hint:[this.hint],this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||o.handleKeyup(e)},"summernote.keydown":function(t,e){o.handleKeydown(e)},"summernote.disable summernote.dialog.shown summernote.blur":function(){o.hide()}}}var n,o,i;return n=t,o=[{key:"shouldInitialize",value:function(){return this.hints.length>0}},{key:"initialize",value:function(){var t=this;this.lastWordRange=null,this.matchingWord=null,this.$popover=this.ui.popover({className:"note-hint-popover",hideArrow:!0,direction:""}).render().appendTo(this.options.container),this.$popover.hide(),this.$content=this.$popover.find(".popover-content,.note-popover-content"),this.$content.on("click",".note-hint-item",(function(n){t.$content.find(".active").removeClass("active"),e()(n.currentTarget).addClass("active"),t.replace()})),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"selectItem",value:function(t){this.$content.find(".active").removeClass("active"),t.addClass("active"),this.$content[0].scrollTop=t[0].offsetTop-this.$content.innerHeight()/2}},{key:"moveDown",value:function(){var t=this.$content.find(".note-hint-item.active"),e=t.next();if(e.length)this.selectItem(e);else{var n=t.parent().next();n.length||(n=this.$content.find(".note-hint-group").first()),this.selectItem(n.find(".note-hint-item").first())}}},{key:"moveUp",value:function(){var t=this.$content.find(".note-hint-item.active"),e=t.prev();if(e.length)this.selectItem(e);else{var n=t.parent().prev();n.length||(n=this.$content.find(".note-hint-group").last()),this.selectItem(n.find(".note-hint-item").last())}}},{key:"replace",value:function(){var t=this.$content.find(".note-hint-item.active");if(t.length){var n=this.nodeFromItem(t);if(null!==this.matchingWord&&0===this.matchingWord.length)this.lastWordRange.so=this.lastWordRange.eo;else if(null!==this.matchingWord&&this.matchingWord.length>0&&!this.lastWordRange.isCollapsed()){var o=this.lastWordRange.eo-this.lastWordRange.so-this.matchingWord.length;o>0&&(this.lastWordRange.so+=o)}if(this.lastWordRange.insertNode(n),"next"===this.options.hintSelect){var i=document.createTextNode("");e()(n).after(i),yt.createFromNodeBefore(i).select()}else yt.createFromNodeAfter(n).select();this.lastWordRange=null,this.hide(),this.context.invoke("editor.focus"),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}}},{key:"nodeFromItem",value:function(t){var e=this.hints[t.data("index")],n=t.data("item"),o=e.content?e.content(n):n;return"string"==typeof o&&(o=ht.createText(o)),o}},{key:"createItemTemplates",value:function(t,n){var o=this.hints[t];return n.map((function(n){var i=e()('<div class="note-hint-item"></div>');return i.append(o.template?o.template(n):n+""),i.data({index:t,item:n}),i}))}},{key:"handleKeydown",value:function(t){this.$popover.is(":visible")&&(t.keyCode===wt.code.ENTER?(t.preventDefault(),this.replace()):t.keyCode===wt.code.UP?(t.preventDefault(),this.moveUp()):t.keyCode===wt.code.DOWN&&(t.preventDefault(),this.moveDown()))}},{key:"searchKeyword",value:function(t,e,n){var o=this.hints[t];if(o&&o.match.test(e)&&o.search){var i=o.match.exec(e);this.matchingWord=i[0],o.search(i[1],n)}else n()}},{key:"createGroup",value:function(t,n){var o=this,i=e()('<div class="note-hint-group note-hint-group-'+t+'"></div>');return this.searchKeyword(t,n,(function(e){(e=e||[]).length&&(i.html(o.createItemTemplates(t,e)),o.show())})),i}},{key:"handleKeyup",value:function(t){var n=this;if(!k.contains([wt.code.ENTER,wt.code.UP,wt.code.DOWN],t.keyCode)){var o,i,r=this.context.invoke("editor.getLastRange");if("words"===this.options.hintMode){if(o=r.getWordsRange(r),i=o.toString(),this.hints.forEach((function(t){if(t.match.test(i))return o=r.getWordsMatchRange(t.match),!1})),!o)return void this.hide();i=o.toString()}else o=r.getWordRange(),i=o.toString();if(this.hints.length&&i){this.$content.empty();var a=m.rect2bnd(k.last(o.getClientRects())),s=e()(this.options.container).offset();a&&(a.top-=s.top,a.left-=s.left,this.$popover.hide(),this.lastWordRange=o,this.hints.forEach((function(t,e){t.match.test(i)&&n.createGroup(e,i).appendTo(n.$content)})),this.$content.find(".note-hint-item:first").addClass("active"),"top"===this.direction?this.$popover.css({left:a.left,top:a.top-this.$popover.outerHeight()-5}):this.$popover.css({left:a.left,top:a.top+a.height+5}))}else this.hide()}}},{key:"show",value:function(){this.$popover.show()}},{key:"hide",value:function(){this.$popover.hide()}}],o&&Se(n.prototype,o),i&&Se(n,i),t}();function Ee(t){return Ee="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ee(t)}function Ie(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}e().summernote=e().extend(e().summernote,{version:"0.8.20",plugins:{},dom:ht,range:yt,lists:k,options:{langInfo:e().summernote.lang["en-US"],editing:!0,modules:{editor:Ft,clipboard:Ht,dropzone:Bt,codeview:jt,statusbar:Kt,fullscreen:qt,handle:Gt,hintPopover:Te,autoLink:Qt,autoSync:Jt,autoReplace:ee,placeholder:oe,buttons:re,toolbar:se,linkDialog:ce,linkPopover:de,imageDialog:fe,imagePopover:me,tablePopover:ge,videoDialog:ye,helpDialog:we,airPopover:xe},buttons:{},lang:"en-US",followingToolbar:!1,toolbarPosition:"top",otherStaticBar:"",codeviewKeepButton:!1,toolbar:[["style",["style"]],["font",["bold","underline","clear"]],["fontname",["fontname"]],["color",["color"]],["para",["ul","ol","paragraph"]],["table",["table"]],["insert",["link","picture","video"]],["view",["fullscreen","codeview","help"]]],popatmouse:!0,popover:{image:[["resize",["resizeFull","resizeHalf","resizeQuarter","resizeNone"]],["float",["floatLeft","floatRight","floatNone"]],["remove",["removeMedia"]]],link:[["link",["linkDialogShow","unlink"]]],table:[["add",["addRowDown","addRowUp","addColLeft","addColRight"]],["delete",["deleteRow","deleteCol","deleteTable"]]],air:[["color",["color"]],["font",["bold","underline","clear"]],["para",["ul","paragraph"]],["table",["table"]],["insert",["link","picture"]],["view",["fullscreen","codeview"]]]},airMode:!1,overrideContextMenu:!1,width:null,height:null,linkTargetBlank:!0,useProtocol:!0,defaultProtocol:"http://",focus:!1,tabDisabled:!1,tabSize:4,styleWithCSS:!1,shortcuts:!0,textareaAutoSync:!0,tooltip:"auto",container:null,maxTextLength:0,blockquoteBreakingLevel:2,spellCheck:!0,disableGrammar:!1,placeholder:null,inheritPlaceholder:!1,recordEveryKeystroke:!1,historyLimit:200,showDomainOnlyForAutolink:!1,hintMode:"word",hintSelect:"after",hintDirection:"bottom",styleTags:["p","blockquote","pre","h1","h2","h3","h4","h5","h6"],fontNames:["Arial","Arial Black","Comic Sans MS","Courier New","Helvetica Neue","Helvetica","Impact","Lucida Grande","Tahoma","Times New Roman","Verdana"],fontNamesIgnoreCheck:[],addDefaultFonts:!0,fontSizes:["8","9","10","11","12","14","18","24","36"],fontSizeUnits:["px","pt"],colors:[["#000000","#424242","#636363","#9C9C94","#CEC6CE","#EFEFEF","#F7F7F7","#FFFFFF"],["#FF0000","#FF9C00","#FFFF00","#00FF00","#00FFFF","#0000FF","#9C00FF","#FF00FF"],["#F7C6CE","#FFE7CE","#FFEFC6","#D6EFD6","#CEDEE7","#CEE7F7","#D6D6E7","#E7D6DE"],["#E79C9C","#FFC69C","#FFE79C","#B5D6A5","#A5C6CE","#9CC6EF","#B5A5D6","#D6A5BD"],["#E76363","#F7AD6B","#FFD663","#94BD7B","#73A5AD","#6BADDE","#8C7BC6","#C67BA5"],["#CE0000","#E79439","#EFC631","#6BA54A","#4A7B8C","#3984C6","#634AA5","#A54A7B"],["#9C0000","#B56308","#BD9400","#397B21","#104A5A","#085294","#311873","#731842"],["#630000","#7B3900","#846300","#295218","#083139","#003163","#21104A","#4A1031"]],colorsName:[["Black","Tundora","Dove Gray","Star Dust","Pale Slate","Gallery","Alabaster","White"],["Red","Orange Peel","Yellow","Green","Cyan","Blue","Electric Violet","Magenta"],["Azalea","Karry","Egg White","Zanah","Botticelli","Tropical Blue","Mischka","Twilight"],["Tonys Pink","Peach Orange","Cream Brulee","Sprout","Casper","Perano","Cold Purple","Careys Pink"],["Mandy","Rajah","Dandelion","Olivine","Gulf Stream","Viking","Blue Marguerite","Puce"],["Guardsman Red","Fire Bush","Golden Dream","Chelsea Cucumber","Smalt Blue","Boston Blue","Butterfly Bush","Cadillac"],["Sangria","Mai Tai","Buddha Gold","Forest Green","Eden","Venice Blue","Meteorite","Claret"],["Rosewood","Cinnamon","Olive","Parsley","Tiber","Midnight Blue","Valentino","Loulou"]],colorButton:{foreColor:"#000000",backColor:"#FFFF00"},lineHeights:["1.0","1.2","1.4","1.5","1.6","1.8","2.0","3.0"],tableClassName:"table table-bordered",insertTableMaxSize:{col:10,row:10},dialogsInBody:!1,dialogsFade:!1,maximumImageFileSize:null,acceptImageFileTypes:"image/*",callbacks:{onBeforeCommand:null,onBlur:null,onBlurCodeview:null,onChange:null,onChangeCodeview:null,onDialogShown:null,onEnter:null,onFocus:null,onImageLinkInsert:null,onImageUpload:null,onImageUploadError:null,onInit:null,onKeydown:null,onKeyup:null,onMousedown:null,onMouseup:null,onPaste:null,onScroll:null},codemirror:{mode:"text/html",htmlMode:!0,lineNumbers:!0},codeviewFilter:!0,codeviewFilterRegex:/<\/*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|ilayer|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|t(?:itle|extarea)|xml)[^>]*?>/gi,codeviewIframeFilter:!0,codeviewIframeWhitelistSrc:[],codeviewIframeWhitelistSrcBase:["www.youtube.com","www.youtube-nocookie.com","www.facebook.com","vine.co","instagram.com","player.vimeo.com","www.dailymotion.com","player.youku.com","jumpingbean.tv","v.qq.com"],keyMap:{pc:{ESC:"escape",ENTER:"insertParagraph","CTRL+Z":"undo","CTRL+Y":"redo",TAB:"tab","SHIFT+TAB":"untab","CTRL+B":"bold","CTRL+I":"italic","CTRL+U":"underline","CTRL+SHIFT+S":"strikethrough","CTRL+BACKSLASH":"removeFormat","CTRL+SHIFT+L":"justifyLeft","CTRL+SHIFT+E":"justifyCenter","CTRL+SHIFT+R":"justifyRight","CTRL+SHIFT+J":"justifyFull","CTRL+SHIFT+NUM7":"insertUnorderedList","CTRL+SHIFT+NUM8":"insertOrderedList","CTRL+LEFTBRACKET":"outdent","CTRL+RIGHTBRACKET":"indent","CTRL+NUM0":"formatPara","CTRL+NUM1":"formatH1","CTRL+NUM2":"formatH2","CTRL+NUM3":"formatH3","CTRL+NUM4":"formatH4","CTRL+NUM5":"formatH5","CTRL+NUM6":"formatH6","CTRL+ENTER":"insertHorizontalRule","CTRL+K":"linkDialog.show"},mac:{ESC:"escape",ENTER:"insertParagraph","CMD+Z":"undo","CMD+SHIFT+Z":"redo",TAB:"tab","SHIFT+TAB":"untab","CMD+B":"bold","CMD+I":"italic","CMD+U":"underline","CMD+SHIFT+S":"strikethrough","CMD+BACKSLASH":"removeFormat","CMD+SHIFT+L":"justifyLeft","CMD+SHIFT+E":"justifyCenter","CMD+SHIFT+R":"justifyRight","CMD+SHIFT+J":"justifyFull","CMD+SHIFT+NUM7":"insertUnorderedList","CMD+SHIFT+NUM8":"insertOrderedList","CMD+LEFTBRACKET":"outdent","CMD+RIGHTBRACKET":"indent","CMD+NUM0":"formatPara","CMD+NUM1":"formatH1","CMD+NUM2":"formatH2","CMD+NUM3":"formatH3","CMD+NUM4":"formatH4","CMD+NUM5":"formatH5","CMD+NUM6":"formatH6","CMD+ENTER":"insertHorizontalRule","CMD+K":"linkDialog.show"}},icons:{align:"note-icon-align",alignCenter:"note-icon-align-center",alignJustify:"note-icon-align-justify",alignLeft:"note-icon-align-left",alignRight:"note-icon-align-right",rowBelow:"note-icon-row-below",colBefore:"note-icon-col-before",colAfter:"note-icon-col-after",rowAbove:"note-icon-row-above",rowRemove:"note-icon-row-remove",colRemove:"note-icon-col-remove",indent:"note-icon-align-indent",outdent:"note-icon-align-outdent",arrowsAlt:"note-icon-arrows-alt",bold:"note-icon-bold",caret:"note-icon-caret",circle:"note-icon-circle",close:"note-icon-close",code:"note-icon-code",eraser:"note-icon-eraser",floatLeft:"note-icon-float-left",floatRight:"note-icon-float-right",font:"note-icon-font",frame:"note-icon-frame",italic:"note-icon-italic",link:"note-icon-link",unlink:"note-icon-chain-broken",magic:"note-icon-magic",menuCheck:"note-icon-menu-check",minus:"note-icon-minus",orderedlist:"note-icon-orderedlist",pencil:"note-icon-pencil",picture:"note-icon-picture",question:"note-icon-question",redo:"note-icon-redo",rollback:"note-icon-rollback",square:"note-icon-square",strikethrough:"note-icon-strikethrough",subscript:"note-icon-subscript",superscript:"note-icon-superscript",table:"note-icon-table",textHeight:"note-icon-text-height",trash:"note-icon-trash",underline:"note-icon-underline",undo:"note-icon-undo",unorderedlist:"note-icon-unorderedlist",video:"note-icon-video"}}});var $e=function(){function t(e,n,o,i){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.markup=e,this.children=n,this.options=o,this.callback=i}var n,o,i;return n=t,(o=[{key:"render",value:function(t){var n=e()(this.markup);if(this.options&&this.options.contents&&n.html(this.options.contents),this.options&&this.options.className&&n.addClass(this.options.className),this.options&&this.options.data&&e().each(this.options.data,(function(t,e){n.attr("data-"+t,e)})),this.options&&this.options.click&&n.on("click",this.options.click),this.children){var o=n.find(".note-children-container");this.children.forEach((function(t){t.render(o.length?o:n)}))}return this.callback&&this.callback(n,this.options),this.options&&this.options.callback&&this.options.callback(n),t&&t.append(n),n}}])&&Ie(n.prototype,o),i&&Ie(n,i),t}();const Ne=function(t,e){return function(){var n="object"===Ee(arguments[1])?arguments[1]:arguments[0],o=Array.isArray(arguments[0])?arguments[0]:[];return n&&n.children&&(o=n.children),new $e(t,o,n,e)}};function Pe(t){return Pe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Pe(t)}var Re=Ne('<div class="note-editor note-frame card"/>'),Le=Ne('<div class="note-toolbar card-header" role="toolbar"/>'),Ae=Ne('<div class="note-editing-area"/>'),Fe=Ne('<textarea class="note-codable" aria-multiline="true"/>'),De=Ne('<div class="note-editable card-block" contentEditable="true" role="textbox" aria-multiline="true"/>'),He=Ne(['<output class="note-status-output" role="status" aria-live="polite"></output>','<div class="note-statusbar" role="status">','<div class="note-resizebar" aria-label="Resize">','<div class="note-icon-bar"></div>','<div class="note-icon-bar"></div>','<div class="note-icon-bar"></div>',"</div>","</div>"].join("")),ze=Ne('<div class="note-editor note-airframe"/>'),Be=Ne(['<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>','<output class="note-status-output" role="status" aria-live="polite"></output>'].join("")),Me=Ne('<div class="note-btn-group btn-group">'),Oe=Ne('<div class="note-dropdown-menu dropdown-menu" role="list">',(function(t,e){var n=Array.isArray(e.items)?e.items.map((function(t){var n="string"==typeof t?t:t.value||"",o=e.template?e.template(t):t,i="object"===Pe(t)?t.option:void 0;return'<a class="dropdown-item" href="#" '+('data-value="'+n+'"'+(void 0!==i?' data-option="'+i+'"':""))+' role="listitem" aria-label="'+n+'">'+o+"</a>"})).join(""):e.items;t.html(n).attr({"aria-label":e.title}),e&&e.codeviewKeepButton&&t.addClass("note-codeview-keep")})),Ue=function(t){return t},je=Ne('<div class="note-dropdown-menu dropdown-menu note-check" role="list">',(function(t,e){var n=Array.isArray(e.items)?e.items.map((function(t){var n="string"==typeof t?t:t.value||"",o=e.template?e.template(t):t;return'<a class="dropdown-item" href="#" data-value="'+n+'" role="listitem" aria-label="'+t+'">'+qe(e.checkClassName)+" "+o+"</a>"})).join(""):e.items;t.html(n).attr({"aria-label":e.title}),e&&e.codeviewKeepButton&&t.addClass("note-codeview-keep")})),We=Ne('<div class="modal note-modal" aria-hidden="false" tabindex="-1" role="dialog"/>',(function(t,e){e.fade&&t.addClass("fade"),t.attr({"aria-label":e.title}),t.html(['<div class="modal-dialog">','<div class="modal-content">',e.title?'<div class="modal-header"><h4 class="modal-title">'+e.title+'</h4><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" aria-hidden="true"></button></div>':"",'<div class="modal-body">'+e.body+"</div>",e.footer?'<div class="modal-footer">'+e.footer+"</div>":"","</div>","</div>"].join(""))})),Ke=Ne(['<div class="note-popover popover show">','<div class="popover-arrow"></div>','<div class="popover-body note-children-container"></div>',"</div>"].join(""),(function(t,e){var n=void 0!==e.direction?e.direction:"bottom";t.attr("data-bs-placement",n),e.hideArrow&&t.find(".popover-arrow").hide()})),Ve=Ne('<div class="form-check"></div>',(function(t,e){t.html(['<label class="form-check-label"'+(e.id?' for="note-'+e.id+'"':"")+">",'<input type="checkbox" class="form-check-input"'+(e.id?' id="note-'+e.id+'"':""),e.checked?" checked":"",' aria-label="'+(e.text?e.text:"")+'"',' aria-checked="'+(e.checked?"true":"false")+'"/>'," "+(e.text?e.text:"")+"</label>"].join(""))})),qe=function(t,e){return t.match(/^</)?t:"<"+(e=e||"i")+' class="'+t+'"></'+e+">"};e().summernote=e().extend(e().summernote,{ui_template:function(t){return{editor:Re,toolbar:Le,editingArea:Ae,codable:Fe,editable:De,statusbar:He,airEditor:ze,airEditable:Be,buttonGroup:Me,dropdown:Oe,dropdownButtonContents:Ue,dropdownCheck:je,dialog:We,popover:Ke,icon:qe,checkbox:Ve,options:t,palette:function(e,n){return Ne('<div class="note-color-palette"/>',(function(e,n){for(var o=[],i=0,r=n.colors.length;i<r;i++){for(var a=n.eventName,s=n.colors[i],l=n.colorsName[i],c=[],u=0,d=s.length;u<d;u++){var h=s[u],f=l[u];c.push(['<button type="button" class="note-color-btn"','style="background-color:',h,'" ','data-event="',a,'" ','data-value="',h,'" ','title="',f,'" ','aria-label="',f,'" ','data-toggle="button" tabindex="-1"></button>'].join(""))}o.push('<div class="note-color-row">'+c.join("")+"</div>")}e.html(o.join("")),n.tooltip&&e.find(".note-color-btn").tooltip({container:n.container||t.container,trigger:"hover",placement:"bottom"})}))(e,n)},button:function(n,o){return Ne('<button type="button" class="note-btn btn btn-light btn-sm" tabindex="-1">',(function(n,o){o&&o.tooltip&&n.attr({title:o.tooltip,"aria-label":o.tooltip}).tooltip({container:o.container||t.container,trigger:"hover",placement:"bottom"}).on("click",(function(t){e()(t.currentTarget).tooltip("hide")})),o&&o.codeviewButton&&n.addClass("note-codeview-keep")}))(n,o)},toggleBtn:function(t,e){t.toggleClass("disabled",!e),t.attr("disabled",!e)},toggleBtnActive:function(t,e){t.toggleClass("active",e)},onDialogShown:function(t,e){t.one("shown.bs.modal",e)},onDialogHidden:function(t,e){t.one("hidden.bs.modal",e)},showDialog:function(t){t.modal("show")},hideDialog:function(t){t.modal("hide")},createLayout:function(e){var n=(t.airMode?ze([Ae([Fe(),Be()])]):"bottom"===t.toolbarPosition?Re([Ae([Fe(),De()]),Le(),He()]):Re([Le(),Ae([Fe(),De()]),He()])).render();return n.insertAfter(e),{note:e,editor:n,toolbar:n.find(".note-toolbar"),editingArea:n.find(".note-editing-area"),editable:n.find(".note-editable"),codable:n.find(".note-codable"),statusbar:n.find(".note-statusbar")}},removeLayout:function(t,e){t.html(e.editable.html()),e.editor.remove(),t.show()}}},interface:"bs5"}),e().summernote.options.styleTags=["p",{title:"Blockquote",tag:"blockquote",className:"blockquote",value:"blockquote"},"pre","h1","h2","h3","h4","h5","h6"]})(),i})()}));
294coder/Efficient-MIF
16,273
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/manopt/manopt/solvers/conjugategradient/linear_conjugategradient.m
function [x, cost, info, options] = linear_conjugategradient(problem, x, options) % Conjugate gradient minimization algorithm for Manopt. % % function [x, cost, info, options] = linear_conjugategradient(problem) % function [x, cost, info, options] = linear_conjugategradient(problem, x0) % function [x, cost, info, options] = linear_conjugategradient(problem, x0, options) % function [x, cost, info, options] = linear_conjugategradient(problem, [], options) % % Apply the conjugate gradient minimization algorithm to the problem % defined in the problem structure, starting at x0 if it is provided % (otherwise, at a random point on the manifold). To specify options whilst % not specifying an initial guess, give x0 as [] (the empty matrix). % % The outputs x and cost are the best reached point on the manifold and its % cost. The struct-array info contains information about the iterations: % iter : the iteration number (0 for the initial guess) % cost : cost value % time : elapsed time in seconds % gradnorm : Riemannian norm of the gradient % stepsize : norm of the last tangent vector retracted % beta : value of the beta parameter (see options.beta_type) % linesearch : information logged by options.linesearch % And possibly additional information logged by options.statsfun. % For example, type [info.gradnorm] to obtain a vector of the successive % gradient norms reached. % % The options structure is used to overwrite the default values. All % options have a default value and are hence optional. To force an option % value, pass an options structure with a field options.optionname, where % optionname is one of the following and the default value is indicated % between parentheses: % % tolgradnorm (1e-6) % The algorithm terminates if the norm of the gradient drops below this. % maxiter (1000) % The algorithm terminates if maxiter iterations have been executed. % maxtime (Inf) % The algorithm terminates if maxtime seconds elapsed. % minstepsize (1e-10) % The algorithm terminates if the linesearch returns a displacement % vector (to be retracted) smaller in norm than this value. % beta_type ('H-S') % Conjugate gradient beta rule used to construct the new search % direction, based on a linear combination of the previous search % direction and the new (preconditioned) gradient. Possible values % for this parameter are: % 'S-D', 'steep' for beta = 0 (preconditioned steepest descent) % 'F-R' for Fletcher-Reeves's rule % 'P-R' for Polak-Ribiere's modified rule % 'H-S' for Hestenes-Stiefel's modified rule % 'H-Z' for Hager-Zhang's modified rule % See Hager and Zhang 2006, "A survey of nonlinear conjugate gradient % methods" for a description of these rules in the Euclidean case and % for an explanation of how to adapt them to the preconditioned case. % The adaption to the Riemannian case is straightforward: see in code % for details. Modified rules take the max between 0 and the computed % beta value, which provides automatic restart, except for H-Z which % uses a different modification. % orth_value (Inf) % Following Powell's restart strategy (Math. prog. 1977), restart CG % (that is, make a -preconditioned- gradient step) if two successive % -preconditioned- gradients are "too" parallel. See for example % Hager and Zhang 2006, "A survey of nonlinear conjugate gradient % methods", page 12. An infinite value disables this strategy. See in % code formula for the specific criterion used. % linesearch (@linesearch_adaptive or @linesearch_hint) % Function handle to a line search function. The options structure is % passed to the line search too, so you can pass it parameters. See % each line search's documentation for info. Another available line % search in manopt is @linesearch, in /manopt/linesearch/linesearch.m % If the problem structure includes a line search hint, then the % default line search used is @linesearch_hint. % statsfun (none) % Function handle to a function that will be called after each % iteration to provide the opportunity to log additional statistics. % They will be returned in the info struct. See the generic Manopt % documentation about solvers for further information. % stopfun (none) % Function handle to a function that will be called at each iteration % to provide the opportunity to specify additional stopping criteria. % See the generic Manopt documentation about solvers for further % information. % verbosity (3) % Integer number used to tune the amount of output the algorithm % generates during execution (mostly as text in the command window). % The higher, the more output. 0 means silent. % storedepth (2) % Maximum number of different points x of the manifold for which a % store structure will be kept in memory in the storedb. If the % caching features of Manopt are not used, this is irrelevant. For % the CG algorithm, a store depth of 2 should always be sufficient. % % % In most of the examples bundled with the toolbox (see link below), the % solver can be replaced by the present one if need be. % % See also: steepestdescent trustregions manopt/solvers/linesearch manopt/examples % An explicit, general listing of this algorithm, with preconditioning, % can be found in the following paper: % @Article{boumal2015lowrank, % Title = {Low-rank matrix completion via preconditioned optimization on the {G}rassmann manifold}, % Author = {Boumal, N. and Absil, P.-A.}, % Journal = {Linear Algebra and its Applications}, % Year = {2015}, % Pages = {200--239}, % Volume = {475}, % Doi = {10.1016/j.laa.2015.02.027}, % } % This file is part of Manopt: www.manopt.org. % Original author: Bamdev Mishra, Dec. 30, 2012. % Contributors: Nicolas Boumal % Change log: % % March 14, 2013, NB: % Added preconditioner support : see Section 8 in % https://www.math.lsu.edu/~hozhang/papers/cgsurvey.pdf % % Sept. 13, 2013, NB: % Now logging beta parameter too. % % Nov. 7, 2013, NB: % The search direction is no longer normalized before it is passed % to the linesearch. This way, it is up to the designers of the % linesearch to decide whether they want to use the norm of the % search direction in their algorithm or not. There are reasons % against it, but practical evidence that it may help too, so we % allow it. The default linesearch_adaptive used does exploit the % norm information. The base linesearch does not. You may select it % by setting options.linesearch = @linesearch; % % Nov. 29, 2013, NB: % Documentation improved: options are now explicitly described. % Removed the Daniel rule for beta: it was not appropriate for % preconditioned CG and I could not find a proper reference for it. % % April 3, 2015 (NB): % Works with the new StoreDB class system. % Verify that the problem description is sufficient for the solver. if ~canGetCost(problem) warning('manopt:getCost', ... 'No cost provided. The algorithm will likely abort.'); end if ~canGetGradient(problem) && ~canGetApproxGradient(problem) warning('manopt:getGradient:approx', ... ['No gradient provided. Using an FD approximation instead (slow).\n' ... 'It may be necessary to increase options.tolgradnorm.\n' ... 'To disable this warning: warning(''off'', ''manopt:getGradient:approx'')']); problem.approxgrad = approxgradientFD(problem); end % Set local defaults here localdefaults.minstepsize = 1e-10; localdefaults.maxiter = 1000; localdefaults.tolgradnorm = 1e-6; localdefaults.storedepth = 20; % Changed by NB : H-S has the "auto restart" property. % See Hager-Zhang 2005/2006 survey about CG methods. % The auto restart comes from the 'max(0, ...)', not so much from the % reason stated in Hager-Zhang I think. P-R also has auto restart. localdefaults.beta_type = 'H-S'; localdefaults.orth_value = Inf; % by BM as suggested in Nocedal and Wright % Depending on whether the problem structure specifies a hint for % line-search algorithms, choose a default line-search that works on % its own (typical) or that uses the hint. if ~canGetLinesearch(problem) localdefaults.linesearch = @linesearch_adaptive; else localdefaults.linesearch = @linesearch_hint; end % Merge global and local defaults, then merge w/ user options, if any. localdefaults = mergeOptions(getGlobalDefaults(), localdefaults); if ~exist('options', 'var') || isempty(options) options = struct(); end options = mergeOptions(localdefaults, options); % For convenience inner = problem.M.inner; lincomb = problem.M.lincomb; timetic = tic(); % If no initial point x is given by the user, generate one at random. if ~exist('x', 'var') || isempty(x) x = problem.M.rand(); end % Create a store database and generate a key for the current x storedb = StoreDB(options.storedepth); key = storedb.getNewKey(); % Compute cost-related quantities for x [cost, grad] = getCostGrad(problem, x, storedb, key); gradnorm = problem.M.norm(x, grad); Pgrad = getPrecon(problem, x, grad, storedb, key); gradPgrad = inner(x, grad, Pgrad); % Iteration counter (at any point, iter is the number of fully executed % iterations so far) iter = 0; % Save stats in a struct array info and preallocate. stats = savestats(); info(1) = stats; info(min(10000, options.maxiter+1)).iter = []; if options.verbosity >= 2 fprintf(' iter\t cost val\t grad. norm\n'); end % Compute a first descent direction (not normalized) desc_dir = lincomb(x, -1, Pgrad); % Start iterating until stopping criterion triggers while true % Display iteration information if options.verbosity >= 2 fprintf('%5d\t%+.16e\t%.8e\n', iter, cost, gradnorm); end % Start timing this iteration timetic = tic(); % Run standard stopping criterion checks [stop, reason] = stoppingcriterion(problem, x, options, info, iter+1); % Run specific stopping criterion check if ~stop && abs(stats.stepsize) < options.minstepsize stop = true; reason = sprintf(['Last stepsize smaller than minimum ' ... 'allowed; options.minstepsize = %g.'], ... options.minstepsize); end if stop if options.verbosity >= 1 fprintf([reason '\n']); end break; end % The line search algorithms require the directional derivative of the % cost at the current point x along the search direction. df0 = inner(x, grad, desc_dir); % If we didn't get a descent direction: restart, i.e., switch to the % negative gradient. Equivalent to resetting the CG direction to a % steepest descent step, which discards the past information. if df0 >= 0 % Or we switch to the negative gradient direction. if options.verbosity >= 3 fprintf(['Conjugate gradient info: got an ascent direction '... '(df0 = %2e), reset to the (preconditioned) '... 'steepest descent direction.\n'], df0); end % Reset to negative gradient: this discards the CG memory. desc_dir = lincomb(x, -1, Pgrad); df0 = -gradPgrad; end % Execute line search [stepsize, newx, newkey, lsstats] = options.linesearch( ... problem, x, desc_dir, cost, df0, options, storedb, key); % Compute the new cost-related quantities for newx [newcost, newgrad] = getCostGrad(problem, newx, storedb, newkey); newgradnorm = problem.M.norm(newx, newgrad); Pnewgrad = getPrecon(problem, newx, newgrad, storedb, newkey); newgradPnewgrad = inner(newx, newgrad, Pnewgrad); % Apply the CG scheme to compute the next search direction. % % This paper https://www.math.lsu.edu/~hozhang/papers/cgsurvey.pdf % by Hager and Zhang lists many known beta rules. The rules defined % here can be found in that paper (or are provided with additional % references), adapted to the Riemannian setting. % if strcmpi(options.beta_type, 'steep') || ... strcmpi(options.beta_type, 'S-D') % Gradient Descent beta = 0; desc_dir = lincomb(x, -1, Pnewgrad); else oldgrad = problem.M.transp(x, newx, grad); orth_grads = inner(newx, oldgrad, Pnewgrad) / newgradPnewgrad; % Powell's restart strategy (see page 12 of Hager and Zhang's % survey on conjugate gradient methods, for example) if abs(orth_grads) >= options.orth_value, beta = 0; desc_dir = lincomb(x, -1, Pnewgrad); else % Compute the CG modification desc_dir = problem.M.transp(x, newx, desc_dir); switch upper(options.beta_type) case 'F-R' % Fletcher-Reeves beta = newgradPnewgrad / gradPgrad; case 'P-R' % Polak-Ribiere+ % vector grad(new) - transported grad(current) diff = lincomb(newx, 1, newgrad, -1, oldgrad); ip_diff = inner(newx, Pnewgrad, diff); beta = ip_diff / gradPgrad; beta = max(0, beta); case 'H-S' % Hestenes-Stiefel+ diff = lincomb(newx, 1, newgrad, -1, oldgrad); ip_diff = inner(newx, Pnewgrad, diff); beta = ip_diff / inner(newx, diff, desc_dir); beta = max(0, beta); case 'H-Z' % Hager-Zhang+ diff = lincomb(newx, 1, newgrad, -1, oldgrad); Poldgrad = problem.M.transp(x, newx, Pgrad); Pdiff = lincomb(newx, 1, Pnewgrad, -1, Poldgrad); deno = inner(newx, diff, desc_dir); numo = inner(newx, diff, Pnewgrad); numo = numo - 2*inner(newx, diff, Pdiff)*... inner(newx, desc_dir, newgrad) / deno; beta = numo / deno; % Robustness (see Hager-Zhang paper mentioned above) desc_dir_norm = problem.M.norm(newx, desc_dir); eta_HZ = -1 / ( desc_dir_norm * min(0.01, gradnorm) ); beta = max(beta, eta_HZ); otherwise error(['Unknown options.beta_type. ' ... 'Should be steep, S-D, F-R, P-R, H-S or H-Z.']); end desc_dir = lincomb(newx, -1, Pnewgrad, beta, desc_dir); end end % Make sure we don't use too much memory for the store database storedb.purge(); % Transfer iterate info x = newx; key = newkey; cost = newcost; grad = newgrad; Pgrad = Pnewgrad; gradnorm = newgradnorm; gradPgrad = newgradPnewgrad; % iter is the number of iterations we have accomplished. iter = iter + 1; % Log statistics for freshly executed iteration stats = savestats(); info(iter+1) = stats; %#ok<AGROW> end info = info(1:iter+1); if options.verbosity >= 1 fprintf('Total time is %f [s] (excludes statsfun)\n', info(end).time); end % Routine in charge of collecting the current iteration stats function stats = savestats() stats.iter = iter; stats.cost = cost; stats.gradnorm = gradnorm; if iter == 0 stats.stepsize = nan; stats.time = toc(timetic); stats.linesearch = []; stats.beta = 0; else stats.stepsize = stepsize; stats.time = info(iter).time + toc(timetic); stats.linesearch = lsstats; stats.beta = beta; end stats = applyStatsfun(problem, x, storedb, key, options, stats); end end
2881099/FreeSql.AdminLTE
164,902
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-lite.min.js
/*! Summernote v0.8.20 | (c) 2013- Alan Hong and contributors | MIT license */ !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e(require("jQuery"));else if("function"==typeof define&&define.amd)define(["jQuery"],e);else{var o="object"==typeof exports?e(require("jQuery")):e(t.jQuery);for(var n in o)("object"==typeof exports?exports:t)[n]=o[n]}}(self,(function(t){return(()=>{"use strict";var e={9770:(t,e,o)=>{var n=o(1145),i=o.n(n);i().summernote=i().summernote||{lang:{}},i().extend(i().summernote.lang,{"en-US":{font:{bold:"Bold",italic:"Italic",underline:"Underline",clear:"Remove Font Style",height:"Line Height",name:"Font Family",strikethrough:"Strikethrough",subscript:"Subscript",superscript:"Superscript",size:"Font Size",sizeunit:"Font Size Unit"},image:{image:"Picture",insert:"Insert Image",resizeFull:"Resize full",resizeHalf:"Resize half",resizeQuarter:"Resize quarter",resizeNone:"Original size",floatLeft:"Float Left",floatRight:"Float Right",floatNone:"Remove float",shapeRounded:"Shape: Rounded",shapeCircle:"Shape: Circle",shapeThumbnail:"Shape: Thumbnail",shapeNone:"Shape: None",dragImageHere:"Drag image or text here",dropImage:"Drop image or Text",selectFromFiles:"Select from files",maximumFileSize:"Maximum file size",maximumFileSizeError:"Maximum file size exceeded.",url:"Image URL",remove:"Remove Image",original:"Original"},video:{video:"Video",videoLink:"Video Link",insert:"Insert Video",url:"Video URL",providers:"(YouTube, Google Drive, Vimeo, Vine, Instagram, DailyMotion, Youku, Peertube)"},link:{link:"Link",insert:"Insert Link",unlink:"Unlink",edit:"Edit",textToDisplay:"Text to display",url:"To what URL should this link go?",openInNewWindow:"Open in new window",useProtocol:"Use default protocol"},table:{table:"Table",addRowAbove:"Add row above",addRowBelow:"Add row below",addColLeft:"Add column left",addColRight:"Add column right",delRow:"Delete row",delCol:"Delete column",delTable:"Delete table"},hr:{insert:"Insert Horizontal Rule"},style:{style:"Style",p:"Normal",blockquote:"Quote",pre:"Code",h1:"Header 1",h2:"Header 2",h3:"Header 3",h4:"Header 4",h5:"Header 5",h6:"Header 6"},lists:{unordered:"Unordered list",ordered:"Ordered list"},options:{help:"Help",fullscreen:"Full Screen",codeview:"Code View"},paragraph:{paragraph:"Paragraph",outdent:"Outdent",indent:"Indent",left:"Align left",center:"Align center",right:"Align right",justify:"Justify full"},color:{recent:"Recent Color",more:"More Color",background:"Background Color",foreground:"Text Color",transparent:"Transparent",setTransparent:"Set transparent",reset:"Reset",resetToDefault:"Reset to default",cpSelect:"Select"},shortcut:{shortcuts:"Keyboard shortcuts",close:"Close",textFormatting:"Text formatting",action:"Action",paragraphFormatting:"Paragraph formatting",documentStyle:"Document Style",extraKeys:"Extra keys"},help:{escape:"Escape",insertParagraph:"Insert Paragraph",undo:"Undo the last command",redo:"Redo the last command",tab:"Tab",untab:"Untab",bold:"Set a bold style",italic:"Set a italic style",underline:"Set a underline style",strikethrough:"Set a strikethrough style",removeFormat:"Clean a style",justifyLeft:"Set left align",justifyCenter:"Set center align",justifyRight:"Set right align",justifyFull:"Set full align",insertUnorderedList:"Toggle unordered list",insertOrderedList:"Toggle ordered list",outdent:"Outdent on current paragraph",indent:"Indent on current paragraph",formatPara:"Change current block's format as a paragraph(P tag)",formatH1:"Change current block's format as H1",formatH2:"Change current block's format as H2",formatH3:"Change current block's format as H3",formatH4:"Change current block's format as H4",formatH5:"Change current block's format as H5",formatH6:"Change current block's format as H6",insertHorizontalRule:"Insert horizontal rule","linkDialog.show":"Show Link Dialog"},history:{undo:"Undo",redo:"Redo"},specialChar:{specialChar:"SPECIAL CHARACTERS",select:"Select Special characters"},output:{noSelection:"No Selection Made!"}}})},1145:e=>{e.exports=t}},o={};function n(t){var i=o[t];if(void 0!==i)return i.exports;var r=o[t]={exports:{}};return e[t](r,r.exports,n),r.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var i={};return(()=>{n.r(i);var t=n(1145),e=n.n(t),o=(n(9770),["sans-serif","serif","monospace","cursive","fantasy"]);function r(t){return-1===e().inArray(t.toLowerCase(),o)?"'".concat(t,"'"):t}var a,s=navigator.userAgent,l=/MSIE|Trident/i.test(s);if(l){var c=/MSIE (\d+[.]\d+)/.exec(s);c&&(a=parseFloat(c[1])),(c=/Trident\/.*rv:([0-9]{1,}[.0-9]{0,})/.exec(s))&&(a=parseFloat(c[1]))}var u=/Edge\/\d+/.test(s),d="ontouchstart"in window||navigator.MaxTouchPoints>0||navigator.msMaxTouchPoints>0,h=l?"DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted":"input";const f={isMac:navigator.appVersion.indexOf("Mac")>-1,isMSIE:l,isEdge:u,isFF:!u&&/firefox/i.test(s),isPhantom:/PhantomJS/i.test(s),isWebkit:!u&&/webkit/i.test(s),isChrome:!u&&/chrome/i.test(s),isSafari:!u&&/safari/i.test(s)&&!/chrome/i.test(s),browserVersion:a,isSupportTouch:d,isFontInstalled:function(t){var e="Comic Sans MS"===t?"Courier New":"Comic Sans MS",o="mmmmmmmmmmwwwww",n=document.createElement("canvas").getContext("2d");n.font="200px '"+e+"'";var i=n.measureText(o).width;return n.font="200px "+r(t)+', "'+e+'"',i!==n.measureText(o).width},isW3CRangeSupport:!!document.createRange,inputEventName:h,genericFontFamilies:o,validFontName:r};var p=0;const v={eq:function(t){return function(e){return t===e}},eq2:function(t,e){return t===e},peq2:function(t){return function(e,o){return e[t]===o[t]}},ok:function(){return!0},fail:function(){return!1},self:function(t){return t},not:function(t){return function(){return!t.apply(t,arguments)}},and:function(t,e){return function(o){return t(o)&&e(o)}},invoke:function(t,e){return function(){return t[e].apply(t,arguments)}},resetUniqueId:function(){p=0},uniqueId:function(t){var e=++p+"";return t?t+e:e},rect2bnd:function(t){var o=e()(document);return{top:t.top+o.scrollTop(),left:t.left+o.scrollLeft(),width:t.right-t.left,height:t.bottom-t.top}},invertObject:function(t){var e={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[t[o]]=o);return e},namespaceToCamel:function(t,e){return(e=e||"")+t.split(".").map((function(t){return t.substring(0,1).toUpperCase()+t.substring(1)})).join("")},debounce:function(t,e,o){var n;return function(){var i=this,r=arguments,a=function(){n=null,o||t.apply(i,r)},s=o&&!n;clearTimeout(n),n=setTimeout(a,e),s&&t.apply(i,r)}},isValidUrl:function(t){return/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/gi.test(t)}};function m(t){return t[0]}function g(t){return t[t.length-1]}function b(t){return t.slice(1)}function k(t,e){if(t&&t.length&&e){if(t.indexOf)return-1!==t.indexOf(e);if(t.contains)return t.contains(e)}return!1}const y={head:m,last:g,initial:function(t){return t.slice(0,t.length-1)},tail:b,prev:function(t,e){if(t&&t.length&&e){var o=t.indexOf(e);return-1===o?null:t[o-1]}return null},next:function(t,e){if(t&&t.length&&e){var o=t.indexOf(e);return-1===o?null:t[o+1]}return null},find:function(t,e){for(var o=0,n=t.length;o<n;o++){var i=t[o];if(e(i))return i}},contains:k,all:function(t,e){for(var o=0,n=t.length;o<n;o++)if(!e(t[o]))return!1;return!0},sum:function(t,e){return e=e||v.self,t.reduce((function(t,o){return t+e(o)}),0)},from:function(t){for(var e=[],o=t.length,n=-1;++n<o;)e[n]=t[n];return e},isEmpty:function(t){return!t||!t.length},clusterBy:function(t,e){return t.length?b(t).reduce((function(t,o){var n=g(t);return e(g(n),o)?n[n.length]=o:t[t.length]=[o],t}),[[m(t)]]):[]},compact:function(t){for(var e=[],o=0,n=t.length;o<n;o++)t[o]&&e.push(t[o]);return e},unique:function(t){for(var e=[],o=0,n=t.length;o<n;o++)k(e,t[o])||e.push(t[o]);return e}};var w=String.fromCharCode(160);function C(t){return t&&e()(t).hasClass("note-editable")}function x(t){return t=t.toUpperCase(),function(e){return e&&e.nodeName.toUpperCase()===t}}function S(t){return t&&3===t.nodeType}function T(t){return t&&/^BR|^IMG|^HR|^IFRAME|^BUTTON|^INPUT|^AUDIO|^VIDEO|^EMBED/.test(t.nodeName.toUpperCase())}function E(t){return!C(t)&&(t&&/^DIV|^P|^LI|^H[1-7]/.test(t.nodeName.toUpperCase()))}var $=x("PRE"),N=x("LI");var I=x("TABLE"),P=x("DATA");function R(t){return!(H(t)||L(t)||A(t)||E(t)||I(t)||D(t)||P(t))}function L(t){return t&&/^UL|^OL/.test(t.nodeName.toUpperCase())}var A=x("HR");function F(t){return t&&/^TD|^TH/.test(t.nodeName.toUpperCase())}var D=x("BLOCKQUOTE");function H(t){return F(t)||D(t)||C(t)}var B=x("A");var z=x("BODY");var M=f.isMSIE&&f.browserVersion<11?"&nbsp;":"<br>";function O(t){return S(t)?t.nodeValue.length:t?t.childNodes.length:0}function j(t){var e=O(t);return 0===e||(!S(t)&&1===e&&t.innerHTML===M||!(!y.all(t.childNodes,S)||""!==t.innerHTML))}function U(t){T(t)||O(t)||(t.innerHTML=M)}function W(t,e){for(;t;){if(e(t))return t;if(C(t))break;t=t.parentNode}return null}function K(t,e){e=e||v.fail;var o=[];return W(t,(function(t){return C(t)||o.push(t),e(t)})),o}function V(t,e){e=e||v.fail;for(var o=[];t&&!e(t);)o.push(t),t=t.nextSibling;return o}function q(t,e){var o=e.nextSibling,n=e.parentNode;return o?n.insertBefore(t,o):n.appendChild(t),t}function _(t,o){return e().each(o,(function(e,o){t.appendChild(o)})),t}function G(t){return 0===t.offset}function Y(t){return t.offset===O(t.node)}function Z(t){return G(t)||Y(t)}function X(t,e){for(;t&&t!==e;){if(0!==J(t))return!1;t=t.parentNode}return!0}function Q(t,e){if(!e)return!1;for(;t&&t!==e;){if(J(t)!==O(t.parentNode)-1)return!1;t=t.parentNode}return!0}function J(t){for(var e=0;t=t.previousSibling;)e+=1;return e}function tt(t){return!!(t&&t.childNodes&&t.childNodes.length)}function et(t,e){var o,n;if(0===t.offset){if(C(t.node))return null;o=t.node.parentNode,n=J(t.node)}else tt(t.node)?n=O(o=t.node.childNodes[t.offset-1]):(o=t.node,n=e?0:t.offset-1);return{node:o,offset:n}}function ot(t,e){var o,n;if(O(t.node)===t.offset){if(C(t.node))return null;var i=it(t.node);i?(o=i,n=0):(o=t.node.parentNode,n=J(t.node)+1)}else tt(t.node)?(o=t.node.childNodes[t.offset],n=0):(o=t.node,n=e?O(t.node):t.offset+1);return{node:o,offset:n}}function nt(t,e){var o,n=0;if(j(t.node))return null===t.node?null:{node:o=t.node.nextSibling,offset:n=0};if(O(t.node)===t.offset){if(C(t.node))return null;o=t.node.parentNode,n=J(t.node)+1,C(o)&&(o=t.node.nextSibling,n=0)}else if(tt(t.node)){if(n=0,j(o=t.node.childNodes[t.offset]))return j(t.node.nextSibling)?null:{node:t.node.nextSibling,offset:n}}else if(o=t.node,n=e?O(t.node):t.offset+1,j(o))return null;return{node:o,offset:n}}function it(t){if(t.nextSibling&&t.parent===t.nextSibling.parent)return S(t.nextSibling)?t.nextSibling:it(t.nextSibling)}function rt(t,e){return t.node===e.node&&t.offset===e.offset}function at(t,e){var o=e&&e.isSkipPaddingBlankHTML,n=e&&e.isNotSplitEdgePoint,i=e&&e.isDiscardEmptySplits;if(i&&(o=!0),Z(t)&&(S(t.node)||n)){if(G(t))return t.node;if(Y(t))return t.node.nextSibling}if(S(t.node))return t.node.splitText(t.offset);var r=t.node.childNodes[t.offset],a=q(t.node.cloneNode(!1),t.node);return _(a,V(r)),o||(U(t.node),U(a)),i&&(j(t.node)&&ct(t.node),j(a))?(ct(a),t.node.nextSibling):a}function st(t,e,o){var n=K(e.node,v.eq(t));return n.length?1===n.length?at(e,o):n.reduce((function(t,n){return t===e.node&&(t=at(e,o)),at({node:n,offset:t?J(t):O(n)},o)})):null}function lt(t){return document.createElement(t)}function ct(t,e){if(t&&t.parentNode){if(t.removeNode)return t.removeNode(e);var o=t.parentNode;if(!e){for(var n=[],i=0,r=t.childNodes.length;i<r;i++)n.push(t.childNodes[i]);for(var a=0,s=n.length;a<s;a++)o.insertBefore(n[a],t)}o.removeChild(t)}}var ut=x("TEXTAREA");function dt(t,e){var o=ut(t[0])?t.val():t.html();return e?o.replace(/[\n\r]/g,""):o}const ht={NBSP_CHAR:w,ZERO_WIDTH_NBSP_CHAR:"\ufeff",blank:M,emptyPara:"<p>".concat(M,"</p>"),makePredByNodeName:x,isEditable:C,isControlSizing:function(t){return t&&e()(t).hasClass("note-control-sizing")},isText:S,isElement:function(t){return t&&1===t.nodeType},isVoid:T,isPara:E,isPurePara:function(t){return E(t)&&!N(t)},isHeading:function(t){return t&&/^H[1-7]/.test(t.nodeName.toUpperCase())},isInline:R,isBlock:v.not(R),isBodyInline:function(t){return R(t)&&!W(t,E)},isBody:z,isParaInline:function(t){return R(t)&&!!W(t,E)},isPre:$,isList:L,isTable:I,isData:P,isCell:F,isBlockquote:D,isBodyContainer:H,isAnchor:B,isDiv:x("DIV"),isLi:N,isBR:x("BR"),isSpan:x("SPAN"),isB:x("B"),isU:x("U"),isS:x("S"),isI:x("I"),isImg:x("IMG"),isTextarea:ut,deepestChildIsEmpty:function(t){do{if(null===t.firstElementChild||""===t.firstElementChild.innerHTML)break}while(t=t.firstElementChild);return j(t)},isEmpty:j,isEmptyAnchor:v.and(B,j),isClosestSibling:function(t,e){return t.nextSibling===e||t.previousSibling===e},withClosestSiblings:function(t,e){e=e||v.ok;var o=[];return t.previousSibling&&e(t.previousSibling)&&o.push(t.previousSibling),o.push(t),t.nextSibling&&e(t.nextSibling)&&o.push(t.nextSibling),o},nodeLength:O,isLeftEdgePoint:G,isRightEdgePoint:Y,isEdgePoint:Z,isLeftEdgeOf:X,isRightEdgeOf:Q,isLeftEdgePointOf:function(t,e){return G(t)&&X(t.node,e)},isRightEdgePointOf:function(t,e){return Y(t)&&Q(t.node,e)},prevPoint:et,nextPoint:ot,nextPointWithEmptyNode:nt,isSamePoint:rt,isVisiblePoint:function(t){if(S(t.node)||!tt(t.node)||j(t.node))return!0;var e=t.node.childNodes[t.offset-1],o=t.node.childNodes[t.offset];return!((e&&!T(e)||o&&!T(o))&&!I(o))},prevPointUntil:function(t,e){for(;t;){if(e(t))return t;t=et(t)}return null},nextPointUntil:function(t,e){for(;t;){if(e(t))return t;t=ot(t)}return null},isCharPoint:function(t){if(!S(t.node))return!1;var e=t.node.nodeValue.charAt(t.offset-1);return e&&" "!==e&&e!==w},isSpacePoint:function(t){if(!S(t.node))return!1;var e=t.node.nodeValue.charAt(t.offset-1);return" "===e||e===w},walkPoint:function(t,e,o,n){for(var i=t;i&&(o(i),!rt(i,e));){i=nt(i,n&&t.node!==i.node&&e.node!==i.node)}},ancestor:W,singleChildAncestor:function(t,e){for(t=t.parentNode;t&&1===O(t);){if(e(t))return t;if(C(t))break;t=t.parentNode}return null},listAncestor:K,lastAncestor:function(t,e){var o=K(t);return y.last(o.filter(e))},listNext:V,listPrev:function(t,e){e=e||v.fail;for(var o=[];t&&!e(t);)o.push(t),t=t.previousSibling;return o},listDescendant:function(t,e){var o=[];return e=e||v.ok,function n(i){t!==i&&e(i)&&o.push(i);for(var r=0,a=i.childNodes.length;r<a;r++)n(i.childNodes[r])}(t),o},commonAncestor:function(t,e){for(var o=K(t),n=e;n;n=n.parentNode)if(o.indexOf(n)>-1)return n;return null},wrap:function(t,o){var n=t.parentNode,i=e()("<"+o+">")[0];return n.insertBefore(i,t),i.appendChild(t),i},insertAfter:q,appendChildNodes:_,position:J,hasChildren:tt,makeOffsetPath:function(t,e){return K(e,v.eq(t)).map(J).reverse()},fromOffsetPath:function(t,e){for(var o=t,n=0,i=e.length;n<i;n++)o=o.childNodes.length<=e[n]?o.childNodes[o.childNodes.length-1]:o.childNodes[e[n]];return o},splitTree:st,splitPoint:function(t,e){var o,n,i=e?E:H,r=K(t.node,i),a=y.last(r)||t.node;i(a)?(o=r[r.length-2],n=a):n=(o=a).parentNode;var s=o&&st(o,t,{isSkipPaddingBlankHTML:e,isNotSplitEdgePoint:e});return s||n!==t.node||(s=t.node.childNodes[t.offset]),{rightNode:s,container:n}},create:lt,createText:function(t){return document.createTextNode(t)},remove:ct,removeWhile:function(t,e){for(;t&&!C(t)&&e(t);){var o=t.parentNode;ct(t),t=o}},replace:function(t,e){if(t.nodeName.toUpperCase()===e.toUpperCase())return t;var o=lt(e);return t.style.cssText&&(o.style.cssText=t.style.cssText),_(o,y.from(t.childNodes)),q(o,t),ct(t),o},html:function(t,e){var o=dt(t);if(e){o=(o=o.replace(/<(\/?)(\b(?!!)[^>\s]*)(.*?)(\s*\/?>)/g,(function(t,e,o){o=o.toUpperCase();var n=/^DIV|^TD|^TH|^P|^LI|^H[1-7]/.test(o)&&!!e,i=/^BLOCKQUOTE|^TABLE|^TBODY|^TR|^HR|^UL|^OL/.test(o);return t+(n||i?"\n":"")}))).trim()}return o},value:dt,posFromPlaceholder:function(t){var o=e()(t),n=o.offset(),i=o.outerHeight(!0);return{left:n.left,top:n.top+i}},attachEvents:function(t,e){Object.keys(e).forEach((function(o){t.on(o,e[o])}))},detachEvents:function(t,e){Object.keys(e).forEach((function(o){t.off(o,e[o])}))},isCustomStyleTag:function(t){return t&&!S(t)&&y.contains(t.classList,"note-styletag")}};function ft(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var pt=function(){function t(o,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$note=o,this.memos={},this.modules={},this.layoutInfo={},this.options=e().extend(!0,{},n),e().summernote.ui=e().summernote.ui_template(this.options),this.ui=e().summernote.ui,this.initialize()}var o,n,i;return o=t,n=[{key:"initialize",value:function(){return this.layoutInfo=this.ui.createLayout(this.$note),this._initialize(),this.$note.hide(),this}},{key:"destroy",value:function(){this._destroy(),this.$note.removeData("summernote"),this.ui.removeLayout(this.$note,this.layoutInfo)}},{key:"reset",value:function(){var t=this.isDisabled();this.code(ht.emptyPara),this._destroy(),this._initialize(),t&&this.disable()}},{key:"_initialize",value:function(){var t=this;this.options.id=v.uniqueId(e().now()),this.options.container=this.options.container||this.layoutInfo.editor;var o=e().extend({},this.options.buttons);Object.keys(o).forEach((function(e){t.memo("button."+e,o[e])}));var n=e().extend({},this.options.modules,e().summernote.plugins||{});Object.keys(n).forEach((function(e){t.module(e,n[e],!0)})),Object.keys(this.modules).forEach((function(e){t.initializeModule(e)}))}},{key:"_destroy",value:function(){var t=this;Object.keys(this.modules).reverse().forEach((function(e){t.removeModule(e)})),Object.keys(this.memos).forEach((function(e){t.removeMemo(e)})),this.triggerEvent("destroy",this)}},{key:"code",value:function(t){var e=this.invoke("codeview.isActivated");if(void 0===t)return this.invoke("codeview.sync"),e?this.layoutInfo.codable.val():this.layoutInfo.editable.html();e?this.invoke("codeview.sync",t):this.layoutInfo.editable.html(t),this.$note.val(t),this.triggerEvent("change",t,this.layoutInfo.editable)}},{key:"isDisabled",value:function(){return"false"===this.layoutInfo.editable.attr("contenteditable")}},{key:"enable",value:function(){this.layoutInfo.editable.attr("contenteditable",!0),this.invoke("toolbar.activate",!0),this.triggerEvent("disable",!1),this.options.editing=!0}},{key:"disable",value:function(){this.invoke("codeview.isActivated")&&this.invoke("codeview.deactivate"),this.layoutInfo.editable.attr("contenteditable",!1),this.options.editing=!1,this.invoke("toolbar.deactivate",!0),this.triggerEvent("disable",!0)}},{key:"triggerEvent",value:function(){var t=y.head(arguments),e=y.tail(y.from(arguments)),o=this.options.callbacks[v.namespaceToCamel(t,"on")];o&&o.apply(this.$note[0],e),this.$note.trigger("summernote."+t,e)}},{key:"initializeModule",value:function(t){var e=this.modules[t];e.shouldInitialize=e.shouldInitialize||v.ok,e.shouldInitialize()&&(e.initialize&&e.initialize(),e.events&&ht.attachEvents(this.$note,e.events))}},{key:"module",value:function(t,e,o){if(1===arguments.length)return this.modules[t];this.modules[t]=new e(this),o||this.initializeModule(t)}},{key:"removeModule",value:function(t){var e=this.modules[t];e.shouldInitialize()&&(e.events&&ht.detachEvents(this.$note,e.events),e.destroy&&e.destroy()),delete this.modules[t]}},{key:"memo",value:function(t,e){if(1===arguments.length)return this.memos[t];this.memos[t]=e}},{key:"removeMemo",value:function(t){this.memos[t]&&this.memos[t].destroy&&this.memos[t].destroy(),delete this.memos[t]}},{key:"createInvokeHandlerAndUpdateState",value:function(t,e){var o=this;return function(n){o.createInvokeHandler(t,e)(n),o.invoke("buttons.updateCurrentStyle")}}},{key:"createInvokeHandler",value:function(t,o){var n=this;return function(i){i.preventDefault();var r=e()(i.target);n.invoke(t,o||r.closest("[data-value]").data("value"),r)}}},{key:"invoke",value:function(){var t=y.head(arguments),e=y.tail(y.from(arguments)),o=t.split("."),n=o.length>1,i=n&&y.head(o),r=n?y.last(o):y.head(o),a=this.modules[i||"editor"];return!i&&this[r]?this[r].apply(this,e):a&&a[r]&&a.shouldInitialize()?a[r].apply(a,e):void 0}}],n&&ft(o.prototype,n),i&&ft(o,i),t}();function vt(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function mt(t,e){var o,n,i=t.parentElement(),r=document.body.createTextRange(),a=y.from(i.childNodes);for(o=0;o<a.length;o++)if(!ht.isText(a[o])){if(r.moveToElementText(a[o]),r.compareEndPoints("StartToStart",t)>=0)break;n=a[o]}if(0!==o&&ht.isText(a[o-1])){var s=document.body.createTextRange(),l=null;s.moveToElementText(n||i),s.collapse(!n),l=n?n.nextSibling:i.firstChild;var c=t.duplicate();c.setEndPoint("StartToStart",s);for(var u=c.text.replace(/[\r\n]/g,"").length;u>l.nodeValue.length&&l.nextSibling;)u-=l.nodeValue.length,l=l.nextSibling;l.nodeValue;e&&l.nextSibling&&ht.isText(l.nextSibling)&&u===l.nodeValue.length&&(u-=l.nodeValue.length,l=l.nextSibling),i=l,o=u}return{cont:i,offset:o}}function gt(t){var e=document.body.createTextRange(),o=function t(e,o){var n,i;if(ht.isText(e)){var r=ht.listPrev(e,v.not(ht.isText)),a=y.last(r).previousSibling;n=a||e.parentNode,o+=y.sum(y.tail(r),ht.nodeLength),i=!a}else{if(n=e.childNodes[o]||e,ht.isText(n))return t(n,0);o=0,i=!1}return{node:n,collapseToStart:i,offset:o}}(t.node,t.offset);return e.moveToElementText(o.node),e.collapse(o.collapseToStart),e.moveStart("character",o.offset),e}e().fn.extend({summernote:function(){var t=e().type(y.head(arguments)),o="string"===t,n="object"===t,i=e().extend({},e().summernote.options,n?y.head(arguments):{});i.langInfo=e().extend(!0,{},e().summernote.lang["en-US"],e().summernote.lang[i.lang]),i.icons=e().extend(!0,{},e().summernote.options.icons,i.icons),i.tooltip="auto"===i.tooltip?!f.isSupportTouch:i.tooltip,this.each((function(t,o){var n=e()(o);if(!n.data("summernote")){var r=new pt(n,i);n.data("summernote",r),n.data("summernote").triggerEvent("init",r.layoutInfo)}}));var r=this.first();if(r.length){var a=r.data("summernote");if(o)return a.invoke.apply(a,y.from(arguments));i.focus&&a.invoke("editor.focus")}return this}});var bt=function(){function t(e,o,n,i){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.sc=e,this.so=o,this.ec=n,this.eo=i,this.isOnEditable=this.makeIsOn(ht.isEditable),this.isOnList=this.makeIsOn(ht.isList),this.isOnAnchor=this.makeIsOn(ht.isAnchor),this.isOnCell=this.makeIsOn(ht.isCell),this.isOnData=this.makeIsOn(ht.isData)}var o,n,i;return o=t,n=[{key:"nativeRange",value:function(){if(f.isW3CRangeSupport){var t=document.createRange();return t.setStart(this.sc,this.so),t.setEnd(this.ec,this.eo),t}var e=gt({node:this.sc,offset:this.so});return e.setEndPoint("EndToEnd",gt({node:this.ec,offset:this.eo})),e}},{key:"getPoints",value:function(){return{sc:this.sc,so:this.so,ec:this.ec,eo:this.eo}}},{key:"getStartPoint",value:function(){return{node:this.sc,offset:this.so}}},{key:"getEndPoint",value:function(){return{node:this.ec,offset:this.eo}}},{key:"select",value:function(){var t=this.nativeRange();if(f.isW3CRangeSupport){var e=document.getSelection();e.rangeCount>0&&e.removeAllRanges(),e.addRange(t)}else t.select();return this}},{key:"scrollIntoView",value:function(t){var o=e()(t).height();return t.scrollTop+o<this.sc.offsetTop&&(t.scrollTop+=Math.abs(t.scrollTop+o-this.sc.offsetTop)),this}},{key:"normalize",value:function(){var e=function(t,e){if(!t)return t;if(ht.isVisiblePoint(t)&&(!ht.isEdgePoint(t)||ht.isRightEdgePoint(t)&&!e||ht.isLeftEdgePoint(t)&&e||ht.isRightEdgePoint(t)&&e&&ht.isVoid(t.node.nextSibling)||ht.isLeftEdgePoint(t)&&!e&&ht.isVoid(t.node.previousSibling)||ht.isBlock(t.node)&&ht.isEmpty(t.node)))return t;var o=ht.ancestor(t.node,ht.isBlock),n=!1;if(!n){var i=ht.prevPoint(t)||{node:null};n=(ht.isLeftEdgePointOf(t,o)||ht.isVoid(i.node))&&!e}var r=!1;if(!r){var a=ht.nextPoint(t)||{node:null};r=(ht.isRightEdgePointOf(t,o)||ht.isVoid(a.node))&&e}if(n||r){if(ht.isVisiblePoint(t))return t;e=!e}return(e?ht.nextPointUntil(ht.nextPoint(t),ht.isVisiblePoint):ht.prevPointUntil(ht.prevPoint(t),ht.isVisiblePoint))||t},o=e(this.getEndPoint(),!1),n=this.isCollapsed()?o:e(this.getStartPoint(),!0);return new t(n.node,n.offset,o.node,o.offset)}},{key:"nodes",value:function(t,e){t=t||v.ok;var o=e&&e.includeAncestor,n=e&&e.fullyContains,i=this.getStartPoint(),r=this.getEndPoint(),a=[],s=[];return ht.walkPoint(i,r,(function(e){var i;ht.isEditable(e.node)||(n?(ht.isLeftEdgePoint(e)&&s.push(e.node),ht.isRightEdgePoint(e)&&y.contains(s,e.node)&&(i=e.node)):i=o?ht.ancestor(e.node,t):e.node,i&&t(i)&&a.push(i))}),!0),y.unique(a)}},{key:"commonAncestor",value:function(){return ht.commonAncestor(this.sc,this.ec)}},{key:"expand",value:function(e){var o=ht.ancestor(this.sc,e),n=ht.ancestor(this.ec,e);if(!o&&!n)return new t(this.sc,this.so,this.ec,this.eo);var i=this.getPoints();return o&&(i.sc=o,i.so=0),n&&(i.ec=n,i.eo=ht.nodeLength(n)),new t(i.sc,i.so,i.ec,i.eo)}},{key:"collapse",value:function(e){return e?new t(this.sc,this.so,this.sc,this.so):new t(this.ec,this.eo,this.ec,this.eo)}},{key:"splitText",value:function(){var e=this.sc===this.ec,o=this.getPoints();return ht.isText(this.ec)&&!ht.isEdgePoint(this.getEndPoint())&&this.ec.splitText(this.eo),ht.isText(this.sc)&&!ht.isEdgePoint(this.getStartPoint())&&(o.sc=this.sc.splitText(this.so),o.so=0,e&&(o.ec=o.sc,o.eo=this.eo-this.so)),new t(o.sc,o.so,o.ec,o.eo)}},{key:"deleteContents",value:function(){if(this.isCollapsed())return this;var o=this.splitText(),n=o.nodes(null,{fullyContains:!0}),i=ht.prevPointUntil(o.getStartPoint(),(function(t){return!y.contains(n,t.node)})),r=[];return e().each(n,(function(t,e){var o=e.parentNode;i.node!==o&&1===ht.nodeLength(o)&&r.push(o),ht.remove(e,!1)})),e().each(r,(function(t,e){ht.remove(e,!1)})),new t(i.node,i.offset,i.node,i.offset).normalize()}},{key:"makeIsOn",value:function(t){return function(){var e=ht.ancestor(this.sc,t);return!!e&&e===ht.ancestor(this.ec,t)}}},{key:"isLeftEdgeOf",value:function(t){if(!ht.isLeftEdgePoint(this.getStartPoint()))return!1;var e=ht.ancestor(this.sc,t);return e&&ht.isLeftEdgeOf(this.sc,e)}},{key:"isCollapsed",value:function(){return this.sc===this.ec&&this.so===this.eo}},{key:"wrapBodyInlineWithPara",value:function(){if(ht.isBodyContainer(this.sc)&&ht.isEmpty(this.sc))return this.sc.innerHTML=ht.emptyPara,new t(this.sc.firstChild,0,this.sc.firstChild,0);var e,o=this.normalize();if(ht.isParaInline(this.sc)||ht.isPara(this.sc))return o;if(ht.isInline(o.sc)){var n=ht.listAncestor(o.sc,v.not(ht.isInline));e=y.last(n),ht.isInline(e)||(e=n[n.length-2]||o.sc.childNodes[o.so])}else e=o.sc.childNodes[o.so>0?o.so-1:0];if(e){var i=ht.listPrev(e,ht.isParaInline).reverse();if((i=i.concat(ht.listNext(e.nextSibling,ht.isParaInline))).length){var r=ht.wrap(y.head(i),"p");ht.appendChildNodes(r,y.tail(i))}}return this.normalize()}},{key:"insertNode",value:function(t){var e=this;(ht.isText(t)||ht.isInline(t))&&(e=this.wrapBodyInlineWithPara().deleteContents());var o=ht.splitPoint(e.getStartPoint(),ht.isInline(t));return o.rightNode?(o.rightNode.parentNode.insertBefore(t,o.rightNode),ht.isEmpty(o.rightNode)&&ht.isPara(t)&&o.rightNode.parentNode.removeChild(o.rightNode)):o.container.appendChild(t),t}},{key:"pasteHTML",value:function(t){t=e().trim(t);var o=e()("<div></div>").html(t)[0],n=y.from(o.childNodes),i=this,r=!1;return i.so>=0&&(n=n.reverse(),r=!0),n=n.map((function(t){return i.insertNode(t)})),r&&(n=n.reverse()),n}},{key:"toString",value:function(){var t=this.nativeRange();return f.isW3CRangeSupport?t.toString():t.text}},{key:"getWordRange",value:function(e){var o=this.getEndPoint();if(!ht.isCharPoint(o))return this;var n=ht.prevPointUntil(o,(function(t){return!ht.isCharPoint(t)}));return e&&(o=ht.nextPointUntil(o,(function(t){return!ht.isCharPoint(t)}))),new t(n.node,n.offset,o.node,o.offset)}},{key:"getWordsRange",value:function(e){var o=this.getEndPoint(),n=function(t){return!ht.isCharPoint(t)&&!ht.isSpacePoint(t)};if(n(o))return this;var i=ht.prevPointUntil(o,n);return e&&(o=ht.nextPointUntil(o,n)),new t(i.node,i.offset,o.node,o.offset)}},{key:"getWordsMatchRange",value:function(e){var o=this.getEndPoint(),n=ht.prevPointUntil(o,(function(n){if(!ht.isCharPoint(n)&&!ht.isSpacePoint(n))return!0;var i=new t(n.node,n.offset,o.node,o.offset),r=e.exec(i.toString());return r&&0===r.index})),i=new t(n.node,n.offset,o.node,o.offset),r=i.toString(),a=e.exec(r);return a&&a[0].length===r.length?i:null}},{key:"bookmark",value:function(t){return{s:{path:ht.makeOffsetPath(t,this.sc),offset:this.so},e:{path:ht.makeOffsetPath(t,this.ec),offset:this.eo}}}},{key:"paraBookmark",value:function(t){return{s:{path:y.tail(ht.makeOffsetPath(y.head(t),this.sc)),offset:this.so},e:{path:y.tail(ht.makeOffsetPath(y.last(t),this.ec)),offset:this.eo}}}},{key:"getClientRects",value:function(){return this.nativeRange().getClientRects()}}],n&&vt(o.prototype,n),i&&vt(o,i),t}();const kt={create:function(t,e,o,n){if(4===arguments.length)return new bt(t,e,o,n);if(2===arguments.length)return new bt(t,e,o=t,n=e);var i=this.createFromSelection();if(!i&&1===arguments.length){var r=arguments[0];return ht.isEditable(r)&&(r=r.lastChild),this.createFromBodyElement(r,ht.emptyPara===arguments[0].innerHTML)}return i},createFromBodyElement:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=this.createFromNode(t);return o.collapse(e)},createFromSelection:function(){var t,e,o,n;if(f.isW3CRangeSupport){var i=document.getSelection();if(!i||0===i.rangeCount)return null;if(ht.isBody(i.anchorNode))return null;var r=i.getRangeAt(0);t=r.startContainer,e=r.startOffset,o=r.endContainer,n=r.endOffset}else{var a=document.selection.createRange(),s=a.duplicate();s.collapse(!1);var l=a;l.collapse(!0);var c=mt(l,!0),u=mt(s,!1);ht.isText(c.node)&&ht.isLeftEdgePoint(c)&&ht.isTextNode(u.node)&&ht.isRightEdgePoint(u)&&u.node.nextSibling===c.node&&(c=u),t=c.cont,e=c.offset,o=u.cont,n=u.offset}return new bt(t,e,o,n)},createFromNode:function(t){var e=t,o=0,n=t,i=ht.nodeLength(n);return ht.isVoid(e)&&(o=ht.listPrev(e).length-1,e=e.parentNode),ht.isBR(n)?(i=ht.listPrev(n).length-1,n=n.parentNode):ht.isVoid(n)&&(i=ht.listPrev(n).length,n=n.parentNode),this.create(e,o,n,i)},createFromNodeBefore:function(t){return this.createFromNode(t).collapse(!0)},createFromNodeAfter:function(t){return this.createFromNode(t).collapse()},createFromBookmark:function(t,e){var o=ht.fromOffsetPath(t,e.s.path),n=e.s.offset,i=ht.fromOffsetPath(t,e.e.path),r=e.e.offset;return new bt(o,n,i,r)},createFromParaBookmark:function(t,e){var o=t.s.offset,n=t.e.offset,i=ht.fromOffsetPath(y.head(e),t.s.path),r=ht.fromOffsetPath(y.last(e),t.e.path);return new bt(i,o,r,n)}};var yt={BACKSPACE:8,TAB:9,ENTER:13,ESCAPE:27,SPACE:32,DELETE:46,LEFT:37,UP:38,RIGHT:39,DOWN:40,NUM0:48,NUM1:49,NUM2:50,NUM3:51,NUM4:52,NUM5:53,NUM6:54,NUM7:55,NUM8:56,B:66,E:69,I:73,J:74,K:75,L:76,R:82,S:83,U:85,V:86,Y:89,Z:90,SLASH:191,LEFTBRACKET:219,BACKSLASH:220,RIGHTBRACKET:221,HOME:36,END:35,PAGEUP:33,PAGEDOWN:34};const wt={isEdit:function(t){return y.contains([yt.BACKSPACE,yt.TAB,yt.ENTER,yt.SPACE,yt.DELETE],t)},isMove:function(t){return y.contains([yt.LEFT,yt.UP,yt.RIGHT,yt.DOWN],t)},isNavigation:function(t){return y.contains([yt.HOME,yt.END,yt.PAGEUP,yt.PAGEDOWN],t)},nameFromCode:v.invertObject(yt),code:yt};function Ct(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var xt=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.stack=[],this.stackOffset=-1,this.context=e,this.$editable=e.layoutInfo.editable,this.editable=this.$editable[0]}var e,o,n;return e=t,(o=[{key:"makeSnapshot",value:function(){var t=kt.create(this.editable);return{contents:this.$editable.html(),bookmark:t&&t.isOnEditable()?t.bookmark(this.editable):{s:{path:[],offset:0},e:{path:[],offset:0}}}}},{key:"applySnapshot",value:function(t){null!==t.contents&&this.$editable.html(t.contents),null!==t.bookmark&&kt.createFromBookmark(this.editable,t.bookmark).select()}},{key:"rewind",value:function(){this.$editable.html()!==this.stack[this.stackOffset].contents&&this.recordUndo(),this.stackOffset=0,this.applySnapshot(this.stack[this.stackOffset])}},{key:"commit",value:function(){this.stack=[],this.stackOffset=-1,this.recordUndo()}},{key:"reset",value:function(){this.stack=[],this.stackOffset=-1,this.$editable.html(""),this.recordUndo()}},{key:"undo",value:function(){this.$editable.html()!==this.stack[this.stackOffset].contents&&this.recordUndo(),this.stackOffset>0&&(this.stackOffset--,this.applySnapshot(this.stack[this.stackOffset]))}},{key:"redo",value:function(){this.stack.length-1>this.stackOffset&&(this.stackOffset++,this.applySnapshot(this.stack[this.stackOffset]))}},{key:"recordUndo",value:function(){this.stackOffset++,this.stack.length>this.stackOffset&&(this.stack=this.stack.slice(0,this.stackOffset)),this.stack.push(this.makeSnapshot()),this.stack.length>this.context.options.historyLimit&&(this.stack.shift(),this.stackOffset-=1)}}])&&Ct(e.prototype,o),n&&Ct(e,n),t}();function St(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var Tt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var o,n,i;return o=t,n=[{key:"jQueryCSS",value:function(t,o){var n={};return e().each(o,(function(e,o){n[o]=t.css(o)})),n}},{key:"fromNode",value:function(t){var e=this.jQueryCSS(t,["font-family","font-size","text-align","list-style-type","line-height"])||{},o=t[0].style.fontSize||e["font-size"];return e["font-size"]=parseInt(o,10),e["font-size-unit"]=o.match(/[a-z%]+$/),e}},{key:"stylePara",value:function(t,o){e().each(t.nodes(ht.isPara,{includeAncestor:!0}),(function(t,n){e()(n).css(o)}))}},{key:"styleNodes",value:function(t,o){t=t.splitText();var n=o&&o.nodeName||"SPAN",i=!(!o||!o.expandClosestSibling),r=!(!o||!o.onlyPartialContains);if(t.isCollapsed())return[t.insertNode(ht.create(n))];var a=ht.makePredByNodeName(n),s=t.nodes(ht.isText,{fullyContains:!0}).map((function(t){return ht.singleChildAncestor(t,a)||ht.wrap(t,n)}));if(i){if(r){var l=t.nodes();a=v.and(a,(function(t){return y.contains(l,t)}))}return s.map((function(t){var o=ht.withClosestSiblings(t,a),n=y.head(o),i=y.tail(o);return e().each(i,(function(t,e){ht.appendChildNodes(n,e.childNodes),ht.remove(e)})),y.head(o)}))}return s}},{key:"current",value:function(t){var o=e()(ht.isElement(t.sc)?t.sc:t.sc.parentNode),n=this.fromNode(o);try{n=e().extend(n,{"font-bold":document.queryCommandState("bold")?"bold":"normal","font-italic":document.queryCommandState("italic")?"italic":"normal","font-underline":document.queryCommandState("underline")?"underline":"normal","font-subscript":document.queryCommandState("subscript")?"subscript":"normal","font-superscript":document.queryCommandState("superscript")?"superscript":"normal","font-strikethrough":document.queryCommandState("strikethrough")?"strikethrough":"normal","font-family":document.queryCommandValue("fontname")||n["font-family"]})}catch(t){}if(t.isOnList()){var i=["circle","disc","disc-leading-zero","square"].indexOf(n["list-style-type"])>-1;n["list-style"]=i?"unordered":"ordered"}else n["list-style"]="none";var r=ht.ancestor(t.sc,ht.isPara);if(r&&r.style["line-height"])n["line-height"]=r.style.lineHeight;else{var a=parseInt(n["line-height"],10)/parseInt(n["font-size"],10);n["line-height"]=a.toFixed(1)}return n.anchor=t.isOnAnchor()&&ht.ancestor(t.sc,ht.isAnchor),n.ancestors=ht.listAncestor(t.sc,ht.isEditable),n.range=t,n}}],n&&St(o.prototype,n),i&&St(o,i),t}();function Et(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var $t=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var o,n,i;return o=t,n=[{key:"insertOrderedList",value:function(t){this.toggleList("OL",t)}},{key:"insertUnorderedList",value:function(t){this.toggleList("UL",t)}},{key:"indent",value:function(t){var o=this,n=kt.create(t).wrapBodyInlineWithPara(),i=n.nodes(ht.isPara,{includeAncestor:!0}),r=y.clusterBy(i,v.peq2("parentNode"));e().each(r,(function(t,n){var i=y.head(n);if(ht.isLi(i)){var r=o.findList(i.previousSibling);r?n.map((function(t){return r.appendChild(t)})):(o.wrapList(n,i.parentNode.nodeName),n.map((function(t){return t.parentNode})).map((function(t){return o.appendToPrevious(t)})))}else e().each(n,(function(t,o){e()(o).css("marginLeft",(function(t,e){return(parseInt(e,10)||0)+25}))}))})),n.select()}},{key:"outdent",value:function(t){var o=this,n=kt.create(t).wrapBodyInlineWithPara(),i=n.nodes(ht.isPara,{includeAncestor:!0}),r=y.clusterBy(i,v.peq2("parentNode"));e().each(r,(function(t,n){var i=y.head(n);ht.isLi(i)?o.releaseList([n]):e().each(n,(function(t,o){e()(o).css("marginLeft",(function(t,e){return(e=parseInt(e,10)||0)>25?e-25:""}))}))})),n.select()}},{key:"toggleList",value:function(t,o){var n=this,i=kt.create(o).wrapBodyInlineWithPara(),r=i.nodes(ht.isPara,{includeAncestor:!0}),a=i.paraBookmark(r),s=y.clusterBy(r,v.peq2("parentNode"));if(y.find(r,ht.isPurePara)){var l=[];e().each(s,(function(e,o){l=l.concat(n.wrapList(o,t))})),r=l}else{var c=i.nodes(ht.isList,{includeAncestor:!0}).filter((function(o){return!e().nodeName(o,t)}));c.length?e().each(c,(function(e,o){ht.replace(o,t)})):r=this.releaseList(s,!0)}kt.createFromParaBookmark(a,r).select()}},{key:"wrapList",value:function(t,e){var o=y.head(t),n=y.last(t),i=ht.isList(o.previousSibling)&&o.previousSibling,r=ht.isList(n.nextSibling)&&n.nextSibling,a=i||ht.insertAfter(ht.create(e||"UL"),n);return t=t.map((function(t){return ht.isPurePara(t)?ht.replace(t,"LI"):t})),ht.appendChildNodes(a,t),r&&(ht.appendChildNodes(a,y.from(r.childNodes)),ht.remove(r)),t}},{key:"releaseList",value:function(t,o){var n=this,i=[];return e().each(t,(function(t,r){var a=y.head(r),s=y.last(r),l=o?ht.lastAncestor(a,ht.isList):a.parentNode,c=l.parentNode;if("LI"===l.parentNode.nodeName)r.map((function(t){var e=n.findNextSiblings(t);c.nextSibling?c.parentNode.insertBefore(t,c.nextSibling):c.parentNode.appendChild(t),e.length&&(n.wrapList(e,l.nodeName),t.appendChild(e[0].parentNode))})),0===l.children.length&&c.removeChild(l),0===c.childNodes.length&&c.parentNode.removeChild(c);else{var u=l.childNodes.length>1?ht.splitTree(l,{node:s.parentNode,offset:ht.position(s)+1},{isSkipPaddingBlankHTML:!0}):null,d=ht.splitTree(l,{node:a.parentNode,offset:ht.position(a)},{isSkipPaddingBlankHTML:!0});r=o?ht.listDescendant(d,ht.isLi):y.from(d.childNodes).filter(ht.isLi),!o&&ht.isList(l.parentNode)||(r=r.map((function(t){return ht.replace(t,"P")}))),e().each(y.from(r).reverse(),(function(t,e){ht.insertAfter(e,l)}));var h=y.compact([l,d,u]);e().each(h,(function(t,o){var n=[o].concat(ht.listDescendant(o,ht.isList));e().each(n.reverse(),(function(t,e){ht.nodeLength(e)||ht.remove(e,!0)}))}))}i=i.concat(r)})),i}},{key:"appendToPrevious",value:function(t){return t.previousSibling?ht.appendChildNodes(t.previousSibling,[t]):this.wrapList([t],"LI")}},{key:"findList",value:function(t){return t?y.find(t.children,(function(t){return["OL","UL"].indexOf(t.nodeName)>-1})):null}},{key:"findNextSiblings",value:function(t){for(var e=[];t.nextSibling;)e.push(t.nextSibling),t=t.nextSibling;return e}}],n&&Et(o.prototype,n),i&&Et(o,i),t}();function Nt(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var It=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.bullet=new $t,this.options=e.options}var o,n,i;return o=t,n=[{key:"insertTab",value:function(t,e){var o=ht.createText(new Array(e+1).join(ht.NBSP_CHAR));(t=t.deleteContents()).insertNode(o,!0),(t=kt.create(o,e)).select()}},{key:"insertParagraph",value:function(t,o){o=(o=(o=o||kt.create(t)).deleteContents()).wrapBodyInlineWithPara();var n,i=ht.ancestor(o.sc,ht.isPara);if(i){if(ht.isLi(i)&&(ht.isEmpty(i)||ht.deepestChildIsEmpty(i)))return void this.bullet.toggleList(i.parentNode.nodeName);var r=null;if(1===this.options.blockquoteBreakingLevel?r=ht.ancestor(i,ht.isBlockquote):2===this.options.blockquoteBreakingLevel&&(r=ht.lastAncestor(i,ht.isBlockquote)),r){n=e()(ht.emptyPara)[0],ht.isRightEdgePoint(o.getStartPoint())&&ht.isBR(o.sc.nextSibling)&&e()(o.sc.nextSibling).remove();var a=ht.splitTree(r,o.getStartPoint(),{isDiscardEmptySplits:!0});a?a.parentNode.insertBefore(n,a):ht.insertAfter(n,r)}else{n=ht.splitTree(i,o.getStartPoint());var s=ht.listDescendant(i,ht.isEmptyAnchor);s=s.concat(ht.listDescendant(n,ht.isEmptyAnchor)),e().each(s,(function(t,e){ht.remove(e)})),(ht.isHeading(n)||ht.isPre(n)||ht.isCustomStyleTag(n))&&ht.isEmpty(n)&&(n=ht.replace(n,"p"))}}else{var l=o.sc.childNodes[o.so];n=e()(ht.emptyPara)[0],l?o.sc.insertBefore(n,l):o.sc.appendChild(n)}kt.create(n,0).normalize().select().scrollIntoView(t)}}],n&&Nt(o.prototype,n),i&&Nt(o,i),t}();function Pt(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var Rt=function t(e,o,n,i){var r={colPos:0,rowPos:0},a=[],s=[];function l(t,e,o,n,i,r,s){var l={baseRow:o,baseCell:n,isRowSpan:i,isColSpan:r,isVirtual:s};a[t]||(a[t]=[]),a[t][e]=l}function c(t,e,o,n){return{baseCell:t.baseCell,action:e,virtualTable:{rowIndex:o,cellIndex:n}}}function u(t,e){if(!a[t])return e;if(!a[t][e])return e;for(var o=e;a[t][o];)if(o++,!a[t][o])return o}function d(t,e){var o=u(t.rowIndex,e.cellIndex),n=e.colSpan>1,i=e.rowSpan>1,a=t.rowIndex===r.rowPos&&e.cellIndex===r.colPos;l(t.rowIndex,o,t,e,i,n,!1);var s=e.attributes.rowSpan?parseInt(e.attributes.rowSpan.value,10):0;if(s>1)for(var c=1;c<s;c++){var d=t.rowIndex+c;h(d,o,e,a),l(d,o,t,e,!0,n,!0)}var f=e.attributes.colSpan?parseInt(e.attributes.colSpan.value,10):0;if(f>1)for(var p=1;p<f;p++){var v=u(t.rowIndex,o+p);h(t.rowIndex,v,e,a),l(t.rowIndex,v,t,e,i,!0,!0)}}function h(t,e,o,n){t===r.rowPos&&r.colPos>=o.cellIndex&&o.cellIndex<=e&&!n&&r.colPos++}function f(e){switch(o){case t.where.Column:if(e.isColSpan)return t.resultAction.SubtractSpanCount;break;case t.where.Row:if(!e.isVirtual&&e.isRowSpan)return t.resultAction.AddCell;if(e.isRowSpan)return t.resultAction.SubtractSpanCount}return t.resultAction.RemoveCell}function p(e){switch(o){case t.where.Column:if(e.isColSpan)return t.resultAction.SumSpanCount;if(e.isRowSpan&&e.isVirtual)return t.resultAction.Ignore;break;case t.where.Row:if(e.isRowSpan)return t.resultAction.SumSpanCount;if(e.isColSpan&&e.isVirtual)return t.resultAction.Ignore}return t.resultAction.AddCell}this.getActionList=function(){for(var e=o===t.where.Row?r.rowPos:-1,i=o===t.where.Column?r.colPos:-1,l=0,u=!0;u;){var d=e>=0?e:l,h=i>=0?i:l,v=a[d];if(!v)return u=!1,s;var m=v[h];if(!m)return u=!1,s;var g=t.resultAction.Ignore;switch(n){case t.requestAction.Add:g=p(m);break;case t.requestAction.Delete:g=f(m)}s.push(c(m,g,d,h)),l++}return s},e&&e.tagName&&("td"===e.tagName.toLowerCase()||"th"===e.tagName.toLowerCase())&&(r.colPos=e.cellIndex,e.parentElement&&e.parentElement.tagName&&"tr"===e.parentElement.tagName.toLowerCase()&&(r.rowPos=e.parentElement.rowIndex)),function(){for(var t=i.rows,e=0;e<t.length;e++)for(var o=t[e].cells,n=0;n<o.length;n++)d(t[e],o[n])}()};Rt.where={Row:0,Column:1},Rt.requestAction={Add:0,Delete:1},Rt.resultAction={Ignore:0,SubtractSpanCount:1,RemoveCell:2,AddCell:3,SumSpanCount:4};var Lt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}var o,n,i;return o=t,n=[{key:"tab",value:function(t,e){var o=ht.ancestor(t.commonAncestor(),ht.isCell),n=ht.ancestor(o,ht.isTable),i=ht.listDescendant(n,ht.isCell),r=y[e?"prev":"next"](i,o);r&&kt.create(r,0).select()}},{key:"addRow",value:function(t,o){for(var n=ht.ancestor(t.commonAncestor(),ht.isCell),i=e()(n).closest("tr"),r=this.recoverAttributes(i),a=e()("<tr"+r+"></tr>"),s=new Rt(n,Rt.where.Row,Rt.requestAction.Add,e()(i).closest("table")[0]).getActionList(),l=0;l<s.length;l++){var c=s[l],u=this.recoverAttributes(c.baseCell);switch(c.action){case Rt.resultAction.AddCell:a.append("<td"+u+">"+ht.blank+"</td>");break;case Rt.resultAction.SumSpanCount:if("top"===o&&(c.baseCell.parent?c.baseCell.closest("tr").rowIndex:0)<=i[0].rowIndex){var d=e()("<div></div>").append(e()("<td"+u+">"+ht.blank+"</td>").removeAttr("rowspan")).html();a.append(d);break}var h=parseInt(c.baseCell.rowSpan,10);h++,c.baseCell.setAttribute("rowSpan",h)}}if("top"===o)i.before(a);else{if(n.rowSpan>1){var f=i[0].rowIndex+(n.rowSpan-2);return void e()(e()(i).parent().find("tr")[f]).after(e()(a))}i.after(a)}}},{key:"addCol",value:function(t,o){var n=ht.ancestor(t.commonAncestor(),ht.isCell),i=e()(n).closest("tr");e()(i).siblings().push(i);for(var r=new Rt(n,Rt.where.Column,Rt.requestAction.Add,e()(i).closest("table")[0]).getActionList(),a=0;a<r.length;a++){var s=r[a],l=this.recoverAttributes(s.baseCell);switch(s.action){case Rt.resultAction.AddCell:"right"===o?e()(s.baseCell).after("<td"+l+">"+ht.blank+"</td>"):e()(s.baseCell).before("<td"+l+">"+ht.blank+"</td>");break;case Rt.resultAction.SumSpanCount:if("right"===o){var c=parseInt(s.baseCell.colSpan,10);c++,s.baseCell.setAttribute("colSpan",c)}else e()(s.baseCell).before("<td"+l+">"+ht.blank+"</td>")}}}},{key:"recoverAttributes",value:function(t){var e="";if(!t)return e;for(var o=t.attributes||[],n=0;n<o.length;n++)"id"!==o[n].name.toLowerCase()&&o[n].specified&&(e+=" "+o[n].name+"='"+o[n].value+"'");return e}},{key:"deleteRow",value:function(t){for(var o=ht.ancestor(t.commonAncestor(),ht.isCell),n=e()(o).closest("tr"),i=n.children("td, th").index(e()(o)),r=n[0].rowIndex,a=new Rt(o,Rt.where.Row,Rt.requestAction.Delete,e()(n).closest("table")[0]).getActionList(),s=0;s<a.length;s++)if(a[s]){var l=a[s].baseCell,c=a[s].virtualTable,u=l.rowSpan&&l.rowSpan>1,d=u?parseInt(l.rowSpan,10):0;switch(a[s].action){case Rt.resultAction.Ignore:continue;case Rt.resultAction.AddCell:var h=n.next("tr")[0];if(!h)continue;var f=n[0].cells[i];u&&(d>2?(d--,h.insertBefore(f,h.cells[i]),h.cells[i].setAttribute("rowSpan",d),h.cells[i].innerHTML=""):2===d&&(h.insertBefore(f,h.cells[i]),h.cells[i].removeAttribute("rowSpan"),h.cells[i].innerHTML=""));continue;case Rt.resultAction.SubtractSpanCount:u&&(d>2?(d--,l.setAttribute("rowSpan",d),c.rowIndex!==r&&l.cellIndex===i&&(l.innerHTML="")):2===d&&(l.removeAttribute("rowSpan"),c.rowIndex!==r&&l.cellIndex===i&&(l.innerHTML="")));continue;case Rt.resultAction.RemoveCell:continue}}n.remove()}},{key:"deleteCol",value:function(t){for(var o=ht.ancestor(t.commonAncestor(),ht.isCell),n=e()(o).closest("tr"),i=n.children("td, th").index(e()(o)),r=new Rt(o,Rt.where.Column,Rt.requestAction.Delete,e()(n).closest("table")[0]).getActionList(),a=0;a<r.length;a++)if(r[a])switch(r[a].action){case Rt.resultAction.Ignore:continue;case Rt.resultAction.SubtractSpanCount:var s=r[a].baseCell;if(s.colSpan&&s.colSpan>1){var l=s.colSpan?parseInt(s.colSpan,10):0;l>2?(l--,s.setAttribute("colSpan",l),s.cellIndex===i&&(s.innerHTML="")):2===l&&(s.removeAttribute("colSpan"),s.cellIndex===i&&(s.innerHTML=""))}continue;case Rt.resultAction.RemoveCell:ht.remove(r[a].baseCell,!0);continue}}},{key:"createTable",value:function(t,o,n){for(var i,r=[],a=0;a<t;a++)r.push("<td>"+ht.blank+"</td>");i=r.join("");for(var s,l=[],c=0;c<o;c++)l.push("<tr>"+i+"</tr>");s=l.join("");var u=e()("<table>"+s+"</table>");return n&&n.tableClassName&&u.addClass(n.tableClassName),u[0]}},{key:"deleteTable",value:function(t){var o=ht.ancestor(t.commonAncestor(),ht.isCell);e()(o).closest("table").remove()}}],n&&Pt(o.prototype,n),i&&Pt(o,i),t}();function At(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var Ft=function(){function t(o){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.$note=o.layoutInfo.note,this.$editor=o.layoutInfo.editor,this.$editable=o.layoutInfo.editable,this.options=o.options,this.lang=this.options.langInfo,this.editable=this.$editable[0],this.lastRange=null,this.snapshot=null,this.style=new Tt,this.table=new Lt,this.typing=new It(o),this.bullet=new $t,this.history=new xt(o),this.context.memo("help.escape",this.lang.help.escape),this.context.memo("help.undo",this.lang.help.undo),this.context.memo("help.redo",this.lang.help.redo),this.context.memo("help.tab",this.lang.help.tab),this.context.memo("help.untab",this.lang.help.untab),this.context.memo("help.insertParagraph",this.lang.help.insertParagraph),this.context.memo("help.insertOrderedList",this.lang.help.insertOrderedList),this.context.memo("help.insertUnorderedList",this.lang.help.insertUnorderedList),this.context.memo("help.indent",this.lang.help.indent),this.context.memo("help.outdent",this.lang.help.outdent),this.context.memo("help.formatPara",this.lang.help.formatPara),this.context.memo("help.insertHorizontalRule",this.lang.help.insertHorizontalRule),this.context.memo("help.fontName",this.lang.help.fontName);for(var i=["bold","italic","underline","strikethrough","superscript","subscript","justifyLeft","justifyCenter","justifyRight","justifyFull","formatBlock","removeFormat","backColor"],r=0,a=i.length;r<a;r++)this[i[r]]=function(t){return function(e){n.beforeCommand(),document.execCommand(t,!1,e),n.afterCommand(!0)}}(i[r]),this.context.memo("help."+i[r],this.lang.help[i[r]]);this.fontName=this.wrapCommand((function(t){return n.fontStyling("font-family",f.validFontName(t))})),this.fontSize=this.wrapCommand((function(t){var e=n.currentStyle()["font-size-unit"];return n.fontStyling("font-size",t+e)})),this.fontSizeUnit=this.wrapCommand((function(t){var e=n.currentStyle()["font-size"];return n.fontStyling("font-size",e+t)}));for(var s=1;s<=6;s++)this["formatH"+s]=function(t){return function(){n.formatBlock("H"+t)}}(s),this.context.memo("help.formatH"+s,this.lang.help["formatH"+s]);this.insertParagraph=this.wrapCommand((function(){n.typing.insertParagraph(n.editable)})),this.insertOrderedList=this.wrapCommand((function(){n.bullet.insertOrderedList(n.editable)})),this.insertUnorderedList=this.wrapCommand((function(){n.bullet.insertUnorderedList(n.editable)})),this.indent=this.wrapCommand((function(){n.bullet.indent(n.editable)})),this.outdent=this.wrapCommand((function(){n.bullet.outdent(n.editable)})),this.insertNode=this.wrapCommand((function(t){n.isLimited(e()(t).text().length)||(n.getLastRange().insertNode(t),n.setLastRange(kt.createFromNodeAfter(t).select()))})),this.insertText=this.wrapCommand((function(t){if(!n.isLimited(t.length)){var e=n.getLastRange().insertNode(ht.createText(t));n.setLastRange(kt.create(e,ht.nodeLength(e)).select())}})),this.pasteHTML=this.wrapCommand((function(t){if(!n.isLimited(t.length)){t=n.context.invoke("codeview.purify",t);var e=n.getLastRange().pasteHTML(t);n.setLastRange(kt.createFromNodeAfter(y.last(e)).select())}})),this.formatBlock=this.wrapCommand((function(t,e){var o=n.options.callbacks.onApplyCustomStyle;o?o.call(n,e,n.context,n.onFormatBlock):n.onFormatBlock(t,e)})),this.insertHorizontalRule=this.wrapCommand((function(){var t=n.getLastRange().insertNode(ht.create("HR"));t.nextSibling&&n.setLastRange(kt.create(t.nextSibling,0).normalize().select())})),this.lineHeight=this.wrapCommand((function(t){n.style.stylePara(n.getLastRange(),{lineHeight:t})})),this.createLink=this.wrapCommand((function(t){var o=t.url,i=t.text,r=t.isNewWindow,a=t.checkProtocol,s=t.range||n.getLastRange(),l=i.length-s.toString().length;if(!(l>0&&n.isLimited(l))){var c=s.toString()!==i;"string"==typeof o&&(o=o.trim()),n.options.onCreateLink?o=n.options.onCreateLink(o):a&&(o=/^([A-Za-z][A-Za-z0-9+-.]*\:|#|\/)/.test(o)?o:n.options.defaultProtocol+o);var u=[];if(c){var d=(s=s.deleteContents()).insertNode(e()("<A>"+i+"</A>")[0]);u.push(d)}else u=n.style.styleNodes(s,{nodeName:"A",expandClosestSibling:!0,onlyPartialContains:!0});e().each(u,(function(t,n){e()(n).attr("href",o),r?e()(n).attr("target","_blank"):e()(n).removeAttr("target")})),n.setLastRange(n.createRangeFromList(u).select())}})),this.color=this.wrapCommand((function(t){var e=t.foreColor,o=t.backColor;e&&document.execCommand("foreColor",!1,e),o&&document.execCommand("backColor",!1,o)})),this.foreColor=this.wrapCommand((function(t){document.execCommand("foreColor",!1,t)})),this.insertTable=this.wrapCommand((function(t){var e=t.split("x");n.getLastRange().deleteContents().insertNode(n.table.createTable(e[0],e[1],n.options))})),this.removeMedia=this.wrapCommand((function(){var t=e()(n.restoreTarget()).parent();t.closest("figure").length?t.closest("figure").remove():t=e()(n.restoreTarget()).detach(),n.context.triggerEvent("media.delete",t,n.$editable)})),this.floatMe=this.wrapCommand((function(t){var o=e()(n.restoreTarget());o.toggleClass("note-float-left","left"===t),o.toggleClass("note-float-right","right"===t),o.css("float","none"===t?"":t)})),this.resize=this.wrapCommand((function(t){var o=e()(n.restoreTarget());0===(t=parseFloat(t))?o.css("width",""):o.css({width:100*t+"%",height:""})}))}var o,n,i;return o=t,n=[{key:"initialize",value:function(){var t=this;this.$editable.on("keydown",(function(e){if(e.keyCode===wt.code.ENTER&&t.context.triggerEvent("enter",e),t.context.triggerEvent("keydown",e),t.snapshot=t.history.makeSnapshot(),t.hasKeyShortCut=!1,e.isDefaultPrevented()||(t.options.shortcuts?t.hasKeyShortCut=t.handleKeyMap(e):t.preventDefaultEditableShortCuts(e)),t.isLimited(1,e)){var o=t.getLastRange();if(o.eo-o.so==0)return!1}t.setLastRange(),t.options.recordEveryKeystroke&&!1===t.hasKeyShortCut&&t.history.recordUndo()})).on("keyup",(function(e){t.setLastRange(),t.context.triggerEvent("keyup",e)})).on("focus",(function(e){t.setLastRange(),t.context.triggerEvent("focus",e)})).on("blur",(function(e){t.context.triggerEvent("blur",e)})).on("mousedown",(function(e){t.context.triggerEvent("mousedown",e)})).on("mouseup",(function(e){t.setLastRange(),t.history.recordUndo(),t.context.triggerEvent("mouseup",e)})).on("scroll",(function(e){t.context.triggerEvent("scroll",e)})).on("paste",(function(e){t.setLastRange(),t.context.triggerEvent("paste",e)})).on("input",(function(){t.isLimited(0)&&t.snapshot&&t.history.applySnapshot(t.snapshot)})),this.$editable.attr("spellcheck",this.options.spellCheck),this.$editable.attr("autocorrect",this.options.spellCheck),this.options.disableGrammar&&this.$editable.attr("data-gramm",!1),this.$editable.html(ht.html(this.$note)||ht.emptyPara),this.$editable.on(f.inputEventName,v.debounce((function(){t.context.triggerEvent("change",t.$editable.html(),t.$editable)}),10)),this.$editable.on("focusin",(function(e){t.context.triggerEvent("focusin",e)})).on("focusout",(function(e){t.context.triggerEvent("focusout",e)})),this.options.airMode?this.options.overrideContextMenu&&this.$editor.on("contextmenu",(function(e){return t.context.triggerEvent("contextmenu",e),!1})):(this.options.width&&this.$editor.outerWidth(this.options.width),this.options.height&&this.$editable.outerHeight(this.options.height),this.options.maxHeight&&this.$editable.css("max-height",this.options.maxHeight),this.options.minHeight&&this.$editable.css("min-height",this.options.minHeight)),this.history.recordUndo(),this.setLastRange()}},{key:"destroy",value:function(){this.$editable.off()}},{key:"handleKeyMap",value:function(t){var e=this.options.keyMap[f.isMac?"mac":"pc"],o=[];t.metaKey&&o.push("CMD"),t.ctrlKey&&!t.altKey&&o.push("CTRL"),t.shiftKey&&o.push("SHIFT");var n=wt.nameFromCode[t.keyCode];n&&o.push(n);var i=e[o.join("+")];if("TAB"!==n||this.options.tabDisable)if(i){if(!1!==this.context.invoke(i))return t.preventDefault(),!0}else wt.isEdit(t.keyCode)&&this.afterCommand();else this.afterCommand();return!1}},{key:"preventDefaultEditableShortCuts",value:function(t){(t.ctrlKey||t.metaKey)&&y.contains([66,73,85],t.keyCode)&&t.preventDefault()}},{key:"isLimited",value:function(t,e){return t=t||0,(void 0===e||!(wt.isMove(e.keyCode)||wt.isNavigation(e.keyCode)||e.ctrlKey||e.metaKey||y.contains([wt.code.BACKSPACE,wt.code.DELETE],e.keyCode)))&&this.options.maxTextLength>0&&this.$editable.text().length+t>this.options.maxTextLength}},{key:"createRange",value:function(){return this.focus(),this.setLastRange(),this.getLastRange()}},{key:"createRangeFromList",value:function(t){var e=kt.createFromNodeBefore(y.head(t)).getStartPoint(),o=kt.createFromNodeAfter(y.last(t)).getEndPoint();return kt.create(e.node,e.offset,o.node,o.offset)}},{key:"setLastRange",value:function(t){t?this.lastRange=t:(this.lastRange=kt.create(this.editable),0===e()(this.lastRange.sc).closest(".note-editable").length&&(this.lastRange=kt.createFromBodyElement(this.editable)))}},{key:"getLastRange",value:function(){return this.lastRange||this.setLastRange(),this.lastRange}},{key:"saveRange",value:function(t){t&&this.getLastRange().collapse().select()}},{key:"restoreRange",value:function(){this.lastRange&&(this.lastRange.select(),this.focus())}},{key:"saveTarget",value:function(t){this.$editable.data("target",t)}},{key:"clearTarget",value:function(){this.$editable.removeData("target")}},{key:"restoreTarget",value:function(){return this.$editable.data("target")}},{key:"currentStyle",value:function(){var t=kt.create();return t&&(t=t.normalize()),t?this.style.current(t):this.style.fromNode(this.$editable)}},{key:"styleFromNode",value:function(t){return this.style.fromNode(t)}},{key:"undo",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.undo(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"commit",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.commit(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"redo",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),this.history.redo(),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"beforeCommand",value:function(){this.context.triggerEvent("before.command",this.$editable.html()),document.execCommand("styleWithCSS",!1,this.options.styleWithCSS),this.focus()}},{key:"afterCommand",value:function(t){this.normalizeContent(),this.history.recordUndo(),t||this.context.triggerEvent("change",this.$editable.html(),this.$editable)}},{key:"tab",value:function(){var t=this.getLastRange();if(t.isCollapsed()&&t.isOnCell())this.table.tab(t);else{if(0===this.options.tabSize)return!1;this.isLimited(this.options.tabSize)||(this.beforeCommand(),this.typing.insertTab(t,this.options.tabSize),this.afterCommand())}}},{key:"untab",value:function(){var t=this.getLastRange();if(t.isCollapsed()&&t.isOnCell())this.table.tab(t,!0);else if(0===this.options.tabSize)return!1}},{key:"wrapCommand",value:function(t){return function(){this.beforeCommand(),t.apply(this,arguments),this.afterCommand()}}},{key:"insertImage",value:function(t,o){var n,i=this;return(n=t,e().Deferred((function(t){var o=e()("<img>");o.one("load",(function(){o.off("error abort"),t.resolve(o)})).one("error abort",(function(){o.off("load").detach(),t.reject(o)})).css({display:"none"}).appendTo(document.body).attr("src",n)})).promise()).then((function(t){i.beforeCommand(),"function"==typeof o?o(t):("string"==typeof o&&t.attr("data-filename",o),t.css("width",Math.min(i.$editable.width(),t.width()))),t.show(),i.getLastRange().insertNode(t[0]),i.setLastRange(kt.createFromNodeAfter(t[0]).select()),i.afterCommand()})).fail((function(t){i.context.triggerEvent("image.upload.error",t)}))}},{key:"insertImagesAsDataURL",value:function(t){var o=this;e().each(t,(function(t,n){var i=n.name;o.options.maximumImageFileSize&&o.options.maximumImageFileSize<n.size?o.context.triggerEvent("image.upload.error",o.lang.image.maximumFileSizeError):function(t){return e().Deferred((function(o){e().extend(new FileReader,{onload:function(t){var e=t.target.result;o.resolve(e)},onerror:function(t){o.reject(t)}}).readAsDataURL(t)})).promise()}(n).then((function(t){return o.insertImage(t,i)})).fail((function(){o.context.triggerEvent("image.upload.error")}))}))}},{key:"insertImagesOrCallback",value:function(t){this.options.callbacks.onImageUpload?this.context.triggerEvent("image.upload",t):this.insertImagesAsDataURL(t)}},{key:"getSelectedText",value:function(){var t=this.getLastRange();return t.isOnAnchor()&&(t=kt.createFromNode(ht.ancestor(t.sc,ht.isAnchor))),t.toString()}},{key:"onFormatBlock",value:function(t,o){if(document.execCommand("FormatBlock",!1,f.isMSIE?"<"+t+">":t),o&&o.length&&(o[0].tagName.toUpperCase()!==t.toUpperCase()&&(o=o.find(t)),o&&o.length)){var n=this.createRange(),i=e()([n.sc,n.ec]).closest(t);i.removeClass();var r=o[0].className||"";r&&i.addClass(r)}}},{key:"formatPara",value:function(){this.formatBlock("P")}},{key:"fontStyling",value:function(t,o){var n=this.getLastRange();if(""!==n){var i=this.style.styleNodes(n);if(this.$editor.find(".note-status-output").html(""),e()(i).css(t,o),n.isCollapsed()){var r=y.head(i);r&&!ht.nodeLength(r)&&(r.innerHTML=ht.ZERO_WIDTH_NBSP_CHAR,kt.createFromNode(r.firstChild).select(),this.setLastRange(),this.$editable.data("bogus",r))}else this.setLastRange(this.createRangeFromList(i).select())}else{var a=e().now();this.$editor.find(".note-status-output").html('<div id="note-status-output-'+a+'" class="alert alert-info">'+this.lang.output.noSelection+"</div>"),setTimeout((function(){e()("#note-status-output-"+a).remove()}),5e3)}}},{key:"unlink",value:function(){var t=this.getLastRange();if(t.isOnAnchor()){var e=ht.ancestor(t.sc,ht.isAnchor);(t=kt.createFromNode(e)).select(),this.setLastRange(),this.beforeCommand(),document.execCommand("unlink"),this.afterCommand()}}},{key:"getLinkInfo",value:function(){var t=this.getLastRange().expand(ht.isAnchor),o=e()(y.head(t.nodes(ht.isAnchor))),n={range:t,text:t.toString(),url:o.length?o.attr("href"):""};return o.length&&(n.isNewWindow="_blank"===o.attr("target")),n}},{key:"addRow",value:function(t){var e=this.getLastRange(this.$editable);e.isCollapsed()&&e.isOnCell()&&(this.beforeCommand(),this.table.addRow(e,t),this.afterCommand())}},{key:"addCol",value:function(t){var e=this.getLastRange(this.$editable);e.isCollapsed()&&e.isOnCell()&&(this.beforeCommand(),this.table.addCol(e,t),this.afterCommand())}},{key:"deleteRow",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteRow(t),this.afterCommand())}},{key:"deleteCol",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteCol(t),this.afterCommand())}},{key:"deleteTable",value:function(){var t=this.getLastRange(this.$editable);t.isCollapsed()&&t.isOnCell()&&(this.beforeCommand(),this.table.deleteTable(t),this.afterCommand())}},{key:"resizeTo",value:function(t,e,o){var n;if(o){var i=t.y/t.x,r=e.data("ratio");n={width:r>i?t.x:t.y/r,height:r>i?t.x*r:t.y}}else n={width:t.x,height:t.y};e.css(n)}},{key:"hasFocus",value:function(){return this.$editable.is(":focus")}},{key:"focus",value:function(){this.hasFocus()||this.$editable.focus()}},{key:"isEmpty",value:function(){return ht.isEmpty(this.$editable[0])||ht.emptyPara===this.$editable.html()}},{key:"empty",value:function(){this.context.invoke("code",ht.emptyPara)}},{key:"normalizeContent",value:function(){this.$editable[0].normalize()}}],n&&At(o.prototype,n),i&&At(o,i),t}();function Dt(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var Ht=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editable=e.layoutInfo.editable}var e,o,n;return e=t,(o=[{key:"initialize",value:function(){this.$editable.on("paste",this.pasteByEvent.bind(this))}},{key:"pasteByEvent",value:function(t){var e=this,o=t.originalEvent.clipboardData;if(o&&o.items&&o.items.length){var n=o.items.length>1?o.items[1]:y.head(o.items);"file"===n.kind&&-1!==n.type.indexOf("image/")?(this.context.invoke("editor.insertImagesOrCallback",[n.getAsFile()]),t.preventDefault()):"string"===n.kind&&this.context.invoke("editor.isLimited",o.getData("Text").length)&&t.preventDefault()}else if(window.clipboardData){var i=window.clipboardData.getData("text");this.context.invoke("editor.isLimited",i.length)&&t.preventDefault()}setTimeout((function(){e.context.invoke("editor.afterCommand")}),10)}}])&&Dt(e.prototype,o),n&&Dt(e,n),t}();function Bt(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var zt=function(){function t(o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.$eventListener=e()(document),this.$editor=o.layoutInfo.editor,this.$editable=o.layoutInfo.editable,this.options=o.options,this.lang=this.options.langInfo,this.documentEventHandlers={},this.$dropzone=e()(['<div class="note-dropzone">','<div class="note-dropzone-message"></div>',"</div>"].join("")).prependTo(this.$editor)}var o,n,i;return o=t,n=[{key:"initialize",value:function(){this.options.disableDragAndDrop?(this.documentEventHandlers.onDrop=function(t){t.preventDefault()},this.$eventListener=this.$dropzone,this.$eventListener.on("drop",this.documentEventHandlers.onDrop)):this.attachDragAndDropEvent()}},{key:"attachDragAndDropEvent",value:function(){var t=this,o=e()(),n=this.$dropzone.find(".note-dropzone-message");this.documentEventHandlers.onDragenter=function(e){var i=t.context.invoke("codeview.isActivated"),r=t.$editor.width()>0&&t.$editor.height()>0;i||o.length||!r||(t.$editor.addClass("dragover"),t.$dropzone.width(t.$editor.width()),t.$dropzone.height(t.$editor.height()),n.text(t.lang.image.dragImageHere)),o=o.add(e.target)},this.documentEventHandlers.onDragleave=function(n){(o=o.not(n.target)).length&&"BODY"!==n.target.nodeName||(o=e()(),t.$editor.removeClass("dragover"))},this.documentEventHandlers.onDrop=function(){o=e()(),t.$editor.removeClass("dragover")},this.$eventListener.on("dragenter",this.documentEventHandlers.onDragenter).on("dragleave",this.documentEventHandlers.onDragleave).on("drop",this.documentEventHandlers.onDrop),this.$dropzone.on("dragenter",(function(){t.$dropzone.addClass("hover"),n.text(t.lang.image.dropImage)})).on("dragleave",(function(){t.$dropzone.removeClass("hover"),n.text(t.lang.image.dragImageHere)})),this.$dropzone.on("drop",(function(o){var n=o.originalEvent.dataTransfer;o.preventDefault(),n&&n.files&&n.files.length?(t.$editable.focus(),t.context.invoke("editor.insertImagesOrCallback",n.files)):e().each(n.types,(function(o,i){if(!(i.toLowerCase().indexOf("_moz_")>-1)){var r=n.getData(i);i.toLowerCase().indexOf("text")>-1?t.context.invoke("editor.pasteHTML",r):e()(r).each((function(e,o){t.context.invoke("editor.insertNode",o)}))}}))})).on("dragover",!1)}},{key:"destroy",value:function(){var t=this;Object.keys(this.documentEventHandlers).forEach((function(e){t.$eventListener.off(e.substr(2).toLowerCase(),t.documentEventHandlers[e])})),this.documentEventHandlers={}}}],n&&Bt(o.prototype,n),i&&Bt(o,i),t}();function Mt(t,e){var o="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!o){if(Array.isArray(t)||(o=function(t,e){if(!t)return;if("string"==typeof t)return Ot(t,e);var o=Object.prototype.toString.call(t).slice(8,-1);"Object"===o&&t.constructor&&(o=t.constructor.name);if("Map"===o||"Set"===o)return Array.from(t);if("Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o))return Ot(t,e)}(t))||e&&t&&"number"==typeof t.length){o&&(t=o);var n=0,i=function(){};return{s:i,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,a=!0,s=!1;return{s:function(){o=o.call(t)},n:function(){var t=o.next();return a=t.done,t},e:function(t){s=!0,r=t},f:function(){try{a||null==o.return||o.return()}finally{if(s)throw r}}}}function Ot(t,e){(null==e||e>t.length)&&(e=t.length);for(var o=0,n=new Array(e);o<e;o++)n[o]=t[o];return n}function jt(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var Ut=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editor=e.layoutInfo.editor,this.$editable=e.layoutInfo.editable,this.$codable=e.layoutInfo.codable,this.options=e.options,this.CodeMirrorConstructor=window.CodeMirror,this.options.codemirror.CodeMirrorConstructor&&(this.CodeMirrorConstructor=this.options.codemirror.CodeMirrorConstructor)}var e,o,n;return e=t,o=[{key:"sync",value:function(t){var e=this.isActivated(),o=this.CodeMirrorConstructor;e&&(t?o?this.$codable.data("cmEditor").getDoc().setValue(t):this.$codable.val(t):o&&this.$codable.data("cmEditor").save())}},{key:"initialize",value:function(){var t=this;this.$codable.on("keyup",(function(e){e.keyCode===wt.code.ESCAPE&&t.deactivate()}))}},{key:"isActivated",value:function(){return this.$editor.hasClass("codeview")}},{key:"toggle",value:function(){this.isActivated()?this.deactivate():this.activate(),this.context.triggerEvent("codeview.toggled")}},{key:"purify",value:function(t){if(this.options.codeviewFilter&&(t=t.replace(this.options.codeviewFilterRegex,""),this.options.codeviewIframeFilter)){var e=this.options.codeviewIframeWhitelistSrc.concat(this.options.codeviewIframeWhitelistSrcBase);t=t.replace(/(<iframe.*?>.*?(?:<\/iframe>)?)/gi,(function(t){if(/<.+src(?==?('|"|\s)?)[\s\S]+src(?=('|"|\s)?)[^>]*?>/i.test(t))return"";var o,n=Mt(e);try{for(n.s();!(o=n.n()).done;){var i=o.value;if(new RegExp('src="(https?:)?//'+i.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")+'/(.+)"').test(t))return t}}catch(t){n.e(t)}finally{n.f()}return""}))}return t}},{key:"activate",value:function(){var t=this,e=this.CodeMirrorConstructor;if(this.$codable.val(ht.html(this.$editable,this.options.prettifyHtml)),this.$codable.height(this.$editable.height()),this.context.invoke("toolbar.updateCodeview",!0),this.context.invoke("airPopover.updateCodeview",!0),this.$editor.addClass("codeview"),this.$codable.focus(),e){var o=e.fromTextArea(this.$codable[0],this.options.codemirror);if(this.options.codemirror.tern){var n=new e.TernServer(this.options.codemirror.tern);o.ternServer=n,o.on("cursorActivity",(function(t){n.updateArgHints(t)}))}o.on("blur",(function(e){t.context.triggerEvent("blur.codeview",o.getValue(),e)})),o.on("change",(function(){t.context.triggerEvent("change.codeview",o.getValue(),o)})),o.setSize(null,this.$editable.outerHeight()),this.$codable.data("cmEditor",o)}else this.$codable.on("blur",(function(e){t.context.triggerEvent("blur.codeview",t.$codable.val(),e)})),this.$codable.on("input",(function(){t.context.triggerEvent("change.codeview",t.$codable.val(),t.$codable)}))}},{key:"deactivate",value:function(){if(this.CodeMirrorConstructor){var t=this.$codable.data("cmEditor");this.$codable.val(t.getValue()),t.toTextArea()}var e=this.purify(ht.value(this.$codable,this.options.prettifyHtml)||ht.emptyPara),o=this.$editable.html()!==e;this.$editable.html(e),this.$editable.height(this.options.height?this.$codable.height():"auto"),this.$editor.removeClass("codeview"),o&&this.context.triggerEvent("change",this.$editable.html(),this.$editable),this.$editable.focus(),this.context.invoke("toolbar.updateCodeview",!1),this.context.invoke("airPopover.updateCodeview",!1)}},{key:"destroy",value:function(){this.isActivated()&&this.deactivate()}}],o&&jt(e.prototype,o),n&&jt(e,n),t}();function Wt(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var Kt=function(){function t(o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$document=e()(document),this.$statusbar=o.layoutInfo.statusbar,this.$editable=o.layoutInfo.editable,this.$codable=o.layoutInfo.codable,this.options=o.options}var o,n,i;return o=t,(n=[{key:"initialize",value:function(){var t=this;this.options.airMode||this.options.disableResizeEditor?this.destroy():this.$statusbar.on("mousedown",(function(e){e.preventDefault(),e.stopPropagation();var o=t.$editable.offset().top-t.$document.scrollTop(),n=t.$codable.offset().top-t.$document.scrollTop(),i=function(e){var i=e.clientY-(o+24),r=e.clientY-(n+24);i=t.options.minheight>0?Math.max(i,t.options.minheight):i,i=t.options.maxHeight>0?Math.min(i,t.options.maxHeight):i,r=t.options.minheight>0?Math.max(r,t.options.minheight):r,r=t.options.maxHeight>0?Math.min(r,t.options.maxHeight):r,t.$editable.height(i),t.$codable.height(r)};t.$document.on("mousemove",i).one("mouseup",(function(){t.$document.off("mousemove",i)}))}))}},{key:"destroy",value:function(){this.$statusbar.off(),this.$statusbar.addClass("locked")}}])&&Wt(o.prototype,n),i&&Wt(o,i),t}();function Vt(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var qt=function(){function t(o){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.$editor=o.layoutInfo.editor,this.$toolbar=o.layoutInfo.toolbar,this.$editable=o.layoutInfo.editable,this.$codable=o.layoutInfo.codable,this.$window=e()(window),this.$scrollbar=e()("html, body"),this.scrollbarClassName="note-fullscreen-body",this.onResize=function(){n.resizeTo({h:n.$window.height()-n.$toolbar.outerHeight()})}}var o,n,i;return o=t,(n=[{key:"resizeTo",value:function(t){this.$editable.css("height",t.h),this.$codable.css("height",t.h),this.$codable.data("cmeditor")&&this.$codable.data("cmeditor").setsize(null,t.h)}},{key:"toggle",value:function(){this.$editor.toggleClass("fullscreen");var t=this.isFullscreen();this.$scrollbar.toggleClass(this.scrollbarClassName,t),t?(this.$editable.data("orgHeight",this.$editable.css("height")),this.$editable.data("orgMaxHeight",this.$editable.css("maxHeight")),this.$editable.css("maxHeight",""),this.$window.on("resize",this.onResize).trigger("resize")):(this.$window.off("resize",this.onResize),this.resizeTo({h:this.$editable.data("orgHeight")}),this.$editable.css("maxHeight",this.$editable.css("orgMaxHeight"))),this.context.invoke("toolbar.updateFullscreen",t)}},{key:"isFullscreen",value:function(){return this.$editor.hasClass("fullscreen")}},{key:"destroy",value:function(){this.$scrollbar.removeClass(this.scrollbarClassName)}}])&&Vt(o.prototype,n),i&&Vt(o,i),t}();function _t(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var Gt=function(){function t(o){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.$document=e()(document),this.$editingArea=o.layoutInfo.editingArea,this.options=o.options,this.lang=this.options.langInfo,this.events={"summernote.mousedown":function(t,e){n.update(e.target,e)&&e.preventDefault()},"summernote.keyup summernote.scroll summernote.change summernote.dialog.shown":function(){n.update()},"summernote.disable summernote.blur":function(){n.hide()},"summernote.codeview.toggled":function(){n.update()}}}var o,n,i;return o=t,n=[{key:"initialize",value:function(){var t=this;this.$handle=e()(['<div class="note-handle">','<div class="note-control-selection">','<div class="note-control-selection-bg"></div>','<div class="note-control-holder note-control-nw"></div>','<div class="note-control-holder note-control-ne"></div>','<div class="note-control-holder note-control-sw"></div>','<div class="',this.options.disableResizeImage?"note-control-holder":"note-control-sizing",' note-control-se"></div>',this.options.disableResizeImage?"":'<div class="note-control-selection-info"></div>',"</div>","</div>"].join("")).prependTo(this.$editingArea),this.$handle.on("mousedown",(function(e){if(ht.isControlSizing(e.target)){e.preventDefault(),e.stopPropagation();var o=t.$handle.find(".note-control-selection").data("target"),n=o.offset(),i=t.$document.scrollTop(),r=function(e){t.context.invoke("editor.resizeTo",{x:e.clientX-n.left,y:e.clientY-(n.top-i)},o,!e.shiftKey),t.update(o[0],e)};t.$document.on("mousemove",r).one("mouseup",(function(e){e.preventDefault(),t.$document.off("mousemove",r),t.context.invoke("editor.afterCommand")})),o.data("ratio")||o.data("ratio",o.height()/o.width())}})),this.$handle.on("wheel",(function(e){e.preventDefault(),t.update()}))}},{key:"destroy",value:function(){this.$handle.remove()}},{key:"update",value:function(t,o){if(this.context.isDisabled())return!1;var n=ht.isImg(t),i=this.$handle.find(".note-control-selection");if(this.context.invoke("imagePopover.update",t,o),n){var r=e()(t),a=r.position(),s={left:a.left+parseInt(r.css("marginLeft"),10),top:a.top+parseInt(r.css("marginTop"),10)},l={w:r.outerWidth(!1),h:r.outerHeight(!1)};i.css({display:"block",left:s.left,top:s.top,width:l.w,height:l.h}).data("target",r);var c=new Image;c.src=r.attr("src");var u=l.w+"x"+l.h+" ("+this.lang.image.original+": "+c.width+"x"+c.height+")";i.find(".note-control-selection-info").text(u),this.context.invoke("editor.saveTarget",t)}else this.hide();return n}},{key:"hide",value:function(){this.context.invoke("editor.clearTarget"),this.$handle.children().hide()}}],n&&_t(o.prototype,n),i&&_t(o,i),t}();function Yt(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var Zt=/^([A-Za-z][A-Za-z0-9+-.]*\:[\/]{2}|tel:|mailto:[A-Z0-9._%+-]+@|xmpp:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i,Xt=function(){function t(e){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.options=e.options,this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||o.handleKeyup(e)},"summernote.keydown":function(t,e){o.handleKeydown(e)}}}var o,n,i;return o=t,(n=[{key:"initialize",value:function(){this.lastWordRange=null}},{key:"destroy",value:function(){this.lastWordRange=null}},{key:"replace",value:function(){if(this.lastWordRange){var t=this.lastWordRange.toString(),o=t.match(Zt);if(o&&(o[1]||o[2])){var n=o[1]?t:"http://"+t,i=this.options.showDomainOnlyForAutolink?t.replace(/^(?:https?:\/\/)?(?:tel?:?)?(?:mailto?:?)?(?:xmpp?:?)?(?:www\.)?/i,"").split("/")[0]:t,r=e()("<a></a>").html(i).attr("href",n)[0];this.context.options.linkTargetBlank&&e()(r).attr("target","_blank"),this.lastWordRange.insertNode(r),this.lastWordRange=null,this.context.invoke("editor.focus")}}}},{key:"handleKeydown",value:function(t){if(y.contains([wt.code.ENTER,wt.code.SPACE],t.keyCode)){var e=this.context.invoke("editor.createRange").getWordRange();this.lastWordRange=e}}},{key:"handleKeyup",value:function(t){y.contains([wt.code.ENTER,wt.code.SPACE],t.keyCode)&&this.replace()}}])&&Yt(o.prototype,n),i&&Yt(o,i),t}();function Qt(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var Jt=function(){function t(e){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$note=e.layoutInfo.note,this.events={"summernote.change":function(){o.$note.val(e.invoke("code"))}}}var e,o,n;return e=t,(o=[{key:"shouldInitialize",value:function(){return ht.isTextarea(this.$note[0])}}])&&Qt(e.prototype,o),n&&Qt(e,n),t}();function te(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var ee=function(){function t(e){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.options=e.options.replace||{},this.keys=[wt.code.ENTER,wt.code.SPACE,wt.code.PERIOD,wt.code.COMMA,wt.code.SEMICOLON,wt.code.SLASH],this.previousKeydownCode=null,this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||o.handleKeyup(e)},"summernote.keydown":function(t,e){o.handleKeydown(e)}}}var e,o,n;return e=t,(o=[{key:"shouldInitialize",value:function(){return!!this.options.match}},{key:"initialize",value:function(){this.lastWord=null}},{key:"destroy",value:function(){this.lastWord=null}},{key:"replace",value:function(){if(this.lastWord){var t=this,e=this.lastWord.toString();this.options.match(e,(function(e){if(e){var o="";if("string"==typeof e?o=ht.createText(e):e instanceof jQuery?o=e[0]:e instanceof Node&&(o=e),!o)return;t.lastWord.insertNode(o),t.lastWord=null,t.context.invoke("editor.focus")}}))}}},{key:"handleKeydown",value:function(t){if(this.previousKeydownCode&&y.contains(this.keys,this.previousKeydownCode))this.previousKeydownCode=t.keyCode;else{if(y.contains(this.keys,t.keyCode)){var e=this.context.invoke("editor.createRange").getWordRange();this.lastWord=e}this.previousKeydownCode=t.keyCode}}},{key:"handleKeyup",value:function(t){y.contains(this.keys,t.keyCode)&&this.replace()}}])&&te(e.prototype,o),n&&te(e,n),t}();function oe(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var ne=function(){function t(e){var o=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=e,this.$editingArea=e.layoutInfo.editingArea,this.options=e.options,!0===this.options.inheritPlaceholder&&(this.options.placeholder=this.context.$note.attr("placeholder")||this.options.placeholder),this.events={"summernote.init summernote.change":function(){o.update()},"summernote.codeview.toggled":function(){o.update()}}}var o,n,i;return o=t,(n=[{key:"shouldInitialize",value:function(){return!!this.options.placeholder}},{key:"initialize",value:function(){var t=this;this.$placeholder=e()('<div class="note-placeholder"></div>'),this.$placeholder.on("click",(function(){t.context.invoke("focus")})).html(this.options.placeholder).prependTo(this.$editingArea),this.update()}},{key:"destroy",value:function(){this.$placeholder.remove()}},{key:"update",value:function(){var t=!this.context.invoke("codeview.isActivated")&&this.context.invoke("editor.isEmpty");this.$placeholder.toggle(t)}}])&&oe(o.prototype,n),i&&oe(o,i),t}();function ie(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var re=function(){function t(o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.ui=e().summernote.ui,this.context=o,this.$toolbar=o.layoutInfo.toolbar,this.options=o.options,this.lang=this.options.langInfo,this.invertedKeyMap=v.invertObject(this.options.keyMap[f.isMac?"mac":"pc"])}var o,n,i;return o=t,n=[{key:"representShortcut",value:function(t){var e=this.invertedKeyMap[t];return this.options.shortcuts&&e?(f.isMac&&(e=e.replace("CMD","⌘").replace("SHIFT","⇧"))," ("+(e=e.replace("BACKSLASH","\\").replace("SLASH","/").replace("LEFTBRACKET","[").replace("RIGHTBRACKET","]"))+")"):""}},{key:"button",value:function(t){return!this.options.tooltip&&t.tooltip&&delete t.tooltip,t.container=this.options.container,this.ui.button(t)}},{key:"initialize",value:function(){this.addToolbarButtons(),this.addImagePopoverButtons(),this.addLinkPopoverButtons(),this.addTablePopoverButtons(),this.fontInstalledMap={}}},{key:"destroy",value:function(){delete this.fontInstalledMap}},{key:"isFontInstalled",value:function(t){return Object.prototype.hasOwnProperty.call(this.fontInstalledMap,t)||(this.fontInstalledMap[t]=f.isFontInstalled(t)||y.contains(this.options.fontNamesIgnoreCheck,t)),this.fontInstalledMap[t]}},{key:"isFontDeservedToAdd",value:function(t){return""!==(t=t.toLowerCase())&&this.isFontInstalled(t)&&-1===f.genericFontFamilies.indexOf(t)}},{key:"colorPalette",value:function(t,o,n,i){var r=this;return this.ui.buttonGroup({className:"note-color "+t,children:[this.button({className:"note-current-color-button",contents:this.ui.icon(this.options.icons.font+" note-recent-color"),tooltip:o,click:function(t){var o=e()(t.currentTarget);n&&i?r.context.invoke("editor.color",{backColor:o.attr("data-backColor"),foreColor:o.attr("data-foreColor")}):n?r.context.invoke("editor.color",{backColor:o.attr("data-backColor")}):i&&r.context.invoke("editor.color",{foreColor:o.attr("data-foreColor")})},callback:function(t){var e=t.find(".note-recent-color");n&&(e.css("background-color",r.options.colorButton.backColor),t.attr("data-backColor",r.options.colorButton.backColor)),i?(e.css("color",r.options.colorButton.foreColor),t.attr("data-foreColor",r.options.colorButton.foreColor)):e.css("color","transparent")}}),this.button({className:"dropdown-toggle",contents:this.ui.dropdownButtonContents("",this.options),tooltip:this.lang.color.more,data:{toggle:"dropdown"}}),this.ui.dropdown({items:(n?['<div class="note-palette">','<div class="note-palette-title">'+this.lang.color.background+"</div>","<div>",'<button type="button" class="note-color-reset btn btn-light btn-default" data-event="backColor" data-value="transparent">',this.lang.color.transparent,"</button>","</div>",'<div class="note-holder" data-event="backColor">\x3c!-- back colors --\x3e</div>',"<div>",'<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="backColorPicker-'+this.options.id+'">',this.lang.color.cpSelect,"</button>",'<input type="color" id="backColorPicker-'+this.options.id+'" class="note-btn note-color-select-btn" value="'+this.options.colorButton.backColor+'" data-event="backColorPalette-'+this.options.id+'">',"</div>",'<div class="note-holder-custom" id="backColorPalette-'+this.options.id+'" data-event="backColor"></div>',"</div>"].join(""):"")+(i?['<div class="note-palette">','<div class="note-palette-title">'+this.lang.color.foreground+"</div>","<div>",'<button type="button" class="note-color-reset btn btn-light btn-default" data-event="removeFormat" data-value="foreColor">',this.lang.color.resetToDefault,"</button>","</div>",'<div class="note-holder" data-event="foreColor">\x3c!-- fore colors --\x3e</div>',"<div>",'<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="foreColorPicker-'+this.options.id+'">',this.lang.color.cpSelect,"</button>",'<input type="color" id="foreColorPicker-'+this.options.id+'" class="note-btn note-color-select-btn" value="'+this.options.colorButton.foreColor+'" data-event="foreColorPalette-'+this.options.id+'">',"</div>",'<div class="note-holder-custom" id="foreColorPalette-'+this.options.id+'" data-event="foreColor"></div>',"</div>"].join(""):""),callback:function(t){t.find(".note-holder").each((function(t,o){var n=e()(o);n.append(r.ui.palette({colors:r.options.colors,colorsName:r.options.colorsName,eventName:n.data("event"),container:r.options.container,tooltip:r.options.tooltip}).render())}));var o=[["#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF"]];t.find(".note-holder-custom").each((function(t,n){var i=e()(n);i.append(r.ui.palette({colors:o,colorsName:o,eventName:i.data("event"),container:r.options.container,tooltip:r.options.tooltip}).render())})),t.find("input[type=color]").each((function(o,n){e()(n).change((function(){var o=t.find("#"+e()(this).data("event")).find(".note-color-btn").first(),n=this.value.toUpperCase();o.css("background-color",n).attr("aria-label",n).attr("data-value",n).attr("data-original-title",n),o.click()}))}))},click:function(o){o.stopPropagation();var n=e()("."+t).find(".note-dropdown-menu"),i=e()(o.target),a=i.data("event"),s=i.attr("data-value");if("openPalette"===a){var l=n.find("#"+s),c=e()(n.find("#"+l.data("event")).find(".note-color-row")[0]),u=c.find(".note-color-btn").last().detach(),d=l.val();u.css("background-color",d).attr("aria-label",d).attr("data-value",d).attr("data-original-title",d),c.prepend(u),l.click()}else{if(y.contains(["backColor","foreColor"],a)){var h="backColor"===a?"background-color":"color",f=i.closest(".note-color").find(".note-recent-color"),p=i.closest(".note-color").find(".note-current-color-button");f.css(h,s),p.attr("data-"+a,s)}r.context.invoke("editor."+a,s)}}})]}).render()}},{key:"addToolbarButtons",value:function(){var t=this;this.context.memo("button.style",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.magic),t.options),tooltip:t.lang.style.style,data:{toggle:"dropdown"}}),t.ui.dropdown({className:"dropdown-style",items:t.options.styleTags,title:t.lang.style.style,template:function(e){"string"==typeof e&&(e={tag:e,title:Object.prototype.hasOwnProperty.call(t.lang.style,e)?t.lang.style[e]:e});var o=e.tag,n=e.title;return"<"+o+(e.style?' style="'+e.style+'" ':"")+(e.className?' class="'+e.className+'"':"")+">"+n+"</"+o+">"},click:t.context.createInvokeHandler("editor.formatBlock")})]).render()}));for(var o=function(e,o){var n=t.options.styleTags[e];t.context.memo("button.style."+n,(function(){return t.button({className:"note-btn-style-"+n,contents:'<div data-value="'+n+'">'+n.toUpperCase()+"</div>",tooltip:t.lang.style[n],click:t.context.createInvokeHandler("editor.formatBlock")}).render()}))},n=0,i=this.options.styleTags.length;n<i;n++)o(n);this.context.memo("button.bold",(function(){return t.button({className:"note-btn-bold",contents:t.ui.icon(t.options.icons.bold),tooltip:t.lang.font.bold+t.representShortcut("bold"),click:t.context.createInvokeHandlerAndUpdateState("editor.bold")}).render()})),this.context.memo("button.italic",(function(){return t.button({className:"note-btn-italic",contents:t.ui.icon(t.options.icons.italic),tooltip:t.lang.font.italic+t.representShortcut("italic"),click:t.context.createInvokeHandlerAndUpdateState("editor.italic")}).render()})),this.context.memo("button.underline",(function(){return t.button({className:"note-btn-underline",contents:t.ui.icon(t.options.icons.underline),tooltip:t.lang.font.underline+t.representShortcut("underline"),click:t.context.createInvokeHandlerAndUpdateState("editor.underline")}).render()})),this.context.memo("button.clear",(function(){return t.button({contents:t.ui.icon(t.options.icons.eraser),tooltip:t.lang.font.clear+t.representShortcut("removeFormat"),click:t.context.createInvokeHandler("editor.removeFormat")}).render()})),this.context.memo("button.strikethrough",(function(){return t.button({className:"note-btn-strikethrough",contents:t.ui.icon(t.options.icons.strikethrough),tooltip:t.lang.font.strikethrough+t.representShortcut("strikethrough"),click:t.context.createInvokeHandlerAndUpdateState("editor.strikethrough")}).render()})),this.context.memo("button.superscript",(function(){return t.button({className:"note-btn-superscript",contents:t.ui.icon(t.options.icons.superscript),tooltip:t.lang.font.superscript,click:t.context.createInvokeHandlerAndUpdateState("editor.superscript")}).render()})),this.context.memo("button.subscript",(function(){return t.button({className:"note-btn-subscript",contents:t.ui.icon(t.options.icons.subscript),tooltip:t.lang.font.subscript,click:t.context.createInvokeHandlerAndUpdateState("editor.subscript")}).render()})),this.context.memo("button.fontname",(function(){var o=t.context.invoke("editor.currentStyle");return t.options.addDefaultFonts&&e().each(o["font-family"].split(","),(function(e,o){o=o.trim().replace(/['"]+/g,""),t.isFontDeservedToAdd(o)&&-1===t.options.fontNames.indexOf(o)&&t.options.fontNames.push(o)})),t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontname"></span>',t.options),tooltip:t.lang.font.name,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontname",checkClassName:t.options.icons.menuCheck,items:t.options.fontNames.filter(t.isFontInstalled.bind(t)),title:t.lang.font.name,template:function(t){return'<span style="font-family: '+f.validFontName(t)+'">'+t+"</span>"},click:t.context.createInvokeHandlerAndUpdateState("editor.fontName")})]).render()})),this.context.memo("button.fontsize",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontsize"></span>',t.options),tooltip:t.lang.font.size,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontsize",checkClassName:t.options.icons.menuCheck,items:t.options.fontSizes,title:t.lang.font.size,click:t.context.createInvokeHandlerAndUpdateState("editor.fontSize")})]).render()})),this.context.memo("button.fontsizeunit",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents('<span class="note-current-fontsizeunit"></span>',t.options),tooltip:t.lang.font.sizeunit,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({className:"dropdown-fontsizeunit",checkClassName:t.options.icons.menuCheck,items:t.options.fontSizeUnits,title:t.lang.font.sizeunit,click:t.context.createInvokeHandlerAndUpdateState("editor.fontSizeUnit")})]).render()})),this.context.memo("button.color",(function(){return t.colorPalette("note-color-all",t.lang.color.recent,!0,!0)})),this.context.memo("button.forecolor",(function(){return t.colorPalette("note-color-fore",t.lang.color.foreground,!1,!0)})),this.context.memo("button.backcolor",(function(){return t.colorPalette("note-color-back",t.lang.color.background,!0,!1)})),this.context.memo("button.ul",(function(){return t.button({contents:t.ui.icon(t.options.icons.unorderedlist),tooltip:t.lang.lists.unordered+t.representShortcut("insertUnorderedList"),click:t.context.createInvokeHandler("editor.insertUnorderedList")}).render()})),this.context.memo("button.ol",(function(){return t.button({contents:t.ui.icon(t.options.icons.orderedlist),tooltip:t.lang.lists.ordered+t.representShortcut("insertOrderedList"),click:t.context.createInvokeHandler("editor.insertOrderedList")}).render()}));var r=this.button({contents:this.ui.icon(this.options.icons.alignLeft),tooltip:this.lang.paragraph.left+this.representShortcut("justifyLeft"),click:this.context.createInvokeHandler("editor.justifyLeft")}),a=this.button({contents:this.ui.icon(this.options.icons.alignCenter),tooltip:this.lang.paragraph.center+this.representShortcut("justifyCenter"),click:this.context.createInvokeHandler("editor.justifyCenter")}),s=this.button({contents:this.ui.icon(this.options.icons.alignRight),tooltip:this.lang.paragraph.right+this.representShortcut("justifyRight"),click:this.context.createInvokeHandler("editor.justifyRight")}),l=this.button({contents:this.ui.icon(this.options.icons.alignJustify),tooltip:this.lang.paragraph.justify+this.representShortcut("justifyFull"),click:this.context.createInvokeHandler("editor.justifyFull")}),c=this.button({contents:this.ui.icon(this.options.icons.outdent),tooltip:this.lang.paragraph.outdent+this.representShortcut("outdent"),click:this.context.createInvokeHandler("editor.outdent")}),u=this.button({contents:this.ui.icon(this.options.icons.indent),tooltip:this.lang.paragraph.indent+this.representShortcut("indent"),click:this.context.createInvokeHandler("editor.indent")});this.context.memo("button.justifyLeft",v.invoke(r,"render")),this.context.memo("button.justifyCenter",v.invoke(a,"render")),this.context.memo("button.justifyRight",v.invoke(s,"render")),this.context.memo("button.justifyFull",v.invoke(l,"render")),this.context.memo("button.outdent",v.invoke(c,"render")),this.context.memo("button.indent",v.invoke(u,"render")),this.context.memo("button.paragraph",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.alignLeft),t.options),tooltip:t.lang.paragraph.paragraph,data:{toggle:"dropdown"}}),t.ui.dropdown([t.ui.buttonGroup({className:"note-align",children:[r,a,s,l]}),t.ui.buttonGroup({className:"note-list",children:[c,u]})])]).render()})),this.context.memo("button.height",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.textHeight),t.options),tooltip:t.lang.font.height,data:{toggle:"dropdown"}}),t.ui.dropdownCheck({items:t.options.lineHeights,checkClassName:t.options.icons.menuCheck,className:"dropdown-line-height",title:t.lang.font.height,click:t.context.createInvokeHandler("editor.lineHeight")})]).render()})),this.context.memo("button.table",(function(){return t.ui.buttonGroup([t.button({className:"dropdown-toggle",contents:t.ui.dropdownButtonContents(t.ui.icon(t.options.icons.table),t.options),tooltip:t.lang.table.table,data:{toggle:"dropdown"}}),t.ui.dropdown({title:t.lang.table.table,className:"note-table",items:['<div class="note-dimension-picker">','<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>','<div class="note-dimension-picker-highlighted"></div>','<div class="note-dimension-picker-unhighlighted"></div>',"</div>",'<div class="note-dimension-display">1 x 1</div>'].join("")})],{callback:function(e){e.find(".note-dimension-picker-mousecatcher").css({width:t.options.insertTableMaxSize.col+"em",height:t.options.insertTableMaxSize.row+"em"}).mouseup(t.context.createInvokeHandler("editor.insertTable")).on("mousemove",t.tableMoveHandler.bind(t))}}).render()})),this.context.memo("button.link",(function(){return t.button({contents:t.ui.icon(t.options.icons.link),tooltip:t.lang.link.link+t.representShortcut("linkDialog.show"),click:t.context.createInvokeHandler("linkDialog.show")}).render()})),this.context.memo("button.picture",(function(){return t.button({contents:t.ui.icon(t.options.icons.picture),tooltip:t.lang.image.image,click:t.context.createInvokeHandler("imageDialog.show")}).render()})),this.context.memo("button.video",(function(){return t.button({contents:t.ui.icon(t.options.icons.video),tooltip:t.lang.video.video,click:t.context.createInvokeHandler("videoDialog.show")}).render()})),this.context.memo("button.hr",(function(){return t.button({contents:t.ui.icon(t.options.icons.minus),tooltip:t.lang.hr.insert+t.representShortcut("insertHorizontalRule"),click:t.context.createInvokeHandler("editor.insertHorizontalRule")}).render()})),this.context.memo("button.fullscreen",(function(){return t.button({className:"btn-fullscreen note-codeview-keep",contents:t.ui.icon(t.options.icons.arrowsAlt),tooltip:t.lang.options.fullscreen,click:t.context.createInvokeHandler("fullscreen.toggle")}).render()})),this.context.memo("button.codeview",(function(){return t.button({className:"btn-codeview note-codeview-keep",contents:t.ui.icon(t.options.icons.code),tooltip:t.lang.options.codeview,click:t.context.createInvokeHandler("codeview.toggle")}).render()})),this.context.memo("button.redo",(function(){return t.button({contents:t.ui.icon(t.options.icons.redo),tooltip:t.lang.history.redo+t.representShortcut("redo"),click:t.context.createInvokeHandler("editor.redo")}).render()})),this.context.memo("button.undo",(function(){return t.button({contents:t.ui.icon(t.options.icons.undo),tooltip:t.lang.history.undo+t.representShortcut("undo"),click:t.context.createInvokeHandler("editor.undo")}).render()})),this.context.memo("button.help",(function(){return t.button({contents:t.ui.icon(t.options.icons.question),tooltip:t.lang.options.help,click:t.context.createInvokeHandler("helpDialog.show")}).render()}))}},{key:"addImagePopoverButtons",value:function(){var t=this;this.context.memo("button.resizeFull",(function(){return t.button({contents:'<span class="note-fontsize-10">100%</span>',tooltip:t.lang.image.resizeFull,click:t.context.createInvokeHandler("editor.resize","1")}).render()})),this.context.memo("button.resizeHalf",(function(){return t.button({contents:'<span class="note-fontsize-10">50%</span>',tooltip:t.lang.image.resizeHalf,click:t.context.createInvokeHandler("editor.resize","0.5")}).render()})),this.context.memo("button.resizeQuarter",(function(){return t.button({contents:'<span class="note-fontsize-10">25%</span>',tooltip:t.lang.image.resizeQuarter,click:t.context.createInvokeHandler("editor.resize","0.25")}).render()})),this.context.memo("button.resizeNone",(function(){return t.button({contents:t.ui.icon(t.options.icons.rollback),tooltip:t.lang.image.resizeNone,click:t.context.createInvokeHandler("editor.resize","0")}).render()})),this.context.memo("button.floatLeft",(function(){return t.button({contents:t.ui.icon(t.options.icons.floatLeft),tooltip:t.lang.image.floatLeft,click:t.context.createInvokeHandler("editor.floatMe","left")}).render()})),this.context.memo("button.floatRight",(function(){return t.button({contents:t.ui.icon(t.options.icons.floatRight),tooltip:t.lang.image.floatRight,click:t.context.createInvokeHandler("editor.floatMe","right")}).render()})),this.context.memo("button.floatNone",(function(){return t.button({contents:t.ui.icon(t.options.icons.rollback),tooltip:t.lang.image.floatNone,click:t.context.createInvokeHandler("editor.floatMe","none")}).render()})),this.context.memo("button.removeMedia",(function(){return t.button({contents:t.ui.icon(t.options.icons.trash),tooltip:t.lang.image.remove,click:t.context.createInvokeHandler("editor.removeMedia")}).render()}))}},{key:"addLinkPopoverButtons",value:function(){var t=this;this.context.memo("button.linkDialogShow",(function(){return t.button({contents:t.ui.icon(t.options.icons.link),tooltip:t.lang.link.edit,click:t.context.createInvokeHandler("linkDialog.show")}).render()})),this.context.memo("button.unlink",(function(){return t.button({contents:t.ui.icon(t.options.icons.unlink),tooltip:t.lang.link.unlink,click:t.context.createInvokeHandler("editor.unlink")}).render()}))}},{key:"addTablePopoverButtons",value:function(){var t=this;this.context.memo("button.addRowUp",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowAbove),tooltip:t.lang.table.addRowAbove,click:t.context.createInvokeHandler("editor.addRow","top")}).render()})),this.context.memo("button.addRowDown",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowBelow),tooltip:t.lang.table.addRowBelow,click:t.context.createInvokeHandler("editor.addRow","bottom")}).render()})),this.context.memo("button.addColLeft",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colBefore),tooltip:t.lang.table.addColLeft,click:t.context.createInvokeHandler("editor.addCol","left")}).render()})),this.context.memo("button.addColRight",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colAfter),tooltip:t.lang.table.addColRight,click:t.context.createInvokeHandler("editor.addCol","right")}).render()})),this.context.memo("button.deleteRow",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.rowRemove),tooltip:t.lang.table.delRow,click:t.context.createInvokeHandler("editor.deleteRow")}).render()})),this.context.memo("button.deleteCol",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.colRemove),tooltip:t.lang.table.delCol,click:t.context.createInvokeHandler("editor.deleteCol")}).render()})),this.context.memo("button.deleteTable",(function(){return t.button({className:"btn-md",contents:t.ui.icon(t.options.icons.trash),tooltip:t.lang.table.delTable,click:t.context.createInvokeHandler("editor.deleteTable")}).render()}))}},{key:"build",value:function(t,e){for(var o=0,n=e.length;o<n;o++){for(var i=e[o],r=Array.isArray(i)?i[0]:i,a=Array.isArray(i)?1===i.length?[i[0]]:i[1]:[i],s=this.ui.buttonGroup({className:"note-"+r}).render(),l=0,c=a.length;l<c;l++){var u=this.context.memo("button."+a[l]);u&&s.append("function"==typeof u?u(this.context):u)}s.appendTo(t)}}},{key:"updateCurrentStyle",value:function(t){var o=t||this.$toolbar,n=this.context.invoke("editor.currentStyle");if(this.updateBtnStates(o,{".note-btn-bold":function(){return"bold"===n["font-bold"]},".note-btn-italic":function(){return"italic"===n["font-italic"]},".note-btn-underline":function(){return"underline"===n["font-underline"]},".note-btn-subscript":function(){return"subscript"===n["font-subscript"]},".note-btn-superscript":function(){return"superscript"===n["font-superscript"]},".note-btn-strikethrough":function(){return"strikethrough"===n["font-strikethrough"]}}),n["font-family"]){var i=n["font-family"].split(",").map((function(t){return t.replace(/[\'\"]/g,"").replace(/\s+$/,"").replace(/^\s+/,"")})),r=y.find(i,this.isFontInstalled.bind(this));o.find(".dropdown-fontname a").each((function(t,o){var n=e()(o),i=n.data("value")+""==r+"";n.toggleClass("checked",i)})),o.find(".note-current-fontname").text(r).css("font-family",r)}if(n["font-size"]){var a=n["font-size"];o.find(".dropdown-fontsize a").each((function(t,o){var n=e()(o),i=n.data("value")+""==a+"";n.toggleClass("checked",i)})),o.find(".note-current-fontsize").text(a);var s=n["font-size-unit"];o.find(".dropdown-fontsizeunit a").each((function(t,o){var n=e()(o),i=n.data("value")+""==s+"";n.toggleClass("checked",i)})),o.find(".note-current-fontsizeunit").text(s)}if(n["line-height"]){var l=n["line-height"];o.find(".dropdown-line-height a").each((function(t,o){var n=e()(o),i=e()(o).data("value")+""==l+"";n.toggleClass("checked",i)})),o.find(".note-current-line-height").text(l)}}},{key:"updateBtnStates",value:function(t,o){var n=this;e().each(o,(function(e,o){n.ui.toggleBtnActive(t.find(e),o())}))}},{key:"tableMoveHandler",value:function(t){var o,n=e()(t.target.parentNode),i=n.next(),r=n.find(".note-dimension-picker-mousecatcher"),a=n.find(".note-dimension-picker-highlighted"),s=n.find(".note-dimension-picker-unhighlighted");if(void 0===t.offsetX){var l=e()(t.target).offset();o={x:t.pageX-l.left,y:t.pageY-l.top}}else o={x:t.offsetX,y:t.offsetY};var c=Math.ceil(o.x/18)||1,u=Math.ceil(o.y/18)||1;a.css({width:c+"em",height:u+"em"}),r.data("value",c+"x"+u),c>3&&c<this.options.insertTableMaxSize.col&&s.css({width:c+1+"em"}),u>3&&u<this.options.insertTableMaxSize.row&&s.css({height:u+1+"em"}),i.html(c+" x "+u)}}],n&&ie(o.prototype,n),i&&ie(o,i),t}();function ae(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var se=function(){function t(o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.$window=e()(window),this.$document=e()(document),this.ui=e().summernote.ui,this.$note=o.layoutInfo.note,this.$editor=o.layoutInfo.editor,this.$toolbar=o.layoutInfo.toolbar,this.$editable=o.layoutInfo.editable,this.$statusbar=o.layoutInfo.statusbar,this.options=o.options,this.isFollowing=!1,this.followScroll=this.followScroll.bind(this)}var o,n,i;return o=t,(n=[{key:"shouldInitialize",value:function(){return!this.options.airMode}},{key:"initialize",value:function(){var t=this;this.options.toolbar=this.options.toolbar||[],this.options.toolbar.length?this.context.invoke("buttons.build",this.$toolbar,this.options.toolbar):this.$toolbar.hide(),this.options.toolbarContainer&&this.$toolbar.appendTo(this.options.toolbarContainer),this.changeContainer(!1),this.$note.on("summernote.keyup summernote.mouseup summernote.change",(function(){t.context.invoke("buttons.updateCurrentStyle")})),this.context.invoke("buttons.updateCurrentStyle"),this.options.followingToolbar&&this.$window.on("scroll resize",this.followScroll)}},{key:"destroy",value:function(){this.$toolbar.children().remove(),this.options.followingToolbar&&this.$window.off("scroll resize",this.followScroll)}},{key:"followScroll",value:function(){if(this.$editor.hasClass("fullscreen"))return!1;var t=this.$editor.outerHeight(),o=this.$editor.width(),n=this.$toolbar.height(),i=this.$statusbar.height(),r=0;this.options.otherStaticBar&&(r=e()(this.options.otherStaticBar).outerHeight());var a=this.$document.scrollTop(),s=this.$editor.offset().top,l=s-r,c=s+t-r-n-i;!this.isFollowing&&a>l&&a<c-n?(this.isFollowing=!0,this.$editable.css({marginTop:this.$toolbar.outerHeight()}),this.$toolbar.css({position:"fixed",top:r,width:o,zIndex:1e3})):this.isFollowing&&(a<l||a>c)&&(this.isFollowing=!1,this.$toolbar.css({position:"relative",top:0,width:"100%",zIndex:"auto"}),this.$editable.css({marginTop:""}))}},{key:"changeContainer",value:function(t){t?this.$toolbar.prependTo(this.$editor):this.options.toolbarContainer&&this.$toolbar.appendTo(this.options.toolbarContainer),this.options.followingToolbar&&this.followScroll()}},{key:"updateFullscreen",value:function(t){this.ui.toggleBtnActive(this.$toolbar.find(".btn-fullscreen"),t),this.changeContainer(t)}},{key:"updateCodeview",value:function(t){this.ui.toggleBtnActive(this.$toolbar.find(".btn-codeview"),t),t?this.deactivate():this.activate()}},{key:"activate",value:function(t){var e=this.$toolbar.find("button");t||(e=e.not(".note-codeview-keep")),this.ui.toggleBtn(e,!0)}},{key:"deactivate",value:function(t){var e=this.$toolbar.find("button");t||(e=e.not(".note-codeview-keep")),this.ui.toggleBtn(e,!1)}}])&&ae(o.prototype,n),i&&ae(o,i),t}();function le(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var ce=function(){function t(o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=o.layoutInfo.editor,this.options=o.options,this.lang=this.options.langInfo,o.memo("help.linkDialog.show",this.options.langInfo.help["linkDialog.show"])}var o,n,i;return o=t,(n=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,o=['<div class="form-group note-form-group">','<label for="note-dialog-link-txt-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.link.textToDisplay,"</label>"),'<input id="note-dialog-link-txt-'.concat(this.options.id,'" class="note-link-text form-control note-form-control note-input" type="text"/>'),"</div>",'<div class="form-group note-form-group">','<label for="note-dialog-link-url-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.link.url,"</label>"),'<input id="note-dialog-link-url-'.concat(this.options.id,'" class="note-link-url form-control note-form-control note-input" type="text" value="http://"/>'),"</div>",this.options.disableLinkTarget?"":e()("<div></div>").append(this.ui.checkbox({className:"sn-checkbox-open-in-new-window",text:this.lang.link.openInNewWindow,checked:!0}).render()).html(),e()("<div></div>").append(this.ui.checkbox({className:"sn-checkbox-use-protocol",text:this.lang.link.useProtocol,checked:!0}).render()).html()].join(""),n='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-link-btn",'" value="').concat(this.lang.link.insert,'" disabled>');this.$dialog=this.ui.dialog({className:"link-dialog",title:this.lang.link.insert,fade:this.options.dialogsFade,body:o,footer:n}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"toggleLinkBtn",value:function(t,e,o){this.ui.toggleBtn(t,e.val()&&o.val())}},{key:"showLinkDialog",value:function(t){var o=this;return e().Deferred((function(e){var n=o.$dialog.find(".note-link-text"),i=o.$dialog.find(".note-link-url"),r=o.$dialog.find(".note-link-btn"),a=o.$dialog.find(".sn-checkbox-open-in-new-window input[type=checkbox]"),s=o.$dialog.find(".sn-checkbox-use-protocol input[type=checkbox]");o.ui.onDialogShown(o.$dialog,(function(){o.context.triggerEvent("dialog.shown"),!t.url&&v.isValidUrl(t.text)&&(t.url=t.text),n.on("input paste propertychange",(function(){t.text=n.val(),o.toggleLinkBtn(r,n,i)})).val(t.text),i.on("input paste propertychange",(function(){t.text||n.val(i.val()),o.toggleLinkBtn(r,n,i)})).val(t.url),f.isSupportTouch||i.trigger("focus"),o.toggleLinkBtn(r,n,i),o.bindEnterKey(i,r),o.bindEnterKey(n,r);var l=void 0!==t.isNewWindow?t.isNewWindow:o.context.options.linkTargetBlank;a.prop("checked",l);var c=!t.url&&o.context.options.useProtocol;s.prop("checked",c),r.one("click",(function(r){r.preventDefault(),e.resolve({range:t.range,url:i.val(),text:n.val(),isNewWindow:a.is(":checked"),checkProtocol:s.is(":checked")}),o.ui.hideDialog(o.$dialog)}))})),o.ui.onDialogHidden(o.$dialog,(function(){n.off(),i.off(),r.off(),"pending"===e.state()&&e.reject()})),o.ui.showDialog(o.$dialog)})).promise()}},{key:"show",value:function(){var t=this,e=this.context.invoke("editor.getLinkInfo");this.context.invoke("editor.saveRange"),this.showLinkDialog(e).then((function(e){t.context.invoke("editor.restoreRange"),t.context.invoke("editor.createLink",e)})).fail((function(){t.context.invoke("editor.restoreRange")}))}}])&&le(o.prototype,n),i&&le(o,i),t}();function ue(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var de=function(){function t(o){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.ui=e().summernote.ui,this.options=o.options,this.events={"summernote.keyup summernote.mouseup summernote.change summernote.scroll":function(){n.update()},"summernote.disable summernote.dialog.shown":function(){n.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&n.$popover[0].contains(e.originalEvent.relatedTarget)||n.hide()}}}var o,n,i;return o=t,(n=[{key:"shouldInitialize",value:function(){return!y.isEmpty(this.options.popover.link)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-link-popover",callback:function(t){t.find(".popover-content,.note-popover-content").prepend('<span><a target="_blank"></a>&nbsp;</span>')}}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.link),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(){if(this.context.invoke("editor.hasFocus")){var t=this.context.invoke("editor.getLastRange");if(t.isCollapsed()&&t.isOnAnchor()){var o=ht.ancestor(t.sc,ht.isAnchor),n=e()(o).attr("href");this.$popover.find("a").attr("href",n).text(n);var i=ht.posFromPlaceholder(o),r=e()(this.options.container).offset();i.top-=r.top,i.left-=r.left,this.$popover.css({display:"block",left:i.left,top:i.top})}else this.hide()}else this.hide()}},{key:"hide",value:function(){this.$popover.hide()}}])&&ue(o.prototype,n),i&&ue(o,i),t}();function he(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var fe=function(){function t(o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=o.layoutInfo.editor,this.options=o.options,this.lang=this.options.langInfo}var o,n,i;return o=t,(n=[{key:"initialize",value:function(){var t="";if(this.options.maximumImageFileSize){var e=Math.floor(Math.log(this.options.maximumImageFileSize)/Math.log(1024)),o=1*(this.options.maximumImageFileSize/Math.pow(1024,e)).toFixed(2)+" "+" KMGTP"[e]+"B";t="<small>".concat(this.lang.image.maximumFileSize+" : "+o,"</small>")}var n=this.options.dialogsInBody?this.$body:this.options.container,i=['<div class="form-group note-form-group note-group-select-from-files">','<label for="note-dialog-image-file-'+this.options.id+'" class="note-form-label">'+this.lang.image.selectFromFiles+"</label>",'<input id="note-dialog-image-file-'+this.options.id+'" class="note-image-input form-control-file note-form-control note-input" ',' type="file" name="files" accept="'+this.options.acceptImageFileTypes+'" multiple="multiple"/>',t,"</div>",'<div class="form-group note-group-image-url">','<label for="note-dialog-image-url-'+this.options.id+'" class="note-form-label">'+this.lang.image.url+"</label>",'<input id="note-dialog-image-url-'+this.options.id+'" class="note-image-url form-control note-form-control note-input" type="text"/>',"</div>"].join(""),r='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-image-btn",'" value="').concat(this.lang.image.insert,'" disabled>');this.$dialog=this.ui.dialog({title:this.lang.image.insert,fade:this.options.dialogsFade,body:i,footer:r}).render().appendTo(n)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"show",value:function(){var t=this;this.context.invoke("editor.saveRange"),this.showImageDialog().then((function(e){t.ui.hideDialog(t.$dialog),t.context.invoke("editor.restoreRange"),"string"==typeof e?t.options.callbacks.onImageLinkInsert?t.context.triggerEvent("image.link.insert",e):t.context.invoke("editor.insertImage",e):t.context.invoke("editor.insertImagesOrCallback",e)})).fail((function(){t.context.invoke("editor.restoreRange")}))}},{key:"showImageDialog",value:function(){var t=this;return e().Deferred((function(e){var o=t.$dialog.find(".note-image-input"),n=t.$dialog.find(".note-image-url"),i=t.$dialog.find(".note-image-btn");t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),o.replaceWith(o.clone().on("change",(function(t){e.resolve(t.target.files||t.target.value)})).val("")),n.on("input paste propertychange",(function(){t.ui.toggleBtn(i,n.val())})).val(""),f.isSupportTouch||n.trigger("focus"),i.click((function(t){t.preventDefault(),e.resolve(n.val())})),t.bindEnterKey(n,i)})),t.ui.onDialogHidden(t.$dialog,(function(){o.off(),n.off(),i.off(),"pending"===e.state()&&e.reject()})),t.ui.showDialog(t.$dialog)}))}}])&&he(o.prototype,n),i&&he(o,i),t}();function pe(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var ve=function(){function t(o){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.ui=e().summernote.ui,this.editable=o.layoutInfo.editable[0],this.options=o.options,this.events={"summernote.disable summernote.dialog.shown":function(){n.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&n.$popover[0].contains(e.originalEvent.relatedTarget)||n.hide()}}}var o,n,i;return o=t,n=[{key:"shouldInitialize",value:function(){return!y.isEmpty(this.options.popover.image)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-image-popover"}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.image),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t,o){if(ht.isImg(t)){var n=e()(t).offset(),i=e()(this.options.container).offset(),r={};this.options.popatmouse?(r.left=o.pageX-20,r.top=o.pageY):r=n,r.top-=i.top,r.left-=i.left,this.$popover.css({display:"block",left:r.left,top:r.top})}else this.hide()}},{key:"hide",value:function(){this.$popover.hide()}}],n&&pe(o.prototype,n),i&&pe(o,i),t}();function me(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var ge=function(){function t(o){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.ui=e().summernote.ui,this.options=o.options,this.events={"summernote.mousedown":function(t,e){n.update(e.target)},"summernote.keyup summernote.scroll summernote.change":function(){n.update()},"summernote.disable summernote.dialog.shown":function(){n.hide()},"summernote.blur":function(t,e){e.originalEvent&&e.originalEvent.relatedTarget&&n.$popover[0].contains(e.originalEvent.relatedTarget)||n.hide()}}}var o,n,i;return o=t,n=[{key:"shouldInitialize",value:function(){return!y.isEmpty(this.options.popover.table)}},{key:"initialize",value:function(){this.$popover=this.ui.popover({className:"note-table-popover"}).render().appendTo(this.options.container);var t=this.$popover.find(".popover-content,.note-popover-content");this.context.invoke("buttons.build",t,this.options.popover.table),f.isFF&&document.execCommand("enableInlineTableEditing",!1,!1),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t){if(this.context.isDisabled())return!1;var o=ht.isCell(t)||ht.isCell(null==t?void 0:t.parentElement);if(o){var n=ht.posFromPlaceholder(t),i=e()(this.options.container).offset();n.top-=i.top,n.left-=i.left,this.$popover.css({display:"block",left:n.left,top:n.top})}else this.hide();return o}},{key:"hide",value:function(){this.$popover.hide()}}],n&&me(o.prototype,n),i&&me(o,i),t}();function be(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var ke=function(){function t(o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=o.layoutInfo.editor,this.options=o.options,this.lang=this.options.langInfo}var o,n,i;return o=t,(n=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,e=['<div class="form-group note-form-group row-fluid">','<label for="note-dialog-video-url-'.concat(this.options.id,'" class="note-form-label">').concat(this.lang.video.url,' <small class="text-muted">').concat(this.lang.video.providers,"</small></label>"),'<input id="note-dialog-video-url-'.concat(this.options.id,'" class="note-video-url form-control note-form-control note-input" type="text"/>'),"</div>"].join(""),o='<input type="button" href="#" class="'.concat("btn btn-primary note-btn note-btn-primary note-video-btn",'" value="').concat(this.lang.video.insert,'" disabled>');this.$dialog=this.ui.dialog({title:this.lang.video.insert,fade:this.options.dialogsFade,body:e,footer:o}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"bindEnterKey",value:function(t,e){t.on("keypress",(function(t){t.keyCode===wt.code.ENTER&&(t.preventDefault(),e.trigger("click"))}))}},{key:"createVideoNode",value:function(t){var o,n=t.match(/\/\/(?:(?:www|m)\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))([\w|-]{11})(?:(?:[\?&]t=)(\S+))?$/),i=t.match(/(?:\.|\/\/)drive\.google\.com\/file\/d\/(.[a-zA-Z0-9_-]*)\/view/),r=t.match(/(?:www\.|\/\/)instagram\.com\/p\/(.[a-zA-Z0-9_-]*)/),a=t.match(/\/\/vine\.co\/v\/([a-zA-Z0-9]+)/),s=t.match(/\/\/(player\.)?vimeo\.com\/([a-z]*\/)*(\d+)[?]?.*/),l=t.match(/.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/),c=t.match(/\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/),u=t.match(/\/\/(.*)\/videos\/watch\/([^?]*)(?:\?(?:start=(\w*))?(?:&stop=(\w*))?(?:&loop=([10]))?(?:&autoplay=([10]))?(?:&muted=([10]))?)?/),d=t.match(/\/\/v\.qq\.com.*?vid=(.+)/),h=t.match(/\/\/v\.qq\.com\/x?\/?(page|cover).*?\/([^\/]+)\.html\??.*/),f=t.match(/^.+.(mp4|m4v)$/),p=t.match(/^.+.(ogg|ogv)$/),v=t.match(/^.+.(webm)$/),m=t.match(/(?:www\.|\/\/)facebook\.com\/([^\/]+)\/videos\/([0-9]+)/);if(n&&11===n[1].length){var g=n[1],b=0;if(void 0!==n[2]){var k=n[2].match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/);if(k)for(var y=[3600,60,1],w=0,C=y.length;w<C;w++)b+=void 0!==k[w+1]?y[w]*parseInt(k[w+1],10):0}o=e()("<iframe>").attr("frameborder",0).attr("src","//www.youtube.com/embed/"+g+(b>0?"?start="+b:"")).attr("width","640").attr("height","360")}else if(i&&i[0].length)o=e()("<iframe>").attr("frameborder",0).attr("src","https://drive.google.com/file/d/"+i[1]+"/preview").attr("width","640").attr("height","480");else if(r&&r[0].length)o=e()("<iframe>").attr("frameborder",0).attr("src","https://instagram.com/p/"+r[1]+"/embed/").attr("width","612").attr("height","710").attr("scrolling","no").attr("allowtransparency","true");else if(a&&a[0].length)o=e()("<iframe>").attr("frameborder",0).attr("src",a[0]+"/embed/simple").attr("width","600").attr("height","600").attr("class","vine-embed");else if(s&&s[3].length)o=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("src","//player.vimeo.com/video/"+s[3]).attr("width","640").attr("height","360");else if(l&&l[2].length)o=e()("<iframe>").attr("frameborder",0).attr("src","//www.dailymotion.com/embed/video/"+l[2]).attr("width","640").attr("height","360");else if(c&&c[1].length)o=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("height","498").attr("width","510").attr("src","//player.youku.com/embed/"+c[1]);else if(u&&u[0].length){var x=0;"undefined"!==u[2]&&(x=u[2]);var S=0;"undefined"!==u[3]&&(S=u[3]);var T=0;"undefined"!==u[4]&&(T=u[4]);var E=0;"undefined"!==u[5]&&(E=u[5]);var $=0;"undefined"!==u[6]&&($=u[6]),o=e()('<iframe allowfullscreen sandbox="allow-same-origin allow-scripts allow-popups">').attr("frameborder",0).attr("src","//"+u[1]+"/videos/embed/"+u[2]+"?loop="+T+"&autoplay="+E+"&muted="+$+(x>0?"&start="+x:"")+(S>0?"&end="+b:"")).attr("width","560").attr("height","315")}else if(d&&d[1].length||h&&h[2].length){var N=d&&d[1].length?d[1]:h[2];o=e()("<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>").attr("frameborder",0).attr("height","310").attr("width","500").attr("src","https://v.qq.com/txp/iframe/player.html?vid="+N+"&amp;auto=0")}else if(f||p||v)o=e()("<video controls>").attr("src",t).attr("width","640").attr("height","360");else{if(!m||!m[0].length)return!1;o=e()("<iframe>").attr("frameborder",0).attr("src","https://www.facebook.com/plugins/video.php?href="+encodeURIComponent(m[0])+"&show_text=0&width=560").attr("width","560").attr("height","301").attr("scrolling","no").attr("allowtransparency","true")}return o.addClass("note-video-clip"),o[0]}},{key:"show",value:function(){var t=this,e=this.context.invoke("editor.getSelectedText");this.context.invoke("editor.saveRange"),this.showVideoDialog(e).then((function(e){t.ui.hideDialog(t.$dialog),t.context.invoke("editor.restoreRange");var o=t.createVideoNode(e);o&&t.context.invoke("editor.insertNode",o)})).fail((function(){t.context.invoke("editor.restoreRange")}))}},{key:"showVideoDialog",value:function(){var t=this;return e().Deferred((function(e){var o=t.$dialog.find(".note-video-url"),n=t.$dialog.find(".note-video-btn");t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),o.on("input paste propertychange",(function(){t.ui.toggleBtn(n,o.val())})),f.isSupportTouch||o.trigger("focus"),n.click((function(t){t.preventDefault(),e.resolve(o.val())})),t.bindEnterKey(o,n)})),t.ui.onDialogHidden(t.$dialog,(function(){o.off(),n.off(),"pending"===e.state()&&e.reject()})),t.ui.showDialog(t.$dialog)}))}}])&&be(o.prototype,n),i&&be(o,i),t}();function ye(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var we=function(){function t(o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.ui=e().summernote.ui,this.$body=e()(document.body),this.$editor=o.layoutInfo.editor,this.options=o.options,this.lang=this.options.langInfo}var o,n,i;return o=t,n=[{key:"initialize",value:function(){var t=this.options.dialogsInBody?this.$body:this.options.container,e=['<p class="text-center">','<a href="http://summernote.org/" target="_blank" rel="noopener noreferrer">Summernote 0.8.20</a> · ','<a href="https://github.com/summernote/summernote" target="_blank" rel="noopener noreferrer">Project</a> · ','<a href="https://github.com/summernote/summernote/issues" target="_blank" rel="noopener noreferrer">Issues</a>',"</p>"].join("");this.$dialog=this.ui.dialog({title:this.lang.options.help,fade:this.options.dialogsFade,body:this.createShortcutList(),footer:e,callback:function(t){t.find(".modal-body,.note-modal-body").css({"max-height":300,overflow:"scroll"})}}).render().appendTo(t)}},{key:"destroy",value:function(){this.ui.hideDialog(this.$dialog),this.$dialog.remove()}},{key:"createShortcutList",value:function(){var t=this,o=this.options.keyMap[f.isMac?"mac":"pc"];return Object.keys(o).map((function(n){var i=o[n],r=e()('<div><div class="help-list-item"></div></div>');return r.append(e()("<label><kbd>"+n+"</kdb></label>").css({width:180,"margin-right":10})).append(e()("<span></span>").html(t.context.memo("help."+i)||i)),r.html()})).join("")}},{key:"showHelpDialog",value:function(){var t=this;return e().Deferred((function(e){t.ui.onDialogShown(t.$dialog,(function(){t.context.triggerEvent("dialog.shown"),e.resolve()})),t.ui.showDialog(t.$dialog)})).promise()}},{key:"show",value:function(){var t=this;this.context.invoke("editor.saveRange"),this.showHelpDialog().then((function(){t.context.invoke("editor.restoreRange")}))}}],n&&ye(o.prototype,n),i&&ye(o,i),t}();function Ce(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var xe=function(){function t(o){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.ui=e().summernote.ui,this.options=o.options,this.hidable=!0,this.onContextmenu=!1,this.pageX=null,this.pageY=null,this.events={"summernote.contextmenu":function(t){n.options.editing&&(t.preventDefault(),t.stopPropagation(),n.onContextmenu=!0,n.update(!0))},"summernote.mousedown":function(t,e){n.pageX=e.pageX,n.pageY=e.pageY},"summernote.keyup summernote.mouseup summernote.scroll":function(t,e){n.options.editing&&!n.onContextmenu&&(n.pageX=e.pageX,n.pageY=e.pageY,n.update()),n.onContextmenu=!1},"summernote.disable summernote.change summernote.dialog.shown summernote.blur":function(){n.hide()},"summernote.focusout":function(){n.$popover.is(":active,:focus")||n.hide()}}}var o,n,i;return o=t,(n=[{key:"shouldInitialize",value:function(){return this.options.airMode&&!y.isEmpty(this.options.popover.air)}},{key:"initialize",value:function(){var t=this;this.$popover=this.ui.popover({className:"note-air-popover"}).render().appendTo(this.options.container);var e=this.$popover.find(".popover-content");this.context.invoke("buttons.build",e,this.options.popover.air),this.$popover.on("mousedown",(function(){t.hidable=!1})),this.$popover.on("mouseup",(function(){t.hidable=!0}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"update",value:function(t){var o=this.context.invoke("editor.currentStyle");if(!o.range||o.range.isCollapsed()&&!t)this.hide();else{var n={left:this.pageX,top:this.pageY},i=e()(this.options.container).offset();n.top-=i.top,n.left-=i.left,this.$popover.css({display:"block",left:Math.max(n.left,0)+-5,top:n.top+5}),this.context.invoke("buttons.updateCurrentStyle",this.$popover)}}},{key:"updateCodeview",value:function(t){this.ui.toggleBtnActive(this.$popover.find(".btn-codeview"),t),t&&this.hide()}},{key:"hide",value:function(){this.hidable&&this.$popover.hide()}}])&&Ce(o.prototype,n),i&&Ce(o,i),t}();function Se(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var Te=function(){function t(o){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.context=o,this.ui=e().summernote.ui,this.$editable=o.layoutInfo.editable,this.options=o.options,this.hint=this.options.hint||[],this.direction=this.options.hintDirection||"bottom",this.hints=Array.isArray(this.hint)?this.hint:[this.hint],this.events={"summernote.keyup":function(t,e){e.isDefaultPrevented()||n.handleKeyup(e)},"summernote.keydown":function(t,e){n.handleKeydown(e)},"summernote.disable summernote.dialog.shown summernote.blur":function(){n.hide()}}}var o,n,i;return o=t,n=[{key:"shouldInitialize",value:function(){return this.hints.length>0}},{key:"initialize",value:function(){var t=this;this.lastWordRange=null,this.matchingWord=null,this.$popover=this.ui.popover({className:"note-hint-popover",hideArrow:!0,direction:""}).render().appendTo(this.options.container),this.$popover.hide(),this.$content=this.$popover.find(".popover-content,.note-popover-content"),this.$content.on("click",".note-hint-item",(function(o){t.$content.find(".active").removeClass("active"),e()(o.currentTarget).addClass("active"),t.replace()})),this.$popover.on("mousedown",(function(t){t.preventDefault()}))}},{key:"destroy",value:function(){this.$popover.remove()}},{key:"selectItem",value:function(t){this.$content.find(".active").removeClass("active"),t.addClass("active"),this.$content[0].scrollTop=t[0].offsetTop-this.$content.innerHeight()/2}},{key:"moveDown",value:function(){var t=this.$content.find(".note-hint-item.active"),e=t.next();if(e.length)this.selectItem(e);else{var o=t.parent().next();o.length||(o=this.$content.find(".note-hint-group").first()),this.selectItem(o.find(".note-hint-item").first())}}},{key:"moveUp",value:function(){var t=this.$content.find(".note-hint-item.active"),e=t.prev();if(e.length)this.selectItem(e);else{var o=t.parent().prev();o.length||(o=this.$content.find(".note-hint-group").last()),this.selectItem(o.find(".note-hint-item").last())}}},{key:"replace",value:function(){var t=this.$content.find(".note-hint-item.active");if(t.length){var o=this.nodeFromItem(t);if(null!==this.matchingWord&&0===this.matchingWord.length)this.lastWordRange.so=this.lastWordRange.eo;else if(null!==this.matchingWord&&this.matchingWord.length>0&&!this.lastWordRange.isCollapsed()){var n=this.lastWordRange.eo-this.lastWordRange.so-this.matchingWord.length;n>0&&(this.lastWordRange.so+=n)}if(this.lastWordRange.insertNode(o),"next"===this.options.hintSelect){var i=document.createTextNode("");e()(o).after(i),kt.createFromNodeBefore(i).select()}else kt.createFromNodeAfter(o).select();this.lastWordRange=null,this.hide(),this.context.invoke("editor.focus"),this.context.triggerEvent("change",this.$editable.html(),this.$editable)}}},{key:"nodeFromItem",value:function(t){var e=this.hints[t.data("index")],o=t.data("item"),n=e.content?e.content(o):o;return"string"==typeof n&&(n=ht.createText(n)),n}},{key:"createItemTemplates",value:function(t,o){var n=this.hints[t];return o.map((function(o){var i=e()('<div class="note-hint-item"></div>');return i.append(n.template?n.template(o):o+""),i.data({index:t,item:o}),i}))}},{key:"handleKeydown",value:function(t){this.$popover.is(":visible")&&(t.keyCode===wt.code.ENTER?(t.preventDefault(),this.replace()):t.keyCode===wt.code.UP?(t.preventDefault(),this.moveUp()):t.keyCode===wt.code.DOWN&&(t.preventDefault(),this.moveDown()))}},{key:"searchKeyword",value:function(t,e,o){var n=this.hints[t];if(n&&n.match.test(e)&&n.search){var i=n.match.exec(e);this.matchingWord=i[0],n.search(i[1],o)}else o()}},{key:"createGroup",value:function(t,o){var n=this,i=e()('<div class="note-hint-group note-hint-group-'+t+'"></div>');return this.searchKeyword(t,o,(function(e){(e=e||[]).length&&(i.html(n.createItemTemplates(t,e)),n.show())})),i}},{key:"handleKeyup",value:function(t){var o=this;if(!y.contains([wt.code.ENTER,wt.code.UP,wt.code.DOWN],t.keyCode)){var n,i,r=this.context.invoke("editor.getLastRange");if("words"===this.options.hintMode){if(n=r.getWordsRange(r),i=n.toString(),this.hints.forEach((function(t){if(t.match.test(i))return n=r.getWordsMatchRange(t.match),!1})),!n)return void this.hide();i=n.toString()}else n=r.getWordRange(),i=n.toString();if(this.hints.length&&i){this.$content.empty();var a=v.rect2bnd(y.last(n.getClientRects())),s=e()(this.options.container).offset();a&&(a.top-=s.top,a.left-=s.left,this.$popover.hide(),this.lastWordRange=n,this.hints.forEach((function(t,e){t.match.test(i)&&o.createGroup(e,i).appendTo(o.$content)})),this.$content.find(".note-hint-item:first").addClass("active"),"top"===this.direction?this.$popover.css({left:a.left,top:a.top-this.$popover.outerHeight()-5}):this.$popover.css({left:a.left,top:a.top+a.height+5}))}else this.hide()}}},{key:"show",value:function(){this.$popover.show()}},{key:"hide",value:function(){this.$popover.hide()}}],n&&Se(o.prototype,n),i&&Se(o,i),t}();function Ee(t){return Ee="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ee(t)}function $e(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}e().summernote=e().extend(e().summernote,{version:"0.8.20",plugins:{},dom:ht,range:kt,lists:y,options:{langInfo:e().summernote.lang["en-US"],editing:!0,modules:{editor:Ft,clipboard:Ht,dropzone:zt,codeview:Ut,statusbar:Kt,fullscreen:qt,handle:Gt,hintPopover:Te,autoLink:Xt,autoSync:Jt,autoReplace:ee,placeholder:ne,buttons:re,toolbar:se,linkDialog:ce,linkPopover:de,imageDialog:fe,imagePopover:ve,tablePopover:ge,videoDialog:ke,helpDialog:we,airPopover:xe},buttons:{},lang:"en-US",followingToolbar:!1,toolbarPosition:"top",otherStaticBar:"",codeviewKeepButton:!1,toolbar:[["style",["style"]],["font",["bold","underline","clear"]],["fontname",["fontname"]],["color",["color"]],["para",["ul","ol","paragraph"]],["table",["table"]],["insert",["link","picture","video"]],["view",["fullscreen","codeview","help"]]],popatmouse:!0,popover:{image:[["resize",["resizeFull","resizeHalf","resizeQuarter","resizeNone"]],["float",["floatLeft","floatRight","floatNone"]],["remove",["removeMedia"]]],link:[["link",["linkDialogShow","unlink"]]],table:[["add",["addRowDown","addRowUp","addColLeft","addColRight"]],["delete",["deleteRow","deleteCol","deleteTable"]]],air:[["color",["color"]],["font",["bold","underline","clear"]],["para",["ul","paragraph"]],["table",["table"]],["insert",["link","picture"]],["view",["fullscreen","codeview"]]]},airMode:!1,overrideContextMenu:!1,width:null,height:null,linkTargetBlank:!0,useProtocol:!0,defaultProtocol:"http://",focus:!1,tabDisabled:!1,tabSize:4,styleWithCSS:!1,shortcuts:!0,textareaAutoSync:!0,tooltip:"auto",container:null,maxTextLength:0,blockquoteBreakingLevel:2,spellCheck:!0,disableGrammar:!1,placeholder:null,inheritPlaceholder:!1,recordEveryKeystroke:!1,historyLimit:200,showDomainOnlyForAutolink:!1,hintMode:"word",hintSelect:"after",hintDirection:"bottom",styleTags:["p","blockquote","pre","h1","h2","h3","h4","h5","h6"],fontNames:["Arial","Arial Black","Comic Sans MS","Courier New","Helvetica Neue","Helvetica","Impact","Lucida Grande","Tahoma","Times New Roman","Verdana"],fontNamesIgnoreCheck:[],addDefaultFonts:!0,fontSizes:["8","9","10","11","12","14","18","24","36"],fontSizeUnits:["px","pt"],colors:[["#000000","#424242","#636363","#9C9C94","#CEC6CE","#EFEFEF","#F7F7F7","#FFFFFF"],["#FF0000","#FF9C00","#FFFF00","#00FF00","#00FFFF","#0000FF","#9C00FF","#FF00FF"],["#F7C6CE","#FFE7CE","#FFEFC6","#D6EFD6","#CEDEE7","#CEE7F7","#D6D6E7","#E7D6DE"],["#E79C9C","#FFC69C","#FFE79C","#B5D6A5","#A5C6CE","#9CC6EF","#B5A5D6","#D6A5BD"],["#E76363","#F7AD6B","#FFD663","#94BD7B","#73A5AD","#6BADDE","#8C7BC6","#C67BA5"],["#CE0000","#E79439","#EFC631","#6BA54A","#4A7B8C","#3984C6","#634AA5","#A54A7B"],["#9C0000","#B56308","#BD9400","#397B21","#104A5A","#085294","#311873","#731842"],["#630000","#7B3900","#846300","#295218","#083139","#003163","#21104A","#4A1031"]],colorsName:[["Black","Tundora","Dove Gray","Star Dust","Pale Slate","Gallery","Alabaster","White"],["Red","Orange Peel","Yellow","Green","Cyan","Blue","Electric Violet","Magenta"],["Azalea","Karry","Egg White","Zanah","Botticelli","Tropical Blue","Mischka","Twilight"],["Tonys Pink","Peach Orange","Cream Brulee","Sprout","Casper","Perano","Cold Purple","Careys Pink"],["Mandy","Rajah","Dandelion","Olivine","Gulf Stream","Viking","Blue Marguerite","Puce"],["Guardsman Red","Fire Bush","Golden Dream","Chelsea Cucumber","Smalt Blue","Boston Blue","Butterfly Bush","Cadillac"],["Sangria","Mai Tai","Buddha Gold","Forest Green","Eden","Venice Blue","Meteorite","Claret"],["Rosewood","Cinnamon","Olive","Parsley","Tiber","Midnight Blue","Valentino","Loulou"]],colorButton:{foreColor:"#000000",backColor:"#FFFF00"},lineHeights:["1.0","1.2","1.4","1.5","1.6","1.8","2.0","3.0"],tableClassName:"table table-bordered",insertTableMaxSize:{col:10,row:10},dialogsInBody:!1,dialogsFade:!1,maximumImageFileSize:null,acceptImageFileTypes:"image/*",callbacks:{onBeforeCommand:null,onBlur:null,onBlurCodeview:null,onChange:null,onChangeCodeview:null,onDialogShown:null,onEnter:null,onFocus:null,onImageLinkInsert:null,onImageUpload:null,onImageUploadError:null,onInit:null,onKeydown:null,onKeyup:null,onMousedown:null,onMouseup:null,onPaste:null,onScroll:null},codemirror:{mode:"text/html",htmlMode:!0,lineNumbers:!0},codeviewFilter:!0,codeviewFilterRegex:/<\/*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|ilayer|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|t(?:itle|extarea)|xml)[^>]*?>/gi,codeviewIframeFilter:!0,codeviewIframeWhitelistSrc:[],codeviewIframeWhitelistSrcBase:["www.youtube.com","www.youtube-nocookie.com","www.facebook.com","vine.co","instagram.com","player.vimeo.com","www.dailymotion.com","player.youku.com","jumpingbean.tv","v.qq.com"],keyMap:{pc:{ESC:"escape",ENTER:"insertParagraph","CTRL+Z":"undo","CTRL+Y":"redo",TAB:"tab","SHIFT+TAB":"untab","CTRL+B":"bold","CTRL+I":"italic","CTRL+U":"underline","CTRL+SHIFT+S":"strikethrough","CTRL+BACKSLASH":"removeFormat","CTRL+SHIFT+L":"justifyLeft","CTRL+SHIFT+E":"justifyCenter","CTRL+SHIFT+R":"justifyRight","CTRL+SHIFT+J":"justifyFull","CTRL+SHIFT+NUM7":"insertUnorderedList","CTRL+SHIFT+NUM8":"insertOrderedList","CTRL+LEFTBRACKET":"outdent","CTRL+RIGHTBRACKET":"indent","CTRL+NUM0":"formatPara","CTRL+NUM1":"formatH1","CTRL+NUM2":"formatH2","CTRL+NUM3":"formatH3","CTRL+NUM4":"formatH4","CTRL+NUM5":"formatH5","CTRL+NUM6":"formatH6","CTRL+ENTER":"insertHorizontalRule","CTRL+K":"linkDialog.show"},mac:{ESC:"escape",ENTER:"insertParagraph","CMD+Z":"undo","CMD+SHIFT+Z":"redo",TAB:"tab","SHIFT+TAB":"untab","CMD+B":"bold","CMD+I":"italic","CMD+U":"underline","CMD+SHIFT+S":"strikethrough","CMD+BACKSLASH":"removeFormat","CMD+SHIFT+L":"justifyLeft","CMD+SHIFT+E":"justifyCenter","CMD+SHIFT+R":"justifyRight","CMD+SHIFT+J":"justifyFull","CMD+SHIFT+NUM7":"insertUnorderedList","CMD+SHIFT+NUM8":"insertOrderedList","CMD+LEFTBRACKET":"outdent","CMD+RIGHTBRACKET":"indent","CMD+NUM0":"formatPara","CMD+NUM1":"formatH1","CMD+NUM2":"formatH2","CMD+NUM3":"formatH3","CMD+NUM4":"formatH4","CMD+NUM5":"formatH5","CMD+NUM6":"formatH6","CMD+ENTER":"insertHorizontalRule","CMD+K":"linkDialog.show"}},icons:{align:"note-icon-align",alignCenter:"note-icon-align-center",alignJustify:"note-icon-align-justify",alignLeft:"note-icon-align-left",alignRight:"note-icon-align-right",rowBelow:"note-icon-row-below",colBefore:"note-icon-col-before",colAfter:"note-icon-col-after",rowAbove:"note-icon-row-above",rowRemove:"note-icon-row-remove",colRemove:"note-icon-col-remove",indent:"note-icon-align-indent",outdent:"note-icon-align-outdent",arrowsAlt:"note-icon-arrows-alt",bold:"note-icon-bold",caret:"note-icon-caret",circle:"note-icon-circle",close:"note-icon-close",code:"note-icon-code",eraser:"note-icon-eraser",floatLeft:"note-icon-float-left",floatRight:"note-icon-float-right",font:"note-icon-font",frame:"note-icon-frame",italic:"note-icon-italic",link:"note-icon-link",unlink:"note-icon-chain-broken",magic:"note-icon-magic",menuCheck:"note-icon-menu-check",minus:"note-icon-minus",orderedlist:"note-icon-orderedlist",pencil:"note-icon-pencil",picture:"note-icon-picture",question:"note-icon-question",redo:"note-icon-redo",rollback:"note-icon-rollback",square:"note-icon-square",strikethrough:"note-icon-strikethrough",subscript:"note-icon-subscript",superscript:"note-icon-superscript",table:"note-icon-table",textHeight:"note-icon-text-height",trash:"note-icon-trash",underline:"note-icon-underline",undo:"note-icon-undo",unorderedlist:"note-icon-unorderedlist",video:"note-icon-video"}}});var Ne=function(){function t(e,o,n,i){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.markup=e,this.children=o,this.options=n,this.callback=i}var o,n,i;return o=t,(n=[{key:"render",value:function(t){var o=e()(this.markup);if(this.options&&this.options.contents&&o.html(this.options.contents),this.options&&this.options.className&&o.addClass(this.options.className),this.options&&this.options.data&&e().each(this.options.data,(function(t,e){o.attr("data-"+t,e)})),this.options&&this.options.click&&o.on("click",this.options.click),this.children){var n=o.find(".note-children-container");this.children.forEach((function(t){t.render(n.length?n:o)}))}return this.callback&&this.callback(o,this.options),this.options&&this.options.callback&&this.options.callback(o),t&&t.append(o),o}}])&&$e(o.prototype,n),i&&$e(o,i),t}();const Ie=function(t,e){return function(){var o="object"===Ee(arguments[1])?arguments[1]:arguments[0],n=Array.isArray(arguments[0])?arguments[0]:[];return o&&o.children&&(n=o.children),new Ne(t,n,o,e)}};function Pe(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}const Re=function(){function t(o,n){if(function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$node=o,this.options=e().extend({},{title:"",target:n.container,trigger:"hover focus",placement:"bottom"},n),this.$tooltip=e()(['<div class="note-tooltip">','<div class="note-tooltip-arrow"></div>','<div class="note-tooltip-content"></div>',"</div>"].join("")),"manual"!==this.options.trigger){var i=this.show.bind(this),r=this.hide.bind(this),a=this.toggle.bind(this);this.options.trigger.split(" ").forEach((function(t){"hover"===t?(o.off("mouseenter mouseleave"),o.on("mouseenter",i).on("mouseleave",r)):"click"===t?o.on("click",a):"focus"===t&&o.on("focus",i).on("blur",r)}))}}var o,n,i;return o=t,(n=[{key:"show",value:function(){var t=this.$node,o=t.offset(),n=e()(this.options.target).offset();o.top-=n.top,o.left-=n.left;var i=this.$tooltip,r=this.options.title||t.attr("title")||t.data("title"),a=this.options.placement||t.data("placement");i.addClass(a),i.find(".note-tooltip-content").text(r),i.appendTo(this.options.target);var s=t.outerWidth(),l=t.outerHeight(),c=i.outerWidth(),u=i.outerHeight();"bottom"===a?i.css({top:o.top+l,left:o.left+(s/2-c/2)}):"top"===a?i.css({top:o.top-u,left:o.left+(s/2-c/2)}):"left"===a?i.css({top:o.top+(l/2-u/2),left:o.left-c}):"right"===a&&i.css({top:o.top+(l/2-u/2),left:o.left+s}),i.addClass("in")}},{key:"hide",value:function(){var t=this;this.$tooltip.removeClass("in"),setTimeout((function(){t.$tooltip.remove()}),200)}},{key:"toggle",value:function(){this.$tooltip.hasClass("in")?this.hide():this.show()}}])&&Pe(o.prototype,n),i&&Pe(o,i),t}();function Le(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}var Ae=function(){function t(o,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$button=o,this.options=e().extend({},{target:n.container},n),this.setEvent()}var o,n,i;return o=t,(n=[{key:"setEvent",value:function(){var t=this;this.$button.on("click",(function(e){t.toggle(),e.stopImmediatePropagation()}))}},{key:"clear",value:function(){var t=e()(".note-btn-group.open");t.find(".note-btn.active").removeClass("active"),t.removeClass("open")}},{key:"show",value:function(){this.$button.addClass("active"),this.$button.parent().addClass("open");var t=this.$button.next(),o=t.offset(),n=t.outerWidth(),i=e()(window).width(),r=parseFloat(e()(this.options.target).css("margin-right"));o.left+n>i-r?t.css("margin-left",i-r-(o.left+n)):t.css("margin-left","")}},{key:"hide",value:function(){this.$button.removeClass("active"),this.$button.parent().removeClass("open")}},{key:"toggle",value:function(){var t=this.$button.parent().hasClass("open");this.clear(),t?this.hide():this.show()}}])&&Le(o.prototype,n),i&&Le(o,i),t}();e()(document).on("click",(function(t){e()(t.target).closest(".note-btn-group").length||(e()(".note-btn-group.open").removeClass("open"),e()(".note-btn-group .note-btn.active").removeClass("active"))})),e()(document).on("click.note-dropdown-menu",(function(t){e()(t.target).closest(".note-dropdown-menu").parent().removeClass("open"),e()(t.target).closest(".note-dropdown-menu").parent().find(".note-btn.active").removeClass("active")}));const Fe=Ae;function De(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}const He=function(){function t(o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.$modal=o,this.$backdrop=e()('<div class="note-modal-backdrop"></div>')}var o,n,i;return o=t,(n=[{key:"show",value:function(){var t=this;this.$backdrop.appendTo(document.body).show(),this.$modal.addClass("open").show(),this.$modal.trigger("note.modal.show"),this.$modal.off("click",".close").on("click",".close",this.hide.bind(this)),this.$modal.on("keydown",(function(e){27===e.which&&(e.preventDefault(),t.hide())}))}},{key:"hide",value:function(){this.$modal.removeClass("open").hide(),this.$backdrop.hide(),this.$modal.trigger("note.modal.hide"),this.$modal.off("keydown")}}])&&De(o.prototype,n),i&&De(o,i),t}();var Be=Ie('<div class="note-editor note-frame"></div>'),ze=Ie('<div class="note-toolbar" role="toolbar"></div>'),Me=Ie('<div class="note-editing-area"></div>'),Oe=Ie('<textarea class="note-codable" aria-multiline="true"></textarea>'),je=Ie('<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>'),Ue=Ie(['<output class="note-status-output" role="status" aria-live="polite"></output>','<div class="note-statusbar" role="status">','<div class="note-resizebar" aria-label="resize">','<div class="note-icon-bar"></div>','<div class="note-icon-bar"></div>','<div class="note-icon-bar"></div>',"</div>","</div>"].join("")),We=Ie('<div class="note-editor note-airframe"></div>'),Ke=Ie(['<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>','<output class="note-status-output" role="status" aria-live="polite"></output>'].join("")),Ve=Ie('<div class="note-btn-group"></div>'),qe=Ie('<button type="button" class="note-btn" tabindex="-1"></button>',(function(t,o){o&&o.tooltip&&(t.attr({"aria-label":o.tooltip}),t.data("_lite_tooltip",new Re(t,{title:o.tooltip,container:o.container})).on("click",(function(t){e()(t.currentTarget).data("_lite_tooltip").hide()}))),o.contents&&t.html(o.contents),o&&o.data&&"dropdown"===o.data.toggle&&t.data("_lite_dropdown",new Fe(t,{container:o.container})),o&&o.codeviewKeepButton&&t.addClass("note-codeview-keep")})),_e=Ie('<div class="note-dropdown-menu" role="list"></div>',(function(t,o){var n=Array.isArray(o.items)?o.items.map((function(t){var n="string"==typeof t?t:t.value||"",i=o.template?o.template(t):t,r=e()('<a class="note-dropdown-item" href="#" data-value="'+n+'" role="listitem" aria-label="'+n+'"></a>');return r.html(i).data("item",t),r})):o.items;t.html(n).attr({"aria-label":o.title}),t.on("click","> .note-dropdown-item",(function(t){var n=e()(this),i=n.data("item"),r=n.data("value");i.click?i.click(n):o.itemClick&&o.itemClick(t,i,r)})),o&&o.codeviewKeepButton&&t.addClass("note-codeview-keep")})),Ge=Ie('<div class="note-dropdown-menu note-check" role="list"></div>',(function(t,o){var n=Array.isArray(o.items)?o.items.map((function(t){var n="string"==typeof t?t:t.value||"",i=o.template?o.template(t):t,r=e()('<a class="note-dropdown-item" href="#" data-value="'+n+'" role="listitem" aria-label="'+t+'"></a>');return r.html([lo(o.checkClassName)," ",i]).data("item",t),r})):o.items;t.html(n).attr({"aria-label":o.title}),t.on("click","> .note-dropdown-item",(function(t){var n=e()(this),i=n.data("item"),r=n.data("value");i.click?i.click(n):o.itemClick&&o.itemClick(t,i,r)})),o&&o.codeviewKeepButton&&t.addClass("note-codeview-keep")})),Ye=function(t,e){return t+" "+lo(e.icons.caret,"span")},Ze=function(t,e){return Ve([qe({className:"dropdown-toggle",contents:t.title+" "+lo("note-icon-caret"),tooltip:t.tooltip,data:{toggle:"dropdown"}}),_e({className:t.className,items:t.items,template:t.template,itemClick:t.itemClick})],{callback:e}).render()},Xe=function(t,e){return Ve([qe({className:"dropdown-toggle",contents:t.title+" "+lo("note-icon-caret"),tooltip:t.tooltip,data:{toggle:"dropdown"}}),Ge({className:t.className,checkClassName:t.checkClassName,items:t.items,template:t.template,itemClick:t.itemClick})],{callback:e}).render()},Qe=function(t){return Ve([qe({className:"dropdown-toggle",contents:t.title+" "+lo("note-icon-caret"),tooltip:t.tooltip,data:{toggle:"dropdown"}}),_e([Ve({className:"note-align",children:t.items[0]}),Ve({className:"note-list",children:t.items[1]})])]).render()},Je=function(t){return Ve([qe({className:"dropdown-toggle",contents:t.title+" "+lo("note-icon-caret"),tooltip:t.tooltip,data:{toggle:"dropdown"}}),_e({className:"note-table",items:['<div class="note-dimension-picker">','<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>','<div class="note-dimension-picker-highlighted"></div>','<div class="note-dimension-picker-unhighlighted"></div>',"</div>",'<div class="note-dimension-display">1 x 1</div>'].join("")})],{callback:function(o){o.find(".note-dimension-picker-mousecatcher").css({width:t.col+"em",height:t.row+"em"}).mouseup(t.itemClick).mousemove((function(o){!function(t,o,n){var i,r=e()(t.target.parentNode),a=r.next(),s=r.find(".note-dimension-picker-mousecatcher"),l=r.find(".note-dimension-picker-highlighted"),c=r.find(".note-dimension-picker-unhighlighted");if(void 0===t.offsetX){var u=e()(t.target).offset();i={x:t.pageX-u.left,y:t.pageY-u.top}}else i={x:t.offsetX,y:t.offsetY};var d=Math.ceil(i.x/18)||1,h=Math.ceil(i.y/18)||1;l.css({width:d+"em",height:h+"em"}),s.data("value",d+"x"+h),d>3&&d<o&&c.css({width:d+1+"em"}),h>3&&h<n&&c.css({height:h+1+"em"}),a.html(d+" x "+h)}(o,t.col,t.row)}))}}).render()},to=Ie('<div class="note-color-palette"></div>',(function(t,o){for(var n=[],i=0,r=o.colors.length;i<r;i++){for(var a=o.eventName,s=o.colors[i],l=o.colorsName[i],c=[],u=0,d=s.length;u<d;u++){var h=s[u],f=l[u];c.push(['<button type="button" class="note-btn note-color-btn"','style="background-color:',h,'" ','data-event="',a,'" ','data-value="',h,'" ','data-title="',f,'" ','aria-label="',f,'" ','data-toggle="button" tabindex="-1"></button>'].join(""))}n.push('<div class="note-color-row">'+c.join("")+"</div>")}t.html(n.join("")),t.find(".note-color-btn").each((function(){e()(this).data("_lite_tooltip",new Re(e()(this),{container:o.container}))}))})),eo=function(t,o){return Ve({className:"note-color",children:[qe({className:"note-current-color-button",contents:t.title,tooltip:t.lang.color.recent,click:t.currentClick,callback:function(t){var e=t.find(".note-recent-color");"foreColor"!==o&&(e.css("background-color","#FFFF00"),t.attr("data-backColor","#FFFF00"))}}),qe({className:"dropdown-toggle",contents:lo("note-icon-caret"),tooltip:t.lang.color.more,data:{toggle:"dropdown"}}),_e({items:["<div>",'<div class="note-btn-group btn-background-color">','<div class="note-palette-title">'+t.lang.color.background+"</div>","<div>",'<button type="button" class="note-color-reset note-btn note-btn-block" data-event="backColor" data-value="transparent">',t.lang.color.transparent,"</button>","</div>",'<div class="note-holder" data-event="backColor"></div>','<div class="btn-sm">','<input type="color" id="html5bcp" class="note-btn btn-default" value="#21104A" style="width:100%;" data-value="cp">','<button type="button" class="note-color-reset btn" data-event="backColor" data-value="cpbackColor">',t.lang.color.cpSelect,"</button>","</div>","</div>",'<div class="note-btn-group btn-foreground-color">','<div class="note-palette-title">'+t.lang.color.foreground+"</div>","<div>",'<button type="button" class="note-color-reset note-btn note-btn-block" data-event="removeFormat" data-value="foreColor">',t.lang.color.resetToDefault,"</button>","</div>",'<div class="note-holder" data-event="foreColor"></div>','<div class="btn-sm">','<input type="color" id="html5fcp" class="note-btn btn-default" value="#21104A" style="width:100%;" data-value="cp">','<button type="button" class="note-color-reset btn" data-event="foreColor" data-value="cpforeColor">',t.lang.color.cpSelect,"</button>","</div>","</div>","</div>"].join(""),callback:function(n){n.find(".note-holder").each((function(){var o=e()(this);o.append(to({colors:t.colors,eventName:o.data("event")}).render())})),"fore"===o?(n.find(".btn-background-color").hide(),n.css({"min-width":"210px"})):"back"===o&&(n.find(".btn-foreground-color").hide(),n.css({"min-width":"210px"}))},click:function(n){var i=e()(n.target),r=i.data("event"),a=i.data("value"),s=document.getElementById("html5fcp").value,l=document.getElementById("html5bcp").value;if("cp"===a?n.stopPropagation():"cpbackColor"===a?a=l:"cpforeColor"===a&&(a=s),r&&a){var c="backColor"===r?"background-color":"color",u=i.closest(".note-color").find(".note-recent-color"),d=i.closest(".note-color").find(".note-current-color-button");u.css(c,a),d.attr("data-"+r,a),"fore"===o?t.itemClick("foreColor",a):"back"===o?t.itemClick("backColor",a):t.itemClick(r,a)}}})]}).render()},oo=Ie('<div class="note-modal" aria-hidden="false" tabindex="-1" role="dialog"></div>',(function(t,e){e.fade&&t.addClass("fade"),t.attr({"aria-label":e.title}),t.html(['<div class="note-modal-content">',e.title?'<div class="note-modal-header"><button type="button" class="close" aria-label="Close" aria-hidden="true"><i class="note-icon-close"></i></button><h4 class="note-modal-title">'+e.title+"</h4></div>":"",'<div class="note-modal-body">'+e.body+"</div>",e.footer?'<div class="note-modal-footer">'+e.footer+"</div>":"","</div>"].join("")),t.data("modal",new He(t,e))})),no=function(t){var e='<div class="note-form-group"><label for="note-dialog-video-url-'+t.id+'" class="note-form-label">'+t.lang.video.url+' <small class="text-muted">'+t.lang.video.providers+'</small></label><input id="note-dialog-video-url-'+t.id+'" class="note-video-url note-input" type="text"/></div>',o=['<button type="button" href="#" class="note-btn note-btn-primary note-video-btn disabled" disabled>',t.lang.video.insert,"</button>"].join("");return oo({title:t.lang.video.insert,fade:t.fade,body:e,footer:o}).render()},io=function(t){var e='<div class="note-form-group note-group-select-from-files"><label for="note-dialog-image-file-'+t.id+'" class="note-form-label">'+t.lang.image.selectFromFiles+'</label><input id="note-dialog-image-file-'+t.id+'" class="note-note-image-input note-input" type="file" name="files" accept="image/*" multiple="multiple"/>'+t.imageLimitation+'</div><div class="note-form-group"><label for="note-dialog-image-url-'+t.id+'" class="note-form-label">'+t.lang.image.url+'</label><input id="note-dialog-image-url-'+t.id+'" class="note-image-url note-input" type="text"/></div>',o=['<button href="#" type="button" class="note-btn note-btn-primary note-btn-large note-image-btn disabled" disabled>',t.lang.image.insert,"</button>"].join("");return oo({title:t.lang.image.insert,fade:t.fade,body:e,footer:o}).render()},ro=function(t){var e='<div class="note-form-group"><label for="note-dialog-link-txt-'+t.id+'" class="note-form-label">'+t.lang.link.textToDisplay+'</label><input id="note-dialog-link-txt-'+t.id+'" class="note-link-text note-input" type="text"/></div><div class="note-form-group"><label for="note-dialog-link-url-'+t.id+'" class="note-form-label">'+t.lang.link.url+'</label><input id="note-dialog-link-url-'+t.id+'" class="note-link-url note-input" type="text" value="http://"/></div>'+(t.disableLinkTarget?"":'<div class="checkbox"><label for="note-dialog-link-nw-'+t.id+'"><input id="note-dialog-link-nw-'+t.id+'" type="checkbox" checked> '+t.lang.link.openInNewWindow+"</label></div>")+'<div class="checkbox"><label for="note-dialog-link-up-'+t.id+'"><input id="note-dialog-link-up-'+t.id+'" type="checkbox" checked> '+t.lang.link.useProtocol+"</label></div>",o=['<button href="#" type="button" class="note-btn note-btn-primary note-link-btn disabled" disabled>',t.lang.link.insert,"</button>"].join("");return oo({className:"link-dialog",title:t.lang.link.insert,fade:t.fade,body:e,footer:o}).render()},ao=Ie(['<div class="note-popover bottom">','<div class="note-popover-arrow"></div>','<div class="popover-content note-children-container"></div>',"</div>"].join(""),(function(t,e){var o=void 0!==e.direction?e.direction:"bottom";t.addClass(o).hide(),e.hideArrow&&t.find(".note-popover-arrow").hide()})),so=Ie('<div class="checkbox"></div>',(function(t,e){t.html(["<label"+(e.id?' for="note-'+e.id+'"':"")+">",'<input role="checkbox" type="checkbox"'+(e.id?' id="note-'+e.id+'"':""),e.checked?" checked":"",' aria-checked="'+(e.checked?"true":"false")+'"/>',e.text?e.text:"","</label>"].join(""))})),lo=function(t,e){return t.match(/^</)?t:"<"+(e=e||"i")+' class="'+t+'"></'+e+">"};e().summernote=e().extend(e().summernote,{ui_template:function(t){return{editor:Be,toolbar:ze,editingArea:Me,codable:Oe,editable:je,statusbar:Ue,airEditor:We,airEditable:Ke,buttonGroup:Ve,button:qe,dropdown:_e,dropdownCheck:Ge,dropdownButton:Ze,dropdownButtonContents:Ye,dropdownCheckButton:Xe,paragraphDropdownButton:Qe,tableDropdownButton:Je,colorDropdownButton:eo,palette:to,dialog:oo,videoDialog:no,imageDialog:io,linkDialog:ro,popover:ao,checkbox:so,icon:lo,options:t,toggleBtn:function(t,e){t.toggleClass("disabled",!e),t.attr("disabled",!e)},toggleBtnActive:function(t,e){t.toggleClass("active",e)},check:function(t,e){t.find(".checked").removeClass("checked"),t.find('[data-value="'+e+'"]').addClass("checked")},onDialogShown:function(t,e){t.one("note.modal.show",e)},onDialogHidden:function(t,e){t.one("note.modal.hide",e)},showDialog:function(t){t.data("modal").show()},hideDialog:function(t){t.data("modal").hide()},getPopoverContent:function(t){return t.find(".note-popover-content")},getDialogBody:function(t){return t.find(".note-modal-body")},createLayout:function(e){var o=(t.airMode?We([Me([Oe(),Ke()])]):"bottom"===t.toolbarPosition?Be([Me([Oe(),je()]),ze(),Ue()]):Be([ze(),Me([Oe(),je()]),Ue()])).render();return o.insertAfter(e),{note:e,editor:o,toolbar:o.find(".note-toolbar"),editingArea:o.find(".note-editing-area"),editable:o.find(".note-editable"),codable:o.find(".note-codable"),statusbar:o.find(".note-statusbar")}},removeLayout:function(t,e){t.html(e.editable.html()),e.editor.remove(),t.off("summernote"),t.show()}}},interface:"lite"})})(),i})()}));
2881099/FreeSql.AdminLTE
23,436
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-bs4.css
/*! * * Super simple WYSIWYG editor v0.8.20 * https://summernote.org * * * Copyright 2013- Alan Hong and contributors * Summernote may be freely distributed under the MIT license. * * Date: 2021-10-14T21:15Z * */ @font-face { font-family: "summernote"; font-style: normal; font-weight: 400; font-display: auto; src: url("./font/summernote.eot?#iefix") format("embedded-opentype"), url("./font/summernote.woff2") format("woff2"), url("./font/summernote.woff") format("woff"), url("./font/summernote.ttf") format("truetype"); } [class^=note-icon]:before, [class*=" note-icon"]:before { display: inline-block; font-family: "summernote"; font-style: normal; font-size: inherit; text-decoration: inherit; text-rendering: auto; text-transform: none; vertical-align: middle; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; speak: none; } .note-icon-fw { text-align: center; width: 1.25em; } .note-icon-border { border: solid 0.08em #eee; border-radius: 0.1em; padding: 0.2em 0.25em 0.15em; } .note-icon-pull-left { float: left; } .note-icon-pull-right { float: right; } .note-icon.note-icon-pull-left { margin-right: 0.3em; } .note-icon.note-icon-pull-right { margin-left: 0.3em; } .note-icon-align::before { content: "\ea01"; } .note-icon-align-center::before { content: "\ea02"; } .note-icon-align-indent::before { content: "\ea03"; } .note-icon-align-justify::before { content: "\ea04"; } .note-icon-align-left::before { content: "\ea05"; } .note-icon-align-outdent::before { content: "\ea06"; } .note-icon-align-right::before { content: "\ea07"; } .note-icon-arrow-circle-down::before { content: "\ea08"; } .note-icon-arrow-circle-left::before { content: "\ea09"; } .note-icon-arrow-circle-right::before { content: "\ea0a"; } .note-icon-arrow-circle-up::before { content: "\ea0b"; } .note-icon-arrows-alt::before { content: "\ea0c"; } .note-icon-arrows-h::before { content: "\ea0d"; } .note-icon-arrows-v::before { content: "\ea0e"; } .note-icon-bold::before { content: "\ea0f"; } .note-icon-caret::before { content: "\ea10"; } .note-icon-chain-broken::before { content: "\ea11"; } .note-icon-circle::before { content: "\ea12"; } .note-icon-close::before { content: "\ea13"; } .note-icon-code::before { content: "\ea14"; } .note-icon-col-after::before { content: "\ea15"; } .note-icon-col-before::before { content: "\ea16"; } .note-icon-col-remove::before { content: "\ea17"; } .note-icon-eraser::before { content: "\ea18"; } .note-icon-float-left::before { content: "\ea19"; } .note-icon-float-none::before { content: "\ea1a"; } .note-icon-float-right::before { content: "\ea1b"; } .note-icon-font::before { content: "\ea1c"; } .note-icon-frame::before { content: "\ea1d"; } .note-icon-italic::before { content: "\ea1e"; } .note-icon-link::before { content: "\ea1f"; } .note-icon-magic::before { content: "\ea20"; } .note-icon-menu-check::before { content: "\ea21"; } .note-icon-minus::before { content: "\ea22"; } .note-icon-orderedlist::before { content: "\ea23"; } .note-icon-pencil::before { content: "\ea24"; } .note-icon-picture::before { content: "\ea25"; } .note-icon-question::before { content: "\ea26"; } .note-icon-redo::before { content: "\ea27"; } .note-icon-rollback::before { content: "\ea28"; } .note-icon-row-above::before { content: "\ea29"; } .note-icon-row-below::before { content: "\ea2a"; } .note-icon-row-remove::before { content: "\ea2b"; } .note-icon-special-character::before { content: "\ea2c"; } .note-icon-square::before { content: "\ea2d"; } .note-icon-strikethrough::before { content: "\ea2e"; } .note-icon-subscript::before { content: "\ea2f"; } .note-icon-summernote::before { content: "\ea30"; } .note-icon-superscript::before { content: "\ea31"; } .note-icon-table::before { content: "\ea32"; } .note-icon-text-height::before { content: "\ea33"; } .note-icon-trash::before { content: "\ea34"; } .note-icon-underline::before { content: "\ea35"; } .note-icon-undo::before { content: "\ea36"; } .note-icon-unorderedlist::before { content: "\ea37"; } .note-icon-video::before { content: "\ea38"; } /* Theme Variables ------------------------------------------ */ /* Layout ------------------------------------------ */ .note-editor { position: relative; } .note-editor .note-dropzone { position: absolute; display: none; z-index: 100; color: lightskyblue; background-color: #fff; opacity: 0.95; } .note-editor .note-dropzone .note-dropzone-message { display: table-cell; vertical-align: middle; text-align: center; font-size: 28px; font-weight: 700; } .note-editor .note-dropzone.hover { color: #098ddf; } .note-editor.dragover .note-dropzone { display: table; } .note-editor .note-editing-area { position: relative; } .note-editor .note-editing-area .note-editable { outline: none; } .note-editor .note-editing-area .note-editable sup { vertical-align: super; } .note-editor .note-editing-area .note-editable sub { vertical-align: sub; } .note-editor .note-editing-area .note-editable img.note-float-left { margin-right: 10px; } .note-editor .note-editing-area .note-editable img.note-float-right { margin-left: 10px; } /* Frame mode layout ------------------------------------------ */ .note-editor.note-frame, .note-editor.note-airframe { border: 1px solid #00000032; } .note-editor.note-frame.codeview .note-editing-area .note-editable, .note-editor.note-airframe.codeview .note-editing-area .note-editable { display: none; } .note-editor.note-frame.codeview .note-editing-area .note-codable, .note-editor.note-airframe.codeview .note-editing-area .note-codable { display: block; } .note-editor.note-frame .note-editing-area, .note-editor.note-airframe .note-editing-area { overflow: hidden; } .note-editor.note-frame .note-editing-area .note-editable, .note-editor.note-airframe .note-editing-area .note-editable { padding: 10px; overflow: auto; word-wrap: break-word; } .note-editor.note-frame .note-editing-area .note-editable[contenteditable=false], .note-editor.note-airframe .note-editing-area .note-editable[contenteditable=false] { background-color: #8080801d; } .note-editor.note-frame .note-editing-area .note-codable, .note-editor.note-airframe .note-editing-area .note-codable { display: none; width: 100%; padding: 10px; border: none; box-shadow: none; font-family: Menlo, Monaco, monospace, sans-serif; font-size: 14px; color: #ccc; background-color: #222; resize: none; outline: none; -ms-box-sizing: border-box; box-sizing: border-box; border-radius: 0; margin-bottom: 0; } .note-editor.note-frame.fullscreen, .note-editor.note-airframe.fullscreen { position: fixed; top: 0; left: 0; width: 100% !important; z-index: 1050; } .note-editor.note-frame.fullscreen .note-resizebar, .note-editor.note-airframe.fullscreen .note-resizebar { display: none; } .note-editor.note-frame .note-status-output, .note-editor.note-airframe .note-status-output { display: block; width: 100%; font-size: 14px; line-height: 1.42857143; height: 20px; margin-bottom: 0; color: #000; border: 0; border-top: 1px solid #e2e2e2; } .note-editor.note-frame .note-status-output:empty, .note-editor.note-airframe .note-status-output:empty { height: 0; border-top: 0 solid transparent; } .note-editor.note-frame .note-status-output .pull-right, .note-editor.note-airframe .note-status-output .pull-right { float: right !important; } .note-editor.note-frame .note-status-output .text-muted, .note-editor.note-airframe .note-status-output .text-muted { color: #777; } .note-editor.note-frame .note-status-output .text-primary, .note-editor.note-airframe .note-status-output .text-primary { color: #286090; } .note-editor.note-frame .note-status-output .text-success, .note-editor.note-airframe .note-status-output .text-success { color: #3c763d; } .note-editor.note-frame .note-status-output .text-info, .note-editor.note-airframe .note-status-output .text-info { color: #31708f; } .note-editor.note-frame .note-status-output .text-warning, .note-editor.note-airframe .note-status-output .text-warning { color: #8a6d3b; } .note-editor.note-frame .note-status-output .text-danger, .note-editor.note-airframe .note-status-output .text-danger { color: #a94442; } .note-editor.note-frame .note-status-output .alert, .note-editor.note-airframe .note-status-output .alert { margin: -7px 0 0 0; padding: 7px 10px 2px 10px; border-radius: 0; color: #000; background-color: #f5f5f5; } .note-editor.note-frame .note-status-output .alert .note-icon, .note-editor.note-airframe .note-status-output .alert .note-icon { margin-right: 5px; } .note-editor.note-frame .note-status-output .alert-success, .note-editor.note-airframe .note-status-output .alert-success { color: #3c763d !important; background-color: #dff0d8 !important; } .note-editor.note-frame .note-status-output .alert-info, .note-editor.note-airframe .note-status-output .alert-info { color: #31708f !important; background-color: #d9edf7 !important; } .note-editor.note-frame .note-status-output .alert-warning, .note-editor.note-airframe .note-status-output .alert-warning { color: #8a6d3b !important; background-color: #fcf8e3 !important; } .note-editor.note-frame .note-status-output .alert-danger, .note-editor.note-airframe .note-status-output .alert-danger { color: #a94442 !important; background-color: #f2dede !important; } .note-editor.note-frame .note-statusbar, .note-editor.note-airframe .note-statusbar { background-color: #8080801d; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top: 1px solid #00000032; } .note-editor.note-frame .note-statusbar .note-resizebar, .note-editor.note-airframe .note-statusbar .note-resizebar { padding-top: 1px; height: 9px; width: 100%; cursor: ns-resize; } .note-editor.note-frame .note-statusbar .note-resizebar .note-icon-bar, .note-editor.note-airframe .note-statusbar .note-resizebar .note-icon-bar { width: 20px; margin: 1px auto; border-top: 1px solid #00000032; } .note-editor.note-frame .note-statusbar.locked .note-resizebar, .note-editor.note-airframe .note-statusbar.locked .note-resizebar { cursor: default; } .note-editor.note-frame .note-statusbar.locked .note-resizebar .note-icon-bar, .note-editor.note-airframe .note-statusbar.locked .note-resizebar .note-icon-bar { display: none; } .note-editor.note-frame .note-placeholder, .note-editor.note-airframe .note-placeholder { padding: 10px; } .note-editor.note-airframe { border: 0; } .note-editor.note-airframe .note-editing-area .note-editable { padding: 0; } /* Popover ------------------------------------------ */ .note-popover.popover { display: none; max-width: none; } .note-popover.popover .popover-content a { display: inline-block; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle; } .note-popover.popover .arrow { left: 20px !important; } /* Popover and Toolbar (Button container) ------------------------------------------ */ .note-toolbar { position: relative; } .note-popover .popover-content, .note-editor .note-toolbar { margin: 0; padding: 0 0 5px 5px; } .note-popover .popover-content > .note-btn-group, .note-editor .note-toolbar > .note-btn-group { margin-top: 5px; margin-left: 0; margin-right: 5px; } .note-popover .popover-content .note-btn-group .note-table, .note-editor .note-toolbar .note-btn-group .note-table { min-width: 0; padding: 5px; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker { font-size: 18px; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher { position: absolute !important; z-index: 3; width: 10em; height: 10em; cursor: pointer; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted { position: relative !important; z-index: 1; width: 5em; height: 5em; background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIj4+Pjp6ekKlAqjAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKhmnaJzPAAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted { position: absolute !important; z-index: 2; width: 1em; height: 1em; background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIjd6vvD2f9LKLW+AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKwNDEVT0AAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat; } .note-popover .popover-content .note-style .dropdown-style blockquote, .note-popover .popover-content .note-style .dropdown-style pre, .note-editor .note-toolbar .note-style .dropdown-style blockquote, .note-editor .note-toolbar .note-style .dropdown-style pre { margin: 0; padding: 5px 10px; } .note-popover .popover-content .note-style .dropdown-style h1, .note-popover .popover-content .note-style .dropdown-style h2, .note-popover .popover-content .note-style .dropdown-style h3, .note-popover .popover-content .note-style .dropdown-style h4, .note-popover .popover-content .note-style .dropdown-style h5, .note-popover .popover-content .note-style .dropdown-style h6, .note-popover .popover-content .note-style .dropdown-style p, .note-editor .note-toolbar .note-style .dropdown-style h1, .note-editor .note-toolbar .note-style .dropdown-style h2, .note-editor .note-toolbar .note-style .dropdown-style h3, .note-editor .note-toolbar .note-style .dropdown-style h4, .note-editor .note-toolbar .note-style .dropdown-style h5, .note-editor .note-toolbar .note-style .dropdown-style h6, .note-editor .note-toolbar .note-style .dropdown-style p { margin: 0; padding: 0; } .note-popover .popover-content .note-color-all .note-dropdown-menu, .note-editor .note-toolbar .note-color-all .note-dropdown-menu { min-width: 337px; } .note-popover .popover-content .note-color .dropdown-toggle, .note-editor .note-toolbar .note-color .dropdown-toggle { width: 20px; padding-left: 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette { display: inline-block; margin: 0; width: 160px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette:first-child, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette:first-child { margin: 0 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-palette-title, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-palette-title { font-size: 12px; margin: 2px 7px; text-align: center; border-bottom: 1px solid #eee; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset, .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select { font-size: 11px; margin: 3px; padding: 0 3px; cursor: pointer; width: 100%; border-radius: 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset:hover, .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select:hover, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset:hover, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select:hover { background: #eee; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-row, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-row { height: 20px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select-btn, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select-btn { display: none; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn { border: 1px solid #eee; } .note-popover .popover-content .note-para .note-dropdown-menu, .note-editor .note-toolbar .note-para .note-dropdown-menu { min-width: 228px; padding: 5px; } .note-popover .popover-content .note-para .note-dropdown-menu > div + div, .note-editor .note-toolbar .note-para .note-dropdown-menu > div + div { margin-left: 5px; } .note-popover .popover-content .note-dropdown-menu, .note-editor .note-toolbar .note-dropdown-menu { min-width: 160px; } .note-popover .popover-content .note-dropdown-menu.right, .note-editor .note-toolbar .note-dropdown-menu.right { right: 0; left: auto; } .note-popover .popover-content .note-dropdown-menu.right::before, .note-editor .note-toolbar .note-dropdown-menu.right::before { right: 9px; left: auto !important; } .note-popover .popover-content .note-dropdown-menu.right::after, .note-editor .note-toolbar .note-dropdown-menu.right::after { right: 10px; left: auto !important; } .note-popover .popover-content .note-dropdown-menu.note-check a i, .note-editor .note-toolbar .note-dropdown-menu.note-check a i { color: deepskyblue; visibility: hidden; } .note-popover .popover-content .note-dropdown-menu.note-check a.checked i, .note-editor .note-toolbar .note-dropdown-menu.note-check a.checked i { visibility: visible; } .note-popover .popover-content .note-fontsize-10, .note-editor .note-toolbar .note-fontsize-10 { font-size: 10px; } .note-popover .popover-content .note-color-palette, .note-editor .note-toolbar .note-color-palette { line-height: 1; } .note-popover .popover-content .note-color-palette div .note-color-btn, .note-editor .note-toolbar .note-color-palette div .note-color-btn { width: 20px; height: 20px; padding: 0; margin: 0; border: 0; border-radius: 0; } .note-popover .popover-content .note-color-palette div .note-color-btn:hover, .note-editor .note-toolbar .note-color-palette div .note-color-btn:hover { transform: scale(1.2); transition: all 0.2s; } /* Dialog ------------------------------------------ */ .note-modal .modal-dialog { outline: 0; border-radius: 5px; box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5); } .note-modal .form-group { margin-left: 0; margin-right: 0; } .note-modal .note-modal-form { margin: 0; } .note-modal .note-image-dialog .note-dropzone { min-height: 100px; font-size: 30px; line-height: 4; color: lightgray; text-align: center; border: 4px dashed lightgray; margin-bottom: 10px; } @-moz-document url-prefix() { .note-modal .note-image-input { height: auto; } } /* Placeholder ------------------------------------------ */ .note-placeholder { position: absolute; display: none; color: gray; } /* Handle ------------------------------------------ */ .note-handle .note-control-selection { position: absolute; display: none; border: 1px solid #000; } .note-handle .note-control-selection > div { position: absolute; } .note-handle .note-control-selection .note-control-selection-bg { width: 100%; height: 100%; background-color: #000; -webkit-opacity: 0.3; -khtml-opacity: 0.3; -moz-opacity: 0.3; opacity: 0.3; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=30); filter: alpha(opacity=30); } .note-handle .note-control-selection .note-control-handle, .note-handle .note-control-selection .note-control-sizing, .note-handle .note-control-selection .note-control-holder { width: 7px; height: 7px; border: 1px solid #000; } .note-handle .note-control-selection .note-control-sizing { background-color: #000; } .note-handle .note-control-selection .note-control-nw { top: -5px; left: -5px; border-right: none; border-bottom: none; } .note-handle .note-control-selection .note-control-ne { top: -5px; right: -5px; border-bottom: none; border-left: none; } .note-handle .note-control-selection .note-control-sw { bottom: -5px; left: -5px; border-top: none; border-right: none; } .note-handle .note-control-selection .note-control-se { right: -5px; bottom: -5px; cursor: se-resize; } .note-handle .note-control-selection .note-control-se.note-control-holder { cursor: default; border-top: none; border-left: none; } .note-handle .note-control-selection .note-control-selection-info { right: 0; bottom: 0; padding: 5px; margin: 5px; color: #fff; background-color: #000; font-size: 12px; border-radius: 5px; -webkit-opacity: 0.7; -khtml-opacity: 0.7; -moz-opacity: 0.7; opacity: 0.7; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=70); filter: alpha(opacity=70); } .note-hint-popover { min-width: 100px; padding: 2px; } .note-hint-popover .popover-content { padding: 3px; max-height: 150px; overflow: auto; } .note-hint-popover .popover-content .note-hint-group .note-hint-item { display: block !important; padding: 3px; } .note-hint-popover .popover-content .note-hint-group .note-hint-item.active, .note-hint-popover .popover-content .note-hint-group .note-hint-item:hover { display: block; clear: both; font-weight: 400; line-height: 1.4; color: white; white-space: nowrap; text-decoration: none; background-color: #428bca; outline: 0; cursor: pointer; } /* Handle ------------------------------------------ */ html .note-fullscreen-body, body .note-fullscreen-body { overflow: hidden !important; } .note-toolbar { background: #8080801d; } .note-btn-group .note-btn { border-color: #00000032; padding: 0.28rem 0.65rem; font-size: 13px; } /*# sourceMappingURL=summernote-bs4.css.map*/
294coder/Efficient-MIF
12,324
utils/ema_utils/ema.py
from __future__ import annotations from typing import Mapping, Set, Tuple from copy import deepcopy from functools import partial import logging import torch from torch import nn, Tensor import torch.distributed from torch.nn import Module import accelerate from accelerate.utils import extract_model_from_parallel logger = logging.getLogger('utils.EMA') def exists(val): return val is not None def inplace_copy(tgt: Tensor, src: Tensor, *, auto_move_device = False): if auto_move_device: src = src.to(tgt.device) tgt.copy_(src) def inplace_lerp(tgt: Tensor, src: Tensor, weight, *, auto_move_device = False): if auto_move_device: src = src.to(tgt.device) tgt.lerp_(src, weight) def is_model_parallel_initialized(model): return accelerate.PartialState().use_distributed # return torch.distributed.is_initialized() or isinstance(model, torch.nn.parallel.DistributedDataParallel) class EMA(Module): """ Implements exponential moving average shadowing for your model. Utilizes an inverse decay schedule to manage longer term training runs. By adjusting the power, you can control how fast EMA will ramp up to your specified beta. @crowsonkb's notes on EMA Warmup: If gamma=1 and power=1, implements a simple average. gamma=1, power=2/3 are good values for models you plan to train for a million or more steps (reaches decay factor 0.999 at 31.6K steps, 0.9999 at 1M steps), gamma=1, power=3/4 for models you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999 at 215.4k steps). Args: inv_gamma (float): Inverse multiplicative factor of EMA warmup. Default: 1. power (float): Exponential factor of EMA warmup. Default: 2/3. min_value (float): The minimum EMA decay rate. Default: 0. """ def __init__( self, model: Module, ema_model: Module | None = None, # if your model has lazylinears or other types of non-deepcopyable modules, you can pass in your own ema model beta = 0.9999, update_after_step = 100, update_every = 10, inv_gamma = 1.0, power = 2 / 3, min_value = 0.0, param_or_buffer_names_no_ema: Set[str] = set(), ignore_names: Set[str] = set(), ignore_startswith_names: Set[str] = set(), include_online_model = True, # set this to False if you do not wish for the online model to be saved along with the ema model (managed externally) allow_different_devices = False, # if the EMA model is on a different device (say CPU), automatically move the tensor use_foreach = False, forward_method_names: Tuple[str, ...] = (), state_include_online_model: bool = False, ): super().__init__() self.beta = beta self.is_frozen = beta == 1. # whether to include the online model within the module tree, so that state_dict also saves it self.include_online_model = include_online_model self.state_include_online_model = state_include_online_model and include_online_model if include_online_model: self.online_model = model else: self.online_model = [model] # hack # ema model self.ema_model = ema_model if not exists(self.ema_model): try: self.ema_model = deepcopy(model) except Exception as e: print(f'Error: While trying to deepcopy model: {e}') print('Your model was not copyable. Please make sure you are not using any LazyLinear') exit() for p in self.ema_model.parameters(): p.detach_() # forwarding methods for forward_method_name in forward_method_names: fn = getattr(self.ema_model, forward_method_name) setattr(self, forward_method_name, fn) # parameter and buffer names self.parameter_names = {name for name, param in self.ema_model.named_parameters() if torch.is_floating_point(param) or torch.is_complex(param)} self.buffer_names = {name for name, buffer in self.ema_model.named_buffers() if torch.is_floating_point(buffer) or torch.is_complex(buffer)} # tensor update functions self.inplace_copy = partial(inplace_copy, auto_move_device = allow_different_devices) self.inplace_lerp = partial(inplace_lerp, auto_move_device = allow_different_devices) # updating hyperparameters self.update_every = update_every self.update_after_step = update_after_step self.inv_gamma = inv_gamma self.power = power self.min_value = min_value assert isinstance(param_or_buffer_names_no_ema, (set, list)) self.param_or_buffer_names_no_ema = param_or_buffer_names_no_ema # parameter or buffer self.ignore_names = ignore_names self.ignore_startswith_names = ignore_startswith_names # whether to manage if EMA model is kept on a different device self.allow_different_devices = allow_different_devices # whether to use foreach if use_foreach: assert hasattr(torch, '_foreach_lerp_') and hasattr(torch, '_foreach_copy_'), 'your version of torch does not have the prerequisite foreach functions' self.use_foreach = use_foreach # init and step states self.register_buffer('initted', torch.tensor(False)) self.register_buffer('step', torch.tensor(0)) @property def model(self): return self.online_model if self.include_online_model else self.online_model[0] def eval(self): return self.ema_model.eval() def restore_ema_model_device(self): device = self.initted.device self.ema_model.to(device) def get_params_iter(self, model): for name, param in model.named_parameters(): if name not in self.parameter_names: continue yield name, param def get_buffers_iter(self, model): for name, buffer in model.named_buffers(): if name not in self.buffer_names: continue yield name, buffer def copy_params_from_model_to_ema(self): copy = self.inplace_copy for (_, ma_params), (_, current_params) in zip(self.get_params_iter(self.ema_model), self.get_params_iter(self.model)): copy(ma_params.data, current_params.data) for (_, ma_buffers), (_, current_buffers) in zip(self.get_buffers_iter(self.ema_model), self.get_buffers_iter(self.model)): copy(ma_buffers.data, current_buffers.data) def copy_params_from_ema_to_model(self): copy = self.inplace_copy for (_, ma_params), (_, current_params) in zip(self.get_params_iter(self.ema_model), self.get_params_iter(self.model)): copy(current_params.data, ma_params.data) for (_, ma_buffers), (_, current_buffers) in zip(self.get_buffers_iter(self.ema_model), self.get_buffers_iter(self.model)): copy(current_buffers.data, ma_buffers.data) def get_current_decay(self): epoch = (self.step - self.update_after_step - 1).clamp(min = 0.) value = 1 - (1 + epoch / self.inv_gamma) ** - self.power if epoch.item() <= 0: return 0. return value.clamp(min = self.min_value, max = self.beta).item() def update(self): step = self.step.item() self.step += 1 if (step % self.update_every) != 0: return if step <= self.update_after_step: self.copy_params_from_model_to_ema() return if not self.initted.item(): self.copy_params_from_model_to_ema() self.initted.data.copy_(torch.tensor(True)) self.update_moving_average(self.ema_model, self.model) @torch.no_grad() def update_moving_average(self, ma_model, current_model): if self.is_frozen: return current_decay = self.get_current_decay() # store all source and target tensors to copy or lerp tensors_to_copy = [] tensors_to_lerp = [] # loop through parameters for (name, current_params), (_, ma_params) in zip(self.get_params_iter(current_model), self.get_params_iter(ma_model)): if name in self.ignore_names: continue if any([name.startswith(prefix) for prefix in self.ignore_startswith_names]): continue if name in self.param_or_buffer_names_no_ema: tensors_to_copy.append((ma_params.data, current_params.data)) continue tensors_to_lerp.append((ma_params.data, current_params.data)) # loop through buffers for (name, current_buffer), (_, ma_buffer) in zip(self.get_buffers_iter(current_model), self.get_buffers_iter(ma_model)): if name in self.ignore_names: continue if any([name.startswith(prefix) for prefix in self.ignore_startswith_names]): continue if name in self.param_or_buffer_names_no_ema: tensors_to_copy.append((ma_buffer.data, current_buffer.data)) continue tensors_to_lerp.append((ma_buffer.data, current_buffer.data)) # execute inplace copy or lerp if not self.use_foreach: for tgt, src in tensors_to_copy: self.inplace_copy(tgt, src) for tgt, src in tensors_to_lerp: self.inplace_lerp(tgt, src, 1. - current_decay) else: # use foreach if available and specified if self.allow_different_devices: tensors_to_copy = [(tgt, src.to(tgt.device)) for tgt, src in tensors_to_copy] tensors_to_lerp = [(tgt, src.to(tgt.device)) for tgt, src in tensors_to_lerp] if len(tensors_to_copy) > 0: tgt_copy, src_copy = zip(*tensors_to_copy) torch._foreach_copy_(tgt_copy, src_copy) if len(tensors_to_lerp) > 0: tgt_lerp, src_lerp = zip(*tensors_to_lerp) torch._foreach_lerp_(tgt_lerp, src_lerp, 1. - current_decay) def __call__(self, *args, **kwargs): return self.ema_model(*args, **kwargs) ## for accelerator state loading def state_dict(self): if self.state_include_online_model: if is_model_parallel_initialized(self.online_model): ema_model_state_dict = extract_model_from_parallel(self.ema_model).state_dict() online_model_state_dict = extract_model_from_parallel(self.online_model).state_dict() return {'ema_model': ema_model_state_dict, 'online_model': online_model_state_dict} return {'ema_model': self.ema_model.state_dict(), 'online_model': self.online_model.state_dict()} else: if torch.distributed.is_initialized() or isinstance(self.online_model, torch.nn.parallel.DistributedDataParallel): return extract_model_from_parallel(self.ema_model).state_dict() return self.ema_model.state_dict() def load_state_dict(self, state_dict): # saved online_model and ema_model logger.info('load ema_model state dict') if self.state_include_online_model and state_dict.get('online_model', None) is not None: if is_model_parallel_initialized(self.online_model): self.ema_model.module.load_state_dict(state_dict['ema_model']) self.online_model.module.load_state_dict(state_dict['online_model']) else: self.online_model.load_state_dict(state_dict['online_model']) self.ema_model.load_state_dict(state_dict['ema_model']) logger.info('load online_model and ema_model state dict') # only has ema_model else: if is_model_parallel_initialized(self.online_model): self.ema_model.module.load_state_dict(state_dict) else: self.ema_model.load_state_dict(state_dict) logger.warning('No online_model is loaded, please make sure you have set `online_model`!')
2881099/FreeSql.AdminLTE
345,564
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-lite.js
/*! * * Super simple WYSIWYG editor v0.8.20 * https://summernote.org * * * Copyright 2013- Alan Hong and contributors * Summernote may be freely distributed under the MIT license. * * Date: 2021-10-14T21:15Z * */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("jQuery")); else if(typeof define === 'function' && define.amd) define(["jQuery"], factory); else { var a = typeof exports === 'object' ? factory(require("jQuery")) : factory(root["jQuery"]); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(self, function(__WEBPACK_EXTERNAL_MODULE__1145__) { return /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ 9770: /***/ ((__unused_webpack_module, __unused_webpack___webpack_exports__, __webpack_require__) => { /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1145); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__); (jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote) = (jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote) || { lang: {} }; jquery__WEBPACK_IMPORTED_MODULE_0___default().extend((jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote.lang), { 'en-US': { font: { bold: 'Bold', italic: 'Italic', underline: 'Underline', clear: 'Remove Font Style', height: 'Line Height', name: 'Font Family', strikethrough: 'Strikethrough', subscript: 'Subscript', superscript: 'Superscript', size: 'Font Size', sizeunit: 'Font Size Unit' }, image: { image: 'Picture', insert: 'Insert Image', resizeFull: 'Resize full', resizeHalf: 'Resize half', resizeQuarter: 'Resize quarter', resizeNone: 'Original size', floatLeft: 'Float Left', floatRight: 'Float Right', floatNone: 'Remove float', shapeRounded: 'Shape: Rounded', shapeCircle: 'Shape: Circle', shapeThumbnail: 'Shape: Thumbnail', shapeNone: 'Shape: None', dragImageHere: 'Drag image or text here', dropImage: 'Drop image or Text', selectFromFiles: 'Select from files', maximumFileSize: 'Maximum file size', maximumFileSizeError: 'Maximum file size exceeded.', url: 'Image URL', remove: 'Remove Image', original: 'Original' }, video: { video: 'Video', videoLink: 'Video Link', insert: 'Insert Video', url: 'Video URL', providers: '(YouTube, Google Drive, Vimeo, Vine, Instagram, DailyMotion, Youku, Peertube)' }, link: { link: 'Link', insert: 'Insert Link', unlink: 'Unlink', edit: 'Edit', textToDisplay: 'Text to display', url: 'To what URL should this link go?', openInNewWindow: 'Open in new window', useProtocol: 'Use default protocol' }, table: { table: 'Table', addRowAbove: 'Add row above', addRowBelow: 'Add row below', addColLeft: 'Add column left', addColRight: 'Add column right', delRow: 'Delete row', delCol: 'Delete column', delTable: 'Delete table' }, hr: { insert: 'Insert Horizontal Rule' }, style: { style: 'Style', p: 'Normal', blockquote: 'Quote', pre: 'Code', h1: 'Header 1', h2: 'Header 2', h3: 'Header 3', h4: 'Header 4', h5: 'Header 5', h6: 'Header 6' }, lists: { unordered: 'Unordered list', ordered: 'Ordered list' }, options: { help: 'Help', fullscreen: 'Full Screen', codeview: 'Code View' }, paragraph: { paragraph: 'Paragraph', outdent: 'Outdent', indent: 'Indent', left: 'Align left', center: 'Align center', right: 'Align right', justify: 'Justify full' }, color: { recent: 'Recent Color', more: 'More Color', background: 'Background Color', foreground: 'Text Color', transparent: 'Transparent', setTransparent: 'Set transparent', reset: 'Reset', resetToDefault: 'Reset to default', cpSelect: 'Select' }, shortcut: { shortcuts: 'Keyboard shortcuts', close: 'Close', textFormatting: 'Text formatting', action: 'Action', paragraphFormatting: 'Paragraph formatting', documentStyle: 'Document Style', extraKeys: 'Extra keys' }, help: { 'escape': 'Escape', 'insertParagraph': 'Insert Paragraph', 'undo': 'Undo the last command', 'redo': 'Redo the last command', 'tab': 'Tab', 'untab': 'Untab', 'bold': 'Set a bold style', 'italic': 'Set a italic style', 'underline': 'Set a underline style', 'strikethrough': 'Set a strikethrough style', 'removeFormat': 'Clean a style', 'justifyLeft': 'Set left align', 'justifyCenter': 'Set center align', 'justifyRight': 'Set right align', 'justifyFull': 'Set full align', 'insertUnorderedList': 'Toggle unordered list', 'insertOrderedList': 'Toggle ordered list', 'outdent': 'Outdent on current paragraph', 'indent': 'Indent on current paragraph', 'formatPara': 'Change current block\'s format as a paragraph(P tag)', 'formatH1': 'Change current block\'s format as H1', 'formatH2': 'Change current block\'s format as H2', 'formatH3': 'Change current block\'s format as H3', 'formatH4': 'Change current block\'s format as H4', 'formatH5': 'Change current block\'s format as H5', 'formatH6': 'Change current block\'s format as H6', 'insertHorizontalRule': 'Insert horizontal rule', 'linkDialog.show': 'Show Link Dialog' }, history: { undo: 'Undo', redo: 'Redo' }, specialChar: { specialChar: 'SPECIAL CHARACTERS', select: 'Select Special characters' }, output: { noSelection: 'No Selection Made!' } } }); /***/ }), /***/ 1145: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_MODULE__1145__; /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. (() => { // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXTERNAL MODULE: external "jQuery" var external_jQuery_ = __webpack_require__(1145); var external_jQuery_default = /*#__PURE__*/__webpack_require__.n(external_jQuery_); // EXTERNAL MODULE: ./src/lang/summernote-en-US.js var summernote_en_US = __webpack_require__(9770); ;// CONCATENATED MODULE: ./src/js/core/env.js /** * returns whether font is installed or not. * * @param {String} fontName * @return {Boolean} */ var genericFontFamilies = ['sans-serif', 'serif', 'monospace', 'cursive', 'fantasy']; function validFontName(fontName) { return external_jQuery_default().inArray(fontName.toLowerCase(), genericFontFamilies) === -1 ? "'".concat(fontName, "'") : fontName; } function isFontInstalled(fontName) { var testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS'; var testText = 'mmmmmmmmmmwwwww'; var testSize = '200px'; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); context.font = testSize + " '" + testFontName + "'"; var originalWidth = context.measureText(testText).width; context.font = testSize + ' ' + validFontName(fontName) + ', "' + testFontName + '"'; var width = context.measureText(testText).width; return originalWidth !== width; } var userAgent = navigator.userAgent; var isMSIE = /MSIE|Trident/i.test(userAgent); var browserVersion; if (isMSIE) { var matches = /MSIE (\d+[.]\d+)/.exec(userAgent); if (matches) { browserVersion = parseFloat(matches[1]); } matches = /Trident\/.*rv:([0-9]{1,}[.0-9]{0,})/.exec(userAgent); if (matches) { browserVersion = parseFloat(matches[1]); } } var isEdge = /Edge\/\d+/.test(userAgent); var isSupportTouch = 'ontouchstart' in window || navigator.MaxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; // [workaround] IE doesn't have input events for contentEditable // - see: https://goo.gl/4bfIvA var inputEventName = isMSIE ? 'DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted' : 'input'; /** * @class core.env * * Object which check platform and agent * * @singleton * @alternateClassName env */ /* harmony default export */ const env = ({ isMac: navigator.appVersion.indexOf('Mac') > -1, isMSIE: isMSIE, isEdge: isEdge, isFF: !isEdge && /firefox/i.test(userAgent), isPhantom: /PhantomJS/i.test(userAgent), isWebkit: !isEdge && /webkit/i.test(userAgent), isChrome: !isEdge && /chrome/i.test(userAgent), isSafari: !isEdge && /safari/i.test(userAgent) && !/chrome/i.test(userAgent), browserVersion: browserVersion, isSupportTouch: isSupportTouch, isFontInstalled: isFontInstalled, isW3CRangeSupport: !!document.createRange, inputEventName: inputEventName, genericFontFamilies: genericFontFamilies, validFontName: validFontName }); ;// CONCATENATED MODULE: ./src/js/core/func.js /** * @class core.func * * func utils (for high-order func's arg) * * @singleton * @alternateClassName func */ function eq(itemA) { return function (itemB) { return itemA === itemB; }; } function eq2(itemA, itemB) { return itemA === itemB; } function peq2(propName) { return function (itemA, itemB) { return itemA[propName] === itemB[propName]; }; } function ok() { return true; } function fail() { return false; } function not(f) { return function () { return !f.apply(f, arguments); }; } function and(fA, fB) { return function (item) { return fA(item) && fB(item); }; } function func_self(a) { return a; } function invoke(obj, method) { return function () { return obj[method].apply(obj, arguments); }; } var idCounter = 0; /** * reset globally-unique id * */ function resetUniqueId() { idCounter = 0; } /** * generate a globally-unique id * * @param {String} [prefix] */ function uniqueId(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 */ function rect2bnd(rect) { var $document = external_jQuery_default()(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} */ function invertObject(obj) { var inverted = {}; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { inverted[obj[key]] = key; } } return inverted; } /** * @param {String} namespace * @param {String} [prefix] * @return {String} */ function namespaceToCamel(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} */ function debounce(func, wait, immediate) { var timeout; return function () { var context = this; var args = arguments; var later = function later() { timeout = null; if (!immediate) { func.apply(context, args); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; } /** * * @param {String} url * @return {Boolean} */ function isValidUrl(url) { var expression = /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/gi; return expression.test(url); } /* harmony default export */ const func = ({ eq: eq, eq2: eq2, peq2: peq2, ok: ok, fail: fail, self: func_self, not: not, and: and, invoke: invoke, resetUniqueId: resetUniqueId, uniqueId: uniqueId, rect2bnd: rect2bnd, invertObject: invertObject, namespaceToCamel: namespaceToCamel, debounce: debounce, isValidUrl: isValidUrl }); ;// CONCATENATED MODULE: ./src/js/core/lists.js /** * returns the first item of an array. * * @param {Array} array */ function head(array) { return array[0]; } /** * returns the last item of an array. * * @param {Array} array */ function last(array) { return array[array.length - 1]; } /** * returns everything but the last entry of the array. * * @param {Array} array */ function initial(array) { return array.slice(0, array.length - 1); } /** * returns the rest of the items in an array. * * @param {Array} array */ function tail(array) { return array.slice(1); } /** * returns item of array */ function find(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. */ function lists_all(array, pred) { for (var idx = 0, len = array.length; idx < len; idx++) { if (!pred(array[idx])) { return false; } } return true; } /** * returns true if the value is present in the list. */ function contains(array, item) { if (array && array.length && item) { if (array.indexOf) { return array.indexOf(item) !== -1; } else if (array.contains) { // `DOMTokenList` doesn't implement `.indexOf`, but it implements `.contains` return array.contains(item); } } return false; } /** * get sum from a list * * @param {Array} array - array * @param {Function} fn - iterator */ function sum(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, ... */ function from(collection) { var result = []; var length = collection.length; var idx = -1; while (++idx < length) { result[idx] = collection[idx]; } return result; } /** * returns whether list is empty or not */ function isEmpty(array) { return !array || !array.length; } /** * cluster elements by predicate function. * * @param {Array} array - array * @param {Function} fn - predicate function for cluster rule * @param {Array[]} */ function clusterBy(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 */ function compact(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 */ function unique(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 */ function next(array, item) { if (array && array.length && item) { var idx = array.indexOf(item); return idx === -1 ? null : array[idx + 1]; } return null; } /** * returns prev item. * @param {Array} array */ function prev(array, item) { if (array && array.length && item) { var idx = array.indexOf(item); return idx === -1 ? null : array[idx - 1]; } return null; } /** * @class core.list * * list utils * * @singleton * @alternateClassName list */ /* harmony default export */ const lists = ({ head: head, last: last, initial: initial, tail: tail, prev: prev, next: next, find: find, contains: contains, all: lists_all, sum: sum, from: from, isEmpty: isEmpty, clusterBy: clusterBy, compact: compact, unique: unique }); ;// CONCATENATED MODULE: ./src/js/core/dom.js var NBSP_CHAR = String.fromCharCode(160); var ZERO_WIDTH_NBSP_CHAR = "\uFEFF"; /** * @method isEditable * * returns whether node is `note-editable` or not. * * @param {Node} node * @return {Boolean} */ function isEditable(node) { return node && external_jQuery_default()(node).hasClass('note-editable'); } /** * @method isControlSizing * * returns whether node is `note-control-sizing` or not. * * @param {Node} node * @return {Boolean} */ function isControlSizing(node) { return node && external_jQuery_default()(node).hasClass('note-control-sizing'); } /** * @method makePredByNodeName * * returns predicate which judge whether nodeName is same * * @param {String} nodeName * @return {Function} */ function makePredByNodeName(nodeName) { nodeName = nodeName.toUpperCase(); return function (node) { return node && node.nodeName.toUpperCase() === nodeName; }; } /** * @method isText * * * * @param {Node} node * @return {Boolean} true if node's type is text(3) */ function isText(node) { return node && node.nodeType === 3; } /** * @method isElement * * * * @param {Node} node * @return {Boolean} true if node's type is element(1) */ function isElement(node) { return node && node.nodeType === 1; } /** * ex) br, col, embed, hr, img, input, ... * @see http://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements */ function isVoid(node) { return node && /^BR|^IMG|^HR|^IFRAME|^BUTTON|^INPUT|^AUDIO|^VIDEO|^EMBED/.test(node.nodeName.toUpperCase()); } function isPara(node) { if (isEditable(node)) { return false; } // Chrome(v31.0), FF(v25.0.1) use DIV for paragraph return node && /^DIV|^P|^LI|^H[1-7]/.test(node.nodeName.toUpperCase()); } function isHeading(node) { return node && /^H[1-7]/.test(node.nodeName.toUpperCase()); } var isPre = makePredByNodeName('PRE'); var isLi = makePredByNodeName('LI'); function isPurePara(node) { return isPara(node) && !isLi(node); } var isTable = makePredByNodeName('TABLE'); var isData = makePredByNodeName('DATA'); function isInline(node) { return !isBodyContainer(node) && !isList(node) && !isHr(node) && !isPara(node) && !isTable(node) && !isBlockquote(node) && !isData(node); } function isList(node) { return node && /^UL|^OL/.test(node.nodeName.toUpperCase()); } var isHr = makePredByNodeName('HR'); function isCell(node) { return node && /^TD|^TH/.test(node.nodeName.toUpperCase()); } var isBlockquote = makePredByNodeName('BLOCKQUOTE'); function isBodyContainer(node) { return isCell(node) || isBlockquote(node) || isEditable(node); } var isAnchor = makePredByNodeName('A'); function isParaInline(node) { return isInline(node) && !!ancestor(node, isPara); } function isBodyInline(node) { return isInline(node) && !ancestor(node, isPara); } var isBody = makePredByNodeName('BODY'); /** * returns whether nodeB is closest sibling of nodeA * * @param {Node} nodeA * @param {Node} nodeB * @return {Boolean} */ function isClosestSibling(nodeA, nodeB) { return nodeA.nextSibling === nodeB || nodeA.previousSibling === nodeB; } /** * returns array of closest siblings with node * * @param {Node} node * @param {function} [pred] - predicate function * @return {Node[]} */ function withClosestSiblings(node, pred) { pred = pred || func.ok; var siblings = []; if (node.previousSibling && pred(node.previousSibling)) { siblings.push(node.previousSibling); } siblings.push(node); if (node.nextSibling && pred(node.nextSibling)) { siblings.push(node.nextSibling); } return siblings; } /** * blank HTML for cursor position * - [workaround] old IE only works with &nbsp; * - [workaround] IE11 and other browser works with bogus br */ var blankHTML = env.isMSIE && env.browserVersion < 11 ? '&nbsp;' : '<br>'; /** * @method nodeLength * * returns #text's text size or element's childNodes size * * @param {Node} node */ function nodeLength(node) { if (isText(node)) { return node.nodeValue.length; } if (node) { return node.childNodes.length; } return 0; } /** * returns whether deepest child node is empty or not. * * @param {Node} node * @return {Boolean} */ function deepestChildIsEmpty(node) { do { if (node.firstElementChild === null || node.firstElementChild.innerHTML === '') break; } while (node = node.firstElementChild); return dom_isEmpty(node); } /** * returns whether node is empty or not. * * @param {Node} node * @return {Boolean} */ function dom_isEmpty(node) { var len = nodeLength(node); if (len === 0) { return true; } else if (!isText(node) && len === 1 && node.innerHTML === blankHTML) { // ex) <p><br></p>, <span><br></span> return true; } else if (lists.all(node.childNodes, isText) && node.innerHTML === '') { // ex) <p></p>, <span></span> return true; } return false; } /** * padding blankHTML if node is empty (for cursor position) */ function paddingBlankHTML(node) { if (!isVoid(node) && !nodeLength(node)) { node.innerHTML = blankHTML; } } /** * find nearest ancestor predicate hit * * @param {Node} node * @param {Function} pred - predicate function */ function ancestor(node, pred) { while (node) { if (pred(node)) { return node; } if (isEditable(node)) { break; } node = node.parentNode; } return null; } /** * find nearest ancestor only single child blood line and predicate hit * * @param {Node} node * @param {Function} pred - predicate function */ function singleChildAncestor(node, pred) { node = node.parentNode; while (node) { if (nodeLength(node) !== 1) { break; } if (pred(node)) { return node; } if (isEditable(node)) { break; } node = node.parentNode; } return null; } /** * returns new array of ancestor nodes (until predicate hit). * * @param {Node} node * @param {Function} [optional] pred - predicate function */ function listAncestor(node, pred) { pred = pred || func.fail; var ancestors = []; ancestor(node, function (el) { if (!isEditable(el)) { ancestors.push(el); } return pred(el); }); return ancestors; } /** * find farthest ancestor predicate hit */ function lastAncestor(node, pred) { var ancestors = listAncestor(node); return lists.last(ancestors.filter(pred)); } /** * returns common ancestor node between two nodes. * * @param {Node} nodeA * @param {Node} nodeB */ function commonAncestor(nodeA, nodeB) { var ancestors = listAncestor(nodeA); for (var n = nodeB; n; n = n.parentNode) { if (ancestors.indexOf(n) > -1) return n; } return null; // difference document area } /** * listing all previous siblings (until predicate hit). * * @param {Node} node * @param {Function} [optional] pred - predicate function */ function listPrev(node, pred) { pred = pred || func.fail; var nodes = []; while (node) { if (pred(node)) { break; } nodes.push(node); node = node.previousSibling; } return nodes; } /** * listing next siblings (until predicate hit). * * @param {Node} node * @param {Function} [pred] - predicate function */ function listNext(node, pred) { pred = pred || func.fail; var nodes = []; while (node) { if (pred(node)) { break; } nodes.push(node); node = node.nextSibling; } return nodes; } /** * listing descendant nodes * * @param {Node} node * @param {Function} [pred] - predicate function */ function listDescendant(node, pred) { var descendants = []; pred = pred || func.ok; // start DFS(depth first search) with node (function fnWalk(current) { if (node !== current && pred(current)) { descendants.push(current); } for (var idx = 0, len = current.childNodes.length; idx < len; idx++) { fnWalk(current.childNodes[idx]); } })(node); return descendants; } /** * wrap node with new tag. * * @param {Node} node * @param {Node} tagName of wrapper * @return {Node} - wrapper */ function wrap(node, wrapperName) { var parent = node.parentNode; var wrapper = external_jQuery_default()('<' + wrapperName + '>')[0]; parent.insertBefore(wrapper, node); wrapper.appendChild(node); return wrapper; } /** * insert node after preceding * * @param {Node} node * @param {Node} preceding - predicate function */ function insertAfter(node, preceding) { var next = preceding.nextSibling; var parent = preceding.parentNode; if (next) { parent.insertBefore(node, next); } else { parent.appendChild(node); } return node; } /** * append elements. * * @param {Node} node * @param {Collection} aChild */ function appendChildNodes(node, aChild) { external_jQuery_default().each(aChild, function (idx, child) { node.appendChild(child); }); return node; } /** * returns whether boundaryPoint is left edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isLeftEdgePoint(point) { return point.offset === 0; } /** * returns whether boundaryPoint is right edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isRightEdgePoint(point) { return point.offset === nodeLength(point.node); } /** * returns whether boundaryPoint is edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isEdgePoint(point) { return isLeftEdgePoint(point) || isRightEdgePoint(point); } /** * returns whether node is left edge of ancestor or not. * * @param {Node} node * @param {Node} ancestor * @return {Boolean} */ function isLeftEdgeOf(node, ancestor) { while (node && node !== ancestor) { if (position(node) !== 0) { return false; } node = node.parentNode; } return true; } /** * returns whether node is right edge of ancestor or not. * * @param {Node} node * @param {Node} ancestor * @return {Boolean} */ function isRightEdgeOf(node, ancestor) { if (!ancestor) { return false; } while (node && node !== ancestor) { if (position(node) !== nodeLength(node.parentNode) - 1) { return false; } node = node.parentNode; } return true; } /** * returns whether point is left edge of ancestor or not. * @param {BoundaryPoint} point * @param {Node} ancestor * @return {Boolean} */ function isLeftEdgePointOf(point, ancestor) { return isLeftEdgePoint(point) && isLeftEdgeOf(point.node, ancestor); } /** * returns whether point is right edge of ancestor or not. * @param {BoundaryPoint} point * @param {Node} ancestor * @return {Boolean} */ function isRightEdgePointOf(point, ancestor) { return isRightEdgePoint(point) && isRightEdgeOf(point.node, ancestor); } /** * returns offset from parent. * * @param {Node} node */ function position(node) { var offset = 0; while (node = node.previousSibling) { offset += 1; } return offset; } function hasChildren(node) { return !!(node && node.childNodes && node.childNodes.length); } /** * returns previous boundaryPoint * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function prevPoint(point, isSkipInnerOffset) { var node; var offset; if (point.offset === 0) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node); } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset - 1]; offset = nodeLength(node); } else { node = point.node; offset = isSkipInnerOffset ? 0 : point.offset - 1; } return { node: node, offset: offset }; } /** * returns next boundaryPoint * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function nextPoint(point, isSkipInnerOffset) { var node, offset; if (nodeLength(point.node) === point.offset) { if (isEditable(point.node)) { return null; } var nextTextNode = getNextTextNode(point.node); if (nextTextNode) { node = nextTextNode; offset = 0; } else { node = point.node.parentNode; offset = position(point.node) + 1; } } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset]; offset = 0; } else { node = point.node; offset = isSkipInnerOffset ? nodeLength(point.node) : point.offset + 1; } return { node: node, offset: offset }; } /** * returns next boundaryPoint with empty node * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function nextPointWithEmptyNode(point, isSkipInnerOffset) { var node, offset = 0; // if node is empty string node, return current node's sibling. if (dom_isEmpty(point.node)) { if (point.node === null) { return null; } node = point.node.nextSibling; offset = 0; return { node: node, offset: offset }; } if (nodeLength(point.node) === point.offset) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node) + 1; // if next node is editable , return current node's sibling node. if (isEditable(node)) { node = point.node.nextSibling; offset = 0; } } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset]; offset = 0; if (dom_isEmpty(node)) { if (!dom_isEmpty(point.node.nextSibling)) { return { node: point.node.nextSibling, offset: offset }; } return null; } } else { node = point.node; offset = isSkipInnerOffset ? nodeLength(point.node) : point.offset + 1; if (dom_isEmpty(node)) { return null; } } return { node: node, offset: offset }; } /* * returns the next Text node index or 0 if not found. */ function getNextTextNode(actual) { if (!actual.nextSibling) return undefined; if (actual.parent !== actual.nextSibling.parent) return undefined; if (isText(actual.nextSibling)) return actual.nextSibling;else return getNextTextNode(actual.nextSibling); } /** * returns whether pointA and pointB is same or not. * * @param {BoundaryPoint} pointA * @param {BoundaryPoint} pointB * @return {Boolean} */ function isSamePoint(pointA, pointB) { return pointA.node === pointB.node && pointA.offset === pointB.offset; } /** * returns whether point is visible (can set cursor) or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isVisiblePoint(point) { if (isText(point.node) || !hasChildren(point.node) || dom_isEmpty(point.node)) { return true; } var leftNode = point.node.childNodes[point.offset - 1]; var rightNode = point.node.childNodes[point.offset]; if ((!leftNode || isVoid(leftNode)) && (!rightNode || isVoid(rightNode)) || isTable(rightNode)) { return true; } return false; } /** * @method prevPointUtil * * @param {BoundaryPoint} point * @param {Function} pred * @return {BoundaryPoint} */ function prevPointUntil(point, pred) { while (point) { if (pred(point)) { return point; } point = prevPoint(point); } return null; } /** * @method nextPointUntil * * @param {BoundaryPoint} point * @param {Function} pred * @return {BoundaryPoint} */ function nextPointUntil(point, pred) { while (point) { if (pred(point)) { return point; } point = nextPoint(point); } return null; } /** * returns whether point has character or not. * * @param {Point} point * @return {Boolean} */ function isCharPoint(point) { if (!isText(point.node)) { return false; } var ch = point.node.nodeValue.charAt(point.offset - 1); return ch && ch !== ' ' && ch !== NBSP_CHAR; } /** * returns whether point has space or not. * * @param {Point} point * @return {Boolean} */ function isSpacePoint(point) { if (!isText(point.node)) { return false; } var ch = point.node.nodeValue.charAt(point.offset - 1); return ch === ' ' || ch === NBSP_CHAR; } /** * @method walkPoint * * @param {BoundaryPoint} startPoint * @param {BoundaryPoint} endPoint * @param {Function} handler * @param {Boolean} isSkipInnerOffset */ function walkPoint(startPoint, endPoint, handler, isSkipInnerOffset) { var point = startPoint; while (point) { handler(point); if (isSamePoint(point, endPoint)) { break; } var isSkipOffset = isSkipInnerOffset && startPoint.node !== point.node && endPoint.node !== point.node; point = nextPointWithEmptyNode(point, isSkipOffset); } } /** * @method makeOffsetPath * * return offsetPath(array of offset) from ancestor * * @param {Node} ancestor - ancestor node * @param {Node} node */ function makeOffsetPath(ancestor, node) { var ancestors = listAncestor(node, func.eq(ancestor)); return ancestors.map(position).reverse(); } /** * @method fromOffsetPath * * return element from offsetPath(array of offset) * * @param {Node} ancestor - ancestor node * @param {array} offsets - offsetPath */ function fromOffsetPath(ancestor, offsets) { var current = ancestor; for (var i = 0, len = offsets.length; i < len; i++) { if (current.childNodes.length <= offsets[i]) { current = current.childNodes[current.childNodes.length - 1]; } else { current = current.childNodes[offsets[i]]; } } return current; } /** * @method splitNode * * split element or #text * * @param {BoundaryPoint} point * @param {Object} [options] * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false * @param {Boolean} [options.isNotSplitEdgePoint] - default: false * @param {Boolean} [options.isDiscardEmptySplits] - default: false * @return {Node} right node of boundaryPoint */ function splitNode(point, options) { var isSkipPaddingBlankHTML = options && options.isSkipPaddingBlankHTML; var isNotSplitEdgePoint = options && options.isNotSplitEdgePoint; var isDiscardEmptySplits = options && options.isDiscardEmptySplits; if (isDiscardEmptySplits) { isSkipPaddingBlankHTML = true; } // edge case if (isEdgePoint(point) && (isText(point.node) || isNotSplitEdgePoint)) { if (isLeftEdgePoint(point)) { return point.node; } else if (isRightEdgePoint(point)) { return point.node.nextSibling; } } // split #text if (isText(point.node)) { return point.node.splitText(point.offset); } else { var childNode = point.node.childNodes[point.offset]; var clone = insertAfter(point.node.cloneNode(false), point.node); appendChildNodes(clone, listNext(childNode)); if (!isSkipPaddingBlankHTML) { paddingBlankHTML(point.node); paddingBlankHTML(clone); } if (isDiscardEmptySplits) { if (dom_isEmpty(point.node)) { remove(point.node); } if (dom_isEmpty(clone)) { remove(clone); return point.node.nextSibling; } } return clone; } } /** * @method splitTree * * split tree by point * * @param {Node} root - split root * @param {BoundaryPoint} point * @param {Object} [options] * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false * @param {Boolean} [options.isNotSplitEdgePoint] - default: false * @return {Node} right node of boundaryPoint */ function splitTree(root, point, options) { // ex) [#text, <span>, <p>] 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 ? position(node) : nodeLength(parent) }, options); }); } /** * split point * * @param {Point} point * @param {Boolean} isInline * @return {Object} */ function splitPoint(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 = lists.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 }; } function create(nodeName) { return document.createElement(nodeName); } function createText(text) { return document.createTextNode(text); } /** * @method remove * * remove node, (isRemoveChild: remove child or not) * * @param {Node} node * @param {Boolean} isRemoveChild */ function remove(node, isRemoveChild) { if (!node || !node.parentNode) { return; } if (node.removeNode) { return node.removeNode(isRemoveChild); } var parent = node.parentNode; if (!isRemoveChild) { var nodes = []; for (var i = 0, len = node.childNodes.length; i < len; i++) { nodes.push(node.childNodes[i]); } for (var _i = 0, _len = nodes.length; _i < _len; _i++) { parent.insertBefore(nodes[_i], node); } } parent.removeChild(node); } /** * @method removeWhile * * @param {Node} node * @param {Function} pred */ function removeWhile(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 */ function replace(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, lists.from(node.childNodes)); insertAfter(newNode, node); remove(node); return newNode; } var isTextarea = makePredByNodeName('TEXTAREA'); /** * @param {jQuery} $node * @param {Boolean} [stripLinebreaks] - default: false */ function value($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] */ function html($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 = markup.trim(); } return markup; } function posFromPlaceholder(placeholder) { var $placeholder = external_jQuery_default()(placeholder); var pos = $placeholder.offset(); var height = $placeholder.outerHeight(true); // include margin return { left: pos.left, top: pos.top + height }; } function attachEvents($node, events) { Object.keys(events).forEach(function (key) { $node.on(key, events[key]); }); } function detachEvents($node, events) { Object.keys(events).forEach(function (key) { $node.off(key, events[key]); }); } /** * @method isCustomStyleTag * * assert if a node contains a "note-styletag" class, * which implies that's a custom-made style tag node * * @param {Node} an HTML DOM node */ function isCustomStyleTag(node) { return node && !isText(node) && lists.contains(node.classList, 'note-styletag'); } /* harmony default export */ const dom = ({ /** @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: "<p>".concat(blankHTML, "</p>"), 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, deepestChildIsEmpty: deepestChildIsEmpty, isEmpty: dom_isEmpty, isEmptyAnchor: func.and(isAnchor, dom_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, nextPointWithEmptyNode: nextPointWithEmptyNode, isSamePoint: isSamePoint, isVisiblePoint: isVisiblePoint, prevPointUntil: prevPointUntil, nextPointUntil: nextPointUntil, isCharPoint: isCharPoint, isSpacePoint: isSpacePoint, 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, isCustomStyleTag: isCustomStyleTag }); ;// CONCATENATED MODULE: ./src/js/Context.js function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var Context = /*#__PURE__*/function () { /** * @param {jQuery} $note * @param {Object} options */ function Context($note, options) { _classCallCheck(this, Context); this.$note = $note; this.memos = {}; this.modules = {}; this.layoutInfo = {}; this.options = external_jQuery_default().extend(true, {}, options); // init ui with options (external_jQuery_default()).summernote.ui = external_jQuery_default().summernote.ui_template(this.options); this.ui = (external_jQuery_default()).summernote.ui; this.initialize(); } /** * create layout and initialize modules and other resources */ _createClass(Context, [{ key: "initialize", value: function initialize() { this.layoutInfo = this.ui.createLayout(this.$note); this._initialize(); this.$note.hide(); return this; } /** * destroy modules and other resources and remove layout */ }, { key: "destroy", value: function destroy() { this._destroy(); this.$note.removeData('summernote'); this.ui.removeLayout(this.$note, this.layoutInfo); } /** * destory modules and other resources and initialize it again */ }, { key: "reset", value: function reset() { var disabled = this.isDisabled(); this.code(dom.emptyPara); this._destroy(); this._initialize(); if (disabled) { this.disable(); } } }, { key: "_initialize", value: function _initialize() { var _this = this; // set own id this.options.id = func.uniqueId(external_jQuery_default().now()); // set default container for tooltips, popovers, and dialogs this.options.container = this.options.container || this.layoutInfo.editor; // add optional buttons var buttons = external_jQuery_default().extend({}, this.options.buttons); Object.keys(buttons).forEach(function (key) { _this.memo('button.' + key, buttons[key]); }); var modules = external_jQuery_default().extend({}, this.options.modules, (external_jQuery_default()).summernote.plugins || {}); // add and initialize modules Object.keys(modules).forEach(function (key) { _this.module(key, modules[key], true); }); Object.keys(this.modules).forEach(function (key) { _this.initializeModule(key); }); } }, { key: "_destroy", value: function _destroy() { var _this2 = this; // destroy modules with reversed order Object.keys(this.modules).reverse().forEach(function (key) { _this2.removeModule(key); }); Object.keys(this.memos).forEach(function (key) { _this2.removeMemo(key); }); // trigger custom onDestroy callback this.triggerEvent('destroy', this); } }, { key: "code", value: function code(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.invoke('codeview.sync', html); } else { this.layoutInfo.editable.html(html); } this.$note.val(html); this.triggerEvent('change', html, this.layoutInfo.editable); } } }, { key: "isDisabled", value: function isDisabled() { return this.layoutInfo.editable.attr('contenteditable') === 'false'; } }, { key: "enable", value: function enable() { this.layoutInfo.editable.attr('contenteditable', true); this.invoke('toolbar.activate', true); this.triggerEvent('disable', false); this.options.editing = true; } }, { key: "disable", value: function disable() { // close codeview if codeview is opend if (this.invoke('codeview.isActivated')) { this.invoke('codeview.deactivate'); } this.layoutInfo.editable.attr('contenteditable', false); this.options.editing = false; this.invoke('toolbar.deactivate', true); this.triggerEvent('disable', true); } }, { key: "triggerEvent", value: function triggerEvent() { var namespace = lists.head(arguments); var args = lists.tail(lists.from(arguments)); var callback = this.options.callbacks[func.namespaceToCamel(namespace, 'on')]; if (callback) { callback.apply(this.$note[0], args); } this.$note.trigger('summernote.' + namespace, args); } }, { key: "initializeModule", value: function initializeModule(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(this.$note, module.events); } } }, { key: "module", value: function module(key, ModuleClass, withoutIntialize) { if (arguments.length === 1) { return this.modules[key]; } this.modules[key] = new ModuleClass(this); if (!withoutIntialize) { this.initializeModule(key); } } }, { key: "removeModule", value: function removeModule(key) { var module = this.modules[key]; if (module.shouldInitialize()) { if (module.events) { dom.detachEvents(this.$note, module.events); } if (module.destroy) { module.destroy(); } } delete this.modules[key]; } }, { key: "memo", value: function memo(key, obj) { if (arguments.length === 1) { return this.memos[key]; } this.memos[key] = obj; } }, { key: "removeMemo", value: function removeMemo(key) { if (this.memos[key] && this.memos[key].destroy) { this.memos[key].destroy(); } delete this.memos[key]; } /** * Some buttons need to change their visual style immediately once they get pressed */ }, { key: "createInvokeHandlerAndUpdateState", value: function createInvokeHandlerAndUpdateState(namespace, value) { var _this3 = this; return function (event) { _this3.createInvokeHandler(namespace, value)(event); _this3.invoke('buttons.updateCurrentStyle'); }; } }, { key: "createInvokeHandler", value: function createInvokeHandler(namespace, value) { var _this4 = this; return function (event) { event.preventDefault(); var $target = external_jQuery_default()(event.target); _this4.invoke(namespace, value || $target.closest('[data-value]').data('value'), $target); }; } }, { key: "invoke", value: function invoke() { var namespace = lists.head(arguments); var args = lists.tail(lists.from(arguments)); var splits = namespace.split('.'); var hasSeparator = splits.length > 1; var moduleName = hasSeparator && lists.head(splits); var methodName = hasSeparator ? lists.last(splits) : lists.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 Context; }(); ;// CONCATENATED MODULE: ./src/js/summernote.js external_jQuery_default().fn.extend({ /** * Summernote API * * @param {Object|String} * @return {this} */ summernote: function summernote() { var type = external_jQuery_default().type(lists.head(arguments)); var isExternalAPICalled = type === 'string'; var hasInitOptions = type === 'object'; var options = external_jQuery_default().extend({}, (external_jQuery_default()).summernote.options, hasInitOptions ? lists.head(arguments) : {}); // Update options options.langInfo = external_jQuery_default().extend(true, {}, (external_jQuery_default()).summernote.lang["en-US"], (external_jQuery_default()).summernote.lang[options.lang]); options.icons = external_jQuery_default().extend(true, {}, (external_jQuery_default()).summernote.options.icons, options.icons); options.tooltip = options.tooltip === 'auto' ? !env.isSupportTouch : options.tooltip; this.each(function (idx, note) { var $note = external_jQuery_default()(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, lists.from(arguments)); } else if (options.focus) { context.invoke('editor.focus'); } } return this; } }); ;// CONCATENATED MODULE: ./src/js/core/range.js function range_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function range_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function range_createClass(Constructor, protoProps, staticProps) { if (protoProps) range_defineProperties(Constructor.prototype, protoProps); if (staticProps) range_defineProperties(Constructor, staticProps); return Constructor; } /** * return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js * * @param {TextRange} textRange * @param {Boolean} isStart * @return {BoundaryPoint} * * @see http://msdn.microsoft.com/en-us/library/ie/ms535872(v=vs.85).aspx */ function textRangeToPoint(textRange, isStart) { var container = textRange.parentElement(); var offset; var tester = document.body.createTextRange(); var prevContainer; var childNodes = lists.from(container.childNodes); for (offset = 0; offset < childNodes.length; offset++) { if (dom.isText(childNodes[offset])) { continue; } tester.moveToElementText(childNodes[offset]); if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; } prevContainer = childNodes[offset]; } if (offset !== 0 && dom.isText(childNodes[offset - 1])) { var textRangeStart = document.body.createTextRange(); var curTextNode = null; textRangeStart.moveToElementText(prevContainer || container); textRangeStart.collapse(!prevContainer); curTextNode = prevContainer ? prevContainer.nextSibling : container.firstChild; var pointTester = textRange.duplicate(); pointTester.setEndPoint('StartToStart', textRangeStart); var textCount = pointTester.text.replace(/[\r\n]/g, '').length; while (textCount > curTextNode.nodeValue.length && curTextNode.nextSibling) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } // [workaround] enforce IE to re-reference curTextNode, hack var dummy = curTextNode.nodeValue; // eslint-disable-line if (isStart && curTextNode.nextSibling && dom.isText(curTextNode.nextSibling) && textCount === curTextNode.nodeValue.length) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } container = curTextNode; offset = textCount; } return { cont: container, offset: offset }; } /** * return TextRange from boundary point (inspired by google closure-library) * @param {BoundaryPoint} point * @return {TextRange} */ function pointToTextRange(point) { var textRangeInfo = function textRangeInfo(container, offset) { var node, isCollapseToStart; if (dom.isText(container)) { var prevTextNodes = dom.listPrev(container, func.not(dom.isText)); var prevContainer = lists.last(prevTextNodes).previousSibling; node = prevContainer || container.parentNode; offset += lists.sum(lists.tail(prevTextNodes), dom.nodeLength); isCollapseToStart = !prevContainer; } else { node = container.childNodes[offset] || container; if (dom.isText(node)) { return textRangeInfo(node, 0); } offset = 0; isCollapseToStart = false; } return { node: node, collapseToStart: isCollapseToStart, offset: offset }; }; var textRange = document.body.createTextRange(); var info = textRangeInfo(point.node, point.offset); textRange.moveToElementText(info.node); textRange.collapse(info.collapseToStart); textRange.moveStart('character', info.offset); return textRange; } /** * Wrapped Range * * @constructor * @param {Node} sc - start container * @param {Number} so - start offset * @param {Node} ec - end container * @param {Number} eo - end offset */ var WrappedRange = /*#__PURE__*/function () { function WrappedRange(sc, so, ec, eo) { range_classCallCheck(this, WrappedRange); this.sc = sc; this.so = so; this.ec = ec; this.eo = eo; // isOnEditable: judge whether range is on editable or not this.isOnEditable = this.makeIsOn(dom.isEditable); // isOnList: judge whether range is on list node or not this.isOnList = this.makeIsOn(dom.isList); // isOnAnchor: judge whether range is on anchor node or not this.isOnAnchor = this.makeIsOn(dom.isAnchor); // isOnCell: judge whether range is on cell node or not this.isOnCell = this.makeIsOn(dom.isCell); // isOnData: judge whether range is on data node or not this.isOnData = this.makeIsOn(dom.isData); } // nativeRange: get nativeRange from sc, so, ec, eo range_createClass(WrappedRange, [{ key: "nativeRange", value: function nativeRange() { if (env.isW3CRangeSupport) { var w3cRange = document.createRange(); w3cRange.setStart(this.sc, this.so); w3cRange.setEnd(this.ec, this.eo); return w3cRange; } else { var textRange = pointToTextRange({ node: this.sc, offset: this.so }); textRange.setEndPoint('EndToEnd', pointToTextRange({ node: this.ec, offset: this.eo })); return textRange; } } }, { key: "getPoints", value: function getPoints() { return { sc: this.sc, so: this.so, ec: this.ec, eo: this.eo }; } }, { key: "getStartPoint", value: function getStartPoint() { return { node: this.sc, offset: this.so }; } }, { key: "getEndPoint", value: function getEndPoint() { return { node: this.ec, offset: this.eo }; } /** * select update visible range */ }, { key: "select", value: function select() { var nativeRng = this.nativeRange(); if (env.isW3CRangeSupport) { var selection = document.getSelection(); if (selection.rangeCount > 0) { selection.removeAllRanges(); } selection.addRange(nativeRng); } else { nativeRng.select(); } return this; } /** * Moves the scrollbar to start container(sc) of current range * * @return {WrappedRange} */ }, { key: "scrollIntoView", value: function scrollIntoView(container) { var height = external_jQuery_default()(container).height(); if (container.scrollTop + height < this.sc.offsetTop) { container.scrollTop += Math.abs(container.scrollTop + height - this.sc.offsetTop); } return this; } /** * @return {WrappedRange} */ }, { key: "normalize", value: function normalize() { /** * @param {BoundaryPoint} point * @param {Boolean} isLeftToRight - true: prefer to choose right node * - false: prefer to choose left node * @return {BoundaryPoint} */ var getVisiblePoint = function getVisiblePoint(point, isLeftToRight) { if (!point) { return point; } // Just use the given point [XXX:Adhoc] // - case 01. if the point is on the middle of the node // - case 02. if the point is on the right edge and prefer to choose left node // - case 03. if the point is on the left edge and prefer to choose right node // - case 04. if the point is on the right edge and prefer to choose right node but the node is void // - case 05. if the point is on the left edge and prefer to choose left node but the node is void // - case 06. if the point is on the block node and there is no children if (dom.isVisiblePoint(point)) { if (!dom.isEdgePoint(point) || dom.isRightEdgePoint(point) && !isLeftToRight || dom.isLeftEdgePoint(point) && isLeftToRight || dom.isRightEdgePoint(point) && isLeftToRight && dom.isVoid(point.node.nextSibling) || dom.isLeftEdgePoint(point) && !isLeftToRight && dom.isVoid(point.node.previousSibling) || dom.isBlock(point.node) && dom.isEmpty(point.node)) { return point; } } // point on block's edge var block = dom.ancestor(point.node, dom.isBlock); var hasRightNode = false; if (!hasRightNode) { var prevPoint = dom.prevPoint(point) || { node: null }; hasRightNode = (dom.isLeftEdgePointOf(point, block) || dom.isVoid(prevPoint.node)) && !isLeftToRight; } var hasLeftNode = false; if (!hasLeftNode) { var _nextPoint = dom.nextPoint(point) || { node: null }; hasLeftNode = (dom.isRightEdgePointOf(point, block) || dom.isVoid(_nextPoint.node)) && isLeftToRight; } if (hasRightNode || hasLeftNode) { // returns point already on visible point if (dom.isVisiblePoint(point)) { return point; } // reverse direction isLeftToRight = !isLeftToRight; } var nextPoint = isLeftToRight ? dom.nextPointUntil(dom.nextPoint(point), dom.isVisiblePoint) : dom.prevPointUntil(dom.prevPoint(point), dom.isVisiblePoint); return nextPoint || point; }; var endPoint = getVisiblePoint(this.getEndPoint(), false); var startPoint = this.isCollapsed() ? endPoint : getVisiblePoint(this.getStartPoint(), true); return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns matched nodes on range * * @param {Function} [pred] - predicate function * @param {Object} [options] * @param {Boolean} [options.includeAncestor] * @param {Boolean} [options.fullyContains] * @return {Node[]} */ }, { key: "nodes", value: function nodes(pred, options) { pred = pred || func.ok; var includeAncestor = options && options.includeAncestor; var fullyContains = options && options.fullyContains; // TODO compare points and sort var startPoint = this.getStartPoint(); var endPoint = this.getEndPoint(); var nodes = []; var leftEdgeNodes = []; dom.walkPoint(startPoint, endPoint, function (point) { if (dom.isEditable(point.node)) { return; } var node; if (fullyContains) { if (dom.isLeftEdgePoint(point)) { leftEdgeNodes.push(point.node); } if (dom.isRightEdgePoint(point) && lists.contains(leftEdgeNodes, point.node)) { node = point.node; } } else if (includeAncestor) { node = dom.ancestor(point.node, pred); } else { node = point.node; } if (node && pred(node)) { nodes.push(node); } }, true); return lists.unique(nodes); } /** * returns commonAncestor of range * @return {Element} - commonAncestor */ }, { key: "commonAncestor", value: function commonAncestor() { return dom.commonAncestor(this.sc, this.ec); } /** * returns expanded range by pred * * @param {Function} pred - predicate function * @return {WrappedRange} */ }, { key: "expand", value: function expand(pred) { var startAncestor = dom.ancestor(this.sc, pred); var endAncestor = dom.ancestor(this.ec, pred); if (!startAncestor && !endAncestor) { return new WrappedRange(this.sc, this.so, this.ec, this.eo); } var boundaryPoints = this.getPoints(); if (startAncestor) { boundaryPoints.sc = startAncestor; boundaryPoints.so = 0; } if (endAncestor) { boundaryPoints.ec = endAncestor; boundaryPoints.eo = dom.nodeLength(endAncestor); } return new WrappedRange(boundaryPoints.sc, boundaryPoints.so, boundaryPoints.ec, boundaryPoints.eo); } /** * @param {Boolean} isCollapseToStart * @return {WrappedRange} */ }, { key: "collapse", value: function collapse(isCollapseToStart) { if (isCollapseToStart) { return new WrappedRange(this.sc, this.so, this.sc, this.so); } else { return new WrappedRange(this.ec, this.eo, this.ec, this.eo); } } /** * splitText on range */ }, { key: "splitText", value: function splitText() { var isSameContainer = this.sc === this.ec; var boundaryPoints = this.getPoints(); if (dom.isText(this.ec) && !dom.isEdgePoint(this.getEndPoint())) { this.ec.splitText(this.eo); } if (dom.isText(this.sc) && !dom.isEdgePoint(this.getStartPoint())) { boundaryPoints.sc = this.sc.splitText(this.so); boundaryPoints.so = 0; if (isSameContainer) { boundaryPoints.ec = boundaryPoints.sc; boundaryPoints.eo = this.eo - this.so; } } return new WrappedRange(boundaryPoints.sc, boundaryPoints.so, boundaryPoints.ec, boundaryPoints.eo); } /** * delete contents on range * @return {WrappedRange} */ }, { key: "deleteContents", value: function deleteContents() { if (this.isCollapsed()) { return this; } var rng = this.splitText(); var nodes = rng.nodes(null, { fullyContains: true }); // find new cursor point var point = dom.prevPointUntil(rng.getStartPoint(), function (point) { return !lists.contains(nodes, point.node); }); var emptyParents = []; external_jQuery_default().each(nodes, function (idx, node) { // find empty parents var parent = node.parentNode; if (point.node !== parent && dom.nodeLength(parent) === 1) { emptyParents.push(parent); } dom.remove(node, false); }); // remove empty parents external_jQuery_default().each(emptyParents, function (idx, node) { dom.remove(node, false); }); return new WrappedRange(point.node, point.offset, point.node, point.offset).normalize(); } /** * makeIsOn: return isOn(pred) function */ }, { key: "makeIsOn", value: function makeIsOn(pred) { return function () { var ancestor = dom.ancestor(this.sc, pred); return !!ancestor && ancestor === dom.ancestor(this.ec, pred); }; } /** * @param {Function} pred * @return {Boolean} */ }, { key: "isLeftEdgeOf", value: function isLeftEdgeOf(pred) { if (!dom.isLeftEdgePoint(this.getStartPoint())) { return false; } var node = dom.ancestor(this.sc, pred); return node && dom.isLeftEdgeOf(this.sc, node); } /** * returns whether range was collapsed or not */ }, { key: "isCollapsed", value: function isCollapsed() { return this.sc === this.ec && this.so === this.eo; } /** * wrap inline nodes which children of body with paragraph * * @return {WrappedRange} */ }, { key: "wrapBodyInlineWithPara", value: function wrapBodyInlineWithPara() { if (dom.isBodyContainer(this.sc) && dom.isEmpty(this.sc)) { this.sc.innerHTML = dom.emptyPara; return new WrappedRange(this.sc.firstChild, 0, this.sc.firstChild, 0); } /** * [workaround] firefox often create range on not visible point. so normalize here. * - firefox: |<p>text</p>| * - chrome: <p>|text|</p> */ var rng = this.normalize(); if (dom.isParaInline(this.sc) || dom.isPara(this.sc)) { return rng; } // find inline top ancestor var topAncestor; if (dom.isInline(rng.sc)) { var ancestors = dom.listAncestor(rng.sc, func.not(dom.isInline)); topAncestor = lists.last(ancestors); if (!dom.isInline(topAncestor)) { topAncestor = ancestors[ancestors.length - 2] || rng.sc.childNodes[rng.so]; } } else { topAncestor = rng.sc.childNodes[rng.so > 0 ? rng.so - 1 : 0]; } if (topAncestor) { // siblings not in paragraph var inlineSiblings = dom.listPrev(topAncestor, dom.isParaInline).reverse(); inlineSiblings = inlineSiblings.concat(dom.listNext(topAncestor.nextSibling, dom.isParaInline)); // wrap with paragraph if (inlineSiblings.length) { var para = dom.wrap(lists.head(inlineSiblings), 'p'); dom.appendChildNodes(para, lists.tail(inlineSiblings)); } } return this.normalize(); } /** * insert node at current cursor * * @param {Node} node * @return {Node} */ }, { key: "insertNode", value: function insertNode(node) { var rng = this; if (dom.isText(node) || dom.isInline(node)) { rng = this.wrapBodyInlineWithPara().deleteContents(); } var info = dom.splitPoint(rng.getStartPoint(), dom.isInline(node)); if (info.rightNode) { info.rightNode.parentNode.insertBefore(node, info.rightNode); if (dom.isEmpty(info.rightNode) && dom.isPara(node)) { info.rightNode.parentNode.removeChild(info.rightNode); } } else { info.container.appendChild(node); } return node; } /** * insert html at current cursor */ }, { key: "pasteHTML", value: function pasteHTML(markup) { markup = external_jQuery_default().trim(markup); var contentsContainer = external_jQuery_default()('<div></div>').html(markup)[0]; var childNodes = lists.from(contentsContainer.childNodes); // const rng = this.wrapBodyInlineWithPara().deleteContents(); var rng = this; var reversed = false; if (rng.so >= 0) { childNodes = childNodes.reverse(); reversed = true; } childNodes = childNodes.map(function (childNode) { return rng.insertNode(childNode); }); if (reversed) { childNodes = childNodes.reverse(); } return childNodes; } /** * returns text in range * * @return {String} */ }, { key: "toString", value: function toString() { var nativeRng = this.nativeRange(); return env.isW3CRangeSupport ? nativeRng.toString() : nativeRng.text; } /** * returns range for word before cursor * * @param {Boolean} [findAfter] - find after cursor, default: false * @return {WrappedRange} */ }, { key: "getWordRange", value: function getWordRange(findAfter) { var endPoint = this.getEndPoint(); if (!dom.isCharPoint(endPoint)) { return this; } var startPoint = dom.prevPointUntil(endPoint, function (point) { return !dom.isCharPoint(point); }); if (findAfter) { endPoint = dom.nextPointUntil(endPoint, function (point) { return !dom.isCharPoint(point); }); } return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns range for words before cursor * * @param {Boolean} [findAfter] - find after cursor, default: false * @return {WrappedRange} */ }, { key: "getWordsRange", value: function getWordsRange(findAfter) { var endPoint = this.getEndPoint(); var isNotTextPoint = function isNotTextPoint(point) { return !dom.isCharPoint(point) && !dom.isSpacePoint(point); }; if (isNotTextPoint(endPoint)) { return this; } var startPoint = dom.prevPointUntil(endPoint, isNotTextPoint); if (findAfter) { endPoint = dom.nextPointUntil(endPoint, isNotTextPoint); } return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns range for words before cursor that match with a Regex * * example: * range: 'hi @Peter Pan' * regex: '/@[a-z ]+/i' * return range: '@Peter Pan' * * @param {RegExp} [regex] * @return {WrappedRange|null} */ }, { key: "getWordsMatchRange", value: function getWordsMatchRange(regex) { var endPoint = this.getEndPoint(); var startPoint = dom.prevPointUntil(endPoint, function (point) { if (!dom.isCharPoint(point) && !dom.isSpacePoint(point)) { return true; } var rng = new WrappedRange(point.node, point.offset, endPoint.node, endPoint.offset); var result = regex.exec(rng.toString()); return result && result.index === 0; }); var rng = new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); var text = rng.toString(); var result = regex.exec(text); if (result && result[0].length === text.length) { return rng; } else { return null; } } /** * create offsetPath bookmark * * @param {Node} editable */ }, { key: "bookmark", value: function bookmark(editable) { return { s: { path: dom.makeOffsetPath(editable, this.sc), offset: this.so }, e: { path: dom.makeOffsetPath(editable, this.ec), offset: this.eo } }; } /** * create offsetPath bookmark base on paragraph * * @param {Node[]} paras */ }, { key: "paraBookmark", value: function paraBookmark(paras) { return { s: { path: lists.tail(dom.makeOffsetPath(lists.head(paras), this.sc)), offset: this.so }, e: { path: lists.tail(dom.makeOffsetPath(lists.last(paras), this.ec)), offset: this.eo } }; } /** * getClientRects * @return {Rect[]} */ }, { key: "getClientRects", value: function getClientRects() { var nativeRng = this.nativeRange(); return nativeRng.getClientRects(); } }]); return WrappedRange; }(); /** * Data structure * * BoundaryPoint: a point of dom tree * * BoundaryPoints: two boundaryPoints corresponding to the start and the end of the Range * * See to http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Position */ /* harmony default export */ const range = ({ /** * create Range Object From arguments or Browser Selection * * @param {Node} sc - start container * @param {Number} so - start offset * @param {Node} ec - end container * @param {Number} eo - end offset * @return {WrappedRange} */ create: function create(sc, so, ec, eo) { if (arguments.length === 4) { return new WrappedRange(sc, so, ec, eo); } else if (arguments.length === 2) { // collapsed ec = sc; eo = so; return new WrappedRange(sc, so, ec, eo); } else { var wrappedRange = this.createFromSelection(); if (!wrappedRange && arguments.length === 1) { var bodyElement = arguments[0]; if (dom.isEditable(bodyElement)) { bodyElement = bodyElement.lastChild; } return this.createFromBodyElement(bodyElement, dom.emptyPara === arguments[0].innerHTML); } return wrappedRange; } }, createFromBodyElement: function createFromBodyElement(bodyElement) { var isCollapseToStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var wrappedRange = this.createFromNode(bodyElement); return wrappedRange.collapse(isCollapseToStart); }, createFromSelection: function createFromSelection() { var sc, so, ec, eo; if (env.isW3CRangeSupport) { var selection = document.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } else if (dom.isBody(selection.anchorNode)) { // Firefox: returns entire body as range on initialization. // We won't never need it. return null; } var nativeRng = selection.getRangeAt(0); sc = nativeRng.startContainer; so = nativeRng.startOffset; ec = nativeRng.endContainer; eo = nativeRng.endOffset; } else { // IE8: TextRange var textRange = document.selection.createRange(); var textRangeEnd = textRange.duplicate(); textRangeEnd.collapse(false); var textRangeStart = textRange; textRangeStart.collapse(true); var startPoint = textRangeToPoint(textRangeStart, true); var endPoint = textRangeToPoint(textRangeEnd, false); // same visible point case: range was collapsed. if (dom.isText(startPoint.node) && dom.isLeftEdgePoint(startPoint) && dom.isTextNode(endPoint.node) && dom.isRightEdgePoint(endPoint) && endPoint.node.nextSibling === startPoint.node) { startPoint = endPoint; } sc = startPoint.cont; so = startPoint.offset; ec = endPoint.cont; eo = endPoint.offset; } return new WrappedRange(sc, so, ec, eo); }, /** * @method * * create WrappedRange from node * * @param {Node} node * @return {WrappedRange} */ createFromNode: function createFromNode(node) { var sc = node; var so = 0; var ec = node; var eo = dom.nodeLength(ec); // browsers can't target a picture or void node if (dom.isVoid(sc)) { so = dom.listPrev(sc).length - 1; sc = sc.parentNode; } if (dom.isBR(ec)) { eo = dom.listPrev(ec).length - 1; ec = ec.parentNode; } else if (dom.isVoid(ec)) { eo = dom.listPrev(ec).length; ec = ec.parentNode; } return this.create(sc, so, ec, eo); }, /** * create WrappedRange from node after position * * @param {Node} node * @return {WrappedRange} */ createFromNodeBefore: function createFromNodeBefore(node) { return this.createFromNode(node).collapse(true); }, /** * create WrappedRange from node after position * * @param {Node} node * @return {WrappedRange} */ createFromNodeAfter: function createFromNodeAfter(node) { return this.createFromNode(node).collapse(); }, /** * @method * * create WrappedRange from bookmark * * @param {Node} editable * @param {Object} bookmark * @return {WrappedRange} */ createFromBookmark: function createFromBookmark(editable, bookmark) { var sc = dom.fromOffsetPath(editable, bookmark.s.path); var so = bookmark.s.offset; var ec = dom.fromOffsetPath(editable, bookmark.e.path); var eo = bookmark.e.offset; return new WrappedRange(sc, so, ec, eo); }, /** * @method * * create WrappedRange from paraBookmark * * @param {Object} bookmark * @param {Node[]} paras * @return {WrappedRange} */ createFromParaBookmark: function createFromParaBookmark(bookmark, paras) { var so = bookmark.s.offset; var eo = bookmark.e.offset; var sc = dom.fromOffsetPath(lists.head(paras), bookmark.s.path); var ec = dom.fromOffsetPath(lists.last(paras), bookmark.e.path); return new WrappedRange(sc, so, ec, eo); } }); ;// CONCATENATED MODULE: ./src/js/core/key.js var KEY_MAP = { 'BACKSPACE': 8, 'TAB': 9, 'ENTER': 13, 'ESCAPE': 27, 'SPACE': 32, 'DELETE': 46, // Arrow 'LEFT': 37, 'UP': 38, 'RIGHT': 39, 'DOWN': 40, // Number: 0-9 'NUM0': 48, 'NUM1': 49, 'NUM2': 50, 'NUM3': 51, 'NUM4': 52, 'NUM5': 53, 'NUM6': 54, 'NUM7': 55, 'NUM8': 56, // Alphabet: a-z 'B': 66, 'E': 69, 'I': 73, 'J': 74, 'K': 75, 'L': 76, 'R': 82, 'S': 83, 'U': 85, 'V': 86, 'Y': 89, 'Z': 90, 'SLASH': 191, 'LEFTBRACKET': 219, 'BACKSLASH': 220, 'RIGHTBRACKET': 221, // Navigation 'HOME': 36, 'END': 35, 'PAGEUP': 33, 'PAGEDOWN': 34 }; /** * @class core.key * * Object for keycodes. * * @singleton * @alternateClassName key */ /* harmony default export */ const key = ({ /** * @method isEdit * * @param {Number} keyCode * @return {Boolean} */ isEdit: function isEdit(keyCode) { return lists.contains([KEY_MAP.BACKSPACE, KEY_MAP.TAB, KEY_MAP.ENTER, KEY_MAP.SPACE, KEY_MAP.DELETE], keyCode); }, /** * @method isMove * * @param {Number} keyCode * @return {Boolean} */ isMove: function isMove(keyCode) { return lists.contains([KEY_MAP.LEFT, KEY_MAP.UP, KEY_MAP.RIGHT, KEY_MAP.DOWN], keyCode); }, /** * @method isNavigation * * @param {Number} keyCode * @return {Boolean} */ isNavigation: function isNavigation(keyCode) { return lists.contains([KEY_MAP.HOME, KEY_MAP.END, KEY_MAP.PAGEUP, KEY_MAP.PAGEDOWN], keyCode); }, /** * @property {Object} nameFromCode * @property {String} nameFromCode.8 "BACKSPACE" */ nameFromCode: func.invertObject(KEY_MAP), code: KEY_MAP }); ;// CONCATENATED MODULE: ./src/js/core/async.js /** * @method readFileAsDataURL * * read contents of file as representing URL * * @param {File} file * @return {Promise} - then: dataUrl */ function readFileAsDataURL(file) { return external_jQuery_default().Deferred(function (deferred) { external_jQuery_default().extend(new FileReader(), { onload: function onload(e) { var dataURL = e.target.result; deferred.resolve(dataURL); }, onerror: function onerror(err) { deferred.reject(err); } }).readAsDataURL(file); }).promise(); } /** * @method createImage * * create `<image>` from url string * * @param {String} url * @return {Promise} - then: $image */ function createImage(url) { return external_jQuery_default().Deferred(function (deferred) { var $img = external_jQuery_default()('<img>'); $img.one('load', function () { $img.off('error abort'); deferred.resolve($img); }).one('error abort', function () { $img.off('load').detach(); deferred.reject($img); }).css({ display: 'none' }).appendTo(document.body).attr('src', url); }).promise(); } ;// CONCATENATED MODULE: ./src/js/editing/History.js function History_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function History_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function History_createClass(Constructor, protoProps, staticProps) { if (protoProps) History_defineProperties(Constructor.prototype, protoProps); if (staticProps) History_defineProperties(Constructor, staticProps); return Constructor; } var History = /*#__PURE__*/function () { function History(context) { History_classCallCheck(this, History); this.stack = []; this.stackOffset = -1; this.context = context; this.$editable = context.layoutInfo.editable; this.editable = this.$editable[0]; } History_createClass(History, [{ key: "makeSnapshot", value: function makeSnapshot() { var rng = range.create(this.editable); var emptyBookmark = { s: { path: [], offset: 0 }, e: { path: [], offset: 0 } }; return { contents: this.$editable.html(), bookmark: rng && rng.isOnEditable() ? rng.bookmark(this.editable) : emptyBookmark }; } }, { key: "applySnapshot", value: function applySnapshot(snapshot) { if (snapshot.contents !== null) { this.$editable.html(snapshot.contents); } if (snapshot.bookmark !== null) { range.createFromBookmark(this.editable, snapshot.bookmark).select(); } } /** * @method rewind * Rewinds the history stack back to the first snapshot taken. * Leaves the stack intact, so that "Redo" can still be used. */ }, { key: "rewind", value: function rewind() { // Create snap shot if not yet recorded if (this.$editable.html() !== this.stack[this.stackOffset].contents) { this.recordUndo(); } // Return to the first available snapshot. this.stackOffset = 0; // Apply that snapshot. this.applySnapshot(this.stack[this.stackOffset]); } /** * @method commit * Resets history stack, but keeps current editor's content. */ }, { key: "commit", value: function commit() { // Clear the stack. this.stack = []; // Restore stackOffset to its original value. this.stackOffset = -1; // Record our first snapshot (of nothing). this.recordUndo(); } /** * @method reset * Resets the history stack completely; reverting to an empty editor. */ }, { key: "reset", value: function reset() { // Clear the stack. this.stack = []; // Restore stackOffset to its original value. this.stackOffset = -1; // Clear the editable area. this.$editable.html(''); // Record our first snapshot (of nothing). this.recordUndo(); } /** * undo */ }, { key: "undo", value: function undo() { // Create snap shot if not yet recorded if (this.$editable.html() !== this.stack[this.stackOffset].contents) { this.recordUndo(); } if (this.stackOffset > 0) { this.stackOffset--; this.applySnapshot(this.stack[this.stackOffset]); } } /** * redo */ }, { key: "redo", value: function redo() { if (this.stack.length - 1 > this.stackOffset) { this.stackOffset++; this.applySnapshot(this.stack[this.stackOffset]); } } /** * recorded undo */ }, { key: "recordUndo", value: function recordUndo() { this.stackOffset++; // Wash out stack after stackOffset if (this.stack.length > this.stackOffset) { this.stack = this.stack.slice(0, this.stackOffset); } // Create new snapshot and push it to the end this.stack.push(this.makeSnapshot()); // If the stack size reachs to the limit, then slice it if (this.stack.length > this.context.options.historyLimit) { this.stack.shift(); this.stackOffset -= 1; } } }]); return History; }(); ;// CONCATENATED MODULE: ./src/js/editing/Style.js function Style_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Style_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Style_createClass(Constructor, protoProps, staticProps) { if (protoProps) Style_defineProperties(Constructor.prototype, protoProps); if (staticProps) Style_defineProperties(Constructor, staticProps); return Constructor; } var Style = /*#__PURE__*/function () { function Style() { Style_classCallCheck(this, Style); } Style_createClass(Style, [{ key: "jQueryCSS", value: /** * @method jQueryCSS * * [workaround] for old jQuery * passing an array of style properties to .css() * will result in an object of property-value pairs. * (compability with version < 1.9) * * @private * @param {jQuery} $obj * @param {Array} propertyNames - An array of one or more CSS properties. * @return {Object} */ function jQueryCSS($obj, propertyNames) { var result = {}; external_jQuery_default().each(propertyNames, function (idx, propertyName) { result[propertyName] = $obj.css(propertyName); }); return result; } /** * returns style object from node * * @param {jQuery} $node * @return {Object} */ }, { key: "fromNode", value: function fromNode($node) { var properties = ['font-family', 'font-size', 'text-align', 'list-style-type', 'line-height']; var styleInfo = this.jQueryCSS($node, properties) || {}; var fontSize = $node[0].style.fontSize || styleInfo['font-size']; styleInfo['font-size'] = parseInt(fontSize, 10); styleInfo['font-size-unit'] = fontSize.match(/[a-z%]+$/); return styleInfo; } /** * paragraph level style * * @param {WrappedRange} rng * @param {Object} styleInfo */ }, { key: "stylePara", value: function stylePara(rng, styleInfo) { external_jQuery_default().each(rng.nodes(dom.isPara, { includeAncestor: true }), function (idx, para) { external_jQuery_default()(para).css(styleInfo); }); } /** * insert and returns styleNodes on range. * * @param {WrappedRange} rng * @param {Object} [options] - options for styleNodes * @param {String} [options.nodeName] - default: `SPAN` * @param {Boolean} [options.expandClosestSibling] - default: `false` * @param {Boolean} [options.onlyPartialContains] - default: `false` * @return {Node[]} */ }, { key: "styleNodes", value: function styleNodes(rng, options) { rng = rng.splitText(); var nodeName = options && options.nodeName || 'SPAN'; var expandClosestSibling = !!(options && options.expandClosestSibling); var onlyPartialContains = !!(options && options.onlyPartialContains); if (rng.isCollapsed()) { return [rng.insertNode(dom.create(nodeName))]; } var pred = dom.makePredByNodeName(nodeName); var nodes = rng.nodes(dom.isText, { fullyContains: true }).map(function (text) { return dom.singleChildAncestor(text, pred) || dom.wrap(text, nodeName); }); if (expandClosestSibling) { if (onlyPartialContains) { var nodesInRange = rng.nodes(); // compose with partial contains predication pred = func.and(pred, function (node) { return lists.contains(nodesInRange, node); }); } return nodes.map(function (node) { var siblings = dom.withClosestSiblings(node, pred); var head = lists.head(siblings); var tails = lists.tail(siblings); external_jQuery_default().each(tails, function (idx, elem) { dom.appendChildNodes(head, elem.childNodes); dom.remove(elem); }); return lists.head(siblings); }); } else { return nodes; } } /** * get current style on cursor * * @param {WrappedRange} rng * @return {Object} - object contains style properties. */ }, { key: "current", value: function current(rng) { var $cont = external_jQuery_default()(!dom.isElement(rng.sc) ? rng.sc.parentNode : rng.sc); var styleInfo = this.fromNode($cont); // document.queryCommandState for toggle state // [workaround] prevent Firefox nsresult: "0x80004005 (NS_ERROR_FAILURE)" try { styleInfo = external_jQuery_default().extend(styleInfo, { 'font-bold': document.queryCommandState('bold') ? 'bold' : 'normal', 'font-italic': document.queryCommandState('italic') ? 'italic' : 'normal', 'font-underline': document.queryCommandState('underline') ? 'underline' : 'normal', 'font-subscript': document.queryCommandState('subscript') ? 'subscript' : 'normal', 'font-superscript': document.queryCommandState('superscript') ? 'superscript' : 'normal', 'font-strikethrough': document.queryCommandState('strikethrough') ? 'strikethrough' : 'normal', 'font-family': document.queryCommandValue('fontname') || styleInfo['font-family'] }); } catch (e) {// eslint-disable-next-line } // list-style-type to list-style(unordered, ordered) if (!rng.isOnList()) { styleInfo['list-style'] = 'none'; } else { var orderedTypes = ['circle', 'disc', 'disc-leading-zero', 'square']; var isUnordered = orderedTypes.indexOf(styleInfo['list-style-type']) > -1; styleInfo['list-style'] = isUnordered ? 'unordered' : 'ordered'; } var para = dom.ancestor(rng.sc, dom.isPara); if (para && para.style['line-height']) { styleInfo['line-height'] = para.style.lineHeight; } else { var lineHeight = parseInt(styleInfo['line-height'], 10) / parseInt(styleInfo['font-size'], 10); styleInfo['line-height'] = lineHeight.toFixed(1); } styleInfo.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor); styleInfo.ancestors = dom.listAncestor(rng.sc, dom.isEditable); styleInfo.range = rng; return styleInfo; } }]); return Style; }(); ;// CONCATENATED MODULE: ./src/js/editing/Bullet.js function Bullet_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Bullet_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Bullet_createClass(Constructor, protoProps, staticProps) { if (protoProps) Bullet_defineProperties(Constructor.prototype, protoProps); if (staticProps) Bullet_defineProperties(Constructor, staticProps); return Constructor; } var Bullet = /*#__PURE__*/function () { function Bullet() { Bullet_classCallCheck(this, Bullet); } Bullet_createClass(Bullet, [{ key: "insertOrderedList", value: /** * toggle ordered list */ function insertOrderedList(editable) { this.toggleList('OL', editable); } /** * toggle unordered list */ }, { key: "insertUnorderedList", value: function insertUnorderedList(editable) { this.toggleList('UL', editable); } /** * indent */ }, { key: "indent", value: function indent(editable) { var _this = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); if (dom.isLi(head)) { var previousList = _this.findList(head.previousSibling); if (previousList) { paras.map(function (para) { return previousList.appendChild(para); }); } else { _this.wrapList(paras, head.parentNode.nodeName); paras.map(function (para) { return para.parentNode; }).map(function (para) { return _this.appendToPrevious(para); }); } } else { external_jQuery_default().each(paras, function (idx, para) { external_jQuery_default()(para).css('marginLeft', function (idx, val) { return (parseInt(val, 10) || 0) + 25; }); }); } }); rng.select(); } /** * outdent */ }, { key: "outdent", value: function outdent(editable) { var _this2 = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); if (dom.isLi(head)) { _this2.releaseList([paras]); } else { external_jQuery_default().each(paras, function (idx, para) { external_jQuery_default()(para).css('marginLeft', function (idx, val) { val = parseInt(val, 10) || 0; return val > 25 ? val - 25 : ''; }); }); } }); rng.select(); } /** * toggle list * * @param {String} listName - OL or UL */ }, { key: "toggleList", value: function toggleList(listName, editable) { var _this3 = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var bookmark = rng.paraBookmark(paras); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); // paragraph to list if (lists.find(paras, dom.isPurePara)) { var wrappedParas = []; external_jQuery_default().each(clustereds, function (idx, paras) { wrappedParas = wrappedParas.concat(_this3.wrapList(paras, listName)); }); paras = wrappedParas; // list to paragraph or change list style } else { var diffLists = rng.nodes(dom.isList, { includeAncestor: true }).filter(function (listNode) { return !external_jQuery_default().nodeName(listNode, listName); }); if (diffLists.length) { external_jQuery_default().each(diffLists, function (idx, listNode) { dom.replace(listNode, listName); }); } else { paras = this.releaseList(clustereds, true); } } range.createFromParaBookmark(bookmark, paras).select(); } /** * @param {Node[]} paras * @param {String} listName * @return {Node[]} */ }, { key: "wrapList", value: function wrapList(paras, listName) { var head = lists.head(paras); var last = lists.last(paras); var prevList = dom.isList(head.previousSibling) && head.previousSibling; var nextList = dom.isList(last.nextSibling) && last.nextSibling; var listNode = prevList || dom.insertAfter(dom.create(listName || 'UL'), last); // P to LI paras = paras.map(function (para) { return dom.isPurePara(para) ? dom.replace(para, 'LI') : para; }); // append to list(<ul>, <ol>) dom.appendChildNodes(listNode, paras); if (nextList) { dom.appendChildNodes(listNode, lists.from(nextList.childNodes)); dom.remove(nextList); } return paras; } /** * @method releaseList * * @param {Array[]} clustereds * @param {Boolean} isEscapseToBody * @return {Node[]} */ }, { key: "releaseList", value: function releaseList(clustereds, isEscapseToBody) { var _this4 = this; var releasedParas = []; external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); var last = lists.last(paras); var headList = isEscapseToBody ? dom.lastAncestor(head, dom.isList) : head.parentNode; var parentItem = headList.parentNode; if (headList.parentNode.nodeName === 'LI') { paras.map(function (para) { var newList = _this4.findNextSiblings(para); if (parentItem.nextSibling) { parentItem.parentNode.insertBefore(para, parentItem.nextSibling); } else { parentItem.parentNode.appendChild(para); } if (newList.length) { _this4.wrapList(newList, headList.nodeName); para.appendChild(newList[0].parentNode); } }); if (headList.children.length === 0) { parentItem.removeChild(headList); } if (parentItem.childNodes.length === 0) { parentItem.parentNode.removeChild(parentItem); } } else { var lastList = headList.childNodes.length > 1 ? dom.splitTree(headList, { node: last.parentNode, offset: dom.position(last) + 1 }, { isSkipPaddingBlankHTML: true }) : null; var middleList = dom.splitTree(headList, { node: head.parentNode, offset: dom.position(head) }, { isSkipPaddingBlankHTML: true }); paras = isEscapseToBody ? dom.listDescendant(middleList, dom.isLi) : lists.from(middleList.childNodes).filter(dom.isLi); // LI to P if (isEscapseToBody || !dom.isList(headList.parentNode)) { paras = paras.map(function (para) { return dom.replace(para, 'P'); }); } external_jQuery_default().each(lists.from(paras).reverse(), function (idx, para) { dom.insertAfter(para, headList); }); // remove empty lists var rootLists = lists.compact([headList, middleList, lastList]); external_jQuery_default().each(rootLists, function (idx, rootList) { var listNodes = [rootList].concat(dom.listDescendant(rootList, dom.isList)); external_jQuery_default().each(listNodes.reverse(), function (idx, listNode) { if (!dom.nodeLength(listNode)) { dom.remove(listNode, true); } }); }); } releasedParas = releasedParas.concat(paras); }); return releasedParas; } /** * @method appendToPrevious * * Appends list to previous list item, if * none exist it wraps the list in a new list item. * * @param {HTMLNode} ListItem * @return {HTMLNode} */ }, { key: "appendToPrevious", value: function appendToPrevious(node) { return node.previousSibling ? dom.appendChildNodes(node.previousSibling, [node]) : this.wrapList([node], 'LI'); } /** * @method findList * * Finds an existing list in list item * * @param {HTMLNode} ListItem * @return {Array[]} */ }, { key: "findList", value: function findList(node) { return node ? lists.find(node.children, function (child) { return ['OL', 'UL'].indexOf(child.nodeName) > -1; }) : null; } /** * @method findNextSiblings * * Finds all list item siblings that follow it * * @param {HTMLNode} ListItem * @return {HTMLNode} */ }, { key: "findNextSiblings", value: function findNextSiblings(node) { var siblings = []; while (node.nextSibling) { siblings.push(node.nextSibling); node = node.nextSibling; } return siblings; } }]); return Bullet; }(); ;// CONCATENATED MODULE: ./src/js/editing/Typing.js function Typing_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Typing_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Typing_createClass(Constructor, protoProps, staticProps) { if (protoProps) Typing_defineProperties(Constructor.prototype, protoProps); if (staticProps) Typing_defineProperties(Constructor, staticProps); return Constructor; } /** * @class editing.Typing * * Typing * */ var Typing = /*#__PURE__*/function () { function Typing(context) { Typing_classCallCheck(this, Typing); // a Bullet instance to toggle lists off this.bullet = new Bullet(); this.options = context.options; } /** * insert tab * * @param {WrappedRange} rng * @param {Number} tabsize */ Typing_createClass(Typing, [{ key: "insertTab", value: function insertTab(rng, tabsize) { var tab = dom.createText(new Array(tabsize + 1).join(dom.NBSP_CHAR)); rng = rng.deleteContents(); rng.insertNode(tab, true); rng = range.create(tab, tabsize); rng.select(); } /** * insert paragraph * * @param {jQuery} $editable * @param {WrappedRange} rng Can be used in unit tests to "mock" the range * * blockquoteBreakingLevel * 0 - No break, the new paragraph remains inside the quote * 1 - Break the first blockquote in the ancestors list * 2 - Break all blockquotes, so that the new paragraph is not quoted (this is the default) */ }, { key: "insertParagraph", value: function insertParagraph(editable, rng) { rng = rng || range.create(editable); // deleteContents on range. rng = rng.deleteContents(); // Wrap range if it needs to be wrapped by paragraph rng = rng.wrapBodyInlineWithPara(); // finding paragraph var splitRoot = dom.ancestor(rng.sc, dom.isPara); var nextPara; // on paragraph: split paragraph if (splitRoot) { // if it is an empty line with li if (dom.isLi(splitRoot) && (dom.isEmpty(splitRoot) || dom.deepestChildIsEmpty(splitRoot))) { // toggle UL/OL and escape this.bullet.toggleList(splitRoot.parentNode.nodeName); return; } else { var blockquote = null; if (this.options.blockquoteBreakingLevel === 1) { blockquote = dom.ancestor(splitRoot, dom.isBlockquote); } else if (this.options.blockquoteBreakingLevel === 2) { blockquote = dom.lastAncestor(splitRoot, dom.isBlockquote); } if (blockquote) { // We're inside a blockquote and options ask us to break it nextPara = external_jQuery_default()(dom.emptyPara)[0]; // If the split is right before a <br>, remove it so that there's no "empty line" // after the split in the new blockquote created if (dom.isRightEdgePoint(rng.getStartPoint()) && dom.isBR(rng.sc.nextSibling)) { external_jQuery_default()(rng.sc.nextSibling).remove(); } var split = dom.splitTree(blockquote, rng.getStartPoint(), { isDiscardEmptySplits: true }); if (split) { split.parentNode.insertBefore(nextPara, split); } else { dom.insertAfter(nextPara, blockquote); // There's no split if we were at the end of the blockquote } } else { nextPara = dom.splitTree(splitRoot, rng.getStartPoint()); // not a blockquote, just insert the paragraph var emptyAnchors = dom.listDescendant(splitRoot, dom.isEmptyAnchor); emptyAnchors = emptyAnchors.concat(dom.listDescendant(nextPara, dom.isEmptyAnchor)); external_jQuery_default().each(emptyAnchors, function (idx, anchor) { dom.remove(anchor); }); // replace empty heading, pre or custom-made styleTag with P tag if ((dom.isHeading(nextPara) || dom.isPre(nextPara) || dom.isCustomStyleTag(nextPara)) && dom.isEmpty(nextPara)) { nextPara = dom.replace(nextPara, 'p'); } } } // no paragraph: insert empty paragraph } else { var next = rng.sc.childNodes[rng.so]; nextPara = external_jQuery_default()(dom.emptyPara)[0]; if (next) { rng.sc.insertBefore(nextPara, next); } else { rng.sc.appendChild(nextPara); } } range.create(nextPara, 0).normalize().select().scrollIntoView(editable); } }]); return Typing; }(); ;// CONCATENATED MODULE: ./src/js/editing/Table.js function Table_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Table_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Table_createClass(Constructor, protoProps, staticProps) { if (protoProps) Table_defineProperties(Constructor.prototype, protoProps); if (staticProps) Table_defineProperties(Constructor, staticProps); return Constructor; } /** * @class Create a virtual table to create what actions to do in change. * @param {object} startPoint Cell selected to apply change. * @param {enum} where Where change will be applied Row or Col. Use enum: TableResultAction.where * @param {enum} action Action to be applied. Use enum: TableResultAction.requestAction * @param {object} domTable Dom element of table to make changes. */ var TableResultAction = function TableResultAction(startPoint, where, action, domTable) { var _startPoint = { 'colPos': 0, 'rowPos': 0 }; var _virtualTable = []; var _actionCellList = []; /// /////////////////////////////////////////// // Private functions /// /////////////////////////////////////////// /** * Set the startPoint of action. */ function setStartPoint() { if (!startPoint || !startPoint.tagName || startPoint.tagName.toLowerCase() !== 'td' && startPoint.tagName.toLowerCase() !== 'th') { // Impossible to identify start Cell point return; } _startPoint.colPos = startPoint.cellIndex; if (!startPoint.parentElement || !startPoint.parentElement.tagName || startPoint.parentElement.tagName.toLowerCase() !== 'tr') { // Impossible to identify start Row point return; } _startPoint.rowPos = startPoint.parentElement.rowIndex; } /** * Define virtual table position info object. * * @param {int} rowIndex Index position in line of virtual table. * @param {int} cellIndex Index position in column of virtual table. * @param {object} baseRow Row affected by this position. * @param {object} baseCell Cell affected by this position. * @param {bool} isSpan Inform if it is an span cell/row. */ function setVirtualTablePosition(rowIndex, cellIndex, baseRow, baseCell, isRowSpan, isColSpan, isVirtualCell) { var objPosition = { 'baseRow': baseRow, 'baseCell': baseCell, 'isRowSpan': isRowSpan, 'isColSpan': isColSpan, 'isVirtual': isVirtualCell }; if (!_virtualTable[rowIndex]) { _virtualTable[rowIndex] = []; } _virtualTable[rowIndex][cellIndex] = objPosition; } /** * Create action cell object. * * @param {object} virtualTableCellObj Object of specific position on virtual table. * @param {enum} resultAction Action to be applied in that item. */ function getActionCell(virtualTableCellObj, resultAction, virtualRowPosition, virtualColPosition) { return { 'baseCell': virtualTableCellObj.baseCell, 'action': resultAction, 'virtualTable': { 'rowIndex': virtualRowPosition, 'cellIndex': virtualColPosition } }; } /** * Recover free index of row to append Cell. * * @param {int} rowIndex Index of row to find free space. * @param {int} cellIndex Index of cell to find free space in table. */ function recoverCellIndex(rowIndex, cellIndex) { if (!_virtualTable[rowIndex]) { return cellIndex; } if (!_virtualTable[rowIndex][cellIndex]) { return cellIndex; } var newCellIndex = cellIndex; while (_virtualTable[rowIndex][newCellIndex]) { newCellIndex++; if (!_virtualTable[rowIndex][newCellIndex]) { return newCellIndex; } } } /** * Recover info about row and cell and add information to virtual table. * * @param {object} row Row to recover information. * @param {object} cell Cell to recover information. */ function addCellInfoToVirtual(row, cell) { var cellIndex = recoverCellIndex(row.rowIndex, cell.cellIndex); var cellHasColspan = cell.colSpan > 1; var cellHasRowspan = cell.rowSpan > 1; var isThisSelectedCell = row.rowIndex === _startPoint.rowPos && cell.cellIndex === _startPoint.colPos; setVirtualTablePosition(row.rowIndex, cellIndex, row, cell, cellHasRowspan, cellHasColspan, false); // Add span rows to virtual Table. var rowspanNumber = cell.attributes.rowSpan ? parseInt(cell.attributes.rowSpan.value, 10) : 0; if (rowspanNumber > 1) { for (var rp = 1; rp < rowspanNumber; rp++) { var rowspanIndex = row.rowIndex + rp; adjustStartPoint(rowspanIndex, cellIndex, cell, isThisSelectedCell); setVirtualTablePosition(rowspanIndex, cellIndex, row, cell, true, cellHasColspan, true); } } // Add span cols to virtual table. var colspanNumber = cell.attributes.colSpan ? parseInt(cell.attributes.colSpan.value, 10) : 0; if (colspanNumber > 1) { for (var cp = 1; cp < colspanNumber; cp++) { var cellspanIndex = recoverCellIndex(row.rowIndex, cellIndex + cp); adjustStartPoint(row.rowIndex, cellspanIndex, cell, isThisSelectedCell); setVirtualTablePosition(row.rowIndex, cellspanIndex, row, cell, cellHasRowspan, true, true); } } } /** * Process validation and adjust of start point if needed * * @param {int} rowIndex * @param {int} cellIndex * @param {object} cell * @param {bool} isSelectedCell */ function adjustStartPoint(rowIndex, cellIndex, cell, isSelectedCell) { if (rowIndex === _startPoint.rowPos && _startPoint.colPos >= cell.cellIndex && cell.cellIndex <= cellIndex && !isSelectedCell) { _startPoint.colPos++; } } /** * Create virtual table of cells with all cells, including span cells. */ function createVirtualTable() { var rows = domTable.rows; for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) { var cells = rows[rowIndex].cells; for (var cellIndex = 0; cellIndex < cells.length; cellIndex++) { addCellInfoToVirtual(rows[rowIndex], cells[cellIndex]); } } } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getDeleteResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; case TableResultAction.where.Row: if (!cell.isVirtual && cell.isRowSpan) { return TableResultAction.resultAction.AddCell; } else if (cell.isRowSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; } return TableResultAction.resultAction.RemoveCell; } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getAddResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isRowSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; case TableResultAction.where.Row: if (cell.isRowSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isColSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; } return TableResultAction.resultAction.AddCell; } function init() { setStartPoint(); createVirtualTable(); } /// /////////////////////////////////////////// // Public functions /// /////////////////////////////////////////// /** * Recover array os what to do in table. */ this.getActionList = function () { var fixedRow = where === TableResultAction.where.Row ? _startPoint.rowPos : -1; var fixedCol = where === TableResultAction.where.Column ? _startPoint.colPos : -1; var actualPosition = 0; var canContinue = true; while (canContinue) { var rowPosition = fixedRow >= 0 ? fixedRow : actualPosition; var colPosition = fixedCol >= 0 ? fixedCol : actualPosition; var row = _virtualTable[rowPosition]; if (!row) { canContinue = false; return _actionCellList; } var cell = row[colPosition]; if (!cell) { canContinue = false; return _actionCellList; } // Define action to be applied in this cell var resultAction = TableResultAction.resultAction.Ignore; switch (action) { case TableResultAction.requestAction.Add: resultAction = getAddResultActionToCell(cell); break; case TableResultAction.requestAction.Delete: resultAction = getDeleteResultActionToCell(cell); break; } _actionCellList.push(getActionCell(cell, resultAction, rowPosition, colPosition)); actualPosition++; } return _actionCellList; }; init(); }; /** * * Where action occours enum. */ TableResultAction.where = { 'Row': 0, 'Column': 1 }; /** * * Requested action to apply enum. */ TableResultAction.requestAction = { 'Add': 0, 'Delete': 1 }; /** * * Result action to be executed enum. */ TableResultAction.resultAction = { 'Ignore': 0, 'SubtractSpanCount': 1, 'RemoveCell': 2, 'AddCell': 3, 'SumSpanCount': 4 }; /** * * @class editing.Table * * Table * */ var Table = /*#__PURE__*/function () { function Table() { Table_classCallCheck(this, Table); } Table_createClass(Table, [{ key: "tab", value: /** * handle tab key * * @param {WrappedRange} rng * @param {Boolean} isShift */ function tab(rng, isShift) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var table = dom.ancestor(cell, dom.isTable); var cells = dom.listDescendant(table, dom.isCell); var nextCell = lists[isShift ? 'prev' : 'next'](cells, cell); if (nextCell) { range.create(nextCell, 0).select(); } } /** * Add a new row * * @param {WrappedRange} rng * @param {String} position (top/bottom) * @return {Node} */ }, { key: "addRow", value: function addRow(rng, position) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var currentTr = external_jQuery_default()(cell).closest('tr'); var trAttributes = this.recoverAttributes(currentTr); var html = external_jQuery_default()('<tr' + trAttributes + '></tr>'); var vTable = new TableResultAction(cell, TableResultAction.where.Row, TableResultAction.requestAction.Add, external_jQuery_default()(currentTr).closest('table')[0]); var actions = vTable.getActionList(); for (var idCell = 0; idCell < actions.length; idCell++) { var currentCell = actions[idCell]; var tdAttributes = this.recoverAttributes(currentCell.baseCell); switch (currentCell.action) { case TableResultAction.resultAction.AddCell: html.append('<td' + tdAttributes + '>' + dom.blank + '</td>'); break; case TableResultAction.resultAction.SumSpanCount: { if (position === 'top') { var baseCellTr = currentCell.baseCell.parent; var isTopFromRowSpan = (!baseCellTr ? 0 : currentCell.baseCell.closest('tr').rowIndex) <= currentTr[0].rowIndex; if (isTopFromRowSpan) { var newTd = external_jQuery_default()('<div></div>').append(external_jQuery_default()('<td' + tdAttributes + '>' + dom.blank + '</td>').removeAttr('rowspan')).html(); html.append(newTd); break; } } var rowspanNumber = parseInt(currentCell.baseCell.rowSpan, 10); rowspanNumber++; currentCell.baseCell.setAttribute('rowSpan', rowspanNumber); } break; } } if (position === 'top') { currentTr.before(html); } else { var cellHasRowspan = cell.rowSpan > 1; if (cellHasRowspan) { var lastTrIndex = currentTr[0].rowIndex + (cell.rowSpan - 2); external_jQuery_default()(external_jQuery_default()(currentTr).parent().find('tr')[lastTrIndex]).after(external_jQuery_default()(html)); return; } currentTr.after(html); } } /** * Add a new col * * @param {WrappedRange} rng * @param {String} position (left/right) * @return {Node} */ }, { key: "addCol", value: function addCol(rng, position) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var rowsGroup = external_jQuery_default()(row).siblings(); rowsGroup.push(row); var vTable = new TableResultAction(cell, TableResultAction.where.Column, TableResultAction.requestAction.Add, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { var currentCell = actions[actionIndex]; var tdAttributes = this.recoverAttributes(currentCell.baseCell); switch (currentCell.action) { case TableResultAction.resultAction.AddCell: if (position === 'right') { external_jQuery_default()(currentCell.baseCell).after('<td' + tdAttributes + '>' + dom.blank + '</td>'); } else { external_jQuery_default()(currentCell.baseCell).before('<td' + tdAttributes + '>' + dom.blank + '</td>'); } break; case TableResultAction.resultAction.SumSpanCount: if (position === 'right') { var colspanNumber = parseInt(currentCell.baseCell.colSpan, 10); colspanNumber++; currentCell.baseCell.setAttribute('colSpan', colspanNumber); } else { external_jQuery_default()(currentCell.baseCell).before('<td' + tdAttributes + '>' + dom.blank + '</td>'); } break; } } } /* * Copy attributes from element. * * @param {object} Element to recover attributes. * @return {string} Copied string elements. */ }, { key: "recoverAttributes", value: function recoverAttributes(el) { var resultStr = ''; if (!el) { return resultStr; } var attrList = el.attributes || []; for (var i = 0; i < attrList.length; i++) { if (attrList[i].name.toLowerCase() === 'id') { continue; } if (attrList[i].specified) { resultStr += ' ' + attrList[i].name + '=\'' + attrList[i].value + '\''; } } return resultStr; } /** * Delete current row * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteRow", value: function deleteRow(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var cellPos = row.children('td, th').index(external_jQuery_default()(cell)); var rowPos = row[0].rowIndex; var vTable = new TableResultAction(cell, TableResultAction.where.Row, TableResultAction.requestAction.Delete, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { if (!actions[actionIndex]) { continue; } var baseCell = actions[actionIndex].baseCell; var virtualPosition = actions[actionIndex].virtualTable; var hasRowspan = baseCell.rowSpan && baseCell.rowSpan > 1; var rowspanNumber = hasRowspan ? parseInt(baseCell.rowSpan, 10) : 0; switch (actions[actionIndex].action) { case TableResultAction.resultAction.Ignore: continue; case TableResultAction.resultAction.AddCell: { var nextRow = row.next('tr')[0]; if (!nextRow) { continue; } var cloneRow = row[0].cells[cellPos]; if (hasRowspan) { if (rowspanNumber > 2) { rowspanNumber--; nextRow.insertBefore(cloneRow, nextRow.cells[cellPos]); nextRow.cells[cellPos].setAttribute('rowSpan', rowspanNumber); nextRow.cells[cellPos].innerHTML = ''; } else if (rowspanNumber === 2) { nextRow.insertBefore(cloneRow, nextRow.cells[cellPos]); nextRow.cells[cellPos].removeAttribute('rowSpan'); nextRow.cells[cellPos].innerHTML = ''; } } } continue; case TableResultAction.resultAction.SubtractSpanCount: if (hasRowspan) { if (rowspanNumber > 2) { rowspanNumber--; baseCell.setAttribute('rowSpan', rowspanNumber); if (virtualPosition.rowIndex !== rowPos && baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } else if (rowspanNumber === 2) { baseCell.removeAttribute('rowSpan'); if (virtualPosition.rowIndex !== rowPos && baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } } continue; case TableResultAction.resultAction.RemoveCell: // Do not need remove cell because row will be deleted. continue; } } row.remove(); } /** * Delete current col * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteCol", value: function deleteCol(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var cellPos = row.children('td, th').index(external_jQuery_default()(cell)); var vTable = new TableResultAction(cell, TableResultAction.where.Column, TableResultAction.requestAction.Delete, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { if (!actions[actionIndex]) { continue; } switch (actions[actionIndex].action) { case TableResultAction.resultAction.Ignore: continue; case TableResultAction.resultAction.SubtractSpanCount: { var baseCell = actions[actionIndex].baseCell; var hasColspan = baseCell.colSpan && baseCell.colSpan > 1; if (hasColspan) { var colspanNumber = baseCell.colSpan ? parseInt(baseCell.colSpan, 10) : 0; if (colspanNumber > 2) { colspanNumber--; baseCell.setAttribute('colSpan', colspanNumber); if (baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } else if (colspanNumber === 2) { baseCell.removeAttribute('colSpan'); if (baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } } } continue; case TableResultAction.resultAction.RemoveCell: dom.remove(actions[actionIndex].baseCell, true); continue; } } } /** * create empty table element * * @param {Number} rowCount * @param {Number} colCount * @return {Node} */ }, { key: "createTable", value: function createTable(colCount, rowCount, options) { var tds = []; var tdHTML; for (var idxCol = 0; idxCol < colCount; idxCol++) { tds.push('<td>' + dom.blank + '</td>'); } tdHTML = tds.join(''); var trs = []; var trHTML; for (var idxRow = 0; idxRow < rowCount; idxRow++) { trs.push('<tr>' + tdHTML + '</tr>'); } trHTML = trs.join(''); var $table = external_jQuery_default()('<table>' + trHTML + '</table>'); if (options && options.tableClassName) { $table.addClass(options.tableClassName); } return $table[0]; } /** * Delete current table * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteTable", value: function deleteTable(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); external_jQuery_default()(cell).closest('table').remove(); } }]); return Table; }(); ;// CONCATENATED MODULE: ./src/js/module/Editor.js function Editor_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Editor_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Editor_createClass(Constructor, protoProps, staticProps) { if (protoProps) Editor_defineProperties(Constructor.prototype, protoProps); if (staticProps) Editor_defineProperties(Constructor, staticProps); return Constructor; } var KEY_BOGUS = 'bogus'; /** * @class Editor */ var Editor = /*#__PURE__*/function () { function Editor(context) { var _this = this; Editor_classCallCheck(this, Editor); this.context = context; this.$note = context.layoutInfo.note; this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.options = context.options; this.lang = this.options.langInfo; this.editable = this.$editable[0]; this.lastRange = null; this.snapshot = null; this.style = new Style(); this.table = new Table(); this.typing = new Typing(context); this.bullet = new Bullet(); this.history = new History(context); this.context.memo('help.escape', this.lang.help.escape); this.context.memo('help.undo', this.lang.help.undo); this.context.memo('help.redo', this.lang.help.redo); this.context.memo('help.tab', this.lang.help.tab); this.context.memo('help.untab', this.lang.help.untab); this.context.memo('help.insertParagraph', this.lang.help.insertParagraph); this.context.memo('help.insertOrderedList', this.lang.help.insertOrderedList); this.context.memo('help.insertUnorderedList', this.lang.help.insertUnorderedList); this.context.memo('help.indent', this.lang.help.indent); this.context.memo('help.outdent', this.lang.help.outdent); this.context.memo('help.formatPara', this.lang.help.formatPara); this.context.memo('help.insertHorizontalRule', this.lang.help.insertHorizontalRule); this.context.memo('help.fontName', this.lang.help.fontName); // native commands(with execCommand), generate function for execCommand var commands = ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull', 'formatBlock', 'removeFormat', 'backColor']; for (var idx = 0, len = commands.length; idx < len; idx++) { this[commands[idx]] = function (sCmd) { return function (value) { _this.beforeCommand(); document.execCommand(sCmd, false, value); _this.afterCommand(true); }; }(commands[idx]); this.context.memo('help.' + commands[idx], this.lang.help[commands[idx]]); } this.fontName = this.wrapCommand(function (value) { return _this.fontStyling('font-family', env.validFontName(value)); }); this.fontSize = this.wrapCommand(function (value) { var unit = _this.currentStyle()['font-size-unit']; return _this.fontStyling('font-size', value + unit); }); this.fontSizeUnit = this.wrapCommand(function (value) { var size = _this.currentStyle()['font-size']; return _this.fontStyling('font-size', size + value); }); for (var _idx = 1; _idx <= 6; _idx++) { this['formatH' + _idx] = function (idx) { return function () { _this.formatBlock('H' + idx); }; }(_idx); this.context.memo('help.formatH' + _idx, this.lang.help['formatH' + _idx]); } this.insertParagraph = this.wrapCommand(function () { _this.typing.insertParagraph(_this.editable); }); this.insertOrderedList = this.wrapCommand(function () { _this.bullet.insertOrderedList(_this.editable); }); this.insertUnorderedList = this.wrapCommand(function () { _this.bullet.insertUnorderedList(_this.editable); }); this.indent = this.wrapCommand(function () { _this.bullet.indent(_this.editable); }); this.outdent = this.wrapCommand(function () { _this.bullet.outdent(_this.editable); }); /** * insertNode * insert node * @param {Node} node */ this.insertNode = this.wrapCommand(function (node) { if (_this.isLimited(external_jQuery_default()(node).text().length)) { return; } var rng = _this.getLastRange(); rng.insertNode(node); _this.setLastRange(range.createFromNodeAfter(node).select()); }); /** * insert text * @param {String} text */ this.insertText = this.wrapCommand(function (text) { if (_this.isLimited(text.length)) { return; } var rng = _this.getLastRange(); var textNode = rng.insertNode(dom.createText(text)); _this.setLastRange(range.create(textNode, dom.nodeLength(textNode)).select()); }); /** * paste HTML * @param {String} markup */ this.pasteHTML = this.wrapCommand(function (markup) { if (_this.isLimited(markup.length)) { return; } markup = _this.context.invoke('codeview.purify', markup); var contents = _this.getLastRange().pasteHTML(markup); _this.setLastRange(range.createFromNodeAfter(lists.last(contents)).select()); }); /** * formatBlock * * @param {String} tagName */ this.formatBlock = this.wrapCommand(function (tagName, $target) { var onApplyCustomStyle = _this.options.callbacks.onApplyCustomStyle; if (onApplyCustomStyle) { onApplyCustomStyle.call(_this, $target, _this.context, _this.onFormatBlock); } else { _this.onFormatBlock(tagName, $target); } }); /** * insert horizontal rule */ this.insertHorizontalRule = this.wrapCommand(function () { var hrNode = _this.getLastRange().insertNode(dom.create('HR')); if (hrNode.nextSibling) { _this.setLastRange(range.create(hrNode.nextSibling, 0).normalize().select()); } }); /** * lineHeight * @param {String} value */ this.lineHeight = this.wrapCommand(function (value) { _this.style.stylePara(_this.getLastRange(), { lineHeight: value }); }); /** * create link (command) * * @param {Object} linkInfo */ this.createLink = this.wrapCommand(function (linkInfo) { var linkUrl = linkInfo.url; var linkText = linkInfo.text; var isNewWindow = linkInfo.isNewWindow; var checkProtocol = linkInfo.checkProtocol; var rng = linkInfo.range || _this.getLastRange(); var additionalTextLength = linkText.length - rng.toString().length; if (additionalTextLength > 0 && _this.isLimited(additionalTextLength)) { return; } var isTextChanged = rng.toString() !== linkText; // handle spaced urls from input if (typeof linkUrl === 'string') { linkUrl = linkUrl.trim(); } if (_this.options.onCreateLink) { linkUrl = _this.options.onCreateLink(linkUrl); } else if (checkProtocol) { // if url doesn't have any protocol and not even a relative or a label, use http:// as default linkUrl = /^([A-Za-z][A-Za-z0-9+-.]*\:|#|\/)/.test(linkUrl) ? linkUrl : _this.options.defaultProtocol + linkUrl; } var anchors = []; if (isTextChanged) { rng = rng.deleteContents(); var anchor = rng.insertNode(external_jQuery_default()('<A>' + linkText + '</A>')[0]); anchors.push(anchor); } else { anchors = _this.style.styleNodes(rng, { nodeName: 'A', expandClosestSibling: true, onlyPartialContains: true }); } external_jQuery_default().each(anchors, function (idx, anchor) { external_jQuery_default()(anchor).attr('href', linkUrl); if (isNewWindow) { external_jQuery_default()(anchor).attr('target', '_blank'); } else { external_jQuery_default()(anchor).removeAttr('target'); } }); _this.setLastRange(_this.createRangeFromList(anchors).select()); }); /** * setting color * * @param {Object} sObjColor color code * @param {String} sObjColor.foreColor foreground color * @param {String} sObjColor.backColor background color */ this.color = this.wrapCommand(function (colorInfo) { var foreColor = colorInfo.foreColor; var backColor = colorInfo.backColor; if (foreColor) { document.execCommand('foreColor', false, foreColor); } if (backColor) { document.execCommand('backColor', false, backColor); } }); /** * Set foreground color * * @param {String} colorCode foreground color code */ this.foreColor = this.wrapCommand(function (colorInfo) { document.execCommand('foreColor', false, colorInfo); }); /** * insert Table * * @param {String} dimension of table (ex : "5x5") */ this.insertTable = this.wrapCommand(function (dim) { var dimension = dim.split('x'); var rng = _this.getLastRange().deleteContents(); rng.insertNode(_this.table.createTable(dimension[0], dimension[1], _this.options)); }); /** * remove media object and Figure Elements if media object is img with Figure. */ this.removeMedia = this.wrapCommand(function () { var $target = external_jQuery_default()(_this.restoreTarget()).parent(); if ($target.closest('figure').length) { $target.closest('figure').remove(); } else { $target = external_jQuery_default()(_this.restoreTarget()).detach(); } _this.context.triggerEvent('media.delete', $target, _this.$editable); }); /** * float me * * @param {String} value */ this.floatMe = this.wrapCommand(function (value) { var $target = external_jQuery_default()(_this.restoreTarget()); $target.toggleClass('note-float-left', value === 'left'); $target.toggleClass('note-float-right', value === 'right'); $target.css('float', value === 'none' ? '' : value); }); /** * resize overlay element * @param {String} value */ this.resize = this.wrapCommand(function (value) { var $target = external_jQuery_default()(_this.restoreTarget()); value = parseFloat(value); if (value === 0) { $target.css('width', ''); } else { $target.css({ width: value * 100 + '%', height: '' }); } }); } Editor_createClass(Editor, [{ key: "initialize", value: function initialize() { var _this2 = this; // bind custom events this.$editable.on('keydown', function (event) { if (event.keyCode === key.code.ENTER) { _this2.context.triggerEvent('enter', event); } _this2.context.triggerEvent('keydown', event); // keep a snapshot to limit text on input event _this2.snapshot = _this2.history.makeSnapshot(); _this2.hasKeyShortCut = false; if (!event.isDefaultPrevented()) { if (_this2.options.shortcuts) { _this2.hasKeyShortCut = _this2.handleKeyMap(event); } else { _this2.preventDefaultEditableShortCuts(event); } } if (_this2.isLimited(1, event)) { var lastRange = _this2.getLastRange(); if (lastRange.eo - lastRange.so === 0) { return false; } } _this2.setLastRange(); // record undo in the key event except keyMap. if (_this2.options.recordEveryKeystroke) { if (_this2.hasKeyShortCut === false) { _this2.history.recordUndo(); } } }).on('keyup', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('keyup', event); }).on('focus', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('focus', event); }).on('blur', function (event) { _this2.context.triggerEvent('blur', event); }).on('mousedown', function (event) { _this2.context.triggerEvent('mousedown', event); }).on('mouseup', function (event) { _this2.setLastRange(); _this2.history.recordUndo(); _this2.context.triggerEvent('mouseup', event); }).on('scroll', function (event) { _this2.context.triggerEvent('scroll', event); }).on('paste', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('paste', event); }).on('input', function () { // To limit composition characters (e.g. Korean) if (_this2.isLimited(0) && _this2.snapshot) { _this2.history.applySnapshot(_this2.snapshot); } }); this.$editable.attr('spellcheck', this.options.spellCheck); this.$editable.attr('autocorrect', this.options.spellCheck); if (this.options.disableGrammar) { this.$editable.attr('data-gramm', false); } // init content before set event this.$editable.html(dom.html(this.$note) || dom.emptyPara); this.$editable.on(env.inputEventName, func.debounce(function () { _this2.context.triggerEvent('change', _this2.$editable.html(), _this2.$editable); }, 10)); this.$editable.on('focusin', function (event) { _this2.context.triggerEvent('focusin', event); }).on('focusout', function (event) { _this2.context.triggerEvent('focusout', event); }); if (this.options.airMode) { if (this.options.overrideContextMenu) { this.$editor.on('contextmenu', function (event) { _this2.context.triggerEvent('contextmenu', event); return false; }); } } else { if (this.options.width) { this.$editor.outerWidth(this.options.width); } if (this.options.height) { this.$editable.outerHeight(this.options.height); } if (this.options.maxHeight) { this.$editable.css('max-height', this.options.maxHeight); } if (this.options.minHeight) { this.$editable.css('min-height', this.options.minHeight); } } this.history.recordUndo(); this.setLastRange(); } }, { key: "destroy", value: function destroy() { this.$editable.off(); } }, { key: "handleKeyMap", value: function handleKeyMap(event) { var keyMap = this.options.keyMap[env.isMac ? 'mac' : 'pc']; var keys = []; if (event.metaKey) { keys.push('CMD'); } if (event.ctrlKey && !event.altKey) { keys.push('CTRL'); } if (event.shiftKey) { keys.push('SHIFT'); } var keyName = key.nameFromCode[event.keyCode]; if (keyName) { keys.push(keyName); } var eventName = keyMap[keys.join('+')]; if (keyName === 'TAB' && !this.options.tabDisable) { this.afterCommand(); } else if (eventName) { if (this.context.invoke(eventName) !== false) { event.preventDefault(); // if keyMap action was invoked return true; } } else if (key.isEdit(event.keyCode)) { this.afterCommand(); } return false; } }, { key: "preventDefaultEditableShortCuts", value: function preventDefaultEditableShortCuts(event) { // B(Bold, 66) / I(Italic, 73) / U(Underline, 85) if ((event.ctrlKey || event.metaKey) && lists.contains([66, 73, 85], event.keyCode)) { event.preventDefault(); } } }, { key: "isLimited", value: function isLimited(pad, event) { pad = pad || 0; if (typeof event !== 'undefined') { if (key.isMove(event.keyCode) || key.isNavigation(event.keyCode) || event.ctrlKey || event.metaKey || lists.contains([key.code.BACKSPACE, key.code.DELETE], event.keyCode)) { return false; } } if (this.options.maxTextLength > 0) { if (this.$editable.text().length + pad > this.options.maxTextLength) { return true; } } return false; } /** * create range * @return {WrappedRange} */ }, { key: "createRange", value: function createRange() { this.focus(); this.setLastRange(); return this.getLastRange(); } /** * create a new range from the list of elements * * @param {list} dom element list * @return {WrappedRange} */ }, { key: "createRangeFromList", value: function createRangeFromList(lst) { var startRange = range.createFromNodeBefore(lists.head(lst)); var startPoint = startRange.getStartPoint(); var endRange = range.createFromNodeAfter(lists.last(lst)); var endPoint = endRange.getEndPoint(); return range.create(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * set the last range * * if given rng is exist, set rng as the last range * or create a new range at the end of the document * * @param {WrappedRange} rng */ }, { key: "setLastRange", value: function setLastRange(rng) { if (rng) { this.lastRange = rng; } else { this.lastRange = range.create(this.editable); if (external_jQuery_default()(this.lastRange.sc).closest('.note-editable').length === 0) { this.lastRange = range.createFromBodyElement(this.editable); } } } /** * get the last range * * if there is a saved last range, return it * or create a new range and return it * * @return {WrappedRange} */ }, { key: "getLastRange", value: function getLastRange() { if (!this.lastRange) { this.setLastRange(); } return this.lastRange; } /** * saveRange * * save current range * * @param {Boolean} [thenCollapse=false] */ }, { key: "saveRange", value: function saveRange(thenCollapse) { if (thenCollapse) { this.getLastRange().collapse().select(); } } /** * restoreRange * * restore lately range */ }, { key: "restoreRange", value: function restoreRange() { if (this.lastRange) { this.lastRange.select(); this.focus(); } } }, { key: "saveTarget", value: function saveTarget(node) { this.$editable.data('target', node); } }, { key: "clearTarget", value: function clearTarget() { this.$editable.removeData('target'); } }, { key: "restoreTarget", value: function restoreTarget() { return this.$editable.data('target'); } /** * currentStyle * * current style * @return {Object|Boolean} unfocus */ }, { key: "currentStyle", value: function currentStyle() { var rng = range.create(); if (rng) { rng = rng.normalize(); } return rng ? this.style.current(rng) : this.style.fromNode(this.$editable); } /** * style from node * * @param {jQuery} $node * @return {Object} */ }, { key: "styleFromNode", value: function styleFromNode($node) { return this.style.fromNode($node); } /** * undo */ }, { key: "undo", value: function undo() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.undo(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /* * commit */ }, { key: "commit", value: function commit() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.commit(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /** * redo */ }, { key: "redo", value: function redo() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.redo(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /** * before command */ }, { key: "beforeCommand", value: function beforeCommand() { this.context.triggerEvent('before.command', this.$editable.html()); // Set styleWithCSS before run a command document.execCommand('styleWithCSS', false, this.options.styleWithCSS); // keep focus on editable before command execution this.focus(); } /** * after command * @param {Boolean} isPreventTrigger */ }, { key: "afterCommand", value: function afterCommand(isPreventTrigger) { this.normalizeContent(); this.history.recordUndo(); if (!isPreventTrigger) { this.context.triggerEvent('change', this.$editable.html(), this.$editable); } } /** * handle tab key */ }, { key: "tab", value: function tab() { var rng = this.getLastRange(); if (rng.isCollapsed() && rng.isOnCell()) { this.table.tab(rng); } else { if (this.options.tabSize === 0) { return false; } if (!this.isLimited(this.options.tabSize)) { this.beforeCommand(); this.typing.insertTab(rng, this.options.tabSize); this.afterCommand(); } } } /** * handle shift+tab key */ }, { key: "untab", value: function untab() { var rng = this.getLastRange(); if (rng.isCollapsed() && rng.isOnCell()) { this.table.tab(rng, true); } else { if (this.options.tabSize === 0) { return false; } } } /** * run given function between beforeCommand and afterCommand */ }, { key: "wrapCommand", value: function wrapCommand(fn) { return function () { this.beforeCommand(); fn.apply(this, arguments); this.afterCommand(); }; } /** * insert image * * @param {String} src * @param {String|Function} param * @return {Promise} */ }, { key: "insertImage", value: function insertImage(src, param) { var _this3 = this; return createImage(src, param).then(function ($image) { _this3.beforeCommand(); if (typeof param === 'function') { param($image); } else { if (typeof param === 'string') { $image.attr('data-filename', param); } $image.css('width', Math.min(_this3.$editable.width(), $image.width())); } $image.show(); _this3.getLastRange().insertNode($image[0]); _this3.setLastRange(range.createFromNodeAfter($image[0]).select()); _this3.afterCommand(); }).fail(function (e) { _this3.context.triggerEvent('image.upload.error', e); }); } /** * insertImages * @param {File[]} files */ }, { key: "insertImagesAsDataURL", value: function insertImagesAsDataURL(files) { var _this4 = this; external_jQuery_default().each(files, function (idx, file) { var filename = file.name; if (_this4.options.maximumImageFileSize && _this4.options.maximumImageFileSize < file.size) { _this4.context.triggerEvent('image.upload.error', _this4.lang.image.maximumFileSizeError); } else { readFileAsDataURL(file).then(function (dataURL) { return _this4.insertImage(dataURL, filename); }).fail(function () { _this4.context.triggerEvent('image.upload.error'); }); } }); } /** * insertImagesOrCallback * @param {File[]} files */ }, { key: "insertImagesOrCallback", value: function insertImagesOrCallback(files) { var callbacks = this.options.callbacks; // If onImageUpload set, if (callbacks.onImageUpload) { this.context.triggerEvent('image.upload', files); // else insert Image as dataURL } else { this.insertImagesAsDataURL(files); } } /** * return selected plain text * @return {String} text */ }, { key: "getSelectedText", value: function getSelectedText() { var rng = this.getLastRange(); // if range on anchor, expand range with anchor if (rng.isOnAnchor()) { rng = range.createFromNode(dom.ancestor(rng.sc, dom.isAnchor)); } return rng.toString(); } }, { key: "onFormatBlock", value: function onFormatBlock(tagName, $target) { // [workaround] for MSIE, IE need `<` document.execCommand('FormatBlock', false, env.isMSIE ? '<' + tagName + '>' : tagName); // support custom class if ($target && $target.length) { // find the exact element has given tagName if ($target[0].tagName.toUpperCase() !== tagName.toUpperCase()) { $target = $target.find(tagName); } if ($target && $target.length) { var currentRange = this.createRange(); var $parent = external_jQuery_default()([currentRange.sc, currentRange.ec]).closest(tagName); // remove class added for current block $parent.removeClass(); var className = $target[0].className || ''; if (className) { $parent.addClass(className); } } } } }, { key: "formatPara", value: function formatPara() { this.formatBlock('P'); } }, { key: "fontStyling", value: function fontStyling(target, value) { var rng = this.getLastRange(); if (rng !== '') { var spans = this.style.styleNodes(rng); this.$editor.find('.note-status-output').html(''); external_jQuery_default()(spans).css(target, value); // [workaround] added styled bogus span for style // - also bogus character needed for cursor position if (rng.isCollapsed()) { var firstSpan = lists.head(spans); if (firstSpan && !dom.nodeLength(firstSpan)) { firstSpan.innerHTML = dom.ZERO_WIDTH_NBSP_CHAR; range.createFromNode(firstSpan.firstChild).select(); this.setLastRange(); this.$editable.data(KEY_BOGUS, firstSpan); } } else { this.setLastRange(this.createRangeFromList(spans).select()); } } else { var noteStatusOutput = external_jQuery_default().now(); this.$editor.find('.note-status-output').html('<div id="note-status-output-' + noteStatusOutput + '" class="alert alert-info">' + this.lang.output.noSelection + '</div>'); setTimeout(function () { external_jQuery_default()('#note-status-output-' + noteStatusOutput).remove(); }, 5000); } } /** * unlink * * @type command */ }, { key: "unlink", value: function unlink() { var rng = this.getLastRange(); if (rng.isOnAnchor()) { var anchor = dom.ancestor(rng.sc, dom.isAnchor); rng = range.createFromNode(anchor); rng.select(); this.setLastRange(); this.beforeCommand(); document.execCommand('unlink'); this.afterCommand(); } } /** * returns link info * * @return {Object} * @return {WrappedRange} return.range * @return {String} return.text * @return {Boolean} [return.isNewWindow=true] * @return {String} [return.url=""] */ }, { key: "getLinkInfo", value: function getLinkInfo() { var rng = this.getLastRange().expand(dom.isAnchor); // Get the first anchor on range(for edit). var $anchor = external_jQuery_default()(lists.head(rng.nodes(dom.isAnchor))); var linkInfo = { range: rng, text: rng.toString(), url: $anchor.length ? $anchor.attr('href') : '' }; // When anchor exists, if ($anchor.length) { // Set isNewWindow by checking its target. linkInfo.isNewWindow = $anchor.attr('target') === '_blank'; } return linkInfo; } }, { key: "addRow", value: function addRow(position) { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.addRow(rng, position); this.afterCommand(); } } }, { key: "addCol", value: function addCol(position) { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.addCol(rng, position); this.afterCommand(); } } }, { key: "deleteRow", value: function deleteRow() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteRow(rng); this.afterCommand(); } } }, { key: "deleteCol", value: function deleteCol() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteCol(rng); this.afterCommand(); } } }, { key: "deleteTable", value: function deleteTable() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteTable(rng); this.afterCommand(); } } /** * @param {Position} pos * @param {jQuery} $target - target element * @param {Boolean} [bKeepRatio] - keep ratio */ }, { key: "resizeTo", value: function resizeTo(pos, $target, bKeepRatio) { var imageSize; if (bKeepRatio) { var newRatio = pos.y / pos.x; var ratio = $target.data('ratio'); imageSize = { width: ratio > newRatio ? pos.x : pos.y / ratio, height: ratio > newRatio ? pos.x * ratio : pos.y }; } else { imageSize = { width: pos.x, height: pos.y }; } $target.css(imageSize); } /** * returns whether editable area has focus or not. */ }, { key: "hasFocus", value: function hasFocus() { return this.$editable.is(':focus'); } /** * set focus */ }, { key: "focus", value: function focus() { // [workaround] Screen will move when page is scolled in IE. // - do focus when not focused if (!this.hasFocus()) { this.$editable.focus(); } } /** * returns whether contents is empty or not. * @return {Boolean} */ }, { key: "isEmpty", value: function isEmpty() { return dom.isEmpty(this.$editable[0]) || dom.emptyPara === this.$editable.html(); } /** * Removes all contents and restores the editable instance to an _emptyPara_. */ }, { key: "empty", value: function empty() { this.context.invoke('code', dom.emptyPara); } /** * normalize content */ }, { key: "normalizeContent", value: function normalizeContent() { this.$editable[0].normalize(); } }]); return Editor; }(); ;// CONCATENATED MODULE: ./src/js/module/Clipboard.js function Clipboard_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Clipboard_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Clipboard_createClass(Constructor, protoProps, staticProps) { if (protoProps) Clipboard_defineProperties(Constructor.prototype, protoProps); if (staticProps) Clipboard_defineProperties(Constructor, staticProps); return Constructor; } var Clipboard = /*#__PURE__*/function () { function Clipboard(context) { Clipboard_classCallCheck(this, Clipboard); this.context = context; this.$editable = context.layoutInfo.editable; } Clipboard_createClass(Clipboard, [{ key: "initialize", value: function initialize() { this.$editable.on('paste', this.pasteByEvent.bind(this)); } /** * paste by clipboard event * * @param {Event} event */ }, { key: "pasteByEvent", value: function pasteByEvent(event) { var _this = this; var clipboardData = event.originalEvent.clipboardData; if (clipboardData && clipboardData.items && clipboardData.items.length) { var item = clipboardData.items.length > 1 ? clipboardData.items[1] : lists.head(clipboardData.items); if (item.kind === 'file' && item.type.indexOf('image/') !== -1) { // paste img file this.context.invoke('editor.insertImagesOrCallback', [item.getAsFile()]); event.preventDefault(); } else if (item.kind === 'string') { // paste text with maxTextLength check if (this.context.invoke('editor.isLimited', clipboardData.getData('Text').length)) { event.preventDefault(); } } } else if (window.clipboardData) { // for IE var text = window.clipboardData.getData('text'); if (this.context.invoke('editor.isLimited', text.length)) { event.preventDefault(); } } // Call editor.afterCommand after proceeding default event handler setTimeout(function () { _this.context.invoke('editor.afterCommand'); }, 10); } }]); return Clipboard; }(); ;// CONCATENATED MODULE: ./src/js/module/Dropzone.js function Dropzone_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Dropzone_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Dropzone_createClass(Constructor, protoProps, staticProps) { if (protoProps) Dropzone_defineProperties(Constructor.prototype, protoProps); if (staticProps) Dropzone_defineProperties(Constructor, staticProps); return Constructor; } var Dropzone = /*#__PURE__*/function () { function Dropzone(context) { Dropzone_classCallCheck(this, Dropzone); this.context = context; this.$eventListener = external_jQuery_default()(document); this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.options = context.options; this.lang = this.options.langInfo; this.documentEventHandlers = {}; this.$dropzone = external_jQuery_default()(['<div class="note-dropzone">', '<div class="note-dropzone-message"></div>', '</div>'].join('')).prependTo(this.$editor); } /** * attach Drag and Drop Events */ Dropzone_createClass(Dropzone, [{ key: "initialize", value: function initialize() { if (this.options.disableDragAndDrop) { // prevent default drop event this.documentEventHandlers.onDrop = function (e) { e.preventDefault(); }; // do not consider outside of dropzone this.$eventListener = this.$dropzone; this.$eventListener.on('drop', this.documentEventHandlers.onDrop); } else { this.attachDragAndDropEvent(); } } /** * attach Drag and Drop Events */ }, { key: "attachDragAndDropEvent", value: function attachDragAndDropEvent() { var _this = this; var collection = external_jQuery_default()(); var $dropzoneMessage = this.$dropzone.find('.note-dropzone-message'); this.documentEventHandlers.onDragenter = function (e) { var isCodeview = _this.context.invoke('codeview.isActivated'); var hasEditorSize = _this.$editor.width() > 0 && _this.$editor.height() > 0; if (!isCodeview && !collection.length && hasEditorSize) { _this.$editor.addClass('dragover'); _this.$dropzone.width(_this.$editor.width()); _this.$dropzone.height(_this.$editor.height()); $dropzoneMessage.text(_this.lang.image.dragImageHere); } collection = collection.add(e.target); }; this.documentEventHandlers.onDragleave = function (e) { collection = collection.not(e.target); // If nodeName is BODY, then just make it over (fix for IE) if (!collection.length || e.target.nodeName === 'BODY') { collection = external_jQuery_default()(); _this.$editor.removeClass('dragover'); } }; this.documentEventHandlers.onDrop = function () { collection = external_jQuery_default()(); _this.$editor.removeClass('dragover'); }; // show dropzone on dragenter when dragging a object to document // -but only if the editor is visible, i.e. has a positive width and height this.$eventListener.on('dragenter', this.documentEventHandlers.onDragenter).on('dragleave', this.documentEventHandlers.onDragleave).on('drop', this.documentEventHandlers.onDrop); // change dropzone's message on hover. this.$dropzone.on('dragenter', function () { _this.$dropzone.addClass('hover'); $dropzoneMessage.text(_this.lang.image.dropImage); }).on('dragleave', function () { _this.$dropzone.removeClass('hover'); $dropzoneMessage.text(_this.lang.image.dragImageHere); }); // attach dropImage this.$dropzone.on('drop', function (event) { var dataTransfer = event.originalEvent.dataTransfer; // stop the browser from opening the dropped content event.preventDefault(); if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { _this.$editable.focus(); _this.context.invoke('editor.insertImagesOrCallback', dataTransfer.files); } else { external_jQuery_default().each(dataTransfer.types, function (idx, type) { // skip moz-specific types if (type.toLowerCase().indexOf('_moz_') > -1) { return; } var content = dataTransfer.getData(type); if (type.toLowerCase().indexOf('text') > -1) { _this.context.invoke('editor.pasteHTML', content); } else { external_jQuery_default()(content).each(function (idx, item) { _this.context.invoke('editor.insertNode', item); }); } }); } }).on('dragover', false); // prevent default dragover event } }, { key: "destroy", value: function destroy() { var _this2 = this; Object.keys(this.documentEventHandlers).forEach(function (key) { _this2.$eventListener.off(key.substr(2).toLowerCase(), _this2.documentEventHandlers[key]); }); this.documentEventHandlers = {}; } }]); return Dropzone; }(); ;// CONCATENATED MODULE: ./src/js/module/Codeview.js function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function Codeview_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Codeview_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Codeview_createClass(Constructor, protoProps, staticProps) { if (protoProps) Codeview_defineProperties(Constructor.prototype, protoProps); if (staticProps) Codeview_defineProperties(Constructor, staticProps); return Constructor; } /** * @class Codeview */ var CodeView = /*#__PURE__*/function () { function CodeView(context) { Codeview_classCallCheck(this, CodeView); this.context = context; this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.options = context.options; this.CodeMirrorConstructor = window.CodeMirror; if (this.options.codemirror.CodeMirrorConstructor) { this.CodeMirrorConstructor = this.options.codemirror.CodeMirrorConstructor; } } Codeview_createClass(CodeView, [{ key: "sync", value: function sync(html) { var isCodeview = this.isActivated(); var CodeMirror = this.CodeMirrorConstructor; if (isCodeview) { if (html) { if (CodeMirror) { this.$codable.data('cmEditor').getDoc().setValue(html); } else { this.$codable.val(html); } } else { if (CodeMirror) { this.$codable.data('cmEditor').save(); } } } } }, { key: "initialize", value: function initialize() { var _this = this; this.$codable.on('keyup', function (event) { if (event.keyCode === key.code.ESCAPE) { _this.deactivate(); } }); } /** * @return {Boolean} */ }, { key: "isActivated", value: function isActivated() { return this.$editor.hasClass('codeview'); } /** * toggle codeview */ }, { key: "toggle", value: function toggle() { if (this.isActivated()) { this.deactivate(); } else { this.activate(); } this.context.triggerEvent('codeview.toggled'); } /** * purify input value * @param value * @returns {*} */ }, { key: "purify", value: function purify(value) { if (this.options.codeviewFilter) { // filter code view regex value = value.replace(this.options.codeviewFilterRegex, ''); // allow specific iframe tag if (this.options.codeviewIframeFilter) { var whitelist = this.options.codeviewIframeWhitelistSrc.concat(this.options.codeviewIframeWhitelistSrcBase); value = value.replace(/(<iframe.*?>.*?(?:<\/iframe>)?)/gi, function (tag) { // remove if src attribute is duplicated if (/<.+src(?==?('|"|\s)?)[\s\S]+src(?=('|"|\s)?)[^>]*?>/i.test(tag)) { return ''; } var _iterator = _createForOfIteratorHelper(whitelist), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var src = _step.value; // pass if src is trusted if (new RegExp('src="(https?:)?\/\/' + src.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '\/(.+)"').test(tag)) { return tag; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return ''; }); } } return value; } /** * activate code view */ }, { key: "activate", value: function activate() { var _this2 = this; var CodeMirror = this.CodeMirrorConstructor; this.$codable.val(dom.html(this.$editable, this.options.prettifyHtml)); this.$codable.height(this.$editable.height()); this.context.invoke('toolbar.updateCodeview', true); this.context.invoke('airPopover.updateCodeview', true); this.$editor.addClass('codeview'); this.$codable.focus(); // activate CodeMirror as codable if (CodeMirror) { var cmEditor = CodeMirror.fromTextArea(this.$codable[0], this.options.codemirror); // CodeMirror TernServer if (this.options.codemirror.tern) { var server = new CodeMirror.TernServer(this.options.codemirror.tern); cmEditor.ternServer = server; cmEditor.on('cursorActivity', function (cm) { server.updateArgHints(cm); }); } cmEditor.on('blur', function (event) { _this2.context.triggerEvent('blur.codeview', cmEditor.getValue(), event); }); cmEditor.on('change', function () { _this2.context.triggerEvent('change.codeview', cmEditor.getValue(), cmEditor); }); // CodeMirror hasn't Padding. cmEditor.setSize(null, this.$editable.outerHeight()); this.$codable.data('cmEditor', cmEditor); } else { this.$codable.on('blur', function (event) { _this2.context.triggerEvent('blur.codeview', _this2.$codable.val(), event); }); this.$codable.on('input', function () { _this2.context.triggerEvent('change.codeview', _this2.$codable.val(), _this2.$codable); }); } } /** * deactivate code view */ }, { key: "deactivate", value: function deactivate() { var CodeMirror = this.CodeMirrorConstructor; // deactivate CodeMirror as codable if (CodeMirror) { var cmEditor = this.$codable.data('cmEditor'); this.$codable.val(cmEditor.getValue()); cmEditor.toTextArea(); } var value = this.purify(dom.value(this.$codable, this.options.prettifyHtml) || dom.emptyPara); var isChange = this.$editable.html() !== value; this.$editable.html(value); this.$editable.height(this.options.height ? this.$codable.height() : 'auto'); this.$editor.removeClass('codeview'); if (isChange) { this.context.triggerEvent('change', this.$editable.html(), this.$editable); } this.$editable.focus(); this.context.invoke('toolbar.updateCodeview', false); this.context.invoke('airPopover.updateCodeview', false); } }, { key: "destroy", value: function destroy() { if (this.isActivated()) { this.deactivate(); } } }]); return CodeView; }(); ;// CONCATENATED MODULE: ./src/js/module/Statusbar.js function Statusbar_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Statusbar_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Statusbar_createClass(Constructor, protoProps, staticProps) { if (protoProps) Statusbar_defineProperties(Constructor.prototype, protoProps); if (staticProps) Statusbar_defineProperties(Constructor, staticProps); return Constructor; } var EDITABLE_PADDING = 24; var Statusbar = /*#__PURE__*/function () { function Statusbar(context) { Statusbar_classCallCheck(this, Statusbar); this.$document = external_jQuery_default()(document); this.$statusbar = context.layoutInfo.statusbar; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.options = context.options; } Statusbar_createClass(Statusbar, [{ key: "initialize", value: function initialize() { var _this = this; if (this.options.airMode || this.options.disableResizeEditor) { this.destroy(); return; } this.$statusbar.on('mousedown', function (event) { event.preventDefault(); event.stopPropagation(); var editableTop = _this.$editable.offset().top - _this.$document.scrollTop(); var editableCodeTop = _this.$codable.offset().top - _this.$document.scrollTop(); var onMouseMove = function onMouseMove(event) { var height = event.clientY - (editableTop + EDITABLE_PADDING); var heightCode = event.clientY - (editableCodeTop + EDITABLE_PADDING); height = _this.options.minheight > 0 ? Math.max(height, _this.options.minheight) : height; height = _this.options.maxHeight > 0 ? Math.min(height, _this.options.maxHeight) : height; heightCode = _this.options.minheight > 0 ? Math.max(heightCode, _this.options.minheight) : heightCode; heightCode = _this.options.maxHeight > 0 ? Math.min(heightCode, _this.options.maxHeight) : heightCode; _this.$editable.height(height); _this.$codable.height(heightCode); }; _this.$document.on('mousemove', onMouseMove).one('mouseup', function () { _this.$document.off('mousemove', onMouseMove); }); }); } }, { key: "destroy", value: function destroy() { this.$statusbar.off(); this.$statusbar.addClass('locked'); } }]); return Statusbar; }(); ;// CONCATENATED MODULE: ./src/js/module/Fullscreen.js function Fullscreen_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Fullscreen_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Fullscreen_createClass(Constructor, protoProps, staticProps) { if (protoProps) Fullscreen_defineProperties(Constructor.prototype, protoProps); if (staticProps) Fullscreen_defineProperties(Constructor, staticProps); return Constructor; } var Fullscreen = /*#__PURE__*/function () { function Fullscreen(context) { var _this = this; Fullscreen_classCallCheck(this, Fullscreen); this.context = context; this.$editor = context.layoutInfo.editor; this.$toolbar = context.layoutInfo.toolbar; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.$window = external_jQuery_default()(window); this.$scrollbar = external_jQuery_default()('html, body'); this.scrollbarClassName = 'note-fullscreen-body'; this.onResize = function () { _this.resizeTo({ h: _this.$window.height() - _this.$toolbar.outerHeight() }); }; } Fullscreen_createClass(Fullscreen, [{ key: "resizeTo", value: function resizeTo(size) { this.$editable.css('height', size.h); this.$codable.css('height', size.h); if (this.$codable.data('cmeditor')) { this.$codable.data('cmeditor').setsize(null, size.h); } } /** * toggle fullscreen */ }, { key: "toggle", value: function toggle() { this.$editor.toggleClass('fullscreen'); var isFullscreen = this.isFullscreen(); this.$scrollbar.toggleClass(this.scrollbarClassName, isFullscreen); if (isFullscreen) { this.$editable.data('orgHeight', this.$editable.css('height')); this.$editable.data('orgMaxHeight', this.$editable.css('maxHeight')); this.$editable.css('maxHeight', ''); this.$window.on('resize', this.onResize).trigger('resize'); } else { this.$window.off('resize', this.onResize); this.resizeTo({ h: this.$editable.data('orgHeight') }); this.$editable.css('maxHeight', this.$editable.css('orgMaxHeight')); } this.context.invoke('toolbar.updateFullscreen', isFullscreen); } }, { key: "isFullscreen", value: function isFullscreen() { return this.$editor.hasClass('fullscreen'); } }, { key: "destroy", value: function destroy() { this.$scrollbar.removeClass(this.scrollbarClassName); } }]); return Fullscreen; }(); ;// CONCATENATED MODULE: ./src/js/module/Handle.js function Handle_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Handle_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Handle_createClass(Constructor, protoProps, staticProps) { if (protoProps) Handle_defineProperties(Constructor.prototype, protoProps); if (staticProps) Handle_defineProperties(Constructor, staticProps); return Constructor; } var Handle = /*#__PURE__*/function () { function Handle(context) { var _this = this; Handle_classCallCheck(this, Handle); this.context = context; this.$document = external_jQuery_default()(document); this.$editingArea = context.layoutInfo.editingArea; this.options = context.options; this.lang = this.options.langInfo; this.events = { 'summernote.mousedown': function summernoteMousedown(we, e) { if (_this.update(e.target, e)) { e.preventDefault(); } }, 'summernote.keyup summernote.scroll summernote.change summernote.dialog.shown': function summernoteKeyupSummernoteScrollSummernoteChangeSummernoteDialogShown() { _this.update(); }, 'summernote.disable summernote.blur': function summernoteDisableSummernoteBlur() { _this.hide(); }, 'summernote.codeview.toggled': function summernoteCodeviewToggled() { _this.update(); } }; } Handle_createClass(Handle, [{ key: "initialize", value: function initialize() { var _this2 = this; this.$handle = external_jQuery_default()(['<div class="note-handle">', '<div class="note-control-selection">', '<div class="note-control-selection-bg"></div>', '<div class="note-control-holder note-control-nw"></div>', '<div class="note-control-holder note-control-ne"></div>', '<div class="note-control-holder note-control-sw"></div>', '<div class="', this.options.disableResizeImage ? 'note-control-holder' : 'note-control-sizing', ' note-control-se"></div>', this.options.disableResizeImage ? '' : '<div class="note-control-selection-info"></div>', '</div>', '</div>'].join('')).prependTo(this.$editingArea); this.$handle.on('mousedown', function (event) { if (dom.isControlSizing(event.target)) { event.preventDefault(); event.stopPropagation(); var $target = _this2.$handle.find('.note-control-selection').data('target'); var posStart = $target.offset(); var scrollTop = _this2.$document.scrollTop(); var onMouseMove = function onMouseMove(event) { _this2.context.invoke('editor.resizeTo', { x: event.clientX - posStart.left, y: event.clientY - (posStart.top - scrollTop) }, $target, !event.shiftKey); _this2.update($target[0], event); }; _this2.$document.on('mousemove', onMouseMove).one('mouseup', function (e) { e.preventDefault(); _this2.$document.off('mousemove', onMouseMove); _this2.context.invoke('editor.afterCommand'); }); if (!$target.data('ratio')) { // original ratio. $target.data('ratio', $target.height() / $target.width()); } } }); // Listen for scrolling on the handle overlay. this.$handle.on('wheel', function (e) { e.preventDefault(); _this2.update(); }); } }, { key: "destroy", value: function destroy() { this.$handle.remove(); } }, { key: "update", value: function update(target, event) { if (this.context.isDisabled()) { return false; } var isImage = dom.isImg(target); var $selection = this.$handle.find('.note-control-selection'); this.context.invoke('imagePopover.update', target, event); if (isImage) { var $image = external_jQuery_default()(target); var position = $image.position(); var pos = { left: position.left + parseInt($image.css('marginLeft'), 10), top: position.top + parseInt($image.css('marginTop'), 10) }; // exclude margin var imageSize = { w: $image.outerWidth(false), h: $image.outerHeight(false) }; $selection.css({ display: 'block', left: pos.left, top: pos.top, width: imageSize.w, height: imageSize.h }).data('target', $image); // save current image element. var origImageObj = new Image(); origImageObj.src = $image.attr('src'); var sizingText = imageSize.w + 'x' + imageSize.h + ' (' + this.lang.image.original + ': ' + origImageObj.width + 'x' + origImageObj.height + ')'; $selection.find('.note-control-selection-info').text(sizingText); this.context.invoke('editor.saveTarget', target); } else { this.hide(); } return isImage; } /** * hide * * @param {jQuery} $handle */ }, { key: "hide", value: function hide() { this.context.invoke('editor.clearTarget'); this.$handle.children().hide(); } }]); return Handle; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoLink.js function AutoLink_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoLink_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoLink_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoLink_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoLink_defineProperties(Constructor, staticProps); return Constructor; } var defaultScheme = 'http://'; var linkPattern = /^([A-Za-z][A-Za-z0-9+-.]*\:[\/]{2}|tel:|mailto:[A-Z0-9._%+-]+@|xmpp:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i; var AutoLink = /*#__PURE__*/function () { function AutoLink(context) { var _this = this; AutoLink_classCallCheck(this, AutoLink); this.context = context; this.options = context.options; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); } }; } AutoLink_createClass(AutoLink, [{ key: "initialize", value: function initialize() { this.lastWordRange = null; } }, { key: "destroy", value: function destroy() { this.lastWordRange = null; } }, { key: "replace", value: function replace() { if (!this.lastWordRange) { return; } var keyword = this.lastWordRange.toString(); var match = keyword.match(linkPattern); if (match && (match[1] || match[2])) { var link = match[1] ? keyword : defaultScheme + keyword; var urlText = this.options.showDomainOnlyForAutolink ? keyword.replace(/^(?:https?:\/\/)?(?:tel?:?)?(?:mailto?:?)?(?:xmpp?:?)?(?:www\.)?/i, '').split('/')[0] : keyword; var node = external_jQuery_default()('<a></a>').html(urlText).attr('href', link)[0]; if (this.context.options.linkTargetBlank) { external_jQuery_default()(node).attr('target', '_blank'); } this.lastWordRange.insertNode(node); this.lastWordRange = null; this.context.invoke('editor.focus'); } } }, { key: "handleKeydown", value: function handleKeydown(e) { if (lists.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) { var wordRange = this.context.invoke('editor.createRange').getWordRange(); this.lastWordRange = wordRange; } } }, { key: "handleKeyup", value: function handleKeyup(e) { if (lists.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) { this.replace(); } } }]); return AutoLink; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoSync.js function AutoSync_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoSync_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoSync_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoSync_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoSync_defineProperties(Constructor, staticProps); return Constructor; } /** * textarea auto sync. */ var AutoSync = /*#__PURE__*/function () { function AutoSync(context) { var _this = this; AutoSync_classCallCheck(this, AutoSync); this.$note = context.layoutInfo.note; this.events = { 'summernote.change': function summernoteChange() { _this.$note.val(context.invoke('code')); } }; } AutoSync_createClass(AutoSync, [{ key: "shouldInitialize", value: function shouldInitialize() { return dom.isTextarea(this.$note[0]); } }]); return AutoSync; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoReplace.js function AutoReplace_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoReplace_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoReplace_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoReplace_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoReplace_defineProperties(Constructor, staticProps); return Constructor; } var AutoReplace = /*#__PURE__*/function () { function AutoReplace(context) { var _this = this; AutoReplace_classCallCheck(this, AutoReplace); this.context = context; this.options = context.options.replace || {}; this.keys = [key.code.ENTER, key.code.SPACE, key.code.PERIOD, key.code.COMMA, key.code.SEMICOLON, key.code.SLASH]; this.previousKeydownCode = null; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); } }; } AutoReplace_createClass(AutoReplace, [{ key: "shouldInitialize", value: function shouldInitialize() { return !!this.options.match; } }, { key: "initialize", value: function initialize() { this.lastWord = null; } }, { key: "destroy", value: function destroy() { this.lastWord = null; } }, { key: "replace", value: function replace() { if (!this.lastWord) { return; } var self = this; var keyword = this.lastWord.toString(); this.options.match(keyword, function (match) { if (match) { var node = ''; if (typeof match === 'string') { node = dom.createText(match); } else if (match instanceof jQuery) { node = match[0]; } else if (match instanceof Node) { node = match; } if (!node) return; self.lastWord.insertNode(node); self.lastWord = null; self.context.invoke('editor.focus'); } }); } }, { key: "handleKeydown", value: function handleKeydown(e) { // this forces it to remember the last whole word, even if multiple termination keys are pressed // before the previous key is let go. if (this.previousKeydownCode && lists.contains(this.keys, this.previousKeydownCode)) { this.previousKeydownCode = e.keyCode; return; } if (lists.contains(this.keys, e.keyCode)) { var wordRange = this.context.invoke('editor.createRange').getWordRange(); this.lastWord = wordRange; } this.previousKeydownCode = e.keyCode; } }, { key: "handleKeyup", value: function handleKeyup(e) { if (lists.contains(this.keys, e.keyCode)) { this.replace(); } } }]); return AutoReplace; }(); ;// CONCATENATED MODULE: ./src/js/module/Placeholder.js function Placeholder_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Placeholder_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Placeholder_createClass(Constructor, protoProps, staticProps) { if (protoProps) Placeholder_defineProperties(Constructor.prototype, protoProps); if (staticProps) Placeholder_defineProperties(Constructor, staticProps); return Constructor; } var Placeholder = /*#__PURE__*/function () { function Placeholder(context) { var _this = this; Placeholder_classCallCheck(this, Placeholder); this.context = context; this.$editingArea = context.layoutInfo.editingArea; this.options = context.options; if (this.options.inheritPlaceholder === true) { // get placeholder value from the original element this.options.placeholder = this.context.$note.attr('placeholder') || this.options.placeholder; } this.events = { 'summernote.init summernote.change': function summernoteInitSummernoteChange() { _this.update(); }, 'summernote.codeview.toggled': function summernoteCodeviewToggled() { _this.update(); } }; } Placeholder_createClass(Placeholder, [{ key: "shouldInitialize", value: function shouldInitialize() { return !!this.options.placeholder; } }, { key: "initialize", value: function initialize() { var _this2 = this; this.$placeholder = external_jQuery_default()('<div class="note-placeholder"></div>'); this.$placeholder.on('click', function () { _this2.context.invoke('focus'); }).html(this.options.placeholder).prependTo(this.$editingArea); this.update(); } }, { key: "destroy", value: function destroy() { this.$placeholder.remove(); } }, { key: "update", value: function update() { var isShow = !this.context.invoke('codeview.isActivated') && this.context.invoke('editor.isEmpty'); this.$placeholder.toggle(isShow); } }]); return Placeholder; }(); ;// CONCATENATED MODULE: ./src/js/module/Buttons.js function Buttons_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Buttons_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Buttons_createClass(Constructor, protoProps, staticProps) { if (protoProps) Buttons_defineProperties(Constructor.prototype, protoProps); if (staticProps) Buttons_defineProperties(Constructor, staticProps); return Constructor; } var Buttons = /*#__PURE__*/function () { function Buttons(context) { Buttons_classCallCheck(this, Buttons); this.ui = (external_jQuery_default()).summernote.ui; this.context = context; this.$toolbar = context.layoutInfo.toolbar; this.options = context.options; this.lang = this.options.langInfo; this.invertedKeyMap = func.invertObject(this.options.keyMap[env.isMac ? 'mac' : 'pc']); } Buttons_createClass(Buttons, [{ key: "representShortcut", value: function representShortcut(editorMethod) { var shortcut = this.invertedKeyMap[editorMethod]; if (!this.options.shortcuts || !shortcut) { return ''; } if (env.isMac) { shortcut = shortcut.replace('CMD', '⌘').replace('SHIFT', '⇧'); } shortcut = shortcut.replace('BACKSLASH', '\\').replace('SLASH', '/').replace('LEFTBRACKET', '[').replace('RIGHTBRACKET', ']'); return ' (' + shortcut + ')'; } }, { key: "button", value: function button(o) { if (!this.options.tooltip && o.tooltip) { delete o.tooltip; } o.container = this.options.container; return this.ui.button(o); } }, { key: "initialize", value: function initialize() { this.addToolbarButtons(); this.addImagePopoverButtons(); this.addLinkPopoverButtons(); this.addTablePopoverButtons(); this.fontInstalledMap = {}; } }, { key: "destroy", value: function destroy() { delete this.fontInstalledMap; } }, { key: "isFontInstalled", value: function isFontInstalled(name) { if (!Object.prototype.hasOwnProperty.call(this.fontInstalledMap, name)) { this.fontInstalledMap[name] = env.isFontInstalled(name) || lists.contains(this.options.fontNamesIgnoreCheck, name); } return this.fontInstalledMap[name]; } }, { key: "isFontDeservedToAdd", value: function isFontDeservedToAdd(name) { name = name.toLowerCase(); return name !== '' && this.isFontInstalled(name) && env.genericFontFamilies.indexOf(name) === -1; } }, { key: "colorPalette", value: function colorPalette(className, tooltip, backColor, foreColor) { var _this = this; return this.ui.buttonGroup({ className: 'note-color ' + className, children: [this.button({ className: 'note-current-color-button', contents: this.ui.icon(this.options.icons.font + ' note-recent-color'), tooltip: tooltip, click: function click(e) { var $button = external_jQuery_default()(e.currentTarget); if (backColor && foreColor) { _this.context.invoke('editor.color', { backColor: $button.attr('data-backColor'), foreColor: $button.attr('data-foreColor') }); } else if (backColor) { _this.context.invoke('editor.color', { backColor: $button.attr('data-backColor') }); } else if (foreColor) { _this.context.invoke('editor.color', { foreColor: $button.attr('data-foreColor') }); } }, callback: function callback($button) { var $recentColor = $button.find('.note-recent-color'); if (backColor) { $recentColor.css('background-color', _this.options.colorButton.backColor); $button.attr('data-backColor', _this.options.colorButton.backColor); } if (foreColor) { $recentColor.css('color', _this.options.colorButton.foreColor); $button.attr('data-foreColor', _this.options.colorButton.foreColor); } else { $recentColor.css('color', 'transparent'); } } }), this.button({ className: 'dropdown-toggle', contents: this.ui.dropdownButtonContents('', this.options), tooltip: this.lang.color.more, data: { toggle: 'dropdown' } }), this.ui.dropdown({ items: (backColor ? ['<div class="note-palette">', '<div class="note-palette-title">' + this.lang.color.background + '</div>', '<div>', '<button type="button" class="note-color-reset btn btn-light btn-default" data-event="backColor" data-value="transparent">', this.lang.color.transparent, '</button>', '</div>', '<div class="note-holder" data-event="backColor"><!-- back colors --></div>', '<div>', '<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="backColorPicker-' + this.options.id + '">', this.lang.color.cpSelect, '</button>', '<input type="color" id="backColorPicker-' + this.options.id + '" class="note-btn note-color-select-btn" value="' + this.options.colorButton.backColor + '" data-event="backColorPalette-' + this.options.id + '">', '</div>', '<div class="note-holder-custom" id="backColorPalette-' + this.options.id + '" data-event="backColor"></div>', '</div>'].join('') : '') + (foreColor ? ['<div class="note-palette">', '<div class="note-palette-title">' + this.lang.color.foreground + '</div>', '<div>', '<button type="button" class="note-color-reset btn btn-light btn-default" data-event="removeFormat" data-value="foreColor">', this.lang.color.resetToDefault, '</button>', '</div>', '<div class="note-holder" data-event="foreColor"><!-- fore colors --></div>', '<div>', '<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="foreColorPicker-' + this.options.id + '">', this.lang.color.cpSelect, '</button>', '<input type="color" id="foreColorPicker-' + this.options.id + '" class="note-btn note-color-select-btn" value="' + this.options.colorButton.foreColor + '" data-event="foreColorPalette-' + this.options.id + '">', '</div>', // Fix missing Div, Commented to find easily if it's wrong '<div class="note-holder-custom" id="foreColorPalette-' + this.options.id + '" data-event="foreColor"></div>', '</div>'].join('') : ''), callback: function callback($dropdown) { $dropdown.find('.note-holder').each(function (idx, item) { var $holder = external_jQuery_default()(item); $holder.append(_this.ui.palette({ colors: _this.options.colors, colorsName: _this.options.colorsName, eventName: $holder.data('event'), container: _this.options.container, tooltip: _this.options.tooltip }).render()); }); /* TODO: do we have to record recent custom colors within cookies? */ var customColors = [['#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF']]; $dropdown.find('.note-holder-custom').each(function (idx, item) { var $holder = external_jQuery_default()(item); $holder.append(_this.ui.palette({ colors: customColors, colorsName: customColors, eventName: $holder.data('event'), container: _this.options.container, tooltip: _this.options.tooltip }).render()); }); $dropdown.find('input[type=color]').each(function (idx, item) { external_jQuery_default()(item).change(function () { var $chip = $dropdown.find('#' + external_jQuery_default()(this).data('event')).find('.note-color-btn').first(); var color = this.value.toUpperCase(); $chip.css('background-color', color).attr('aria-label', color).attr('data-value', color).attr('data-original-title', color); $chip.click(); }); }); }, click: function click(event) { event.stopPropagation(); var $parent = external_jQuery_default()('.' + className).find('.note-dropdown-menu'); var $button = external_jQuery_default()(event.target); var eventName = $button.data('event'); var value = $button.attr('data-value'); if (eventName === 'openPalette') { var $picker = $parent.find('#' + value); var $palette = external_jQuery_default()($parent.find('#' + $picker.data('event')).find('.note-color-row')[0]); // Shift palette chips var $chip = $palette.find('.note-color-btn').last().detach(); // Set chip attributes var color = $picker.val(); $chip.css('background-color', color).attr('aria-label', color).attr('data-value', color).attr('data-original-title', color); $palette.prepend($chip); $picker.click(); } else { if (lists.contains(['backColor', 'foreColor'], eventName)) { var key = eventName === 'backColor' ? 'background-color' : 'color'; var $color = $button.closest('.note-color').find('.note-recent-color'); var $currentButton = $button.closest('.note-color').find('.note-current-color-button'); $color.css(key, value); $currentButton.attr('data-' + eventName, value); } _this.context.invoke('editor.' + eventName, value); } } })] }).render(); } }, { key: "addToolbarButtons", value: function addToolbarButtons() { var _this2 = this; this.context.memo('button.style', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.magic), _this2.options), tooltip: _this2.lang.style.style, data: { toggle: 'dropdown' } }), _this2.ui.dropdown({ className: 'dropdown-style', items: _this2.options.styleTags, title: _this2.lang.style.style, template: function template(item) { // TBD: need to be simplified if (typeof item === 'string') { item = { tag: item, title: Object.prototype.hasOwnProperty.call(_this2.lang.style, item) ? _this2.lang.style[item] : item }; } var tag = item.tag; var title = item.title; var style = item.style ? ' style="' + item.style + '" ' : ''; var className = item.className ? ' class="' + item.className + '"' : ''; return '<' + tag + style + className + '>' + title + '</' + tag + '>'; }, click: _this2.context.createInvokeHandler('editor.formatBlock') })]).render(); }); var _loop = function _loop(styleIdx, styleLen) { var item = _this2.options.styleTags[styleIdx]; _this2.context.memo('button.style.' + item, function () { return _this2.button({ className: 'note-btn-style-' + item, contents: '<div data-value="' + item + '">' + item.toUpperCase() + '</div>', tooltip: _this2.lang.style[item], click: _this2.context.createInvokeHandler('editor.formatBlock') }).render(); }); }; for (var styleIdx = 0, styleLen = this.options.styleTags.length; styleIdx < styleLen; styleIdx++) { _loop(styleIdx, styleLen); } this.context.memo('button.bold', function () { return _this2.button({ className: 'note-btn-bold', contents: _this2.ui.icon(_this2.options.icons.bold), tooltip: _this2.lang.font.bold + _this2.representShortcut('bold'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.bold') }).render(); }); this.context.memo('button.italic', function () { return _this2.button({ className: 'note-btn-italic', contents: _this2.ui.icon(_this2.options.icons.italic), tooltip: _this2.lang.font.italic + _this2.representShortcut('italic'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.italic') }).render(); }); this.context.memo('button.underline', function () { return _this2.button({ className: 'note-btn-underline', contents: _this2.ui.icon(_this2.options.icons.underline), tooltip: _this2.lang.font.underline + _this2.representShortcut('underline'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.underline') }).render(); }); this.context.memo('button.clear', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.eraser), tooltip: _this2.lang.font.clear + _this2.representShortcut('removeFormat'), click: _this2.context.createInvokeHandler('editor.removeFormat') }).render(); }); this.context.memo('button.strikethrough', function () { return _this2.button({ className: 'note-btn-strikethrough', contents: _this2.ui.icon(_this2.options.icons.strikethrough), tooltip: _this2.lang.font.strikethrough + _this2.representShortcut('strikethrough'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.strikethrough') }).render(); }); this.context.memo('button.superscript', function () { return _this2.button({ className: 'note-btn-superscript', contents: _this2.ui.icon(_this2.options.icons.superscript), tooltip: _this2.lang.font.superscript, click: _this2.context.createInvokeHandlerAndUpdateState('editor.superscript') }).render(); }); this.context.memo('button.subscript', function () { return _this2.button({ className: 'note-btn-subscript', contents: _this2.ui.icon(_this2.options.icons.subscript), tooltip: _this2.lang.font.subscript, click: _this2.context.createInvokeHandlerAndUpdateState('editor.subscript') }).render(); }); this.context.memo('button.fontname', function () { var styleInfo = _this2.context.invoke('editor.currentStyle'); if (_this2.options.addDefaultFonts) { // Add 'default' fonts into the fontnames array if not exist external_jQuery_default().each(styleInfo['font-family'].split(','), function (idx, fontname) { fontname = fontname.trim().replace(/['"]+/g, ''); if (_this2.isFontDeservedToAdd(fontname)) { if (_this2.options.fontNames.indexOf(fontname) === -1) { _this2.options.fontNames.push(fontname); } } }); } return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontname"></span>', _this2.options), tooltip: _this2.lang.font.name, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontname', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontNames.filter(_this2.isFontInstalled.bind(_this2)), title: _this2.lang.font.name, template: function template(item) { return '<span style="font-family: ' + env.validFontName(item) + '">' + item + '</span>'; }, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontName') })]).render(); }); this.context.memo('button.fontsize', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontsize"></span>', _this2.options), tooltip: _this2.lang.font.size, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontsize', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontSizes, title: _this2.lang.font.size, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontSize') })]).render(); }); this.context.memo('button.fontsizeunit', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontsizeunit"></span>', _this2.options), tooltip: _this2.lang.font.sizeunit, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontsizeunit', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontSizeUnits, title: _this2.lang.font.sizeunit, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontSizeUnit') })]).render(); }); this.context.memo('button.color', function () { return _this2.colorPalette('note-color-all', _this2.lang.color.recent, true, true); }); this.context.memo('button.forecolor', function () { return _this2.colorPalette('note-color-fore', _this2.lang.color.foreground, false, true); }); this.context.memo('button.backcolor', function () { return _this2.colorPalette('note-color-back', _this2.lang.color.background, true, false); }); this.context.memo('button.ul', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.unorderedlist), tooltip: _this2.lang.lists.unordered + _this2.representShortcut('insertUnorderedList'), click: _this2.context.createInvokeHandler('editor.insertUnorderedList') }).render(); }); this.context.memo('button.ol', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.orderedlist), tooltip: _this2.lang.lists.ordered + _this2.representShortcut('insertOrderedList'), click: _this2.context.createInvokeHandler('editor.insertOrderedList') }).render(); }); var justifyLeft = this.button({ contents: this.ui.icon(this.options.icons.alignLeft), tooltip: this.lang.paragraph.left + this.representShortcut('justifyLeft'), click: this.context.createInvokeHandler('editor.justifyLeft') }); var justifyCenter = this.button({ contents: this.ui.icon(this.options.icons.alignCenter), tooltip: this.lang.paragraph.center + this.representShortcut('justifyCenter'), click: this.context.createInvokeHandler('editor.justifyCenter') }); var justifyRight = this.button({ contents: this.ui.icon(this.options.icons.alignRight), tooltip: this.lang.paragraph.right + this.representShortcut('justifyRight'), click: this.context.createInvokeHandler('editor.justifyRight') }); var justifyFull = this.button({ contents: this.ui.icon(this.options.icons.alignJustify), tooltip: this.lang.paragraph.justify + this.representShortcut('justifyFull'), click: this.context.createInvokeHandler('editor.justifyFull') }); var outdent = this.button({ contents: this.ui.icon(this.options.icons.outdent), tooltip: this.lang.paragraph.outdent + this.representShortcut('outdent'), click: this.context.createInvokeHandler('editor.outdent') }); var indent = this.button({ contents: this.ui.icon(this.options.icons.indent), tooltip: this.lang.paragraph.indent + this.representShortcut('indent'), click: this.context.createInvokeHandler('editor.indent') }); this.context.memo('button.justifyLeft', func.invoke(justifyLeft, 'render')); this.context.memo('button.justifyCenter', func.invoke(justifyCenter, 'render')); this.context.memo('button.justifyRight', func.invoke(justifyRight, 'render')); this.context.memo('button.justifyFull', func.invoke(justifyFull, 'render')); this.context.memo('button.outdent', func.invoke(outdent, 'render')); this.context.memo('button.indent', func.invoke(indent, 'render')); this.context.memo('button.paragraph', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.alignLeft), _this2.options), tooltip: _this2.lang.paragraph.paragraph, data: { toggle: 'dropdown' } }), _this2.ui.dropdown([_this2.ui.buttonGroup({ className: 'note-align', children: [justifyLeft, justifyCenter, justifyRight, justifyFull] }), _this2.ui.buttonGroup({ className: 'note-list', children: [outdent, indent] })])]).render(); }); this.context.memo('button.height', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.textHeight), _this2.options), tooltip: _this2.lang.font.height, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ items: _this2.options.lineHeights, checkClassName: _this2.options.icons.menuCheck, className: 'dropdown-line-height', title: _this2.lang.font.height, click: _this2.context.createInvokeHandler('editor.lineHeight') })]).render(); }); this.context.memo('button.table', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.table), _this2.options), tooltip: _this2.lang.table.table, data: { toggle: 'dropdown' } }), _this2.ui.dropdown({ title: _this2.lang.table.table, className: 'note-table', items: ['<div class="note-dimension-picker">', '<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>', '<div class="note-dimension-picker-highlighted"></div>', '<div class="note-dimension-picker-unhighlighted"></div>', '</div>', '<div class="note-dimension-display">1 x 1</div>'].join('') })], { callback: function callback($node) { var $catcher = $node.find('.note-dimension-picker-mousecatcher'); $catcher.css({ width: _this2.options.insertTableMaxSize.col + 'em', height: _this2.options.insertTableMaxSize.row + 'em' }).mouseup(_this2.context.createInvokeHandler('editor.insertTable')).on('mousemove', _this2.tableMoveHandler.bind(_this2)); } }).render(); }); this.context.memo('button.link', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.link), tooltip: _this2.lang.link.link + _this2.representShortcut('linkDialog.show'), click: _this2.context.createInvokeHandler('linkDialog.show') }).render(); }); this.context.memo('button.picture', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.picture), tooltip: _this2.lang.image.image, click: _this2.context.createInvokeHandler('imageDialog.show') }).render(); }); this.context.memo('button.video', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.video), tooltip: _this2.lang.video.video, click: _this2.context.createInvokeHandler('videoDialog.show') }).render(); }); this.context.memo('button.hr', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.minus), tooltip: _this2.lang.hr.insert + _this2.representShortcut('insertHorizontalRule'), click: _this2.context.createInvokeHandler('editor.insertHorizontalRule') }).render(); }); this.context.memo('button.fullscreen', function () { return _this2.button({ className: 'btn-fullscreen note-codeview-keep', contents: _this2.ui.icon(_this2.options.icons.arrowsAlt), tooltip: _this2.lang.options.fullscreen, click: _this2.context.createInvokeHandler('fullscreen.toggle') }).render(); }); this.context.memo('button.codeview', function () { return _this2.button({ className: 'btn-codeview note-codeview-keep', contents: _this2.ui.icon(_this2.options.icons.code), tooltip: _this2.lang.options.codeview, click: _this2.context.createInvokeHandler('codeview.toggle') }).render(); }); this.context.memo('button.redo', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.redo), tooltip: _this2.lang.history.redo + _this2.representShortcut('redo'), click: _this2.context.createInvokeHandler('editor.redo') }).render(); }); this.context.memo('button.undo', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.undo), tooltip: _this2.lang.history.undo + _this2.representShortcut('undo'), click: _this2.context.createInvokeHandler('editor.undo') }).render(); }); this.context.memo('button.help', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.question), tooltip: _this2.lang.options.help, click: _this2.context.createInvokeHandler('helpDialog.show') }).render(); }); } /** * image: [ * ['imageResize', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']], * ['float', ['floatLeft', 'floatRight', 'floatNone']], * ['remove', ['removeMedia']], * ], */ }, { key: "addImagePopoverButtons", value: function addImagePopoverButtons() { var _this3 = this; // Image Size Buttons this.context.memo('button.resizeFull', function () { return _this3.button({ contents: '<span class="note-fontsize-10">100%</span>', tooltip: _this3.lang.image.resizeFull, click: _this3.context.createInvokeHandler('editor.resize', '1') }).render(); }); this.context.memo('button.resizeHalf', function () { return _this3.button({ contents: '<span class="note-fontsize-10">50%</span>', tooltip: _this3.lang.image.resizeHalf, click: _this3.context.createInvokeHandler('editor.resize', '0.5') }).render(); }); this.context.memo('button.resizeQuarter', function () { return _this3.button({ contents: '<span class="note-fontsize-10">25%</span>', tooltip: _this3.lang.image.resizeQuarter, click: _this3.context.createInvokeHandler('editor.resize', '0.25') }).render(); }); this.context.memo('button.resizeNone', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.rollback), tooltip: _this3.lang.image.resizeNone, click: _this3.context.createInvokeHandler('editor.resize', '0') }).render(); }); // Float Buttons this.context.memo('button.floatLeft', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.floatLeft), tooltip: _this3.lang.image.floatLeft, click: _this3.context.createInvokeHandler('editor.floatMe', 'left') }).render(); }); this.context.memo('button.floatRight', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.floatRight), tooltip: _this3.lang.image.floatRight, click: _this3.context.createInvokeHandler('editor.floatMe', 'right') }).render(); }); this.context.memo('button.floatNone', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.rollback), tooltip: _this3.lang.image.floatNone, click: _this3.context.createInvokeHandler('editor.floatMe', 'none') }).render(); }); // Remove Buttons this.context.memo('button.removeMedia', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.trash), tooltip: _this3.lang.image.remove, click: _this3.context.createInvokeHandler('editor.removeMedia') }).render(); }); } }, { key: "addLinkPopoverButtons", value: function addLinkPopoverButtons() { var _this4 = this; this.context.memo('button.linkDialogShow', function () { return _this4.button({ contents: _this4.ui.icon(_this4.options.icons.link), tooltip: _this4.lang.link.edit, click: _this4.context.createInvokeHandler('linkDialog.show') }).render(); }); this.context.memo('button.unlink', function () { return _this4.button({ contents: _this4.ui.icon(_this4.options.icons.unlink), tooltip: _this4.lang.link.unlink, click: _this4.context.createInvokeHandler('editor.unlink') }).render(); }); } /** * table : [ * ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']], * ['delete', ['deleteRow', 'deleteCol', 'deleteTable']] * ], */ }, { key: "addTablePopoverButtons", value: function addTablePopoverButtons() { var _this5 = this; this.context.memo('button.addRowUp', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowAbove), tooltip: _this5.lang.table.addRowAbove, click: _this5.context.createInvokeHandler('editor.addRow', 'top') }).render(); }); this.context.memo('button.addRowDown', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowBelow), tooltip: _this5.lang.table.addRowBelow, click: _this5.context.createInvokeHandler('editor.addRow', 'bottom') }).render(); }); this.context.memo('button.addColLeft', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colBefore), tooltip: _this5.lang.table.addColLeft, click: _this5.context.createInvokeHandler('editor.addCol', 'left') }).render(); }); this.context.memo('button.addColRight', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colAfter), tooltip: _this5.lang.table.addColRight, click: _this5.context.createInvokeHandler('editor.addCol', 'right') }).render(); }); this.context.memo('button.deleteRow', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowRemove), tooltip: _this5.lang.table.delRow, click: _this5.context.createInvokeHandler('editor.deleteRow') }).render(); }); this.context.memo('button.deleteCol', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colRemove), tooltip: _this5.lang.table.delCol, click: _this5.context.createInvokeHandler('editor.deleteCol') }).render(); }); this.context.memo('button.deleteTable', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.trash), tooltip: _this5.lang.table.delTable, click: _this5.context.createInvokeHandler('editor.deleteTable') }).render(); }); } }, { key: "build", value: function build($container, groups) { for (var groupIdx = 0, groupLen = groups.length; groupIdx < groupLen; groupIdx++) { var group = groups[groupIdx]; var groupName = Array.isArray(group) ? group[0] : group; var buttons = Array.isArray(group) ? group.length === 1 ? [group[0]] : group[1] : [group]; var $group = this.ui.buttonGroup({ className: 'note-' + groupName }).render(); for (var idx = 0, len = buttons.length; idx < len; idx++) { var btn = this.context.memo('button.' + buttons[idx]); if (btn) { $group.append(typeof btn === 'function' ? btn(this.context) : btn); } } $group.appendTo($container); } } /** * @param {jQuery} [$container] */ }, { key: "updateCurrentStyle", value: function updateCurrentStyle($container) { var $cont = $container || this.$toolbar; var styleInfo = this.context.invoke('editor.currentStyle'); this.updateBtnStates($cont, { '.note-btn-bold': function noteBtnBold() { return styleInfo['font-bold'] === 'bold'; }, '.note-btn-italic': function noteBtnItalic() { return styleInfo['font-italic'] === 'italic'; }, '.note-btn-underline': function noteBtnUnderline() { return styleInfo['font-underline'] === 'underline'; }, '.note-btn-subscript': function noteBtnSubscript() { return styleInfo['font-subscript'] === 'subscript'; }, '.note-btn-superscript': function noteBtnSuperscript() { return styleInfo['font-superscript'] === 'superscript'; }, '.note-btn-strikethrough': function noteBtnStrikethrough() { return styleInfo['font-strikethrough'] === 'strikethrough'; } }); if (styleInfo['font-family']) { var fontNames = styleInfo['font-family'].split(',').map(function (name) { return name.replace(/[\'\"]/g, '').replace(/\s+$/, '').replace(/^\s+/, ''); }); var fontName = lists.find(fontNames, this.isFontInstalled.bind(this)); $cont.find('.dropdown-fontname a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare string to avoid creating another func. var isChecked = $item.data('value') + '' === fontName + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontname').text(fontName).css('font-family', fontName); } if (styleInfo['font-size']) { var fontSize = styleInfo['font-size']; $cont.find('.dropdown-fontsize a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare with string to avoid creating another func. var isChecked = $item.data('value') + '' === fontSize + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontsize').text(fontSize); var fontSizeUnit = styleInfo['font-size-unit']; $cont.find('.dropdown-fontsizeunit a').each(function (idx, item) { var $item = external_jQuery_default()(item); var isChecked = $item.data('value') + '' === fontSizeUnit + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontsizeunit').text(fontSizeUnit); } if (styleInfo['line-height']) { var lineHeight = styleInfo['line-height']; $cont.find('.dropdown-line-height a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare with string to avoid creating another func. var isChecked = external_jQuery_default()(item).data('value') + '' === lineHeight + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-line-height').text(lineHeight); } } }, { key: "updateBtnStates", value: function updateBtnStates($container, infos) { var _this6 = this; external_jQuery_default().each(infos, function (selector, pred) { _this6.ui.toggleBtnActive($container.find(selector), pred()); }); } }, { key: "tableMoveHandler", value: function tableMoveHandler(event) { var PX_PER_EM = 18; var $picker = external_jQuery_default()(event.target.parentNode); // target is mousecatcher var $dimensionDisplay = $picker.next(); var $catcher = $picker.find('.note-dimension-picker-mousecatcher'); var $highlighted = $picker.find('.note-dimension-picker-highlighted'); var $unhighlighted = $picker.find('.note-dimension-picker-unhighlighted'); var posOffset; // HTML5 with jQuery - e.offsetX is undefined in Firefox if (event.offsetX === undefined) { var posCatcher = external_jQuery_default()(event.target).offset(); posOffset = { x: event.pageX - posCatcher.left, y: event.pageY - posCatcher.top }; } else { posOffset = { x: event.offsetX, y: event.offsetY }; } var dim = { c: Math.ceil(posOffset.x / PX_PER_EM) || 1, r: Math.ceil(posOffset.y / PX_PER_EM) || 1 }; $highlighted.css({ width: dim.c + 'em', height: dim.r + 'em' }); $catcher.data('value', dim.c + 'x' + dim.r); if (dim.c > 3 && dim.c < this.options.insertTableMaxSize.col) { $unhighlighted.css({ width: dim.c + 1 + 'em' }); } if (dim.r > 3 && dim.r < this.options.insertTableMaxSize.row) { $unhighlighted.css({ height: dim.r + 1 + 'em' }); } $dimensionDisplay.html(dim.c + ' x ' + dim.r); } }]); return Buttons; }(); ;// CONCATENATED MODULE: ./src/js/module/Toolbar.js function Toolbar_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Toolbar_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Toolbar_createClass(Constructor, protoProps, staticProps) { if (protoProps) Toolbar_defineProperties(Constructor.prototype, protoProps); if (staticProps) Toolbar_defineProperties(Constructor, staticProps); return Constructor; } var Toolbar = /*#__PURE__*/function () { function Toolbar(context) { Toolbar_classCallCheck(this, Toolbar); this.context = context; this.$window = external_jQuery_default()(window); this.$document = external_jQuery_default()(document); this.ui = (external_jQuery_default()).summernote.ui; this.$note = context.layoutInfo.note; this.$editor = context.layoutInfo.editor; this.$toolbar = context.layoutInfo.toolbar; this.$editable = context.layoutInfo.editable; this.$statusbar = context.layoutInfo.statusbar; this.options = context.options; this.isFollowing = false; this.followScroll = this.followScroll.bind(this); } Toolbar_createClass(Toolbar, [{ key: "shouldInitialize", value: function shouldInitialize() { return !this.options.airMode; } }, { key: "initialize", value: function initialize() { var _this = this; this.options.toolbar = this.options.toolbar || []; if (!this.options.toolbar.length) { this.$toolbar.hide(); } else { this.context.invoke('buttons.build', this.$toolbar, this.options.toolbar); } if (this.options.toolbarContainer) { this.$toolbar.appendTo(this.options.toolbarContainer); } this.changeContainer(false); this.$note.on('summernote.keyup summernote.mouseup summernote.change', function () { _this.context.invoke('buttons.updateCurrentStyle'); }); this.context.invoke('buttons.updateCurrentStyle'); if (this.options.followingToolbar) { this.$window.on('scroll resize', this.followScroll); } } }, { key: "destroy", value: function destroy() { this.$toolbar.children().remove(); if (this.options.followingToolbar) { this.$window.off('scroll resize', this.followScroll); } } }, { key: "followScroll", value: function followScroll() { if (this.$editor.hasClass('fullscreen')) { return false; } var editorHeight = this.$editor.outerHeight(); var editorWidth = this.$editor.width(); var toolbarHeight = this.$toolbar.height(); var statusbarHeight = this.$statusbar.height(); // check if the web app is currently using another static bar var otherBarHeight = 0; if (this.options.otherStaticBar) { otherBarHeight = external_jQuery_default()(this.options.otherStaticBar).outerHeight(); } var currentOffset = this.$document.scrollTop(); var editorOffsetTop = this.$editor.offset().top; var editorOffsetBottom = editorOffsetTop + editorHeight; var activateOffset = editorOffsetTop - otherBarHeight; var deactivateOffsetBottom = editorOffsetBottom - otherBarHeight - toolbarHeight - statusbarHeight; if (!this.isFollowing && currentOffset > activateOffset && currentOffset < deactivateOffsetBottom - toolbarHeight) { this.isFollowing = true; this.$editable.css({ marginTop: this.$toolbar.outerHeight() }); this.$toolbar.css({ position: 'fixed', top: otherBarHeight, width: editorWidth, zIndex: 1000 }); } else if (this.isFollowing && (currentOffset < activateOffset || currentOffset > deactivateOffsetBottom)) { this.isFollowing = false; this.$toolbar.css({ position: 'relative', top: 0, width: '100%', zIndex: 'auto' }); this.$editable.css({ marginTop: '' }); } } }, { key: "changeContainer", value: function changeContainer(isFullscreen) { if (isFullscreen) { this.$toolbar.prependTo(this.$editor); } else { if (this.options.toolbarContainer) { this.$toolbar.appendTo(this.options.toolbarContainer); } } if (this.options.followingToolbar) { this.followScroll(); } } }, { key: "updateFullscreen", value: function updateFullscreen(isFullscreen) { this.ui.toggleBtnActive(this.$toolbar.find('.btn-fullscreen'), isFullscreen); this.changeContainer(isFullscreen); } }, { key: "updateCodeview", value: function updateCodeview(isCodeview) { this.ui.toggleBtnActive(this.$toolbar.find('.btn-codeview'), isCodeview); if (isCodeview) { this.deactivate(); } else { this.activate(); } } }, { key: "activate", value: function activate(isIncludeCodeview) { var $btn = this.$toolbar.find('button'); if (!isIncludeCodeview) { $btn = $btn.not('.note-codeview-keep'); } this.ui.toggleBtn($btn, true); } }, { key: "deactivate", value: function deactivate(isIncludeCodeview) { var $btn = this.$toolbar.find('button'); if (!isIncludeCodeview) { $btn = $btn.not('.note-codeview-keep'); } this.ui.toggleBtn($btn, false); } }]); return Toolbar; }(); ;// CONCATENATED MODULE: ./src/js/module/LinkDialog.js function LinkDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function LinkDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function LinkDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) LinkDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) LinkDialog_defineProperties(Constructor, staticProps); return Constructor; } var LinkDialog = /*#__PURE__*/function () { function LinkDialog(context) { LinkDialog_classCallCheck(this, LinkDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; context.memo('help.linkDialog.show', this.options.langInfo.help['linkDialog.show']); } LinkDialog_createClass(LinkDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group">', "<label for=\"note-dialog-link-txt-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.link.textToDisplay, "</label>"), "<input id=\"note-dialog-link-txt-".concat(this.options.id, "\" class=\"note-link-text form-control note-form-control note-input\" type=\"text\"/>"), '</div>', '<div class="form-group note-form-group">', "<label for=\"note-dialog-link-url-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.link.url, "</label>"), "<input id=\"note-dialog-link-url-".concat(this.options.id, "\" class=\"note-link-url form-control note-form-control note-input\" type=\"text\" value=\"http://\"/>"), '</div>', !this.options.disableLinkTarget ? external_jQuery_default()('<div></div>').append(this.ui.checkbox({ className: 'sn-checkbox-open-in-new-window', text: this.lang.link.openInNewWindow, checked: true }).render()).html() : '', external_jQuery_default()('<div></div>').append(this.ui.checkbox({ className: 'sn-checkbox-use-protocol', text: this.lang.link.useProtocol, checked: true }).render()).html()].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-link-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.link.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ className: 'link-dialog', title: this.lang.link.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } /** * toggle update button */ }, { key: "toggleLinkBtn", value: function toggleLinkBtn($linkBtn, $linkText, $linkUrl) { this.ui.toggleBtn($linkBtn, $linkText.val() && $linkUrl.val()); } /** * Show link dialog and set event handlers on dialog controls. * * @param {Object} linkInfo * @return {Promise} */ }, { key: "showLinkDialog", value: function showLinkDialog(linkInfo) { var _this = this; return external_jQuery_default().Deferred(function (deferred) { var $linkText = _this.$dialog.find('.note-link-text'); var $linkUrl = _this.$dialog.find('.note-link-url'); var $linkBtn = _this.$dialog.find('.note-link-btn'); var $openInNewWindow = _this.$dialog.find('.sn-checkbox-open-in-new-window input[type=checkbox]'); var $useProtocol = _this.$dialog.find('.sn-checkbox-use-protocol input[type=checkbox]'); _this.ui.onDialogShown(_this.$dialog, function () { _this.context.triggerEvent('dialog.shown'); // If no url was given and given text is valid URL then copy that into URL Field if (!linkInfo.url && func.isValidUrl(linkInfo.text)) { linkInfo.url = linkInfo.text; } $linkText.on('input paste propertychange', function () { // If linktext was modified by input events, // cloning text from linkUrl will be stopped. linkInfo.text = $linkText.val(); _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); }).val(linkInfo.text); $linkUrl.on('input paste propertychange', function () { // Display same text on `Text to display` as default // when linktext has no text if (!linkInfo.text) { $linkText.val($linkUrl.val()); } _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); }).val(linkInfo.url); if (!env.isSupportTouch) { $linkUrl.trigger('focus'); } _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); _this.bindEnterKey($linkUrl, $linkBtn); _this.bindEnterKey($linkText, $linkBtn); var isNewWindowChecked = linkInfo.isNewWindow !== undefined ? linkInfo.isNewWindow : _this.context.options.linkTargetBlank; $openInNewWindow.prop('checked', isNewWindowChecked); var useProtocolChecked = linkInfo.url ? false : _this.context.options.useProtocol; $useProtocol.prop('checked', useProtocolChecked); $linkBtn.one('click', function (event) { event.preventDefault(); deferred.resolve({ range: linkInfo.range, url: $linkUrl.val(), text: $linkText.val(), isNewWindow: $openInNewWindow.is(':checked'), checkProtocol: $useProtocol.is(':checked') }); _this.ui.hideDialog(_this.$dialog); }); }); _this.ui.onDialogHidden(_this.$dialog, function () { // detach events $linkText.off(); $linkUrl.off(); $linkBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this.ui.showDialog(_this.$dialog); }).promise(); } /** * @param {Object} layoutInfo */ }, { key: "show", value: function show() { var _this2 = this; var linkInfo = this.context.invoke('editor.getLinkInfo'); this.context.invoke('editor.saveRange'); this.showLinkDialog(linkInfo).then(function (linkInfo) { _this2.context.invoke('editor.restoreRange'); _this2.context.invoke('editor.createLink', linkInfo); }).fail(function () { _this2.context.invoke('editor.restoreRange'); }); } }]); return LinkDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/LinkPopover.js function LinkPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function LinkPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function LinkPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) LinkPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) LinkPopover_defineProperties(Constructor, staticProps); return Constructor; } var LinkPopover = /*#__PURE__*/function () { function LinkPopover(context) { var _this = this; LinkPopover_classCallCheck(this, LinkPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.events = { 'summernote.keyup summernote.mouseup summernote.change summernote.scroll': function summernoteKeyupSummernoteMouseupSummernoteChangeSummernoteScroll() { _this.update(); }, 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } LinkPopover_createClass(LinkPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.link); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-link-popover', callback: function callback($node) { var $content = $node.find('.popover-content,.note-popover-content'); $content.prepend('<span><a target="_blank"></a>&nbsp;</span>'); } }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.link); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update() { // Prevent focusing on editable when invoke('code') is executed if (!this.context.invoke('editor.hasFocus')) { this.hide(); return; } var rng = this.context.invoke('editor.getLastRange'); if (rng.isCollapsed() && rng.isOnAnchor()) { var anchor = dom.ancestor(rng.sc, dom.isAnchor); var href = external_jQuery_default()(anchor).attr('href'); this.$popover.find('a').attr('href', href).text(href); var pos = dom.posFromPlaceholder(anchor); var containerOffset = external_jQuery_default()(this.options.container).offset(); pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return LinkPopover; }(); ;// CONCATENATED MODULE: ./src/js/module/ImageDialog.js function ImageDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function ImageDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function ImageDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) ImageDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) ImageDialog_defineProperties(Constructor, staticProps); return Constructor; } var ImageDialog = /*#__PURE__*/function () { function ImageDialog(context) { ImageDialog_classCallCheck(this, ImageDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } ImageDialog_createClass(ImageDialog, [{ key: "initialize", value: function initialize() { var imageLimitation = ''; if (this.options.maximumImageFileSize) { var unit = Math.floor(Math.log(this.options.maximumImageFileSize) / Math.log(1024)); var readableSize = (this.options.maximumImageFileSize / Math.pow(1024, unit)).toFixed(2) * 1 + ' ' + ' KMGTP'[unit] + 'B'; imageLimitation = "<small>".concat(this.lang.image.maximumFileSize + ' : ' + readableSize, "</small>"); } var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group note-group-select-from-files">', '<label for="note-dialog-image-file-' + this.options.id + '" class="note-form-label">' + this.lang.image.selectFromFiles + '</label>', '<input id="note-dialog-image-file-' + this.options.id + '" class="note-image-input form-control-file note-form-control note-input" ', ' type="file" name="files" accept="' + this.options.acceptImageFileTypes + '" multiple="multiple"/>', imageLimitation, '</div>', '<div class="form-group note-group-image-url">', '<label for="note-dialog-image-url-' + this.options.id + '" class="note-form-label">' + this.lang.image.url + '</label>', '<input id="note-dialog-image-url-' + this.options.id + '" class="note-image-url form-control note-form-control note-input" type="text"/>', '</div>'].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-image-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.image.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ title: this.lang.image.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } }, { key: "show", value: function show() { var _this = this; this.context.invoke('editor.saveRange'); this.showImageDialog().then(function (data) { // [workaround] hide dialog before restore range for IE range focus _this.ui.hideDialog(_this.$dialog); _this.context.invoke('editor.restoreRange'); if (typeof data === 'string') { // image url // If onImageLinkInsert set, if (_this.options.callbacks.onImageLinkInsert) { _this.context.triggerEvent('image.link.insert', data); } else { _this.context.invoke('editor.insertImage', data); } } else { // array of files _this.context.invoke('editor.insertImagesOrCallback', data); } }).fail(function () { _this.context.invoke('editor.restoreRange'); }); } /** * show image dialog * * @param {jQuery} $dialog * @return {Promise} */ }, { key: "showImageDialog", value: function showImageDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { var $imageInput = _this2.$dialog.find('.note-image-input'); var $imageUrl = _this2.$dialog.find('.note-image-url'); var $imageBtn = _this2.$dialog.find('.note-image-btn'); _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); // Cloning imageInput to clear element. $imageInput.replaceWith($imageInput.clone().on('change', function (event) { deferred.resolve(event.target.files || event.target.value); }).val('')); $imageUrl.on('input paste propertychange', function () { _this2.ui.toggleBtn($imageBtn, $imageUrl.val()); }).val(''); if (!env.isSupportTouch) { $imageUrl.trigger('focus'); } $imageBtn.click(function (event) { event.preventDefault(); deferred.resolve($imageUrl.val()); }); _this2.bindEnterKey($imageUrl, $imageBtn); }); _this2.ui.onDialogHidden(_this2.$dialog, function () { $imageInput.off(); $imageUrl.off(); $imageBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this2.ui.showDialog(_this2.$dialog); }); } }]); return ImageDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/ImagePopover.js function ImagePopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function ImagePopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function ImagePopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) ImagePopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) ImagePopover_defineProperties(Constructor, staticProps); return Constructor; } /** * Image popover module * mouse events that show/hide popover will be handled by Handle.js. * Handle.js will receive the events and invoke 'imagePopover.update'. */ var ImagePopover = /*#__PURE__*/function () { function ImagePopover(context) { var _this = this; ImagePopover_classCallCheck(this, ImagePopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.editable = context.layoutInfo.editable[0]; this.options = context.options; this.events = { 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } ImagePopover_createClass(ImagePopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.image); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-image-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.image); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(target, event) { if (dom.isImg(target)) { var position = external_jQuery_default()(target).offset(); var containerOffset = external_jQuery_default()(this.options.container).offset(); var pos = {}; if (this.options.popatmouse) { pos.left = event.pageX - 20; pos.top = event.pageY; } else { pos = position; } pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return ImagePopover; }(); ;// CONCATENATED MODULE: ./src/js/module/TablePopover.js function TablePopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function TablePopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function TablePopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) TablePopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) TablePopover_defineProperties(Constructor, staticProps); return Constructor; } var TablePopover = /*#__PURE__*/function () { function TablePopover(context) { var _this = this; TablePopover_classCallCheck(this, TablePopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.events = { 'summernote.mousedown': function summernoteMousedown(we, e) { _this.update(e.target); }, 'summernote.keyup summernote.scroll summernote.change': function summernoteKeyupSummernoteScrollSummernoteChange() { _this.update(); }, 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } TablePopover_createClass(TablePopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.table); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-table-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.table); // [workaround] Disable Firefox's default table editor if (env.isFF) { document.execCommand('enableInlineTableEditing', false, false); } this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(target) { if (this.context.isDisabled()) { return false; } var isCell = dom.isCell(target) || dom.isCell(target === null || target === void 0 ? void 0 : target.parentElement); if (isCell) { var pos = dom.posFromPlaceholder(target); var containerOffset = external_jQuery_default()(this.options.container).offset(); pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } return isCell; } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return TablePopover; }(); ;// CONCATENATED MODULE: ./src/js/module/VideoDialog.js function VideoDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function VideoDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function VideoDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) VideoDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) VideoDialog_defineProperties(Constructor, staticProps); return Constructor; } var VideoDialog = /*#__PURE__*/function () { function VideoDialog(context) { VideoDialog_classCallCheck(this, VideoDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } VideoDialog_createClass(VideoDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group row-fluid">', "<label for=\"note-dialog-video-url-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.video.url, " <small class=\"text-muted\">").concat(this.lang.video.providers, "</small></label>"), "<input id=\"note-dialog-video-url-".concat(this.options.id, "\" class=\"note-video-url form-control note-form-control note-input\" type=\"text\"/>"), '</div>'].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-video-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.video.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ title: this.lang.video.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } }, { key: "createVideoNode", value: function createVideoNode(url) { // video url patterns(youtube, instagram, vimeo, dailymotion, youku, peertube, mp4, ogg, webm) var ytRegExp = /\/\/(?:(?:www|m)\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))([\w|-]{11})(?:(?:[\?&]t=)(\S+))?$/; var ytRegExpForStart = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/; var ytMatch = url.match(ytRegExp); var gdRegExp = /(?:\.|\/\/)drive\.google\.com\/file\/d\/(.[a-zA-Z0-9_-]*)\/view/; var gdMatch = url.match(gdRegExp); var igRegExp = /(?:www\.|\/\/)instagram\.com\/p\/(.[a-zA-Z0-9_-]*)/; var igMatch = url.match(igRegExp); var vRegExp = /\/\/vine\.co\/v\/([a-zA-Z0-9]+)/; var vMatch = url.match(vRegExp); var vimRegExp = /\/\/(player\.)?vimeo\.com\/([a-z]*\/)*(\d+)[?]?.*/; var vimMatch = url.match(vimRegExp); var dmRegExp = /.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/; var dmMatch = url.match(dmRegExp); var youkuRegExp = /\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/; var youkuMatch = url.match(youkuRegExp); var peerTubeRegExp = /\/\/(.*)\/videos\/watch\/([^?]*)(?:\?(?:start=(\w*))?(?:&stop=(\w*))?(?:&loop=([10]))?(?:&autoplay=([10]))?(?:&muted=([10]))?)?/; var peerTubeMatch = url.match(peerTubeRegExp); var qqRegExp = /\/\/v\.qq\.com.*?vid=(.+)/; var qqMatch = url.match(qqRegExp); var qqRegExp2 = /\/\/v\.qq\.com\/x?\/?(page|cover).*?\/([^\/]+)\.html\??.*/; var qqMatch2 = url.match(qqRegExp2); var mp4RegExp = /^.+.(mp4|m4v)$/; var mp4Match = url.match(mp4RegExp); var oggRegExp = /^.+.(ogg|ogv)$/; var oggMatch = url.match(oggRegExp); var webmRegExp = /^.+.(webm)$/; var webmMatch = url.match(webmRegExp); var fbRegExp = /(?:www\.|\/\/)facebook\.com\/([^\/]+)\/videos\/([0-9]+)/; var fbMatch = url.match(fbRegExp); var $video; if (ytMatch && ytMatch[1].length === 11) { var youtubeId = ytMatch[1]; var start = 0; if (typeof ytMatch[2] !== 'undefined') { var ytMatchForStart = ytMatch[2].match(ytRegExpForStart); if (ytMatchForStart) { for (var n = [3600, 60, 1], i = 0, r = n.length; i < r; i++) { start += typeof ytMatchForStart[i + 1] !== 'undefined' ? n[i] * parseInt(ytMatchForStart[i + 1], 10) : 0; } } } $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', '//www.youtube.com/embed/' + youtubeId + (start > 0 ? '?start=' + start : '')).attr('width', '640').attr('height', '360'); } else if (gdMatch && gdMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://drive.google.com/file/d/' + gdMatch[1] + '/preview').attr('width', '640').attr('height', '480'); } else if (igMatch && igMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://instagram.com/p/' + igMatch[1] + '/embed/').attr('width', '612').attr('height', '710').attr('scrolling', 'no').attr('allowtransparency', 'true'); } else if (vMatch && vMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', vMatch[0] + '/embed/simple').attr('width', '600').attr('height', '600').attr('class', 'vine-embed'); } else if (vimMatch && vimMatch[3].length) { $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('src', '//player.vimeo.com/video/' + vimMatch[3]).attr('width', '640').attr('height', '360'); } else if (dmMatch && dmMatch[2].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', '//www.dailymotion.com/embed/video/' + dmMatch[2]).attr('width', '640').attr('height', '360'); } else if (youkuMatch && youkuMatch[1].length) { $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('height', '498').attr('width', '510').attr('src', '//player.youku.com/embed/' + youkuMatch[1]); } else if (peerTubeMatch && peerTubeMatch[0].length) { var begin = 0; if (peerTubeMatch[2] !== 'undefined') begin = peerTubeMatch[2]; var end = 0; if (peerTubeMatch[3] !== 'undefined') end = peerTubeMatch[3]; var loop = 0; if (peerTubeMatch[4] !== 'undefined') loop = peerTubeMatch[4]; var autoplay = 0; if (peerTubeMatch[5] !== 'undefined') autoplay = peerTubeMatch[5]; var muted = 0; if (peerTubeMatch[6] !== 'undefined') muted = peerTubeMatch[6]; $video = external_jQuery_default()('<iframe allowfullscreen sandbox="allow-same-origin allow-scripts allow-popups">').attr('frameborder', 0).attr('src', '//' + peerTubeMatch[1] + '/videos/embed/' + peerTubeMatch[2] + "?loop=" + loop + "&autoplay=" + autoplay + "&muted=" + muted + (begin > 0 ? '&start=' + begin : '') + (end > 0 ? '&end=' + start : '')).attr('width', '560').attr('height', '315'); } else if (qqMatch && qqMatch[1].length || qqMatch2 && qqMatch2[2].length) { var vid = qqMatch && qqMatch[1].length ? qqMatch[1] : qqMatch2[2]; $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('height', '310').attr('width', '500').attr('src', 'https://v.qq.com/txp/iframe/player.html?vid=' + vid + '&amp;auto=0'); } else if (mp4Match || oggMatch || webmMatch) { $video = external_jQuery_default()('<video controls>').attr('src', url).attr('width', '640').attr('height', '360'); } else if (fbMatch && fbMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://www.facebook.com/plugins/video.php?href=' + encodeURIComponent(fbMatch[0]) + '&show_text=0&width=560').attr('width', '560').attr('height', '301').attr('scrolling', 'no').attr('allowtransparency', 'true'); } else { // this is not a known video link. Now what, Cat? Now what? return false; } $video.addClass('note-video-clip'); return $video[0]; } }, { key: "show", value: function show() { var _this = this; var text = this.context.invoke('editor.getSelectedText'); this.context.invoke('editor.saveRange'); this.showVideoDialog(text).then(function (url) { // [workaround] hide dialog before restore range for IE range focus _this.ui.hideDialog(_this.$dialog); _this.context.invoke('editor.restoreRange'); // build node var $node = _this.createVideoNode(url); if ($node) { // insert video node _this.context.invoke('editor.insertNode', $node); } }).fail(function () { _this.context.invoke('editor.restoreRange'); }); } /** * show video dialog * * @param {jQuery} $dialog * @return {Promise} */ }, { key: "showVideoDialog", value: function showVideoDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { var $videoUrl = _this2.$dialog.find('.note-video-url'); var $videoBtn = _this2.$dialog.find('.note-video-btn'); _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); $videoUrl.on('input paste propertychange', function () { _this2.ui.toggleBtn($videoBtn, $videoUrl.val()); }); if (!env.isSupportTouch) { $videoUrl.trigger('focus'); } $videoBtn.click(function (event) { event.preventDefault(); deferred.resolve($videoUrl.val()); }); _this2.bindEnterKey($videoUrl, $videoBtn); }); _this2.ui.onDialogHidden(_this2.$dialog, function () { $videoUrl.off(); $videoBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this2.ui.showDialog(_this2.$dialog); }); } }]); return VideoDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/HelpDialog.js function HelpDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function HelpDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function HelpDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) HelpDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) HelpDialog_defineProperties(Constructor, staticProps); return Constructor; } var HelpDialog = /*#__PURE__*/function () { function HelpDialog(context) { HelpDialog_classCallCheck(this, HelpDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } HelpDialog_createClass(HelpDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<p class="text-center">', '<a href="http://summernote.org/" target="_blank" rel="noopener noreferrer">Summernote 0.8.20</a> · ', '<a href="https://github.com/summernote/summernote" target="_blank" rel="noopener noreferrer">Project</a> · ', '<a href="https://github.com/summernote/summernote/issues" target="_blank" rel="noopener noreferrer">Issues</a>', '</p>'].join(''); this.$dialog = this.ui.dialog({ title: this.lang.options.help, fade: this.options.dialogsFade, body: this.createShortcutList(), footer: body, callback: function callback($node) { $node.find('.modal-body,.note-modal-body').css({ 'max-height': 300, 'overflow': 'scroll' }); } }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "createShortcutList", value: function createShortcutList() { var _this = this; var keyMap = this.options.keyMap[env.isMac ? 'mac' : 'pc']; return Object.keys(keyMap).map(function (key) { var command = keyMap[key]; var $row = external_jQuery_default()('<div><div class="help-list-item"></div></div>'); $row.append(external_jQuery_default()('<label><kbd>' + key + '</kdb></label>').css({ 'width': 180, 'margin-right': 10 })).append(external_jQuery_default()('<span></span>').html(_this.context.memo('help.' + command) || command)); return $row.html(); }).join(''); } /** * show help dialog * * @return {Promise} */ }, { key: "showHelpDialog", value: function showHelpDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); deferred.resolve(); }); _this2.ui.showDialog(_this2.$dialog); }).promise(); } }, { key: "show", value: function show() { var _this3 = this; this.context.invoke('editor.saveRange'); this.showHelpDialog().then(function () { _this3.context.invoke('editor.restoreRange'); }); } }]); return HelpDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/AirPopover.js function AirPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AirPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AirPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) AirPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) AirPopover_defineProperties(Constructor, staticProps); return Constructor; } var AIRMODE_POPOVER_X_OFFSET = -5; var AIRMODE_POPOVER_Y_OFFSET = 5; var AirPopover = /*#__PURE__*/function () { function AirPopover(context) { var _this = this; AirPopover_classCallCheck(this, AirPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.hidable = true; this.onContextmenu = false; this.pageX = null; this.pageY = null; this.events = { 'summernote.contextmenu': function summernoteContextmenu(e) { if (_this.options.editing) { e.preventDefault(); e.stopPropagation(); _this.onContextmenu = true; _this.update(true); } }, 'summernote.mousedown': function summernoteMousedown(we, e) { _this.pageX = e.pageX; _this.pageY = e.pageY; }, 'summernote.keyup summernote.mouseup summernote.scroll': function summernoteKeyupSummernoteMouseupSummernoteScroll(we, e) { if (_this.options.editing && !_this.onContextmenu) { _this.pageX = e.pageX; _this.pageY = e.pageY; _this.update(); } _this.onContextmenu = false; }, 'summernote.disable summernote.change summernote.dialog.shown summernote.blur': function summernoteDisableSummernoteChangeSummernoteDialogShownSummernoteBlur() { _this.hide(); }, 'summernote.focusout': function summernoteFocusout() { if (!_this.$popover.is(':active,:focus')) { _this.hide(); } } }; } AirPopover_createClass(AirPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return this.options.airMode && !lists.isEmpty(this.options.popover.air); } }, { key: "initialize", value: function initialize() { var _this2 = this; this.$popover = this.ui.popover({ className: 'note-air-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.air); // disable hiding this popover preemptively by 'summernote.blur' event. this.$popover.on('mousedown', function () { _this2.hidable = false; }); // (re-)enable hiding after 'summernote.blur' has been handled (aka. ignored). this.$popover.on('mouseup', function () { _this2.hidable = true; }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(forcelyOpen) { var styleInfo = this.context.invoke('editor.currentStyle'); if (styleInfo.range && (!styleInfo.range.isCollapsed() || forcelyOpen)) { var rect = { left: this.pageX, top: this.pageY }; var containerOffset = external_jQuery_default()(this.options.container).offset(); rect.top -= containerOffset.top; rect.left -= containerOffset.left; this.$popover.css({ display: 'block', left: Math.max(rect.left, 0) + AIRMODE_POPOVER_X_OFFSET, top: rect.top + AIRMODE_POPOVER_Y_OFFSET }); this.context.invoke('buttons.updateCurrentStyle', this.$popover); } else { this.hide(); } } }, { key: "updateCodeview", value: function updateCodeview(isCodeview) { this.ui.toggleBtnActive(this.$popover.find('.btn-codeview'), isCodeview); if (isCodeview) { this.hide(); } } }, { key: "hide", value: function hide() { if (this.hidable) { this.$popover.hide(); } } }]); return AirPopover; }(); ;// CONCATENATED MODULE: ./src/js/module/HintPopover.js function HintPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function HintPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function HintPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) HintPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) HintPopover_defineProperties(Constructor, staticProps); return Constructor; } var POPOVER_DIST = 5; var HintPopover = /*#__PURE__*/function () { function HintPopover(context) { var _this = this; HintPopover_classCallCheck(this, HintPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$editable = context.layoutInfo.editable; this.options = context.options; this.hint = this.options.hint || []; this.direction = this.options.hintDirection || 'bottom'; this.hints = Array.isArray(this.hint) ? this.hint : [this.hint]; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); }, 'summernote.disable summernote.dialog.shown summernote.blur': function summernoteDisableSummernoteDialogShownSummernoteBlur() { _this.hide(); } }; } HintPopover_createClass(HintPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return this.hints.length > 0; } }, { key: "initialize", value: function initialize() { var _this2 = this; this.lastWordRange = null; this.matchingWord = null; this.$popover = this.ui.popover({ className: 'note-hint-popover', hideArrow: true, direction: '' }).render().appendTo(this.options.container); this.$popover.hide(); this.$content = this.$popover.find('.popover-content,.note-popover-content'); this.$content.on('click', '.note-hint-item', function (e) { _this2.$content.find('.active').removeClass('active'); external_jQuery_default()(e.currentTarget).addClass('active'); _this2.replace(); }); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "selectItem", value: function selectItem($item) { this.$content.find('.active').removeClass('active'); $item.addClass('active'); this.$content[0].scrollTop = $item[0].offsetTop - this.$content.innerHeight() / 2; } }, { key: "moveDown", value: function moveDown() { var $current = this.$content.find('.note-hint-item.active'); var $next = $current.next(); if ($next.length) { this.selectItem($next); } else { var $nextGroup = $current.parent().next(); if (!$nextGroup.length) { $nextGroup = this.$content.find('.note-hint-group').first(); } this.selectItem($nextGroup.find('.note-hint-item').first()); } } }, { key: "moveUp", value: function moveUp() { var $current = this.$content.find('.note-hint-item.active'); var $prev = $current.prev(); if ($prev.length) { this.selectItem($prev); } else { var $prevGroup = $current.parent().prev(); if (!$prevGroup.length) { $prevGroup = this.$content.find('.note-hint-group').last(); } this.selectItem($prevGroup.find('.note-hint-item').last()); } } }, { key: "replace", value: function replace() { var $item = this.$content.find('.note-hint-item.active'); if ($item.length) { var node = this.nodeFromItem($item); // If matchingWord length = 0 -> capture OK / open hint / but as mention capture "" (\w*) if (this.matchingWord !== null && this.matchingWord.length === 0) { this.lastWordRange.so = this.lastWordRange.eo; // Else si > 0 and normal case -> adjust range "before" for correct position of insertion } else if (this.matchingWord !== null && this.matchingWord.length > 0 && !this.lastWordRange.isCollapsed()) { var rangeCompute = this.lastWordRange.eo - this.lastWordRange.so - this.matchingWord.length; if (rangeCompute > 0) { this.lastWordRange.so += rangeCompute; } } this.lastWordRange.insertNode(node); if (this.options.hintSelect === 'next') { var blank = document.createTextNode(''); external_jQuery_default()(node).after(blank); range.createFromNodeBefore(blank).select(); } else { range.createFromNodeAfter(node).select(); } this.lastWordRange = null; this.hide(); this.context.invoke('editor.focus'); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } } }, { key: "nodeFromItem", value: function nodeFromItem($item) { var hint = this.hints[$item.data('index')]; var item = $item.data('item'); var node = hint.content ? hint.content(item) : item; if (typeof node === 'string') { node = dom.createText(node); } return node; } }, { key: "createItemTemplates", value: function createItemTemplates(hintIdx, items) { var hint = this.hints[hintIdx]; return items.map(function (item /*, idx */ ) { var $item = external_jQuery_default()('<div class="note-hint-item"></div>'); $item.append(hint.template ? hint.template(item) : item + ''); $item.data({ 'index': hintIdx, 'item': item }); return $item; }); } }, { key: "handleKeydown", value: function handleKeydown(e) { if (!this.$popover.is(':visible')) { return; } if (e.keyCode === key.code.ENTER) { e.preventDefault(); this.replace(); } else if (e.keyCode === key.code.UP) { e.preventDefault(); this.moveUp(); } else if (e.keyCode === key.code.DOWN) { e.preventDefault(); this.moveDown(); } } }, { key: "searchKeyword", value: function searchKeyword(index, keyword, callback) { var hint = this.hints[index]; if (hint && hint.match.test(keyword) && hint.search) { var matches = hint.match.exec(keyword); this.matchingWord = matches[0]; hint.search(matches[1], callback); } else { callback(); } } }, { key: "createGroup", value: function createGroup(idx, keyword) { var _this3 = this; var $group = external_jQuery_default()('<div class="note-hint-group note-hint-group-' + idx + '"></div>'); this.searchKeyword(idx, keyword, function (items) { items = items || []; if (items.length) { $group.html(_this3.createItemTemplates(idx, items)); _this3.show(); } }); return $group; } }, { key: "handleKeyup", value: function handleKeyup(e) { var _this4 = this; if (!lists.contains([key.code.ENTER, key.code.UP, key.code.DOWN], e.keyCode)) { var _range = this.context.invoke('editor.getLastRange'); var wordRange, keyword; if (this.options.hintMode === 'words') { wordRange = _range.getWordsRange(_range); keyword = wordRange.toString(); this.hints.forEach(function (hint) { if (hint.match.test(keyword)) { wordRange = _range.getWordsMatchRange(hint.match); return false; } }); if (!wordRange) { this.hide(); return; } keyword = wordRange.toString(); } else { wordRange = _range.getWordRange(); keyword = wordRange.toString(); } if (this.hints.length && keyword) { this.$content.empty(); var bnd = func.rect2bnd(lists.last(wordRange.getClientRects())); var containerOffset = external_jQuery_default()(this.options.container).offset(); if (bnd) { bnd.top -= containerOffset.top; bnd.left -= containerOffset.left; this.$popover.hide(); this.lastWordRange = wordRange; this.hints.forEach(function (hint, idx) { if (hint.match.test(keyword)) { _this4.createGroup(idx, keyword).appendTo(_this4.$content); } }); // select first .note-hint-item this.$content.find('.note-hint-item:first').addClass('active'); // set position for popover after group is created if (this.direction === 'top') { this.$popover.css({ left: bnd.left, top: bnd.top - this.$popover.outerHeight() - POPOVER_DIST }); } else { this.$popover.css({ left: bnd.left, top: bnd.top + bnd.height + POPOVER_DIST }); } } } else { this.hide(); } } } }, { key: "show", value: function show() { this.$popover.show(); } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return HintPopover; }(); ;// CONCATENATED MODULE: ./src/js/settings.js (external_jQuery_default()).summernote = external_jQuery_default().extend((external_jQuery_default()).summernote, { version: '0.8.20', plugins: {}, dom: dom, range: range, lists: lists, options: { langInfo: (external_jQuery_default()).summernote.lang["en-US"], editing: true, modules: { 'editor': Editor, 'clipboard': Clipboard, 'dropzone': Dropzone, 'codeview': CodeView, 'statusbar': Statusbar, 'fullscreen': Fullscreen, 'handle': Handle, // FIXME: HintPopover must be front of autolink // - Script error about range when Enter key is pressed on hint popover 'hintPopover': HintPopover, 'autoLink': AutoLink, 'autoSync': AutoSync, 'autoReplace': AutoReplace, 'placeholder': Placeholder, 'buttons': Buttons, 'toolbar': Toolbar, 'linkDialog': LinkDialog, 'linkPopover': LinkPopover, 'imageDialog': ImageDialog, 'imagePopover': ImagePopover, 'tablePopover': TablePopover, 'videoDialog': VideoDialog, 'helpDialog': HelpDialog, 'airPopover': AirPopover }, buttons: {}, lang: 'en-US', followingToolbar: false, toolbarPosition: 'top', otherStaticBar: '', // toolbar codeviewKeepButton: false, toolbar: [['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['fontname', ['fontname']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture', 'video']], ['view', ['fullscreen', 'codeview', 'help']]], // popover popatmouse: true, popover: { image: [['resize', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']], ['float', ['floatLeft', 'floatRight', 'floatNone']], ['remove', ['removeMedia']]], link: [['link', ['linkDialogShow', 'unlink']]], table: [['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']], ['delete', ['deleteRow', 'deleteCol', 'deleteTable']]], air: [['color', ['color']], ['font', ['bold', 'underline', 'clear']], ['para', ['ul', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture']], ['view', ['fullscreen', 'codeview']]] }, // air mode: inline editor airMode: false, overrideContextMenu: false, // TBD width: null, height: null, linkTargetBlank: true, useProtocol: true, defaultProtocol: 'http://', focus: false, tabDisabled: false, tabSize: 4, styleWithCSS: false, shortcuts: true, textareaAutoSync: true, tooltip: 'auto', container: null, maxTextLength: 0, blockquoteBreakingLevel: 2, spellCheck: true, disableGrammar: false, placeholder: null, inheritPlaceholder: false, // TODO: need to be documented recordEveryKeystroke: false, historyLimit: 200, // TODO: need to be documented showDomainOnlyForAutolink: false, // TODO: need to be documented hintMode: 'word', hintSelect: 'after', hintDirection: 'bottom', styleTags: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'], fontNames: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande', 'Tahoma', 'Times New Roman', 'Verdana'], fontNamesIgnoreCheck: [], addDefaultFonts: true, fontSizes: ['8', '9', '10', '11', '12', '14', '18', '24', '36'], fontSizeUnits: ['px', 'pt'], // pallete colors(n x n) colors: [['#000000', '#424242', '#636363', '#9C9C94', '#CEC6CE', '#EFEFEF', '#F7F7F7', '#FFFFFF'], ['#FF0000', '#FF9C00', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#9C00FF', '#FF00FF'], ['#F7C6CE', '#FFE7CE', '#FFEFC6', '#D6EFD6', '#CEDEE7', '#CEE7F7', '#D6D6E7', '#E7D6DE'], ['#E79C9C', '#FFC69C', '#FFE79C', '#B5D6A5', '#A5C6CE', '#9CC6EF', '#B5A5D6', '#D6A5BD'], ['#E76363', '#F7AD6B', '#FFD663', '#94BD7B', '#73A5AD', '#6BADDE', '#8C7BC6', '#C67BA5'], ['#CE0000', '#E79439', '#EFC631', '#6BA54A', '#4A7B8C', '#3984C6', '#634AA5', '#A54A7B'], ['#9C0000', '#B56308', '#BD9400', '#397B21', '#104A5A', '#085294', '#311873', '#731842'], ['#630000', '#7B3900', '#846300', '#295218', '#083139', '#003163', '#21104A', '#4A1031']], // http://chir.ag/projects/name-that-color/ colorsName: [['Black', 'Tundora', 'Dove Gray', 'Star Dust', 'Pale Slate', 'Gallery', 'Alabaster', 'White'], ['Red', 'Orange Peel', 'Yellow', 'Green', 'Cyan', 'Blue', 'Electric Violet', 'Magenta'], ['Azalea', 'Karry', 'Egg White', 'Zanah', 'Botticelli', 'Tropical Blue', 'Mischka', 'Twilight'], ['Tonys Pink', 'Peach Orange', 'Cream Brulee', 'Sprout', 'Casper', 'Perano', 'Cold Purple', 'Careys Pink'], ['Mandy', 'Rajah', 'Dandelion', 'Olivine', 'Gulf Stream', 'Viking', 'Blue Marguerite', 'Puce'], ['Guardsman Red', 'Fire Bush', 'Golden Dream', 'Chelsea Cucumber', 'Smalt Blue', 'Boston Blue', 'Butterfly Bush', 'Cadillac'], ['Sangria', 'Mai Tai', 'Buddha Gold', 'Forest Green', 'Eden', 'Venice Blue', 'Meteorite', 'Claret'], ['Rosewood', 'Cinnamon', 'Olive', 'Parsley', 'Tiber', 'Midnight Blue', 'Valentino', 'Loulou']], colorButton: { foreColor: '#000000', backColor: '#FFFF00' }, lineHeights: ['1.0', '1.2', '1.4', '1.5', '1.6', '1.8', '2.0', '3.0'], tableClassName: 'table table-bordered', insertTableMaxSize: { col: 10, row: 10 }, // By default, dialogs are attached in container. dialogsInBody: false, dialogsFade: false, maximumImageFileSize: null, acceptImageFileTypes: "image/*", callbacks: { onBeforeCommand: null, onBlur: null, onBlurCodeview: null, onChange: null, onChangeCodeview: null, onDialogShown: null, onEnter: null, onFocus: null, onImageLinkInsert: null, onImageUpload: null, onImageUploadError: null, onInit: null, onKeydown: null, onKeyup: null, onMousedown: null, onMouseup: null, onPaste: null, onScroll: null }, codemirror: { mode: 'text/html', htmlMode: true, lineNumbers: true }, codeviewFilter: true, codeviewFilterRegex: /<\/*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|ilayer|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|t(?:itle|extarea)|xml)[^>]*?>/gi, codeviewIframeFilter: true, codeviewIframeWhitelistSrc: [], codeviewIframeWhitelistSrcBase: ['www.youtube.com', 'www.youtube-nocookie.com', 'www.facebook.com', 'vine.co', 'instagram.com', 'player.vimeo.com', 'www.dailymotion.com', 'player.youku.com', 'jumpingbean.tv', 'v.qq.com'], keyMap: { pc: { 'ESC': 'escape', 'ENTER': 'insertParagraph', 'CTRL+Z': 'undo', 'CTRL+Y': 'redo', 'TAB': 'tab', 'SHIFT+TAB': 'untab', 'CTRL+B': 'bold', 'CTRL+I': 'italic', 'CTRL+U': 'underline', 'CTRL+SHIFT+S': 'strikethrough', 'CTRL+BACKSLASH': 'removeFormat', 'CTRL+SHIFT+L': 'justifyLeft', 'CTRL+SHIFT+E': 'justifyCenter', 'CTRL+SHIFT+R': 'justifyRight', 'CTRL+SHIFT+J': 'justifyFull', 'CTRL+SHIFT+NUM7': 'insertUnorderedList', 'CTRL+SHIFT+NUM8': 'insertOrderedList', 'CTRL+LEFTBRACKET': 'outdent', 'CTRL+RIGHTBRACKET': 'indent', 'CTRL+NUM0': 'formatPara', 'CTRL+NUM1': 'formatH1', 'CTRL+NUM2': 'formatH2', 'CTRL+NUM3': 'formatH3', 'CTRL+NUM4': 'formatH4', 'CTRL+NUM5': 'formatH5', 'CTRL+NUM6': 'formatH6', 'CTRL+ENTER': 'insertHorizontalRule', 'CTRL+K': 'linkDialog.show' }, mac: { 'ESC': 'escape', 'ENTER': 'insertParagraph', 'CMD+Z': 'undo', 'CMD+SHIFT+Z': 'redo', 'TAB': 'tab', 'SHIFT+TAB': 'untab', 'CMD+B': 'bold', 'CMD+I': 'italic', 'CMD+U': 'underline', 'CMD+SHIFT+S': 'strikethrough', 'CMD+BACKSLASH': 'removeFormat', 'CMD+SHIFT+L': 'justifyLeft', 'CMD+SHIFT+E': 'justifyCenter', 'CMD+SHIFT+R': 'justifyRight', 'CMD+SHIFT+J': 'justifyFull', 'CMD+SHIFT+NUM7': 'insertUnorderedList', 'CMD+SHIFT+NUM8': 'insertOrderedList', 'CMD+LEFTBRACKET': 'outdent', 'CMD+RIGHTBRACKET': 'indent', 'CMD+NUM0': 'formatPara', 'CMD+NUM1': 'formatH1', 'CMD+NUM2': 'formatH2', 'CMD+NUM3': 'formatH3', 'CMD+NUM4': 'formatH4', 'CMD+NUM5': 'formatH5', 'CMD+NUM6': 'formatH6', 'CMD+ENTER': 'insertHorizontalRule', 'CMD+K': 'linkDialog.show' } }, icons: { 'align': 'note-icon-align', 'alignCenter': 'note-icon-align-center', 'alignJustify': 'note-icon-align-justify', 'alignLeft': 'note-icon-align-left', 'alignRight': 'note-icon-align-right', 'rowBelow': 'note-icon-row-below', 'colBefore': 'note-icon-col-before', 'colAfter': 'note-icon-col-after', 'rowAbove': 'note-icon-row-above', 'rowRemove': 'note-icon-row-remove', 'colRemove': 'note-icon-col-remove', 'indent': 'note-icon-align-indent', 'outdent': 'note-icon-align-outdent', 'arrowsAlt': 'note-icon-arrows-alt', 'bold': 'note-icon-bold', 'caret': 'note-icon-caret', 'circle': 'note-icon-circle', 'close': 'note-icon-close', 'code': 'note-icon-code', 'eraser': 'note-icon-eraser', 'floatLeft': 'note-icon-float-left', 'floatRight': 'note-icon-float-right', 'font': 'note-icon-font', 'frame': 'note-icon-frame', 'italic': 'note-icon-italic', 'link': 'note-icon-link', 'unlink': 'note-icon-chain-broken', 'magic': 'note-icon-magic', 'menuCheck': 'note-icon-menu-check', 'minus': 'note-icon-minus', 'orderedlist': 'note-icon-orderedlist', 'pencil': 'note-icon-pencil', 'picture': 'note-icon-picture', 'question': 'note-icon-question', 'redo': 'note-icon-redo', 'rollback': 'note-icon-rollback', 'square': 'note-icon-square', 'strikethrough': 'note-icon-strikethrough', 'subscript': 'note-icon-subscript', 'superscript': 'note-icon-superscript', 'table': 'note-icon-table', 'textHeight': 'note-icon-text-height', 'trash': 'note-icon-trash', 'underline': 'note-icon-underline', 'undo': 'note-icon-undo', 'unorderedlist': 'note-icon-unorderedlist', 'video': 'note-icon-video' } } }); ;// CONCATENATED MODULE: ./src/js/renderer.js function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function renderer_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function renderer_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function renderer_createClass(Constructor, protoProps, staticProps) { if (protoProps) renderer_defineProperties(Constructor.prototype, protoProps); if (staticProps) renderer_defineProperties(Constructor, staticProps); return Constructor; } var Renderer = /*#__PURE__*/function () { function Renderer(markup, children, options, callback) { renderer_classCallCheck(this, Renderer); this.markup = markup; this.children = children; this.options = options; this.callback = callback; } renderer_createClass(Renderer, [{ key: "render", value: function render($parent) { var $node = external_jQuery_default()(this.markup); if (this.options && this.options.contents) { $node.html(this.options.contents); } if (this.options && this.options.className) { $node.addClass(this.options.className); } if (this.options && this.options.data) { external_jQuery_default().each(this.options.data, function (k, v) { $node.attr('data-' + k, v); }); } if (this.options && this.options.click) { $node.on('click', this.options.click); } if (this.children) { var $container = $node.find('.note-children-container'); this.children.forEach(function (child) { child.render($container.length ? $container : $node); }); } if (this.callback) { this.callback($node, this.options); } if (this.options && this.options.callback) { this.options.callback($node); } if ($parent) { $parent.append($node); } return $node; } }]); return Renderer; }(); /* harmony default export */ const renderer = ({ create: function create(markup, callback) { return function () { var options = _typeof(arguments[1]) === 'object' ? arguments[1] : arguments[0]; var children = Array.isArray(arguments[0]) ? arguments[0] : []; if (options && options.children) { children = options.children; } return new Renderer(markup, children, options, callback); }; } }); ;// CONCATENATED MODULE: ./src/styles/lite/js/TooltipUI.js function TooltipUI_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function TooltipUI_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function TooltipUI_createClass(Constructor, protoProps, staticProps) { if (protoProps) TooltipUI_defineProperties(Constructor.prototype, protoProps); if (staticProps) TooltipUI_defineProperties(Constructor, staticProps); return Constructor; } var TooltipUI = /*#__PURE__*/function () { function TooltipUI($node, options) { TooltipUI_classCallCheck(this, TooltipUI); this.$node = $node; this.options = external_jQuery_default().extend({}, { title: '', target: options.container, trigger: 'hover focus', placement: 'bottom' }, options); // create tooltip node this.$tooltip = external_jQuery_default()(['<div class="note-tooltip">', '<div class="note-tooltip-arrow"></div>', '<div class="note-tooltip-content"></div>', '</div>'].join('')); // define event if (this.options.trigger !== 'manual') { var showCallback = this.show.bind(this); var hideCallback = this.hide.bind(this); var toggleCallback = this.toggle.bind(this); this.options.trigger.split(' ').forEach(function (eventName) { if (eventName === 'hover') { $node.off('mouseenter mouseleave'); $node.on('mouseenter', showCallback).on('mouseleave', hideCallback); } else if (eventName === 'click') { $node.on('click', toggleCallback); } else if (eventName === 'focus') { $node.on('focus', showCallback).on('blur', hideCallback); } }); } } TooltipUI_createClass(TooltipUI, [{ key: "show", value: function show() { var $node = this.$node; var offset = $node.offset(); var targetOffset = external_jQuery_default()(this.options.target).offset(); offset.top -= targetOffset.top; offset.left -= targetOffset.left; var $tooltip = this.$tooltip; var title = this.options.title || $node.attr('title') || $node.data('title'); var placement = this.options.placement || $node.data('placement'); $tooltip.addClass(placement); $tooltip.find('.note-tooltip-content').text(title); $tooltip.appendTo(this.options.target); var nodeWidth = $node.outerWidth(); var nodeHeight = $node.outerHeight(); var tooltipWidth = $tooltip.outerWidth(); var tooltipHeight = $tooltip.outerHeight(); if (placement === 'bottom') { $tooltip.css({ top: offset.top + nodeHeight, left: offset.left + (nodeWidth / 2 - tooltipWidth / 2) }); } else if (placement === 'top') { $tooltip.css({ top: offset.top - tooltipHeight, left: offset.left + (nodeWidth / 2 - tooltipWidth / 2) }); } else if (placement === 'left') { $tooltip.css({ top: offset.top + (nodeHeight / 2 - tooltipHeight / 2), left: offset.left - tooltipWidth }); } else if (placement === 'right') { $tooltip.css({ top: offset.top + (nodeHeight / 2 - tooltipHeight / 2), left: offset.left + nodeWidth }); } $tooltip.addClass('in'); } }, { key: "hide", value: function hide() { var _this = this; this.$tooltip.removeClass('in'); setTimeout(function () { _this.$tooltip.remove(); }, 200); } }, { key: "toggle", value: function toggle() { if (this.$tooltip.hasClass('in')) { this.hide(); } else { this.show(); } } }]); return TooltipUI; }(); /* harmony default export */ const js_TooltipUI = (TooltipUI); ;// CONCATENATED MODULE: ./src/styles/lite/js/DropdownUI.js function DropdownUI_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function DropdownUI_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function DropdownUI_createClass(Constructor, protoProps, staticProps) { if (protoProps) DropdownUI_defineProperties(Constructor.prototype, protoProps); if (staticProps) DropdownUI_defineProperties(Constructor, staticProps); return Constructor; } var DropdownUI = /*#__PURE__*/function () { function DropdownUI($node, options) { DropdownUI_classCallCheck(this, DropdownUI); this.$button = $node; this.options = external_jQuery_default().extend({}, { target: options.container }, options); this.setEvent(); } DropdownUI_createClass(DropdownUI, [{ key: "setEvent", value: function setEvent() { var _this = this; this.$button.on('click', function (e) { _this.toggle(); e.stopImmediatePropagation(); }); } }, { key: "clear", value: function clear() { var $parent = external_jQuery_default()('.note-btn-group.open'); $parent.find('.note-btn.active').removeClass('active'); $parent.removeClass('open'); } }, { key: "show", value: function show() { this.$button.addClass('active'); this.$button.parent().addClass('open'); var $dropdown = this.$button.next(); var offset = $dropdown.offset(); var width = $dropdown.outerWidth(); var windowWidth = external_jQuery_default()(window).width(); var targetMarginRight = parseFloat(external_jQuery_default()(this.options.target).css('margin-right')); if (offset.left + width > windowWidth - targetMarginRight) { $dropdown.css('margin-left', windowWidth - targetMarginRight - (offset.left + width)); } else { $dropdown.css('margin-left', ''); } } }, { key: "hide", value: function hide() { this.$button.removeClass('active'); this.$button.parent().removeClass('open'); } }, { key: "toggle", value: function toggle() { var isOpened = this.$button.parent().hasClass('open'); this.clear(); if (isOpened) { this.hide(); } else { this.show(); } } }]); return DropdownUI; }(); external_jQuery_default()(document).on('click', function (e) { if (!external_jQuery_default()(e.target).closest('.note-btn-group').length) { external_jQuery_default()('.note-btn-group.open').removeClass('open'); external_jQuery_default()('.note-btn-group .note-btn.active').removeClass('active'); } }); external_jQuery_default()(document).on('click.note-dropdown-menu', function (e) { external_jQuery_default()(e.target).closest('.note-dropdown-menu').parent().removeClass('open'); external_jQuery_default()(e.target).closest('.note-dropdown-menu').parent().find('.note-btn.active').removeClass('active'); }); /* harmony default export */ const js_DropdownUI = (DropdownUI); ;// CONCATENATED MODULE: ./src/styles/lite/js/ModalUI.js function ModalUI_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function ModalUI_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function ModalUI_createClass(Constructor, protoProps, staticProps) { if (protoProps) ModalUI_defineProperties(Constructor.prototype, protoProps); if (staticProps) ModalUI_defineProperties(Constructor, staticProps); return Constructor; } var ModalUI = /*#__PURE__*/function () { function ModalUI($node /*, options */ ) { ModalUI_classCallCheck(this, ModalUI); this.$modal = $node; this.$backdrop = external_jQuery_default()('<div class="note-modal-backdrop"></div>'); } ModalUI_createClass(ModalUI, [{ key: "show", value: function show() { var _this = this; this.$backdrop.appendTo(document.body).show(); this.$modal.addClass('open').show(); this.$modal.trigger('note.modal.show'); this.$modal.off('click', '.close').on('click', '.close', this.hide.bind(this)); this.$modal.on('keydown', function (event) { if (event.which === 27) { event.preventDefault(); _this.hide(); } }); } }, { key: "hide", value: function hide() { this.$modal.removeClass('open').hide(); this.$backdrop.hide(); this.$modal.trigger('note.modal.hide'); this.$modal.off('keydown'); } }]); return ModalUI; }(); /* harmony default export */ const js_ModalUI = (ModalUI); ;// CONCATENATED MODULE: ./src/styles/lite/summernote-lite.js var editor = renderer.create('<div class="note-editor note-frame"></div>'); var toolbar = renderer.create('<div class="note-toolbar" role="toolbar"></div>'); var editingArea = renderer.create('<div class="note-editing-area"></div>'); var codable = renderer.create('<textarea class="note-codable" aria-multiline="true"></textarea>'); var editable = renderer.create('<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>'); var statusbar = renderer.create(['<output class="note-status-output" role="status" aria-live="polite"></output>', '<div class="note-statusbar" role="status">', '<div class="note-resizebar" aria-label="resize">', '<div class="note-icon-bar"></div>', '<div class="note-icon-bar"></div>', '<div class="note-icon-bar"></div>', '</div>', '</div>'].join('')); var airEditor = renderer.create('<div class="note-editor note-airframe"></div>'); var airEditable = renderer.create(['<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>', '<output class="note-status-output" role="status" aria-live="polite"></output>'].join('')); var buttonGroup = renderer.create('<div class="note-btn-group"></div>'); var summernote_lite_button = renderer.create('<button type="button" class="note-btn" tabindex="-1"></button>', function ($node, options) { // set button type if (options && options.tooltip) { $node.attr({ 'aria-label': options.tooltip }); $node.data('_lite_tooltip', new js_TooltipUI($node, { title: options.tooltip, container: options.container })).on('click', function (e) { external_jQuery_default()(e.currentTarget).data('_lite_tooltip').hide(); }); } if (options.contents) { $node.html(options.contents); } if (options && options.data && options.data.toggle === 'dropdown') { $node.data('_lite_dropdown', new js_DropdownUI($node, { container: options.container })); } if (options && options.codeviewKeepButton) { $node.addClass('note-codeview-keep'); } }); var dropdown = renderer.create('<div class="note-dropdown-menu" role="list"></div>', function ($node, options) { var markup = Array.isArray(options.items) ? options.items.map(function (item) { var value = typeof item === 'string' ? item : item.value || ''; var content = options.template ? options.template(item) : item; var $temp = external_jQuery_default()('<a class="note-dropdown-item" href="#" data-value="' + value + '" role="listitem" aria-label="' + value + '"></a>'); $temp.html(content).data('item', item); return $temp; }) : options.items; $node.html(markup).attr({ 'aria-label': options.title }); $node.on('click', '> .note-dropdown-item', function (e) { var $a = external_jQuery_default()(this); var item = $a.data('item'); var value = $a.data('value'); if (item.click) { item.click($a); } else if (options.itemClick) { options.itemClick(e, item, value); } }); if (options && options.codeviewKeepButton) { $node.addClass('note-codeview-keep'); } }); var dropdownCheck = renderer.create('<div class="note-dropdown-menu note-check" role="list"></div>', function ($node, options) { var markup = Array.isArray(options.items) ? options.items.map(function (item) { var value = typeof item === 'string' ? item : item.value || ''; var content = options.template ? options.template(item) : item; var $temp = external_jQuery_default()('<a class="note-dropdown-item" href="#" data-value="' + value + '" role="listitem" aria-label="' + item + '"></a>'); $temp.html([icon(options.checkClassName), ' ', content]).data('item', item); return $temp; }) : options.items; $node.html(markup).attr({ 'aria-label': options.title }); $node.on('click', '> .note-dropdown-item', function (e) { var $a = external_jQuery_default()(this); var item = $a.data('item'); var value = $a.data('value'); if (item.click) { item.click($a); } else if (options.itemClick) { options.itemClick(e, item, value); } }); if (options && options.codeviewKeepButton) { $node.addClass('note-codeview-keep'); } }); var dropdownButtonContents = function dropdownButtonContents(contents, options) { return contents + ' ' + icon(options.icons.caret, 'span'); }; var dropdownButton = function dropdownButton(opt, callback) { return buttonGroup([summernote_lite_button({ className: 'dropdown-toggle', contents: opt.title + ' ' + icon('note-icon-caret'), tooltip: opt.tooltip, data: { toggle: 'dropdown' } }), dropdown({ className: opt.className, items: opt.items, template: opt.template, itemClick: opt.itemClick })], { callback: callback }).render(); }; var dropdownCheckButton = function dropdownCheckButton(opt, callback) { return buttonGroup([summernote_lite_button({ className: 'dropdown-toggle', contents: opt.title + ' ' + icon('note-icon-caret'), tooltip: opt.tooltip, data: { toggle: 'dropdown' } }), dropdownCheck({ className: opt.className, checkClassName: opt.checkClassName, items: opt.items, template: opt.template, itemClick: opt.itemClick })], { callback: callback }).render(); }; var paragraphDropdownButton = function paragraphDropdownButton(opt) { return buttonGroup([summernote_lite_button({ className: 'dropdown-toggle', contents: opt.title + ' ' + icon('note-icon-caret'), tooltip: opt.tooltip, data: { toggle: 'dropdown' } }), dropdown([buttonGroup({ className: 'note-align', children: opt.items[0] }), buttonGroup({ className: 'note-list', children: opt.items[1] })])]).render(); }; var tableMoveHandler = function tableMoveHandler(event, col, row) { var PX_PER_EM = 18; var $picker = external_jQuery_default()(event.target.parentNode); // target is mousecatcher var $dimensionDisplay = $picker.next(); var $catcher = $picker.find('.note-dimension-picker-mousecatcher'); var $highlighted = $picker.find('.note-dimension-picker-highlighted'); var $unhighlighted = $picker.find('.note-dimension-picker-unhighlighted'); var posOffset; // HTML5 with jQuery - e.offsetX is undefined in Firefox if (event.offsetX === undefined) { var posCatcher = external_jQuery_default()(event.target).offset(); posOffset = { x: event.pageX - posCatcher.left, y: event.pageY - posCatcher.top }; } else { posOffset = { x: event.offsetX, y: event.offsetY }; } var dim = { c: Math.ceil(posOffset.x / PX_PER_EM) || 1, r: Math.ceil(posOffset.y / PX_PER_EM) || 1 }; $highlighted.css({ width: dim.c + 'em', height: dim.r + 'em' }); $catcher.data('value', dim.c + 'x' + dim.r); if (dim.c > 3 && dim.c < col) { $unhighlighted.css({ width: dim.c + 1 + 'em' }); } if (dim.r > 3 && dim.r < row) { $unhighlighted.css({ height: dim.r + 1 + 'em' }); } $dimensionDisplay.html(dim.c + ' x ' + dim.r); }; var tableDropdownButton = function tableDropdownButton(opt) { return buttonGroup([summernote_lite_button({ className: 'dropdown-toggle', contents: opt.title + ' ' + icon('note-icon-caret'), tooltip: opt.tooltip, data: { toggle: 'dropdown' } }), dropdown({ className: 'note-table', items: ['<div class="note-dimension-picker">', '<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>', '<div class="note-dimension-picker-highlighted"></div>', '<div class="note-dimension-picker-unhighlighted"></div>', '</div>', '<div class="note-dimension-display">1 x 1</div>'].join('') })], { callback: function callback($node) { var $catcher = $node.find('.note-dimension-picker-mousecatcher'); $catcher.css({ width: opt.col + 'em', height: opt.row + 'em' }).mouseup(opt.itemClick).mousemove(function (e) { tableMoveHandler(e, opt.col, opt.row); }); } }).render(); }; var palette = renderer.create('<div class="note-color-palette"></div>', function ($node, options) { var contents = []; for (var row = 0, rowSize = options.colors.length; row < rowSize; row++) { var eventName = options.eventName; var colors = options.colors[row]; var colorsName = options.colorsName[row]; var buttons = []; for (var col = 0, colSize = colors.length; col < colSize; col++) { var color = colors[col]; var colorName = colorsName[col]; buttons.push(['<button type="button" class="note-btn note-color-btn"', 'style="background-color:', color, '" ', 'data-event="', eventName, '" ', 'data-value="', color, '" ', 'data-title="', colorName, '" ', 'aria-label="', colorName, '" ', 'data-toggle="button" tabindex="-1"></button>'].join('')); } contents.push('<div class="note-color-row">' + buttons.join('') + '</div>'); } $node.html(contents.join('')); $node.find('.note-color-btn').each(function () { external_jQuery_default()(this).data('_lite_tooltip', new js_TooltipUI(external_jQuery_default()(this), { container: options.container })); }); }); var colorDropdownButton = function colorDropdownButton(opt, type) { return buttonGroup({ className: 'note-color', children: [summernote_lite_button({ className: 'note-current-color-button', contents: opt.title, tooltip: opt.lang.color.recent, click: opt.currentClick, callback: function callback($button) { var $recentColor = $button.find('.note-recent-color'); if (type !== 'foreColor') { $recentColor.css('background-color', '#FFFF00'); $button.attr('data-backColor', '#FFFF00'); } } }), summernote_lite_button({ className: 'dropdown-toggle', contents: icon('note-icon-caret'), tooltip: opt.lang.color.more, data: { toggle: 'dropdown' } }), dropdown({ items: ['<div>', '<div class="note-btn-group btn-background-color">', '<div class="note-palette-title">' + opt.lang.color.background + '</div>', '<div>', '<button type="button" class="note-color-reset note-btn note-btn-block" data-event="backColor" data-value="transparent">', opt.lang.color.transparent, '</button>', '</div>', '<div class="note-holder" data-event="backColor"></div>', '<div class="btn-sm">', '<input type="color" id="html5bcp" class="note-btn btn-default" value="#21104A" style="width:100%;" data-value="cp">', '<button type="button" class="note-color-reset btn" data-event="backColor" data-value="cpbackColor">', opt.lang.color.cpSelect, '</button>', '</div>', '</div>', '<div class="note-btn-group btn-foreground-color">', '<div class="note-palette-title">' + opt.lang.color.foreground + '</div>', '<div>', '<button type="button" class="note-color-reset note-btn note-btn-block" data-event="removeFormat" data-value="foreColor">', opt.lang.color.resetToDefault, '</button>', '</div>', '<div class="note-holder" data-event="foreColor"></div>', '<div class="btn-sm">', '<input type="color" id="html5fcp" class="note-btn btn-default" value="#21104A" style="width:100%;" data-value="cp">', '<button type="button" class="note-color-reset btn" data-event="foreColor" data-value="cpforeColor">', opt.lang.color.cpSelect, '</button>', '</div>', '</div>', '</div>'].join(''), callback: function callback($dropdown) { $dropdown.find('.note-holder').each(function () { var $holder = external_jQuery_default()(this); $holder.append(palette({ colors: opt.colors, eventName: $holder.data('event') }).render()); }); if (type === 'fore') { $dropdown.find('.btn-background-color').hide(); $dropdown.css({ 'min-width': '210px' }); } else if (type === 'back') { $dropdown.find('.btn-foreground-color').hide(); $dropdown.css({ 'min-width': '210px' }); } }, click: function click(event) { var $button = external_jQuery_default()(event.target); var eventName = $button.data('event'); var value = $button.data('value'); var foreinput = document.getElementById('html5fcp').value; var backinput = document.getElementById('html5bcp').value; if (value === 'cp') { event.stopPropagation(); } else if (value === 'cpbackColor') { value = backinput; } else if (value === 'cpforeColor') { value = foreinput; } if (eventName && value) { var key = eventName === 'backColor' ? 'background-color' : 'color'; var $color = $button.closest('.note-color').find('.note-recent-color'); var $currentButton = $button.closest('.note-color').find('.note-current-color-button'); $color.css(key, value); $currentButton.attr('data-' + eventName, value); if (type === 'fore') { opt.itemClick('foreColor', value); } else if (type === 'back') { opt.itemClick('backColor', value); } else { opt.itemClick(eventName, value); } } } })] }).render(); }; var dialog = renderer.create('<div class="note-modal" aria-hidden="false" tabindex="-1" role="dialog"></div>', function ($node, options) { if (options.fade) { $node.addClass('fade'); } $node.attr({ 'aria-label': options.title }); $node.html(['<div class="note-modal-content">', options.title ? '<div class="note-modal-header"><button type="button" class="close" aria-label="Close" aria-hidden="true"><i class="note-icon-close"></i></button><h4 class="note-modal-title">' + options.title + '</h4></div>' : '', '<div class="note-modal-body">' + options.body + '</div>', options.footer ? '<div class="note-modal-footer">' + options.footer + '</div>' : '', '</div>'].join('')); $node.data('modal', new js_ModalUI($node, options)); }); var videoDialog = function videoDialog(opt) { var body = '<div class="note-form-group">' + '<label for="note-dialog-video-url-' + opt.id + '" class="note-form-label">' + opt.lang.video.url + ' <small class="text-muted">' + opt.lang.video.providers + '</small></label>' + '<input id="note-dialog-video-url-' + opt.id + '" class="note-video-url note-input" type="text"/>' + '</div>'; var footer = ['<button type="button" href="#" class="note-btn note-btn-primary note-video-btn disabled" disabled>', opt.lang.video.insert, '</button>'].join(''); return dialog({ title: opt.lang.video.insert, fade: opt.fade, body: body, footer: footer }).render(); }; var imageDialog = function imageDialog(opt) { var body = '<div class="note-form-group note-group-select-from-files">' + '<label for="note-dialog-image-file-' + opt.id + '" class="note-form-label">' + opt.lang.image.selectFromFiles + '</label>' + '<input id="note-dialog-image-file-' + opt.id + '" class="note-note-image-input note-input" type="file" name="files" accept="image/*" multiple="multiple"/>' + opt.imageLimitation + '</div>' + '<div class="note-form-group">' + '<label for="note-dialog-image-url-' + opt.id + '" class="note-form-label">' + opt.lang.image.url + '</label>' + '<input id="note-dialog-image-url-' + opt.id + '" class="note-image-url note-input" type="text"/>' + '</div>'; var footer = ['<button href="#" type="button" class="note-btn note-btn-primary note-btn-large note-image-btn disabled" disabled>', opt.lang.image.insert, '</button>'].join(''); return dialog({ title: opt.lang.image.insert, fade: opt.fade, body: body, footer: footer }).render(); }; var linkDialog = function linkDialog(opt) { var body = '<div class="note-form-group">' + '<label for="note-dialog-link-txt-' + opt.id + '" class="note-form-label">' + opt.lang.link.textToDisplay + '</label>' + '<input id="note-dialog-link-txt-' + opt.id + '" class="note-link-text note-input" type="text"/>' + '</div>' + '<div class="note-form-group">' + '<label for="note-dialog-link-url-' + opt.id + '" class="note-form-label">' + opt.lang.link.url + '</label>' + '<input id="note-dialog-link-url-' + opt.id + '" class="note-link-url note-input" type="text" value="http://"/>' + '</div>' + (!opt.disableLinkTarget ? '<div class="checkbox"><label for="note-dialog-link-nw-' + opt.id + '"><input id="note-dialog-link-nw-' + opt.id + '" type="checkbox" checked> ' + opt.lang.link.openInNewWindow + '</label></div>' : '') + '<div class="checkbox"><label for="note-dialog-link-up-' + opt.id + '"><input id="note-dialog-link-up-' + opt.id + '" type="checkbox" checked> ' + opt.lang.link.useProtocol + '</label></div>'; var footer = ['<button href="#" type="button" class="note-btn note-btn-primary note-link-btn disabled" disabled>', opt.lang.link.insert, '</button>'].join(''); return dialog({ className: 'link-dialog', title: opt.lang.link.insert, fade: opt.fade, body: body, footer: footer }).render(); }; var popover = renderer.create(['<div class="note-popover bottom">', '<div class="note-popover-arrow"></div>', '<div class="popover-content note-children-container"></div>', '</div>'].join(''), function ($node, options) { var direction = typeof options.direction !== 'undefined' ? options.direction : 'bottom'; $node.addClass(direction).hide(); if (options.hideArrow) { $node.find('.note-popover-arrow').hide(); } }); var summernote_lite_checkbox = renderer.create('<div class="checkbox"></div>', function ($node, options) { $node.html(['<label' + (options.id ? ' for="note-' + options.id + '"' : '') + '>', '<input role="checkbox" type="checkbox"' + (options.id ? ' id="note-' + options.id + '"' : ''), options.checked ? ' checked' : '', ' aria-checked="' + (options.checked ? 'true' : 'false') + '"/>', options.text ? options.text : '', '</label>'].join('')); }); var icon = function icon(iconClassName, tagName) { if (iconClassName.match(/^</)) { return iconClassName; } tagName = tagName || 'i'; return '<' + tagName + ' class="' + iconClassName + '"></' + tagName + '>'; }; var ui = function ui(editorOptions) { return { editor: editor, toolbar: toolbar, editingArea: editingArea, codable: codable, editable: editable, statusbar: statusbar, airEditor: airEditor, airEditable: airEditable, buttonGroup: buttonGroup, button: summernote_lite_button, dropdown: dropdown, dropdownCheck: dropdownCheck, dropdownButton: dropdownButton, dropdownButtonContents: dropdownButtonContents, dropdownCheckButton: dropdownCheckButton, paragraphDropdownButton: paragraphDropdownButton, tableDropdownButton: tableDropdownButton, colorDropdownButton: colorDropdownButton, palette: palette, dialog: dialog, videoDialog: videoDialog, imageDialog: imageDialog, linkDialog: linkDialog, popover: popover, checkbox: summernote_lite_checkbox, icon: icon, options: editorOptions, toggleBtn: function toggleBtn($btn, isEnable) { $btn.toggleClass('disabled', !isEnable); $btn.attr('disabled', !isEnable); }, toggleBtnActive: function toggleBtnActive($btn, isActive) { $btn.toggleClass('active', isActive); }, check: function check($dom, value) { $dom.find('.checked').removeClass('checked'); $dom.find('[data-value="' + value + '"]').addClass('checked'); }, onDialogShown: function onDialogShown($dialog, handler) { $dialog.one('note.modal.show', handler); }, onDialogHidden: function onDialogHidden($dialog, handler) { $dialog.one('note.modal.hide', handler); }, showDialog: function showDialog($dialog) { $dialog.data('modal').show(); }, hideDialog: function hideDialog($dialog) { $dialog.data('modal').hide(); }, /** * get popover content area * * @param $popover * @returns {*} */ getPopoverContent: function getPopoverContent($popover) { return $popover.find('.note-popover-content'); }, /** * get dialog's body area * * @param $dialog * @returns {*} */ getDialogBody: function getDialogBody($dialog) { return $dialog.find('.note-modal-body'); }, createLayout: function createLayout($note) { var $editor = (editorOptions.airMode ? airEditor([editingArea([codable(), airEditable()])]) : editorOptions.toolbarPosition === 'bottom' ? editor([editingArea([codable(), editable()]), toolbar(), statusbar()]) : editor([toolbar(), editingArea([codable(), editable()]), statusbar()])).render(); $editor.insertAfter($note); return { note: $note, editor: $editor, toolbar: $editor.find('.note-toolbar'), editingArea: $editor.find('.note-editing-area'), editable: $editor.find('.note-editable'), codable: $editor.find('.note-codable'), statusbar: $editor.find('.note-statusbar') }; }, removeLayout: function removeLayout($note, layoutInfo) { $note.html(layoutInfo.editable.html()); layoutInfo.editor.remove(); $note.off('summernote'); // remove summernote custom event $note.show(); } }; }; (external_jQuery_default()).summernote = external_jQuery_default().extend((external_jQuery_default()).summernote, { ui_template: ui, "interface": 'lite' }); })(); /******/ return __webpack_exports__; /******/ })() ; }); //# sourceMappingURL=summernote-lite.js.map
294coder/Efficient-MIF
13,574
utils/ema_utils/post_hoc_ema.py
from __future__ import annotations from pathlib import Path from copy import deepcopy from functools import partial import torch from torch import nn, Tensor from torch.nn import Module, ModuleList import numpy as np from typing import Set, Tuple def exists(val): return val is not None def default(val, d): return val if exists(val) else d def first(arr): return arr[0] def get_module_device(m: Module): return next(m.parameters()).device def inplace_copy(tgt: Tensor, src: Tensor, *, auto_move_device = False): if auto_move_device: src = src.to(tgt.device) tgt.copy_(src) def inplace_lerp(tgt: Tensor, src: Tensor, weight, *, auto_move_device = False): if auto_move_device: src = src.to(tgt.device) tgt.lerp_(src, weight) # algorithm 2 in https://arxiv.org/abs/2312.02696 def sigma_rel_to_gamma(sigma_rel): t = sigma_rel ** -2 return np.roots([1, 7, 16 - t, 12 - t]).real.max().item() class KarrasEMA(Module): """ exponential moving average module that uses hyperparameters from the paper https://arxiv.org/abs/2312.02696 can either use gamma or sigma_rel from paper """ def __init__( self, model: Module, sigma_rel: float | None = None, gamma: float | None = None, ema_model: Module | None = None, # if your model has lazylinears or other types of non-deepcopyable modules, you can pass in your own ema model update_every: int = 100, frozen: bool = False, param_or_buffer_names_no_ema: Set[str] = set(), ignore_names: Set[str] = set(), ignore_startswith_names: Set[str] = set(), allow_different_devices = False # if the EMA model is on a different device (say CPU), automatically move the tensor ): super().__init__() assert exists(sigma_rel) ^ exists(gamma), 'either sigma_rel or gamma is given. gamma is derived from sigma_rel as in the paper, then beta is dervied from gamma' if exists(sigma_rel): gamma = sigma_rel_to_gamma(sigma_rel) self.gamma = gamma self.frozen = frozen self.online_model = [model] # ema model self.ema_model = ema_model if not exists(self.ema_model): try: self.ema_model = deepcopy(model) except Exception as e: print(f'Error: While trying to deepcopy model: {e}') print('Your model was not copyable. Please make sure you are not using any LazyLinear') exit() for p in self.ema_model.parameters(): p.detach_() # parameter and buffer names self.parameter_names = {name for name, param in self.ema_model.named_parameters() if torch.is_floating_point(param) or torch.is_complex(param)} self.buffer_names = {name for name, buffer in self.ema_model.named_buffers() if torch.is_floating_point(buffer) or torch.is_complex(buffer)} # tensor update functions self.inplace_copy = partial(inplace_copy, auto_move_device = allow_different_devices) self.inplace_lerp = partial(inplace_lerp, auto_move_device = allow_different_devices) # updating hyperparameters self.update_every = update_every assert isinstance(param_or_buffer_names_no_ema, (set, list)) self.param_or_buffer_names_no_ema = param_or_buffer_names_no_ema # parameter or buffer self.ignore_names = ignore_names self.ignore_startswith_names = ignore_startswith_names # whether to manage if EMA model is kept on a different device self.allow_different_devices = allow_different_devices # init and step states self.register_buffer('initted', torch.tensor(False)) self.register_buffer('step', torch.tensor(0)) @property def model(self): return first(self.online_model) @property def beta(self): return (1 - 1 / (self.step + 1)) ** (1 + self.gamma) def eval(self): return self.ema_model.eval() def restore_ema_model_device(self): device = self.initted.device self.ema_model.to(device) def get_params_iter(self, model): for name, param in model.named_parameters(): if name not in self.parameter_names: continue yield name, param def get_buffers_iter(self, model): for name, buffer in model.named_buffers(): if name not in self.buffer_names: continue yield name, buffer def copy_params_from_model_to_ema(self): copy = self.inplace_copy for (_, ma_params), (_, current_params) in zip(self.get_params_iter(self.ema_model), self.get_params_iter(self.model)): copy(ma_params.data, current_params.data) for (_, ma_buffers), (_, current_buffers) in zip(self.get_buffers_iter(self.ema_model), self.get_buffers_iter(self.model)): copy(ma_buffers.data, current_buffers.data) def copy_params_from_ema_to_model(self): copy = self.inplace_copy for (_, ma_params), (_, current_params) in zip(self.get_params_iter(self.ema_model), self.get_params_iter(self.model)): copy(current_params.data, ma_params.data) for (_, ma_buffers), (_, current_buffers) in zip(self.get_buffers_iter(self.ema_model), self.get_buffers_iter(self.model)): copy(current_buffers.data, ma_buffers.data) def update(self): step = self.step.item() self.step += 1 if (step % self.update_every) != 0: return if not self.initted.item(): self.copy_params_from_model_to_ema() self.initted.data.copy_(torch.tensor(True)) self.update_moving_average(self.ema_model, self.model) def iter_all_ema_params_and_buffers(self): for name, ma_params in self.get_params_iter(self.ema_model): if name in self.ignore_names: continue if any([name.startswith(prefix) for prefix in self.ignore_startswith_names]): continue if name in self.param_or_buffer_names_no_ema: continue yield ma_params for name, ma_buffer in self.get_buffers_iter(self.ema_model): if name in self.ignore_names: continue if any([name.startswith(prefix) for prefix in self.ignore_startswith_names]): continue if name in self.param_or_buffer_names_no_ema: continue yield ma_buffer @torch.no_grad() def update_moving_average(self, ma_model, current_model): if self.frozen: return copy, lerp = self.inplace_copy, self.inplace_lerp current_decay = self.beta for (name, current_params), (_, ma_params) in zip(self.get_params_iter(current_model), self.get_params_iter(ma_model)): if name in self.ignore_names: continue if any([name.startswith(prefix) for prefix in self.ignore_startswith_names]): continue if name in self.param_or_buffer_names_no_ema: copy(ma_params.data, current_params.data) continue lerp(ma_params.data, current_params.data, 1. - current_decay) for (name, current_buffer), (_, ma_buffer) in zip(self.get_buffers_iter(current_model), self.get_buffers_iter(ma_model)): if name in self.ignore_names: continue if any([name.startswith(prefix) for prefix in self.ignore_startswith_names]): continue if name in self.param_or_buffer_names_no_ema: copy(ma_buffer.data, current_buffer.data) continue lerp(ma_buffer.data, current_buffer.data, 1. - current_decay) def __call__(self, *args, **kwargs): return self.ema_model(*args, **kwargs) # post hoc ema wrapper # solving of the weights for combining all checkpoints into a newly synthesized EMA at desired gamma # Algorithm 3 copied from paper, redone in torch def p_dot_p(t_a, gamma_a, t_b, gamma_b): t_ratio = t_a / t_b t_exp = torch.where(t_a < t_b , gamma_b , -gamma_a) t_max = torch.maximum(t_a , t_b) num = (gamma_a + 1) * (gamma_b + 1) * t_ratio ** t_exp den = (gamma_a + gamma_b + 1) * t_max return num / den def solve_weights(t_i, gamma_i, t_r, gamma_r): rv = lambda x: x.double().reshape(-1, 1) cv = lambda x: x.double().reshape(1, -1) A = p_dot_p(rv(t_i), rv(gamma_i), cv(t_i), cv(gamma_i)) b = p_dot_p(rv(t_i), rv(gamma_i), cv(t_r), cv(gamma_r)) return torch.linalg.solve(A, b) class PostHocEMA(Module): def __init__( self, model: Module, sigma_rels: Tuple[float, ...] | None = None, gammas: Tuple[float, ...] | None = None, checkpoint_every_num_steps: int = 1000, checkpoint_folder: str = './post-hoc-ema-checkpoints', checkpoint_dtype: torch.dtype = torch.float16, **kwargs ): super().__init__() assert exists(sigma_rels) ^ exists(gammas) if exists(sigma_rels): gammas = tuple(map(sigma_rel_to_gamma, sigma_rels)) assert len(gammas) > 1, 'at least 2 ema models with different gammas in order to synthesize new ema models of a different gamma' assert len(set(gammas)) == len(gammas), 'calculated gammas must be all unique' self.gammas = gammas self.num_ema_models = len(gammas) self._model = [model] self.ema_models = ModuleList([KarrasEMA(model, gamma = gamma, **kwargs) for gamma in gammas]) self.checkpoint_folder = Path(checkpoint_folder) self.checkpoint_folder.mkdir(exist_ok = True, parents = True) assert self.checkpoint_folder.is_dir() self.checkpoint_every_num_steps = checkpoint_every_num_steps self.checkpoint_dtype = checkpoint_dtype self.ema_kwargs = kwargs @property def model(self): return first(self._model) @property def step(self): return first(self.ema_models).step @property def device(self): return self.step.device def copy_params_from_model_to_ema(self): for ema_model in self.ema_models: ema_model.copy_params_from_model_to_ema() def copy_params_from_ema_to_model(self): for ema_model in self.ema_models: ema_model.copy_params_from_ema_to_model() def update(self): for ema_model in self.ema_models: ema_model.update() if not (self.step.item() % self.checkpoint_every_num_steps): self.checkpoint() def checkpoint(self): step = self.step.item() for ind, ema_model in enumerate(self.ema_models): filename = f'{ind}.{step}.pt' path = self.checkpoint_folder / filename pkg = deepcopy(ema_model).to(self.checkpoint_dtype).state_dict() torch.save(pkg, str(path)) def synthesize_ema_model( self, gamma: float | None = None, sigma_rel: float | None = None, step: int | None = None, ) -> KarrasEMA: assert exists(gamma) ^ exists(sigma_rel) device = self.device if exists(sigma_rel): gamma = sigma_rel_to_gamma(sigma_rel) synthesized_ema_model = KarrasEMA( model = self.model, gamma = gamma, **self.ema_kwargs ) synthesized_ema_model # get all checkpoints gammas = [] timesteps = [] checkpoints = [*self.checkpoint_folder.glob('*.pt')] for file in checkpoints: gamma_ind, timestep = map(int, file.stem.split('.')) gammas.append(self.gammas[gamma_ind]) timesteps.append(timestep) step = default(step, max(timesteps)) assert step <= max(timesteps), f'you can only synthesize for a timestep that is less than the max timestep {max(timesteps)}' # line up with Algorithm 3 gamma_i = torch.tensor(gammas, device = device) t_i = torch.tensor(timesteps, device = device) gamma_r = torch.tensor([gamma], device = device) t_r = torch.tensor([step], device = device) # solve for weights for combining all checkpoints into synthesized, using least squares as in paper weights = solve_weights(t_i, gamma_i, t_r, gamma_r) weights = weights.squeeze(-1) # now sum up all the checkpoints using the weights one by one tmp_ema_model = KarrasEMA( model = self.model, gamma = gamma, **self.ema_kwargs ) for ind, (checkpoint, weight) in enumerate(zip(checkpoints, weights.tolist())): is_first = ind == 0 # load checkpoint into a temporary ema model ckpt_state_dict = torch.load(str(checkpoint)) tmp_ema_model.load_state_dict(ckpt_state_dict) # add weighted checkpoint to synthesized for ckpt_tensor, synth_tensor in zip(tmp_ema_model.iter_all_ema_params_and_buffers(), synthesized_ema_model.iter_all_ema_params_and_buffers()): if is_first: synth_tensor.zero_() synth_tensor.add_(ckpt_tensor * weight) # return the synthesized model return synthesized_ema_model def __call__(self, *args, **kwargs): return tuple(ema_model(*args, **kwargs) for ema_model in self.ema_models)
2881099/FreeSql.AdminLTE
19,392
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote.min.css
@font-face{font-display:auto;font-family:summernote;font-style:normal;font-weight:400;src:url(font/summernote.eot?#iefix) format("embedded-opentype"),url(font/summernote.woff2) format("woff2"),url(font/summernote.woff) format("woff"),url(font/summernote.ttf) format("truetype")}[class*=" note-icon"]:before,[class^=note-icon]:before{text-rendering:auto;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;speak:none;display:inline-block;font-family:summernote;font-size:inherit;font-style:normal;text-decoration:inherit;text-transform:none;vertical-align:middle}.note-icon-fw{text-align:center;width:1.25em}.note-icon-border{border:.08em solid #eee;border-radius:.1em;padding:.2em .25em .15em}.note-icon-pull-left{float:left}.note-icon-pull-right{float:right}.note-icon.note-icon-pull-left{margin-right:.3em}.note-icon.note-icon-pull-right{margin-left:.3em}.note-icon-align:before{content:"\ea01"}.note-icon-align-center:before{content:"\ea02"}.note-icon-align-indent:before{content:"\ea03"}.note-icon-align-justify:before{content:"\ea04"}.note-icon-align-left:before{content:"\ea05"}.note-icon-align-outdent:before{content:"\ea06"}.note-icon-align-right:before{content:"\ea07"}.note-icon-arrow-circle-down:before{content:"\ea08"}.note-icon-arrow-circle-left:before{content:"\ea09"}.note-icon-arrow-circle-right:before{content:"\ea0a"}.note-icon-arrow-circle-up:before{content:"\ea0b"}.note-icon-arrows-alt:before{content:"\ea0c"}.note-icon-arrows-h:before{content:"\ea0d"}.note-icon-arrows-v:before{content:"\ea0e"}.note-icon-bold:before{content:"\ea0f"}.note-icon-caret:before{content:"\ea10"}.note-icon-chain-broken:before{content:"\ea11"}.note-icon-circle:before{content:"\ea12"}.note-icon-close:before{content:"\ea13"}.note-icon-code:before{content:"\ea14"}.note-icon-col-after:before{content:"\ea15"}.note-icon-col-before:before{content:"\ea16"}.note-icon-col-remove:before{content:"\ea17"}.note-icon-eraser:before{content:"\ea18"}.note-icon-float-left:before{content:"\ea19"}.note-icon-float-none:before{content:"\ea1a"}.note-icon-float-right:before{content:"\ea1b"}.note-icon-font:before{content:"\ea1c"}.note-icon-frame:before{content:"\ea1d"}.note-icon-italic:before{content:"\ea1e"}.note-icon-link:before{content:"\ea1f"}.note-icon-magic:before{content:"\ea20"}.note-icon-menu-check:before{content:"\ea21"}.note-icon-minus:before{content:"\ea22"}.note-icon-orderedlist:before{content:"\ea23"}.note-icon-pencil:before{content:"\ea24"}.note-icon-picture:before{content:"\ea25"}.note-icon-question:before{content:"\ea26"}.note-icon-redo:before{content:"\ea27"}.note-icon-rollback:before{content:"\ea28"}.note-icon-row-above:before{content:"\ea29"}.note-icon-row-below:before{content:"\ea2a"}.note-icon-row-remove:before{content:"\ea2b"}.note-icon-special-character:before{content:"\ea2c"}.note-icon-square:before{content:"\ea2d"}.note-icon-strikethrough:before{content:"\ea2e"}.note-icon-subscript:before{content:"\ea2f"}.note-icon-summernote:before{content:"\ea30"}.note-icon-superscript:before{content:"\ea31"}.note-icon-table:before{content:"\ea32"}.note-icon-text-height:before{content:"\ea33"}.note-icon-trash:before{content:"\ea34"}.note-icon-underline:before{content:"\ea35"}.note-icon-undo:before{content:"\ea36"}.note-icon-unorderedlist:before{content:"\ea37"}.note-icon-video:before{content:"\ea38"}.note-editor{position:relative}.note-editor .note-dropzone{background-color:#fff;color:#87cefa;display:none;opacity:.95;position:absolute;z-index:100}.note-editor .note-dropzone .note-dropzone-message{display:table-cell;font-size:28px;font-weight:700;text-align:center;vertical-align:middle}.note-editor .note-dropzone.hover{color:#098ddf}.note-editor.dragover .note-dropzone{display:table}.note-editor .note-editing-area{position:relative}.note-editor .note-editing-area .note-editable{outline:none}.note-editor .note-editing-area .note-editable sup{vertical-align:super}.note-editor .note-editing-area .note-editable sub{vertical-align:sub}.note-editor .note-editing-area .note-editable img.note-float-left{margin-right:10px}.note-editor .note-editing-area .note-editable img.note-float-right{margin-left:10px}.note-editor.note-airframe,.note-editor.note-frame{border:1px solid #00000032}.note-editor.note-airframe.codeview .note-editing-area .note-editable,.note-editor.note-frame.codeview .note-editing-area .note-editable{display:none}.note-editor.note-airframe.codeview .note-editing-area .note-codable,.note-editor.note-frame.codeview .note-editing-area .note-codable{display:block}.note-editor.note-airframe .note-editing-area,.note-editor.note-frame .note-editing-area{overflow:hidden}.note-editor.note-airframe .note-editing-area .note-editable,.note-editor.note-frame .note-editing-area .note-editable{word-wrap:break-word;overflow:auto;padding:10px}.note-editor.note-airframe .note-editing-area .note-editable[contenteditable=false],.note-editor.note-frame .note-editing-area .note-editable[contenteditable=false]{background-color:#8080801d}.note-editor.note-airframe .note-editing-area .note-codable,.note-editor.note-frame .note-editing-area .note-codable{background-color:#222;border:none;border-radius:0;box-shadow:none;-ms-box-sizing:border-box;box-sizing:border-box;color:#ccc;display:none;font-family:Menlo,Monaco,monospace,sans-serif;font-size:14px;margin-bottom:0;outline:none;padding:10px;resize:none;width:100%}.note-editor.note-airframe.fullscreen,.note-editor.note-frame.fullscreen{left:0;position:fixed;top:0;width:100%!important;z-index:1050}.note-editor.note-airframe.fullscreen .note-resizebar,.note-editor.note-frame.fullscreen .note-resizebar{display:none}.note-editor.note-airframe .note-status-output,.note-editor.note-frame .note-status-output{border:0;border-top:1px solid #e2e2e2;color:#000;display:block;font-size:14px;height:20px;line-height:1.42857143;margin-bottom:0;width:100%}.note-editor.note-airframe .note-status-output:empty,.note-editor.note-frame .note-status-output:empty{border-top:0 solid transparent;height:0}.note-editor.note-airframe .note-status-output .pull-right,.note-editor.note-frame .note-status-output .pull-right{float:right!important}.note-editor.note-airframe .note-status-output .text-muted,.note-editor.note-frame .note-status-output .text-muted{color:#777}.note-editor.note-airframe .note-status-output .text-primary,.note-editor.note-frame .note-status-output .text-primary{color:#286090}.note-editor.note-airframe .note-status-output .text-success,.note-editor.note-frame .note-status-output .text-success{color:#3c763d}.note-editor.note-airframe .note-status-output .text-info,.note-editor.note-frame .note-status-output .text-info{color:#31708f}.note-editor.note-airframe .note-status-output .text-warning,.note-editor.note-frame .note-status-output .text-warning{color:#8a6d3b}.note-editor.note-airframe .note-status-output .text-danger,.note-editor.note-frame .note-status-output .text-danger{color:#a94442}.note-editor.note-airframe .note-status-output .alert,.note-editor.note-frame .note-status-output .alert{background-color:#f5f5f5;border-radius:0;color:#000;margin:-7px 0 0;padding:7px 10px 2px}.note-editor.note-airframe .note-status-output .alert .note-icon,.note-editor.note-frame .note-status-output .alert .note-icon{margin-right:5px}.note-editor.note-airframe .note-status-output .alert-success,.note-editor.note-frame .note-status-output .alert-success{background-color:#dff0d8!important;color:#3c763d!important}.note-editor.note-airframe .note-status-output .alert-info,.note-editor.note-frame .note-status-output .alert-info{background-color:#d9edf7!important;color:#31708f!important}.note-editor.note-airframe .note-status-output .alert-warning,.note-editor.note-frame .note-status-output .alert-warning{background-color:#fcf8e3!important;color:#8a6d3b!important}.note-editor.note-airframe .note-status-output .alert-danger,.note-editor.note-frame .note-status-output .alert-danger{background-color:#f2dede!important;color:#a94442!important}.note-editor.note-airframe .note-statusbar,.note-editor.note-frame .note-statusbar{background-color:#8080801d;border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-top:1px solid #00000032}.note-editor.note-airframe .note-statusbar .note-resizebar,.note-editor.note-frame .note-statusbar .note-resizebar{cursor:ns-resize;height:9px;padding-top:1px;width:100%}.note-editor.note-airframe .note-statusbar .note-resizebar .note-icon-bar,.note-editor.note-frame .note-statusbar .note-resizebar .note-icon-bar{border-top:1px solid #00000032;margin:1px auto;width:20px}.note-editor.note-airframe .note-statusbar.locked .note-resizebar,.note-editor.note-frame .note-statusbar.locked .note-resizebar{cursor:default}.note-editor.note-airframe .note-statusbar.locked .note-resizebar .note-icon-bar,.note-editor.note-frame .note-statusbar.locked .note-resizebar .note-icon-bar{display:none}.note-editor.note-airframe .note-placeholder,.note-editor.note-frame .note-placeholder{padding:10px}.note-editor.note-airframe{border:0}.note-editor.note-airframe .note-editing-area .note-editable{padding:0}.note-popover.popover{display:none;max-width:none}.note-popover.popover .popover-content a{display:inline-block;max-width:200px;overflow:hidden;text-overflow:ellipsis;vertical-align:middle;white-space:nowrap}.note-popover.popover .arrow{left:20px!important}.note-toolbar{position:relative}.note-editor .note-toolbar,.note-popover .popover-content{margin:0;padding:0 0 5px 5px}.note-editor .note-toolbar>.note-btn-group,.note-popover .popover-content>.note-btn-group{margin-left:0;margin-right:5px;margin-top:5px}.note-editor .note-toolbar .note-btn-group .note-table,.note-popover .popover-content .note-btn-group .note-table{min-width:0;padding:5px}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker{font-size:18px}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher{cursor:pointer;height:10em;position:absolute!important;width:10em;z-index:3}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted{background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIj4+Pjp6ekKlAqjAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKhmnaJzPAAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat;height:5em;position:relative!important;width:5em;z-index:1}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted{background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIjd6vvD2f9LKLW+AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKwNDEVT0AAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat;height:1em;position:absolute!important;width:1em;z-index:2}.note-editor .note-toolbar .note-style .dropdown-style blockquote,.note-editor .note-toolbar .note-style .dropdown-style pre,.note-popover .popover-content .note-style .dropdown-style blockquote,.note-popover .popover-content .note-style .dropdown-style pre{margin:0;padding:5px 10px}.note-editor .note-toolbar .note-style .dropdown-style h1,.note-editor .note-toolbar .note-style .dropdown-style h2,.note-editor .note-toolbar .note-style .dropdown-style h3,.note-editor .note-toolbar .note-style .dropdown-style h4,.note-editor .note-toolbar .note-style .dropdown-style h5,.note-editor .note-toolbar .note-style .dropdown-style h6,.note-editor .note-toolbar .note-style .dropdown-style p,.note-popover .popover-content .note-style .dropdown-style h1,.note-popover .popover-content .note-style .dropdown-style h2,.note-popover .popover-content .note-style .dropdown-style h3,.note-popover .popover-content .note-style .dropdown-style h4,.note-popover .popover-content .note-style .dropdown-style h5,.note-popover .popover-content .note-style .dropdown-style h6,.note-popover .popover-content .note-style .dropdown-style p{margin:0;padding:0}.note-editor .note-toolbar .note-color-all .note-dropdown-menu,.note-popover .popover-content .note-color-all .note-dropdown-menu{min-width:337px}.note-editor .note-toolbar .note-color .dropdown-toggle,.note-popover .popover-content .note-color .dropdown-toggle{padding-left:5px;width:20px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette{display:inline-block;margin:0;width:160px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette:first-child,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette:first-child{margin:0 5px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-palette-title,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-palette-title{border-bottom:1px solid #eee;font-size:12px;margin:2px 7px;text-align:center}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset,.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select{border-radius:5px;cursor:pointer;font-size:11px;margin:3px;padding:0 3px;width:100%}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset:hover,.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select:hover,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset:hover,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select:hover{background:#eee}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-row,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-row{height:20px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select-btn,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select-btn{display:none}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn{border:1px solid #eee}.note-editor .note-toolbar .note-para .note-dropdown-menu,.note-popover .popover-content .note-para .note-dropdown-menu{min-width:228px;padding:5px}.note-editor .note-toolbar .note-para .note-dropdown-menu>div+div,.note-popover .popover-content .note-para .note-dropdown-menu>div+div{margin-left:5px}.note-editor .note-toolbar .note-dropdown-menu,.note-popover .popover-content .note-dropdown-menu{min-width:160px}.note-editor .note-toolbar .note-dropdown-menu.right,.note-popover .popover-content .note-dropdown-menu.right{left:auto;right:0}.note-editor .note-toolbar .note-dropdown-menu.right:before,.note-popover .popover-content .note-dropdown-menu.right:before{left:auto!important;right:9px}.note-editor .note-toolbar .note-dropdown-menu.right:after,.note-popover .popover-content .note-dropdown-menu.right:after{left:auto!important;right:10px}.note-editor .note-toolbar .note-dropdown-menu.note-check a i,.note-popover .popover-content .note-dropdown-menu.note-check a i{color:#00bfff;visibility:hidden}.note-editor .note-toolbar .note-dropdown-menu.note-check a.checked i,.note-popover .popover-content .note-dropdown-menu.note-check a.checked i{visibility:visible}.note-editor .note-toolbar .note-fontsize-10,.note-popover .popover-content .note-fontsize-10{font-size:10px}.note-editor .note-toolbar .note-color-palette,.note-popover .popover-content .note-color-palette{line-height:1}.note-editor .note-toolbar .note-color-palette div .note-color-btn,.note-popover .popover-content .note-color-palette div .note-color-btn{border:0;border-radius:0;height:20px;margin:0;padding:0;width:20px}.note-editor .note-toolbar .note-color-palette div .note-color-btn:hover,.note-popover .popover-content .note-color-palette div .note-color-btn:hover{transform:scale(1.2);transition:all .2s}.note-modal .modal-dialog{border-radius:5px;box-shadow:0 3px 9px rgba(0,0,0,.5);outline:0}.note-modal .form-group{margin-left:0;margin-right:0}.note-modal .note-modal-form{margin:0}.note-modal .note-image-dialog .note-dropzone{border:4px dashed #d3d3d3;color:#d3d3d3;font-size:30px;line-height:4;margin-bottom:10px;min-height:100px;text-align:center}@-moz-document url-prefix(){.note-modal .note-image-input{height:auto}}.note-placeholder{color:gray;display:none;position:absolute}.note-handle .note-control-selection{border:1px solid #000;display:none;position:absolute}.note-handle .note-control-selection>div{position:absolute}.note-handle .note-control-selection .note-control-selection-bg{background-color:#000;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30);filter:alpha(opacity=30);height:100%;-webkit-opacity:.3;-khtml-opacity:.3;-moz-opacity:.3;opacity:.3;width:100%}.note-handle .note-control-selection .note-control-handle,.note-handle .note-control-selection .note-control-holder,.note-handle .note-control-selection .note-control-sizing{border:1px solid #000;height:7px;width:7px}.note-handle .note-control-selection .note-control-sizing{background-color:#000}.note-handle .note-control-selection .note-control-nw{border-bottom:none;border-right:none;left:-5px;top:-5px}.note-handle .note-control-selection .note-control-ne{border-bottom:none;border-left:none;right:-5px;top:-5px}.note-handle .note-control-selection .note-control-sw{border-right:none;border-top:none;bottom:-5px;left:-5px}.note-handle .note-control-selection .note-control-se{bottom:-5px;cursor:se-resize;right:-5px}.note-handle .note-control-selection .note-control-se.note-control-holder{border-left:none;border-top:none;cursor:default}.note-handle .note-control-selection .note-control-selection-info{background-color:#000;border-radius:5px;bottom:0;color:#fff;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=70);filter:alpha(opacity=70);font-size:12px;margin:5px;-webkit-opacity:.7;-khtml-opacity:.7;-moz-opacity:.7;opacity:.7;padding:5px;right:0}.note-hint-popover{min-width:100px;padding:2px}.note-hint-popover .popover-content{max-height:150px;overflow:auto;padding:3px}.note-hint-popover .popover-content .note-hint-group .note-hint-item{display:block!important;padding:3px}.note-hint-popover .popover-content .note-hint-group .note-hint-item.active,.note-hint-popover .popover-content .note-hint-group .note-hint-item:hover{background-color:#428bca;clear:both;color:#fff;cursor:pointer;display:block;font-weight:400;line-height:1.4;outline:0;text-decoration:none;white-space:nowrap}body .note-fullscreen-body,html .note-fullscreen-body{overflow:hidden!important}
294coder/Efficient-MIF
3,234
utils/loss_landscape/plot_trajectory.py
""" Plot the optimization path in the space spanned by principle directions. """ import numpy as np import torch import copy import math import h5py import os import argparse import model_loader import net_plotter from projection import setup_PCA_directions, project_trajectory import plot_2D if __name__ == '__main__': parser = argparse.ArgumentParser(description='Plot optimization trajectory') parser.add_argument('--dataset', default='cifar10', help='dataset') parser.add_argument('--model', default='resnet56', help='trained models') parser.add_argument('--model_folder', default='', help='folders for models to be projected') parser.add_argument('--dir_type', default='weights', help="""direction type: weights (all weights except bias and BN paras) | states (include BN.running_mean/var)""") parser.add_argument('--ignore', default='', help='ignore bias and BN paras: biasbn (no bias or bn)') parser.add_argument('--prefix', default='model_', help='prefix for the checkpint model') parser.add_argument('--suffix', default='.t7', help='prefix for the checkpint model') parser.add_argument('--start_epoch', default=0, type=int, help='min index of epochs') parser.add_argument('--max_epoch', default=300, type=int, help='max number of epochs') parser.add_argument('--save_epoch', default=1, type=int, help='save models every few epochs') parser.add_argument('--dir_file', default='', help='load the direction file for projection') args = parser.parse_args() #-------------------------------------------------------------------------- # load the final model #-------------------------------------------------------------------------- last_model_file = args.model_folder + '/' + args.prefix + str(args.max_epoch) + args.suffix net = model_loader.load(args.dataset, args.model, last_model_file) w = net_plotter.get_weights(net) s = net.state_dict() #-------------------------------------------------------------------------- # collect models to be projected #-------------------------------------------------------------------------- model_files = [] for epoch in range(args.start_epoch, args.max_epoch + args.save_epoch, args.save_epoch): model_file = args.model_folder + '/' + args.prefix + str(epoch) + args.suffix assert os.path.exists(model_file), 'model %s does not exist' % model_file model_files.append(model_file) #-------------------------------------------------------------------------- # load or create projection directions #-------------------------------------------------------------------------- if args.dir_file: dir_file = args.dir_file else: dir_file = setup_PCA_directions(args, model_files, w, s) #-------------------------------------------------------------------------- # projection trajectory to given directions #-------------------------------------------------------------------------- proj_file = project_trajectory(dir_file, w, s, args.dataset, args.model, model_files, args.dir_type, 'cos') plot_2D.plot_trajectory(proj_file, dir_file)
2881099/FreeSql.AdminLTE
324,686
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-bs4.js
/*! * * Super simple WYSIWYG editor v0.8.20 * https://summernote.org * * * Copyright 2013- Alan Hong and contributors * Summernote may be freely distributed under the MIT license. * * Date: 2021-10-14T21:15Z * */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("jQuery")); else if(typeof define === 'function' && define.amd) define(["jQuery"], factory); else { var a = typeof exports === 'object' ? factory(require("jQuery")) : factory(root["jQuery"]); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(self, function(__WEBPACK_EXTERNAL_MODULE__1145__) { return /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ 9770: /***/ ((__unused_webpack_module, __unused_webpack___webpack_exports__, __webpack_require__) => { /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1145); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__); (jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote) = (jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote) || { lang: {} }; jquery__WEBPACK_IMPORTED_MODULE_0___default().extend((jquery__WEBPACK_IMPORTED_MODULE_0___default().summernote.lang), { 'en-US': { font: { bold: 'Bold', italic: 'Italic', underline: 'Underline', clear: 'Remove Font Style', height: 'Line Height', name: 'Font Family', strikethrough: 'Strikethrough', subscript: 'Subscript', superscript: 'Superscript', size: 'Font Size', sizeunit: 'Font Size Unit' }, image: { image: 'Picture', insert: 'Insert Image', resizeFull: 'Resize full', resizeHalf: 'Resize half', resizeQuarter: 'Resize quarter', resizeNone: 'Original size', floatLeft: 'Float Left', floatRight: 'Float Right', floatNone: 'Remove float', shapeRounded: 'Shape: Rounded', shapeCircle: 'Shape: Circle', shapeThumbnail: 'Shape: Thumbnail', shapeNone: 'Shape: None', dragImageHere: 'Drag image or text here', dropImage: 'Drop image or Text', selectFromFiles: 'Select from files', maximumFileSize: 'Maximum file size', maximumFileSizeError: 'Maximum file size exceeded.', url: 'Image URL', remove: 'Remove Image', original: 'Original' }, video: { video: 'Video', videoLink: 'Video Link', insert: 'Insert Video', url: 'Video URL', providers: '(YouTube, Google Drive, Vimeo, Vine, Instagram, DailyMotion, Youku, Peertube)' }, link: { link: 'Link', insert: 'Insert Link', unlink: 'Unlink', edit: 'Edit', textToDisplay: 'Text to display', url: 'To what URL should this link go?', openInNewWindow: 'Open in new window', useProtocol: 'Use default protocol' }, table: { table: 'Table', addRowAbove: 'Add row above', addRowBelow: 'Add row below', addColLeft: 'Add column left', addColRight: 'Add column right', delRow: 'Delete row', delCol: 'Delete column', delTable: 'Delete table' }, hr: { insert: 'Insert Horizontal Rule' }, style: { style: 'Style', p: 'Normal', blockquote: 'Quote', pre: 'Code', h1: 'Header 1', h2: 'Header 2', h3: 'Header 3', h4: 'Header 4', h5: 'Header 5', h6: 'Header 6' }, lists: { unordered: 'Unordered list', ordered: 'Ordered list' }, options: { help: 'Help', fullscreen: 'Full Screen', codeview: 'Code View' }, paragraph: { paragraph: 'Paragraph', outdent: 'Outdent', indent: 'Indent', left: 'Align left', center: 'Align center', right: 'Align right', justify: 'Justify full' }, color: { recent: 'Recent Color', more: 'More Color', background: 'Background Color', foreground: 'Text Color', transparent: 'Transparent', setTransparent: 'Set transparent', reset: 'Reset', resetToDefault: 'Reset to default', cpSelect: 'Select' }, shortcut: { shortcuts: 'Keyboard shortcuts', close: 'Close', textFormatting: 'Text formatting', action: 'Action', paragraphFormatting: 'Paragraph formatting', documentStyle: 'Document Style', extraKeys: 'Extra keys' }, help: { 'escape': 'Escape', 'insertParagraph': 'Insert Paragraph', 'undo': 'Undo the last command', 'redo': 'Redo the last command', 'tab': 'Tab', 'untab': 'Untab', 'bold': 'Set a bold style', 'italic': 'Set a italic style', 'underline': 'Set a underline style', 'strikethrough': 'Set a strikethrough style', 'removeFormat': 'Clean a style', 'justifyLeft': 'Set left align', 'justifyCenter': 'Set center align', 'justifyRight': 'Set right align', 'justifyFull': 'Set full align', 'insertUnorderedList': 'Toggle unordered list', 'insertOrderedList': 'Toggle ordered list', 'outdent': 'Outdent on current paragraph', 'indent': 'Indent on current paragraph', 'formatPara': 'Change current block\'s format as a paragraph(P tag)', 'formatH1': 'Change current block\'s format as H1', 'formatH2': 'Change current block\'s format as H2', 'formatH3': 'Change current block\'s format as H3', 'formatH4': 'Change current block\'s format as H4', 'formatH5': 'Change current block\'s format as H5', 'formatH6': 'Change current block\'s format as H6', 'insertHorizontalRule': 'Insert horizontal rule', 'linkDialog.show': 'Show Link Dialog' }, history: { undo: 'Undo', redo: 'Redo' }, specialChar: { specialChar: 'SPECIAL CHARACTERS', select: 'Select Special characters' }, output: { noSelection: 'No Selection Made!' } } }); /***/ }), /***/ 1145: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_MODULE__1145__; /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. (() => { // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXTERNAL MODULE: external "jQuery" var external_jQuery_ = __webpack_require__(1145); var external_jQuery_default = /*#__PURE__*/__webpack_require__.n(external_jQuery_); // EXTERNAL MODULE: ./src/lang/summernote-en-US.js var summernote_en_US = __webpack_require__(9770); ;// CONCATENATED MODULE: ./src/js/core/env.js /** * returns whether font is installed or not. * * @param {String} fontName * @return {Boolean} */ var genericFontFamilies = ['sans-serif', 'serif', 'monospace', 'cursive', 'fantasy']; function validFontName(fontName) { return external_jQuery_default().inArray(fontName.toLowerCase(), genericFontFamilies) === -1 ? "'".concat(fontName, "'") : fontName; } function isFontInstalled(fontName) { var testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS'; var testText = 'mmmmmmmmmmwwwww'; var testSize = '200px'; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); context.font = testSize + " '" + testFontName + "'"; var originalWidth = context.measureText(testText).width; context.font = testSize + ' ' + validFontName(fontName) + ', "' + testFontName + '"'; var width = context.measureText(testText).width; return originalWidth !== width; } var userAgent = navigator.userAgent; var isMSIE = /MSIE|Trident/i.test(userAgent); var browserVersion; if (isMSIE) { var matches = /MSIE (\d+[.]\d+)/.exec(userAgent); if (matches) { browserVersion = parseFloat(matches[1]); } matches = /Trident\/.*rv:([0-9]{1,}[.0-9]{0,})/.exec(userAgent); if (matches) { browserVersion = parseFloat(matches[1]); } } var isEdge = /Edge\/\d+/.test(userAgent); var isSupportTouch = 'ontouchstart' in window || navigator.MaxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; // [workaround] IE doesn't have input events for contentEditable // - see: https://goo.gl/4bfIvA var inputEventName = isMSIE ? 'DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted' : 'input'; /** * @class core.env * * Object which check platform and agent * * @singleton * @alternateClassName env */ /* harmony default export */ const env = ({ isMac: navigator.appVersion.indexOf('Mac') > -1, isMSIE: isMSIE, isEdge: isEdge, isFF: !isEdge && /firefox/i.test(userAgent), isPhantom: /PhantomJS/i.test(userAgent), isWebkit: !isEdge && /webkit/i.test(userAgent), isChrome: !isEdge && /chrome/i.test(userAgent), isSafari: !isEdge && /safari/i.test(userAgent) && !/chrome/i.test(userAgent), browserVersion: browserVersion, isSupportTouch: isSupportTouch, isFontInstalled: isFontInstalled, isW3CRangeSupport: !!document.createRange, inputEventName: inputEventName, genericFontFamilies: genericFontFamilies, validFontName: validFontName }); ;// CONCATENATED MODULE: ./src/js/core/func.js /** * @class core.func * * func utils (for high-order func's arg) * * @singleton * @alternateClassName func */ function eq(itemA) { return function (itemB) { return itemA === itemB; }; } function eq2(itemA, itemB) { return itemA === itemB; } function peq2(propName) { return function (itemA, itemB) { return itemA[propName] === itemB[propName]; }; } function ok() { return true; } function fail() { return false; } function not(f) { return function () { return !f.apply(f, arguments); }; } function and(fA, fB) { return function (item) { return fA(item) && fB(item); }; } function func_self(a) { return a; } function invoke(obj, method) { return function () { return obj[method].apply(obj, arguments); }; } var idCounter = 0; /** * reset globally-unique id * */ function resetUniqueId() { idCounter = 0; } /** * generate a globally-unique id * * @param {String} [prefix] */ function uniqueId(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 */ function rect2bnd(rect) { var $document = external_jQuery_default()(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} */ function invertObject(obj) { var inverted = {}; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { inverted[obj[key]] = key; } } return inverted; } /** * @param {String} namespace * @param {String} [prefix] * @return {String} */ function namespaceToCamel(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} */ function debounce(func, wait, immediate) { var timeout; return function () { var context = this; var args = arguments; var later = function later() { timeout = null; if (!immediate) { func.apply(context, args); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; } /** * * @param {String} url * @return {Boolean} */ function isValidUrl(url) { var expression = /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/gi; return expression.test(url); } /* harmony default export */ const func = ({ eq: eq, eq2: eq2, peq2: peq2, ok: ok, fail: fail, self: func_self, not: not, and: and, invoke: invoke, resetUniqueId: resetUniqueId, uniqueId: uniqueId, rect2bnd: rect2bnd, invertObject: invertObject, namespaceToCamel: namespaceToCamel, debounce: debounce, isValidUrl: isValidUrl }); ;// CONCATENATED MODULE: ./src/js/core/lists.js /** * returns the first item of an array. * * @param {Array} array */ function head(array) { return array[0]; } /** * returns the last item of an array. * * @param {Array} array */ function last(array) { return array[array.length - 1]; } /** * returns everything but the last entry of the array. * * @param {Array} array */ function initial(array) { return array.slice(0, array.length - 1); } /** * returns the rest of the items in an array. * * @param {Array} array */ function tail(array) { return array.slice(1); } /** * returns item of array */ function find(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. */ function lists_all(array, pred) { for (var idx = 0, len = array.length; idx < len; idx++) { if (!pred(array[idx])) { return false; } } return true; } /** * returns true if the value is present in the list. */ function contains(array, item) { if (array && array.length && item) { if (array.indexOf) { return array.indexOf(item) !== -1; } else if (array.contains) { // `DOMTokenList` doesn't implement `.indexOf`, but it implements `.contains` return array.contains(item); } } return false; } /** * get sum from a list * * @param {Array} array - array * @param {Function} fn - iterator */ function sum(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, ... */ function from(collection) { var result = []; var length = collection.length; var idx = -1; while (++idx < length) { result[idx] = collection[idx]; } return result; } /** * returns whether list is empty or not */ function isEmpty(array) { return !array || !array.length; } /** * cluster elements by predicate function. * * @param {Array} array - array * @param {Function} fn - predicate function for cluster rule * @param {Array[]} */ function clusterBy(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 */ function compact(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 */ function unique(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 */ function next(array, item) { if (array && array.length && item) { var idx = array.indexOf(item); return idx === -1 ? null : array[idx + 1]; } return null; } /** * returns prev item. * @param {Array} array */ function prev(array, item) { if (array && array.length && item) { var idx = array.indexOf(item); return idx === -1 ? null : array[idx - 1]; } return null; } /** * @class core.list * * list utils * * @singleton * @alternateClassName list */ /* harmony default export */ const lists = ({ head: head, last: last, initial: initial, tail: tail, prev: prev, next: next, find: find, contains: contains, all: lists_all, sum: sum, from: from, isEmpty: isEmpty, clusterBy: clusterBy, compact: compact, unique: unique }); ;// CONCATENATED MODULE: ./src/js/core/dom.js var NBSP_CHAR = String.fromCharCode(160); var ZERO_WIDTH_NBSP_CHAR = "\uFEFF"; /** * @method isEditable * * returns whether node is `note-editable` or not. * * @param {Node} node * @return {Boolean} */ function isEditable(node) { return node && external_jQuery_default()(node).hasClass('note-editable'); } /** * @method isControlSizing * * returns whether node is `note-control-sizing` or not. * * @param {Node} node * @return {Boolean} */ function isControlSizing(node) { return node && external_jQuery_default()(node).hasClass('note-control-sizing'); } /** * @method makePredByNodeName * * returns predicate which judge whether nodeName is same * * @param {String} nodeName * @return {Function} */ function makePredByNodeName(nodeName) { nodeName = nodeName.toUpperCase(); return function (node) { return node && node.nodeName.toUpperCase() === nodeName; }; } /** * @method isText * * * * @param {Node} node * @return {Boolean} true if node's type is text(3) */ function isText(node) { return node && node.nodeType === 3; } /** * @method isElement * * * * @param {Node} node * @return {Boolean} true if node's type is element(1) */ function isElement(node) { return node && node.nodeType === 1; } /** * ex) br, col, embed, hr, img, input, ... * @see http://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements */ function isVoid(node) { return node && /^BR|^IMG|^HR|^IFRAME|^BUTTON|^INPUT|^AUDIO|^VIDEO|^EMBED/.test(node.nodeName.toUpperCase()); } function isPara(node) { if (isEditable(node)) { return false; } // Chrome(v31.0), FF(v25.0.1) use DIV for paragraph return node && /^DIV|^P|^LI|^H[1-7]/.test(node.nodeName.toUpperCase()); } function isHeading(node) { return node && /^H[1-7]/.test(node.nodeName.toUpperCase()); } var isPre = makePredByNodeName('PRE'); var isLi = makePredByNodeName('LI'); function isPurePara(node) { return isPara(node) && !isLi(node); } var isTable = makePredByNodeName('TABLE'); var isData = makePredByNodeName('DATA'); function isInline(node) { return !isBodyContainer(node) && !isList(node) && !isHr(node) && !isPara(node) && !isTable(node) && !isBlockquote(node) && !isData(node); } function isList(node) { return node && /^UL|^OL/.test(node.nodeName.toUpperCase()); } var isHr = makePredByNodeName('HR'); function isCell(node) { return node && /^TD|^TH/.test(node.nodeName.toUpperCase()); } var isBlockquote = makePredByNodeName('BLOCKQUOTE'); function isBodyContainer(node) { return isCell(node) || isBlockquote(node) || isEditable(node); } var isAnchor = makePredByNodeName('A'); function isParaInline(node) { return isInline(node) && !!ancestor(node, isPara); } function isBodyInline(node) { return isInline(node) && !ancestor(node, isPara); } var isBody = makePredByNodeName('BODY'); /** * returns whether nodeB is closest sibling of nodeA * * @param {Node} nodeA * @param {Node} nodeB * @return {Boolean} */ function isClosestSibling(nodeA, nodeB) { return nodeA.nextSibling === nodeB || nodeA.previousSibling === nodeB; } /** * returns array of closest siblings with node * * @param {Node} node * @param {function} [pred] - predicate function * @return {Node[]} */ function withClosestSiblings(node, pred) { pred = pred || func.ok; var siblings = []; if (node.previousSibling && pred(node.previousSibling)) { siblings.push(node.previousSibling); } siblings.push(node); if (node.nextSibling && pred(node.nextSibling)) { siblings.push(node.nextSibling); } return siblings; } /** * blank HTML for cursor position * - [workaround] old IE only works with &nbsp; * - [workaround] IE11 and other browser works with bogus br */ var blankHTML = env.isMSIE && env.browserVersion < 11 ? '&nbsp;' : '<br>'; /** * @method nodeLength * * returns #text's text size or element's childNodes size * * @param {Node} node */ function nodeLength(node) { if (isText(node)) { return node.nodeValue.length; } if (node) { return node.childNodes.length; } return 0; } /** * returns whether deepest child node is empty or not. * * @param {Node} node * @return {Boolean} */ function deepestChildIsEmpty(node) { do { if (node.firstElementChild === null || node.firstElementChild.innerHTML === '') break; } while (node = node.firstElementChild); return dom_isEmpty(node); } /** * returns whether node is empty or not. * * @param {Node} node * @return {Boolean} */ function dom_isEmpty(node) { var len = nodeLength(node); if (len === 0) { return true; } else if (!isText(node) && len === 1 && node.innerHTML === blankHTML) { // ex) <p><br></p>, <span><br></span> return true; } else if (lists.all(node.childNodes, isText) && node.innerHTML === '') { // ex) <p></p>, <span></span> return true; } return false; } /** * padding blankHTML if node is empty (for cursor position) */ function paddingBlankHTML(node) { if (!isVoid(node) && !nodeLength(node)) { node.innerHTML = blankHTML; } } /** * find nearest ancestor predicate hit * * @param {Node} node * @param {Function} pred - predicate function */ function ancestor(node, pred) { while (node) { if (pred(node)) { return node; } if (isEditable(node)) { break; } node = node.parentNode; } return null; } /** * find nearest ancestor only single child blood line and predicate hit * * @param {Node} node * @param {Function} pred - predicate function */ function singleChildAncestor(node, pred) { node = node.parentNode; while (node) { if (nodeLength(node) !== 1) { break; } if (pred(node)) { return node; } if (isEditable(node)) { break; } node = node.parentNode; } return null; } /** * returns new array of ancestor nodes (until predicate hit). * * @param {Node} node * @param {Function} [optional] pred - predicate function */ function listAncestor(node, pred) { pred = pred || func.fail; var ancestors = []; ancestor(node, function (el) { if (!isEditable(el)) { ancestors.push(el); } return pred(el); }); return ancestors; } /** * find farthest ancestor predicate hit */ function lastAncestor(node, pred) { var ancestors = listAncestor(node); return lists.last(ancestors.filter(pred)); } /** * returns common ancestor node between two nodes. * * @param {Node} nodeA * @param {Node} nodeB */ function commonAncestor(nodeA, nodeB) { var ancestors = listAncestor(nodeA); for (var n = nodeB; n; n = n.parentNode) { if (ancestors.indexOf(n) > -1) return n; } return null; // difference document area } /** * listing all previous siblings (until predicate hit). * * @param {Node} node * @param {Function} [optional] pred - predicate function */ function listPrev(node, pred) { pred = pred || func.fail; var nodes = []; while (node) { if (pred(node)) { break; } nodes.push(node); node = node.previousSibling; } return nodes; } /** * listing next siblings (until predicate hit). * * @param {Node} node * @param {Function} [pred] - predicate function */ function listNext(node, pred) { pred = pred || func.fail; var nodes = []; while (node) { if (pred(node)) { break; } nodes.push(node); node = node.nextSibling; } return nodes; } /** * listing descendant nodes * * @param {Node} node * @param {Function} [pred] - predicate function */ function listDescendant(node, pred) { var descendants = []; pred = pred || func.ok; // start DFS(depth first search) with node (function fnWalk(current) { if (node !== current && pred(current)) { descendants.push(current); } for (var idx = 0, len = current.childNodes.length; idx < len; idx++) { fnWalk(current.childNodes[idx]); } })(node); return descendants; } /** * wrap node with new tag. * * @param {Node} node * @param {Node} tagName of wrapper * @return {Node} - wrapper */ function wrap(node, wrapperName) { var parent = node.parentNode; var wrapper = external_jQuery_default()('<' + wrapperName + '>')[0]; parent.insertBefore(wrapper, node); wrapper.appendChild(node); return wrapper; } /** * insert node after preceding * * @param {Node} node * @param {Node} preceding - predicate function */ function insertAfter(node, preceding) { var next = preceding.nextSibling; var parent = preceding.parentNode; if (next) { parent.insertBefore(node, next); } else { parent.appendChild(node); } return node; } /** * append elements. * * @param {Node} node * @param {Collection} aChild */ function appendChildNodes(node, aChild) { external_jQuery_default().each(aChild, function (idx, child) { node.appendChild(child); }); return node; } /** * returns whether boundaryPoint is left edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isLeftEdgePoint(point) { return point.offset === 0; } /** * returns whether boundaryPoint is right edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isRightEdgePoint(point) { return point.offset === nodeLength(point.node); } /** * returns whether boundaryPoint is edge or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isEdgePoint(point) { return isLeftEdgePoint(point) || isRightEdgePoint(point); } /** * returns whether node is left edge of ancestor or not. * * @param {Node} node * @param {Node} ancestor * @return {Boolean} */ function isLeftEdgeOf(node, ancestor) { while (node && node !== ancestor) { if (position(node) !== 0) { return false; } node = node.parentNode; } return true; } /** * returns whether node is right edge of ancestor or not. * * @param {Node} node * @param {Node} ancestor * @return {Boolean} */ function isRightEdgeOf(node, ancestor) { if (!ancestor) { return false; } while (node && node !== ancestor) { if (position(node) !== nodeLength(node.parentNode) - 1) { return false; } node = node.parentNode; } return true; } /** * returns whether point is left edge of ancestor or not. * @param {BoundaryPoint} point * @param {Node} ancestor * @return {Boolean} */ function isLeftEdgePointOf(point, ancestor) { return isLeftEdgePoint(point) && isLeftEdgeOf(point.node, ancestor); } /** * returns whether point is right edge of ancestor or not. * @param {BoundaryPoint} point * @param {Node} ancestor * @return {Boolean} */ function isRightEdgePointOf(point, ancestor) { return isRightEdgePoint(point) && isRightEdgeOf(point.node, ancestor); } /** * returns offset from parent. * * @param {Node} node */ function position(node) { var offset = 0; while (node = node.previousSibling) { offset += 1; } return offset; } function hasChildren(node) { return !!(node && node.childNodes && node.childNodes.length); } /** * returns previous boundaryPoint * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function prevPoint(point, isSkipInnerOffset) { var node; var offset; if (point.offset === 0) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node); } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset - 1]; offset = nodeLength(node); } else { node = point.node; offset = isSkipInnerOffset ? 0 : point.offset - 1; } return { node: node, offset: offset }; } /** * returns next boundaryPoint * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function nextPoint(point, isSkipInnerOffset) { var node, offset; if (nodeLength(point.node) === point.offset) { if (isEditable(point.node)) { return null; } var nextTextNode = getNextTextNode(point.node); if (nextTextNode) { node = nextTextNode; offset = 0; } else { node = point.node.parentNode; offset = position(point.node) + 1; } } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset]; offset = 0; } else { node = point.node; offset = isSkipInnerOffset ? nodeLength(point.node) : point.offset + 1; } return { node: node, offset: offset }; } /** * returns next boundaryPoint with empty node * * @param {BoundaryPoint} point * @param {Boolean} isSkipInnerOffset * @return {BoundaryPoint} */ function nextPointWithEmptyNode(point, isSkipInnerOffset) { var node, offset = 0; // if node is empty string node, return current node's sibling. if (dom_isEmpty(point.node)) { if (point.node === null) { return null; } node = point.node.nextSibling; offset = 0; return { node: node, offset: offset }; } if (nodeLength(point.node) === point.offset) { if (isEditable(point.node)) { return null; } node = point.node.parentNode; offset = position(point.node) + 1; // if next node is editable , return current node's sibling node. if (isEditable(node)) { node = point.node.nextSibling; offset = 0; } } else if (hasChildren(point.node)) { node = point.node.childNodes[point.offset]; offset = 0; if (dom_isEmpty(node)) { if (!dom_isEmpty(point.node.nextSibling)) { return { node: point.node.nextSibling, offset: offset }; } return null; } } else { node = point.node; offset = isSkipInnerOffset ? nodeLength(point.node) : point.offset + 1; if (dom_isEmpty(node)) { return null; } } return { node: node, offset: offset }; } /* * returns the next Text node index or 0 if not found. */ function getNextTextNode(actual) { if (!actual.nextSibling) return undefined; if (actual.parent !== actual.nextSibling.parent) return undefined; if (isText(actual.nextSibling)) return actual.nextSibling;else return getNextTextNode(actual.nextSibling); } /** * returns whether pointA and pointB is same or not. * * @param {BoundaryPoint} pointA * @param {BoundaryPoint} pointB * @return {Boolean} */ function isSamePoint(pointA, pointB) { return pointA.node === pointB.node && pointA.offset === pointB.offset; } /** * returns whether point is visible (can set cursor) or not. * * @param {BoundaryPoint} point * @return {Boolean} */ function isVisiblePoint(point) { if (isText(point.node) || !hasChildren(point.node) || dom_isEmpty(point.node)) { return true; } var leftNode = point.node.childNodes[point.offset - 1]; var rightNode = point.node.childNodes[point.offset]; if ((!leftNode || isVoid(leftNode)) && (!rightNode || isVoid(rightNode)) || isTable(rightNode)) { return true; } return false; } /** * @method prevPointUtil * * @param {BoundaryPoint} point * @param {Function} pred * @return {BoundaryPoint} */ function prevPointUntil(point, pred) { while (point) { if (pred(point)) { return point; } point = prevPoint(point); } return null; } /** * @method nextPointUntil * * @param {BoundaryPoint} point * @param {Function} pred * @return {BoundaryPoint} */ function nextPointUntil(point, pred) { while (point) { if (pred(point)) { return point; } point = nextPoint(point); } return null; } /** * returns whether point has character or not. * * @param {Point} point * @return {Boolean} */ function isCharPoint(point) { if (!isText(point.node)) { return false; } var ch = point.node.nodeValue.charAt(point.offset - 1); return ch && ch !== ' ' && ch !== NBSP_CHAR; } /** * returns whether point has space or not. * * @param {Point} point * @return {Boolean} */ function isSpacePoint(point) { if (!isText(point.node)) { return false; } var ch = point.node.nodeValue.charAt(point.offset - 1); return ch === ' ' || ch === NBSP_CHAR; } /** * @method walkPoint * * @param {BoundaryPoint} startPoint * @param {BoundaryPoint} endPoint * @param {Function} handler * @param {Boolean} isSkipInnerOffset */ function walkPoint(startPoint, endPoint, handler, isSkipInnerOffset) { var point = startPoint; while (point) { handler(point); if (isSamePoint(point, endPoint)) { break; } var isSkipOffset = isSkipInnerOffset && startPoint.node !== point.node && endPoint.node !== point.node; point = nextPointWithEmptyNode(point, isSkipOffset); } } /** * @method makeOffsetPath * * return offsetPath(array of offset) from ancestor * * @param {Node} ancestor - ancestor node * @param {Node} node */ function makeOffsetPath(ancestor, node) { var ancestors = listAncestor(node, func.eq(ancestor)); return ancestors.map(position).reverse(); } /** * @method fromOffsetPath * * return element from offsetPath(array of offset) * * @param {Node} ancestor - ancestor node * @param {array} offsets - offsetPath */ function fromOffsetPath(ancestor, offsets) { var current = ancestor; for (var i = 0, len = offsets.length; i < len; i++) { if (current.childNodes.length <= offsets[i]) { current = current.childNodes[current.childNodes.length - 1]; } else { current = current.childNodes[offsets[i]]; } } return current; } /** * @method splitNode * * split element or #text * * @param {BoundaryPoint} point * @param {Object} [options] * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false * @param {Boolean} [options.isNotSplitEdgePoint] - default: false * @param {Boolean} [options.isDiscardEmptySplits] - default: false * @return {Node} right node of boundaryPoint */ function splitNode(point, options) { var isSkipPaddingBlankHTML = options && options.isSkipPaddingBlankHTML; var isNotSplitEdgePoint = options && options.isNotSplitEdgePoint; var isDiscardEmptySplits = options && options.isDiscardEmptySplits; if (isDiscardEmptySplits) { isSkipPaddingBlankHTML = true; } // edge case if (isEdgePoint(point) && (isText(point.node) || isNotSplitEdgePoint)) { if (isLeftEdgePoint(point)) { return point.node; } else if (isRightEdgePoint(point)) { return point.node.nextSibling; } } // split #text if (isText(point.node)) { return point.node.splitText(point.offset); } else { var childNode = point.node.childNodes[point.offset]; var clone = insertAfter(point.node.cloneNode(false), point.node); appendChildNodes(clone, listNext(childNode)); if (!isSkipPaddingBlankHTML) { paddingBlankHTML(point.node); paddingBlankHTML(clone); } if (isDiscardEmptySplits) { if (dom_isEmpty(point.node)) { remove(point.node); } if (dom_isEmpty(clone)) { remove(clone); return point.node.nextSibling; } } return clone; } } /** * @method splitTree * * split tree by point * * @param {Node} root - split root * @param {BoundaryPoint} point * @param {Object} [options] * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false * @param {Boolean} [options.isNotSplitEdgePoint] - default: false * @return {Node} right node of boundaryPoint */ function splitTree(root, point, options) { // ex) [#text, <span>, <p>] 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 ? position(node) : nodeLength(parent) }, options); }); } /** * split point * * @param {Point} point * @param {Boolean} isInline * @return {Object} */ function splitPoint(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 = lists.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 }; } function create(nodeName) { return document.createElement(nodeName); } function createText(text) { return document.createTextNode(text); } /** * @method remove * * remove node, (isRemoveChild: remove child or not) * * @param {Node} node * @param {Boolean} isRemoveChild */ function remove(node, isRemoveChild) { if (!node || !node.parentNode) { return; } if (node.removeNode) { return node.removeNode(isRemoveChild); } var parent = node.parentNode; if (!isRemoveChild) { var nodes = []; for (var i = 0, len = node.childNodes.length; i < len; i++) { nodes.push(node.childNodes[i]); } for (var _i = 0, _len = nodes.length; _i < _len; _i++) { parent.insertBefore(nodes[_i], node); } } parent.removeChild(node); } /** * @method removeWhile * * @param {Node} node * @param {Function} pred */ function removeWhile(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 */ function replace(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, lists.from(node.childNodes)); insertAfter(newNode, node); remove(node); return newNode; } var isTextarea = makePredByNodeName('TEXTAREA'); /** * @param {jQuery} $node * @param {Boolean} [stripLinebreaks] - default: false */ function value($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] */ function html($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 = markup.trim(); } return markup; } function posFromPlaceholder(placeholder) { var $placeholder = external_jQuery_default()(placeholder); var pos = $placeholder.offset(); var height = $placeholder.outerHeight(true); // include margin return { left: pos.left, top: pos.top + height }; } function attachEvents($node, events) { Object.keys(events).forEach(function (key) { $node.on(key, events[key]); }); } function detachEvents($node, events) { Object.keys(events).forEach(function (key) { $node.off(key, events[key]); }); } /** * @method isCustomStyleTag * * assert if a node contains a "note-styletag" class, * which implies that's a custom-made style tag node * * @param {Node} an HTML DOM node */ function isCustomStyleTag(node) { return node && !isText(node) && lists.contains(node.classList, 'note-styletag'); } /* harmony default export */ const dom = ({ /** @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: "<p>".concat(blankHTML, "</p>"), 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, deepestChildIsEmpty: deepestChildIsEmpty, isEmpty: dom_isEmpty, isEmptyAnchor: func.and(isAnchor, dom_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, nextPointWithEmptyNode: nextPointWithEmptyNode, isSamePoint: isSamePoint, isVisiblePoint: isVisiblePoint, prevPointUntil: prevPointUntil, nextPointUntil: nextPointUntil, isCharPoint: isCharPoint, isSpacePoint: isSpacePoint, 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, isCustomStyleTag: isCustomStyleTag }); ;// CONCATENATED MODULE: ./src/js/Context.js function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var Context = /*#__PURE__*/function () { /** * @param {jQuery} $note * @param {Object} options */ function Context($note, options) { _classCallCheck(this, Context); this.$note = $note; this.memos = {}; this.modules = {}; this.layoutInfo = {}; this.options = external_jQuery_default().extend(true, {}, options); // init ui with options (external_jQuery_default()).summernote.ui = external_jQuery_default().summernote.ui_template(this.options); this.ui = (external_jQuery_default()).summernote.ui; this.initialize(); } /** * create layout and initialize modules and other resources */ _createClass(Context, [{ key: "initialize", value: function initialize() { this.layoutInfo = this.ui.createLayout(this.$note); this._initialize(); this.$note.hide(); return this; } /** * destroy modules and other resources and remove layout */ }, { key: "destroy", value: function destroy() { this._destroy(); this.$note.removeData('summernote'); this.ui.removeLayout(this.$note, this.layoutInfo); } /** * destory modules and other resources and initialize it again */ }, { key: "reset", value: function reset() { var disabled = this.isDisabled(); this.code(dom.emptyPara); this._destroy(); this._initialize(); if (disabled) { this.disable(); } } }, { key: "_initialize", value: function _initialize() { var _this = this; // set own id this.options.id = func.uniqueId(external_jQuery_default().now()); // set default container for tooltips, popovers, and dialogs this.options.container = this.options.container || this.layoutInfo.editor; // add optional buttons var buttons = external_jQuery_default().extend({}, this.options.buttons); Object.keys(buttons).forEach(function (key) { _this.memo('button.' + key, buttons[key]); }); var modules = external_jQuery_default().extend({}, this.options.modules, (external_jQuery_default()).summernote.plugins || {}); // add and initialize modules Object.keys(modules).forEach(function (key) { _this.module(key, modules[key], true); }); Object.keys(this.modules).forEach(function (key) { _this.initializeModule(key); }); } }, { key: "_destroy", value: function _destroy() { var _this2 = this; // destroy modules with reversed order Object.keys(this.modules).reverse().forEach(function (key) { _this2.removeModule(key); }); Object.keys(this.memos).forEach(function (key) { _this2.removeMemo(key); }); // trigger custom onDestroy callback this.triggerEvent('destroy', this); } }, { key: "code", value: function code(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.invoke('codeview.sync', html); } else { this.layoutInfo.editable.html(html); } this.$note.val(html); this.triggerEvent('change', html, this.layoutInfo.editable); } } }, { key: "isDisabled", value: function isDisabled() { return this.layoutInfo.editable.attr('contenteditable') === 'false'; } }, { key: "enable", value: function enable() { this.layoutInfo.editable.attr('contenteditable', true); this.invoke('toolbar.activate', true); this.triggerEvent('disable', false); this.options.editing = true; } }, { key: "disable", value: function disable() { // close codeview if codeview is opend if (this.invoke('codeview.isActivated')) { this.invoke('codeview.deactivate'); } this.layoutInfo.editable.attr('contenteditable', false); this.options.editing = false; this.invoke('toolbar.deactivate', true); this.triggerEvent('disable', true); } }, { key: "triggerEvent", value: function triggerEvent() { var namespace = lists.head(arguments); var args = lists.tail(lists.from(arguments)); var callback = this.options.callbacks[func.namespaceToCamel(namespace, 'on')]; if (callback) { callback.apply(this.$note[0], args); } this.$note.trigger('summernote.' + namespace, args); } }, { key: "initializeModule", value: function initializeModule(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(this.$note, module.events); } } }, { key: "module", value: function module(key, ModuleClass, withoutIntialize) { if (arguments.length === 1) { return this.modules[key]; } this.modules[key] = new ModuleClass(this); if (!withoutIntialize) { this.initializeModule(key); } } }, { key: "removeModule", value: function removeModule(key) { var module = this.modules[key]; if (module.shouldInitialize()) { if (module.events) { dom.detachEvents(this.$note, module.events); } if (module.destroy) { module.destroy(); } } delete this.modules[key]; } }, { key: "memo", value: function memo(key, obj) { if (arguments.length === 1) { return this.memos[key]; } this.memos[key] = obj; } }, { key: "removeMemo", value: function removeMemo(key) { if (this.memos[key] && this.memos[key].destroy) { this.memos[key].destroy(); } delete this.memos[key]; } /** * Some buttons need to change their visual style immediately once they get pressed */ }, { key: "createInvokeHandlerAndUpdateState", value: function createInvokeHandlerAndUpdateState(namespace, value) { var _this3 = this; return function (event) { _this3.createInvokeHandler(namespace, value)(event); _this3.invoke('buttons.updateCurrentStyle'); }; } }, { key: "createInvokeHandler", value: function createInvokeHandler(namespace, value) { var _this4 = this; return function (event) { event.preventDefault(); var $target = external_jQuery_default()(event.target); _this4.invoke(namespace, value || $target.closest('[data-value]').data('value'), $target); }; } }, { key: "invoke", value: function invoke() { var namespace = lists.head(arguments); var args = lists.tail(lists.from(arguments)); var splits = namespace.split('.'); var hasSeparator = splits.length > 1; var moduleName = hasSeparator && lists.head(splits); var methodName = hasSeparator ? lists.last(splits) : lists.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 Context; }(); ;// CONCATENATED MODULE: ./src/js/summernote.js external_jQuery_default().fn.extend({ /** * Summernote API * * @param {Object|String} * @return {this} */ summernote: function summernote() { var type = external_jQuery_default().type(lists.head(arguments)); var isExternalAPICalled = type === 'string'; var hasInitOptions = type === 'object'; var options = external_jQuery_default().extend({}, (external_jQuery_default()).summernote.options, hasInitOptions ? lists.head(arguments) : {}); // Update options options.langInfo = external_jQuery_default().extend(true, {}, (external_jQuery_default()).summernote.lang["en-US"], (external_jQuery_default()).summernote.lang[options.lang]); options.icons = external_jQuery_default().extend(true, {}, (external_jQuery_default()).summernote.options.icons, options.icons); options.tooltip = options.tooltip === 'auto' ? !env.isSupportTouch : options.tooltip; this.each(function (idx, note) { var $note = external_jQuery_default()(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, lists.from(arguments)); } else if (options.focus) { context.invoke('editor.focus'); } } return this; } }); ;// CONCATENATED MODULE: ./src/js/core/range.js function range_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function range_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function range_createClass(Constructor, protoProps, staticProps) { if (protoProps) range_defineProperties(Constructor.prototype, protoProps); if (staticProps) range_defineProperties(Constructor, staticProps); return Constructor; } /** * return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js * * @param {TextRange} textRange * @param {Boolean} isStart * @return {BoundaryPoint} * * @see http://msdn.microsoft.com/en-us/library/ie/ms535872(v=vs.85).aspx */ function textRangeToPoint(textRange, isStart) { var container = textRange.parentElement(); var offset; var tester = document.body.createTextRange(); var prevContainer; var childNodes = lists.from(container.childNodes); for (offset = 0; offset < childNodes.length; offset++) { if (dom.isText(childNodes[offset])) { continue; } tester.moveToElementText(childNodes[offset]); if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; } prevContainer = childNodes[offset]; } if (offset !== 0 && dom.isText(childNodes[offset - 1])) { var textRangeStart = document.body.createTextRange(); var curTextNode = null; textRangeStart.moveToElementText(prevContainer || container); textRangeStart.collapse(!prevContainer); curTextNode = prevContainer ? prevContainer.nextSibling : container.firstChild; var pointTester = textRange.duplicate(); pointTester.setEndPoint('StartToStart', textRangeStart); var textCount = pointTester.text.replace(/[\r\n]/g, '').length; while (textCount > curTextNode.nodeValue.length && curTextNode.nextSibling) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } // [workaround] enforce IE to re-reference curTextNode, hack var dummy = curTextNode.nodeValue; // eslint-disable-line if (isStart && curTextNode.nextSibling && dom.isText(curTextNode.nextSibling) && textCount === curTextNode.nodeValue.length) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } container = curTextNode; offset = textCount; } return { cont: container, offset: offset }; } /** * return TextRange from boundary point (inspired by google closure-library) * @param {BoundaryPoint} point * @return {TextRange} */ function pointToTextRange(point) { var textRangeInfo = function textRangeInfo(container, offset) { var node, isCollapseToStart; if (dom.isText(container)) { var prevTextNodes = dom.listPrev(container, func.not(dom.isText)); var prevContainer = lists.last(prevTextNodes).previousSibling; node = prevContainer || container.parentNode; offset += lists.sum(lists.tail(prevTextNodes), dom.nodeLength); isCollapseToStart = !prevContainer; } else { node = container.childNodes[offset] || container; if (dom.isText(node)) { return textRangeInfo(node, 0); } offset = 0; isCollapseToStart = false; } return { node: node, collapseToStart: isCollapseToStart, offset: offset }; }; var textRange = document.body.createTextRange(); var info = textRangeInfo(point.node, point.offset); textRange.moveToElementText(info.node); textRange.collapse(info.collapseToStart); textRange.moveStart('character', info.offset); return textRange; } /** * Wrapped Range * * @constructor * @param {Node} sc - start container * @param {Number} so - start offset * @param {Node} ec - end container * @param {Number} eo - end offset */ var WrappedRange = /*#__PURE__*/function () { function WrappedRange(sc, so, ec, eo) { range_classCallCheck(this, WrappedRange); this.sc = sc; this.so = so; this.ec = ec; this.eo = eo; // isOnEditable: judge whether range is on editable or not this.isOnEditable = this.makeIsOn(dom.isEditable); // isOnList: judge whether range is on list node or not this.isOnList = this.makeIsOn(dom.isList); // isOnAnchor: judge whether range is on anchor node or not this.isOnAnchor = this.makeIsOn(dom.isAnchor); // isOnCell: judge whether range is on cell node or not this.isOnCell = this.makeIsOn(dom.isCell); // isOnData: judge whether range is on data node or not this.isOnData = this.makeIsOn(dom.isData); } // nativeRange: get nativeRange from sc, so, ec, eo range_createClass(WrappedRange, [{ key: "nativeRange", value: function nativeRange() { if (env.isW3CRangeSupport) { var w3cRange = document.createRange(); w3cRange.setStart(this.sc, this.so); w3cRange.setEnd(this.ec, this.eo); return w3cRange; } else { var textRange = pointToTextRange({ node: this.sc, offset: this.so }); textRange.setEndPoint('EndToEnd', pointToTextRange({ node: this.ec, offset: this.eo })); return textRange; } } }, { key: "getPoints", value: function getPoints() { return { sc: this.sc, so: this.so, ec: this.ec, eo: this.eo }; } }, { key: "getStartPoint", value: function getStartPoint() { return { node: this.sc, offset: this.so }; } }, { key: "getEndPoint", value: function getEndPoint() { return { node: this.ec, offset: this.eo }; } /** * select update visible range */ }, { key: "select", value: function select() { var nativeRng = this.nativeRange(); if (env.isW3CRangeSupport) { var selection = document.getSelection(); if (selection.rangeCount > 0) { selection.removeAllRanges(); } selection.addRange(nativeRng); } else { nativeRng.select(); } return this; } /** * Moves the scrollbar to start container(sc) of current range * * @return {WrappedRange} */ }, { key: "scrollIntoView", value: function scrollIntoView(container) { var height = external_jQuery_default()(container).height(); if (container.scrollTop + height < this.sc.offsetTop) { container.scrollTop += Math.abs(container.scrollTop + height - this.sc.offsetTop); } return this; } /** * @return {WrappedRange} */ }, { key: "normalize", value: function normalize() { /** * @param {BoundaryPoint} point * @param {Boolean} isLeftToRight - true: prefer to choose right node * - false: prefer to choose left node * @return {BoundaryPoint} */ var getVisiblePoint = function getVisiblePoint(point, isLeftToRight) { if (!point) { return point; } // Just use the given point [XXX:Adhoc] // - case 01. if the point is on the middle of the node // - case 02. if the point is on the right edge and prefer to choose left node // - case 03. if the point is on the left edge and prefer to choose right node // - case 04. if the point is on the right edge and prefer to choose right node but the node is void // - case 05. if the point is on the left edge and prefer to choose left node but the node is void // - case 06. if the point is on the block node and there is no children if (dom.isVisiblePoint(point)) { if (!dom.isEdgePoint(point) || dom.isRightEdgePoint(point) && !isLeftToRight || dom.isLeftEdgePoint(point) && isLeftToRight || dom.isRightEdgePoint(point) && isLeftToRight && dom.isVoid(point.node.nextSibling) || dom.isLeftEdgePoint(point) && !isLeftToRight && dom.isVoid(point.node.previousSibling) || dom.isBlock(point.node) && dom.isEmpty(point.node)) { return point; } } // point on block's edge var block = dom.ancestor(point.node, dom.isBlock); var hasRightNode = false; if (!hasRightNode) { var prevPoint = dom.prevPoint(point) || { node: null }; hasRightNode = (dom.isLeftEdgePointOf(point, block) || dom.isVoid(prevPoint.node)) && !isLeftToRight; } var hasLeftNode = false; if (!hasLeftNode) { var _nextPoint = dom.nextPoint(point) || { node: null }; hasLeftNode = (dom.isRightEdgePointOf(point, block) || dom.isVoid(_nextPoint.node)) && isLeftToRight; } if (hasRightNode || hasLeftNode) { // returns point already on visible point if (dom.isVisiblePoint(point)) { return point; } // reverse direction isLeftToRight = !isLeftToRight; } var nextPoint = isLeftToRight ? dom.nextPointUntil(dom.nextPoint(point), dom.isVisiblePoint) : dom.prevPointUntil(dom.prevPoint(point), dom.isVisiblePoint); return nextPoint || point; }; var endPoint = getVisiblePoint(this.getEndPoint(), false); var startPoint = this.isCollapsed() ? endPoint : getVisiblePoint(this.getStartPoint(), true); return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns matched nodes on range * * @param {Function} [pred] - predicate function * @param {Object} [options] * @param {Boolean} [options.includeAncestor] * @param {Boolean} [options.fullyContains] * @return {Node[]} */ }, { key: "nodes", value: function nodes(pred, options) { pred = pred || func.ok; var includeAncestor = options && options.includeAncestor; var fullyContains = options && options.fullyContains; // TODO compare points and sort var startPoint = this.getStartPoint(); var endPoint = this.getEndPoint(); var nodes = []; var leftEdgeNodes = []; dom.walkPoint(startPoint, endPoint, function (point) { if (dom.isEditable(point.node)) { return; } var node; if (fullyContains) { if (dom.isLeftEdgePoint(point)) { leftEdgeNodes.push(point.node); } if (dom.isRightEdgePoint(point) && lists.contains(leftEdgeNodes, point.node)) { node = point.node; } } else if (includeAncestor) { node = dom.ancestor(point.node, pred); } else { node = point.node; } if (node && pred(node)) { nodes.push(node); } }, true); return lists.unique(nodes); } /** * returns commonAncestor of range * @return {Element} - commonAncestor */ }, { key: "commonAncestor", value: function commonAncestor() { return dom.commonAncestor(this.sc, this.ec); } /** * returns expanded range by pred * * @param {Function} pred - predicate function * @return {WrappedRange} */ }, { key: "expand", value: function expand(pred) { var startAncestor = dom.ancestor(this.sc, pred); var endAncestor = dom.ancestor(this.ec, pred); if (!startAncestor && !endAncestor) { return new WrappedRange(this.sc, this.so, this.ec, this.eo); } var boundaryPoints = this.getPoints(); if (startAncestor) { boundaryPoints.sc = startAncestor; boundaryPoints.so = 0; } if (endAncestor) { boundaryPoints.ec = endAncestor; boundaryPoints.eo = dom.nodeLength(endAncestor); } return new WrappedRange(boundaryPoints.sc, boundaryPoints.so, boundaryPoints.ec, boundaryPoints.eo); } /** * @param {Boolean} isCollapseToStart * @return {WrappedRange} */ }, { key: "collapse", value: function collapse(isCollapseToStart) { if (isCollapseToStart) { return new WrappedRange(this.sc, this.so, this.sc, this.so); } else { return new WrappedRange(this.ec, this.eo, this.ec, this.eo); } } /** * splitText on range */ }, { key: "splitText", value: function splitText() { var isSameContainer = this.sc === this.ec; var boundaryPoints = this.getPoints(); if (dom.isText(this.ec) && !dom.isEdgePoint(this.getEndPoint())) { this.ec.splitText(this.eo); } if (dom.isText(this.sc) && !dom.isEdgePoint(this.getStartPoint())) { boundaryPoints.sc = this.sc.splitText(this.so); boundaryPoints.so = 0; if (isSameContainer) { boundaryPoints.ec = boundaryPoints.sc; boundaryPoints.eo = this.eo - this.so; } } return new WrappedRange(boundaryPoints.sc, boundaryPoints.so, boundaryPoints.ec, boundaryPoints.eo); } /** * delete contents on range * @return {WrappedRange} */ }, { key: "deleteContents", value: function deleteContents() { if (this.isCollapsed()) { return this; } var rng = this.splitText(); var nodes = rng.nodes(null, { fullyContains: true }); // find new cursor point var point = dom.prevPointUntil(rng.getStartPoint(), function (point) { return !lists.contains(nodes, point.node); }); var emptyParents = []; external_jQuery_default().each(nodes, function (idx, node) { // find empty parents var parent = node.parentNode; if (point.node !== parent && dom.nodeLength(parent) === 1) { emptyParents.push(parent); } dom.remove(node, false); }); // remove empty parents external_jQuery_default().each(emptyParents, function (idx, node) { dom.remove(node, false); }); return new WrappedRange(point.node, point.offset, point.node, point.offset).normalize(); } /** * makeIsOn: return isOn(pred) function */ }, { key: "makeIsOn", value: function makeIsOn(pred) { return function () { var ancestor = dom.ancestor(this.sc, pred); return !!ancestor && ancestor === dom.ancestor(this.ec, pred); }; } /** * @param {Function} pred * @return {Boolean} */ }, { key: "isLeftEdgeOf", value: function isLeftEdgeOf(pred) { if (!dom.isLeftEdgePoint(this.getStartPoint())) { return false; } var node = dom.ancestor(this.sc, pred); return node && dom.isLeftEdgeOf(this.sc, node); } /** * returns whether range was collapsed or not */ }, { key: "isCollapsed", value: function isCollapsed() { return this.sc === this.ec && this.so === this.eo; } /** * wrap inline nodes which children of body with paragraph * * @return {WrappedRange} */ }, { key: "wrapBodyInlineWithPara", value: function wrapBodyInlineWithPara() { if (dom.isBodyContainer(this.sc) && dom.isEmpty(this.sc)) { this.sc.innerHTML = dom.emptyPara; return new WrappedRange(this.sc.firstChild, 0, this.sc.firstChild, 0); } /** * [workaround] firefox often create range on not visible point. so normalize here. * - firefox: |<p>text</p>| * - chrome: <p>|text|</p> */ var rng = this.normalize(); if (dom.isParaInline(this.sc) || dom.isPara(this.sc)) { return rng; } // find inline top ancestor var topAncestor; if (dom.isInline(rng.sc)) { var ancestors = dom.listAncestor(rng.sc, func.not(dom.isInline)); topAncestor = lists.last(ancestors); if (!dom.isInline(topAncestor)) { topAncestor = ancestors[ancestors.length - 2] || rng.sc.childNodes[rng.so]; } } else { topAncestor = rng.sc.childNodes[rng.so > 0 ? rng.so - 1 : 0]; } if (topAncestor) { // siblings not in paragraph var inlineSiblings = dom.listPrev(topAncestor, dom.isParaInline).reverse(); inlineSiblings = inlineSiblings.concat(dom.listNext(topAncestor.nextSibling, dom.isParaInline)); // wrap with paragraph if (inlineSiblings.length) { var para = dom.wrap(lists.head(inlineSiblings), 'p'); dom.appendChildNodes(para, lists.tail(inlineSiblings)); } } return this.normalize(); } /** * insert node at current cursor * * @param {Node} node * @return {Node} */ }, { key: "insertNode", value: function insertNode(node) { var rng = this; if (dom.isText(node) || dom.isInline(node)) { rng = this.wrapBodyInlineWithPara().deleteContents(); } var info = dom.splitPoint(rng.getStartPoint(), dom.isInline(node)); if (info.rightNode) { info.rightNode.parentNode.insertBefore(node, info.rightNode); if (dom.isEmpty(info.rightNode) && dom.isPara(node)) { info.rightNode.parentNode.removeChild(info.rightNode); } } else { info.container.appendChild(node); } return node; } /** * insert html at current cursor */ }, { key: "pasteHTML", value: function pasteHTML(markup) { markup = external_jQuery_default().trim(markup); var contentsContainer = external_jQuery_default()('<div></div>').html(markup)[0]; var childNodes = lists.from(contentsContainer.childNodes); // const rng = this.wrapBodyInlineWithPara().deleteContents(); var rng = this; var reversed = false; if (rng.so >= 0) { childNodes = childNodes.reverse(); reversed = true; } childNodes = childNodes.map(function (childNode) { return rng.insertNode(childNode); }); if (reversed) { childNodes = childNodes.reverse(); } return childNodes; } /** * returns text in range * * @return {String} */ }, { key: "toString", value: function toString() { var nativeRng = this.nativeRange(); return env.isW3CRangeSupport ? nativeRng.toString() : nativeRng.text; } /** * returns range for word before cursor * * @param {Boolean} [findAfter] - find after cursor, default: false * @return {WrappedRange} */ }, { key: "getWordRange", value: function getWordRange(findAfter) { var endPoint = this.getEndPoint(); if (!dom.isCharPoint(endPoint)) { return this; } var startPoint = dom.prevPointUntil(endPoint, function (point) { return !dom.isCharPoint(point); }); if (findAfter) { endPoint = dom.nextPointUntil(endPoint, function (point) { return !dom.isCharPoint(point); }); } return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns range for words before cursor * * @param {Boolean} [findAfter] - find after cursor, default: false * @return {WrappedRange} */ }, { key: "getWordsRange", value: function getWordsRange(findAfter) { var endPoint = this.getEndPoint(); var isNotTextPoint = function isNotTextPoint(point) { return !dom.isCharPoint(point) && !dom.isSpacePoint(point); }; if (isNotTextPoint(endPoint)) { return this; } var startPoint = dom.prevPointUntil(endPoint, isNotTextPoint); if (findAfter) { endPoint = dom.nextPointUntil(endPoint, isNotTextPoint); } return new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * returns range for words before cursor that match with a Regex * * example: * range: 'hi @Peter Pan' * regex: '/@[a-z ]+/i' * return range: '@Peter Pan' * * @param {RegExp} [regex] * @return {WrappedRange|null} */ }, { key: "getWordsMatchRange", value: function getWordsMatchRange(regex) { var endPoint = this.getEndPoint(); var startPoint = dom.prevPointUntil(endPoint, function (point) { if (!dom.isCharPoint(point) && !dom.isSpacePoint(point)) { return true; } var rng = new WrappedRange(point.node, point.offset, endPoint.node, endPoint.offset); var result = regex.exec(rng.toString()); return result && result.index === 0; }); var rng = new WrappedRange(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); var text = rng.toString(); var result = regex.exec(text); if (result && result[0].length === text.length) { return rng; } else { return null; } } /** * create offsetPath bookmark * * @param {Node} editable */ }, { key: "bookmark", value: function bookmark(editable) { return { s: { path: dom.makeOffsetPath(editable, this.sc), offset: this.so }, e: { path: dom.makeOffsetPath(editable, this.ec), offset: this.eo } }; } /** * create offsetPath bookmark base on paragraph * * @param {Node[]} paras */ }, { key: "paraBookmark", value: function paraBookmark(paras) { return { s: { path: lists.tail(dom.makeOffsetPath(lists.head(paras), this.sc)), offset: this.so }, e: { path: lists.tail(dom.makeOffsetPath(lists.last(paras), this.ec)), offset: this.eo } }; } /** * getClientRects * @return {Rect[]} */ }, { key: "getClientRects", value: function getClientRects() { var nativeRng = this.nativeRange(); return nativeRng.getClientRects(); } }]); return WrappedRange; }(); /** * Data structure * * BoundaryPoint: a point of dom tree * * BoundaryPoints: two boundaryPoints corresponding to the start and the end of the Range * * See to http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Position */ /* harmony default export */ const range = ({ /** * create Range Object From arguments or Browser Selection * * @param {Node} sc - start container * @param {Number} so - start offset * @param {Node} ec - end container * @param {Number} eo - end offset * @return {WrappedRange} */ create: function create(sc, so, ec, eo) { if (arguments.length === 4) { return new WrappedRange(sc, so, ec, eo); } else if (arguments.length === 2) { // collapsed ec = sc; eo = so; return new WrappedRange(sc, so, ec, eo); } else { var wrappedRange = this.createFromSelection(); if (!wrappedRange && arguments.length === 1) { var bodyElement = arguments[0]; if (dom.isEditable(bodyElement)) { bodyElement = bodyElement.lastChild; } return this.createFromBodyElement(bodyElement, dom.emptyPara === arguments[0].innerHTML); } return wrappedRange; } }, createFromBodyElement: function createFromBodyElement(bodyElement) { var isCollapseToStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var wrappedRange = this.createFromNode(bodyElement); return wrappedRange.collapse(isCollapseToStart); }, createFromSelection: function createFromSelection() { var sc, so, ec, eo; if (env.isW3CRangeSupport) { var selection = document.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } else if (dom.isBody(selection.anchorNode)) { // Firefox: returns entire body as range on initialization. // We won't never need it. return null; } var nativeRng = selection.getRangeAt(0); sc = nativeRng.startContainer; so = nativeRng.startOffset; ec = nativeRng.endContainer; eo = nativeRng.endOffset; } else { // IE8: TextRange var textRange = document.selection.createRange(); var textRangeEnd = textRange.duplicate(); textRangeEnd.collapse(false); var textRangeStart = textRange; textRangeStart.collapse(true); var startPoint = textRangeToPoint(textRangeStart, true); var endPoint = textRangeToPoint(textRangeEnd, false); // same visible point case: range was collapsed. if (dom.isText(startPoint.node) && dom.isLeftEdgePoint(startPoint) && dom.isTextNode(endPoint.node) && dom.isRightEdgePoint(endPoint) && endPoint.node.nextSibling === startPoint.node) { startPoint = endPoint; } sc = startPoint.cont; so = startPoint.offset; ec = endPoint.cont; eo = endPoint.offset; } return new WrappedRange(sc, so, ec, eo); }, /** * @method * * create WrappedRange from node * * @param {Node} node * @return {WrappedRange} */ createFromNode: function createFromNode(node) { var sc = node; var so = 0; var ec = node; var eo = dom.nodeLength(ec); // browsers can't target a picture or void node if (dom.isVoid(sc)) { so = dom.listPrev(sc).length - 1; sc = sc.parentNode; } if (dom.isBR(ec)) { eo = dom.listPrev(ec).length - 1; ec = ec.parentNode; } else if (dom.isVoid(ec)) { eo = dom.listPrev(ec).length; ec = ec.parentNode; } return this.create(sc, so, ec, eo); }, /** * create WrappedRange from node after position * * @param {Node} node * @return {WrappedRange} */ createFromNodeBefore: function createFromNodeBefore(node) { return this.createFromNode(node).collapse(true); }, /** * create WrappedRange from node after position * * @param {Node} node * @return {WrappedRange} */ createFromNodeAfter: function createFromNodeAfter(node) { return this.createFromNode(node).collapse(); }, /** * @method * * create WrappedRange from bookmark * * @param {Node} editable * @param {Object} bookmark * @return {WrappedRange} */ createFromBookmark: function createFromBookmark(editable, bookmark) { var sc = dom.fromOffsetPath(editable, bookmark.s.path); var so = bookmark.s.offset; var ec = dom.fromOffsetPath(editable, bookmark.e.path); var eo = bookmark.e.offset; return new WrappedRange(sc, so, ec, eo); }, /** * @method * * create WrappedRange from paraBookmark * * @param {Object} bookmark * @param {Node[]} paras * @return {WrappedRange} */ createFromParaBookmark: function createFromParaBookmark(bookmark, paras) { var so = bookmark.s.offset; var eo = bookmark.e.offset; var sc = dom.fromOffsetPath(lists.head(paras), bookmark.s.path); var ec = dom.fromOffsetPath(lists.last(paras), bookmark.e.path); return new WrappedRange(sc, so, ec, eo); } }); ;// CONCATENATED MODULE: ./src/js/core/key.js var KEY_MAP = { 'BACKSPACE': 8, 'TAB': 9, 'ENTER': 13, 'ESCAPE': 27, 'SPACE': 32, 'DELETE': 46, // Arrow 'LEFT': 37, 'UP': 38, 'RIGHT': 39, 'DOWN': 40, // Number: 0-9 'NUM0': 48, 'NUM1': 49, 'NUM2': 50, 'NUM3': 51, 'NUM4': 52, 'NUM5': 53, 'NUM6': 54, 'NUM7': 55, 'NUM8': 56, // Alphabet: a-z 'B': 66, 'E': 69, 'I': 73, 'J': 74, 'K': 75, 'L': 76, 'R': 82, 'S': 83, 'U': 85, 'V': 86, 'Y': 89, 'Z': 90, 'SLASH': 191, 'LEFTBRACKET': 219, 'BACKSLASH': 220, 'RIGHTBRACKET': 221, // Navigation 'HOME': 36, 'END': 35, 'PAGEUP': 33, 'PAGEDOWN': 34 }; /** * @class core.key * * Object for keycodes. * * @singleton * @alternateClassName key */ /* harmony default export */ const key = ({ /** * @method isEdit * * @param {Number} keyCode * @return {Boolean} */ isEdit: function isEdit(keyCode) { return lists.contains([KEY_MAP.BACKSPACE, KEY_MAP.TAB, KEY_MAP.ENTER, KEY_MAP.SPACE, KEY_MAP.DELETE], keyCode); }, /** * @method isMove * * @param {Number} keyCode * @return {Boolean} */ isMove: function isMove(keyCode) { return lists.contains([KEY_MAP.LEFT, KEY_MAP.UP, KEY_MAP.RIGHT, KEY_MAP.DOWN], keyCode); }, /** * @method isNavigation * * @param {Number} keyCode * @return {Boolean} */ isNavigation: function isNavigation(keyCode) { return lists.contains([KEY_MAP.HOME, KEY_MAP.END, KEY_MAP.PAGEUP, KEY_MAP.PAGEDOWN], keyCode); }, /** * @property {Object} nameFromCode * @property {String} nameFromCode.8 "BACKSPACE" */ nameFromCode: func.invertObject(KEY_MAP), code: KEY_MAP }); ;// CONCATENATED MODULE: ./src/js/core/async.js /** * @method readFileAsDataURL * * read contents of file as representing URL * * @param {File} file * @return {Promise} - then: dataUrl */ function readFileAsDataURL(file) { return external_jQuery_default().Deferred(function (deferred) { external_jQuery_default().extend(new FileReader(), { onload: function onload(e) { var dataURL = e.target.result; deferred.resolve(dataURL); }, onerror: function onerror(err) { deferred.reject(err); } }).readAsDataURL(file); }).promise(); } /** * @method createImage * * create `<image>` from url string * * @param {String} url * @return {Promise} - then: $image */ function createImage(url) { return external_jQuery_default().Deferred(function (deferred) { var $img = external_jQuery_default()('<img>'); $img.one('load', function () { $img.off('error abort'); deferred.resolve($img); }).one('error abort', function () { $img.off('load').detach(); deferred.reject($img); }).css({ display: 'none' }).appendTo(document.body).attr('src', url); }).promise(); } ;// CONCATENATED MODULE: ./src/js/editing/History.js function History_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function History_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function History_createClass(Constructor, protoProps, staticProps) { if (protoProps) History_defineProperties(Constructor.prototype, protoProps); if (staticProps) History_defineProperties(Constructor, staticProps); return Constructor; } var History = /*#__PURE__*/function () { function History(context) { History_classCallCheck(this, History); this.stack = []; this.stackOffset = -1; this.context = context; this.$editable = context.layoutInfo.editable; this.editable = this.$editable[0]; } History_createClass(History, [{ key: "makeSnapshot", value: function makeSnapshot() { var rng = range.create(this.editable); var emptyBookmark = { s: { path: [], offset: 0 }, e: { path: [], offset: 0 } }; return { contents: this.$editable.html(), bookmark: rng && rng.isOnEditable() ? rng.bookmark(this.editable) : emptyBookmark }; } }, { key: "applySnapshot", value: function applySnapshot(snapshot) { if (snapshot.contents !== null) { this.$editable.html(snapshot.contents); } if (snapshot.bookmark !== null) { range.createFromBookmark(this.editable, snapshot.bookmark).select(); } } /** * @method rewind * Rewinds the history stack back to the first snapshot taken. * Leaves the stack intact, so that "Redo" can still be used. */ }, { key: "rewind", value: function rewind() { // Create snap shot if not yet recorded if (this.$editable.html() !== this.stack[this.stackOffset].contents) { this.recordUndo(); } // Return to the first available snapshot. this.stackOffset = 0; // Apply that snapshot. this.applySnapshot(this.stack[this.stackOffset]); } /** * @method commit * Resets history stack, but keeps current editor's content. */ }, { key: "commit", value: function commit() { // Clear the stack. this.stack = []; // Restore stackOffset to its original value. this.stackOffset = -1; // Record our first snapshot (of nothing). this.recordUndo(); } /** * @method reset * Resets the history stack completely; reverting to an empty editor. */ }, { key: "reset", value: function reset() { // Clear the stack. this.stack = []; // Restore stackOffset to its original value. this.stackOffset = -1; // Clear the editable area. this.$editable.html(''); // Record our first snapshot (of nothing). this.recordUndo(); } /** * undo */ }, { key: "undo", value: function undo() { // Create snap shot if not yet recorded if (this.$editable.html() !== this.stack[this.stackOffset].contents) { this.recordUndo(); } if (this.stackOffset > 0) { this.stackOffset--; this.applySnapshot(this.stack[this.stackOffset]); } } /** * redo */ }, { key: "redo", value: function redo() { if (this.stack.length - 1 > this.stackOffset) { this.stackOffset++; this.applySnapshot(this.stack[this.stackOffset]); } } /** * recorded undo */ }, { key: "recordUndo", value: function recordUndo() { this.stackOffset++; // Wash out stack after stackOffset if (this.stack.length > this.stackOffset) { this.stack = this.stack.slice(0, this.stackOffset); } // Create new snapshot and push it to the end this.stack.push(this.makeSnapshot()); // If the stack size reachs to the limit, then slice it if (this.stack.length > this.context.options.historyLimit) { this.stack.shift(); this.stackOffset -= 1; } } }]); return History; }(); ;// CONCATENATED MODULE: ./src/js/editing/Style.js function Style_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Style_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Style_createClass(Constructor, protoProps, staticProps) { if (protoProps) Style_defineProperties(Constructor.prototype, protoProps); if (staticProps) Style_defineProperties(Constructor, staticProps); return Constructor; } var Style = /*#__PURE__*/function () { function Style() { Style_classCallCheck(this, Style); } Style_createClass(Style, [{ key: "jQueryCSS", value: /** * @method jQueryCSS * * [workaround] for old jQuery * passing an array of style properties to .css() * will result in an object of property-value pairs. * (compability with version < 1.9) * * @private * @param {jQuery} $obj * @param {Array} propertyNames - An array of one or more CSS properties. * @return {Object} */ function jQueryCSS($obj, propertyNames) { var result = {}; external_jQuery_default().each(propertyNames, function (idx, propertyName) { result[propertyName] = $obj.css(propertyName); }); return result; } /** * returns style object from node * * @param {jQuery} $node * @return {Object} */ }, { key: "fromNode", value: function fromNode($node) { var properties = ['font-family', 'font-size', 'text-align', 'list-style-type', 'line-height']; var styleInfo = this.jQueryCSS($node, properties) || {}; var fontSize = $node[0].style.fontSize || styleInfo['font-size']; styleInfo['font-size'] = parseInt(fontSize, 10); styleInfo['font-size-unit'] = fontSize.match(/[a-z%]+$/); return styleInfo; } /** * paragraph level style * * @param {WrappedRange} rng * @param {Object} styleInfo */ }, { key: "stylePara", value: function stylePara(rng, styleInfo) { external_jQuery_default().each(rng.nodes(dom.isPara, { includeAncestor: true }), function (idx, para) { external_jQuery_default()(para).css(styleInfo); }); } /** * insert and returns styleNodes on range. * * @param {WrappedRange} rng * @param {Object} [options] - options for styleNodes * @param {String} [options.nodeName] - default: `SPAN` * @param {Boolean} [options.expandClosestSibling] - default: `false` * @param {Boolean} [options.onlyPartialContains] - default: `false` * @return {Node[]} */ }, { key: "styleNodes", value: function styleNodes(rng, options) { rng = rng.splitText(); var nodeName = options && options.nodeName || 'SPAN'; var expandClosestSibling = !!(options && options.expandClosestSibling); var onlyPartialContains = !!(options && options.onlyPartialContains); if (rng.isCollapsed()) { return [rng.insertNode(dom.create(nodeName))]; } var pred = dom.makePredByNodeName(nodeName); var nodes = rng.nodes(dom.isText, { fullyContains: true }).map(function (text) { return dom.singleChildAncestor(text, pred) || dom.wrap(text, nodeName); }); if (expandClosestSibling) { if (onlyPartialContains) { var nodesInRange = rng.nodes(); // compose with partial contains predication pred = func.and(pred, function (node) { return lists.contains(nodesInRange, node); }); } return nodes.map(function (node) { var siblings = dom.withClosestSiblings(node, pred); var head = lists.head(siblings); var tails = lists.tail(siblings); external_jQuery_default().each(tails, function (idx, elem) { dom.appendChildNodes(head, elem.childNodes); dom.remove(elem); }); return lists.head(siblings); }); } else { return nodes; } } /** * get current style on cursor * * @param {WrappedRange} rng * @return {Object} - object contains style properties. */ }, { key: "current", value: function current(rng) { var $cont = external_jQuery_default()(!dom.isElement(rng.sc) ? rng.sc.parentNode : rng.sc); var styleInfo = this.fromNode($cont); // document.queryCommandState for toggle state // [workaround] prevent Firefox nsresult: "0x80004005 (NS_ERROR_FAILURE)" try { styleInfo = external_jQuery_default().extend(styleInfo, { 'font-bold': document.queryCommandState('bold') ? 'bold' : 'normal', 'font-italic': document.queryCommandState('italic') ? 'italic' : 'normal', 'font-underline': document.queryCommandState('underline') ? 'underline' : 'normal', 'font-subscript': document.queryCommandState('subscript') ? 'subscript' : 'normal', 'font-superscript': document.queryCommandState('superscript') ? 'superscript' : 'normal', 'font-strikethrough': document.queryCommandState('strikethrough') ? 'strikethrough' : 'normal', 'font-family': document.queryCommandValue('fontname') || styleInfo['font-family'] }); } catch (e) {// eslint-disable-next-line } // list-style-type to list-style(unordered, ordered) if (!rng.isOnList()) { styleInfo['list-style'] = 'none'; } else { var orderedTypes = ['circle', 'disc', 'disc-leading-zero', 'square']; var isUnordered = orderedTypes.indexOf(styleInfo['list-style-type']) > -1; styleInfo['list-style'] = isUnordered ? 'unordered' : 'ordered'; } var para = dom.ancestor(rng.sc, dom.isPara); if (para && para.style['line-height']) { styleInfo['line-height'] = para.style.lineHeight; } else { var lineHeight = parseInt(styleInfo['line-height'], 10) / parseInt(styleInfo['font-size'], 10); styleInfo['line-height'] = lineHeight.toFixed(1); } styleInfo.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor); styleInfo.ancestors = dom.listAncestor(rng.sc, dom.isEditable); styleInfo.range = rng; return styleInfo; } }]); return Style; }(); ;// CONCATENATED MODULE: ./src/js/editing/Bullet.js function Bullet_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Bullet_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Bullet_createClass(Constructor, protoProps, staticProps) { if (protoProps) Bullet_defineProperties(Constructor.prototype, protoProps); if (staticProps) Bullet_defineProperties(Constructor, staticProps); return Constructor; } var Bullet = /*#__PURE__*/function () { function Bullet() { Bullet_classCallCheck(this, Bullet); } Bullet_createClass(Bullet, [{ key: "insertOrderedList", value: /** * toggle ordered list */ function insertOrderedList(editable) { this.toggleList('OL', editable); } /** * toggle unordered list */ }, { key: "insertUnorderedList", value: function insertUnorderedList(editable) { this.toggleList('UL', editable); } /** * indent */ }, { key: "indent", value: function indent(editable) { var _this = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); if (dom.isLi(head)) { var previousList = _this.findList(head.previousSibling); if (previousList) { paras.map(function (para) { return previousList.appendChild(para); }); } else { _this.wrapList(paras, head.parentNode.nodeName); paras.map(function (para) { return para.parentNode; }).map(function (para) { return _this.appendToPrevious(para); }); } } else { external_jQuery_default().each(paras, function (idx, para) { external_jQuery_default()(para).css('marginLeft', function (idx, val) { return (parseInt(val, 10) || 0) + 25; }); }); } }); rng.select(); } /** * outdent */ }, { key: "outdent", value: function outdent(editable) { var _this2 = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); if (dom.isLi(head)) { _this2.releaseList([paras]); } else { external_jQuery_default().each(paras, function (idx, para) { external_jQuery_default()(para).css('marginLeft', function (idx, val) { val = parseInt(val, 10) || 0; return val > 25 ? val - 25 : ''; }); }); } }); rng.select(); } /** * toggle list * * @param {String} listName - OL or UL */ }, { key: "toggleList", value: function toggleList(listName, editable) { var _this3 = this; var rng = range.create(editable).wrapBodyInlineWithPara(); var paras = rng.nodes(dom.isPara, { includeAncestor: true }); var bookmark = rng.paraBookmark(paras); var clustereds = lists.clusterBy(paras, func.peq2('parentNode')); // paragraph to list if (lists.find(paras, dom.isPurePara)) { var wrappedParas = []; external_jQuery_default().each(clustereds, function (idx, paras) { wrappedParas = wrappedParas.concat(_this3.wrapList(paras, listName)); }); paras = wrappedParas; // list to paragraph or change list style } else { var diffLists = rng.nodes(dom.isList, { includeAncestor: true }).filter(function (listNode) { return !external_jQuery_default().nodeName(listNode, listName); }); if (diffLists.length) { external_jQuery_default().each(diffLists, function (idx, listNode) { dom.replace(listNode, listName); }); } else { paras = this.releaseList(clustereds, true); } } range.createFromParaBookmark(bookmark, paras).select(); } /** * @param {Node[]} paras * @param {String} listName * @return {Node[]} */ }, { key: "wrapList", value: function wrapList(paras, listName) { var head = lists.head(paras); var last = lists.last(paras); var prevList = dom.isList(head.previousSibling) && head.previousSibling; var nextList = dom.isList(last.nextSibling) && last.nextSibling; var listNode = prevList || dom.insertAfter(dom.create(listName || 'UL'), last); // P to LI paras = paras.map(function (para) { return dom.isPurePara(para) ? dom.replace(para, 'LI') : para; }); // append to list(<ul>, <ol>) dom.appendChildNodes(listNode, paras); if (nextList) { dom.appendChildNodes(listNode, lists.from(nextList.childNodes)); dom.remove(nextList); } return paras; } /** * @method releaseList * * @param {Array[]} clustereds * @param {Boolean} isEscapseToBody * @return {Node[]} */ }, { key: "releaseList", value: function releaseList(clustereds, isEscapseToBody) { var _this4 = this; var releasedParas = []; external_jQuery_default().each(clustereds, function (idx, paras) { var head = lists.head(paras); var last = lists.last(paras); var headList = isEscapseToBody ? dom.lastAncestor(head, dom.isList) : head.parentNode; var parentItem = headList.parentNode; if (headList.parentNode.nodeName === 'LI') { paras.map(function (para) { var newList = _this4.findNextSiblings(para); if (parentItem.nextSibling) { parentItem.parentNode.insertBefore(para, parentItem.nextSibling); } else { parentItem.parentNode.appendChild(para); } if (newList.length) { _this4.wrapList(newList, headList.nodeName); para.appendChild(newList[0].parentNode); } }); if (headList.children.length === 0) { parentItem.removeChild(headList); } if (parentItem.childNodes.length === 0) { parentItem.parentNode.removeChild(parentItem); } } else { var lastList = headList.childNodes.length > 1 ? dom.splitTree(headList, { node: last.parentNode, offset: dom.position(last) + 1 }, { isSkipPaddingBlankHTML: true }) : null; var middleList = dom.splitTree(headList, { node: head.parentNode, offset: dom.position(head) }, { isSkipPaddingBlankHTML: true }); paras = isEscapseToBody ? dom.listDescendant(middleList, dom.isLi) : lists.from(middleList.childNodes).filter(dom.isLi); // LI to P if (isEscapseToBody || !dom.isList(headList.parentNode)) { paras = paras.map(function (para) { return dom.replace(para, 'P'); }); } external_jQuery_default().each(lists.from(paras).reverse(), function (idx, para) { dom.insertAfter(para, headList); }); // remove empty lists var rootLists = lists.compact([headList, middleList, lastList]); external_jQuery_default().each(rootLists, function (idx, rootList) { var listNodes = [rootList].concat(dom.listDescendant(rootList, dom.isList)); external_jQuery_default().each(listNodes.reverse(), function (idx, listNode) { if (!dom.nodeLength(listNode)) { dom.remove(listNode, true); } }); }); } releasedParas = releasedParas.concat(paras); }); return releasedParas; } /** * @method appendToPrevious * * Appends list to previous list item, if * none exist it wraps the list in a new list item. * * @param {HTMLNode} ListItem * @return {HTMLNode} */ }, { key: "appendToPrevious", value: function appendToPrevious(node) { return node.previousSibling ? dom.appendChildNodes(node.previousSibling, [node]) : this.wrapList([node], 'LI'); } /** * @method findList * * Finds an existing list in list item * * @param {HTMLNode} ListItem * @return {Array[]} */ }, { key: "findList", value: function findList(node) { return node ? lists.find(node.children, function (child) { return ['OL', 'UL'].indexOf(child.nodeName) > -1; }) : null; } /** * @method findNextSiblings * * Finds all list item siblings that follow it * * @param {HTMLNode} ListItem * @return {HTMLNode} */ }, { key: "findNextSiblings", value: function findNextSiblings(node) { var siblings = []; while (node.nextSibling) { siblings.push(node.nextSibling); node = node.nextSibling; } return siblings; } }]); return Bullet; }(); ;// CONCATENATED MODULE: ./src/js/editing/Typing.js function Typing_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Typing_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Typing_createClass(Constructor, protoProps, staticProps) { if (protoProps) Typing_defineProperties(Constructor.prototype, protoProps); if (staticProps) Typing_defineProperties(Constructor, staticProps); return Constructor; } /** * @class editing.Typing * * Typing * */ var Typing = /*#__PURE__*/function () { function Typing(context) { Typing_classCallCheck(this, Typing); // a Bullet instance to toggle lists off this.bullet = new Bullet(); this.options = context.options; } /** * insert tab * * @param {WrappedRange} rng * @param {Number} tabsize */ Typing_createClass(Typing, [{ key: "insertTab", value: function insertTab(rng, tabsize) { var tab = dom.createText(new Array(tabsize + 1).join(dom.NBSP_CHAR)); rng = rng.deleteContents(); rng.insertNode(tab, true); rng = range.create(tab, tabsize); rng.select(); } /** * insert paragraph * * @param {jQuery} $editable * @param {WrappedRange} rng Can be used in unit tests to "mock" the range * * blockquoteBreakingLevel * 0 - No break, the new paragraph remains inside the quote * 1 - Break the first blockquote in the ancestors list * 2 - Break all blockquotes, so that the new paragraph is not quoted (this is the default) */ }, { key: "insertParagraph", value: function insertParagraph(editable, rng) { rng = rng || range.create(editable); // deleteContents on range. rng = rng.deleteContents(); // Wrap range if it needs to be wrapped by paragraph rng = rng.wrapBodyInlineWithPara(); // finding paragraph var splitRoot = dom.ancestor(rng.sc, dom.isPara); var nextPara; // on paragraph: split paragraph if (splitRoot) { // if it is an empty line with li if (dom.isLi(splitRoot) && (dom.isEmpty(splitRoot) || dom.deepestChildIsEmpty(splitRoot))) { // toggle UL/OL and escape this.bullet.toggleList(splitRoot.parentNode.nodeName); return; } else { var blockquote = null; if (this.options.blockquoteBreakingLevel === 1) { blockquote = dom.ancestor(splitRoot, dom.isBlockquote); } else if (this.options.blockquoteBreakingLevel === 2) { blockquote = dom.lastAncestor(splitRoot, dom.isBlockquote); } if (blockquote) { // We're inside a blockquote and options ask us to break it nextPara = external_jQuery_default()(dom.emptyPara)[0]; // If the split is right before a <br>, remove it so that there's no "empty line" // after the split in the new blockquote created if (dom.isRightEdgePoint(rng.getStartPoint()) && dom.isBR(rng.sc.nextSibling)) { external_jQuery_default()(rng.sc.nextSibling).remove(); } var split = dom.splitTree(blockquote, rng.getStartPoint(), { isDiscardEmptySplits: true }); if (split) { split.parentNode.insertBefore(nextPara, split); } else { dom.insertAfter(nextPara, blockquote); // There's no split if we were at the end of the blockquote } } else { nextPara = dom.splitTree(splitRoot, rng.getStartPoint()); // not a blockquote, just insert the paragraph var emptyAnchors = dom.listDescendant(splitRoot, dom.isEmptyAnchor); emptyAnchors = emptyAnchors.concat(dom.listDescendant(nextPara, dom.isEmptyAnchor)); external_jQuery_default().each(emptyAnchors, function (idx, anchor) { dom.remove(anchor); }); // replace empty heading, pre or custom-made styleTag with P tag if ((dom.isHeading(nextPara) || dom.isPre(nextPara) || dom.isCustomStyleTag(nextPara)) && dom.isEmpty(nextPara)) { nextPara = dom.replace(nextPara, 'p'); } } } // no paragraph: insert empty paragraph } else { var next = rng.sc.childNodes[rng.so]; nextPara = external_jQuery_default()(dom.emptyPara)[0]; if (next) { rng.sc.insertBefore(nextPara, next); } else { rng.sc.appendChild(nextPara); } } range.create(nextPara, 0).normalize().select().scrollIntoView(editable); } }]); return Typing; }(); ;// CONCATENATED MODULE: ./src/js/editing/Table.js function Table_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Table_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Table_createClass(Constructor, protoProps, staticProps) { if (protoProps) Table_defineProperties(Constructor.prototype, protoProps); if (staticProps) Table_defineProperties(Constructor, staticProps); return Constructor; } /** * @class Create a virtual table to create what actions to do in change. * @param {object} startPoint Cell selected to apply change. * @param {enum} where Where change will be applied Row or Col. Use enum: TableResultAction.where * @param {enum} action Action to be applied. Use enum: TableResultAction.requestAction * @param {object} domTable Dom element of table to make changes. */ var TableResultAction = function TableResultAction(startPoint, where, action, domTable) { var _startPoint = { 'colPos': 0, 'rowPos': 0 }; var _virtualTable = []; var _actionCellList = []; /// /////////////////////////////////////////// // Private functions /// /////////////////////////////////////////// /** * Set the startPoint of action. */ function setStartPoint() { if (!startPoint || !startPoint.tagName || startPoint.tagName.toLowerCase() !== 'td' && startPoint.tagName.toLowerCase() !== 'th') { // Impossible to identify start Cell point return; } _startPoint.colPos = startPoint.cellIndex; if (!startPoint.parentElement || !startPoint.parentElement.tagName || startPoint.parentElement.tagName.toLowerCase() !== 'tr') { // Impossible to identify start Row point return; } _startPoint.rowPos = startPoint.parentElement.rowIndex; } /** * Define virtual table position info object. * * @param {int} rowIndex Index position in line of virtual table. * @param {int} cellIndex Index position in column of virtual table. * @param {object} baseRow Row affected by this position. * @param {object} baseCell Cell affected by this position. * @param {bool} isSpan Inform if it is an span cell/row. */ function setVirtualTablePosition(rowIndex, cellIndex, baseRow, baseCell, isRowSpan, isColSpan, isVirtualCell) { var objPosition = { 'baseRow': baseRow, 'baseCell': baseCell, 'isRowSpan': isRowSpan, 'isColSpan': isColSpan, 'isVirtual': isVirtualCell }; if (!_virtualTable[rowIndex]) { _virtualTable[rowIndex] = []; } _virtualTable[rowIndex][cellIndex] = objPosition; } /** * Create action cell object. * * @param {object} virtualTableCellObj Object of specific position on virtual table. * @param {enum} resultAction Action to be applied in that item. */ function getActionCell(virtualTableCellObj, resultAction, virtualRowPosition, virtualColPosition) { return { 'baseCell': virtualTableCellObj.baseCell, 'action': resultAction, 'virtualTable': { 'rowIndex': virtualRowPosition, 'cellIndex': virtualColPosition } }; } /** * Recover free index of row to append Cell. * * @param {int} rowIndex Index of row to find free space. * @param {int} cellIndex Index of cell to find free space in table. */ function recoverCellIndex(rowIndex, cellIndex) { if (!_virtualTable[rowIndex]) { return cellIndex; } if (!_virtualTable[rowIndex][cellIndex]) { return cellIndex; } var newCellIndex = cellIndex; while (_virtualTable[rowIndex][newCellIndex]) { newCellIndex++; if (!_virtualTable[rowIndex][newCellIndex]) { return newCellIndex; } } } /** * Recover info about row and cell and add information to virtual table. * * @param {object} row Row to recover information. * @param {object} cell Cell to recover information. */ function addCellInfoToVirtual(row, cell) { var cellIndex = recoverCellIndex(row.rowIndex, cell.cellIndex); var cellHasColspan = cell.colSpan > 1; var cellHasRowspan = cell.rowSpan > 1; var isThisSelectedCell = row.rowIndex === _startPoint.rowPos && cell.cellIndex === _startPoint.colPos; setVirtualTablePosition(row.rowIndex, cellIndex, row, cell, cellHasRowspan, cellHasColspan, false); // Add span rows to virtual Table. var rowspanNumber = cell.attributes.rowSpan ? parseInt(cell.attributes.rowSpan.value, 10) : 0; if (rowspanNumber > 1) { for (var rp = 1; rp < rowspanNumber; rp++) { var rowspanIndex = row.rowIndex + rp; adjustStartPoint(rowspanIndex, cellIndex, cell, isThisSelectedCell); setVirtualTablePosition(rowspanIndex, cellIndex, row, cell, true, cellHasColspan, true); } } // Add span cols to virtual table. var colspanNumber = cell.attributes.colSpan ? parseInt(cell.attributes.colSpan.value, 10) : 0; if (colspanNumber > 1) { for (var cp = 1; cp < colspanNumber; cp++) { var cellspanIndex = recoverCellIndex(row.rowIndex, cellIndex + cp); adjustStartPoint(row.rowIndex, cellspanIndex, cell, isThisSelectedCell); setVirtualTablePosition(row.rowIndex, cellspanIndex, row, cell, cellHasRowspan, true, true); } } } /** * Process validation and adjust of start point if needed * * @param {int} rowIndex * @param {int} cellIndex * @param {object} cell * @param {bool} isSelectedCell */ function adjustStartPoint(rowIndex, cellIndex, cell, isSelectedCell) { if (rowIndex === _startPoint.rowPos && _startPoint.colPos >= cell.cellIndex && cell.cellIndex <= cellIndex && !isSelectedCell) { _startPoint.colPos++; } } /** * Create virtual table of cells with all cells, including span cells. */ function createVirtualTable() { var rows = domTable.rows; for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) { var cells = rows[rowIndex].cells; for (var cellIndex = 0; cellIndex < cells.length; cellIndex++) { addCellInfoToVirtual(rows[rowIndex], cells[cellIndex]); } } } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getDeleteResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; case TableResultAction.where.Row: if (!cell.isVirtual && cell.isRowSpan) { return TableResultAction.resultAction.AddCell; } else if (cell.isRowSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; } return TableResultAction.resultAction.RemoveCell; } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getAddResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isRowSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; case TableResultAction.where.Row: if (cell.isRowSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isColSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; } return TableResultAction.resultAction.AddCell; } function init() { setStartPoint(); createVirtualTable(); } /// /////////////////////////////////////////// // Public functions /// /////////////////////////////////////////// /** * Recover array os what to do in table. */ this.getActionList = function () { var fixedRow = where === TableResultAction.where.Row ? _startPoint.rowPos : -1; var fixedCol = where === TableResultAction.where.Column ? _startPoint.colPos : -1; var actualPosition = 0; var canContinue = true; while (canContinue) { var rowPosition = fixedRow >= 0 ? fixedRow : actualPosition; var colPosition = fixedCol >= 0 ? fixedCol : actualPosition; var row = _virtualTable[rowPosition]; if (!row) { canContinue = false; return _actionCellList; } var cell = row[colPosition]; if (!cell) { canContinue = false; return _actionCellList; } // Define action to be applied in this cell var resultAction = TableResultAction.resultAction.Ignore; switch (action) { case TableResultAction.requestAction.Add: resultAction = getAddResultActionToCell(cell); break; case TableResultAction.requestAction.Delete: resultAction = getDeleteResultActionToCell(cell); break; } _actionCellList.push(getActionCell(cell, resultAction, rowPosition, colPosition)); actualPosition++; } return _actionCellList; }; init(); }; /** * * Where action occours enum. */ TableResultAction.where = { 'Row': 0, 'Column': 1 }; /** * * Requested action to apply enum. */ TableResultAction.requestAction = { 'Add': 0, 'Delete': 1 }; /** * * Result action to be executed enum. */ TableResultAction.resultAction = { 'Ignore': 0, 'SubtractSpanCount': 1, 'RemoveCell': 2, 'AddCell': 3, 'SumSpanCount': 4 }; /** * * @class editing.Table * * Table * */ var Table = /*#__PURE__*/function () { function Table() { Table_classCallCheck(this, Table); } Table_createClass(Table, [{ key: "tab", value: /** * handle tab key * * @param {WrappedRange} rng * @param {Boolean} isShift */ function tab(rng, isShift) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var table = dom.ancestor(cell, dom.isTable); var cells = dom.listDescendant(table, dom.isCell); var nextCell = lists[isShift ? 'prev' : 'next'](cells, cell); if (nextCell) { range.create(nextCell, 0).select(); } } /** * Add a new row * * @param {WrappedRange} rng * @param {String} position (top/bottom) * @return {Node} */ }, { key: "addRow", value: function addRow(rng, position) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var currentTr = external_jQuery_default()(cell).closest('tr'); var trAttributes = this.recoverAttributes(currentTr); var html = external_jQuery_default()('<tr' + trAttributes + '></tr>'); var vTable = new TableResultAction(cell, TableResultAction.where.Row, TableResultAction.requestAction.Add, external_jQuery_default()(currentTr).closest('table')[0]); var actions = vTable.getActionList(); for (var idCell = 0; idCell < actions.length; idCell++) { var currentCell = actions[idCell]; var tdAttributes = this.recoverAttributes(currentCell.baseCell); switch (currentCell.action) { case TableResultAction.resultAction.AddCell: html.append('<td' + tdAttributes + '>' + dom.blank + '</td>'); break; case TableResultAction.resultAction.SumSpanCount: { if (position === 'top') { var baseCellTr = currentCell.baseCell.parent; var isTopFromRowSpan = (!baseCellTr ? 0 : currentCell.baseCell.closest('tr').rowIndex) <= currentTr[0].rowIndex; if (isTopFromRowSpan) { var newTd = external_jQuery_default()('<div></div>').append(external_jQuery_default()('<td' + tdAttributes + '>' + dom.blank + '</td>').removeAttr('rowspan')).html(); html.append(newTd); break; } } var rowspanNumber = parseInt(currentCell.baseCell.rowSpan, 10); rowspanNumber++; currentCell.baseCell.setAttribute('rowSpan', rowspanNumber); } break; } } if (position === 'top') { currentTr.before(html); } else { var cellHasRowspan = cell.rowSpan > 1; if (cellHasRowspan) { var lastTrIndex = currentTr[0].rowIndex + (cell.rowSpan - 2); external_jQuery_default()(external_jQuery_default()(currentTr).parent().find('tr')[lastTrIndex]).after(external_jQuery_default()(html)); return; } currentTr.after(html); } } /** * Add a new col * * @param {WrappedRange} rng * @param {String} position (left/right) * @return {Node} */ }, { key: "addCol", value: function addCol(rng, position) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var rowsGroup = external_jQuery_default()(row).siblings(); rowsGroup.push(row); var vTable = new TableResultAction(cell, TableResultAction.where.Column, TableResultAction.requestAction.Add, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { var currentCell = actions[actionIndex]; var tdAttributes = this.recoverAttributes(currentCell.baseCell); switch (currentCell.action) { case TableResultAction.resultAction.AddCell: if (position === 'right') { external_jQuery_default()(currentCell.baseCell).after('<td' + tdAttributes + '>' + dom.blank + '</td>'); } else { external_jQuery_default()(currentCell.baseCell).before('<td' + tdAttributes + '>' + dom.blank + '</td>'); } break; case TableResultAction.resultAction.SumSpanCount: if (position === 'right') { var colspanNumber = parseInt(currentCell.baseCell.colSpan, 10); colspanNumber++; currentCell.baseCell.setAttribute('colSpan', colspanNumber); } else { external_jQuery_default()(currentCell.baseCell).before('<td' + tdAttributes + '>' + dom.blank + '</td>'); } break; } } } /* * Copy attributes from element. * * @param {object} Element to recover attributes. * @return {string} Copied string elements. */ }, { key: "recoverAttributes", value: function recoverAttributes(el) { var resultStr = ''; if (!el) { return resultStr; } var attrList = el.attributes || []; for (var i = 0; i < attrList.length; i++) { if (attrList[i].name.toLowerCase() === 'id') { continue; } if (attrList[i].specified) { resultStr += ' ' + attrList[i].name + '=\'' + attrList[i].value + '\''; } } return resultStr; } /** * Delete current row * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteRow", value: function deleteRow(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var cellPos = row.children('td, th').index(external_jQuery_default()(cell)); var rowPos = row[0].rowIndex; var vTable = new TableResultAction(cell, TableResultAction.where.Row, TableResultAction.requestAction.Delete, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { if (!actions[actionIndex]) { continue; } var baseCell = actions[actionIndex].baseCell; var virtualPosition = actions[actionIndex].virtualTable; var hasRowspan = baseCell.rowSpan && baseCell.rowSpan > 1; var rowspanNumber = hasRowspan ? parseInt(baseCell.rowSpan, 10) : 0; switch (actions[actionIndex].action) { case TableResultAction.resultAction.Ignore: continue; case TableResultAction.resultAction.AddCell: { var nextRow = row.next('tr')[0]; if (!nextRow) { continue; } var cloneRow = row[0].cells[cellPos]; if (hasRowspan) { if (rowspanNumber > 2) { rowspanNumber--; nextRow.insertBefore(cloneRow, nextRow.cells[cellPos]); nextRow.cells[cellPos].setAttribute('rowSpan', rowspanNumber); nextRow.cells[cellPos].innerHTML = ''; } else if (rowspanNumber === 2) { nextRow.insertBefore(cloneRow, nextRow.cells[cellPos]); nextRow.cells[cellPos].removeAttribute('rowSpan'); nextRow.cells[cellPos].innerHTML = ''; } } } continue; case TableResultAction.resultAction.SubtractSpanCount: if (hasRowspan) { if (rowspanNumber > 2) { rowspanNumber--; baseCell.setAttribute('rowSpan', rowspanNumber); if (virtualPosition.rowIndex !== rowPos && baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } else if (rowspanNumber === 2) { baseCell.removeAttribute('rowSpan'); if (virtualPosition.rowIndex !== rowPos && baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } } continue; case TableResultAction.resultAction.RemoveCell: // Do not need remove cell because row will be deleted. continue; } } row.remove(); } /** * Delete current col * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteCol", value: function deleteCol(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); var row = external_jQuery_default()(cell).closest('tr'); var cellPos = row.children('td, th').index(external_jQuery_default()(cell)); var vTable = new TableResultAction(cell, TableResultAction.where.Column, TableResultAction.requestAction.Delete, external_jQuery_default()(row).closest('table')[0]); var actions = vTable.getActionList(); for (var actionIndex = 0; actionIndex < actions.length; actionIndex++) { if (!actions[actionIndex]) { continue; } switch (actions[actionIndex].action) { case TableResultAction.resultAction.Ignore: continue; case TableResultAction.resultAction.SubtractSpanCount: { var baseCell = actions[actionIndex].baseCell; var hasColspan = baseCell.colSpan && baseCell.colSpan > 1; if (hasColspan) { var colspanNumber = baseCell.colSpan ? parseInt(baseCell.colSpan, 10) : 0; if (colspanNumber > 2) { colspanNumber--; baseCell.setAttribute('colSpan', colspanNumber); if (baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } else if (colspanNumber === 2) { baseCell.removeAttribute('colSpan'); if (baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } } } continue; case TableResultAction.resultAction.RemoveCell: dom.remove(actions[actionIndex].baseCell, true); continue; } } } /** * create empty table element * * @param {Number} rowCount * @param {Number} colCount * @return {Node} */ }, { key: "createTable", value: function createTable(colCount, rowCount, options) { var tds = []; var tdHTML; for (var idxCol = 0; idxCol < colCount; idxCol++) { tds.push('<td>' + dom.blank + '</td>'); } tdHTML = tds.join(''); var trs = []; var trHTML; for (var idxRow = 0; idxRow < rowCount; idxRow++) { trs.push('<tr>' + tdHTML + '</tr>'); } trHTML = trs.join(''); var $table = external_jQuery_default()('<table>' + trHTML + '</table>'); if (options && options.tableClassName) { $table.addClass(options.tableClassName); } return $table[0]; } /** * Delete current table * * @param {WrappedRange} rng * @return {Node} */ }, { key: "deleteTable", value: function deleteTable(rng) { var cell = dom.ancestor(rng.commonAncestor(), dom.isCell); external_jQuery_default()(cell).closest('table').remove(); } }]); return Table; }(); ;// CONCATENATED MODULE: ./src/js/module/Editor.js function Editor_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Editor_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Editor_createClass(Constructor, protoProps, staticProps) { if (protoProps) Editor_defineProperties(Constructor.prototype, protoProps); if (staticProps) Editor_defineProperties(Constructor, staticProps); return Constructor; } var KEY_BOGUS = 'bogus'; /** * @class Editor */ var Editor = /*#__PURE__*/function () { function Editor(context) { var _this = this; Editor_classCallCheck(this, Editor); this.context = context; this.$note = context.layoutInfo.note; this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.options = context.options; this.lang = this.options.langInfo; this.editable = this.$editable[0]; this.lastRange = null; this.snapshot = null; this.style = new Style(); this.table = new Table(); this.typing = new Typing(context); this.bullet = new Bullet(); this.history = new History(context); this.context.memo('help.escape', this.lang.help.escape); this.context.memo('help.undo', this.lang.help.undo); this.context.memo('help.redo', this.lang.help.redo); this.context.memo('help.tab', this.lang.help.tab); this.context.memo('help.untab', this.lang.help.untab); this.context.memo('help.insertParagraph', this.lang.help.insertParagraph); this.context.memo('help.insertOrderedList', this.lang.help.insertOrderedList); this.context.memo('help.insertUnorderedList', this.lang.help.insertUnorderedList); this.context.memo('help.indent', this.lang.help.indent); this.context.memo('help.outdent', this.lang.help.outdent); this.context.memo('help.formatPara', this.lang.help.formatPara); this.context.memo('help.insertHorizontalRule', this.lang.help.insertHorizontalRule); this.context.memo('help.fontName', this.lang.help.fontName); // native commands(with execCommand), generate function for execCommand var commands = ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull', 'formatBlock', 'removeFormat', 'backColor']; for (var idx = 0, len = commands.length; idx < len; idx++) { this[commands[idx]] = function (sCmd) { return function (value) { _this.beforeCommand(); document.execCommand(sCmd, false, value); _this.afterCommand(true); }; }(commands[idx]); this.context.memo('help.' + commands[idx], this.lang.help[commands[idx]]); } this.fontName = this.wrapCommand(function (value) { return _this.fontStyling('font-family', env.validFontName(value)); }); this.fontSize = this.wrapCommand(function (value) { var unit = _this.currentStyle()['font-size-unit']; return _this.fontStyling('font-size', value + unit); }); this.fontSizeUnit = this.wrapCommand(function (value) { var size = _this.currentStyle()['font-size']; return _this.fontStyling('font-size', size + value); }); for (var _idx = 1; _idx <= 6; _idx++) { this['formatH' + _idx] = function (idx) { return function () { _this.formatBlock('H' + idx); }; }(_idx); this.context.memo('help.formatH' + _idx, this.lang.help['formatH' + _idx]); } this.insertParagraph = this.wrapCommand(function () { _this.typing.insertParagraph(_this.editable); }); this.insertOrderedList = this.wrapCommand(function () { _this.bullet.insertOrderedList(_this.editable); }); this.insertUnorderedList = this.wrapCommand(function () { _this.bullet.insertUnorderedList(_this.editable); }); this.indent = this.wrapCommand(function () { _this.bullet.indent(_this.editable); }); this.outdent = this.wrapCommand(function () { _this.bullet.outdent(_this.editable); }); /** * insertNode * insert node * @param {Node} node */ this.insertNode = this.wrapCommand(function (node) { if (_this.isLimited(external_jQuery_default()(node).text().length)) { return; } var rng = _this.getLastRange(); rng.insertNode(node); _this.setLastRange(range.createFromNodeAfter(node).select()); }); /** * insert text * @param {String} text */ this.insertText = this.wrapCommand(function (text) { if (_this.isLimited(text.length)) { return; } var rng = _this.getLastRange(); var textNode = rng.insertNode(dom.createText(text)); _this.setLastRange(range.create(textNode, dom.nodeLength(textNode)).select()); }); /** * paste HTML * @param {String} markup */ this.pasteHTML = this.wrapCommand(function (markup) { if (_this.isLimited(markup.length)) { return; } markup = _this.context.invoke('codeview.purify', markup); var contents = _this.getLastRange().pasteHTML(markup); _this.setLastRange(range.createFromNodeAfter(lists.last(contents)).select()); }); /** * formatBlock * * @param {String} tagName */ this.formatBlock = this.wrapCommand(function (tagName, $target) { var onApplyCustomStyle = _this.options.callbacks.onApplyCustomStyle; if (onApplyCustomStyle) { onApplyCustomStyle.call(_this, $target, _this.context, _this.onFormatBlock); } else { _this.onFormatBlock(tagName, $target); } }); /** * insert horizontal rule */ this.insertHorizontalRule = this.wrapCommand(function () { var hrNode = _this.getLastRange().insertNode(dom.create('HR')); if (hrNode.nextSibling) { _this.setLastRange(range.create(hrNode.nextSibling, 0).normalize().select()); } }); /** * lineHeight * @param {String} value */ this.lineHeight = this.wrapCommand(function (value) { _this.style.stylePara(_this.getLastRange(), { lineHeight: value }); }); /** * create link (command) * * @param {Object} linkInfo */ this.createLink = this.wrapCommand(function (linkInfo) { var linkUrl = linkInfo.url; var linkText = linkInfo.text; var isNewWindow = linkInfo.isNewWindow; var checkProtocol = linkInfo.checkProtocol; var rng = linkInfo.range || _this.getLastRange(); var additionalTextLength = linkText.length - rng.toString().length; if (additionalTextLength > 0 && _this.isLimited(additionalTextLength)) { return; } var isTextChanged = rng.toString() !== linkText; // handle spaced urls from input if (typeof linkUrl === 'string') { linkUrl = linkUrl.trim(); } if (_this.options.onCreateLink) { linkUrl = _this.options.onCreateLink(linkUrl); } else if (checkProtocol) { // if url doesn't have any protocol and not even a relative or a label, use http:// as default linkUrl = /^([A-Za-z][A-Za-z0-9+-.]*\:|#|\/)/.test(linkUrl) ? linkUrl : _this.options.defaultProtocol + linkUrl; } var anchors = []; if (isTextChanged) { rng = rng.deleteContents(); var anchor = rng.insertNode(external_jQuery_default()('<A>' + linkText + '</A>')[0]); anchors.push(anchor); } else { anchors = _this.style.styleNodes(rng, { nodeName: 'A', expandClosestSibling: true, onlyPartialContains: true }); } external_jQuery_default().each(anchors, function (idx, anchor) { external_jQuery_default()(anchor).attr('href', linkUrl); if (isNewWindow) { external_jQuery_default()(anchor).attr('target', '_blank'); } else { external_jQuery_default()(anchor).removeAttr('target'); } }); _this.setLastRange(_this.createRangeFromList(anchors).select()); }); /** * setting color * * @param {Object} sObjColor color code * @param {String} sObjColor.foreColor foreground color * @param {String} sObjColor.backColor background color */ this.color = this.wrapCommand(function (colorInfo) { var foreColor = colorInfo.foreColor; var backColor = colorInfo.backColor; if (foreColor) { document.execCommand('foreColor', false, foreColor); } if (backColor) { document.execCommand('backColor', false, backColor); } }); /** * Set foreground color * * @param {String} colorCode foreground color code */ this.foreColor = this.wrapCommand(function (colorInfo) { document.execCommand('foreColor', false, colorInfo); }); /** * insert Table * * @param {String} dimension of table (ex : "5x5") */ this.insertTable = this.wrapCommand(function (dim) { var dimension = dim.split('x'); var rng = _this.getLastRange().deleteContents(); rng.insertNode(_this.table.createTable(dimension[0], dimension[1], _this.options)); }); /** * remove media object and Figure Elements if media object is img with Figure. */ this.removeMedia = this.wrapCommand(function () { var $target = external_jQuery_default()(_this.restoreTarget()).parent(); if ($target.closest('figure').length) { $target.closest('figure').remove(); } else { $target = external_jQuery_default()(_this.restoreTarget()).detach(); } _this.context.triggerEvent('media.delete', $target, _this.$editable); }); /** * float me * * @param {String} value */ this.floatMe = this.wrapCommand(function (value) { var $target = external_jQuery_default()(_this.restoreTarget()); $target.toggleClass('note-float-left', value === 'left'); $target.toggleClass('note-float-right', value === 'right'); $target.css('float', value === 'none' ? '' : value); }); /** * resize overlay element * @param {String} value */ this.resize = this.wrapCommand(function (value) { var $target = external_jQuery_default()(_this.restoreTarget()); value = parseFloat(value); if (value === 0) { $target.css('width', ''); } else { $target.css({ width: value * 100 + '%', height: '' }); } }); } Editor_createClass(Editor, [{ key: "initialize", value: function initialize() { var _this2 = this; // bind custom events this.$editable.on('keydown', function (event) { if (event.keyCode === key.code.ENTER) { _this2.context.triggerEvent('enter', event); } _this2.context.triggerEvent('keydown', event); // keep a snapshot to limit text on input event _this2.snapshot = _this2.history.makeSnapshot(); _this2.hasKeyShortCut = false; if (!event.isDefaultPrevented()) { if (_this2.options.shortcuts) { _this2.hasKeyShortCut = _this2.handleKeyMap(event); } else { _this2.preventDefaultEditableShortCuts(event); } } if (_this2.isLimited(1, event)) { var lastRange = _this2.getLastRange(); if (lastRange.eo - lastRange.so === 0) { return false; } } _this2.setLastRange(); // record undo in the key event except keyMap. if (_this2.options.recordEveryKeystroke) { if (_this2.hasKeyShortCut === false) { _this2.history.recordUndo(); } } }).on('keyup', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('keyup', event); }).on('focus', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('focus', event); }).on('blur', function (event) { _this2.context.triggerEvent('blur', event); }).on('mousedown', function (event) { _this2.context.triggerEvent('mousedown', event); }).on('mouseup', function (event) { _this2.setLastRange(); _this2.history.recordUndo(); _this2.context.triggerEvent('mouseup', event); }).on('scroll', function (event) { _this2.context.triggerEvent('scroll', event); }).on('paste', function (event) { _this2.setLastRange(); _this2.context.triggerEvent('paste', event); }).on('input', function () { // To limit composition characters (e.g. Korean) if (_this2.isLimited(0) && _this2.snapshot) { _this2.history.applySnapshot(_this2.snapshot); } }); this.$editable.attr('spellcheck', this.options.spellCheck); this.$editable.attr('autocorrect', this.options.spellCheck); if (this.options.disableGrammar) { this.$editable.attr('data-gramm', false); } // init content before set event this.$editable.html(dom.html(this.$note) || dom.emptyPara); this.$editable.on(env.inputEventName, func.debounce(function () { _this2.context.triggerEvent('change', _this2.$editable.html(), _this2.$editable); }, 10)); this.$editable.on('focusin', function (event) { _this2.context.triggerEvent('focusin', event); }).on('focusout', function (event) { _this2.context.triggerEvent('focusout', event); }); if (this.options.airMode) { if (this.options.overrideContextMenu) { this.$editor.on('contextmenu', function (event) { _this2.context.triggerEvent('contextmenu', event); return false; }); } } else { if (this.options.width) { this.$editor.outerWidth(this.options.width); } if (this.options.height) { this.$editable.outerHeight(this.options.height); } if (this.options.maxHeight) { this.$editable.css('max-height', this.options.maxHeight); } if (this.options.minHeight) { this.$editable.css('min-height', this.options.minHeight); } } this.history.recordUndo(); this.setLastRange(); } }, { key: "destroy", value: function destroy() { this.$editable.off(); } }, { key: "handleKeyMap", value: function handleKeyMap(event) { var keyMap = this.options.keyMap[env.isMac ? 'mac' : 'pc']; var keys = []; if (event.metaKey) { keys.push('CMD'); } if (event.ctrlKey && !event.altKey) { keys.push('CTRL'); } if (event.shiftKey) { keys.push('SHIFT'); } var keyName = key.nameFromCode[event.keyCode]; if (keyName) { keys.push(keyName); } var eventName = keyMap[keys.join('+')]; if (keyName === 'TAB' && !this.options.tabDisable) { this.afterCommand(); } else if (eventName) { if (this.context.invoke(eventName) !== false) { event.preventDefault(); // if keyMap action was invoked return true; } } else if (key.isEdit(event.keyCode)) { this.afterCommand(); } return false; } }, { key: "preventDefaultEditableShortCuts", value: function preventDefaultEditableShortCuts(event) { // B(Bold, 66) / I(Italic, 73) / U(Underline, 85) if ((event.ctrlKey || event.metaKey) && lists.contains([66, 73, 85], event.keyCode)) { event.preventDefault(); } } }, { key: "isLimited", value: function isLimited(pad, event) { pad = pad || 0; if (typeof event !== 'undefined') { if (key.isMove(event.keyCode) || key.isNavigation(event.keyCode) || event.ctrlKey || event.metaKey || lists.contains([key.code.BACKSPACE, key.code.DELETE], event.keyCode)) { return false; } } if (this.options.maxTextLength > 0) { if (this.$editable.text().length + pad > this.options.maxTextLength) { return true; } } return false; } /** * create range * @return {WrappedRange} */ }, { key: "createRange", value: function createRange() { this.focus(); this.setLastRange(); return this.getLastRange(); } /** * create a new range from the list of elements * * @param {list} dom element list * @return {WrappedRange} */ }, { key: "createRangeFromList", value: function createRangeFromList(lst) { var startRange = range.createFromNodeBefore(lists.head(lst)); var startPoint = startRange.getStartPoint(); var endRange = range.createFromNodeAfter(lists.last(lst)); var endPoint = endRange.getEndPoint(); return range.create(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset); } /** * set the last range * * if given rng is exist, set rng as the last range * or create a new range at the end of the document * * @param {WrappedRange} rng */ }, { key: "setLastRange", value: function setLastRange(rng) { if (rng) { this.lastRange = rng; } else { this.lastRange = range.create(this.editable); if (external_jQuery_default()(this.lastRange.sc).closest('.note-editable').length === 0) { this.lastRange = range.createFromBodyElement(this.editable); } } } /** * get the last range * * if there is a saved last range, return it * or create a new range and return it * * @return {WrappedRange} */ }, { key: "getLastRange", value: function getLastRange() { if (!this.lastRange) { this.setLastRange(); } return this.lastRange; } /** * saveRange * * save current range * * @param {Boolean} [thenCollapse=false] */ }, { key: "saveRange", value: function saveRange(thenCollapse) { if (thenCollapse) { this.getLastRange().collapse().select(); } } /** * restoreRange * * restore lately range */ }, { key: "restoreRange", value: function restoreRange() { if (this.lastRange) { this.lastRange.select(); this.focus(); } } }, { key: "saveTarget", value: function saveTarget(node) { this.$editable.data('target', node); } }, { key: "clearTarget", value: function clearTarget() { this.$editable.removeData('target'); } }, { key: "restoreTarget", value: function restoreTarget() { return this.$editable.data('target'); } /** * currentStyle * * current style * @return {Object|Boolean} unfocus */ }, { key: "currentStyle", value: function currentStyle() { var rng = range.create(); if (rng) { rng = rng.normalize(); } return rng ? this.style.current(rng) : this.style.fromNode(this.$editable); } /** * style from node * * @param {jQuery} $node * @return {Object} */ }, { key: "styleFromNode", value: function styleFromNode($node) { return this.style.fromNode($node); } /** * undo */ }, { key: "undo", value: function undo() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.undo(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /* * commit */ }, { key: "commit", value: function commit() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.commit(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /** * redo */ }, { key: "redo", value: function redo() { this.context.triggerEvent('before.command', this.$editable.html()); this.history.redo(); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } /** * before command */ }, { key: "beforeCommand", value: function beforeCommand() { this.context.triggerEvent('before.command', this.$editable.html()); // Set styleWithCSS before run a command document.execCommand('styleWithCSS', false, this.options.styleWithCSS); // keep focus on editable before command execution this.focus(); } /** * after command * @param {Boolean} isPreventTrigger */ }, { key: "afterCommand", value: function afterCommand(isPreventTrigger) { this.normalizeContent(); this.history.recordUndo(); if (!isPreventTrigger) { this.context.triggerEvent('change', this.$editable.html(), this.$editable); } } /** * handle tab key */ }, { key: "tab", value: function tab() { var rng = this.getLastRange(); if (rng.isCollapsed() && rng.isOnCell()) { this.table.tab(rng); } else { if (this.options.tabSize === 0) { return false; } if (!this.isLimited(this.options.tabSize)) { this.beforeCommand(); this.typing.insertTab(rng, this.options.tabSize); this.afterCommand(); } } } /** * handle shift+tab key */ }, { key: "untab", value: function untab() { var rng = this.getLastRange(); if (rng.isCollapsed() && rng.isOnCell()) { this.table.tab(rng, true); } else { if (this.options.tabSize === 0) { return false; } } } /** * run given function between beforeCommand and afterCommand */ }, { key: "wrapCommand", value: function wrapCommand(fn) { return function () { this.beforeCommand(); fn.apply(this, arguments); this.afterCommand(); }; } /** * insert image * * @param {String} src * @param {String|Function} param * @return {Promise} */ }, { key: "insertImage", value: function insertImage(src, param) { var _this3 = this; return createImage(src, param).then(function ($image) { _this3.beforeCommand(); if (typeof param === 'function') { param($image); } else { if (typeof param === 'string') { $image.attr('data-filename', param); } $image.css('width', Math.min(_this3.$editable.width(), $image.width())); } $image.show(); _this3.getLastRange().insertNode($image[0]); _this3.setLastRange(range.createFromNodeAfter($image[0]).select()); _this3.afterCommand(); }).fail(function (e) { _this3.context.triggerEvent('image.upload.error', e); }); } /** * insertImages * @param {File[]} files */ }, { key: "insertImagesAsDataURL", value: function insertImagesAsDataURL(files) { var _this4 = this; external_jQuery_default().each(files, function (idx, file) { var filename = file.name; if (_this4.options.maximumImageFileSize && _this4.options.maximumImageFileSize < file.size) { _this4.context.triggerEvent('image.upload.error', _this4.lang.image.maximumFileSizeError); } else { readFileAsDataURL(file).then(function (dataURL) { return _this4.insertImage(dataURL, filename); }).fail(function () { _this4.context.triggerEvent('image.upload.error'); }); } }); } /** * insertImagesOrCallback * @param {File[]} files */ }, { key: "insertImagesOrCallback", value: function insertImagesOrCallback(files) { var callbacks = this.options.callbacks; // If onImageUpload set, if (callbacks.onImageUpload) { this.context.triggerEvent('image.upload', files); // else insert Image as dataURL } else { this.insertImagesAsDataURL(files); } } /** * return selected plain text * @return {String} text */ }, { key: "getSelectedText", value: function getSelectedText() { var rng = this.getLastRange(); // if range on anchor, expand range with anchor if (rng.isOnAnchor()) { rng = range.createFromNode(dom.ancestor(rng.sc, dom.isAnchor)); } return rng.toString(); } }, { key: "onFormatBlock", value: function onFormatBlock(tagName, $target) { // [workaround] for MSIE, IE need `<` document.execCommand('FormatBlock', false, env.isMSIE ? '<' + tagName + '>' : tagName); // support custom class if ($target && $target.length) { // find the exact element has given tagName if ($target[0].tagName.toUpperCase() !== tagName.toUpperCase()) { $target = $target.find(tagName); } if ($target && $target.length) { var currentRange = this.createRange(); var $parent = external_jQuery_default()([currentRange.sc, currentRange.ec]).closest(tagName); // remove class added for current block $parent.removeClass(); var className = $target[0].className || ''; if (className) { $parent.addClass(className); } } } } }, { key: "formatPara", value: function formatPara() { this.formatBlock('P'); } }, { key: "fontStyling", value: function fontStyling(target, value) { var rng = this.getLastRange(); if (rng !== '') { var spans = this.style.styleNodes(rng); this.$editor.find('.note-status-output').html(''); external_jQuery_default()(spans).css(target, value); // [workaround] added styled bogus span for style // - also bogus character needed for cursor position if (rng.isCollapsed()) { var firstSpan = lists.head(spans); if (firstSpan && !dom.nodeLength(firstSpan)) { firstSpan.innerHTML = dom.ZERO_WIDTH_NBSP_CHAR; range.createFromNode(firstSpan.firstChild).select(); this.setLastRange(); this.$editable.data(KEY_BOGUS, firstSpan); } } else { this.setLastRange(this.createRangeFromList(spans).select()); } } else { var noteStatusOutput = external_jQuery_default().now(); this.$editor.find('.note-status-output').html('<div id="note-status-output-' + noteStatusOutput + '" class="alert alert-info">' + this.lang.output.noSelection + '</div>'); setTimeout(function () { external_jQuery_default()('#note-status-output-' + noteStatusOutput).remove(); }, 5000); } } /** * unlink * * @type command */ }, { key: "unlink", value: function unlink() { var rng = this.getLastRange(); if (rng.isOnAnchor()) { var anchor = dom.ancestor(rng.sc, dom.isAnchor); rng = range.createFromNode(anchor); rng.select(); this.setLastRange(); this.beforeCommand(); document.execCommand('unlink'); this.afterCommand(); } } /** * returns link info * * @return {Object} * @return {WrappedRange} return.range * @return {String} return.text * @return {Boolean} [return.isNewWindow=true] * @return {String} [return.url=""] */ }, { key: "getLinkInfo", value: function getLinkInfo() { var rng = this.getLastRange().expand(dom.isAnchor); // Get the first anchor on range(for edit). var $anchor = external_jQuery_default()(lists.head(rng.nodes(dom.isAnchor))); var linkInfo = { range: rng, text: rng.toString(), url: $anchor.length ? $anchor.attr('href') : '' }; // When anchor exists, if ($anchor.length) { // Set isNewWindow by checking its target. linkInfo.isNewWindow = $anchor.attr('target') === '_blank'; } return linkInfo; } }, { key: "addRow", value: function addRow(position) { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.addRow(rng, position); this.afterCommand(); } } }, { key: "addCol", value: function addCol(position) { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.addCol(rng, position); this.afterCommand(); } } }, { key: "deleteRow", value: function deleteRow() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteRow(rng); this.afterCommand(); } } }, { key: "deleteCol", value: function deleteCol() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteCol(rng); this.afterCommand(); } } }, { key: "deleteTable", value: function deleteTable() { var rng = this.getLastRange(this.$editable); if (rng.isCollapsed() && rng.isOnCell()) { this.beforeCommand(); this.table.deleteTable(rng); this.afterCommand(); } } /** * @param {Position} pos * @param {jQuery} $target - target element * @param {Boolean} [bKeepRatio] - keep ratio */ }, { key: "resizeTo", value: function resizeTo(pos, $target, bKeepRatio) { var imageSize; if (bKeepRatio) { var newRatio = pos.y / pos.x; var ratio = $target.data('ratio'); imageSize = { width: ratio > newRatio ? pos.x : pos.y / ratio, height: ratio > newRatio ? pos.x * ratio : pos.y }; } else { imageSize = { width: pos.x, height: pos.y }; } $target.css(imageSize); } /** * returns whether editable area has focus or not. */ }, { key: "hasFocus", value: function hasFocus() { return this.$editable.is(':focus'); } /** * set focus */ }, { key: "focus", value: function focus() { // [workaround] Screen will move when page is scolled in IE. // - do focus when not focused if (!this.hasFocus()) { this.$editable.focus(); } } /** * returns whether contents is empty or not. * @return {Boolean} */ }, { key: "isEmpty", value: function isEmpty() { return dom.isEmpty(this.$editable[0]) || dom.emptyPara === this.$editable.html(); } /** * Removes all contents and restores the editable instance to an _emptyPara_. */ }, { key: "empty", value: function empty() { this.context.invoke('code', dom.emptyPara); } /** * normalize content */ }, { key: "normalizeContent", value: function normalizeContent() { this.$editable[0].normalize(); } }]); return Editor; }(); ;// CONCATENATED MODULE: ./src/js/module/Clipboard.js function Clipboard_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Clipboard_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Clipboard_createClass(Constructor, protoProps, staticProps) { if (protoProps) Clipboard_defineProperties(Constructor.prototype, protoProps); if (staticProps) Clipboard_defineProperties(Constructor, staticProps); return Constructor; } var Clipboard = /*#__PURE__*/function () { function Clipboard(context) { Clipboard_classCallCheck(this, Clipboard); this.context = context; this.$editable = context.layoutInfo.editable; } Clipboard_createClass(Clipboard, [{ key: "initialize", value: function initialize() { this.$editable.on('paste', this.pasteByEvent.bind(this)); } /** * paste by clipboard event * * @param {Event} event */ }, { key: "pasteByEvent", value: function pasteByEvent(event) { var _this = this; var clipboardData = event.originalEvent.clipboardData; if (clipboardData && clipboardData.items && clipboardData.items.length) { var item = clipboardData.items.length > 1 ? clipboardData.items[1] : lists.head(clipboardData.items); if (item.kind === 'file' && item.type.indexOf('image/') !== -1) { // paste img file this.context.invoke('editor.insertImagesOrCallback', [item.getAsFile()]); event.preventDefault(); } else if (item.kind === 'string') { // paste text with maxTextLength check if (this.context.invoke('editor.isLimited', clipboardData.getData('Text').length)) { event.preventDefault(); } } } else if (window.clipboardData) { // for IE var text = window.clipboardData.getData('text'); if (this.context.invoke('editor.isLimited', text.length)) { event.preventDefault(); } } // Call editor.afterCommand after proceeding default event handler setTimeout(function () { _this.context.invoke('editor.afterCommand'); }, 10); } }]); return Clipboard; }(); ;// CONCATENATED MODULE: ./src/js/module/Dropzone.js function Dropzone_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Dropzone_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Dropzone_createClass(Constructor, protoProps, staticProps) { if (protoProps) Dropzone_defineProperties(Constructor.prototype, protoProps); if (staticProps) Dropzone_defineProperties(Constructor, staticProps); return Constructor; } var Dropzone = /*#__PURE__*/function () { function Dropzone(context) { Dropzone_classCallCheck(this, Dropzone); this.context = context; this.$eventListener = external_jQuery_default()(document); this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.options = context.options; this.lang = this.options.langInfo; this.documentEventHandlers = {}; this.$dropzone = external_jQuery_default()(['<div class="note-dropzone">', '<div class="note-dropzone-message"></div>', '</div>'].join('')).prependTo(this.$editor); } /** * attach Drag and Drop Events */ Dropzone_createClass(Dropzone, [{ key: "initialize", value: function initialize() { if (this.options.disableDragAndDrop) { // prevent default drop event this.documentEventHandlers.onDrop = function (e) { e.preventDefault(); }; // do not consider outside of dropzone this.$eventListener = this.$dropzone; this.$eventListener.on('drop', this.documentEventHandlers.onDrop); } else { this.attachDragAndDropEvent(); } } /** * attach Drag and Drop Events */ }, { key: "attachDragAndDropEvent", value: function attachDragAndDropEvent() { var _this = this; var collection = external_jQuery_default()(); var $dropzoneMessage = this.$dropzone.find('.note-dropzone-message'); this.documentEventHandlers.onDragenter = function (e) { var isCodeview = _this.context.invoke('codeview.isActivated'); var hasEditorSize = _this.$editor.width() > 0 && _this.$editor.height() > 0; if (!isCodeview && !collection.length && hasEditorSize) { _this.$editor.addClass('dragover'); _this.$dropzone.width(_this.$editor.width()); _this.$dropzone.height(_this.$editor.height()); $dropzoneMessage.text(_this.lang.image.dragImageHere); } collection = collection.add(e.target); }; this.documentEventHandlers.onDragleave = function (e) { collection = collection.not(e.target); // If nodeName is BODY, then just make it over (fix for IE) if (!collection.length || e.target.nodeName === 'BODY') { collection = external_jQuery_default()(); _this.$editor.removeClass('dragover'); } }; this.documentEventHandlers.onDrop = function () { collection = external_jQuery_default()(); _this.$editor.removeClass('dragover'); }; // show dropzone on dragenter when dragging a object to document // -but only if the editor is visible, i.e. has a positive width and height this.$eventListener.on('dragenter', this.documentEventHandlers.onDragenter).on('dragleave', this.documentEventHandlers.onDragleave).on('drop', this.documentEventHandlers.onDrop); // change dropzone's message on hover. this.$dropzone.on('dragenter', function () { _this.$dropzone.addClass('hover'); $dropzoneMessage.text(_this.lang.image.dropImage); }).on('dragleave', function () { _this.$dropzone.removeClass('hover'); $dropzoneMessage.text(_this.lang.image.dragImageHere); }); // attach dropImage this.$dropzone.on('drop', function (event) { var dataTransfer = event.originalEvent.dataTransfer; // stop the browser from opening the dropped content event.preventDefault(); if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { _this.$editable.focus(); _this.context.invoke('editor.insertImagesOrCallback', dataTransfer.files); } else { external_jQuery_default().each(dataTransfer.types, function (idx, type) { // skip moz-specific types if (type.toLowerCase().indexOf('_moz_') > -1) { return; } var content = dataTransfer.getData(type); if (type.toLowerCase().indexOf('text') > -1) { _this.context.invoke('editor.pasteHTML', content); } else { external_jQuery_default()(content).each(function (idx, item) { _this.context.invoke('editor.insertNode', item); }); } }); } }).on('dragover', false); // prevent default dragover event } }, { key: "destroy", value: function destroy() { var _this2 = this; Object.keys(this.documentEventHandlers).forEach(function (key) { _this2.$eventListener.off(key.substr(2).toLowerCase(), _this2.documentEventHandlers[key]); }); this.documentEventHandlers = {}; } }]); return Dropzone; }(); ;// CONCATENATED MODULE: ./src/js/module/Codeview.js function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function Codeview_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Codeview_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Codeview_createClass(Constructor, protoProps, staticProps) { if (protoProps) Codeview_defineProperties(Constructor.prototype, protoProps); if (staticProps) Codeview_defineProperties(Constructor, staticProps); return Constructor; } /** * @class Codeview */ var CodeView = /*#__PURE__*/function () { function CodeView(context) { Codeview_classCallCheck(this, CodeView); this.context = context; this.$editor = context.layoutInfo.editor; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.options = context.options; this.CodeMirrorConstructor = window.CodeMirror; if (this.options.codemirror.CodeMirrorConstructor) { this.CodeMirrorConstructor = this.options.codemirror.CodeMirrorConstructor; } } Codeview_createClass(CodeView, [{ key: "sync", value: function sync(html) { var isCodeview = this.isActivated(); var CodeMirror = this.CodeMirrorConstructor; if (isCodeview) { if (html) { if (CodeMirror) { this.$codable.data('cmEditor').getDoc().setValue(html); } else { this.$codable.val(html); } } else { if (CodeMirror) { this.$codable.data('cmEditor').save(); } } } } }, { key: "initialize", value: function initialize() { var _this = this; this.$codable.on('keyup', function (event) { if (event.keyCode === key.code.ESCAPE) { _this.deactivate(); } }); } /** * @return {Boolean} */ }, { key: "isActivated", value: function isActivated() { return this.$editor.hasClass('codeview'); } /** * toggle codeview */ }, { key: "toggle", value: function toggle() { if (this.isActivated()) { this.deactivate(); } else { this.activate(); } this.context.triggerEvent('codeview.toggled'); } /** * purify input value * @param value * @returns {*} */ }, { key: "purify", value: function purify(value) { if (this.options.codeviewFilter) { // filter code view regex value = value.replace(this.options.codeviewFilterRegex, ''); // allow specific iframe tag if (this.options.codeviewIframeFilter) { var whitelist = this.options.codeviewIframeWhitelistSrc.concat(this.options.codeviewIframeWhitelistSrcBase); value = value.replace(/(<iframe.*?>.*?(?:<\/iframe>)?)/gi, function (tag) { // remove if src attribute is duplicated if (/<.+src(?==?('|"|\s)?)[\s\S]+src(?=('|"|\s)?)[^>]*?>/i.test(tag)) { return ''; } var _iterator = _createForOfIteratorHelper(whitelist), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var src = _step.value; // pass if src is trusted if (new RegExp('src="(https?:)?\/\/' + src.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '\/(.+)"').test(tag)) { return tag; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return ''; }); } } return value; } /** * activate code view */ }, { key: "activate", value: function activate() { var _this2 = this; var CodeMirror = this.CodeMirrorConstructor; this.$codable.val(dom.html(this.$editable, this.options.prettifyHtml)); this.$codable.height(this.$editable.height()); this.context.invoke('toolbar.updateCodeview', true); this.context.invoke('airPopover.updateCodeview', true); this.$editor.addClass('codeview'); this.$codable.focus(); // activate CodeMirror as codable if (CodeMirror) { var cmEditor = CodeMirror.fromTextArea(this.$codable[0], this.options.codemirror); // CodeMirror TernServer if (this.options.codemirror.tern) { var server = new CodeMirror.TernServer(this.options.codemirror.tern); cmEditor.ternServer = server; cmEditor.on('cursorActivity', function (cm) { server.updateArgHints(cm); }); } cmEditor.on('blur', function (event) { _this2.context.triggerEvent('blur.codeview', cmEditor.getValue(), event); }); cmEditor.on('change', function () { _this2.context.triggerEvent('change.codeview', cmEditor.getValue(), cmEditor); }); // CodeMirror hasn't Padding. cmEditor.setSize(null, this.$editable.outerHeight()); this.$codable.data('cmEditor', cmEditor); } else { this.$codable.on('blur', function (event) { _this2.context.triggerEvent('blur.codeview', _this2.$codable.val(), event); }); this.$codable.on('input', function () { _this2.context.triggerEvent('change.codeview', _this2.$codable.val(), _this2.$codable); }); } } /** * deactivate code view */ }, { key: "deactivate", value: function deactivate() { var CodeMirror = this.CodeMirrorConstructor; // deactivate CodeMirror as codable if (CodeMirror) { var cmEditor = this.$codable.data('cmEditor'); this.$codable.val(cmEditor.getValue()); cmEditor.toTextArea(); } var value = this.purify(dom.value(this.$codable, this.options.prettifyHtml) || dom.emptyPara); var isChange = this.$editable.html() !== value; this.$editable.html(value); this.$editable.height(this.options.height ? this.$codable.height() : 'auto'); this.$editor.removeClass('codeview'); if (isChange) { this.context.triggerEvent('change', this.$editable.html(), this.$editable); } this.$editable.focus(); this.context.invoke('toolbar.updateCodeview', false); this.context.invoke('airPopover.updateCodeview', false); } }, { key: "destroy", value: function destroy() { if (this.isActivated()) { this.deactivate(); } } }]); return CodeView; }(); ;// CONCATENATED MODULE: ./src/js/module/Statusbar.js function Statusbar_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Statusbar_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Statusbar_createClass(Constructor, protoProps, staticProps) { if (protoProps) Statusbar_defineProperties(Constructor.prototype, protoProps); if (staticProps) Statusbar_defineProperties(Constructor, staticProps); return Constructor; } var EDITABLE_PADDING = 24; var Statusbar = /*#__PURE__*/function () { function Statusbar(context) { Statusbar_classCallCheck(this, Statusbar); this.$document = external_jQuery_default()(document); this.$statusbar = context.layoutInfo.statusbar; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.options = context.options; } Statusbar_createClass(Statusbar, [{ key: "initialize", value: function initialize() { var _this = this; if (this.options.airMode || this.options.disableResizeEditor) { this.destroy(); return; } this.$statusbar.on('mousedown', function (event) { event.preventDefault(); event.stopPropagation(); var editableTop = _this.$editable.offset().top - _this.$document.scrollTop(); var editableCodeTop = _this.$codable.offset().top - _this.$document.scrollTop(); var onMouseMove = function onMouseMove(event) { var height = event.clientY - (editableTop + EDITABLE_PADDING); var heightCode = event.clientY - (editableCodeTop + EDITABLE_PADDING); height = _this.options.minheight > 0 ? Math.max(height, _this.options.minheight) : height; height = _this.options.maxHeight > 0 ? Math.min(height, _this.options.maxHeight) : height; heightCode = _this.options.minheight > 0 ? Math.max(heightCode, _this.options.minheight) : heightCode; heightCode = _this.options.maxHeight > 0 ? Math.min(heightCode, _this.options.maxHeight) : heightCode; _this.$editable.height(height); _this.$codable.height(heightCode); }; _this.$document.on('mousemove', onMouseMove).one('mouseup', function () { _this.$document.off('mousemove', onMouseMove); }); }); } }, { key: "destroy", value: function destroy() { this.$statusbar.off(); this.$statusbar.addClass('locked'); } }]); return Statusbar; }(); ;// CONCATENATED MODULE: ./src/js/module/Fullscreen.js function Fullscreen_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Fullscreen_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Fullscreen_createClass(Constructor, protoProps, staticProps) { if (protoProps) Fullscreen_defineProperties(Constructor.prototype, protoProps); if (staticProps) Fullscreen_defineProperties(Constructor, staticProps); return Constructor; } var Fullscreen = /*#__PURE__*/function () { function Fullscreen(context) { var _this = this; Fullscreen_classCallCheck(this, Fullscreen); this.context = context; this.$editor = context.layoutInfo.editor; this.$toolbar = context.layoutInfo.toolbar; this.$editable = context.layoutInfo.editable; this.$codable = context.layoutInfo.codable; this.$window = external_jQuery_default()(window); this.$scrollbar = external_jQuery_default()('html, body'); this.scrollbarClassName = 'note-fullscreen-body'; this.onResize = function () { _this.resizeTo({ h: _this.$window.height() - _this.$toolbar.outerHeight() }); }; } Fullscreen_createClass(Fullscreen, [{ key: "resizeTo", value: function resizeTo(size) { this.$editable.css('height', size.h); this.$codable.css('height', size.h); if (this.$codable.data('cmeditor')) { this.$codable.data('cmeditor').setsize(null, size.h); } } /** * toggle fullscreen */ }, { key: "toggle", value: function toggle() { this.$editor.toggleClass('fullscreen'); var isFullscreen = this.isFullscreen(); this.$scrollbar.toggleClass(this.scrollbarClassName, isFullscreen); if (isFullscreen) { this.$editable.data('orgHeight', this.$editable.css('height')); this.$editable.data('orgMaxHeight', this.$editable.css('maxHeight')); this.$editable.css('maxHeight', ''); this.$window.on('resize', this.onResize).trigger('resize'); } else { this.$window.off('resize', this.onResize); this.resizeTo({ h: this.$editable.data('orgHeight') }); this.$editable.css('maxHeight', this.$editable.css('orgMaxHeight')); } this.context.invoke('toolbar.updateFullscreen', isFullscreen); } }, { key: "isFullscreen", value: function isFullscreen() { return this.$editor.hasClass('fullscreen'); } }, { key: "destroy", value: function destroy() { this.$scrollbar.removeClass(this.scrollbarClassName); } }]); return Fullscreen; }(); ;// CONCATENATED MODULE: ./src/js/module/Handle.js function Handle_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Handle_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Handle_createClass(Constructor, protoProps, staticProps) { if (protoProps) Handle_defineProperties(Constructor.prototype, protoProps); if (staticProps) Handle_defineProperties(Constructor, staticProps); return Constructor; } var Handle = /*#__PURE__*/function () { function Handle(context) { var _this = this; Handle_classCallCheck(this, Handle); this.context = context; this.$document = external_jQuery_default()(document); this.$editingArea = context.layoutInfo.editingArea; this.options = context.options; this.lang = this.options.langInfo; this.events = { 'summernote.mousedown': function summernoteMousedown(we, e) { if (_this.update(e.target, e)) { e.preventDefault(); } }, 'summernote.keyup summernote.scroll summernote.change summernote.dialog.shown': function summernoteKeyupSummernoteScrollSummernoteChangeSummernoteDialogShown() { _this.update(); }, 'summernote.disable summernote.blur': function summernoteDisableSummernoteBlur() { _this.hide(); }, 'summernote.codeview.toggled': function summernoteCodeviewToggled() { _this.update(); } }; } Handle_createClass(Handle, [{ key: "initialize", value: function initialize() { var _this2 = this; this.$handle = external_jQuery_default()(['<div class="note-handle">', '<div class="note-control-selection">', '<div class="note-control-selection-bg"></div>', '<div class="note-control-holder note-control-nw"></div>', '<div class="note-control-holder note-control-ne"></div>', '<div class="note-control-holder note-control-sw"></div>', '<div class="', this.options.disableResizeImage ? 'note-control-holder' : 'note-control-sizing', ' note-control-se"></div>', this.options.disableResizeImage ? '' : '<div class="note-control-selection-info"></div>', '</div>', '</div>'].join('')).prependTo(this.$editingArea); this.$handle.on('mousedown', function (event) { if (dom.isControlSizing(event.target)) { event.preventDefault(); event.stopPropagation(); var $target = _this2.$handle.find('.note-control-selection').data('target'); var posStart = $target.offset(); var scrollTop = _this2.$document.scrollTop(); var onMouseMove = function onMouseMove(event) { _this2.context.invoke('editor.resizeTo', { x: event.clientX - posStart.left, y: event.clientY - (posStart.top - scrollTop) }, $target, !event.shiftKey); _this2.update($target[0], event); }; _this2.$document.on('mousemove', onMouseMove).one('mouseup', function (e) { e.preventDefault(); _this2.$document.off('mousemove', onMouseMove); _this2.context.invoke('editor.afterCommand'); }); if (!$target.data('ratio')) { // original ratio. $target.data('ratio', $target.height() / $target.width()); } } }); // Listen for scrolling on the handle overlay. this.$handle.on('wheel', function (e) { e.preventDefault(); _this2.update(); }); } }, { key: "destroy", value: function destroy() { this.$handle.remove(); } }, { key: "update", value: function update(target, event) { if (this.context.isDisabled()) { return false; } var isImage = dom.isImg(target); var $selection = this.$handle.find('.note-control-selection'); this.context.invoke('imagePopover.update', target, event); if (isImage) { var $image = external_jQuery_default()(target); var position = $image.position(); var pos = { left: position.left + parseInt($image.css('marginLeft'), 10), top: position.top + parseInt($image.css('marginTop'), 10) }; // exclude margin var imageSize = { w: $image.outerWidth(false), h: $image.outerHeight(false) }; $selection.css({ display: 'block', left: pos.left, top: pos.top, width: imageSize.w, height: imageSize.h }).data('target', $image); // save current image element. var origImageObj = new Image(); origImageObj.src = $image.attr('src'); var sizingText = imageSize.w + 'x' + imageSize.h + ' (' + this.lang.image.original + ': ' + origImageObj.width + 'x' + origImageObj.height + ')'; $selection.find('.note-control-selection-info').text(sizingText); this.context.invoke('editor.saveTarget', target); } else { this.hide(); } return isImage; } /** * hide * * @param {jQuery} $handle */ }, { key: "hide", value: function hide() { this.context.invoke('editor.clearTarget'); this.$handle.children().hide(); } }]); return Handle; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoLink.js function AutoLink_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoLink_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoLink_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoLink_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoLink_defineProperties(Constructor, staticProps); return Constructor; } var defaultScheme = 'http://'; var linkPattern = /^([A-Za-z][A-Za-z0-9+-.]*\:[\/]{2}|tel:|mailto:[A-Z0-9._%+-]+@|xmpp:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i; var AutoLink = /*#__PURE__*/function () { function AutoLink(context) { var _this = this; AutoLink_classCallCheck(this, AutoLink); this.context = context; this.options = context.options; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); } }; } AutoLink_createClass(AutoLink, [{ key: "initialize", value: function initialize() { this.lastWordRange = null; } }, { key: "destroy", value: function destroy() { this.lastWordRange = null; } }, { key: "replace", value: function replace() { if (!this.lastWordRange) { return; } var keyword = this.lastWordRange.toString(); var match = keyword.match(linkPattern); if (match && (match[1] || match[2])) { var link = match[1] ? keyword : defaultScheme + keyword; var urlText = this.options.showDomainOnlyForAutolink ? keyword.replace(/^(?:https?:\/\/)?(?:tel?:?)?(?:mailto?:?)?(?:xmpp?:?)?(?:www\.)?/i, '').split('/')[0] : keyword; var node = external_jQuery_default()('<a></a>').html(urlText).attr('href', link)[0]; if (this.context.options.linkTargetBlank) { external_jQuery_default()(node).attr('target', '_blank'); } this.lastWordRange.insertNode(node); this.lastWordRange = null; this.context.invoke('editor.focus'); } } }, { key: "handleKeydown", value: function handleKeydown(e) { if (lists.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) { var wordRange = this.context.invoke('editor.createRange').getWordRange(); this.lastWordRange = wordRange; } } }, { key: "handleKeyup", value: function handleKeyup(e) { if (lists.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) { this.replace(); } } }]); return AutoLink; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoSync.js function AutoSync_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoSync_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoSync_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoSync_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoSync_defineProperties(Constructor, staticProps); return Constructor; } /** * textarea auto sync. */ var AutoSync = /*#__PURE__*/function () { function AutoSync(context) { var _this = this; AutoSync_classCallCheck(this, AutoSync); this.$note = context.layoutInfo.note; this.events = { 'summernote.change': function summernoteChange() { _this.$note.val(context.invoke('code')); } }; } AutoSync_createClass(AutoSync, [{ key: "shouldInitialize", value: function shouldInitialize() { return dom.isTextarea(this.$note[0]); } }]); return AutoSync; }(); ;// CONCATENATED MODULE: ./src/js/module/AutoReplace.js function AutoReplace_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AutoReplace_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AutoReplace_createClass(Constructor, protoProps, staticProps) { if (protoProps) AutoReplace_defineProperties(Constructor.prototype, protoProps); if (staticProps) AutoReplace_defineProperties(Constructor, staticProps); return Constructor; } var AutoReplace = /*#__PURE__*/function () { function AutoReplace(context) { var _this = this; AutoReplace_classCallCheck(this, AutoReplace); this.context = context; this.options = context.options.replace || {}; this.keys = [key.code.ENTER, key.code.SPACE, key.code.PERIOD, key.code.COMMA, key.code.SEMICOLON, key.code.SLASH]; this.previousKeydownCode = null; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); } }; } AutoReplace_createClass(AutoReplace, [{ key: "shouldInitialize", value: function shouldInitialize() { return !!this.options.match; } }, { key: "initialize", value: function initialize() { this.lastWord = null; } }, { key: "destroy", value: function destroy() { this.lastWord = null; } }, { key: "replace", value: function replace() { if (!this.lastWord) { return; } var self = this; var keyword = this.lastWord.toString(); this.options.match(keyword, function (match) { if (match) { var node = ''; if (typeof match === 'string') { node = dom.createText(match); } else if (match instanceof jQuery) { node = match[0]; } else if (match instanceof Node) { node = match; } if (!node) return; self.lastWord.insertNode(node); self.lastWord = null; self.context.invoke('editor.focus'); } }); } }, { key: "handleKeydown", value: function handleKeydown(e) { // this forces it to remember the last whole word, even if multiple termination keys are pressed // before the previous key is let go. if (this.previousKeydownCode && lists.contains(this.keys, this.previousKeydownCode)) { this.previousKeydownCode = e.keyCode; return; } if (lists.contains(this.keys, e.keyCode)) { var wordRange = this.context.invoke('editor.createRange').getWordRange(); this.lastWord = wordRange; } this.previousKeydownCode = e.keyCode; } }, { key: "handleKeyup", value: function handleKeyup(e) { if (lists.contains(this.keys, e.keyCode)) { this.replace(); } } }]); return AutoReplace; }(); ;// CONCATENATED MODULE: ./src/js/module/Placeholder.js function Placeholder_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Placeholder_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Placeholder_createClass(Constructor, protoProps, staticProps) { if (protoProps) Placeholder_defineProperties(Constructor.prototype, protoProps); if (staticProps) Placeholder_defineProperties(Constructor, staticProps); return Constructor; } var Placeholder = /*#__PURE__*/function () { function Placeholder(context) { var _this = this; Placeholder_classCallCheck(this, Placeholder); this.context = context; this.$editingArea = context.layoutInfo.editingArea; this.options = context.options; if (this.options.inheritPlaceholder === true) { // get placeholder value from the original element this.options.placeholder = this.context.$note.attr('placeholder') || this.options.placeholder; } this.events = { 'summernote.init summernote.change': function summernoteInitSummernoteChange() { _this.update(); }, 'summernote.codeview.toggled': function summernoteCodeviewToggled() { _this.update(); } }; } Placeholder_createClass(Placeholder, [{ key: "shouldInitialize", value: function shouldInitialize() { return !!this.options.placeholder; } }, { key: "initialize", value: function initialize() { var _this2 = this; this.$placeholder = external_jQuery_default()('<div class="note-placeholder"></div>'); this.$placeholder.on('click', function () { _this2.context.invoke('focus'); }).html(this.options.placeholder).prependTo(this.$editingArea); this.update(); } }, { key: "destroy", value: function destroy() { this.$placeholder.remove(); } }, { key: "update", value: function update() { var isShow = !this.context.invoke('codeview.isActivated') && this.context.invoke('editor.isEmpty'); this.$placeholder.toggle(isShow); } }]); return Placeholder; }(); ;// CONCATENATED MODULE: ./src/js/module/Buttons.js function Buttons_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Buttons_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Buttons_createClass(Constructor, protoProps, staticProps) { if (protoProps) Buttons_defineProperties(Constructor.prototype, protoProps); if (staticProps) Buttons_defineProperties(Constructor, staticProps); return Constructor; } var Buttons = /*#__PURE__*/function () { function Buttons(context) { Buttons_classCallCheck(this, Buttons); this.ui = (external_jQuery_default()).summernote.ui; this.context = context; this.$toolbar = context.layoutInfo.toolbar; this.options = context.options; this.lang = this.options.langInfo; this.invertedKeyMap = func.invertObject(this.options.keyMap[env.isMac ? 'mac' : 'pc']); } Buttons_createClass(Buttons, [{ key: "representShortcut", value: function representShortcut(editorMethod) { var shortcut = this.invertedKeyMap[editorMethod]; if (!this.options.shortcuts || !shortcut) { return ''; } if (env.isMac) { shortcut = shortcut.replace('CMD', '⌘').replace('SHIFT', '⇧'); } shortcut = shortcut.replace('BACKSLASH', '\\').replace('SLASH', '/').replace('LEFTBRACKET', '[').replace('RIGHTBRACKET', ']'); return ' (' + shortcut + ')'; } }, { key: "button", value: function button(o) { if (!this.options.tooltip && o.tooltip) { delete o.tooltip; } o.container = this.options.container; return this.ui.button(o); } }, { key: "initialize", value: function initialize() { this.addToolbarButtons(); this.addImagePopoverButtons(); this.addLinkPopoverButtons(); this.addTablePopoverButtons(); this.fontInstalledMap = {}; } }, { key: "destroy", value: function destroy() { delete this.fontInstalledMap; } }, { key: "isFontInstalled", value: function isFontInstalled(name) { if (!Object.prototype.hasOwnProperty.call(this.fontInstalledMap, name)) { this.fontInstalledMap[name] = env.isFontInstalled(name) || lists.contains(this.options.fontNamesIgnoreCheck, name); } return this.fontInstalledMap[name]; } }, { key: "isFontDeservedToAdd", value: function isFontDeservedToAdd(name) { name = name.toLowerCase(); return name !== '' && this.isFontInstalled(name) && env.genericFontFamilies.indexOf(name) === -1; } }, { key: "colorPalette", value: function colorPalette(className, tooltip, backColor, foreColor) { var _this = this; return this.ui.buttonGroup({ className: 'note-color ' + className, children: [this.button({ className: 'note-current-color-button', contents: this.ui.icon(this.options.icons.font + ' note-recent-color'), tooltip: tooltip, click: function click(e) { var $button = external_jQuery_default()(e.currentTarget); if (backColor && foreColor) { _this.context.invoke('editor.color', { backColor: $button.attr('data-backColor'), foreColor: $button.attr('data-foreColor') }); } else if (backColor) { _this.context.invoke('editor.color', { backColor: $button.attr('data-backColor') }); } else if (foreColor) { _this.context.invoke('editor.color', { foreColor: $button.attr('data-foreColor') }); } }, callback: function callback($button) { var $recentColor = $button.find('.note-recent-color'); if (backColor) { $recentColor.css('background-color', _this.options.colorButton.backColor); $button.attr('data-backColor', _this.options.colorButton.backColor); } if (foreColor) { $recentColor.css('color', _this.options.colorButton.foreColor); $button.attr('data-foreColor', _this.options.colorButton.foreColor); } else { $recentColor.css('color', 'transparent'); } } }), this.button({ className: 'dropdown-toggle', contents: this.ui.dropdownButtonContents('', this.options), tooltip: this.lang.color.more, data: { toggle: 'dropdown' } }), this.ui.dropdown({ items: (backColor ? ['<div class="note-palette">', '<div class="note-palette-title">' + this.lang.color.background + '</div>', '<div>', '<button type="button" class="note-color-reset btn btn-light btn-default" data-event="backColor" data-value="transparent">', this.lang.color.transparent, '</button>', '</div>', '<div class="note-holder" data-event="backColor"><!-- back colors --></div>', '<div>', '<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="backColorPicker-' + this.options.id + '">', this.lang.color.cpSelect, '</button>', '<input type="color" id="backColorPicker-' + this.options.id + '" class="note-btn note-color-select-btn" value="' + this.options.colorButton.backColor + '" data-event="backColorPalette-' + this.options.id + '">', '</div>', '<div class="note-holder-custom" id="backColorPalette-' + this.options.id + '" data-event="backColor"></div>', '</div>'].join('') : '') + (foreColor ? ['<div class="note-palette">', '<div class="note-palette-title">' + this.lang.color.foreground + '</div>', '<div>', '<button type="button" class="note-color-reset btn btn-light btn-default" data-event="removeFormat" data-value="foreColor">', this.lang.color.resetToDefault, '</button>', '</div>', '<div class="note-holder" data-event="foreColor"><!-- fore colors --></div>', '<div>', '<button type="button" class="note-color-select btn btn-light btn-default" data-event="openPalette" data-value="foreColorPicker-' + this.options.id + '">', this.lang.color.cpSelect, '</button>', '<input type="color" id="foreColorPicker-' + this.options.id + '" class="note-btn note-color-select-btn" value="' + this.options.colorButton.foreColor + '" data-event="foreColorPalette-' + this.options.id + '">', '</div>', // Fix missing Div, Commented to find easily if it's wrong '<div class="note-holder-custom" id="foreColorPalette-' + this.options.id + '" data-event="foreColor"></div>', '</div>'].join('') : ''), callback: function callback($dropdown) { $dropdown.find('.note-holder').each(function (idx, item) { var $holder = external_jQuery_default()(item); $holder.append(_this.ui.palette({ colors: _this.options.colors, colorsName: _this.options.colorsName, eventName: $holder.data('event'), container: _this.options.container, tooltip: _this.options.tooltip }).render()); }); /* TODO: do we have to record recent custom colors within cookies? */ var customColors = [['#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF']]; $dropdown.find('.note-holder-custom').each(function (idx, item) { var $holder = external_jQuery_default()(item); $holder.append(_this.ui.palette({ colors: customColors, colorsName: customColors, eventName: $holder.data('event'), container: _this.options.container, tooltip: _this.options.tooltip }).render()); }); $dropdown.find('input[type=color]').each(function (idx, item) { external_jQuery_default()(item).change(function () { var $chip = $dropdown.find('#' + external_jQuery_default()(this).data('event')).find('.note-color-btn').first(); var color = this.value.toUpperCase(); $chip.css('background-color', color).attr('aria-label', color).attr('data-value', color).attr('data-original-title', color); $chip.click(); }); }); }, click: function click(event) { event.stopPropagation(); var $parent = external_jQuery_default()('.' + className).find('.note-dropdown-menu'); var $button = external_jQuery_default()(event.target); var eventName = $button.data('event'); var value = $button.attr('data-value'); if (eventName === 'openPalette') { var $picker = $parent.find('#' + value); var $palette = external_jQuery_default()($parent.find('#' + $picker.data('event')).find('.note-color-row')[0]); // Shift palette chips var $chip = $palette.find('.note-color-btn').last().detach(); // Set chip attributes var color = $picker.val(); $chip.css('background-color', color).attr('aria-label', color).attr('data-value', color).attr('data-original-title', color); $palette.prepend($chip); $picker.click(); } else { if (lists.contains(['backColor', 'foreColor'], eventName)) { var key = eventName === 'backColor' ? 'background-color' : 'color'; var $color = $button.closest('.note-color').find('.note-recent-color'); var $currentButton = $button.closest('.note-color').find('.note-current-color-button'); $color.css(key, value); $currentButton.attr('data-' + eventName, value); } _this.context.invoke('editor.' + eventName, value); } } })] }).render(); } }, { key: "addToolbarButtons", value: function addToolbarButtons() { var _this2 = this; this.context.memo('button.style', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.magic), _this2.options), tooltip: _this2.lang.style.style, data: { toggle: 'dropdown' } }), _this2.ui.dropdown({ className: 'dropdown-style', items: _this2.options.styleTags, title: _this2.lang.style.style, template: function template(item) { // TBD: need to be simplified if (typeof item === 'string') { item = { tag: item, title: Object.prototype.hasOwnProperty.call(_this2.lang.style, item) ? _this2.lang.style[item] : item }; } var tag = item.tag; var title = item.title; var style = item.style ? ' style="' + item.style + '" ' : ''; var className = item.className ? ' class="' + item.className + '"' : ''; return '<' + tag + style + className + '>' + title + '</' + tag + '>'; }, click: _this2.context.createInvokeHandler('editor.formatBlock') })]).render(); }); var _loop = function _loop(styleIdx, styleLen) { var item = _this2.options.styleTags[styleIdx]; _this2.context.memo('button.style.' + item, function () { return _this2.button({ className: 'note-btn-style-' + item, contents: '<div data-value="' + item + '">' + item.toUpperCase() + '</div>', tooltip: _this2.lang.style[item], click: _this2.context.createInvokeHandler('editor.formatBlock') }).render(); }); }; for (var styleIdx = 0, styleLen = this.options.styleTags.length; styleIdx < styleLen; styleIdx++) { _loop(styleIdx, styleLen); } this.context.memo('button.bold', function () { return _this2.button({ className: 'note-btn-bold', contents: _this2.ui.icon(_this2.options.icons.bold), tooltip: _this2.lang.font.bold + _this2.representShortcut('bold'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.bold') }).render(); }); this.context.memo('button.italic', function () { return _this2.button({ className: 'note-btn-italic', contents: _this2.ui.icon(_this2.options.icons.italic), tooltip: _this2.lang.font.italic + _this2.representShortcut('italic'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.italic') }).render(); }); this.context.memo('button.underline', function () { return _this2.button({ className: 'note-btn-underline', contents: _this2.ui.icon(_this2.options.icons.underline), tooltip: _this2.lang.font.underline + _this2.representShortcut('underline'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.underline') }).render(); }); this.context.memo('button.clear', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.eraser), tooltip: _this2.lang.font.clear + _this2.representShortcut('removeFormat'), click: _this2.context.createInvokeHandler('editor.removeFormat') }).render(); }); this.context.memo('button.strikethrough', function () { return _this2.button({ className: 'note-btn-strikethrough', contents: _this2.ui.icon(_this2.options.icons.strikethrough), tooltip: _this2.lang.font.strikethrough + _this2.representShortcut('strikethrough'), click: _this2.context.createInvokeHandlerAndUpdateState('editor.strikethrough') }).render(); }); this.context.memo('button.superscript', function () { return _this2.button({ className: 'note-btn-superscript', contents: _this2.ui.icon(_this2.options.icons.superscript), tooltip: _this2.lang.font.superscript, click: _this2.context.createInvokeHandlerAndUpdateState('editor.superscript') }).render(); }); this.context.memo('button.subscript', function () { return _this2.button({ className: 'note-btn-subscript', contents: _this2.ui.icon(_this2.options.icons.subscript), tooltip: _this2.lang.font.subscript, click: _this2.context.createInvokeHandlerAndUpdateState('editor.subscript') }).render(); }); this.context.memo('button.fontname', function () { var styleInfo = _this2.context.invoke('editor.currentStyle'); if (_this2.options.addDefaultFonts) { // Add 'default' fonts into the fontnames array if not exist external_jQuery_default().each(styleInfo['font-family'].split(','), function (idx, fontname) { fontname = fontname.trim().replace(/['"]+/g, ''); if (_this2.isFontDeservedToAdd(fontname)) { if (_this2.options.fontNames.indexOf(fontname) === -1) { _this2.options.fontNames.push(fontname); } } }); } return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontname"></span>', _this2.options), tooltip: _this2.lang.font.name, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontname', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontNames.filter(_this2.isFontInstalled.bind(_this2)), title: _this2.lang.font.name, template: function template(item) { return '<span style="font-family: ' + env.validFontName(item) + '">' + item + '</span>'; }, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontName') })]).render(); }); this.context.memo('button.fontsize', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontsize"></span>', _this2.options), tooltip: _this2.lang.font.size, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontsize', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontSizes, title: _this2.lang.font.size, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontSize') })]).render(); }); this.context.memo('button.fontsizeunit', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents('<span class="note-current-fontsizeunit"></span>', _this2.options), tooltip: _this2.lang.font.sizeunit, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ className: 'dropdown-fontsizeunit', checkClassName: _this2.options.icons.menuCheck, items: _this2.options.fontSizeUnits, title: _this2.lang.font.sizeunit, click: _this2.context.createInvokeHandlerAndUpdateState('editor.fontSizeUnit') })]).render(); }); this.context.memo('button.color', function () { return _this2.colorPalette('note-color-all', _this2.lang.color.recent, true, true); }); this.context.memo('button.forecolor', function () { return _this2.colorPalette('note-color-fore', _this2.lang.color.foreground, false, true); }); this.context.memo('button.backcolor', function () { return _this2.colorPalette('note-color-back', _this2.lang.color.background, true, false); }); this.context.memo('button.ul', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.unorderedlist), tooltip: _this2.lang.lists.unordered + _this2.representShortcut('insertUnorderedList'), click: _this2.context.createInvokeHandler('editor.insertUnorderedList') }).render(); }); this.context.memo('button.ol', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.orderedlist), tooltip: _this2.lang.lists.ordered + _this2.representShortcut('insertOrderedList'), click: _this2.context.createInvokeHandler('editor.insertOrderedList') }).render(); }); var justifyLeft = this.button({ contents: this.ui.icon(this.options.icons.alignLeft), tooltip: this.lang.paragraph.left + this.representShortcut('justifyLeft'), click: this.context.createInvokeHandler('editor.justifyLeft') }); var justifyCenter = this.button({ contents: this.ui.icon(this.options.icons.alignCenter), tooltip: this.lang.paragraph.center + this.representShortcut('justifyCenter'), click: this.context.createInvokeHandler('editor.justifyCenter') }); var justifyRight = this.button({ contents: this.ui.icon(this.options.icons.alignRight), tooltip: this.lang.paragraph.right + this.representShortcut('justifyRight'), click: this.context.createInvokeHandler('editor.justifyRight') }); var justifyFull = this.button({ contents: this.ui.icon(this.options.icons.alignJustify), tooltip: this.lang.paragraph.justify + this.representShortcut('justifyFull'), click: this.context.createInvokeHandler('editor.justifyFull') }); var outdent = this.button({ contents: this.ui.icon(this.options.icons.outdent), tooltip: this.lang.paragraph.outdent + this.representShortcut('outdent'), click: this.context.createInvokeHandler('editor.outdent') }); var indent = this.button({ contents: this.ui.icon(this.options.icons.indent), tooltip: this.lang.paragraph.indent + this.representShortcut('indent'), click: this.context.createInvokeHandler('editor.indent') }); this.context.memo('button.justifyLeft', func.invoke(justifyLeft, 'render')); this.context.memo('button.justifyCenter', func.invoke(justifyCenter, 'render')); this.context.memo('button.justifyRight', func.invoke(justifyRight, 'render')); this.context.memo('button.justifyFull', func.invoke(justifyFull, 'render')); this.context.memo('button.outdent', func.invoke(outdent, 'render')); this.context.memo('button.indent', func.invoke(indent, 'render')); this.context.memo('button.paragraph', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.alignLeft), _this2.options), tooltip: _this2.lang.paragraph.paragraph, data: { toggle: 'dropdown' } }), _this2.ui.dropdown([_this2.ui.buttonGroup({ className: 'note-align', children: [justifyLeft, justifyCenter, justifyRight, justifyFull] }), _this2.ui.buttonGroup({ className: 'note-list', children: [outdent, indent] })])]).render(); }); this.context.memo('button.height', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.textHeight), _this2.options), tooltip: _this2.lang.font.height, data: { toggle: 'dropdown' } }), _this2.ui.dropdownCheck({ items: _this2.options.lineHeights, checkClassName: _this2.options.icons.menuCheck, className: 'dropdown-line-height', title: _this2.lang.font.height, click: _this2.context.createInvokeHandler('editor.lineHeight') })]).render(); }); this.context.memo('button.table', function () { return _this2.ui.buttonGroup([_this2.button({ className: 'dropdown-toggle', contents: _this2.ui.dropdownButtonContents(_this2.ui.icon(_this2.options.icons.table), _this2.options), tooltip: _this2.lang.table.table, data: { toggle: 'dropdown' } }), _this2.ui.dropdown({ title: _this2.lang.table.table, className: 'note-table', items: ['<div class="note-dimension-picker">', '<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>', '<div class="note-dimension-picker-highlighted"></div>', '<div class="note-dimension-picker-unhighlighted"></div>', '</div>', '<div class="note-dimension-display">1 x 1</div>'].join('') })], { callback: function callback($node) { var $catcher = $node.find('.note-dimension-picker-mousecatcher'); $catcher.css({ width: _this2.options.insertTableMaxSize.col + 'em', height: _this2.options.insertTableMaxSize.row + 'em' }).mouseup(_this2.context.createInvokeHandler('editor.insertTable')).on('mousemove', _this2.tableMoveHandler.bind(_this2)); } }).render(); }); this.context.memo('button.link', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.link), tooltip: _this2.lang.link.link + _this2.representShortcut('linkDialog.show'), click: _this2.context.createInvokeHandler('linkDialog.show') }).render(); }); this.context.memo('button.picture', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.picture), tooltip: _this2.lang.image.image, click: _this2.context.createInvokeHandler('imageDialog.show') }).render(); }); this.context.memo('button.video', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.video), tooltip: _this2.lang.video.video, click: _this2.context.createInvokeHandler('videoDialog.show') }).render(); }); this.context.memo('button.hr', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.minus), tooltip: _this2.lang.hr.insert + _this2.representShortcut('insertHorizontalRule'), click: _this2.context.createInvokeHandler('editor.insertHorizontalRule') }).render(); }); this.context.memo('button.fullscreen', function () { return _this2.button({ className: 'btn-fullscreen note-codeview-keep', contents: _this2.ui.icon(_this2.options.icons.arrowsAlt), tooltip: _this2.lang.options.fullscreen, click: _this2.context.createInvokeHandler('fullscreen.toggle') }).render(); }); this.context.memo('button.codeview', function () { return _this2.button({ className: 'btn-codeview note-codeview-keep', contents: _this2.ui.icon(_this2.options.icons.code), tooltip: _this2.lang.options.codeview, click: _this2.context.createInvokeHandler('codeview.toggle') }).render(); }); this.context.memo('button.redo', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.redo), tooltip: _this2.lang.history.redo + _this2.representShortcut('redo'), click: _this2.context.createInvokeHandler('editor.redo') }).render(); }); this.context.memo('button.undo', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.undo), tooltip: _this2.lang.history.undo + _this2.representShortcut('undo'), click: _this2.context.createInvokeHandler('editor.undo') }).render(); }); this.context.memo('button.help', function () { return _this2.button({ contents: _this2.ui.icon(_this2.options.icons.question), tooltip: _this2.lang.options.help, click: _this2.context.createInvokeHandler('helpDialog.show') }).render(); }); } /** * image: [ * ['imageResize', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']], * ['float', ['floatLeft', 'floatRight', 'floatNone']], * ['remove', ['removeMedia']], * ], */ }, { key: "addImagePopoverButtons", value: function addImagePopoverButtons() { var _this3 = this; // Image Size Buttons this.context.memo('button.resizeFull', function () { return _this3.button({ contents: '<span class="note-fontsize-10">100%</span>', tooltip: _this3.lang.image.resizeFull, click: _this3.context.createInvokeHandler('editor.resize', '1') }).render(); }); this.context.memo('button.resizeHalf', function () { return _this3.button({ contents: '<span class="note-fontsize-10">50%</span>', tooltip: _this3.lang.image.resizeHalf, click: _this3.context.createInvokeHandler('editor.resize', '0.5') }).render(); }); this.context.memo('button.resizeQuarter', function () { return _this3.button({ contents: '<span class="note-fontsize-10">25%</span>', tooltip: _this3.lang.image.resizeQuarter, click: _this3.context.createInvokeHandler('editor.resize', '0.25') }).render(); }); this.context.memo('button.resizeNone', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.rollback), tooltip: _this3.lang.image.resizeNone, click: _this3.context.createInvokeHandler('editor.resize', '0') }).render(); }); // Float Buttons this.context.memo('button.floatLeft', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.floatLeft), tooltip: _this3.lang.image.floatLeft, click: _this3.context.createInvokeHandler('editor.floatMe', 'left') }).render(); }); this.context.memo('button.floatRight', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.floatRight), tooltip: _this3.lang.image.floatRight, click: _this3.context.createInvokeHandler('editor.floatMe', 'right') }).render(); }); this.context.memo('button.floatNone', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.rollback), tooltip: _this3.lang.image.floatNone, click: _this3.context.createInvokeHandler('editor.floatMe', 'none') }).render(); }); // Remove Buttons this.context.memo('button.removeMedia', function () { return _this3.button({ contents: _this3.ui.icon(_this3.options.icons.trash), tooltip: _this3.lang.image.remove, click: _this3.context.createInvokeHandler('editor.removeMedia') }).render(); }); } }, { key: "addLinkPopoverButtons", value: function addLinkPopoverButtons() { var _this4 = this; this.context.memo('button.linkDialogShow', function () { return _this4.button({ contents: _this4.ui.icon(_this4.options.icons.link), tooltip: _this4.lang.link.edit, click: _this4.context.createInvokeHandler('linkDialog.show') }).render(); }); this.context.memo('button.unlink', function () { return _this4.button({ contents: _this4.ui.icon(_this4.options.icons.unlink), tooltip: _this4.lang.link.unlink, click: _this4.context.createInvokeHandler('editor.unlink') }).render(); }); } /** * table : [ * ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']], * ['delete', ['deleteRow', 'deleteCol', 'deleteTable']] * ], */ }, { key: "addTablePopoverButtons", value: function addTablePopoverButtons() { var _this5 = this; this.context.memo('button.addRowUp', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowAbove), tooltip: _this5.lang.table.addRowAbove, click: _this5.context.createInvokeHandler('editor.addRow', 'top') }).render(); }); this.context.memo('button.addRowDown', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowBelow), tooltip: _this5.lang.table.addRowBelow, click: _this5.context.createInvokeHandler('editor.addRow', 'bottom') }).render(); }); this.context.memo('button.addColLeft', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colBefore), tooltip: _this5.lang.table.addColLeft, click: _this5.context.createInvokeHandler('editor.addCol', 'left') }).render(); }); this.context.memo('button.addColRight', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colAfter), tooltip: _this5.lang.table.addColRight, click: _this5.context.createInvokeHandler('editor.addCol', 'right') }).render(); }); this.context.memo('button.deleteRow', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.rowRemove), tooltip: _this5.lang.table.delRow, click: _this5.context.createInvokeHandler('editor.deleteRow') }).render(); }); this.context.memo('button.deleteCol', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.colRemove), tooltip: _this5.lang.table.delCol, click: _this5.context.createInvokeHandler('editor.deleteCol') }).render(); }); this.context.memo('button.deleteTable', function () { return _this5.button({ className: 'btn-md', contents: _this5.ui.icon(_this5.options.icons.trash), tooltip: _this5.lang.table.delTable, click: _this5.context.createInvokeHandler('editor.deleteTable') }).render(); }); } }, { key: "build", value: function build($container, groups) { for (var groupIdx = 0, groupLen = groups.length; groupIdx < groupLen; groupIdx++) { var group = groups[groupIdx]; var groupName = Array.isArray(group) ? group[0] : group; var buttons = Array.isArray(group) ? group.length === 1 ? [group[0]] : group[1] : [group]; var $group = this.ui.buttonGroup({ className: 'note-' + groupName }).render(); for (var idx = 0, len = buttons.length; idx < len; idx++) { var btn = this.context.memo('button.' + buttons[idx]); if (btn) { $group.append(typeof btn === 'function' ? btn(this.context) : btn); } } $group.appendTo($container); } } /** * @param {jQuery} [$container] */ }, { key: "updateCurrentStyle", value: function updateCurrentStyle($container) { var $cont = $container || this.$toolbar; var styleInfo = this.context.invoke('editor.currentStyle'); this.updateBtnStates($cont, { '.note-btn-bold': function noteBtnBold() { return styleInfo['font-bold'] === 'bold'; }, '.note-btn-italic': function noteBtnItalic() { return styleInfo['font-italic'] === 'italic'; }, '.note-btn-underline': function noteBtnUnderline() { return styleInfo['font-underline'] === 'underline'; }, '.note-btn-subscript': function noteBtnSubscript() { return styleInfo['font-subscript'] === 'subscript'; }, '.note-btn-superscript': function noteBtnSuperscript() { return styleInfo['font-superscript'] === 'superscript'; }, '.note-btn-strikethrough': function noteBtnStrikethrough() { return styleInfo['font-strikethrough'] === 'strikethrough'; } }); if (styleInfo['font-family']) { var fontNames = styleInfo['font-family'].split(',').map(function (name) { return name.replace(/[\'\"]/g, '').replace(/\s+$/, '').replace(/^\s+/, ''); }); var fontName = lists.find(fontNames, this.isFontInstalled.bind(this)); $cont.find('.dropdown-fontname a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare string to avoid creating another func. var isChecked = $item.data('value') + '' === fontName + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontname').text(fontName).css('font-family', fontName); } if (styleInfo['font-size']) { var fontSize = styleInfo['font-size']; $cont.find('.dropdown-fontsize a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare with string to avoid creating another func. var isChecked = $item.data('value') + '' === fontSize + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontsize').text(fontSize); var fontSizeUnit = styleInfo['font-size-unit']; $cont.find('.dropdown-fontsizeunit a').each(function (idx, item) { var $item = external_jQuery_default()(item); var isChecked = $item.data('value') + '' === fontSizeUnit + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-fontsizeunit').text(fontSizeUnit); } if (styleInfo['line-height']) { var lineHeight = styleInfo['line-height']; $cont.find('.dropdown-line-height a').each(function (idx, item) { var $item = external_jQuery_default()(item); // always compare with string to avoid creating another func. var isChecked = external_jQuery_default()(item).data('value') + '' === lineHeight + ''; $item.toggleClass('checked', isChecked); }); $cont.find('.note-current-line-height').text(lineHeight); } } }, { key: "updateBtnStates", value: function updateBtnStates($container, infos) { var _this6 = this; external_jQuery_default().each(infos, function (selector, pred) { _this6.ui.toggleBtnActive($container.find(selector), pred()); }); } }, { key: "tableMoveHandler", value: function tableMoveHandler(event) { var PX_PER_EM = 18; var $picker = external_jQuery_default()(event.target.parentNode); // target is mousecatcher var $dimensionDisplay = $picker.next(); var $catcher = $picker.find('.note-dimension-picker-mousecatcher'); var $highlighted = $picker.find('.note-dimension-picker-highlighted'); var $unhighlighted = $picker.find('.note-dimension-picker-unhighlighted'); var posOffset; // HTML5 with jQuery - e.offsetX is undefined in Firefox if (event.offsetX === undefined) { var posCatcher = external_jQuery_default()(event.target).offset(); posOffset = { x: event.pageX - posCatcher.left, y: event.pageY - posCatcher.top }; } else { posOffset = { x: event.offsetX, y: event.offsetY }; } var dim = { c: Math.ceil(posOffset.x / PX_PER_EM) || 1, r: Math.ceil(posOffset.y / PX_PER_EM) || 1 }; $highlighted.css({ width: dim.c + 'em', height: dim.r + 'em' }); $catcher.data('value', dim.c + 'x' + dim.r); if (dim.c > 3 && dim.c < this.options.insertTableMaxSize.col) { $unhighlighted.css({ width: dim.c + 1 + 'em' }); } if (dim.r > 3 && dim.r < this.options.insertTableMaxSize.row) { $unhighlighted.css({ height: dim.r + 1 + 'em' }); } $dimensionDisplay.html(dim.c + ' x ' + dim.r); } }]); return Buttons; }(); ;// CONCATENATED MODULE: ./src/js/module/Toolbar.js function Toolbar_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function Toolbar_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function Toolbar_createClass(Constructor, protoProps, staticProps) { if (protoProps) Toolbar_defineProperties(Constructor.prototype, protoProps); if (staticProps) Toolbar_defineProperties(Constructor, staticProps); return Constructor; } var Toolbar = /*#__PURE__*/function () { function Toolbar(context) { Toolbar_classCallCheck(this, Toolbar); this.context = context; this.$window = external_jQuery_default()(window); this.$document = external_jQuery_default()(document); this.ui = (external_jQuery_default()).summernote.ui; this.$note = context.layoutInfo.note; this.$editor = context.layoutInfo.editor; this.$toolbar = context.layoutInfo.toolbar; this.$editable = context.layoutInfo.editable; this.$statusbar = context.layoutInfo.statusbar; this.options = context.options; this.isFollowing = false; this.followScroll = this.followScroll.bind(this); } Toolbar_createClass(Toolbar, [{ key: "shouldInitialize", value: function shouldInitialize() { return !this.options.airMode; } }, { key: "initialize", value: function initialize() { var _this = this; this.options.toolbar = this.options.toolbar || []; if (!this.options.toolbar.length) { this.$toolbar.hide(); } else { this.context.invoke('buttons.build', this.$toolbar, this.options.toolbar); } if (this.options.toolbarContainer) { this.$toolbar.appendTo(this.options.toolbarContainer); } this.changeContainer(false); this.$note.on('summernote.keyup summernote.mouseup summernote.change', function () { _this.context.invoke('buttons.updateCurrentStyle'); }); this.context.invoke('buttons.updateCurrentStyle'); if (this.options.followingToolbar) { this.$window.on('scroll resize', this.followScroll); } } }, { key: "destroy", value: function destroy() { this.$toolbar.children().remove(); if (this.options.followingToolbar) { this.$window.off('scroll resize', this.followScroll); } } }, { key: "followScroll", value: function followScroll() { if (this.$editor.hasClass('fullscreen')) { return false; } var editorHeight = this.$editor.outerHeight(); var editorWidth = this.$editor.width(); var toolbarHeight = this.$toolbar.height(); var statusbarHeight = this.$statusbar.height(); // check if the web app is currently using another static bar var otherBarHeight = 0; if (this.options.otherStaticBar) { otherBarHeight = external_jQuery_default()(this.options.otherStaticBar).outerHeight(); } var currentOffset = this.$document.scrollTop(); var editorOffsetTop = this.$editor.offset().top; var editorOffsetBottom = editorOffsetTop + editorHeight; var activateOffset = editorOffsetTop - otherBarHeight; var deactivateOffsetBottom = editorOffsetBottom - otherBarHeight - toolbarHeight - statusbarHeight; if (!this.isFollowing && currentOffset > activateOffset && currentOffset < deactivateOffsetBottom - toolbarHeight) { this.isFollowing = true; this.$editable.css({ marginTop: this.$toolbar.outerHeight() }); this.$toolbar.css({ position: 'fixed', top: otherBarHeight, width: editorWidth, zIndex: 1000 }); } else if (this.isFollowing && (currentOffset < activateOffset || currentOffset > deactivateOffsetBottom)) { this.isFollowing = false; this.$toolbar.css({ position: 'relative', top: 0, width: '100%', zIndex: 'auto' }); this.$editable.css({ marginTop: '' }); } } }, { key: "changeContainer", value: function changeContainer(isFullscreen) { if (isFullscreen) { this.$toolbar.prependTo(this.$editor); } else { if (this.options.toolbarContainer) { this.$toolbar.appendTo(this.options.toolbarContainer); } } if (this.options.followingToolbar) { this.followScroll(); } } }, { key: "updateFullscreen", value: function updateFullscreen(isFullscreen) { this.ui.toggleBtnActive(this.$toolbar.find('.btn-fullscreen'), isFullscreen); this.changeContainer(isFullscreen); } }, { key: "updateCodeview", value: function updateCodeview(isCodeview) { this.ui.toggleBtnActive(this.$toolbar.find('.btn-codeview'), isCodeview); if (isCodeview) { this.deactivate(); } else { this.activate(); } } }, { key: "activate", value: function activate(isIncludeCodeview) { var $btn = this.$toolbar.find('button'); if (!isIncludeCodeview) { $btn = $btn.not('.note-codeview-keep'); } this.ui.toggleBtn($btn, true); } }, { key: "deactivate", value: function deactivate(isIncludeCodeview) { var $btn = this.$toolbar.find('button'); if (!isIncludeCodeview) { $btn = $btn.not('.note-codeview-keep'); } this.ui.toggleBtn($btn, false); } }]); return Toolbar; }(); ;// CONCATENATED MODULE: ./src/js/module/LinkDialog.js function LinkDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function LinkDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function LinkDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) LinkDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) LinkDialog_defineProperties(Constructor, staticProps); return Constructor; } var LinkDialog = /*#__PURE__*/function () { function LinkDialog(context) { LinkDialog_classCallCheck(this, LinkDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; context.memo('help.linkDialog.show', this.options.langInfo.help['linkDialog.show']); } LinkDialog_createClass(LinkDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group">', "<label for=\"note-dialog-link-txt-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.link.textToDisplay, "</label>"), "<input id=\"note-dialog-link-txt-".concat(this.options.id, "\" class=\"note-link-text form-control note-form-control note-input\" type=\"text\"/>"), '</div>', '<div class="form-group note-form-group">', "<label for=\"note-dialog-link-url-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.link.url, "</label>"), "<input id=\"note-dialog-link-url-".concat(this.options.id, "\" class=\"note-link-url form-control note-form-control note-input\" type=\"text\" value=\"http://\"/>"), '</div>', !this.options.disableLinkTarget ? external_jQuery_default()('<div></div>').append(this.ui.checkbox({ className: 'sn-checkbox-open-in-new-window', text: this.lang.link.openInNewWindow, checked: true }).render()).html() : '', external_jQuery_default()('<div></div>').append(this.ui.checkbox({ className: 'sn-checkbox-use-protocol', text: this.lang.link.useProtocol, checked: true }).render()).html()].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-link-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.link.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ className: 'link-dialog', title: this.lang.link.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } /** * toggle update button */ }, { key: "toggleLinkBtn", value: function toggleLinkBtn($linkBtn, $linkText, $linkUrl) { this.ui.toggleBtn($linkBtn, $linkText.val() && $linkUrl.val()); } /** * Show link dialog and set event handlers on dialog controls. * * @param {Object} linkInfo * @return {Promise} */ }, { key: "showLinkDialog", value: function showLinkDialog(linkInfo) { var _this = this; return external_jQuery_default().Deferred(function (deferred) { var $linkText = _this.$dialog.find('.note-link-text'); var $linkUrl = _this.$dialog.find('.note-link-url'); var $linkBtn = _this.$dialog.find('.note-link-btn'); var $openInNewWindow = _this.$dialog.find('.sn-checkbox-open-in-new-window input[type=checkbox]'); var $useProtocol = _this.$dialog.find('.sn-checkbox-use-protocol input[type=checkbox]'); _this.ui.onDialogShown(_this.$dialog, function () { _this.context.triggerEvent('dialog.shown'); // If no url was given and given text is valid URL then copy that into URL Field if (!linkInfo.url && func.isValidUrl(linkInfo.text)) { linkInfo.url = linkInfo.text; } $linkText.on('input paste propertychange', function () { // If linktext was modified by input events, // cloning text from linkUrl will be stopped. linkInfo.text = $linkText.val(); _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); }).val(linkInfo.text); $linkUrl.on('input paste propertychange', function () { // Display same text on `Text to display` as default // when linktext has no text if (!linkInfo.text) { $linkText.val($linkUrl.val()); } _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); }).val(linkInfo.url); if (!env.isSupportTouch) { $linkUrl.trigger('focus'); } _this.toggleLinkBtn($linkBtn, $linkText, $linkUrl); _this.bindEnterKey($linkUrl, $linkBtn); _this.bindEnterKey($linkText, $linkBtn); var isNewWindowChecked = linkInfo.isNewWindow !== undefined ? linkInfo.isNewWindow : _this.context.options.linkTargetBlank; $openInNewWindow.prop('checked', isNewWindowChecked); var useProtocolChecked = linkInfo.url ? false : _this.context.options.useProtocol; $useProtocol.prop('checked', useProtocolChecked); $linkBtn.one('click', function (event) { event.preventDefault(); deferred.resolve({ range: linkInfo.range, url: $linkUrl.val(), text: $linkText.val(), isNewWindow: $openInNewWindow.is(':checked'), checkProtocol: $useProtocol.is(':checked') }); _this.ui.hideDialog(_this.$dialog); }); }); _this.ui.onDialogHidden(_this.$dialog, function () { // detach events $linkText.off(); $linkUrl.off(); $linkBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this.ui.showDialog(_this.$dialog); }).promise(); } /** * @param {Object} layoutInfo */ }, { key: "show", value: function show() { var _this2 = this; var linkInfo = this.context.invoke('editor.getLinkInfo'); this.context.invoke('editor.saveRange'); this.showLinkDialog(linkInfo).then(function (linkInfo) { _this2.context.invoke('editor.restoreRange'); _this2.context.invoke('editor.createLink', linkInfo); }).fail(function () { _this2.context.invoke('editor.restoreRange'); }); } }]); return LinkDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/LinkPopover.js function LinkPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function LinkPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function LinkPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) LinkPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) LinkPopover_defineProperties(Constructor, staticProps); return Constructor; } var LinkPopover = /*#__PURE__*/function () { function LinkPopover(context) { var _this = this; LinkPopover_classCallCheck(this, LinkPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.events = { 'summernote.keyup summernote.mouseup summernote.change summernote.scroll': function summernoteKeyupSummernoteMouseupSummernoteChangeSummernoteScroll() { _this.update(); }, 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } LinkPopover_createClass(LinkPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.link); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-link-popover', callback: function callback($node) { var $content = $node.find('.popover-content,.note-popover-content'); $content.prepend('<span><a target="_blank"></a>&nbsp;</span>'); } }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.link); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update() { // Prevent focusing on editable when invoke('code') is executed if (!this.context.invoke('editor.hasFocus')) { this.hide(); return; } var rng = this.context.invoke('editor.getLastRange'); if (rng.isCollapsed() && rng.isOnAnchor()) { var anchor = dom.ancestor(rng.sc, dom.isAnchor); var href = external_jQuery_default()(anchor).attr('href'); this.$popover.find('a').attr('href', href).text(href); var pos = dom.posFromPlaceholder(anchor); var containerOffset = external_jQuery_default()(this.options.container).offset(); pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return LinkPopover; }(); ;// CONCATENATED MODULE: ./src/js/module/ImageDialog.js function ImageDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function ImageDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function ImageDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) ImageDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) ImageDialog_defineProperties(Constructor, staticProps); return Constructor; } var ImageDialog = /*#__PURE__*/function () { function ImageDialog(context) { ImageDialog_classCallCheck(this, ImageDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } ImageDialog_createClass(ImageDialog, [{ key: "initialize", value: function initialize() { var imageLimitation = ''; if (this.options.maximumImageFileSize) { var unit = Math.floor(Math.log(this.options.maximumImageFileSize) / Math.log(1024)); var readableSize = (this.options.maximumImageFileSize / Math.pow(1024, unit)).toFixed(2) * 1 + ' ' + ' KMGTP'[unit] + 'B'; imageLimitation = "<small>".concat(this.lang.image.maximumFileSize + ' : ' + readableSize, "</small>"); } var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group note-group-select-from-files">', '<label for="note-dialog-image-file-' + this.options.id + '" class="note-form-label">' + this.lang.image.selectFromFiles + '</label>', '<input id="note-dialog-image-file-' + this.options.id + '" class="note-image-input form-control-file note-form-control note-input" ', ' type="file" name="files" accept="' + this.options.acceptImageFileTypes + '" multiple="multiple"/>', imageLimitation, '</div>', '<div class="form-group note-group-image-url">', '<label for="note-dialog-image-url-' + this.options.id + '" class="note-form-label">' + this.lang.image.url + '</label>', '<input id="note-dialog-image-url-' + this.options.id + '" class="note-image-url form-control note-form-control note-input" type="text"/>', '</div>'].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-image-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.image.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ title: this.lang.image.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } }, { key: "show", value: function show() { var _this = this; this.context.invoke('editor.saveRange'); this.showImageDialog().then(function (data) { // [workaround] hide dialog before restore range for IE range focus _this.ui.hideDialog(_this.$dialog); _this.context.invoke('editor.restoreRange'); if (typeof data === 'string') { // image url // If onImageLinkInsert set, if (_this.options.callbacks.onImageLinkInsert) { _this.context.triggerEvent('image.link.insert', data); } else { _this.context.invoke('editor.insertImage', data); } } else { // array of files _this.context.invoke('editor.insertImagesOrCallback', data); } }).fail(function () { _this.context.invoke('editor.restoreRange'); }); } /** * show image dialog * * @param {jQuery} $dialog * @return {Promise} */ }, { key: "showImageDialog", value: function showImageDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { var $imageInput = _this2.$dialog.find('.note-image-input'); var $imageUrl = _this2.$dialog.find('.note-image-url'); var $imageBtn = _this2.$dialog.find('.note-image-btn'); _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); // Cloning imageInput to clear element. $imageInput.replaceWith($imageInput.clone().on('change', function (event) { deferred.resolve(event.target.files || event.target.value); }).val('')); $imageUrl.on('input paste propertychange', function () { _this2.ui.toggleBtn($imageBtn, $imageUrl.val()); }).val(''); if (!env.isSupportTouch) { $imageUrl.trigger('focus'); } $imageBtn.click(function (event) { event.preventDefault(); deferred.resolve($imageUrl.val()); }); _this2.bindEnterKey($imageUrl, $imageBtn); }); _this2.ui.onDialogHidden(_this2.$dialog, function () { $imageInput.off(); $imageUrl.off(); $imageBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this2.ui.showDialog(_this2.$dialog); }); } }]); return ImageDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/ImagePopover.js function ImagePopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function ImagePopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function ImagePopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) ImagePopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) ImagePopover_defineProperties(Constructor, staticProps); return Constructor; } /** * Image popover module * mouse events that show/hide popover will be handled by Handle.js. * Handle.js will receive the events and invoke 'imagePopover.update'. */ var ImagePopover = /*#__PURE__*/function () { function ImagePopover(context) { var _this = this; ImagePopover_classCallCheck(this, ImagePopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.editable = context.layoutInfo.editable[0]; this.options = context.options; this.events = { 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } ImagePopover_createClass(ImagePopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.image); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-image-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.image); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(target, event) { if (dom.isImg(target)) { var position = external_jQuery_default()(target).offset(); var containerOffset = external_jQuery_default()(this.options.container).offset(); var pos = {}; if (this.options.popatmouse) { pos.left = event.pageX - 20; pos.top = event.pageY; } else { pos = position; } pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return ImagePopover; }(); ;// CONCATENATED MODULE: ./src/js/module/TablePopover.js function TablePopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function TablePopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function TablePopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) TablePopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) TablePopover_defineProperties(Constructor, staticProps); return Constructor; } var TablePopover = /*#__PURE__*/function () { function TablePopover(context) { var _this = this; TablePopover_classCallCheck(this, TablePopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.events = { 'summernote.mousedown': function summernoteMousedown(we, e) { _this.update(e.target); }, 'summernote.keyup summernote.scroll summernote.change': function summernoteKeyupSummernoteScrollSummernoteChange() { _this.update(); }, 'summernote.disable summernote.dialog.shown': function summernoteDisableSummernoteDialogShown() { _this.hide(); }, 'summernote.blur': function summernoteBlur(we, e) { if (e.originalEvent && e.originalEvent.relatedTarget) { if (!_this.$popover[0].contains(e.originalEvent.relatedTarget)) { _this.hide(); } } else { _this.hide(); } } }; } TablePopover_createClass(TablePopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return !lists.isEmpty(this.options.popover.table); } }, { key: "initialize", value: function initialize() { this.$popover = this.ui.popover({ className: 'note-table-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content,.note-popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.table); // [workaround] Disable Firefox's default table editor if (env.isFF) { document.execCommand('enableInlineTableEditing', false, false); } this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(target) { if (this.context.isDisabled()) { return false; } var isCell = dom.isCell(target) || dom.isCell(target === null || target === void 0 ? void 0 : target.parentElement); if (isCell) { var pos = dom.posFromPlaceholder(target); var containerOffset = external_jQuery_default()(this.options.container).offset(); pos.top -= containerOffset.top; pos.left -= containerOffset.left; this.$popover.css({ display: 'block', left: pos.left, top: pos.top }); } else { this.hide(); } return isCell; } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return TablePopover; }(); ;// CONCATENATED MODULE: ./src/js/module/VideoDialog.js function VideoDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function VideoDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function VideoDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) VideoDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) VideoDialog_defineProperties(Constructor, staticProps); return Constructor; } var VideoDialog = /*#__PURE__*/function () { function VideoDialog(context) { VideoDialog_classCallCheck(this, VideoDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } VideoDialog_createClass(VideoDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<div class="form-group note-form-group row-fluid">', "<label for=\"note-dialog-video-url-".concat(this.options.id, "\" class=\"note-form-label\">").concat(this.lang.video.url, " <small class=\"text-muted\">").concat(this.lang.video.providers, "</small></label>"), "<input id=\"note-dialog-video-url-".concat(this.options.id, "\" class=\"note-video-url form-control note-form-control note-input\" type=\"text\"/>"), '</div>'].join(''); var buttonClass = 'btn btn-primary note-btn note-btn-primary note-video-btn'; var footer = "<input type=\"button\" href=\"#\" class=\"".concat(buttonClass, "\" value=\"").concat(this.lang.video.insert, "\" disabled>"); this.$dialog = this.ui.dialog({ title: this.lang.video.insert, fade: this.options.dialogsFade, body: body, footer: footer }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "bindEnterKey", value: function bindEnterKey($input, $btn) { $input.on('keypress', function (event) { if (event.keyCode === key.code.ENTER) { event.preventDefault(); $btn.trigger('click'); } }); } }, { key: "createVideoNode", value: function createVideoNode(url) { // video url patterns(youtube, instagram, vimeo, dailymotion, youku, peertube, mp4, ogg, webm) var ytRegExp = /\/\/(?:(?:www|m)\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))([\w|-]{11})(?:(?:[\?&]t=)(\S+))?$/; var ytRegExpForStart = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/; var ytMatch = url.match(ytRegExp); var gdRegExp = /(?:\.|\/\/)drive\.google\.com\/file\/d\/(.[a-zA-Z0-9_-]*)\/view/; var gdMatch = url.match(gdRegExp); var igRegExp = /(?:www\.|\/\/)instagram\.com\/p\/(.[a-zA-Z0-9_-]*)/; var igMatch = url.match(igRegExp); var vRegExp = /\/\/vine\.co\/v\/([a-zA-Z0-9]+)/; var vMatch = url.match(vRegExp); var vimRegExp = /\/\/(player\.)?vimeo\.com\/([a-z]*\/)*(\d+)[?]?.*/; var vimMatch = url.match(vimRegExp); var dmRegExp = /.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/; var dmMatch = url.match(dmRegExp); var youkuRegExp = /\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/; var youkuMatch = url.match(youkuRegExp); var peerTubeRegExp = /\/\/(.*)\/videos\/watch\/([^?]*)(?:\?(?:start=(\w*))?(?:&stop=(\w*))?(?:&loop=([10]))?(?:&autoplay=([10]))?(?:&muted=([10]))?)?/; var peerTubeMatch = url.match(peerTubeRegExp); var qqRegExp = /\/\/v\.qq\.com.*?vid=(.+)/; var qqMatch = url.match(qqRegExp); var qqRegExp2 = /\/\/v\.qq\.com\/x?\/?(page|cover).*?\/([^\/]+)\.html\??.*/; var qqMatch2 = url.match(qqRegExp2); var mp4RegExp = /^.+.(mp4|m4v)$/; var mp4Match = url.match(mp4RegExp); var oggRegExp = /^.+.(ogg|ogv)$/; var oggMatch = url.match(oggRegExp); var webmRegExp = /^.+.(webm)$/; var webmMatch = url.match(webmRegExp); var fbRegExp = /(?:www\.|\/\/)facebook\.com\/([^\/]+)\/videos\/([0-9]+)/; var fbMatch = url.match(fbRegExp); var $video; if (ytMatch && ytMatch[1].length === 11) { var youtubeId = ytMatch[1]; var start = 0; if (typeof ytMatch[2] !== 'undefined') { var ytMatchForStart = ytMatch[2].match(ytRegExpForStart); if (ytMatchForStart) { for (var n = [3600, 60, 1], i = 0, r = n.length; i < r; i++) { start += typeof ytMatchForStart[i + 1] !== 'undefined' ? n[i] * parseInt(ytMatchForStart[i + 1], 10) : 0; } } } $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', '//www.youtube.com/embed/' + youtubeId + (start > 0 ? '?start=' + start : '')).attr('width', '640').attr('height', '360'); } else if (gdMatch && gdMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://drive.google.com/file/d/' + gdMatch[1] + '/preview').attr('width', '640').attr('height', '480'); } else if (igMatch && igMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://instagram.com/p/' + igMatch[1] + '/embed/').attr('width', '612').attr('height', '710').attr('scrolling', 'no').attr('allowtransparency', 'true'); } else if (vMatch && vMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', vMatch[0] + '/embed/simple').attr('width', '600').attr('height', '600').attr('class', 'vine-embed'); } else if (vimMatch && vimMatch[3].length) { $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('src', '//player.vimeo.com/video/' + vimMatch[3]).attr('width', '640').attr('height', '360'); } else if (dmMatch && dmMatch[2].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', '//www.dailymotion.com/embed/video/' + dmMatch[2]).attr('width', '640').attr('height', '360'); } else if (youkuMatch && youkuMatch[1].length) { $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('height', '498').attr('width', '510').attr('src', '//player.youku.com/embed/' + youkuMatch[1]); } else if (peerTubeMatch && peerTubeMatch[0].length) { var begin = 0; if (peerTubeMatch[2] !== 'undefined') begin = peerTubeMatch[2]; var end = 0; if (peerTubeMatch[3] !== 'undefined') end = peerTubeMatch[3]; var loop = 0; if (peerTubeMatch[4] !== 'undefined') loop = peerTubeMatch[4]; var autoplay = 0; if (peerTubeMatch[5] !== 'undefined') autoplay = peerTubeMatch[5]; var muted = 0; if (peerTubeMatch[6] !== 'undefined') muted = peerTubeMatch[6]; $video = external_jQuery_default()('<iframe allowfullscreen sandbox="allow-same-origin allow-scripts allow-popups">').attr('frameborder', 0).attr('src', '//' + peerTubeMatch[1] + '/videos/embed/' + peerTubeMatch[2] + "?loop=" + loop + "&autoplay=" + autoplay + "&muted=" + muted + (begin > 0 ? '&start=' + begin : '') + (end > 0 ? '&end=' + start : '')).attr('width', '560').attr('height', '315'); } else if (qqMatch && qqMatch[1].length || qqMatch2 && qqMatch2[2].length) { var vid = qqMatch && qqMatch[1].length ? qqMatch[1] : qqMatch2[2]; $video = external_jQuery_default()('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>').attr('frameborder', 0).attr('height', '310').attr('width', '500').attr('src', 'https://v.qq.com/txp/iframe/player.html?vid=' + vid + '&amp;auto=0'); } else if (mp4Match || oggMatch || webmMatch) { $video = external_jQuery_default()('<video controls>').attr('src', url).attr('width', '640').attr('height', '360'); } else if (fbMatch && fbMatch[0].length) { $video = external_jQuery_default()('<iframe>').attr('frameborder', 0).attr('src', 'https://www.facebook.com/plugins/video.php?href=' + encodeURIComponent(fbMatch[0]) + '&show_text=0&width=560').attr('width', '560').attr('height', '301').attr('scrolling', 'no').attr('allowtransparency', 'true'); } else { // this is not a known video link. Now what, Cat? Now what? return false; } $video.addClass('note-video-clip'); return $video[0]; } }, { key: "show", value: function show() { var _this = this; var text = this.context.invoke('editor.getSelectedText'); this.context.invoke('editor.saveRange'); this.showVideoDialog(text).then(function (url) { // [workaround] hide dialog before restore range for IE range focus _this.ui.hideDialog(_this.$dialog); _this.context.invoke('editor.restoreRange'); // build node var $node = _this.createVideoNode(url); if ($node) { // insert video node _this.context.invoke('editor.insertNode', $node); } }).fail(function () { _this.context.invoke('editor.restoreRange'); }); } /** * show video dialog * * @param {jQuery} $dialog * @return {Promise} */ }, { key: "showVideoDialog", value: function showVideoDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { var $videoUrl = _this2.$dialog.find('.note-video-url'); var $videoBtn = _this2.$dialog.find('.note-video-btn'); _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); $videoUrl.on('input paste propertychange', function () { _this2.ui.toggleBtn($videoBtn, $videoUrl.val()); }); if (!env.isSupportTouch) { $videoUrl.trigger('focus'); } $videoBtn.click(function (event) { event.preventDefault(); deferred.resolve($videoUrl.val()); }); _this2.bindEnterKey($videoUrl, $videoBtn); }); _this2.ui.onDialogHidden(_this2.$dialog, function () { $videoUrl.off(); $videoBtn.off(); if (deferred.state() === 'pending') { deferred.reject(); } }); _this2.ui.showDialog(_this2.$dialog); }); } }]); return VideoDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/HelpDialog.js function HelpDialog_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function HelpDialog_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function HelpDialog_createClass(Constructor, protoProps, staticProps) { if (protoProps) HelpDialog_defineProperties(Constructor.prototype, protoProps); if (staticProps) HelpDialog_defineProperties(Constructor, staticProps); return Constructor; } var HelpDialog = /*#__PURE__*/function () { function HelpDialog(context) { HelpDialog_classCallCheck(this, HelpDialog); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$body = external_jQuery_default()(document.body); this.$editor = context.layoutInfo.editor; this.options = context.options; this.lang = this.options.langInfo; } HelpDialog_createClass(HelpDialog, [{ key: "initialize", value: function initialize() { var $container = this.options.dialogsInBody ? this.$body : this.options.container; var body = ['<p class="text-center">', '<a href="http://summernote.org/" target="_blank" rel="noopener noreferrer">Summernote 0.8.20</a> · ', '<a href="https://github.com/summernote/summernote" target="_blank" rel="noopener noreferrer">Project</a> · ', '<a href="https://github.com/summernote/summernote/issues" target="_blank" rel="noopener noreferrer">Issues</a>', '</p>'].join(''); this.$dialog = this.ui.dialog({ title: this.lang.options.help, fade: this.options.dialogsFade, body: this.createShortcutList(), footer: body, callback: function callback($node) { $node.find('.modal-body,.note-modal-body').css({ 'max-height': 300, 'overflow': 'scroll' }); } }).render().appendTo($container); } }, { key: "destroy", value: function destroy() { this.ui.hideDialog(this.$dialog); this.$dialog.remove(); } }, { key: "createShortcutList", value: function createShortcutList() { var _this = this; var keyMap = this.options.keyMap[env.isMac ? 'mac' : 'pc']; return Object.keys(keyMap).map(function (key) { var command = keyMap[key]; var $row = external_jQuery_default()('<div><div class="help-list-item"></div></div>'); $row.append(external_jQuery_default()('<label><kbd>' + key + '</kdb></label>').css({ 'width': 180, 'margin-right': 10 })).append(external_jQuery_default()('<span></span>').html(_this.context.memo('help.' + command) || command)); return $row.html(); }).join(''); } /** * show help dialog * * @return {Promise} */ }, { key: "showHelpDialog", value: function showHelpDialog() { var _this2 = this; return external_jQuery_default().Deferred(function (deferred) { _this2.ui.onDialogShown(_this2.$dialog, function () { _this2.context.triggerEvent('dialog.shown'); deferred.resolve(); }); _this2.ui.showDialog(_this2.$dialog); }).promise(); } }, { key: "show", value: function show() { var _this3 = this; this.context.invoke('editor.saveRange'); this.showHelpDialog().then(function () { _this3.context.invoke('editor.restoreRange'); }); } }]); return HelpDialog; }(); ;// CONCATENATED MODULE: ./src/js/module/AirPopover.js function AirPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function AirPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function AirPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) AirPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) AirPopover_defineProperties(Constructor, staticProps); return Constructor; } var AIRMODE_POPOVER_X_OFFSET = -5; var AIRMODE_POPOVER_Y_OFFSET = 5; var AirPopover = /*#__PURE__*/function () { function AirPopover(context) { var _this = this; AirPopover_classCallCheck(this, AirPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.options = context.options; this.hidable = true; this.onContextmenu = false; this.pageX = null; this.pageY = null; this.events = { 'summernote.contextmenu': function summernoteContextmenu(e) { if (_this.options.editing) { e.preventDefault(); e.stopPropagation(); _this.onContextmenu = true; _this.update(true); } }, 'summernote.mousedown': function summernoteMousedown(we, e) { _this.pageX = e.pageX; _this.pageY = e.pageY; }, 'summernote.keyup summernote.mouseup summernote.scroll': function summernoteKeyupSummernoteMouseupSummernoteScroll(we, e) { if (_this.options.editing && !_this.onContextmenu) { _this.pageX = e.pageX; _this.pageY = e.pageY; _this.update(); } _this.onContextmenu = false; }, 'summernote.disable summernote.change summernote.dialog.shown summernote.blur': function summernoteDisableSummernoteChangeSummernoteDialogShownSummernoteBlur() { _this.hide(); }, 'summernote.focusout': function summernoteFocusout() { if (!_this.$popover.is(':active,:focus')) { _this.hide(); } } }; } AirPopover_createClass(AirPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return this.options.airMode && !lists.isEmpty(this.options.popover.air); } }, { key: "initialize", value: function initialize() { var _this2 = this; this.$popover = this.ui.popover({ className: 'note-air-popover' }).render().appendTo(this.options.container); var $content = this.$popover.find('.popover-content'); this.context.invoke('buttons.build', $content, this.options.popover.air); // disable hiding this popover preemptively by 'summernote.blur' event. this.$popover.on('mousedown', function () { _this2.hidable = false; }); // (re-)enable hiding after 'summernote.blur' has been handled (aka. ignored). this.$popover.on('mouseup', function () { _this2.hidable = true; }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "update", value: function update(forcelyOpen) { var styleInfo = this.context.invoke('editor.currentStyle'); if (styleInfo.range && (!styleInfo.range.isCollapsed() || forcelyOpen)) { var rect = { left: this.pageX, top: this.pageY }; var containerOffset = external_jQuery_default()(this.options.container).offset(); rect.top -= containerOffset.top; rect.left -= containerOffset.left; this.$popover.css({ display: 'block', left: Math.max(rect.left, 0) + AIRMODE_POPOVER_X_OFFSET, top: rect.top + AIRMODE_POPOVER_Y_OFFSET }); this.context.invoke('buttons.updateCurrentStyle', this.$popover); } else { this.hide(); } } }, { key: "updateCodeview", value: function updateCodeview(isCodeview) { this.ui.toggleBtnActive(this.$popover.find('.btn-codeview'), isCodeview); if (isCodeview) { this.hide(); } } }, { key: "hide", value: function hide() { if (this.hidable) { this.$popover.hide(); } } }]); return AirPopover; }(); ;// CONCATENATED MODULE: ./src/js/module/HintPopover.js function HintPopover_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function HintPopover_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function HintPopover_createClass(Constructor, protoProps, staticProps) { if (protoProps) HintPopover_defineProperties(Constructor.prototype, protoProps); if (staticProps) HintPopover_defineProperties(Constructor, staticProps); return Constructor; } var POPOVER_DIST = 5; var HintPopover = /*#__PURE__*/function () { function HintPopover(context) { var _this = this; HintPopover_classCallCheck(this, HintPopover); this.context = context; this.ui = (external_jQuery_default()).summernote.ui; this.$editable = context.layoutInfo.editable; this.options = context.options; this.hint = this.options.hint || []; this.direction = this.options.hintDirection || 'bottom'; this.hints = Array.isArray(this.hint) ? this.hint : [this.hint]; this.events = { 'summernote.keyup': function summernoteKeyup(we, e) { if (!e.isDefaultPrevented()) { _this.handleKeyup(e); } }, 'summernote.keydown': function summernoteKeydown(we, e) { _this.handleKeydown(e); }, 'summernote.disable summernote.dialog.shown summernote.blur': function summernoteDisableSummernoteDialogShownSummernoteBlur() { _this.hide(); } }; } HintPopover_createClass(HintPopover, [{ key: "shouldInitialize", value: function shouldInitialize() { return this.hints.length > 0; } }, { key: "initialize", value: function initialize() { var _this2 = this; this.lastWordRange = null; this.matchingWord = null; this.$popover = this.ui.popover({ className: 'note-hint-popover', hideArrow: true, direction: '' }).render().appendTo(this.options.container); this.$popover.hide(); this.$content = this.$popover.find('.popover-content,.note-popover-content'); this.$content.on('click', '.note-hint-item', function (e) { _this2.$content.find('.active').removeClass('active'); external_jQuery_default()(e.currentTarget).addClass('active'); _this2.replace(); }); this.$popover.on('mousedown', function (e) { e.preventDefault(); }); } }, { key: "destroy", value: function destroy() { this.$popover.remove(); } }, { key: "selectItem", value: function selectItem($item) { this.$content.find('.active').removeClass('active'); $item.addClass('active'); this.$content[0].scrollTop = $item[0].offsetTop - this.$content.innerHeight() / 2; } }, { key: "moveDown", value: function moveDown() { var $current = this.$content.find('.note-hint-item.active'); var $next = $current.next(); if ($next.length) { this.selectItem($next); } else { var $nextGroup = $current.parent().next(); if (!$nextGroup.length) { $nextGroup = this.$content.find('.note-hint-group').first(); } this.selectItem($nextGroup.find('.note-hint-item').first()); } } }, { key: "moveUp", value: function moveUp() { var $current = this.$content.find('.note-hint-item.active'); var $prev = $current.prev(); if ($prev.length) { this.selectItem($prev); } else { var $prevGroup = $current.parent().prev(); if (!$prevGroup.length) { $prevGroup = this.$content.find('.note-hint-group').last(); } this.selectItem($prevGroup.find('.note-hint-item').last()); } } }, { key: "replace", value: function replace() { var $item = this.$content.find('.note-hint-item.active'); if ($item.length) { var node = this.nodeFromItem($item); // If matchingWord length = 0 -> capture OK / open hint / but as mention capture "" (\w*) if (this.matchingWord !== null && this.matchingWord.length === 0) { this.lastWordRange.so = this.lastWordRange.eo; // Else si > 0 and normal case -> adjust range "before" for correct position of insertion } else if (this.matchingWord !== null && this.matchingWord.length > 0 && !this.lastWordRange.isCollapsed()) { var rangeCompute = this.lastWordRange.eo - this.lastWordRange.so - this.matchingWord.length; if (rangeCompute > 0) { this.lastWordRange.so += rangeCompute; } } this.lastWordRange.insertNode(node); if (this.options.hintSelect === 'next') { var blank = document.createTextNode(''); external_jQuery_default()(node).after(blank); range.createFromNodeBefore(blank).select(); } else { range.createFromNodeAfter(node).select(); } this.lastWordRange = null; this.hide(); this.context.invoke('editor.focus'); this.context.triggerEvent('change', this.$editable.html(), this.$editable); } } }, { key: "nodeFromItem", value: function nodeFromItem($item) { var hint = this.hints[$item.data('index')]; var item = $item.data('item'); var node = hint.content ? hint.content(item) : item; if (typeof node === 'string') { node = dom.createText(node); } return node; } }, { key: "createItemTemplates", value: function createItemTemplates(hintIdx, items) { var hint = this.hints[hintIdx]; return items.map(function (item /*, idx */ ) { var $item = external_jQuery_default()('<div class="note-hint-item"></div>'); $item.append(hint.template ? hint.template(item) : item + ''); $item.data({ 'index': hintIdx, 'item': item }); return $item; }); } }, { key: "handleKeydown", value: function handleKeydown(e) { if (!this.$popover.is(':visible')) { return; } if (e.keyCode === key.code.ENTER) { e.preventDefault(); this.replace(); } else if (e.keyCode === key.code.UP) { e.preventDefault(); this.moveUp(); } else if (e.keyCode === key.code.DOWN) { e.preventDefault(); this.moveDown(); } } }, { key: "searchKeyword", value: function searchKeyword(index, keyword, callback) { var hint = this.hints[index]; if (hint && hint.match.test(keyword) && hint.search) { var matches = hint.match.exec(keyword); this.matchingWord = matches[0]; hint.search(matches[1], callback); } else { callback(); } } }, { key: "createGroup", value: function createGroup(idx, keyword) { var _this3 = this; var $group = external_jQuery_default()('<div class="note-hint-group note-hint-group-' + idx + '"></div>'); this.searchKeyword(idx, keyword, function (items) { items = items || []; if (items.length) { $group.html(_this3.createItemTemplates(idx, items)); _this3.show(); } }); return $group; } }, { key: "handleKeyup", value: function handleKeyup(e) { var _this4 = this; if (!lists.contains([key.code.ENTER, key.code.UP, key.code.DOWN], e.keyCode)) { var _range = this.context.invoke('editor.getLastRange'); var wordRange, keyword; if (this.options.hintMode === 'words') { wordRange = _range.getWordsRange(_range); keyword = wordRange.toString(); this.hints.forEach(function (hint) { if (hint.match.test(keyword)) { wordRange = _range.getWordsMatchRange(hint.match); return false; } }); if (!wordRange) { this.hide(); return; } keyword = wordRange.toString(); } else { wordRange = _range.getWordRange(); keyword = wordRange.toString(); } if (this.hints.length && keyword) { this.$content.empty(); var bnd = func.rect2bnd(lists.last(wordRange.getClientRects())); var containerOffset = external_jQuery_default()(this.options.container).offset(); if (bnd) { bnd.top -= containerOffset.top; bnd.left -= containerOffset.left; this.$popover.hide(); this.lastWordRange = wordRange; this.hints.forEach(function (hint, idx) { if (hint.match.test(keyword)) { _this4.createGroup(idx, keyword).appendTo(_this4.$content); } }); // select first .note-hint-item this.$content.find('.note-hint-item:first').addClass('active'); // set position for popover after group is created if (this.direction === 'top') { this.$popover.css({ left: bnd.left, top: bnd.top - this.$popover.outerHeight() - POPOVER_DIST }); } else { this.$popover.css({ left: bnd.left, top: bnd.top + bnd.height + POPOVER_DIST }); } } } else { this.hide(); } } } }, { key: "show", value: function show() { this.$popover.show(); } }, { key: "hide", value: function hide() { this.$popover.hide(); } }]); return HintPopover; }(); ;// CONCATENATED MODULE: ./src/js/settings.js (external_jQuery_default()).summernote = external_jQuery_default().extend((external_jQuery_default()).summernote, { version: '0.8.20', plugins: {}, dom: dom, range: range, lists: lists, options: { langInfo: (external_jQuery_default()).summernote.lang["en-US"], editing: true, modules: { 'editor': Editor, 'clipboard': Clipboard, 'dropzone': Dropzone, 'codeview': CodeView, 'statusbar': Statusbar, 'fullscreen': Fullscreen, 'handle': Handle, // FIXME: HintPopover must be front of autolink // - Script error about range when Enter key is pressed on hint popover 'hintPopover': HintPopover, 'autoLink': AutoLink, 'autoSync': AutoSync, 'autoReplace': AutoReplace, 'placeholder': Placeholder, 'buttons': Buttons, 'toolbar': Toolbar, 'linkDialog': LinkDialog, 'linkPopover': LinkPopover, 'imageDialog': ImageDialog, 'imagePopover': ImagePopover, 'tablePopover': TablePopover, 'videoDialog': VideoDialog, 'helpDialog': HelpDialog, 'airPopover': AirPopover }, buttons: {}, lang: 'en-US', followingToolbar: false, toolbarPosition: 'top', otherStaticBar: '', // toolbar codeviewKeepButton: false, toolbar: [['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['fontname', ['fontname']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture', 'video']], ['view', ['fullscreen', 'codeview', 'help']]], // popover popatmouse: true, popover: { image: [['resize', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']], ['float', ['floatLeft', 'floatRight', 'floatNone']], ['remove', ['removeMedia']]], link: [['link', ['linkDialogShow', 'unlink']]], table: [['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']], ['delete', ['deleteRow', 'deleteCol', 'deleteTable']]], air: [['color', ['color']], ['font', ['bold', 'underline', 'clear']], ['para', ['ul', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture']], ['view', ['fullscreen', 'codeview']]] }, // air mode: inline editor airMode: false, overrideContextMenu: false, // TBD width: null, height: null, linkTargetBlank: true, useProtocol: true, defaultProtocol: 'http://', focus: false, tabDisabled: false, tabSize: 4, styleWithCSS: false, shortcuts: true, textareaAutoSync: true, tooltip: 'auto', container: null, maxTextLength: 0, blockquoteBreakingLevel: 2, spellCheck: true, disableGrammar: false, placeholder: null, inheritPlaceholder: false, // TODO: need to be documented recordEveryKeystroke: false, historyLimit: 200, // TODO: need to be documented showDomainOnlyForAutolink: false, // TODO: need to be documented hintMode: 'word', hintSelect: 'after', hintDirection: 'bottom', styleTags: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'], fontNames: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande', 'Tahoma', 'Times New Roman', 'Verdana'], fontNamesIgnoreCheck: [], addDefaultFonts: true, fontSizes: ['8', '9', '10', '11', '12', '14', '18', '24', '36'], fontSizeUnits: ['px', 'pt'], // pallete colors(n x n) colors: [['#000000', '#424242', '#636363', '#9C9C94', '#CEC6CE', '#EFEFEF', '#F7F7F7', '#FFFFFF'], ['#FF0000', '#FF9C00', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#9C00FF', '#FF00FF'], ['#F7C6CE', '#FFE7CE', '#FFEFC6', '#D6EFD6', '#CEDEE7', '#CEE7F7', '#D6D6E7', '#E7D6DE'], ['#E79C9C', '#FFC69C', '#FFE79C', '#B5D6A5', '#A5C6CE', '#9CC6EF', '#B5A5D6', '#D6A5BD'], ['#E76363', '#F7AD6B', '#FFD663', '#94BD7B', '#73A5AD', '#6BADDE', '#8C7BC6', '#C67BA5'], ['#CE0000', '#E79439', '#EFC631', '#6BA54A', '#4A7B8C', '#3984C6', '#634AA5', '#A54A7B'], ['#9C0000', '#B56308', '#BD9400', '#397B21', '#104A5A', '#085294', '#311873', '#731842'], ['#630000', '#7B3900', '#846300', '#295218', '#083139', '#003163', '#21104A', '#4A1031']], // http://chir.ag/projects/name-that-color/ colorsName: [['Black', 'Tundora', 'Dove Gray', 'Star Dust', 'Pale Slate', 'Gallery', 'Alabaster', 'White'], ['Red', 'Orange Peel', 'Yellow', 'Green', 'Cyan', 'Blue', 'Electric Violet', 'Magenta'], ['Azalea', 'Karry', 'Egg White', 'Zanah', 'Botticelli', 'Tropical Blue', 'Mischka', 'Twilight'], ['Tonys Pink', 'Peach Orange', 'Cream Brulee', 'Sprout', 'Casper', 'Perano', 'Cold Purple', 'Careys Pink'], ['Mandy', 'Rajah', 'Dandelion', 'Olivine', 'Gulf Stream', 'Viking', 'Blue Marguerite', 'Puce'], ['Guardsman Red', 'Fire Bush', 'Golden Dream', 'Chelsea Cucumber', 'Smalt Blue', 'Boston Blue', 'Butterfly Bush', 'Cadillac'], ['Sangria', 'Mai Tai', 'Buddha Gold', 'Forest Green', 'Eden', 'Venice Blue', 'Meteorite', 'Claret'], ['Rosewood', 'Cinnamon', 'Olive', 'Parsley', 'Tiber', 'Midnight Blue', 'Valentino', 'Loulou']], colorButton: { foreColor: '#000000', backColor: '#FFFF00' }, lineHeights: ['1.0', '1.2', '1.4', '1.5', '1.6', '1.8', '2.0', '3.0'], tableClassName: 'table table-bordered', insertTableMaxSize: { col: 10, row: 10 }, // By default, dialogs are attached in container. dialogsInBody: false, dialogsFade: false, maximumImageFileSize: null, acceptImageFileTypes: "image/*", callbacks: { onBeforeCommand: null, onBlur: null, onBlurCodeview: null, onChange: null, onChangeCodeview: null, onDialogShown: null, onEnter: null, onFocus: null, onImageLinkInsert: null, onImageUpload: null, onImageUploadError: null, onInit: null, onKeydown: null, onKeyup: null, onMousedown: null, onMouseup: null, onPaste: null, onScroll: null }, codemirror: { mode: 'text/html', htmlMode: true, lineNumbers: true }, codeviewFilter: true, codeviewFilterRegex: /<\/*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|ilayer|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|t(?:itle|extarea)|xml)[^>]*?>/gi, codeviewIframeFilter: true, codeviewIframeWhitelistSrc: [], codeviewIframeWhitelistSrcBase: ['www.youtube.com', 'www.youtube-nocookie.com', 'www.facebook.com', 'vine.co', 'instagram.com', 'player.vimeo.com', 'www.dailymotion.com', 'player.youku.com', 'jumpingbean.tv', 'v.qq.com'], keyMap: { pc: { 'ESC': 'escape', 'ENTER': 'insertParagraph', 'CTRL+Z': 'undo', 'CTRL+Y': 'redo', 'TAB': 'tab', 'SHIFT+TAB': 'untab', 'CTRL+B': 'bold', 'CTRL+I': 'italic', 'CTRL+U': 'underline', 'CTRL+SHIFT+S': 'strikethrough', 'CTRL+BACKSLASH': 'removeFormat', 'CTRL+SHIFT+L': 'justifyLeft', 'CTRL+SHIFT+E': 'justifyCenter', 'CTRL+SHIFT+R': 'justifyRight', 'CTRL+SHIFT+J': 'justifyFull', 'CTRL+SHIFT+NUM7': 'insertUnorderedList', 'CTRL+SHIFT+NUM8': 'insertOrderedList', 'CTRL+LEFTBRACKET': 'outdent', 'CTRL+RIGHTBRACKET': 'indent', 'CTRL+NUM0': 'formatPara', 'CTRL+NUM1': 'formatH1', 'CTRL+NUM2': 'formatH2', 'CTRL+NUM3': 'formatH3', 'CTRL+NUM4': 'formatH4', 'CTRL+NUM5': 'formatH5', 'CTRL+NUM6': 'formatH6', 'CTRL+ENTER': 'insertHorizontalRule', 'CTRL+K': 'linkDialog.show' }, mac: { 'ESC': 'escape', 'ENTER': 'insertParagraph', 'CMD+Z': 'undo', 'CMD+SHIFT+Z': 'redo', 'TAB': 'tab', 'SHIFT+TAB': 'untab', 'CMD+B': 'bold', 'CMD+I': 'italic', 'CMD+U': 'underline', 'CMD+SHIFT+S': 'strikethrough', 'CMD+BACKSLASH': 'removeFormat', 'CMD+SHIFT+L': 'justifyLeft', 'CMD+SHIFT+E': 'justifyCenter', 'CMD+SHIFT+R': 'justifyRight', 'CMD+SHIFT+J': 'justifyFull', 'CMD+SHIFT+NUM7': 'insertUnorderedList', 'CMD+SHIFT+NUM8': 'insertOrderedList', 'CMD+LEFTBRACKET': 'outdent', 'CMD+RIGHTBRACKET': 'indent', 'CMD+NUM0': 'formatPara', 'CMD+NUM1': 'formatH1', 'CMD+NUM2': 'formatH2', 'CMD+NUM3': 'formatH3', 'CMD+NUM4': 'formatH4', 'CMD+NUM5': 'formatH5', 'CMD+NUM6': 'formatH6', 'CMD+ENTER': 'insertHorizontalRule', 'CMD+K': 'linkDialog.show' } }, icons: { 'align': 'note-icon-align', 'alignCenter': 'note-icon-align-center', 'alignJustify': 'note-icon-align-justify', 'alignLeft': 'note-icon-align-left', 'alignRight': 'note-icon-align-right', 'rowBelow': 'note-icon-row-below', 'colBefore': 'note-icon-col-before', 'colAfter': 'note-icon-col-after', 'rowAbove': 'note-icon-row-above', 'rowRemove': 'note-icon-row-remove', 'colRemove': 'note-icon-col-remove', 'indent': 'note-icon-align-indent', 'outdent': 'note-icon-align-outdent', 'arrowsAlt': 'note-icon-arrows-alt', 'bold': 'note-icon-bold', 'caret': 'note-icon-caret', 'circle': 'note-icon-circle', 'close': 'note-icon-close', 'code': 'note-icon-code', 'eraser': 'note-icon-eraser', 'floatLeft': 'note-icon-float-left', 'floatRight': 'note-icon-float-right', 'font': 'note-icon-font', 'frame': 'note-icon-frame', 'italic': 'note-icon-italic', 'link': 'note-icon-link', 'unlink': 'note-icon-chain-broken', 'magic': 'note-icon-magic', 'menuCheck': 'note-icon-menu-check', 'minus': 'note-icon-minus', 'orderedlist': 'note-icon-orderedlist', 'pencil': 'note-icon-pencil', 'picture': 'note-icon-picture', 'question': 'note-icon-question', 'redo': 'note-icon-redo', 'rollback': 'note-icon-rollback', 'square': 'note-icon-square', 'strikethrough': 'note-icon-strikethrough', 'subscript': 'note-icon-subscript', 'superscript': 'note-icon-superscript', 'table': 'note-icon-table', 'textHeight': 'note-icon-text-height', 'trash': 'note-icon-trash', 'underline': 'note-icon-underline', 'undo': 'note-icon-undo', 'unorderedlist': 'note-icon-unorderedlist', 'video': 'note-icon-video' } } }); ;// CONCATENATED MODULE: ./src/js/renderer.js function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function renderer_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function renderer_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function renderer_createClass(Constructor, protoProps, staticProps) { if (protoProps) renderer_defineProperties(Constructor.prototype, protoProps); if (staticProps) renderer_defineProperties(Constructor, staticProps); return Constructor; } var Renderer = /*#__PURE__*/function () { function Renderer(markup, children, options, callback) { renderer_classCallCheck(this, Renderer); this.markup = markup; this.children = children; this.options = options; this.callback = callback; } renderer_createClass(Renderer, [{ key: "render", value: function render($parent) { var $node = external_jQuery_default()(this.markup); if (this.options && this.options.contents) { $node.html(this.options.contents); } if (this.options && this.options.className) { $node.addClass(this.options.className); } if (this.options && this.options.data) { external_jQuery_default().each(this.options.data, function (k, v) { $node.attr('data-' + k, v); }); } if (this.options && this.options.click) { $node.on('click', this.options.click); } if (this.children) { var $container = $node.find('.note-children-container'); this.children.forEach(function (child) { child.render($container.length ? $container : $node); }); } if (this.callback) { this.callback($node, this.options); } if (this.options && this.options.callback) { this.options.callback($node); } if ($parent) { $parent.append($node); } return $node; } }]); return Renderer; }(); /* harmony default export */ const renderer = ({ create: function create(markup, callback) { return function () { var options = _typeof(arguments[1]) === 'object' ? arguments[1] : arguments[0]; var children = Array.isArray(arguments[0]) ? arguments[0] : []; if (options && options.children) { children = options.children; } return new Renderer(markup, children, options, callback); }; } }); ;// CONCATENATED MODULE: ./src/styles/bs4/summernote-bs4.js function summernote_bs4_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { summernote_bs4_typeof = function _typeof(obj) { return typeof obj; }; } else { summernote_bs4_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return summernote_bs4_typeof(obj); } var editor = renderer.create('<div class="note-editor note-frame card"></div>'); var toolbar = renderer.create('<div class="note-toolbar card-header" role="toolbar"></div>'); var editingArea = renderer.create('<div class="note-editing-area"></div>'); var codable = renderer.create('<textarea class="note-codable" aria-multiline="true"></textarea>'); var editable = renderer.create('<div class="note-editable card-block" contentEditable="true" role="textbox" aria-multiline="true"></div>'); var statusbar = renderer.create(['<output class="note-status-output" role="status" aria-live="polite"></output>', '<div class="note-statusbar" role="status">', '<div class="note-resizebar" aria-label="Resize">', '<div class="note-icon-bar"></div>', '<div class="note-icon-bar"></div>', '<div class="note-icon-bar"></div>', '</div>', '</div>'].join('')); var airEditor = renderer.create('<div class="note-editor note-airframe"></div>'); var airEditable = renderer.create(['<div class="note-editable" contentEditable="true" role="textbox" aria-multiline="true"></div>', '<output class="note-status-output" role="status" aria-live="polite"></output>'].join('')); var buttonGroup = renderer.create('<div class="note-btn-group btn-group"></div>'); var dropdown = renderer.create('<div class="note-dropdown-menu dropdown-menu" role="list"></div>', function ($node, options) { var markup = Array.isArray(options.items) ? options.items.map(function (item) { var value = typeof item === 'string' ? item : item.value || ''; var content = options.template ? options.template(item) : item; var option = summernote_bs4_typeof(item) === 'object' ? item.option : undefined; var dataValue = 'data-value="' + value + '"'; var dataOption = option !== undefined ? ' data-option="' + option + '"' : ''; return '<a class="dropdown-item" href="#" ' + (dataValue + dataOption) + ' role="listitem" aria-label="' + value + '">' + content + '</a>'; }).join('') : options.items; $node.html(markup).attr({ 'aria-label': options.title }); if (options && options.codeviewKeepButton) { $node.addClass('note-codeview-keep'); } }); var dropdownButtonContents = function dropdownButtonContents(contents) { return contents; }; var dropdownCheck = renderer.create('<div class="note-dropdown-menu dropdown-menu note-check" role="list"></div>', function ($node, options) { var markup = Array.isArray(options.items) ? options.items.map(function (item) { var value = typeof item === 'string' ? item : item.value || ''; var content = options.template ? options.template(item) : item; return '<a class="dropdown-item" href="#" data-value="' + value + '" role="listitem" aria-label="' + item + '">' + icon(options.checkClassName) + ' ' + content + '</a>'; }).join('') : options.items; $node.html(markup).attr({ 'aria-label': options.title }); if (options && options.codeviewKeepButton) { $node.addClass('note-codeview-keep'); } }); var dialog = renderer.create('<div class="modal note-modal" aria-hidden="false" tabindex="-1" role="dialog"></div>', function ($node, options) { if (options.fade) { $node.addClass('fade'); } $node.attr({ 'aria-label': options.title }); $node.html(['<div class="modal-dialog">', '<div class="modal-content">', options.title ? '<div class="modal-header">' + '<h4 class="modal-title">' + options.title + '</h4>' + '<button type="button" class="close" data-dismiss="modal" aria-label="Close" aria-hidden="true">&times;</button>' + '</div>' : '', '<div class="modal-body">' + options.body + '</div>', options.footer ? '<div class="modal-footer">' + options.footer + '</div>' : '', '</div>', '</div>'].join('')); }); var popover = renderer.create(['<div class="note-popover popover in">', '<div class="arrow"></div>', '<div class="popover-content note-children-container"></div>', '</div>'].join(''), function ($node, options) { var direction = typeof options.direction !== 'undefined' ? options.direction : 'bottom'; $node.addClass(direction); if (options.hideArrow) { $node.find('.arrow').hide(); } }); var summernote_bs4_checkbox = renderer.create('<div class="form-check"></div>', function ($node, options) { $node.html(['<label class="form-check-label"' + (options.id ? ' for="note-' + options.id + '"' : '') + '>', '<input type="checkbox" class="form-check-input"' + (options.id ? ' id="note-' + options.id + '"' : ''), options.checked ? ' checked' : '', ' aria-label="' + (options.text ? options.text : '') + '"', ' aria-checked="' + (options.checked ? 'true' : 'false') + '"/>', ' ' + (options.text ? options.text : '') + '</label>'].join('')); }); var icon = function icon(iconClassName, tagName) { if (iconClassName.match(/^</)) { return iconClassName; } tagName = tagName || 'i'; return '<' + tagName + ' class="' + iconClassName + '"></' + tagName + '>'; }; var ui = function ui(editorOptions) { return { editor: editor, toolbar: toolbar, editingArea: editingArea, codable: codable, editable: editable, statusbar: statusbar, airEditor: airEditor, airEditable: airEditable, buttonGroup: buttonGroup, dropdown: dropdown, dropdownButtonContents: dropdownButtonContents, dropdownCheck: dropdownCheck, dialog: dialog, popover: popover, icon: icon, checkbox: summernote_bs4_checkbox, options: editorOptions, palette: function palette($node, options) { return renderer.create('<div class="note-color-palette"></div>', function ($node, options) { var contents = []; for (var row = 0, rowSize = options.colors.length; row < rowSize; row++) { var eventName = options.eventName; var colors = options.colors[row]; var colorsName = options.colorsName[row]; var buttons = []; for (var col = 0, colSize = colors.length; col < colSize; col++) { var color = colors[col]; var colorName = colorsName[col]; buttons.push(['<button type="button" class="note-color-btn"', 'style="background-color:', color, '" ', 'data-event="', eventName, '" ', 'data-value="', color, '" ', 'title="', colorName, '" ', 'aria-label="', colorName, '" ', 'data-toggle="button" tabindex="-1"></button>'].join('')); } contents.push('<div class="note-color-row">' + buttons.join('') + '</div>'); } $node.html(contents.join('')); if (options.tooltip) { $node.find('.note-color-btn').tooltip({ container: options.container || editorOptions.container, trigger: 'hover', placement: 'bottom' }); } })($node, options); }, button: function button($node, options) { return renderer.create('<button type="button" class="note-btn btn btn-light btn-sm" tabindex="-1"></button>', function ($node, options) { if (options && options.tooltip) { $node.attr({ title: options.tooltip, 'aria-label': options.tooltip }).tooltip({ container: options.container || editorOptions.container, trigger: 'hover', placement: 'bottom' }).on('click', function (e) { external_jQuery_default()(e.currentTarget).tooltip('hide'); }); } if (options && options.codeviewButton) { $node.addClass('note-codeview-keep'); } })($node, options); }, toggleBtn: function toggleBtn($btn, isEnable) { $btn.toggleClass('disabled', !isEnable); $btn.attr('disabled', !isEnable); }, toggleBtnActive: function toggleBtnActive($btn, isActive) { $btn.toggleClass('active', isActive); }, onDialogShown: function onDialogShown($dialog, handler) { $dialog.one('shown.bs.modal', handler); }, onDialogHidden: function onDialogHidden($dialog, handler) { $dialog.one('hidden.bs.modal', handler); }, showDialog: function showDialog($dialog) { $dialog.modal('show'); }, hideDialog: function hideDialog($dialog) { $dialog.modal('hide'); }, createLayout: function createLayout($note) { var $editor = (editorOptions.airMode ? airEditor([editingArea([codable(), airEditable()])]) : editorOptions.toolbarPosition === 'bottom' ? editor([editingArea([codable(), editable()]), toolbar(), statusbar()]) : editor([toolbar(), editingArea([codable(), editable()]), statusbar()])).render(); $editor.insertAfter($note); return { note: $note, editor: $editor, toolbar: $editor.find('.note-toolbar'), editingArea: $editor.find('.note-editing-area'), editable: $editor.find('.note-editable'), codable: $editor.find('.note-codable'), statusbar: $editor.find('.note-statusbar') }; }, removeLayout: function removeLayout($note, layoutInfo) { $note.html(layoutInfo.editable.html()); layoutInfo.editor.remove(); $note.show(); } }; }; (external_jQuery_default()).summernote = external_jQuery_default().extend((external_jQuery_default()).summernote, { ui_template: ui, "interface": 'bs4' }); (external_jQuery_default()).summernote.options.styleTags = ['p', { title: 'Blockquote', tag: 'blockquote', className: 'blockquote', value: 'blockquote' }, 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']; })(); /******/ return __webpack_exports__; /******/ })() ; }); //# sourceMappingURL=summernote-bs4.js.map
2881099/FreeSql.AdminLTE
30,595
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-lite.min.css
@font-face{font-display:auto;font-family:summernote;font-style:normal;font-weight:400;src:url(font/summernote.eot?#iefix) format("embedded-opentype"),url(font/summernote.woff2) format("woff2"),url(font/summernote.woff) format("woff"),url(font/summernote.ttf) format("truetype")}[class*=" note-icon"]:before,[class^=note-icon]:before{text-rendering:auto;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;speak:none;display:inline-block;font-family:summernote;font-size:inherit;font-style:normal;text-decoration:inherit;text-transform:none;vertical-align:middle}.note-icon-fw{text-align:center;width:1.25em}.note-icon-border{border:.08em solid #eee;border-radius:.1em;padding:.2em .25em .15em}.note-icon-pull-left{float:left}.note-icon-pull-right{float:right}.note-icon.note-icon-pull-left{margin-right:.3em}.note-icon.note-icon-pull-right{margin-left:.3em}.note-icon-align:before{content:"\ea01"}.note-icon-align-center:before{content:"\ea02"}.note-icon-align-indent:before{content:"\ea03"}.note-icon-align-justify:before{content:"\ea04"}.note-icon-align-left:before{content:"\ea05"}.note-icon-align-outdent:before{content:"\ea06"}.note-icon-align-right:before{content:"\ea07"}.note-icon-arrow-circle-down:before{content:"\ea08"}.note-icon-arrow-circle-left:before{content:"\ea09"}.note-icon-arrow-circle-right:before{content:"\ea0a"}.note-icon-arrow-circle-up:before{content:"\ea0b"}.note-icon-arrows-alt:before{content:"\ea0c"}.note-icon-arrows-h:before{content:"\ea0d"}.note-icon-arrows-v:before{content:"\ea0e"}.note-icon-bold:before{content:"\ea0f"}.note-icon-caret:before{content:"\ea10"}.note-icon-chain-broken:before{content:"\ea11"}.note-icon-circle:before{content:"\ea12"}.note-icon-close:before{content:"\ea13"}.note-icon-code:before{content:"\ea14"}.note-icon-col-after:before{content:"\ea15"}.note-icon-col-before:before{content:"\ea16"}.note-icon-col-remove:before{content:"\ea17"}.note-icon-eraser:before{content:"\ea18"}.note-icon-float-left:before{content:"\ea19"}.note-icon-float-none:before{content:"\ea1a"}.note-icon-float-right:before{content:"\ea1b"}.note-icon-font:before{content:"\ea1c"}.note-icon-frame:before{content:"\ea1d"}.note-icon-italic:before{content:"\ea1e"}.note-icon-link:before{content:"\ea1f"}.note-icon-magic:before{content:"\ea20"}.note-icon-menu-check:before{content:"\ea21"}.note-icon-minus:before{content:"\ea22"}.note-icon-orderedlist:before{content:"\ea23"}.note-icon-pencil:before{content:"\ea24"}.note-icon-picture:before{content:"\ea25"}.note-icon-question:before{content:"\ea26"}.note-icon-redo:before{content:"\ea27"}.note-icon-rollback:before{content:"\ea28"}.note-icon-row-above:before{content:"\ea29"}.note-icon-row-below:before{content:"\ea2a"}.note-icon-row-remove:before{content:"\ea2b"}.note-icon-special-character:before{content:"\ea2c"}.note-icon-square:before{content:"\ea2d"}.note-icon-strikethrough:before{content:"\ea2e"}.note-icon-subscript:before{content:"\ea2f"}.note-icon-summernote:before{content:"\ea30"}.note-icon-superscript:before{content:"\ea31"}.note-icon-table:before{content:"\ea32"}.note-icon-text-height:before{content:"\ea33"}.note-icon-trash:before{content:"\ea34"}.note-icon-underline:before{content:"\ea35"}.note-icon-undo:before{content:"\ea36"}.note-icon-unorderedlist:before{content:"\ea37"}.note-icon-video:before{content:"\ea38"}.note-frame{border-radius:4px;-ms-box-sizing:border-box;box-sizing:border-box;color:#000;font-family:sans-serif}.note-toolbar{background-color:#f5f5f5;border-bottom:1px solid;border-color:#ddd;border-top-left-radius:3px;border-top-right-radius:3px;color:#333;padding:10px 5px}.note-btn-group{display:inline-block;margin-right:8px;position:relative}.note-btn-group>.note-btn-group{margin-right:0}.note-btn-group>.note-btn:first-child{margin-left:0}.note-btn-group .note-btn+.note-btn,.note-btn-group .note-btn+.note-btn-group,.note-btn-group .note-btn-group+.note-btn,.note-btn-group .note-btn-group+.note-btn-group{margin-left:-1px}.note-btn-group>.note-btn-group:not(:first-child)>.note-btn,.note-btn-group>.note-btn:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.note-btn-group>.note-btn-group:not(:last-child)>.note-btn,.note-btn-group>.note-btn:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-top-right-radius:0}.note-btn-group.open>.note-dropdown{display:block}.note-btn{background-color:#fff;background-image:none;border:1px solid #dae0e5;border-radius:3px;color:#333;cursor:pointer;display:inline-block;font-size:14px;font-weight:400;line-height:1.4;margin-bottom:0;outline:0;padding:5px 10px;text-align:center;touch-action:manipulation;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;vertical-align:middle;white-space:nowrap}.note-btn.focus,.note-btn:focus,.note-btn:hover{background-color:#ebebeb;border-color:#dae0e5;color:#333}.note-btn.disabled.focus,.note-btn.disabled:focus,.note-btn[disabled].focus,.note-btn[disabled]:focus,fieldset[disabled] .note-btn.focus,fieldset[disabled] .note-btn:focus{background-color:#fff;border-color:#dae0e5}.note-btn.active,.note-btn.focus,.note-btn:active,.note-btn:focus,.note-btn:hover{background-color:#ebebeb;border:1px solid #dae0e5;border-radius:1px;color:#333;outline:0;text-decoration:none}.note-btn.active,.note-btn:active{background-image:none;box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.note-btn.disabled,.note-btn[disabled],fieldset[disabled] .note-btn{box-shadow:none;cursor:not-allowed;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=65);filter:alpha(opacity=65);-webkit-opacity:.65;-khtml-opacity:.65;-moz-opacity:.65;opacity:.65}.note-btn>span.note-icon-caret:first-child{margin-left:-1px}.note-btn>span.note-icon-caret:nth-child(2){margin-right:-5px;padding-left:3px}.note-btn-primary{background:#fa6362;color:#fff}.note-btn-primary.focus,.note-btn-primary:focus,.note-btn-primary:hover{background-color:#fa6362;border:1px solid #dae0e5;border-radius:1px;color:#fff;text-decoration:none}.note-btn-block{display:block;width:100%}.note-btn-block+.note-btn-block{margin-top:5px}input[type=button].note-btn-block,input[type=reset].note-btn-block,input[type=submit].note-btn-block{width:100%}button.close{-webkit-appearance:none;background:transparent;border:0;cursor:pointer;padding:0}.close{color:#000;float:right;font-size:21px;line-height:1;opacity:.2}.close:hover{-ms-filter:alpha(opacity=100);filter:alpha(opacity=100);-webkit-opacity:1;-khtml-opacity:1;-moz-opacity:1;opacity:1}.note-dropdown{position:relative}.note-color .dropdown-toggle{padding-left:5px;width:30px}.note-dropdown-menu{background:#fff;background-clip:padding-box;border:1px solid #e2e2e2;box-shadow:0 1px 1px rgba(0,0,0,.06);display:none;float:left;left:0;min-width:100px;padding:5px;position:absolute;text-align:left;top:100%;z-index:1000}.note-dropdown-menu>:last-child{margin-right:0}.note-btn-group.open .note-dropdown-menu,.note-dropdown-item{display:block}.note-dropdown-item:hover{background-color:#ebebeb}a.note-dropdown-item,a.note-dropdown-item:hover{color:#000;margin:5px 0;text-decoration:none}.note-modal{bottom:0;display:none;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=100);filter:alpha(opacity=100);left:0;-webkit-opacity:1;-khtml-opacity:1;-moz-opacity:1;opacity:1;position:fixed;right:0;top:0;z-index:1050}.note-modal.open{display:block}.note-modal-content{background:#fff;background-clip:border-box;border:1px solid rgba(0,0,0,.2);border-radius:5px;box-shadow:0 3px 9px rgba(0,0,0,.5);margin:30px 20px;outline:0;position:relative;width:auto}.note-modal-header{border:1px solid #ededef;padding:10px 20px}.note-modal-body{padding:20px 30px;position:relative}.note-modal-body kbd{background-color:#000;border-radius:2px;-ms-box-sizing:border-box;box-sizing:border-box;color:#fff;font-weight:700;padding:3px 5px}.note-modal-footer{height:40px;padding:10px;text-align:center}.note-modal-footer a{color:#337ab7;text-decoration:none}.note-modal-footer a:focus,.note-modal-footer a:hover{color:#23527c;text-decoration:underline}.note-modal-footer .note-btn{float:right}.note-modal-title{color:#42515f;font-size:20px;line-height:1.4;margin:0}.note-modal-backdrop{background:#000;bottom:0;display:none;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=50);filter:alpha(opacity=50);left:0;-webkit-opacity:.5;-khtml-opacity:.5;-moz-opacity:.5;opacity:.5;position:fixed;right:0;top:0;z-index:1040}.note-modal-backdrop.open{display:block}@media (min-width:768px){.note-modal-content{margin:30px auto;width:600px}}@media (min-width:992px){.note-modal-content-large{width:900px}}.note-modal .note-help-block{color:#737373;display:block;margin-bottom:10px;margin-top:5px}.note-modal .note-nav{display:flex;flex-wrap:wrap;list-style:none;margin-bottom:0;padding-left:0}.note-modal .note-nav-link{-webkit-text-decoration-skip:objects;background-color:transparent;color:#007bff;display:block;padding:.5rem 1rem;text-decoration:none}.note-modal .note-nav-link:focus,.note-modal .note-nav-link:hover{color:#0056b3;text-decoration:none}.note-modal .note-nav-link.disabled{color:#868e96}.note-modal .note-nav-tabs{border-bottom:1px solid #ddd}.note-modal .note-nav-tabs .note-nav-item{margin-bottom:-1px}.note-modal .note-nav-tabs .note-nav-link{border:1px solid transparent;border-top-left-radius:.25rem;border-top-right-radius:.25rem}.note-modal .note-nav-tabs .note-nav-link:focus,.note-modal .note-nav-tabs .note-nav-link:hover{border-color:#e9ecef #e9ecef #ddd}.note-modal .note-nav-tabs .note-nav-link.disabled{background-color:transparent;border-color:transparent;color:#868e96}.note-modal .note-nav-tabs .note-nav-item.show .note-nav-link{background-color:#fff;border-color:#ddd #ddd #fff;color:#495057}.note-modal .note-tab-content{margin:15px auto}.note-modal .note-tab-content>.note-tab-pane,.note-modal .note-tab-content>.note-tab-pane:target~.note-tab-pane:last-child{display:none}.note-modal .note-tab-content>.note-tab-pane:target,.note-modal .note-tab-content>:last-child{display:block}.note-form-group{padding-bottom:20px}.note-form-group:last-child{padding-bottom:0}.note-form-label{color:#42515f;display:block;font-size:16px;font-weight:700;margin-bottom:10px;width:100%}.note-input{background:#fff;border:1px solid #ededef;-ms-box-sizing:border-box;box-sizing:border-box;display:block;font-size:14px;outline:0;padding:6px 4px;width:100%}.note-input::-webkit-input-placeholder{color:#eee}.note-input:-moz-placeholder,.note-input::-moz-placeholder{color:#eee}.note-input:-ms-input-placeholder{color:#eee}.note-tooltip{display:block;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);filter:alpha(opacity=0);font-size:13px;-webkit-opacity:0;-khtml-opacity:0;-moz-opacity:0;opacity:0;position:absolute;transition:opacity .15s;z-index:1070}.note-tooltip.in{-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=90);filter:alpha(opacity=90);-webkit-opacity:.9;-khtml-opacity:.9;-moz-opacity:.9;opacity:.9}.note-tooltip.top{margin-top:-3px;padding:5px 0}.note-tooltip.right{margin-left:3px;padding:0 5px}.note-tooltip.bottom{margin-top:3px;padding:5px 0}.note-tooltip.left{margin-left:-3px;padding:0 5px}.note-tooltip.bottom .note-tooltip-arrow{border-bottom-color:#000;border-width:0 5px 5px;left:50%;margin-left:-5px;top:0}.note-tooltip.top .note-tooltip-arrow{border-top-color:#000;border-width:5px 5px 0;bottom:0;left:50%;margin-left:-5px}.note-tooltip.right .note-tooltip-arrow{border-right-color:#000;border-width:5px 5px 5px 0;left:0;margin-top:-5px;top:50%}.note-tooltip.left .note-tooltip-arrow{border-left-color:#000;border-width:5px 0 5px 5px;margin-top:-5px;right:0;top:50%}.note-tooltip-arrow{border-color:transparent;border-style:solid;height:0;position:absolute;width:0}.note-tooltip-content{background-color:#000;color:#fff;font-family:sans-serif;max-width:200px;padding:3px 8px;text-align:center}.note-popover{background:#fff;border:1px solid #ccc;display:block;display:none;font-family:sans-serif;font-size:13px;position:absolute;z-index:1060}.note-popover.in{display:block}.note-popover.top{margin-top:-10px;padding:5px 0}.note-popover.right{margin-left:10px;padding:0 5px}.note-popover.bottom{margin-top:10px;padding:5px 0}.note-popover.left{margin-left:-10px;padding:0 5px}.note-popover.bottom .note-popover-arrow{border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25);border-top-width:0;left:20px;margin-left:-10px;top:-11px}.note-popover.bottom .note-popover-arrow:after{border-bottom-color:#fff;border-top-width:0;content:"\0020";margin-left:-10px;top:1px}.note-popover.top .note-popover-arrow{border-bottom-width:0;border-top-color:#999;border-top-color:rgba(0,0,0,.25);bottom:-11px;left:20px;margin-left:-10px}.note-popover.top .note-popover-arrow:after{border-bottom-width:0;border-top-color:#fff;bottom:1px;content:"\0020";margin-left:-10px}.note-popover.right .note-popover-arrow{border-left-width:0;border-right-color:#999;border-right-color:rgba(0,0,0,.25);left:-11px;margin-top:-10px;top:50%}.note-popover.right .note-popover-arrow:after{border-left-width:0;border-right-color:#fff;content:"\0020";left:1px;margin-top:-10px}.note-popover.left .note-popover-arrow{border-left-color:#999;border-left-color:rgba(0,0,0,.25);border-right-width:0;margin-top:-10px;right:-11px;top:50%}.note-popover.left .note-popover-arrow:after{border-left-color:#fff;border-right-width:0;content:"\0020";margin-top:-10px;right:1px}.note-popover-arrow{border:11px solid transparent;height:0;position:absolute;width:0}.note-popover-arrow:after{border:10px solid transparent;content:"\0020";display:block;height:0;position:absolute;width:0}.note-popover-content{background-color:#fff;color:#000;min-height:30px;min-width:100px;padding:3px 8px;text-align:center}.note-editor{position:relative}.note-editor .note-dropzone{background-color:#fff;color:#87cefa;display:none;opacity:.95;position:absolute;z-index:100}.note-editor .note-dropzone .note-dropzone-message{display:table-cell;font-size:28px;font-weight:700;text-align:center;vertical-align:middle}.note-editor .note-dropzone.hover{color:#098ddf}.note-editor.dragover .note-dropzone{display:table}.note-editor .note-editing-area{position:relative}.note-editor .note-editing-area .note-editable{outline:none}.note-editor .note-editing-area .note-editable sup{vertical-align:super}.note-editor .note-editing-area .note-editable sub{vertical-align:sub}.note-editor .note-editing-area .note-editable img.note-float-left{margin-right:10px}.note-editor .note-editing-area .note-editable img.note-float-right{margin-left:10px}.note-editor.note-airframe,.note-editor.note-frame{border:1px solid #00000032}.note-editor.note-airframe.codeview .note-editing-area .note-editable,.note-editor.note-frame.codeview .note-editing-area .note-editable{display:none}.note-editor.note-airframe.codeview .note-editing-area .note-codable,.note-editor.note-frame.codeview .note-editing-area .note-codable{display:block}.note-editor.note-airframe .note-editing-area,.note-editor.note-frame .note-editing-area{overflow:hidden}.note-editor.note-airframe .note-editing-area .note-editable,.note-editor.note-frame .note-editing-area .note-editable{word-wrap:break-word;overflow:auto;padding:10px}.note-editor.note-airframe .note-editing-area .note-editable[contenteditable=false],.note-editor.note-frame .note-editing-area .note-editable[contenteditable=false]{background-color:#8080801d}.note-editor.note-airframe .note-editing-area .note-codable,.note-editor.note-frame .note-editing-area .note-codable{background-color:#222;border:none;border-radius:0;box-shadow:none;-ms-box-sizing:border-box;box-sizing:border-box;color:#ccc;display:none;font-family:Menlo,Monaco,monospace,sans-serif;font-size:14px;margin-bottom:0;outline:none;padding:10px;resize:none;width:100%}.note-editor.note-airframe.fullscreen,.note-editor.note-frame.fullscreen{left:0;position:fixed;top:0;width:100%!important;z-index:1050}.note-editor.note-airframe.fullscreen .note-resizebar,.note-editor.note-frame.fullscreen .note-resizebar{display:none}.note-editor.note-airframe .note-status-output,.note-editor.note-frame .note-status-output{border:0;border-top:1px solid #e2e2e2;color:#000;display:block;font-size:14px;height:20px;line-height:1.42857143;margin-bottom:0;width:100%}.note-editor.note-airframe .note-status-output:empty,.note-editor.note-frame .note-status-output:empty{border-top:0 solid transparent;height:0}.note-editor.note-airframe .note-status-output .pull-right,.note-editor.note-frame .note-status-output .pull-right{float:right!important}.note-editor.note-airframe .note-status-output .text-muted,.note-editor.note-frame .note-status-output .text-muted{color:#777}.note-editor.note-airframe .note-status-output .text-primary,.note-editor.note-frame .note-status-output .text-primary{color:#286090}.note-editor.note-airframe .note-status-output .text-success,.note-editor.note-frame .note-status-output .text-success{color:#3c763d}.note-editor.note-airframe .note-status-output .text-info,.note-editor.note-frame .note-status-output .text-info{color:#31708f}.note-editor.note-airframe .note-status-output .text-warning,.note-editor.note-frame .note-status-output .text-warning{color:#8a6d3b}.note-editor.note-airframe .note-status-output .text-danger,.note-editor.note-frame .note-status-output .text-danger{color:#a94442}.note-editor.note-airframe .note-status-output .alert,.note-editor.note-frame .note-status-output .alert{background-color:#f5f5f5;border-radius:0;color:#000;margin:-7px 0 0;padding:7px 10px 2px}.note-editor.note-airframe .note-status-output .alert .note-icon,.note-editor.note-frame .note-status-output .alert .note-icon{margin-right:5px}.note-editor.note-airframe .note-status-output .alert-success,.note-editor.note-frame .note-status-output .alert-success{background-color:#dff0d8!important;color:#3c763d!important}.note-editor.note-airframe .note-status-output .alert-info,.note-editor.note-frame .note-status-output .alert-info{background-color:#d9edf7!important;color:#31708f!important}.note-editor.note-airframe .note-status-output .alert-warning,.note-editor.note-frame .note-status-output .alert-warning{background-color:#fcf8e3!important;color:#8a6d3b!important}.note-editor.note-airframe .note-status-output .alert-danger,.note-editor.note-frame .note-status-output .alert-danger{background-color:#f2dede!important;color:#a94442!important}.note-editor.note-airframe .note-statusbar,.note-editor.note-frame .note-statusbar{background-color:#8080801d;border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-top:1px solid #00000032}.note-editor.note-airframe .note-statusbar .note-resizebar,.note-editor.note-frame .note-statusbar .note-resizebar{cursor:ns-resize;height:9px;padding-top:1px;width:100%}.note-editor.note-airframe .note-statusbar .note-resizebar .note-icon-bar,.note-editor.note-frame .note-statusbar .note-resizebar .note-icon-bar{border-top:1px solid #00000032;margin:1px auto;width:20px}.note-editor.note-airframe .note-statusbar.locked .note-resizebar,.note-editor.note-frame .note-statusbar.locked .note-resizebar{cursor:default}.note-editor.note-airframe .note-statusbar.locked .note-resizebar .note-icon-bar,.note-editor.note-frame .note-statusbar.locked .note-resizebar .note-icon-bar{display:none}.note-editor.note-airframe .note-placeholder,.note-editor.note-frame .note-placeholder{padding:10px}.note-editor.note-airframe{border:0}.note-editor.note-airframe .note-editing-area .note-editable{padding:0}.note-popover.popover{display:none;max-width:none}.note-popover.popover .popover-content a{display:inline-block;max-width:200px;overflow:hidden;text-overflow:ellipsis;vertical-align:middle;white-space:nowrap}.note-popover.popover .arrow{left:20px!important}.note-toolbar{position:relative}.note-editor .note-toolbar,.note-popover .popover-content{margin:0;padding:0 0 5px 5px}.note-editor .note-toolbar>.note-btn-group,.note-popover .popover-content>.note-btn-group{margin-left:0;margin-right:5px;margin-top:5px}.note-editor .note-toolbar .note-btn-group .note-table,.note-popover .popover-content .note-btn-group .note-table{min-width:0;padding:5px}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker{font-size:18px}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher{cursor:pointer;height:10em;position:absolute!important;width:10em;z-index:3}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted{background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIj4+Pjp6ekKlAqjAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKhmnaJzPAAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat;height:5em;position:relative!important;width:5em;z-index:1}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted{background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIjd6vvD2f9LKLW+AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKwNDEVT0AAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat;height:1em;position:absolute!important;width:1em;z-index:2}.note-editor .note-toolbar .note-style .dropdown-style blockquote,.note-editor .note-toolbar .note-style .dropdown-style pre,.note-popover .popover-content .note-style .dropdown-style blockquote,.note-popover .popover-content .note-style .dropdown-style pre{margin:0;padding:5px 10px}.note-editor .note-toolbar .note-style .dropdown-style h1,.note-editor .note-toolbar .note-style .dropdown-style h2,.note-editor .note-toolbar .note-style .dropdown-style h3,.note-editor .note-toolbar .note-style .dropdown-style h4,.note-editor .note-toolbar .note-style .dropdown-style h5,.note-editor .note-toolbar .note-style .dropdown-style h6,.note-editor .note-toolbar .note-style .dropdown-style p,.note-popover .popover-content .note-style .dropdown-style h1,.note-popover .popover-content .note-style .dropdown-style h2,.note-popover .popover-content .note-style .dropdown-style h3,.note-popover .popover-content .note-style .dropdown-style h4,.note-popover .popover-content .note-style .dropdown-style h5,.note-popover .popover-content .note-style .dropdown-style h6,.note-popover .popover-content .note-style .dropdown-style p{margin:0;padding:0}.note-editor .note-toolbar .note-color-all .note-dropdown-menu,.note-popover .popover-content .note-color-all .note-dropdown-menu{min-width:337px}.note-editor .note-toolbar .note-color .dropdown-toggle,.note-popover .popover-content .note-color .dropdown-toggle{padding-left:5px;width:20px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette{display:inline-block;margin:0;width:160px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette:first-child,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette:first-child{margin:0 5px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-palette-title,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-palette-title{border-bottom:1px solid #eee;font-size:12px;margin:2px 7px;text-align:center}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset,.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select{border-radius:5px;cursor:pointer;font-size:11px;margin:3px;padding:0 3px;width:100%}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset:hover,.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select:hover,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset:hover,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select:hover{background:#eee}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-row,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-row{height:20px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select-btn,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select-btn{display:none}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn{border:1px solid #eee}.note-editor .note-toolbar .note-para .note-dropdown-menu,.note-popover .popover-content .note-para .note-dropdown-menu{min-width:228px;padding:5px}.note-editor .note-toolbar .note-para .note-dropdown-menu>div+div,.note-popover .popover-content .note-para .note-dropdown-menu>div+div{margin-left:5px}.note-editor .note-toolbar .note-dropdown-menu,.note-popover .popover-content .note-dropdown-menu{min-width:160px}.note-editor .note-toolbar .note-dropdown-menu.right,.note-popover .popover-content .note-dropdown-menu.right{left:auto;right:0}.note-editor .note-toolbar .note-dropdown-menu.right:before,.note-popover .popover-content .note-dropdown-menu.right:before{left:auto!important;right:9px}.note-editor .note-toolbar .note-dropdown-menu.right:after,.note-popover .popover-content .note-dropdown-menu.right:after{left:auto!important;right:10px}.note-editor .note-toolbar .note-dropdown-menu.note-check a i,.note-popover .popover-content .note-dropdown-menu.note-check a i{color:#00bfff;visibility:hidden}.note-editor .note-toolbar .note-dropdown-menu.note-check a.checked i,.note-popover .popover-content .note-dropdown-menu.note-check a.checked i{visibility:visible}.note-editor .note-toolbar .note-fontsize-10,.note-popover .popover-content .note-fontsize-10{font-size:10px}.note-editor .note-toolbar .note-color-palette,.note-popover .popover-content .note-color-palette{line-height:1}.note-editor .note-toolbar .note-color-palette div .note-color-btn,.note-popover .popover-content .note-color-palette div .note-color-btn{border:0;border-radius:0;height:20px;margin:0;padding:0;width:20px}.note-editor .note-toolbar .note-color-palette div .note-color-btn:hover,.note-popover .popover-content .note-color-palette div .note-color-btn:hover{transform:scale(1.2);transition:all .2s}.note-modal .modal-dialog{border-radius:5px;box-shadow:0 3px 9px rgba(0,0,0,.5);outline:0}.note-modal .form-group{margin-left:0;margin-right:0}.note-modal .note-modal-form{margin:0}.note-modal .note-image-dialog .note-dropzone{border:4px dashed #d3d3d3;color:#d3d3d3;font-size:30px;line-height:4;margin-bottom:10px;min-height:100px;text-align:center}.note-placeholder{color:gray;display:none;position:absolute}.note-handle .note-control-selection{border:1px solid #000;display:none;position:absolute}.note-handle .note-control-selection>div{position:absolute}.note-handle .note-control-selection .note-control-selection-bg{background-color:#000;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30);filter:alpha(opacity=30);height:100%;-webkit-opacity:.3;-khtml-opacity:.3;-moz-opacity:.3;opacity:.3;width:100%}.note-handle .note-control-selection .note-control-handle,.note-handle .note-control-selection .note-control-holder,.note-handle .note-control-selection .note-control-sizing{border:1px solid #000;height:7px;width:7px}.note-handle .note-control-selection .note-control-sizing{background-color:#000}.note-handle .note-control-selection .note-control-nw{border-bottom:none;border-right:none;left:-5px;top:-5px}.note-handle .note-control-selection .note-control-ne{border-bottom:none;border-left:none;right:-5px;top:-5px}.note-handle .note-control-selection .note-control-sw{border-right:none;border-top:none;bottom:-5px;left:-5px}.note-handle .note-control-selection .note-control-se{bottom:-5px;cursor:se-resize;right:-5px}.note-handle .note-control-selection .note-control-se.note-control-holder{border-left:none;border-top:none;cursor:default}.note-handle .note-control-selection .note-control-selection-info{background-color:#000;border-radius:5px;bottom:0;color:#fff;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=70);filter:alpha(opacity=70);font-size:12px;margin:5px;-webkit-opacity:.7;-khtml-opacity:.7;-moz-opacity:.7;opacity:.7;padding:5px;right:0}.note-hint-popover{min-width:100px;padding:2px}.note-hint-popover .popover-content{max-height:150px;overflow:auto;padding:3px}.note-hint-popover .popover-content .note-hint-group .note-hint-item{display:block!important;padding:3px}.note-hint-popover .popover-content .note-hint-group .note-hint-item.active,.note-hint-popover .popover-content .note-hint-group .note-hint-item:hover{background-color:#428bca;clear:both;color:#fff;cursor:pointer;display:block;font-weight:400;line-height:1.4;outline:0;text-decoration:none;white-space:nowrap}body .note-fullscreen-body,html .note-fullscreen-body{overflow:hidden!important}.note-editor .note-editing-area .note-editable table{border-collapse:collapse;width:100%}.note-editor .note-editing-area .note-editable table td,.note-editor .note-editing-area .note-editable table th{border:1px solid #ececec;padding:5px 3px}.note-editor .note-editing-area .note-editable a{background-color:inherit;color:#337ab7;font-family:inherit;font-weight:inherit;text-decoration:inherit}.note-editor .note-editing-area .note-editable a:focus,.note-editor .note-editing-area .note-editable a:hover{color:#23527c;outline:0;text-decoration:underline}.note-editor .note-editing-area .note-editable figure{margin:0}.note-modal .note-modal-body label{display:inline-block;margin-bottom:2px;padding:2px 5px}.note-modal .note-modal-body .help-list-item:hover{background-color:#e0e0e0}@-moz-document url-prefix(){.note-modal .note-image-input{height:auto}}.help-list-item label{display:inline-block;margin-bottom:5px}
294coder/Efficient-MIF
14,178
utils/loss_landscape/plot_surface.py
""" Calculate and visualize the loss surface. Usage example: >> python plot_surface.py --x=-1:1:101 --y=-1:1:101 --model resnet56 --cuda """ import argparse import copy import h5py import torch import time import socket import os import sys import numpy as np import torchvision import torch.nn as nn import dataloader import evaluation import projection as proj import net_plotter import plot_2D import plot_1D import model_loader import scheduler import mpi4pytorch as mpi def name_surface_file(args, dir_file): # skip if surf_file is specified in args if args.surf_file: return args.surf_file # use args.dir_file as the perfix surf_file = dir_file # resolution surf_file += '_[%s,%s,%d]' % (str(args.xmin), str(args.xmax), int(args.xnum)) if args.y: surf_file += 'x[%s,%s,%d]' % (str(args.ymin), str(args.ymax), int(args.ynum)) # dataloder parameters if args.raw_data: # without data normalization surf_file += '_rawdata' if args.data_split > 1: surf_file += '_datasplit=' + str(args.data_split) + '_splitidx=' + str(args.split_idx) return surf_file + ".h5" def setup_surface_file(args, surf_file, dir_file): # skip if the direction file already exists if os.path.exists(surf_file): f = h5py.File(surf_file, 'r') if (args.y and 'ycoordinates' in f.keys()) or 'xcoordinates' in f.keys(): f.close() print ("%s is already set up" % surf_file) return f = h5py.File(surf_file, 'a') f['dir_file'] = dir_file # Create the coordinates(resolutions) at which the function is evaluated xcoordinates = np.linspace(args.xmin, args.xmax, num=args.xnum) f['xcoordinates'] = xcoordinates if args.y: ycoordinates = np.linspace(args.ymin, args.ymax, num=args.ynum) f['ycoordinates'] = ycoordinates f.close() return surf_file def crunch(surf_file, net, w, s, d, dataloader, loss_key, acc_key, comm, rank, args): """ Calculate the loss values and accuracies of modified models in parallel using MPI reduce. """ f = h5py.File(surf_file, 'r+' if rank == 0 else 'r') losses, accuracies = [], [] xcoordinates = f['xcoordinates'][:] ycoordinates = f['ycoordinates'][:] if 'ycoordinates' in f.keys() else None if loss_key not in f.keys(): shape = xcoordinates.shape if ycoordinates is None else (len(xcoordinates),len(ycoordinates)) losses = -np.ones(shape=shape) accuracies = -np.ones(shape=shape) if rank == 0: f[loss_key] = losses f[acc_key] = accuracies else: losses = f[loss_key][:] accuracies = f[acc_key][:] # Generate a list of indices of 'losses' that need to be filled in. # The coordinates of each unfilled index (with respect to the direction vectors # stored in 'd') are stored in 'coords'. inds, coords, inds_nums = scheduler.get_job_indices(losses, xcoordinates, ycoordinates, comm) print('Computing %d values for rank %d'% (len(inds), rank)) start_time = time.time() total_sync = 0.0 criterion = nn.CrossEntropyLoss() if args.loss_name == 'mse': criterion = nn.MSELoss() # Loop over all uncalculated loss values for count, ind in enumerate(inds): # Get the coordinates of the loss value being calculated coord = coords[count] # Load the weights corresponding to those coordinates into the net if args.dir_type == 'weights': net_plotter.set_weights(net.module if args.ngpu > 1 else net, w, d, coord) elif args.dir_type == 'states': net_plotter.set_states(net.module if args.ngpu > 1 else net, s, d, coord) # Record the time to compute the loss value loss_start = time.time() loss, acc = evaluation.eval_loss(net, criterion, dataloader, args.cuda) loss_compute_time = time.time() - loss_start # Record the result in the local array losses.ravel()[ind] = loss accuracies.ravel()[ind] = acc # Send updated plot data to the master node syc_start = time.time() losses = mpi.reduce_max(comm, losses) accuracies = mpi.reduce_max(comm, accuracies) syc_time = time.time() - syc_start total_sync += syc_time # Only the master node writes to the file - this avoids write conflicts if rank == 0: f[loss_key][:] = losses f[acc_key][:] = accuracies f.flush() print('Evaluating rank %d %d/%d (%.1f%%) coord=%s \t%s= %.3f \t%s=%.2f \ttime=%.2f \tsync=%.2f' % ( rank, count, len(inds), 100.0 * count/len(inds), str(coord), loss_key, loss, acc_key, acc, loss_compute_time, syc_time)) # This is only needed to make MPI run smoothly. If this process has less work than # the rank0 process, then we need to keep calling reduce so the rank0 process doesn't block for i in range(max(inds_nums) - len(inds)): losses = mpi.reduce_max(comm, losses) accuracies = mpi.reduce_max(comm, accuracies) total_time = time.time() - start_time print('Rank %d done! Total time: %.2f Sync: %.2f' % (rank, total_time, total_sync)) f.close() ############################################################### # MAIN ############################################################### if __name__ == '__main__': parser = argparse.ArgumentParser(description='plotting loss surface') parser.add_argument('--mpi', '-m', action='store_true', help='use mpi') parser.add_argument('--cuda', '-c', action='store_true', help='use cuda') parser.add_argument('--threads', default=2, type=int, help='number of threads') parser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use for each rank, useful for data parallel evaluation') parser.add_argument('--batch_size', default=128, type=int, help='minibatch size') # data parameters parser.add_argument('--dataset', default='cifar10', help='cifar10 | imagenet') parser.add_argument('--datapath', default='cifar10/data', metavar='DIR', help='path to the dataset') parser.add_argument('--raw_data', action='store_true', default=False, help='no data preprocessing') parser.add_argument('--data_split', default=1, type=int, help='the number of splits for the dataloader') parser.add_argument('--split_idx', default=0, type=int, help='the index of data splits for the dataloader') parser.add_argument('--trainloader', default='', help='path to the dataloader with random labels') parser.add_argument('--testloader', default='', help='path to the testloader with random labels') # model parameters parser.add_argument('--model', default='resnet56', help='model name') parser.add_argument('--model_folder', default='', help='the common folder that contains model_file and model_file2') parser.add_argument('--model_file', default='', help='path to the trained model file') parser.add_argument('--model_file2', default='', help='use (model_file2 - model_file) as the xdirection') parser.add_argument('--model_file3', default='', help='use (model_file3 - model_file) as the ydirection') parser.add_argument('--loss_name', '-l', default='crossentropy', help='loss functions: crossentropy | mse') # direction parameters parser.add_argument('--dir_file', default='', help='specify the name of direction file, or the path to an eisting direction file') parser.add_argument('--dir_type', default='weights', help='direction type: weights | states (including BN\'s running_mean/var)') parser.add_argument('--x', default='-1:1:51', help='A string with format xmin:x_max:xnum') parser.add_argument('--y', default=None, help='A string with format ymin:ymax:ynum') parser.add_argument('--xnorm', default='', help='direction normalization: filter | layer | weight') parser.add_argument('--ynorm', default='', help='direction normalization: filter | layer | weight') parser.add_argument('--xignore', default='', help='ignore bias and BN parameters: biasbn') parser.add_argument('--yignore', default='', help='ignore bias and BN parameters: biasbn') parser.add_argument('--same_dir', action='store_true', default=False, help='use the same random direction for both x-axis and y-axis') parser.add_argument('--idx', default=0, type=int, help='the index for the repeatness experiment') parser.add_argument('--surf_file', default='', help='customize the name of surface file, could be an existing file.') # plot parameters parser.add_argument('--proj_file', default='', help='the .h5 file contains projected optimization trajectory.') parser.add_argument('--loss_max', default=5, type=float, help='Maximum value to show in 1D plot') parser.add_argument('--vmax', default=10, type=float, help='Maximum value to map') parser.add_argument('--vmin', default=0.1, type=float, help='Miminum value to map') parser.add_argument('--vlevel', default=0.5, type=float, help='plot contours every vlevel') parser.add_argument('--show', action='store_true', default=False, help='show plotted figures') parser.add_argument('--log', action='store_true', default=False, help='use log scale for loss values') parser.add_argument('--plot', action='store_true', default=False, help='plot figures after computation') args = parser.parse_args() torch.manual_seed(123) #-------------------------------------------------------------------------- # Environment setup #-------------------------------------------------------------------------- if args.mpi: comm = mpi.setup_MPI() rank, nproc = comm.Get_rank(), comm.Get_size() else: comm, rank, nproc = None, 0, 1 # in case of multiple GPUs per node, set the GPU to use for each rank if args.cuda: if not torch.cuda.is_available(): raise Exception('User selected cuda option, but cuda is not available on this machine') gpu_count = torch.cuda.device_count() torch.cuda.set_device(rank % gpu_count) print('Rank %d use GPU %d of %d GPUs on %s' % (rank, torch.cuda.current_device(), gpu_count, socket.gethostname())) #-------------------------------------------------------------------------- # Check plotting resolution #-------------------------------------------------------------------------- try: args.xmin, args.xmax, args.xnum = [float(a) for a in args.x.split(':')] args.ymin, args.ymax, args.ynum = (None, None, None) if args.y: args.ymin, args.ymax, args.ynum = [float(a) for a in args.y.split(':')] assert args.ymin and args.ymax and args.ynum, \ 'You specified some arguments for the y axis, but not all' except: raise Exception('Improper format for x- or y-coordinates. Try something like -1:1:51') #-------------------------------------------------------------------------- # Load models and extract parameters #-------------------------------------------------------------------------- net = model_loader.load(args.dataset, args.model, args.model_file) w = net_plotter.get_weights(net) # initial parameters s = copy.deepcopy(net.state_dict()) # deepcopy since state_dict are references if args.ngpu > 1: # data parallel with multiple GPUs on a single node net = nn.DataParallel(net, device_ids=range(torch.cuda.device_count())) #-------------------------------------------------------------------------- # Setup the direction file and the surface file #-------------------------------------------------------------------------- dir_file = net_plotter.name_direction_file(args) # name the direction file if rank == 0: net_plotter.setup_direction(args, dir_file, net) surf_file = name_surface_file(args, dir_file) if rank == 0: setup_surface_file(args, surf_file, dir_file) # wait until master has setup the direction file and surface file mpi.barrier(comm) # load directions d = net_plotter.load_directions(dir_file) # calculate the consine similarity of the two directions if len(d) == 2 and rank == 0: similarity = proj.cal_angle(proj.nplist_to_tensor(d[0]), proj.nplist_to_tensor(d[1])) print('cosine similarity between x-axis and y-axis: %f' % similarity) #-------------------------------------------------------------------------- # Setup dataloader #-------------------------------------------------------------------------- # download CIFAR10 if it does not exit if rank == 0 and args.dataset == 'cifar10': torchvision.datasets.CIFAR10(root=args.dataset + '/data', train=True, download=True) mpi.barrier(comm) trainloader, testloader = dataloader.load_dataset(args.dataset, args.datapath, args.batch_size, args.threads, args.raw_data, args.data_split, args.split_idx, args.trainloader, args.testloader) #-------------------------------------------------------------------------- # Start the computation #-------------------------------------------------------------------------- crunch(surf_file, net, w, s, d, trainloader, 'train_loss', 'train_acc', comm, rank, args) # crunch(surf_file, net, w, s, d, testloader, 'test_loss', 'test_acc', comm, rank, args) #-------------------------------------------------------------------------- # Plot figures #-------------------------------------------------------------------------- if args.plot and rank == 0: if args.y and args.proj_file: plot_2D.plot_contour_trajectory(surf_file, dir_file, args.proj_file, 'train_loss', args.show) elif args.y: plot_2D.plot_2d_contour(surf_file, 'train_loss', args.vmin, args.vmax, args.vlevel, args.show) else: plot_1D.plot_1d_loss_err(surf_file, args.xmin, args.xmax, args.loss_max, args.log, args.show)
281677160/openwrt-package
3,495
luci-app-nginx-pingos/patches/101-feature_test_fix.patch
--- a/auto/cc/name +++ b/auto/cc/name @@ -7,7 +7,7 @@ if [ "$NGX_PLATFORM" != win32 ]; then ngx_feature="C compiler" ngx_feature_name= - ngx_feature_run=yes + ngx_feature_run= ngx_feature_incs= ngx_feature_path= ngx_feature_libs= --- a/auto/cc/conf +++ b/auto/cc/conf @@ -183,7 +183,7 @@ if [ "$NGX_PLATFORM" != win32 ]; then else ngx_feature="gcc builtin atomic operations" ngx_feature_name=NGX_HAVE_GCC_ATOMIC - ngx_feature_run=yes + ngx_feature_run=no ngx_feature_incs= ngx_feature_path= ngx_feature_libs= @@ -204,7 +204,7 @@ if [ "$NGX_PLATFORM" != win32 ]; then else ngx_feature="C99 variadic macros" ngx_feature_name="NGX_HAVE_C99_VARIADIC_MACROS" - ngx_feature_run=yes + ngx_feature_run=no ngx_feature_incs="#include <stdio.h> #define var(dummy, ...) sprintf(__VA_ARGS__)" ngx_feature_path= @@ -218,7 +218,7 @@ if [ "$NGX_PLATFORM" != win32 ]; then ngx_feature="gcc variadic macros" ngx_feature_name="NGX_HAVE_GCC_VARIADIC_MACROS" - ngx_feature_run=yes + ngx_feature_run=no ngx_feature_incs="#include <stdio.h> #define var(dummy, args...) sprintf(args)" ngx_feature_path= --- a/auto/os/linux +++ b/auto/os/linux @@ -36,7 +36,7 @@ fi ngx_feature="epoll" ngx_feature_name="NGX_HAVE_EPOLL" -ngx_feature_run=yes +ngx_feature_run=no ngx_feature_incs="#include <sys/epoll.h>" ngx_feature_path= ngx_feature_libs= @@ -110,7 +110,7 @@ ngx_feature_test="int fd; struct stat sb CC_AUX_FLAGS="$cc_aux_flags -D_GNU_SOURCE" ngx_feature="sendfile()" ngx_feature_name="NGX_HAVE_SENDFILE" -ngx_feature_run=yes +ngx_feature_run=no ngx_feature_incs="#include <sys/sendfile.h> #include <errno.h>" ngx_feature_path= @@ -131,7 +131,7 @@ fi CC_AUX_FLAGS="$cc_aux_flags -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64" ngx_feature="sendfile64()" ngx_feature_name="NGX_HAVE_SENDFILE64" -ngx_feature_run=yes +ngx_feature_run=no ngx_feature_incs="#include <sys/sendfile.h> #include <errno.h>" ngx_feature_path= @@ -149,7 +149,7 @@ ngx_include="sys/prctl.h"; . auto/includ ngx_feature="prctl(PR_SET_DUMPABLE)" ngx_feature_name="NGX_HAVE_PR_SET_DUMPABLE" -ngx_feature_run=yes +ngx_feature_run=no ngx_feature_incs="#include <sys/prctl.h>" ngx_feature_path= ngx_feature_libs= --- a/auto/unix +++ b/auto/unix @@ -840,7 +840,7 @@ ngx_feature_test="void *p; p = memalign( ngx_feature="mmap(MAP_ANON|MAP_SHARED)" ngx_feature_name="NGX_HAVE_MAP_ANON" -ngx_feature_run=yes +ngx_feature_run=no ngx_feature_incs="#include <sys/mman.h>" ngx_feature_path= ngx_feature_libs= @@ -853,7 +853,7 @@ ngx_feature_test="void *p; ngx_feature='mmap("/dev/zero", MAP_SHARED)' ngx_feature_name="NGX_HAVE_MAP_DEVZERO" -ngx_feature_run=yes +ngx_feature_run=no ngx_feature_incs="#include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h>" @@ -868,7 +868,7 @@ ngx_feature_test='void *p; int fd; ngx_feature="System V shared memory" ngx_feature_name="NGX_HAVE_SYSVSHM" -ngx_feature_run=yes +ngx_feature_run=no ngx_feature_incs="#include <sys/ipc.h> #include <sys/shm.h>" ngx_feature_path= @@ -882,7 +882,7 @@ ngx_feature_test="int id; ngx_feature="POSIX semaphores" ngx_feature_name="NGX_HAVE_POSIX_SEM" -ngx_feature_run=yes +ngx_feature_run=no ngx_feature_incs="#include <semaphore.h>" ngx_feature_path= ngx_feature_libs=
2881099/FreeSql.AdminLTE
23,436
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-bs5.css
/*! * * Super simple WYSIWYG editor v0.8.20 * https://summernote.org * * * Copyright 2013- Alan Hong and contributors * Summernote may be freely distributed under the MIT license. * * Date: 2021-10-14T21:15Z * */ @font-face { font-family: "summernote"; font-style: normal; font-weight: 400; font-display: auto; src: url("./font/summernote.eot?#iefix") format("embedded-opentype"), url("./font/summernote.woff2") format("woff2"), url("./font/summernote.woff") format("woff"), url("./font/summernote.ttf") format("truetype"); } [class^=note-icon]:before, [class*=" note-icon"]:before { display: inline-block; font-family: "summernote"; font-style: normal; font-size: inherit; text-decoration: inherit; text-rendering: auto; text-transform: none; vertical-align: middle; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; speak: none; } .note-icon-fw { text-align: center; width: 1.25em; } .note-icon-border { border: solid 0.08em #eee; border-radius: 0.1em; padding: 0.2em 0.25em 0.15em; } .note-icon-pull-left { float: left; } .note-icon-pull-right { float: right; } .note-icon.note-icon-pull-left { margin-right: 0.3em; } .note-icon.note-icon-pull-right { margin-left: 0.3em; } .note-icon-align::before { content: "\ea01"; } .note-icon-align-center::before { content: "\ea02"; } .note-icon-align-indent::before { content: "\ea03"; } .note-icon-align-justify::before { content: "\ea04"; } .note-icon-align-left::before { content: "\ea05"; } .note-icon-align-outdent::before { content: "\ea06"; } .note-icon-align-right::before { content: "\ea07"; } .note-icon-arrow-circle-down::before { content: "\ea08"; } .note-icon-arrow-circle-left::before { content: "\ea09"; } .note-icon-arrow-circle-right::before { content: "\ea0a"; } .note-icon-arrow-circle-up::before { content: "\ea0b"; } .note-icon-arrows-alt::before { content: "\ea0c"; } .note-icon-arrows-h::before { content: "\ea0d"; } .note-icon-arrows-v::before { content: "\ea0e"; } .note-icon-bold::before { content: "\ea0f"; } .note-icon-caret::before { content: "\ea10"; } .note-icon-chain-broken::before { content: "\ea11"; } .note-icon-circle::before { content: "\ea12"; } .note-icon-close::before { content: "\ea13"; } .note-icon-code::before { content: "\ea14"; } .note-icon-col-after::before { content: "\ea15"; } .note-icon-col-before::before { content: "\ea16"; } .note-icon-col-remove::before { content: "\ea17"; } .note-icon-eraser::before { content: "\ea18"; } .note-icon-float-left::before { content: "\ea19"; } .note-icon-float-none::before { content: "\ea1a"; } .note-icon-float-right::before { content: "\ea1b"; } .note-icon-font::before { content: "\ea1c"; } .note-icon-frame::before { content: "\ea1d"; } .note-icon-italic::before { content: "\ea1e"; } .note-icon-link::before { content: "\ea1f"; } .note-icon-magic::before { content: "\ea20"; } .note-icon-menu-check::before { content: "\ea21"; } .note-icon-minus::before { content: "\ea22"; } .note-icon-orderedlist::before { content: "\ea23"; } .note-icon-pencil::before { content: "\ea24"; } .note-icon-picture::before { content: "\ea25"; } .note-icon-question::before { content: "\ea26"; } .note-icon-redo::before { content: "\ea27"; } .note-icon-rollback::before { content: "\ea28"; } .note-icon-row-above::before { content: "\ea29"; } .note-icon-row-below::before { content: "\ea2a"; } .note-icon-row-remove::before { content: "\ea2b"; } .note-icon-special-character::before { content: "\ea2c"; } .note-icon-square::before { content: "\ea2d"; } .note-icon-strikethrough::before { content: "\ea2e"; } .note-icon-subscript::before { content: "\ea2f"; } .note-icon-summernote::before { content: "\ea30"; } .note-icon-superscript::before { content: "\ea31"; } .note-icon-table::before { content: "\ea32"; } .note-icon-text-height::before { content: "\ea33"; } .note-icon-trash::before { content: "\ea34"; } .note-icon-underline::before { content: "\ea35"; } .note-icon-undo::before { content: "\ea36"; } .note-icon-unorderedlist::before { content: "\ea37"; } .note-icon-video::before { content: "\ea38"; } /* Theme Variables ------------------------------------------ */ /* Layout ------------------------------------------ */ .note-editor { position: relative; } .note-editor .note-dropzone { position: absolute; display: none; z-index: 100; color: lightskyblue; background-color: #fff; opacity: 0.95; } .note-editor .note-dropzone .note-dropzone-message { display: table-cell; vertical-align: middle; text-align: center; font-size: 28px; font-weight: 700; } .note-editor .note-dropzone.hover { color: #098ddf; } .note-editor.dragover .note-dropzone { display: table; } .note-editor .note-editing-area { position: relative; } .note-editor .note-editing-area .note-editable { outline: none; } .note-editor .note-editing-area .note-editable sup { vertical-align: super; } .note-editor .note-editing-area .note-editable sub { vertical-align: sub; } .note-editor .note-editing-area .note-editable img.note-float-left { margin-right: 10px; } .note-editor .note-editing-area .note-editable img.note-float-right { margin-left: 10px; } /* Frame mode layout ------------------------------------------ */ .note-editor.note-frame, .note-editor.note-airframe { border: 1px solid #00000032; } .note-editor.note-frame.codeview .note-editing-area .note-editable, .note-editor.note-airframe.codeview .note-editing-area .note-editable { display: none; } .note-editor.note-frame.codeview .note-editing-area .note-codable, .note-editor.note-airframe.codeview .note-editing-area .note-codable { display: block; } .note-editor.note-frame .note-editing-area, .note-editor.note-airframe .note-editing-area { overflow: hidden; } .note-editor.note-frame .note-editing-area .note-editable, .note-editor.note-airframe .note-editing-area .note-editable { padding: 10px; overflow: auto; word-wrap: break-word; } .note-editor.note-frame .note-editing-area .note-editable[contenteditable=false], .note-editor.note-airframe .note-editing-area .note-editable[contenteditable=false] { background-color: #8080801d; } .note-editor.note-frame .note-editing-area .note-codable, .note-editor.note-airframe .note-editing-area .note-codable { display: none; width: 100%; padding: 10px; border: none; box-shadow: none; font-family: Menlo, Monaco, monospace, sans-serif; font-size: 14px; color: #ccc; background-color: #222; resize: none; outline: none; -ms-box-sizing: border-box; box-sizing: border-box; border-radius: 0; margin-bottom: 0; } .note-editor.note-frame.fullscreen, .note-editor.note-airframe.fullscreen { position: fixed; top: 0; left: 0; width: 100% !important; z-index: 1050; } .note-editor.note-frame.fullscreen .note-resizebar, .note-editor.note-airframe.fullscreen .note-resizebar { display: none; } .note-editor.note-frame .note-status-output, .note-editor.note-airframe .note-status-output { display: block; width: 100%; font-size: 14px; line-height: 1.42857143; height: 20px; margin-bottom: 0; color: #000; border: 0; border-top: 1px solid #e2e2e2; } .note-editor.note-frame .note-status-output:empty, .note-editor.note-airframe .note-status-output:empty { height: 0; border-top: 0 solid transparent; } .note-editor.note-frame .note-status-output .pull-right, .note-editor.note-airframe .note-status-output .pull-right { float: right !important; } .note-editor.note-frame .note-status-output .text-muted, .note-editor.note-airframe .note-status-output .text-muted { color: #777; } .note-editor.note-frame .note-status-output .text-primary, .note-editor.note-airframe .note-status-output .text-primary { color: #286090; } .note-editor.note-frame .note-status-output .text-success, .note-editor.note-airframe .note-status-output .text-success { color: #3c763d; } .note-editor.note-frame .note-status-output .text-info, .note-editor.note-airframe .note-status-output .text-info { color: #31708f; } .note-editor.note-frame .note-status-output .text-warning, .note-editor.note-airframe .note-status-output .text-warning { color: #8a6d3b; } .note-editor.note-frame .note-status-output .text-danger, .note-editor.note-airframe .note-status-output .text-danger { color: #a94442; } .note-editor.note-frame .note-status-output .alert, .note-editor.note-airframe .note-status-output .alert { margin: -7px 0 0 0; padding: 7px 10px 2px 10px; border-radius: 0; color: #000; background-color: #f5f5f5; } .note-editor.note-frame .note-status-output .alert .note-icon, .note-editor.note-airframe .note-status-output .alert .note-icon { margin-right: 5px; } .note-editor.note-frame .note-status-output .alert-success, .note-editor.note-airframe .note-status-output .alert-success { color: #3c763d !important; background-color: #dff0d8 !important; } .note-editor.note-frame .note-status-output .alert-info, .note-editor.note-airframe .note-status-output .alert-info { color: #31708f !important; background-color: #d9edf7 !important; } .note-editor.note-frame .note-status-output .alert-warning, .note-editor.note-airframe .note-status-output .alert-warning { color: #8a6d3b !important; background-color: #fcf8e3 !important; } .note-editor.note-frame .note-status-output .alert-danger, .note-editor.note-airframe .note-status-output .alert-danger { color: #a94442 !important; background-color: #f2dede !important; } .note-editor.note-frame .note-statusbar, .note-editor.note-airframe .note-statusbar { background-color: #8080801d; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top: 1px solid #00000032; } .note-editor.note-frame .note-statusbar .note-resizebar, .note-editor.note-airframe .note-statusbar .note-resizebar { padding-top: 1px; height: 9px; width: 100%; cursor: ns-resize; } .note-editor.note-frame .note-statusbar .note-resizebar .note-icon-bar, .note-editor.note-airframe .note-statusbar .note-resizebar .note-icon-bar { width: 20px; margin: 1px auto; border-top: 1px solid #00000032; } .note-editor.note-frame .note-statusbar.locked .note-resizebar, .note-editor.note-airframe .note-statusbar.locked .note-resizebar { cursor: default; } .note-editor.note-frame .note-statusbar.locked .note-resizebar .note-icon-bar, .note-editor.note-airframe .note-statusbar.locked .note-resizebar .note-icon-bar { display: none; } .note-editor.note-frame .note-placeholder, .note-editor.note-airframe .note-placeholder { padding: 10px; } .note-editor.note-airframe { border: 0; } .note-editor.note-airframe .note-editing-area .note-editable { padding: 0; } /* Popover ------------------------------------------ */ .note-popover.popover { display: none; max-width: none; } .note-popover.popover .popover-content a { display: inline-block; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle; } .note-popover.popover .arrow { left: 20px !important; } /* Popover and Toolbar (Button container) ------------------------------------------ */ .note-toolbar { position: relative; } .note-popover .popover-content, .note-editor .note-toolbar { margin: 0; padding: 0 0 5px 5px; } .note-popover .popover-content > .note-btn-group, .note-editor .note-toolbar > .note-btn-group { margin-top: 5px; margin-left: 0; margin-right: 5px; } .note-popover .popover-content .note-btn-group .note-table, .note-editor .note-toolbar .note-btn-group .note-table { min-width: 0; padding: 5px; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker { font-size: 18px; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher { position: absolute !important; z-index: 3; width: 10em; height: 10em; cursor: pointer; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted { position: relative !important; z-index: 1; width: 5em; height: 5em; background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIj4+Pjp6ekKlAqjAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKhmnaJzPAAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat; } .note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted, .note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted { position: absolute !important; z-index: 2; width: 1em; height: 1em; background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIjd6vvD2f9LKLW+AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKwNDEVT0AAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat; } .note-popover .popover-content .note-style .dropdown-style blockquote, .note-popover .popover-content .note-style .dropdown-style pre, .note-editor .note-toolbar .note-style .dropdown-style blockquote, .note-editor .note-toolbar .note-style .dropdown-style pre { margin: 0; padding: 5px 10px; } .note-popover .popover-content .note-style .dropdown-style h1, .note-popover .popover-content .note-style .dropdown-style h2, .note-popover .popover-content .note-style .dropdown-style h3, .note-popover .popover-content .note-style .dropdown-style h4, .note-popover .popover-content .note-style .dropdown-style h5, .note-popover .popover-content .note-style .dropdown-style h6, .note-popover .popover-content .note-style .dropdown-style p, .note-editor .note-toolbar .note-style .dropdown-style h1, .note-editor .note-toolbar .note-style .dropdown-style h2, .note-editor .note-toolbar .note-style .dropdown-style h3, .note-editor .note-toolbar .note-style .dropdown-style h4, .note-editor .note-toolbar .note-style .dropdown-style h5, .note-editor .note-toolbar .note-style .dropdown-style h6, .note-editor .note-toolbar .note-style .dropdown-style p { margin: 0; padding: 0; } .note-popover .popover-content .note-color-all .note-dropdown-menu, .note-editor .note-toolbar .note-color-all .note-dropdown-menu { min-width: 337px; } .note-popover .popover-content .note-color .dropdown-toggle, .note-editor .note-toolbar .note-color .dropdown-toggle { width: 20px; padding-left: 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette { display: inline-block; margin: 0; width: 160px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette:first-child, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette:first-child { margin: 0 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-palette-title, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-palette-title { font-size: 12px; margin: 2px 7px; text-align: center; border-bottom: 1px solid #eee; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset, .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select { font-size: 11px; margin: 3px; padding: 0 3px; cursor: pointer; width: 100%; border-radius: 5px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset:hover, .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select:hover, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset:hover, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select:hover { background: #eee; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-row, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-row { height: 20px; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select-btn, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select-btn { display: none; } .note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn, .note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn { border: 1px solid #eee; } .note-popover .popover-content .note-para .note-dropdown-menu, .note-editor .note-toolbar .note-para .note-dropdown-menu { min-width: 228px; padding: 5px; } .note-popover .popover-content .note-para .note-dropdown-menu > div + div, .note-editor .note-toolbar .note-para .note-dropdown-menu > div + div { margin-left: 5px; } .note-popover .popover-content .note-dropdown-menu, .note-editor .note-toolbar .note-dropdown-menu { min-width: 160px; } .note-popover .popover-content .note-dropdown-menu.right, .note-editor .note-toolbar .note-dropdown-menu.right { right: 0; left: auto; } .note-popover .popover-content .note-dropdown-menu.right::before, .note-editor .note-toolbar .note-dropdown-menu.right::before { right: 9px; left: auto !important; } .note-popover .popover-content .note-dropdown-menu.right::after, .note-editor .note-toolbar .note-dropdown-menu.right::after { right: 10px; left: auto !important; } .note-popover .popover-content .note-dropdown-menu.note-check a i, .note-editor .note-toolbar .note-dropdown-menu.note-check a i { color: deepskyblue; visibility: hidden; } .note-popover .popover-content .note-dropdown-menu.note-check a.checked i, .note-editor .note-toolbar .note-dropdown-menu.note-check a.checked i { visibility: visible; } .note-popover .popover-content .note-fontsize-10, .note-editor .note-toolbar .note-fontsize-10 { font-size: 10px; } .note-popover .popover-content .note-color-palette, .note-editor .note-toolbar .note-color-palette { line-height: 1; } .note-popover .popover-content .note-color-palette div .note-color-btn, .note-editor .note-toolbar .note-color-palette div .note-color-btn { width: 20px; height: 20px; padding: 0; margin: 0; border: 0; border-radius: 0; } .note-popover .popover-content .note-color-palette div .note-color-btn:hover, .note-editor .note-toolbar .note-color-palette div .note-color-btn:hover { transform: scale(1.2); transition: all 0.2s; } /* Dialog ------------------------------------------ */ .note-modal .modal-dialog { outline: 0; border-radius: 5px; box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5); } .note-modal .form-group { margin-left: 0; margin-right: 0; } .note-modal .note-modal-form { margin: 0; } .note-modal .note-image-dialog .note-dropzone { min-height: 100px; font-size: 30px; line-height: 4; color: lightgray; text-align: center; border: 4px dashed lightgray; margin-bottom: 10px; } @-moz-document url-prefix() { .note-modal .note-image-input { height: auto; } } /* Placeholder ------------------------------------------ */ .note-placeholder { position: absolute; display: none; color: gray; } /* Handle ------------------------------------------ */ .note-handle .note-control-selection { position: absolute; display: none; border: 1px solid #000; } .note-handle .note-control-selection > div { position: absolute; } .note-handle .note-control-selection .note-control-selection-bg { width: 100%; height: 100%; background-color: #000; -webkit-opacity: 0.3; -khtml-opacity: 0.3; -moz-opacity: 0.3; opacity: 0.3; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=30); filter: alpha(opacity=30); } .note-handle .note-control-selection .note-control-handle, .note-handle .note-control-selection .note-control-sizing, .note-handle .note-control-selection .note-control-holder { width: 7px; height: 7px; border: 1px solid #000; } .note-handle .note-control-selection .note-control-sizing { background-color: #000; } .note-handle .note-control-selection .note-control-nw { top: -5px; left: -5px; border-right: none; border-bottom: none; } .note-handle .note-control-selection .note-control-ne { top: -5px; right: -5px; border-bottom: none; border-left: none; } .note-handle .note-control-selection .note-control-sw { bottom: -5px; left: -5px; border-top: none; border-right: none; } .note-handle .note-control-selection .note-control-se { right: -5px; bottom: -5px; cursor: se-resize; } .note-handle .note-control-selection .note-control-se.note-control-holder { cursor: default; border-top: none; border-left: none; } .note-handle .note-control-selection .note-control-selection-info { right: 0; bottom: 0; padding: 5px; margin: 5px; color: #fff; background-color: #000; font-size: 12px; border-radius: 5px; -webkit-opacity: 0.7; -khtml-opacity: 0.7; -moz-opacity: 0.7; opacity: 0.7; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=70); filter: alpha(opacity=70); } .note-hint-popover { min-width: 100px; padding: 2px; } .note-hint-popover .popover-content { padding: 3px; max-height: 150px; overflow: auto; } .note-hint-popover .popover-content .note-hint-group .note-hint-item { display: block !important; padding: 3px; } .note-hint-popover .popover-content .note-hint-group .note-hint-item.active, .note-hint-popover .popover-content .note-hint-group .note-hint-item:hover { display: block; clear: both; font-weight: 400; line-height: 1.4; color: white; white-space: nowrap; text-decoration: none; background-color: #428bca; outline: 0; cursor: pointer; } /* Handle ------------------------------------------ */ html .note-fullscreen-body, body .note-fullscreen-body { overflow: hidden !important; } .note-toolbar { background: #8080801d; } .note-btn-group .note-btn { border-color: #00000032; padding: 0.28rem 0.65rem; font-size: 13px; } /*# sourceMappingURL=summernote-bs5.css.map*/
294coder/Efficient-MIF
5,784
utils/loss_landscape/hess_vec_prod.py
import torch import time import numpy as np from torch import nn from torch.autograd import Variable from scipy.sparse.linalg import LinearOperator, eigsh ################################################################################ # Supporting Functions ################################################################################ def npvec_to_tensorlist(vec, params): """ Convert a numpy vector to a list of tensor with the same dimensions as params Args: vec: a 1D numpy vector params: a list of parameters from net Returns: rval: a list of tensors with the same shape as params """ loc = 0 rval = [] for p in params: numel = p.data.numel() rval.append(torch.from_numpy(vec[loc:loc+numel]).view(p.data.shape).float()) loc += numel assert loc == vec.size, 'The vector has more elements than the net has parameters' return rval def gradtensor_to_npvec(net, include_bn=False): """ Extract gradients from net, and return a concatenated numpy vector. Args: net: trained model include_bn: If include_bn, then gradients w.r.t. BN parameters and bias values are also included. Otherwise only gradients with dim > 1 are considered. Returns: a concatenated numpy vector containing all gradients """ filter = lambda p: include_bn or len(p.data.size()) > 1 return np.concatenate([p.grad.data.cpu().numpy().ravel() for p in net.parameters() if filter(p)]) ################################################################################ # For computing Hessian-vector products ################################################################################ def eval_hess_vec_prod(vec, params, net, criterion, dataloader, use_cuda=False): """ Evaluate product of the Hessian of the loss function with a direction vector "vec". The product result is saved in the grad of net. Args: vec: a list of tensor with the same dimensions as "params". params: the parameter list of the net (ignoring biases and BN parameters). net: model with trained parameters. criterion: loss function. dataloader: dataloader for the dataset. use_cuda: use GPU. """ if use_cuda: net.cuda() vec = [v.cuda() for v in vec] net.eval() net.zero_grad() # clears grad for every parameter in the net for batch_idx, (inputs, targets) in enumerate(dataloader): inputs, targets = Variable(inputs), Variable(targets) if use_cuda: inputs, targets = inputs.cuda(), targets.cuda() outputs = net(inputs) loss = criterion(outputs, targets) grad_f = torch.autograd.grad(loss, inputs=params, create_graph=True) # Compute inner product of gradient with the direction vector prod = Variable(torch.zeros(1)).type(type(grad_f[0].data)) for (g, v) in zip(grad_f, vec): prod = prod + (g * v).cpu().sum() # Compute the Hessian-vector product, H*v # prod.backward() computes dprod/dparams for every parameter in params and # accumulate the gradients into the params.grad attributes prod.backward() ################################################################################ # For computing Eigenvalues of Hessian ################################################################################ def min_max_hessian_eigs(net, dataloader, criterion, rank=0, use_cuda=False, verbose=False): """ Compute the largest and the smallest eigenvalues of the Hessian marix. Args: net: the trained model. dataloader: dataloader for the dataset, may use a subset of it. criterion: loss function. rank: rank of the working node. use_cuda: use GPU verbose: print more information Returns: maxeig: max eigenvalue mineig: min eigenvalue hess_vec_prod.count: number of iterations for calculating max and min eigenvalues """ params = [p for p in net.parameters() if len(p.size()) > 1] N = sum(p.numel() for p in params) def hess_vec_prod(vec): hess_vec_prod.count += 1 # simulates a static variable vec = npvec_to_tensorlist(vec, params) start_time = time.time() eval_hess_vec_prod(vec, params, net, criterion, dataloader, use_cuda) prod_time = time.time() - start_time if verbose and rank == 0: print(" Iter: %d time: %f" % (hess_vec_prod.count, prod_time)) return gradtensor_to_npvec(net) hess_vec_prod.count = 0 if verbose and rank == 0: print("Rank %d: computing max eigenvalue" % rank) A = LinearOperator((N, N), matvec=hess_vec_prod) eigvals, eigvecs = eigsh(A, k=1, tol=1e-2) maxeig = eigvals[0] if verbose and rank == 0: print('max eigenvalue = %f' % maxeig) # If the largest eigenvalue is positive, shift matrix so that any negative eigenvalue is now the largest # We assume the smallest eigenvalue is zero or less, and so this shift is more than what we need shift = maxeig*.51 def shifted_hess_vec_prod(vec): return hess_vec_prod(vec) - shift*vec if verbose and rank == 0: print("Rank %d: Computing shifted eigenvalue" % rank) A = LinearOperator((N, N), matvec=shifted_hess_vec_prod) eigvals, eigvecs = eigsh(A, k=1, tol=1e-2) eigvals = eigvals + shift mineig = eigvals[0] if verbose and rank == 0: print('min eigenvalue = ' + str(mineig)) if maxeig <= 0 and mineig > 0: maxeig, mineig = mineig, maxeig return maxeig, mineig, hess_vec_prod.count
281677160/openwrt-package
1,985
luci-app-nginx-pingos/luasrc/view/pingos/status.htm
<fieldset class="cbi-section"> <legend><%:Running Status%></legend> <fieldset class="cbi-section"> <div class="cbi-value"> <label class="cbi-value-title">Nginx <%:Status%></label> <div class="cbi-value-field" id="_nginx_status"><%:Collecting data...%></div> </div> <div class="cbi-value"> <label class="cbi-value-title"></label> <div class="cbi-value-field"> <font color="red" id="tips"></font> <ul id="tips2"> <li>rtmp rtmp://ip/live/<%:Stream name%></li> <li>http(s)-flv http(s)://ip/flv/<%:Stream name%></li> <li>hls http(s)://ip/hls/<%:Stream name%>.m3u8</li> <li>hls+ http(s)://ip/hls2/<%:Stream name%>.m3u8</li> <li>http(s)-ts http(s)://ip/ts/<%:Stream name%></li> </ul> </div> </div> </fieldset> </fieldset> <script type="text/javascript">//<![CDATA[ var nginx_status = document.getElementById('_nginx_status'); XHR.poll(3, '<%=url([[admin]], [[nas]], [[pingos]], [[status]])%>', null, function(x, json) { if (x && x.status == 200) { if (nginx_status) { var str = ""; if (json.status) { document.getElementById("tips").innerHTML = '<%:If you need external network access, please open the port by yourself.%>'; str = '<font color="green"><%:RUNNING%> ✓</font><input type="button" class="cbi-button cbi-input-apply" value="<%:Enter interface%>" onclick="open_web()" />' } else { document.getElementById("tips").innerHTML = ''; str = '<font color="red"><%:NOT RUNNING%> X</font>'; } nginx_status.innerHTML = str; } } } ); function open_web(){ var port = '<%=luci.sys.exec("uci -q get pingos.@global[0].http_port"):gsub("^%s*(.-)%s*$", "%1")%>'; var ishttps = '<%=luci.sys.exec("uci -q get pingos.@global[0].https"):gsub("^%s*(.-)%s*$", "%1")%>'; var protocol = (ishttps == "1") ? "https://" : "http://"; var hostname = location.hostname; var url = protocol + hostname + ":" + port; window.open(url, 'target', ''); } //]]></script>
294coder/Efficient-MIF
11,852
utils/loss_landscape/plot_hessian_eigen.py
""" Calculate the hessian matrix of the projected surface and their eigen values. """ import argparse import copy import numpy as np import h5py import torch import time import socket import os import sys import torchvision import torch.nn as nn import mpi4pytorch import dataloader import net_plotter import plot_2D import plot_1D import model_loader import scheduler import projection as proj import hess_vec_prod from plot_surface import name_surface_file, setup_surface_file def crunch_hessian_eigs(surf_file, net, w, s, d, dataloader, comm, rank, args): """ Calculate eigen values of the hessian matrix of a given model in parallel using mpi reduce. This is the synchronized version. """ f = h5py.File(surf_file, 'r+' if rank == 0 else 'r') min_eig, max_eig = [], [] xcoordinates = f['xcoordinates'][:] ycoordinates = f['ycoordinates'][:] if 'ycoordinates' in f.keys() else None if 'min_eig' not in f.keys(): shape = xcoordinates.shape if ycoordinates is None else (len(xcoordinates),len(ycoordinates)) max_eig = -np.ones(shape=shape) min_eig = np.ones(shape=shape) if rank == 0: f['min_eig'] = min_eig f['max_eig'] = max_eig else: min_eig = f['min_eig'][:] max_eig = f['max_eig'][:] # Generate a list of all indices that need to be filled in. # The coordinates of each unfilled index are stored in 'coords'. inds, coords, inds_nums = scheduler.get_job_indices(max_eig, xcoordinates, ycoordinates, comm) print('Computing %d values for rank %d'% (len(inds), rank)) criterion = nn.CrossEntropyLoss() # set the loss function criteria # Loop over all un-calculated coords start_time = time.time() total_sync = 0.0 for count, ind in enumerate(inds): # Get the coordinates of the points being calculated coord = coords[count] # Load the weights corresponding to those coordinates into the net if args.dir_type == 'weights': net_plotter.set_weights(net.module if args.ngpu > 1 else net, w, d, coord) elif args.dir_type == 'states': net_plotter.set_states(net.module if args.ngpu > 1 else net, s, d, coord) # Compute the eign values of the hessian matrix compute_start = time.time() maxeig, mineig, iter_count = hess_vec_prod.min_max_hessian_eigs(net, dataloader, \ criterion, rank=rank, use_cuda=args.cuda, verbose=True) compute_time = time.time() - compute_start # Record the result in the local array max_eig.ravel()[ind] = maxeig min_eig.ravel()[ind] = mineig # Send updated plot data to the master node sync_start_time = time.time() max_eig = mpi4pytorch.reduce_max(comm, max_eig) min_eig = mpi4pytorch.reduce_min(comm, min_eig) sync_time = time.time() - sync_start_time total_sync += sync_time # Only the master node writes to the file - this avoids write conflicts if rank == 0: f['max_eig'][:] = max_eig f['min_eig'][:] = min_eig print("rank: %d %d/%d (%0.2f%%) %d\t %s \tmaxeig:%8.5f \tmineig:%8.5f \titer: %d \ttime:%.2f \tsync:%.2f" % ( \ rank, count + 1, len(inds), 100.0 * (count + 1)/len(inds), ind, str(coord), \ maxeig, mineig, iter_count, compute_time, sync_time)) # This is only needed to make MPI run smoothly. If this process has less work # than the rank0 process, then we need to keep calling allreduce so the rank0 process doesn't block for i in range(max(inds_nums) - len(inds)): max_eig = mpi4pytorch.reduce_max(comm, max_eig) min_eig = mpi4pytorch.reduce_min(comm, min_eig) total_time = time.time() - start_time print('Rank %d done! Total time: %f Sync: %f '%(rank, total_time, total_sync)) f.close() ############################################################### #### MAIN ############################################################### if __name__ == '__main__': parser = argparse.ArgumentParser(description='plotting loss surface') parser.add_argument('--mpi', '-m', action='store_true', help='use mpi') parser.add_argument('--cuda', '-c', action='store_true', help='use cuda') parser.add_argument('--threads', default=2, type=int, help='number of threads') parser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use for each rank, useful for data parallel evaluation') parser.add_argument('--batch_size', default=128, type=int, help='minibatch size') # data parameters parser.add_argument('--dataset', default='cifar10', help='cifar10 | imagenet') parser.add_argument('--datapath', default='cifar10/data', metavar='DIR', help='path to the dataset') parser.add_argument('--raw_data', action='store_true', default=False, help='no data preprocessing') parser.add_argument('--data_split', default=1, type=int, help='the number of splits for the dataloader') parser.add_argument('--split_idx', default=0, type=int, help='the index of data splits for the dataloader') parser.add_argument('--trainloader', default='', help='path to the dataloader with random labels') parser.add_argument('--testloader', default='', help='path to the testloader with random labels') # model parameters parser.add_argument('--model', default='resnet56', help='model name') parser.add_argument('--model_folder', default='', help='the common folder that contains model_file and model_file2') parser.add_argument('--model_file', default='', help='path to the trained model file') parser.add_argument('--model_file2', default='', help='use (model_file2 - model_file) as the xdirection') parser.add_argument('--model_file3', default='', help='use (model_file3 - model_file) as the ydirection') parser.add_argument('--loss_name', '-l', default='crossentropy', help='loss functions: crossentropy | mse') # direction parameters parser.add_argument('--dir_file', default='', help='specify the name of direction file, or the path to an eisting direction file') parser.add_argument('--dir_type', default='weights', help='direction type: weights | states (including BN\'s running_mean/var)') parser.add_argument('--x', default='-1:1:51', help='A string with format xmin:x_max:xnum') parser.add_argument('--y', default=None, help='A string with format ymin:ymax:ynum') parser.add_argument('--xnorm', default='', help='direction normalization: filter | layer | weight') parser.add_argument('--ynorm', default='', help='direction normalization: filter | layer | weight') parser.add_argument('--xignore', default='', help='ignore bias and BN parameters: biasbn') parser.add_argument('--yignore', default='', help='ignore bias and BN parameters: biasbn') parser.add_argument('--idx', default=0, type=int, help='the index for the repeatness experiment') parser.add_argument('--surf_file', default='', help='customize the name of surface file, could be an existing file.') # plot parameters parser.add_argument('--show', action='store_true', default=False, help='show plotted figures') parser.add_argument('--plot', action='store_true', default=False, help='plot figures after computation') args = parser.parse_args() torch.manual_seed(123) #-------------------------------------------------------------------------- # Environment setup #-------------------------------------------------------------------------- if args.mpi: comm = mpi4pytorch.setup_MPI() rank, nproc = comm.Get_rank(), comm.Get_size() else: comm, rank, nproc = None, 0, 1 # in case of multiple GPUs per node, set the GPU to use for each rank if args.cuda: if not torch.cuda.is_available(): raise Exception('User selected cuda option, but cuda is not available on this machine') gpu_count = torch.cuda.device_count() torch.cuda.set_device(rank % gpu_count) print('Rank %d use GPU %d of %d GPUs on %s' % (rank, torch.cuda.current_device(), gpu_count, socket.gethostname())) #-------------------------------------------------------------------------- # Check plotting resolution #-------------------------------------------------------------------------- try: args.xmin, args.xmax, args.xnum = [float(a) for a in args.x.split(':')] args.ymin, args.ymax, args.ynum = (None, None, None) if args.y: args.ymin, args.ymax, args.ynum = [float(a) for a in args.y.split(':')] assert args.ymin and args.ymax and args.ynum, \ 'You specified some arguments for the y axis, but not all' except: raise Exception('Improper format for x- or y-coordinates. Try something like -1:1:51') #-------------------------------------------------------------------------- # Load models and extract parameters #-------------------------------------------------------------------------- net = model_loader.load(args.dataset, args.model, args.model_file) w = net_plotter.get_weights(net) # initial parameters s = copy.deepcopy(net.state_dict()) # deepcopy since state_dict are references if args.ngpu > 1: # data parallel with multiple GPUs on a single node net = nn.DataParallel(net, device_ids=range(torch.cuda.device_count())) #-------------------------------------------------------------------------- # Setup the direction file and the surface file #-------------------------------------------------------------------------- dir_file = net_plotter.name_direction_file(args) # name the direction file if rank == 0: net_plotter.setup_direction(args, dir_file, net) surf_file = name_surface_file(args, dir_file) if rank == 0: setup_surface_file(args, surf_file, dir_file) # wait until master has setup the direction file and surface file mpi4pytorch.barrier(comm) # load directions d = net_plotter.load_directions(dir_file) # calculate the consine similarity of the two directions if len(d) == 2 and rank == 0: similarity = proj.cal_angle(proj.nplist_to_tensor(d[0]), proj.nplist_to_tensor(d[1])) print('cosine similarity between x-axis and y-axis: %f' % similarity) #-------------------------------------------------------------------------- # Setup dataloader #-------------------------------------------------------------------------- # download CIFAR10 if it does not exit if rank == 0 and args.dataset == 'cifar10': torchvision.datasets.CIFAR10(root=args.dataset + '/data', train=True, download=True) mpi4pytorch.barrier(comm) trainloader, testloader = dataloader.load_dataset(args.dataset, args.datapath, args.batch_size, args.threads, args.raw_data, args.data_split, args.split_idx, args.trainloader, args.testloader) #-------------------------------------------------------------------------- # Start the computation #-------------------------------------------------------------------------- crunch_hessian_eigs(surf_file, net, w, s, d, trainloader, comm, rank, args) print ("Rank " + str(rank) + ' is done!') #-------------------------------------------------------------------------- # Plot figures #-------------------------------------------------------------------------- if args.plot and rank == 0: if args.y: plot_2D.plot_2d_eig_ratio(surf_file, 'min_eig', 'max_eig', args.show) else: plot_1D.plot_1d_eig_ratio(surf_file, args.xmin, args.xmax, 'min_eig', 'max_eig')
2881099/FreeSql.AdminLTE
19,513
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-bs5.min.css
@font-face{font-display:auto;font-family:summernote;font-style:normal;font-weight:400;src:url(font/summernote.eot?#iefix) format("embedded-opentype"),url(font/summernote.woff2) format("woff2"),url(font/summernote.woff) format("woff"),url(font/summernote.ttf) format("truetype")}[class*=" note-icon"]:before,[class^=note-icon]:before{text-rendering:auto;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;speak:none;display:inline-block;font-family:summernote;font-size:inherit;font-style:normal;text-decoration:inherit;text-transform:none;vertical-align:middle}.note-icon-fw{text-align:center;width:1.25em}.note-icon-border{border:.08em solid #eee;border-radius:.1em;padding:.2em .25em .15em}.note-icon-pull-left{float:left}.note-icon-pull-right{float:right}.note-icon.note-icon-pull-left{margin-right:.3em}.note-icon.note-icon-pull-right{margin-left:.3em}.note-icon-align:before{content:"\ea01"}.note-icon-align-center:before{content:"\ea02"}.note-icon-align-indent:before{content:"\ea03"}.note-icon-align-justify:before{content:"\ea04"}.note-icon-align-left:before{content:"\ea05"}.note-icon-align-outdent:before{content:"\ea06"}.note-icon-align-right:before{content:"\ea07"}.note-icon-arrow-circle-down:before{content:"\ea08"}.note-icon-arrow-circle-left:before{content:"\ea09"}.note-icon-arrow-circle-right:before{content:"\ea0a"}.note-icon-arrow-circle-up:before{content:"\ea0b"}.note-icon-arrows-alt:before{content:"\ea0c"}.note-icon-arrows-h:before{content:"\ea0d"}.note-icon-arrows-v:before{content:"\ea0e"}.note-icon-bold:before{content:"\ea0f"}.note-icon-caret:before{content:"\ea10"}.note-icon-chain-broken:before{content:"\ea11"}.note-icon-circle:before{content:"\ea12"}.note-icon-close:before{content:"\ea13"}.note-icon-code:before{content:"\ea14"}.note-icon-col-after:before{content:"\ea15"}.note-icon-col-before:before{content:"\ea16"}.note-icon-col-remove:before{content:"\ea17"}.note-icon-eraser:before{content:"\ea18"}.note-icon-float-left:before{content:"\ea19"}.note-icon-float-none:before{content:"\ea1a"}.note-icon-float-right:before{content:"\ea1b"}.note-icon-font:before{content:"\ea1c"}.note-icon-frame:before{content:"\ea1d"}.note-icon-italic:before{content:"\ea1e"}.note-icon-link:before{content:"\ea1f"}.note-icon-magic:before{content:"\ea20"}.note-icon-menu-check:before{content:"\ea21"}.note-icon-minus:before{content:"\ea22"}.note-icon-orderedlist:before{content:"\ea23"}.note-icon-pencil:before{content:"\ea24"}.note-icon-picture:before{content:"\ea25"}.note-icon-question:before{content:"\ea26"}.note-icon-redo:before{content:"\ea27"}.note-icon-rollback:before{content:"\ea28"}.note-icon-row-above:before{content:"\ea29"}.note-icon-row-below:before{content:"\ea2a"}.note-icon-row-remove:before{content:"\ea2b"}.note-icon-special-character:before{content:"\ea2c"}.note-icon-square:before{content:"\ea2d"}.note-icon-strikethrough:before{content:"\ea2e"}.note-icon-subscript:before{content:"\ea2f"}.note-icon-summernote:before{content:"\ea30"}.note-icon-superscript:before{content:"\ea31"}.note-icon-table:before{content:"\ea32"}.note-icon-text-height:before{content:"\ea33"}.note-icon-trash:before{content:"\ea34"}.note-icon-underline:before{content:"\ea35"}.note-icon-undo:before{content:"\ea36"}.note-icon-unorderedlist:before{content:"\ea37"}.note-icon-video:before{content:"\ea38"}.note-editor{position:relative}.note-editor .note-dropzone{background-color:#fff;color:#87cefa;display:none;opacity:.95;position:absolute;z-index:100}.note-editor .note-dropzone .note-dropzone-message{display:table-cell;font-size:28px;font-weight:700;text-align:center;vertical-align:middle}.note-editor .note-dropzone.hover{color:#098ddf}.note-editor.dragover .note-dropzone{display:table}.note-editor .note-editing-area{position:relative}.note-editor .note-editing-area .note-editable{outline:none}.note-editor .note-editing-area .note-editable sup{vertical-align:super}.note-editor .note-editing-area .note-editable sub{vertical-align:sub}.note-editor .note-editing-area .note-editable img.note-float-left{margin-right:10px}.note-editor .note-editing-area .note-editable img.note-float-right{margin-left:10px}.note-editor.note-airframe,.note-editor.note-frame{border:1px solid #00000032}.note-editor.note-airframe.codeview .note-editing-area .note-editable,.note-editor.note-frame.codeview .note-editing-area .note-editable{display:none}.note-editor.note-airframe.codeview .note-editing-area .note-codable,.note-editor.note-frame.codeview .note-editing-area .note-codable{display:block}.note-editor.note-airframe .note-editing-area,.note-editor.note-frame .note-editing-area{overflow:hidden}.note-editor.note-airframe .note-editing-area .note-editable,.note-editor.note-frame .note-editing-area .note-editable{word-wrap:break-word;overflow:auto;padding:10px}.note-editor.note-airframe .note-editing-area .note-editable[contenteditable=false],.note-editor.note-frame .note-editing-area .note-editable[contenteditable=false]{background-color:#8080801d}.note-editor.note-airframe .note-editing-area .note-codable,.note-editor.note-frame .note-editing-area .note-codable{background-color:#222;border:none;border-radius:0;box-shadow:none;-ms-box-sizing:border-box;box-sizing:border-box;color:#ccc;display:none;font-family:Menlo,Monaco,monospace,sans-serif;font-size:14px;margin-bottom:0;outline:none;padding:10px;resize:none;width:100%}.note-editor.note-airframe.fullscreen,.note-editor.note-frame.fullscreen{left:0;position:fixed;top:0;width:100%!important;z-index:1050}.note-editor.note-airframe.fullscreen .note-resizebar,.note-editor.note-frame.fullscreen .note-resizebar{display:none}.note-editor.note-airframe .note-status-output,.note-editor.note-frame .note-status-output{border:0;border-top:1px solid #e2e2e2;color:#000;display:block;font-size:14px;height:20px;line-height:1.42857143;margin-bottom:0;width:100%}.note-editor.note-airframe .note-status-output:empty,.note-editor.note-frame .note-status-output:empty{border-top:0 solid transparent;height:0}.note-editor.note-airframe .note-status-output .pull-right,.note-editor.note-frame .note-status-output .pull-right{float:right!important}.note-editor.note-airframe .note-status-output .text-muted,.note-editor.note-frame .note-status-output .text-muted{color:#777}.note-editor.note-airframe .note-status-output .text-primary,.note-editor.note-frame .note-status-output .text-primary{color:#286090}.note-editor.note-airframe .note-status-output .text-success,.note-editor.note-frame .note-status-output .text-success{color:#3c763d}.note-editor.note-airframe .note-status-output .text-info,.note-editor.note-frame .note-status-output .text-info{color:#31708f}.note-editor.note-airframe .note-status-output .text-warning,.note-editor.note-frame .note-status-output .text-warning{color:#8a6d3b}.note-editor.note-airframe .note-status-output .text-danger,.note-editor.note-frame .note-status-output .text-danger{color:#a94442}.note-editor.note-airframe .note-status-output .alert,.note-editor.note-frame .note-status-output .alert{background-color:#f5f5f5;border-radius:0;color:#000;margin:-7px 0 0;padding:7px 10px 2px}.note-editor.note-airframe .note-status-output .alert .note-icon,.note-editor.note-frame .note-status-output .alert .note-icon{margin-right:5px}.note-editor.note-airframe .note-status-output .alert-success,.note-editor.note-frame .note-status-output .alert-success{background-color:#dff0d8!important;color:#3c763d!important}.note-editor.note-airframe .note-status-output .alert-info,.note-editor.note-frame .note-status-output .alert-info{background-color:#d9edf7!important;color:#31708f!important}.note-editor.note-airframe .note-status-output .alert-warning,.note-editor.note-frame .note-status-output .alert-warning{background-color:#fcf8e3!important;color:#8a6d3b!important}.note-editor.note-airframe .note-status-output .alert-danger,.note-editor.note-frame .note-status-output .alert-danger{background-color:#f2dede!important;color:#a94442!important}.note-editor.note-airframe .note-statusbar,.note-editor.note-frame .note-statusbar{background-color:#8080801d;border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-top:1px solid #00000032}.note-editor.note-airframe .note-statusbar .note-resizebar,.note-editor.note-frame .note-statusbar .note-resizebar{cursor:ns-resize;height:9px;padding-top:1px;width:100%}.note-editor.note-airframe .note-statusbar .note-resizebar .note-icon-bar,.note-editor.note-frame .note-statusbar .note-resizebar .note-icon-bar{border-top:1px solid #00000032;margin:1px auto;width:20px}.note-editor.note-airframe .note-statusbar.locked .note-resizebar,.note-editor.note-frame .note-statusbar.locked .note-resizebar{cursor:default}.note-editor.note-airframe .note-statusbar.locked .note-resizebar .note-icon-bar,.note-editor.note-frame .note-statusbar.locked .note-resizebar .note-icon-bar{display:none}.note-editor.note-airframe .note-placeholder,.note-editor.note-frame .note-placeholder{padding:10px}.note-editor.note-airframe{border:0}.note-editor.note-airframe .note-editing-area .note-editable{padding:0}.note-popover.popover{display:none;max-width:none}.note-popover.popover .popover-content a{display:inline-block;max-width:200px;overflow:hidden;text-overflow:ellipsis;vertical-align:middle;white-space:nowrap}.note-popover.popover .arrow{left:20px!important}.note-toolbar{position:relative}.note-editor .note-toolbar,.note-popover .popover-content{margin:0;padding:0 0 5px 5px}.note-editor .note-toolbar>.note-btn-group,.note-popover .popover-content>.note-btn-group{margin-left:0;margin-right:5px;margin-top:5px}.note-editor .note-toolbar .note-btn-group .note-table,.note-popover .popover-content .note-btn-group .note-table{min-width:0;padding:5px}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker{font-size:18px}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher{cursor:pointer;height:10em;position:absolute!important;width:10em;z-index:3}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted{background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIj4+Pjp6ekKlAqjAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKhmnaJzPAAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat;height:5em;position:relative!important;width:5em;z-index:1}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted{background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIjd6vvD2f9LKLW+AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKwNDEVT0AAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat;height:1em;position:absolute!important;width:1em;z-index:2}.note-editor .note-toolbar .note-style .dropdown-style blockquote,.note-editor .note-toolbar .note-style .dropdown-style pre,.note-popover .popover-content .note-style .dropdown-style blockquote,.note-popover .popover-content .note-style .dropdown-style pre{margin:0;padding:5px 10px}.note-editor .note-toolbar .note-style .dropdown-style h1,.note-editor .note-toolbar .note-style .dropdown-style h2,.note-editor .note-toolbar .note-style .dropdown-style h3,.note-editor .note-toolbar .note-style .dropdown-style h4,.note-editor .note-toolbar .note-style .dropdown-style h5,.note-editor .note-toolbar .note-style .dropdown-style h6,.note-editor .note-toolbar .note-style .dropdown-style p,.note-popover .popover-content .note-style .dropdown-style h1,.note-popover .popover-content .note-style .dropdown-style h2,.note-popover .popover-content .note-style .dropdown-style h3,.note-popover .popover-content .note-style .dropdown-style h4,.note-popover .popover-content .note-style .dropdown-style h5,.note-popover .popover-content .note-style .dropdown-style h6,.note-popover .popover-content .note-style .dropdown-style p{margin:0;padding:0}.note-editor .note-toolbar .note-color-all .note-dropdown-menu,.note-popover .popover-content .note-color-all .note-dropdown-menu{min-width:337px}.note-editor .note-toolbar .note-color .dropdown-toggle,.note-popover .popover-content .note-color .dropdown-toggle{padding-left:5px;width:20px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette{display:inline-block;margin:0;width:160px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette:first-child,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette:first-child{margin:0 5px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-palette-title,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-palette-title{border-bottom:1px solid #eee;font-size:12px;margin:2px 7px;text-align:center}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset,.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select{border-radius:5px;cursor:pointer;font-size:11px;margin:3px;padding:0 3px;width:100%}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset:hover,.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select:hover,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset:hover,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select:hover{background:#eee}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-row,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-row{height:20px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select-btn,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select-btn{display:none}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn{border:1px solid #eee}.note-editor .note-toolbar .note-para .note-dropdown-menu,.note-popover .popover-content .note-para .note-dropdown-menu{min-width:228px;padding:5px}.note-editor .note-toolbar .note-para .note-dropdown-menu>div+div,.note-popover .popover-content .note-para .note-dropdown-menu>div+div{margin-left:5px}.note-editor .note-toolbar .note-dropdown-menu,.note-popover .popover-content .note-dropdown-menu{min-width:160px}.note-editor .note-toolbar .note-dropdown-menu.right,.note-popover .popover-content .note-dropdown-menu.right{left:auto;right:0}.note-editor .note-toolbar .note-dropdown-menu.right:before,.note-popover .popover-content .note-dropdown-menu.right:before{left:auto!important;right:9px}.note-editor .note-toolbar .note-dropdown-menu.right:after,.note-popover .popover-content .note-dropdown-menu.right:after{left:auto!important;right:10px}.note-editor .note-toolbar .note-dropdown-menu.note-check a i,.note-popover .popover-content .note-dropdown-menu.note-check a i{color:#00bfff;visibility:hidden}.note-editor .note-toolbar .note-dropdown-menu.note-check a.checked i,.note-popover .popover-content .note-dropdown-menu.note-check a.checked i{visibility:visible}.note-editor .note-toolbar .note-fontsize-10,.note-popover .popover-content .note-fontsize-10{font-size:10px}.note-editor .note-toolbar .note-color-palette,.note-popover .popover-content .note-color-palette{line-height:1}.note-editor .note-toolbar .note-color-palette div .note-color-btn,.note-popover .popover-content .note-color-palette div .note-color-btn{border:0;border-radius:0;height:20px;margin:0;padding:0;width:20px}.note-editor .note-toolbar .note-color-palette div .note-color-btn:hover,.note-popover .popover-content .note-color-palette div .note-color-btn:hover{transform:scale(1.2);transition:all .2s}.note-modal .modal-dialog{border-radius:5px;box-shadow:0 3px 9px rgba(0,0,0,.5);outline:0}.note-modal .form-group{margin-left:0;margin-right:0}.note-modal .note-modal-form{margin:0}.note-modal .note-image-dialog .note-dropzone{border:4px dashed #d3d3d3;color:#d3d3d3;font-size:30px;line-height:4;margin-bottom:10px;min-height:100px;text-align:center}@-moz-document url-prefix(){.note-modal .note-image-input{height:auto}}.note-placeholder{color:gray;display:none;position:absolute}.note-handle .note-control-selection{border:1px solid #000;display:none;position:absolute}.note-handle .note-control-selection>div{position:absolute}.note-handle .note-control-selection .note-control-selection-bg{background-color:#000;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30);filter:alpha(opacity=30);height:100%;-webkit-opacity:.3;-khtml-opacity:.3;-moz-opacity:.3;opacity:.3;width:100%}.note-handle .note-control-selection .note-control-handle,.note-handle .note-control-selection .note-control-holder,.note-handle .note-control-selection .note-control-sizing{border:1px solid #000;height:7px;width:7px}.note-handle .note-control-selection .note-control-sizing{background-color:#000}.note-handle .note-control-selection .note-control-nw{border-bottom:none;border-right:none;left:-5px;top:-5px}.note-handle .note-control-selection .note-control-ne{border-bottom:none;border-left:none;right:-5px;top:-5px}.note-handle .note-control-selection .note-control-sw{border-right:none;border-top:none;bottom:-5px;left:-5px}.note-handle .note-control-selection .note-control-se{bottom:-5px;cursor:se-resize;right:-5px}.note-handle .note-control-selection .note-control-se.note-control-holder{border-left:none;border-top:none;cursor:default}.note-handle .note-control-selection .note-control-selection-info{background-color:#000;border-radius:5px;bottom:0;color:#fff;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=70);filter:alpha(opacity=70);font-size:12px;margin:5px;-webkit-opacity:.7;-khtml-opacity:.7;-moz-opacity:.7;opacity:.7;padding:5px;right:0}.note-hint-popover{min-width:100px;padding:2px}.note-hint-popover .popover-content{max-height:150px;overflow:auto;padding:3px}.note-hint-popover .popover-content .note-hint-group .note-hint-item{display:block!important;padding:3px}.note-hint-popover .popover-content .note-hint-group .note-hint-item.active,.note-hint-popover .popover-content .note-hint-group .note-hint-item:hover{background-color:#428bca;clear:both;color:#fff;cursor:pointer;display:block;font-weight:400;line-height:1.4;outline:0;text-decoration:none;white-space:nowrap}body .note-fullscreen-body,html .note-fullscreen-body{overflow:hidden!important}.note-toolbar{background:#8080801d}.note-btn-group .note-btn{border-color:#00000032;font-size:13px;padding:.28rem .65rem}
281677160/openwrt-package
2,124
luci-app-nginx-pingos/luasrc/model/cbi/pingos.lua
m = Map("pingos", translate("PingOS")) m:append(Template("pingos/status")) s = m:section(TypedSection, "global") s.anonymous = true s.addremove = false s:tab("global", translate("Global Settings")) s:tab("template", translate("Edit Template")) nginx = s:taboption("template", Value, "_nginx", translatef("Edit the template that is used for generating the %s configuration.", "nginx"), translatef("This is the content of the file '%s'", "/etc/pingos.template") .. "<br />" .. translatef("Values enclosed by pipe symbols ('|') should not be changed. They get their values from the '%s' tab.", translate("Global Settings"))) nginx.template = "cbi/tvalue" nginx.rows = 30 function nginx.cfgvalue(self, section) return nixio.fs.readfile("/etc/pingos.template") end function nginx.write(self, section, value) value = value:gsub("\r\n?", "\n") nixio.fs.writefile("/etc/pingos.template", value) end o = s:taboption("global", Flag, "enable", translate("Enable")) o.rmempty = false o = s:taboption("global", Flag, "ipv6", translate("Listen IPv6")) o.rmempty = false o = s:taboption("global", Value, "http_port", "HTTP(S)" ..translate("Port")) o.datatype = "port" o.default = 8082 o.rmempty = false o = s:taboption("global", Flag, "https", translate("HTTPS")) o.rmempty = false o = s:taboption("global", FileUpload, "certificate", translate("certificate")) o:depends("https", 1) o = s:taboption("global", FileUpload, "key", translate("key")) o:depends("https", 1) o = s:taboption("global", Value, "rtmp_port", "RTMP" ..translate("Port")) o.datatype = "port" o.default = 1935 o.rmempty = false o = s:taboption("global", Flag, "hls", translate("HLS")) o.rmempty = false o = s:taboption("global", Flag, "hls2", translate("HLS2")) o.rmempty = false o = s:taboption("global", Flag, "ts_record", "TS " .. translate("Record")) o.rmempty = false o = s:taboption("global", Flag, "flv_record", "FLV " .. translate("Record")) o.rmempty = false o = s:taboption("global", Value, "record_path", translate("Record") .. translate("Path")) o.default = "/tmp/record" o:depends("ts_record", 1) o:depends("flv_record", 1) return m
294coder/Efficient-MIF
3,372
utils/loss_landscape/scheduler.py
""" A task scheduler that assign unfinished jobs to different workers. """ import numpy as np def get_unplotted_indices(vals, xcoordinates, ycoordinates=None): """ Args: vals: values at (x, y), with value -1 when the value is not yet calculated. xcoordinates: x locations, i.e.,[-1, -0.5, 0, 0.5, 1] ycoordinates: y locations, i.e.,[-1, -0.5, 0, 0.5, 1] Returns: - a list of indices into vals for points that have not yet been calculated. - a list of corresponding coordinates, with one x/y coordinate per row. """ # Create a list of indices into the vectorizes vals inds = np.array(range(vals.size)) # Select the indices of the un-recorded entries, assuming un-recorded entries # will be smaller than zero. In case some vals (other than loss values) are # negative and those indexces will be selected again and calcualted over and over. inds = inds[vals.ravel() <= 0] # Make lists containing the x- and y-coodinates of the points to be plotted if ycoordinates is not None: # If the plot is 2D, then use meshgrid to enumerate all coordinates in the 2D mesh xcoord_mesh, ycoord_mesh = np.meshgrid(xcoordinates, ycoordinates) s1 = xcoord_mesh.ravel()[inds] s2 = ycoord_mesh.ravel()[inds] return inds, np.c_[s1,s2] else: return inds, xcoordinates.ravel()[inds] def split_inds(num_inds, nproc): """ Evenly slice out a set of jobs that are handled by each MPI process. - Assuming each job takes the same amount of time. - Each process handles an (approx) equal size slice of jobs. - If the number of processes is larger than rows to divide up, then some high-rank processes will receive an empty slice rows, e.g., there will be 3, 2, 2, 2 jobs assigned to rank0, rank1, rank2, rank3 given 9 jobs with 4 MPI processes. """ chunk = num_inds // nproc remainder = num_inds % nproc splitted_idx = [] for rank in range(0, nproc): # Set the starting index for this slice start_idx = rank * chunk + min(rank, remainder) # The stopping index can't go beyond the end of the array stop_idx = start_idx + chunk + (rank < remainder) splitted_idx.append(range(start_idx, stop_idx)) return splitted_idx def get_job_indices(vals, xcoordinates, ycoordinates, comm): """ Prepare the job indices over which coordinate to calculate. Args: vals: the value matrix xcoordinates: x locations, i.e.,[-1, -0.5, 0, 0.5, 1] ycoordinates: y locations, i.e.,[-1, -0.5, 0, 0.5, 1] comm: MPI environment Returns: inds: indices that splitted for current rank coords: coordinates for current rank inds_nums: max number of indices for all ranks """ inds, coords = get_unplotted_indices(vals, xcoordinates, ycoordinates) rank = 0 if comm is None else comm.Get_rank() nproc = 1 if comm is None else comm.Get_size() splitted_idx = split_inds(len(inds), nproc) # Split the indices over the available MPI processes inds = inds[splitted_idx[rank]] coords = coords[splitted_idx[rank]] # Figure out the number of jobs that each MPI process needs to calculate. inds_nums = [len(idx) for idx in splitted_idx] return inds, coords, inds_nums
2881099/FreeSql.AdminLTE
19,513
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/summernote/summernote-bs4.min.css
@font-face{font-display:auto;font-family:summernote;font-style:normal;font-weight:400;src:url(font/summernote.eot?#iefix) format("embedded-opentype"),url(font/summernote.woff2) format("woff2"),url(font/summernote.woff) format("woff"),url(font/summernote.ttf) format("truetype")}[class*=" note-icon"]:before,[class^=note-icon]:before{text-rendering:auto;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;speak:none;display:inline-block;font-family:summernote;font-size:inherit;font-style:normal;text-decoration:inherit;text-transform:none;vertical-align:middle}.note-icon-fw{text-align:center;width:1.25em}.note-icon-border{border:.08em solid #eee;border-radius:.1em;padding:.2em .25em .15em}.note-icon-pull-left{float:left}.note-icon-pull-right{float:right}.note-icon.note-icon-pull-left{margin-right:.3em}.note-icon.note-icon-pull-right{margin-left:.3em}.note-icon-align:before{content:"\ea01"}.note-icon-align-center:before{content:"\ea02"}.note-icon-align-indent:before{content:"\ea03"}.note-icon-align-justify:before{content:"\ea04"}.note-icon-align-left:before{content:"\ea05"}.note-icon-align-outdent:before{content:"\ea06"}.note-icon-align-right:before{content:"\ea07"}.note-icon-arrow-circle-down:before{content:"\ea08"}.note-icon-arrow-circle-left:before{content:"\ea09"}.note-icon-arrow-circle-right:before{content:"\ea0a"}.note-icon-arrow-circle-up:before{content:"\ea0b"}.note-icon-arrows-alt:before{content:"\ea0c"}.note-icon-arrows-h:before{content:"\ea0d"}.note-icon-arrows-v:before{content:"\ea0e"}.note-icon-bold:before{content:"\ea0f"}.note-icon-caret:before{content:"\ea10"}.note-icon-chain-broken:before{content:"\ea11"}.note-icon-circle:before{content:"\ea12"}.note-icon-close:before{content:"\ea13"}.note-icon-code:before{content:"\ea14"}.note-icon-col-after:before{content:"\ea15"}.note-icon-col-before:before{content:"\ea16"}.note-icon-col-remove:before{content:"\ea17"}.note-icon-eraser:before{content:"\ea18"}.note-icon-float-left:before{content:"\ea19"}.note-icon-float-none:before{content:"\ea1a"}.note-icon-float-right:before{content:"\ea1b"}.note-icon-font:before{content:"\ea1c"}.note-icon-frame:before{content:"\ea1d"}.note-icon-italic:before{content:"\ea1e"}.note-icon-link:before{content:"\ea1f"}.note-icon-magic:before{content:"\ea20"}.note-icon-menu-check:before{content:"\ea21"}.note-icon-minus:before{content:"\ea22"}.note-icon-orderedlist:before{content:"\ea23"}.note-icon-pencil:before{content:"\ea24"}.note-icon-picture:before{content:"\ea25"}.note-icon-question:before{content:"\ea26"}.note-icon-redo:before{content:"\ea27"}.note-icon-rollback:before{content:"\ea28"}.note-icon-row-above:before{content:"\ea29"}.note-icon-row-below:before{content:"\ea2a"}.note-icon-row-remove:before{content:"\ea2b"}.note-icon-special-character:before{content:"\ea2c"}.note-icon-square:before{content:"\ea2d"}.note-icon-strikethrough:before{content:"\ea2e"}.note-icon-subscript:before{content:"\ea2f"}.note-icon-summernote:before{content:"\ea30"}.note-icon-superscript:before{content:"\ea31"}.note-icon-table:before{content:"\ea32"}.note-icon-text-height:before{content:"\ea33"}.note-icon-trash:before{content:"\ea34"}.note-icon-underline:before{content:"\ea35"}.note-icon-undo:before{content:"\ea36"}.note-icon-unorderedlist:before{content:"\ea37"}.note-icon-video:before{content:"\ea38"}.note-editor{position:relative}.note-editor .note-dropzone{background-color:#fff;color:#87cefa;display:none;opacity:.95;position:absolute;z-index:100}.note-editor .note-dropzone .note-dropzone-message{display:table-cell;font-size:28px;font-weight:700;text-align:center;vertical-align:middle}.note-editor .note-dropzone.hover{color:#098ddf}.note-editor.dragover .note-dropzone{display:table}.note-editor .note-editing-area{position:relative}.note-editor .note-editing-area .note-editable{outline:none}.note-editor .note-editing-area .note-editable sup{vertical-align:super}.note-editor .note-editing-area .note-editable sub{vertical-align:sub}.note-editor .note-editing-area .note-editable img.note-float-left{margin-right:10px}.note-editor .note-editing-area .note-editable img.note-float-right{margin-left:10px}.note-editor.note-airframe,.note-editor.note-frame{border:1px solid #00000032}.note-editor.note-airframe.codeview .note-editing-area .note-editable,.note-editor.note-frame.codeview .note-editing-area .note-editable{display:none}.note-editor.note-airframe.codeview .note-editing-area .note-codable,.note-editor.note-frame.codeview .note-editing-area .note-codable{display:block}.note-editor.note-airframe .note-editing-area,.note-editor.note-frame .note-editing-area{overflow:hidden}.note-editor.note-airframe .note-editing-area .note-editable,.note-editor.note-frame .note-editing-area .note-editable{word-wrap:break-word;overflow:auto;padding:10px}.note-editor.note-airframe .note-editing-area .note-editable[contenteditable=false],.note-editor.note-frame .note-editing-area .note-editable[contenteditable=false]{background-color:#8080801d}.note-editor.note-airframe .note-editing-area .note-codable,.note-editor.note-frame .note-editing-area .note-codable{background-color:#222;border:none;border-radius:0;box-shadow:none;-ms-box-sizing:border-box;box-sizing:border-box;color:#ccc;display:none;font-family:Menlo,Monaco,monospace,sans-serif;font-size:14px;margin-bottom:0;outline:none;padding:10px;resize:none;width:100%}.note-editor.note-airframe.fullscreen,.note-editor.note-frame.fullscreen{left:0;position:fixed;top:0;width:100%!important;z-index:1050}.note-editor.note-airframe.fullscreen .note-resizebar,.note-editor.note-frame.fullscreen .note-resizebar{display:none}.note-editor.note-airframe .note-status-output,.note-editor.note-frame .note-status-output{border:0;border-top:1px solid #e2e2e2;color:#000;display:block;font-size:14px;height:20px;line-height:1.42857143;margin-bottom:0;width:100%}.note-editor.note-airframe .note-status-output:empty,.note-editor.note-frame .note-status-output:empty{border-top:0 solid transparent;height:0}.note-editor.note-airframe .note-status-output .pull-right,.note-editor.note-frame .note-status-output .pull-right{float:right!important}.note-editor.note-airframe .note-status-output .text-muted,.note-editor.note-frame .note-status-output .text-muted{color:#777}.note-editor.note-airframe .note-status-output .text-primary,.note-editor.note-frame .note-status-output .text-primary{color:#286090}.note-editor.note-airframe .note-status-output .text-success,.note-editor.note-frame .note-status-output .text-success{color:#3c763d}.note-editor.note-airframe .note-status-output .text-info,.note-editor.note-frame .note-status-output .text-info{color:#31708f}.note-editor.note-airframe .note-status-output .text-warning,.note-editor.note-frame .note-status-output .text-warning{color:#8a6d3b}.note-editor.note-airframe .note-status-output .text-danger,.note-editor.note-frame .note-status-output .text-danger{color:#a94442}.note-editor.note-airframe .note-status-output .alert,.note-editor.note-frame .note-status-output .alert{background-color:#f5f5f5;border-radius:0;color:#000;margin:-7px 0 0;padding:7px 10px 2px}.note-editor.note-airframe .note-status-output .alert .note-icon,.note-editor.note-frame .note-status-output .alert .note-icon{margin-right:5px}.note-editor.note-airframe .note-status-output .alert-success,.note-editor.note-frame .note-status-output .alert-success{background-color:#dff0d8!important;color:#3c763d!important}.note-editor.note-airframe .note-status-output .alert-info,.note-editor.note-frame .note-status-output .alert-info{background-color:#d9edf7!important;color:#31708f!important}.note-editor.note-airframe .note-status-output .alert-warning,.note-editor.note-frame .note-status-output .alert-warning{background-color:#fcf8e3!important;color:#8a6d3b!important}.note-editor.note-airframe .note-status-output .alert-danger,.note-editor.note-frame .note-status-output .alert-danger{background-color:#f2dede!important;color:#a94442!important}.note-editor.note-airframe .note-statusbar,.note-editor.note-frame .note-statusbar{background-color:#8080801d;border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-top:1px solid #00000032}.note-editor.note-airframe .note-statusbar .note-resizebar,.note-editor.note-frame .note-statusbar .note-resizebar{cursor:ns-resize;height:9px;padding-top:1px;width:100%}.note-editor.note-airframe .note-statusbar .note-resizebar .note-icon-bar,.note-editor.note-frame .note-statusbar .note-resizebar .note-icon-bar{border-top:1px solid #00000032;margin:1px auto;width:20px}.note-editor.note-airframe .note-statusbar.locked .note-resizebar,.note-editor.note-frame .note-statusbar.locked .note-resizebar{cursor:default}.note-editor.note-airframe .note-statusbar.locked .note-resizebar .note-icon-bar,.note-editor.note-frame .note-statusbar.locked .note-resizebar .note-icon-bar{display:none}.note-editor.note-airframe .note-placeholder,.note-editor.note-frame .note-placeholder{padding:10px}.note-editor.note-airframe{border:0}.note-editor.note-airframe .note-editing-area .note-editable{padding:0}.note-popover.popover{display:none;max-width:none}.note-popover.popover .popover-content a{display:inline-block;max-width:200px;overflow:hidden;text-overflow:ellipsis;vertical-align:middle;white-space:nowrap}.note-popover.popover .arrow{left:20px!important}.note-toolbar{position:relative}.note-editor .note-toolbar,.note-popover .popover-content{margin:0;padding:0 0 5px 5px}.note-editor .note-toolbar>.note-btn-group,.note-popover .popover-content>.note-btn-group{margin-left:0;margin-right:5px;margin-top:5px}.note-editor .note-toolbar .note-btn-group .note-table,.note-popover .popover-content .note-btn-group .note-table{min-width:0;padding:5px}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker{font-size:18px}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-mousecatcher{cursor:pointer;height:10em;position:absolute!important;width:10em;z-index:3}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-unhighlighted{background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIj4+Pjp6ekKlAqjAAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKhmnaJzPAAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat;height:5em;position:relative!important;width:5em;z-index:1}.note-editor .note-toolbar .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted,.note-popover .popover-content .note-btn-group .note-table .note-dimension-picker .note-dimension-picker-highlighted{background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASAgMAAAAroGbEAAAACVBMVEUAAIjd6vvD2f9LKLW+AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfYAR0BKwNDEVT0AAAAG0lEQVQI12NgAAOtVatWMTCohoaGUY+EmIkEAEruEzK2J7tvAAAAAElFTkSuQmCC") repeat;height:1em;position:absolute!important;width:1em;z-index:2}.note-editor .note-toolbar .note-style .dropdown-style blockquote,.note-editor .note-toolbar .note-style .dropdown-style pre,.note-popover .popover-content .note-style .dropdown-style blockquote,.note-popover .popover-content .note-style .dropdown-style pre{margin:0;padding:5px 10px}.note-editor .note-toolbar .note-style .dropdown-style h1,.note-editor .note-toolbar .note-style .dropdown-style h2,.note-editor .note-toolbar .note-style .dropdown-style h3,.note-editor .note-toolbar .note-style .dropdown-style h4,.note-editor .note-toolbar .note-style .dropdown-style h5,.note-editor .note-toolbar .note-style .dropdown-style h6,.note-editor .note-toolbar .note-style .dropdown-style p,.note-popover .popover-content .note-style .dropdown-style h1,.note-popover .popover-content .note-style .dropdown-style h2,.note-popover .popover-content .note-style .dropdown-style h3,.note-popover .popover-content .note-style .dropdown-style h4,.note-popover .popover-content .note-style .dropdown-style h5,.note-popover .popover-content .note-style .dropdown-style h6,.note-popover .popover-content .note-style .dropdown-style p{margin:0;padding:0}.note-editor .note-toolbar .note-color-all .note-dropdown-menu,.note-popover .popover-content .note-color-all .note-dropdown-menu{min-width:337px}.note-editor .note-toolbar .note-color .dropdown-toggle,.note-popover .popover-content .note-color .dropdown-toggle{padding-left:5px;width:20px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette{display:inline-block;margin:0;width:160px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette:first-child,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette:first-child{margin:0 5px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-palette-title,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-palette-title{border-bottom:1px solid #eee;font-size:12px;margin:2px 7px;text-align:center}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset,.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select{border-radius:5px;cursor:pointer;font-size:11px;margin:3px;padding:0 3px;width:100%}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-reset:hover,.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select:hover,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-reset:hover,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select:hover{background:#eee}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-row,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-row{height:20px}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-color-select-btn,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-color-select-btn{display:none}.note-editor .note-toolbar .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn,.note-popover .popover-content .note-color .note-dropdown-menu .note-palette .note-holder-custom .note-color-btn{border:1px solid #eee}.note-editor .note-toolbar .note-para .note-dropdown-menu,.note-popover .popover-content .note-para .note-dropdown-menu{min-width:228px;padding:5px}.note-editor .note-toolbar .note-para .note-dropdown-menu>div+div,.note-popover .popover-content .note-para .note-dropdown-menu>div+div{margin-left:5px}.note-editor .note-toolbar .note-dropdown-menu,.note-popover .popover-content .note-dropdown-menu{min-width:160px}.note-editor .note-toolbar .note-dropdown-menu.right,.note-popover .popover-content .note-dropdown-menu.right{left:auto;right:0}.note-editor .note-toolbar .note-dropdown-menu.right:before,.note-popover .popover-content .note-dropdown-menu.right:before{left:auto!important;right:9px}.note-editor .note-toolbar .note-dropdown-menu.right:after,.note-popover .popover-content .note-dropdown-menu.right:after{left:auto!important;right:10px}.note-editor .note-toolbar .note-dropdown-menu.note-check a i,.note-popover .popover-content .note-dropdown-menu.note-check a i{color:#00bfff;visibility:hidden}.note-editor .note-toolbar .note-dropdown-menu.note-check a.checked i,.note-popover .popover-content .note-dropdown-menu.note-check a.checked i{visibility:visible}.note-editor .note-toolbar .note-fontsize-10,.note-popover .popover-content .note-fontsize-10{font-size:10px}.note-editor .note-toolbar .note-color-palette,.note-popover .popover-content .note-color-palette{line-height:1}.note-editor .note-toolbar .note-color-palette div .note-color-btn,.note-popover .popover-content .note-color-palette div .note-color-btn{border:0;border-radius:0;height:20px;margin:0;padding:0;width:20px}.note-editor .note-toolbar .note-color-palette div .note-color-btn:hover,.note-popover .popover-content .note-color-palette div .note-color-btn:hover{transform:scale(1.2);transition:all .2s}.note-modal .modal-dialog{border-radius:5px;box-shadow:0 3px 9px rgba(0,0,0,.5);outline:0}.note-modal .form-group{margin-left:0;margin-right:0}.note-modal .note-modal-form{margin:0}.note-modal .note-image-dialog .note-dropzone{border:4px dashed #d3d3d3;color:#d3d3d3;font-size:30px;line-height:4;margin-bottom:10px;min-height:100px;text-align:center}@-moz-document url-prefix(){.note-modal .note-image-input{height:auto}}.note-placeholder{color:gray;display:none;position:absolute}.note-handle .note-control-selection{border:1px solid #000;display:none;position:absolute}.note-handle .note-control-selection>div{position:absolute}.note-handle .note-control-selection .note-control-selection-bg{background-color:#000;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30);filter:alpha(opacity=30);height:100%;-webkit-opacity:.3;-khtml-opacity:.3;-moz-opacity:.3;opacity:.3;width:100%}.note-handle .note-control-selection .note-control-handle,.note-handle .note-control-selection .note-control-holder,.note-handle .note-control-selection .note-control-sizing{border:1px solid #000;height:7px;width:7px}.note-handle .note-control-selection .note-control-sizing{background-color:#000}.note-handle .note-control-selection .note-control-nw{border-bottom:none;border-right:none;left:-5px;top:-5px}.note-handle .note-control-selection .note-control-ne{border-bottom:none;border-left:none;right:-5px;top:-5px}.note-handle .note-control-selection .note-control-sw{border-right:none;border-top:none;bottom:-5px;left:-5px}.note-handle .note-control-selection .note-control-se{bottom:-5px;cursor:se-resize;right:-5px}.note-handle .note-control-selection .note-control-se.note-control-holder{border-left:none;border-top:none;cursor:default}.note-handle .note-control-selection .note-control-selection-info{background-color:#000;border-radius:5px;bottom:0;color:#fff;-ms-filter:progid:DXImageTransform.Microsoft.Alpha(opacity=70);filter:alpha(opacity=70);font-size:12px;margin:5px;-webkit-opacity:.7;-khtml-opacity:.7;-moz-opacity:.7;opacity:.7;padding:5px;right:0}.note-hint-popover{min-width:100px;padding:2px}.note-hint-popover .popover-content{max-height:150px;overflow:auto;padding:3px}.note-hint-popover .popover-content .note-hint-group .note-hint-item{display:block!important;padding:3px}.note-hint-popover .popover-content .note-hint-group .note-hint-item.active,.note-hint-popover .popover-content .note-hint-group .note-hint-item:hover{background-color:#428bca;clear:both;color:#fff;cursor:pointer;display:block;font-weight:400;line-height:1.4;outline:0;text-decoration:none;white-space:nowrap}body .note-fullscreen-body,html .note-fullscreen-body{overflow:hidden!important}.note-toolbar{background:#8080801d}.note-btn-group .note-btn{border-color:#00000032;font-size:13px;padding:.28rem .65rem}
29jitender/Spotlight
2,314
gradlew.bat
@if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega
281677160/openwrt-package
7,101
luci-app-nginx-pingos/modules/nginx-ts-module/README.rst
************************* NGINX MPEG-TS Live Module ************************* .. contents:: Features ======== - receives MPEG-TS over HTTP - produces and manages live HLS_ - produces and manages live MPEG-DASH_ Compatibility ============= - `nginx <http://nginx.org>`_ version >= 1.11.5 Build ===== Building nginx with the module: .. code-block:: bash # static module $ ./configure --add-module=/path/to/nginx-ts-module # dynamic module $ ./configure --add-dynamic-module=/path/to/nginx-ts-module Directives ========== ts -- ========== ======== *Syntax:* ``ts`` *Context:* location ========== ======== Sets up a live MPEG-TS handler for the location. This directive is **required** for HLS or MPEG-DASH generation. The last URI component is used as a stream name. For example, if the URI is ``/foo/bar/baz``, the stream name is ``baz``. A simple way to stream MPEG-TS over HTTP is by running ``ffmpeg``: .. code-block:: bash $ ffmpeg ... -f mpegts http://127.0.0.1:8000/foo By default, HTTP request body size is limited in nginx. To enable live streaming without size limitation, use the directive ``client_max_body_size 0``. ts_hls ------ ========== ======== *Syntax:* ``ts_hls path=PATH [segment=MIN[:MAX]] [segments=NUMBER] [max_size=SIZE] [noclean]`` *Context:* location ========== ======== Enables generating live HLS in the location. The ``PATH`` parameter specifies a directory where HLS playlist and segment files will be created. The directory is created if missing. For every publshed stream a subdirectory with the stream name is created under the ``PATH`` directory. The HLS playlist file created in the stream subdirectory is named ``index.m3u8``. A path handler is installed to watch files in the directory. The old files in the directory are automatically deleted once they get old enough and are not supposed to be accessed by clients anymore. It is not allowed to reuse the path in other ``ts_hls`` or ``ts_dash`` directives. The ``segment`` parameter specifies minimum and maximum segment durations. If the stream has video, segments are started at video key frames. If a key frame does not appear within ``MAX`` duration, the segment is truncated. The default value for minimum segment duration is 5 seconds. If unspecified, maximum segment duration is set to be twice as much as the minimum. The ``segments`` parameter specifies the maximum number of segments in a playlist. As new segments are added to the playlist, the oldest segments are removed from it. The ``max_size`` parameter specifies the maximum size of a segment. A segment is truncated once it reaches this size. The ``noclean`` parameter indicates that the old files (segments and the playlist) should not be automatically deleted from disk. Example:: location / { ts; ts_hls path=/var/hls segment=10s; } ts_dash ------- ========== ======== *Syntax:* ``ts_dash path=PATH [segment=MIN[:MAX]] [segments=NUMBER] [max_size=SIZE] [noclean]`` *Context:* location ========== ======== Enables generating live MPEG-DASH in the location. The ``PATH`` parameter specifies a directory where MPEG-DASH manifest and segment files will be created. The directory is created if missing. For every publshed stream a subdirectory with the stream name is created under the ``PATH`` directory. The MPEG-DASH manifest file created in the stream subdirectory is named ``index.mpd``. A path handler is installed to watch files in the directory. The old files in the directory are automatically deleted once they get old enough and are not supposed to be accessed by clients anymore. It is not allowed to reuse the path in other ``ts_hls`` or ``ts_dash`` directives. The ``segment`` parameter specifies minimum and maximum segment durations. If the stream has video, segments are started at video key frames. If a key frame does not appear within ``MAX`` duration, the segment is truncated. The default value for minimum segment duration is 5 seconds. If unspecified, maximum segment duration is set to be twice as much as the minimum. When setting an explicit value for the ``MAX`` parameter, the following note should be taken into account. If the next segment is shorter than the previous one by a factor more that two, dash.js_ can end up in a busy cycle requesting the second segment over and over again. The ``segments`` parameter specifies the maximum number of segments in a manifest. As new segments are added to the manifest, the oldest segments are removed from it. The ``max_size`` parameter specifies the maximum size of a segment. A segment is truncated once it reaches this size. The ``noclean`` parameter indicates that the old files (segments and the manifest) should not be automatically deleted from disk. Example:: location / { ts; ts_dash path=/var/hls segment=10s; } Example ======= nginx.conf:: # nginx.conf events { } http { server { listen 8000; location / { root html; } location /publish/ { ts; ts_hls path=/var/media/hls segment=10s; ts_dash path=/var/media/dash segment=10s; client_max_body_size 0; } location /play/ { types { application/x-mpegURL m3u8; application/dash+xml mpd; video/MP2T ts; video/mp4 mp4; } alias /var/media/; } } } HLS in HTML: .. code-block:: html <body> <video width="640" height="480" controls autoplay src="http://127.0.0.1:8000/play/hls/sintel/index.m3u8"> </video> </body> MPEG-DASH in HTML using the dash.js_ player: .. code-block:: html <script src="http://cdn.dashjs.org/latest/dash.all.min.js"></script> <body> <video data-dashjs-player width="640" height="480" controls autoplay src="http://127.0.0.1:8000/play/dash/sintel/index.mpd"> </video> </body> Broadcasting a single-bitrate mp4 file: .. code-block:: bash $ ffmpeg -re -i ~/Movies/sintel.mp4 -bsf:v h264_mp4toannexb -c copy -f mpegts http://127.0.0.1:8000/publish/sintel Broadcasting an mp4 file in multiple bitrates. For proper HLS generation streams should be grouped into MPEG-TS programs with the ``-program`` option of ``ffmpeg``: .. code-block:: bash $ ffmpeg -re -i ~/Movies/sintel.mp4 -bsf:v h264_mp4toannexb -map 0:0 -map 0:1 -map 0:0 -map 0:1 -c:v:0 copy -c:a:0 copy -c:v:1 libx264 -b:v:1 100k -c:a:1 libfaac -ac:a:1 1 -b:a:1 32k -program "st=0:st=1" -program "st=2:st=3" -f mpegts http://127.0.0.1:8000/publish/sintel .. _HLS: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23 .. _MPEG-DASH: https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP .. _dash.js: https://github.com/Dash-Industry-Forum/dash.js
29jitender/Spotlight
4,347
README.md
# THIS LIBRARY IS NO LONGER MAINTAINED. I suggest you check alternatives. # Spotlight Spotlight is an Android library used to onboard users by showcasing specific features in the app. [![Platform](https://img.shields.io/badge/platform-android-green.svg)](http://developer.android.com/index.html) <img src="https://img.shields.io/badge/license-Apache 2.0-green.svg?style=flat"> [![API](https://img.shields.io/badge/API-11%2B-green.svg?style=flat)](https://android-arsenal.com/api?level=11) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Spotlight-green.svg?style=flat)](http://android-arsenal.com/details/1/3730) # Screen <img src="https://raw.githubusercontent.com/wooplr/Spotlight/master/art/intro.gif?token=AA5ZAHdvAspW6Zj8YyyKamkV7jWXFtMHks5XaQovwA%3D%3D"/> # Usage ```java new SpotlightView.Builder(this) .introAnimationDuration(400) .enableRevealAnimation(isRevealEnabled) .performClick(true) .fadeinTextDuration(400) .headingTvColor(Color.parseColor("#eb273f")) .headingTvSize(32) .headingTvText("Love") .subHeadingTvColor(Color.parseColor("#ffffff")) .subHeadingTvSize(16) .subHeadingTvText("Like the picture?\nLet others know.") .maskColor(Color.parseColor("#dc000000")) .target(view) .lineAnimDuration(400) .lineAndArcColor(Color.parseColor("#eb273f")) .dismissOnTouch(true) .dismissOnBackPress(true) .enableDismissAfterShown(true) .usageId(usageId) //UNIQUE ID .show(); ``` ## Download ### Gradle 1. Define the jitpack remote Maven repository inside the repositories block of your root `build.gradle` file ```javascript allprojects { repositories { ... maven { url "https://jitpack.io" } } } ``` 2. Add the Spotlight dependency ```javascript dependencies { ... implementation 'com.github.wooplr:Spotlight:1.2.3' } ``` ### Maven 1. Define the jitpack remote Maven repository in your `pom.xml` at the end of repositories ```xml <repositories> ... <repository> <id>jitpack.io</id> <url>https://jitpack.io</url> </repository> </repositories> ``` 2. Add the Spotlight dependency ```xml <dependency> <groupId>com.github.wooplr</groupId> <artifactId>Spotlight</artifactId> <version>1.2.3</version> </dependency> ``` # Builder Methods ### maskColor(int) Overlay Color ### target(View) View to showcase ### introAnimationDuration(long) Intro animation duration (For Reveal and Fadein) ### enableRevealAnimation(boolean) Enable reveal animation (Only for Lollipop and above) ### fadeinTextDuration(long) Fade in animation duration for spotlight text (Heading and Sub-heading) ### headingTvSize(int) Size of heading text ### headingTvColor(int) Color of heading text ### headingTvText(CharSequence) Text to display in heading ### subHeadingTvSize(int) Size of sub-heading text ### subHeadingTvColor(int) Color of sub-heading text ### subHeadingTvText(CharSequence) Text to display in sub-heading ### setTypeface(Typeface) Custom font for text in spotlight view ### lineAndArcColor(int) Color of the spotlight line ### lineAnimDuration(long) Line animation duration ### performClick(boolean) Perform a click on target view ### usageId(String) Unique id for each spotlight ### dismissOnTouch(boolean) Dismiss spotlight on touch outside ### enableDismissAfterShown(boolean) Dismiss spotlight on touch outside after spotlight is completely visible # Configuration Method ```java //Create global config instance to reuse it SpotlightConfig config = new SpotlightConfig(); config.isDismissOnTouch(true); config.setLineAndArcColor(0xFFFFFFFF); ... .setConfiguration(config) ``` # Author [Jitender Chaudhary](https://github.com/29jitender) # Proguard rules ```java -keep class com.wooplr.spotlight.** { *; } -keep interface com.wooplr.spotlight.** -keep enum com.wooplr.spotlight.** ``` # Credits [MaterialIntroView](https://github.com/iammert/MaterialIntroView) [Rahul Khanna](https://www.linkedin.com/in/rahul-khanna-01705827) [Suraj Barthy](https://dribbble.com/thesbdesign) ## License [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt)
294coder/Efficient-MIF
5,419
utils/loss_landscape/dataloader.py
import torch import torchvision from torchvision import transforms import os import numpy as np import argparse def get_relative_path(file): script_dir = os.path.dirname(__file__) # <-- absolute dir the script is in return os.path.join(script_dir, file) def load_dataset(dataset='cifar10', datapath='cifar10/data', batch_size=128, \ threads=2, raw_data=False, data_split=1, split_idx=0, \ trainloader_path="", testloader_path=""): """ Setup dataloader. The data is not randomly cropped as in training because of we want to esimate the loss value with a fixed dataset. Args: raw_data: raw images, no data preprocessing data_split: the number of splits for the training dataloader split_idx: the index for the split of the dataloader, starting at 0 Returns: train_loader, test_loader """ # use specific dataloaders if trainloader_path and testloader_path: assert os.path.exists(trainloader_path), 'trainloader does not exist' assert os.path.exists(testloader_path), 'testloader does not exist' train_loader = torch.load(trainloader_path) test_loader = torch.load(testloader_path) return train_loader, test_loader assert split_idx < data_split, 'the index of data partition should be smaller than the total number of split' if dataset == 'cifar10': normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]], std=[x/255.0 for x in [63.0, 62.1, 66.7]]) data_folder = get_relative_path(datapath) if raw_data: transform = transforms.Compose([ transforms.ToTensor() ]) else: transform = transforms.Compose([ transforms.ToTensor(), normalize, ]) trainset = torchvision.datasets.CIFAR10(root=data_folder, train=True, download=True, transform=transform) # If data_split>1, then randomly select a subset of the data. E.g., if datasplit=3, then # randomly choose 1/3 of the data. if data_split > 1: indices = torch.tensor(np.arange(len(trainset))) data_num = len(trainset) // data_split # the number of data in a chunk of the split # Randomly sample indices. Use seed=0 in the generator to make this reproducible state = np.random.get_state() np.random.seed(0) indices = np.random.choice(indices, data_num, replace=False) np.random.set_state(state) train_sampler = torch.utils.data.sampler.SubsetRandomSampler(indices) train_loader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, sampler=train_sampler, shuffle=False, num_workers=threads) else: kwargs = {'num_workers': 2, 'pin_memory': True} train_loader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=False, **kwargs) testset = torchvision.datasets.CIFAR10(root=data_folder, train=False, download=False, transform=transform) test_loader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=threads) return train_loader, test_loader ############################################################### #### MAIN ############################################################### if __name__ == '__main__': parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training') parser.add_argument('--mpi', '-m', action='store_true', help='use mpi') parser.add_argument('--cuda', '-c', action='store_true', help='use cuda') parser.add_argument('--threads', default=2, type=int, help='number of threads') parser.add_argument('--batch_size', default=128, type=int, help='minibatch size') parser.add_argument('--dataset', default='cifar10', help='cifar10 | imagenet') parser.add_argument('--datapath', default='cifar10/data', metavar='DIR', help='path to the dataset') parser.add_argument('--raw_data', action='store_true', default=False, help='do not normalize data') parser.add_argument('--data_split', default=1, type=int, help='the number of splits for the dataloader') parser.add_argument('--split_idx', default=0, type=int, help='the index of data splits for the dataloader') parser.add_argument('--trainloader', default='', help='path to the dataloader with random labels') parser.add_argument('--testloader', default='', help='path to the testloader with random labels') args = parser.parse_args() trainloader, testloader = load_dataset(args.dataset, args.datapath, args.batch_size, args.threads, args.raw_data, args.data_split, args.split_idx, args.trainloader, args.testloader) print('num of batches: %d' % len(trainloader)) for batch_idx, (inputs, targets) in enumerate(trainloader): print('batch_idx: %d batch_size: %d'%(batch_idx, len(inputs)))
2881099/FreeSql.AdminLTE
25,965
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/fastclick/fastclick.js
;(function () { 'use strict'; /** * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs. * * @codingstandard ftlabs-jsv2 * @copyright The Financial Times Limited [All Rights Reserved] * @license MIT License (see LICENSE.txt) */ /*jslint browser:true, node:true*/ /*global define, Event, Node*/ /** * Instantiate fast-clicking listeners on the specified layer. * * @constructor * @param {Element} layer The layer to listen on * @param {Object} [options={}] The options to override the defaults */ function FastClick(layer, options) { var oldOnClick; options = options || {}; /** * Whether a click is currently being tracked. * * @type boolean */ this.trackingClick = false; /** * Timestamp for when click tracking started. * * @type number */ this.trackingClickStart = 0; /** * The element being tracked for a click. * * @type EventTarget */ this.targetElement = null; /** * X-coordinate of touch start event. * * @type number */ this.touchStartX = 0; /** * Y-coordinate of touch start event. * * @type number */ this.touchStartY = 0; /** * ID of the last touch, retrieved from Touch.identifier. * * @type number */ this.lastTouchIdentifier = 0; /** * Touchmove boundary, beyond which a click will be cancelled. * * @type number */ this.touchBoundary = options.touchBoundary || 10; /** * The FastClick layer. * * @type Element */ this.layer = layer; /** * The minimum time between tap(touchstart and touchend) events * * @type number */ this.tapDelay = options.tapDelay || 200; /** * The maximum time for a tap * * @type number */ this.tapTimeout = options.tapTimeout || 700; if (FastClick.notNeeded(layer)) { return; } // Some old versions of Android don't have Function.prototype.bind function bind(method, context) { return function() { return method.apply(context, arguments); }; } var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel']; var context = this; for (var i = 0, l = methods.length; i < l; i++) { context[methods[i]] = bind(context[methods[i]], context); } // Set up event handlers as required if (deviceIsAndroid) { layer.addEventListener('mouseover', this.onMouse, true); layer.addEventListener('mousedown', this.onMouse, true); layer.addEventListener('mouseup', this.onMouse, true); } layer.addEventListener('click', this.onClick, true); layer.addEventListener('touchstart', this.onTouchStart, false); layer.addEventListener('touchmove', this.onTouchMove, false); layer.addEventListener('touchend', this.onTouchEnd, false); layer.addEventListener('touchcancel', this.onTouchCancel, false); // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick // layer when they are cancelled. if (!Event.prototype.stopImmediatePropagation) { layer.removeEventListener = function(type, callback, capture) { var rmv = Node.prototype.removeEventListener; if (type === 'click') { rmv.call(layer, type, callback.hijacked || callback, capture); } else { rmv.call(layer, type, callback, capture); } }; layer.addEventListener = function(type, callback, capture) { var adv = Node.prototype.addEventListener; if (type === 'click') { adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) { if (!event.propagationStopped) { callback(event); } }), capture); } else { adv.call(layer, type, callback, capture); } }; } // If a handler is already declared in the element's onclick attribute, it will be fired before // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and // adding it as listener. if (typeof layer.onclick === 'function') { // Android browser on at least 3.2 requires a new reference to the function in layer.onclick // - the old one won't work if passed to addEventListener directly. oldOnClick = layer.onclick; layer.addEventListener('click', function(event) { oldOnClick(event); }, false); layer.onclick = null; } } /** * Windows Phone 8.1 fakes user agent string to look like Android and iPhone. * * @type boolean */ var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0; /** * Android requires exceptions. * * @type boolean */ var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone; /** * iOS requires exceptions. * * @type boolean */ var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone; /** * iOS 4 requires an exception for select elements. * * @type boolean */ var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent); /** * iOS 6.0-7.* requires the target element to be manually derived * * @type boolean */ var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent); /** * BlackBerry requires exceptions. * * @type boolean */ var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0; /** * Determine whether a given element requires a native click. * * @param {EventTarget|Element} target Target DOM element * @returns {boolean} Returns true if the element needs a native click */ FastClick.prototype.needsClick = function(target) { switch (target.nodeName.toLowerCase()) { // Don't send a synthetic click to disabled inputs (issue #62) case 'button': case 'select': case 'textarea': if (target.disabled) { return true; } break; case 'input': // File inputs need real clicks on iOS 6 due to a browser bug (issue #68) if ((deviceIsIOS && target.type === 'file') || target.disabled) { return true; } break; case 'label': case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames case 'video': return true; } return (/\bneedsclick\b/).test(target.className); }; /** * Determine whether a given element requires a call to focus to simulate click into element. * * @param {EventTarget|Element} target Target DOM element * @returns {boolean} Returns true if the element requires a call to focus to simulate native click. */ FastClick.prototype.needsFocus = function(target) { switch (target.nodeName.toLowerCase()) { case 'textarea': return true; case 'select': return !deviceIsAndroid; case 'input': switch (target.type) { case 'button': case 'checkbox': case 'file': case 'image': case 'radio': case 'submit': return false; } // No point in attempting to focus disabled inputs return !target.disabled && !target.readOnly; default: return (/\bneedsfocus\b/).test(target.className); } }; /** * Send a click event to the specified element. * * @param {EventTarget|Element} targetElement * @param {Event} event */ FastClick.prototype.sendClick = function(targetElement, event) { var clickEvent, touch; // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24) if (document.activeElement && document.activeElement !== targetElement) { document.activeElement.blur(); } touch = event.changedTouches[0]; // Synthesise a click event, with an extra attribute so it can be tracked clickEvent = document.createEvent('MouseEvents'); clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null); clickEvent.forwardedTouchEvent = true; targetElement.dispatchEvent(clickEvent); }; FastClick.prototype.determineEventType = function(targetElement) { //Issue #159: Android Chrome Select Box does not open with a synthetic click event if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') { return 'mousedown'; } return 'click'; }; /** * @param {EventTarget|Element} targetElement */ FastClick.prototype.focus = function(targetElement) { var length; // Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724. if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') { length = targetElement.value.length; targetElement.setSelectionRange(length, length); } else { targetElement.focus(); } }; /** * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it. * * @param {EventTarget|Element} targetElement */ FastClick.prototype.updateScrollParent = function(targetElement) { var scrollParent, parentElement; scrollParent = targetElement.fastClickScrollParent; // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the // target element was moved to another parent. if (!scrollParent || !scrollParent.contains(targetElement)) { parentElement = targetElement; do { if (parentElement.scrollHeight > parentElement.offsetHeight) { scrollParent = parentElement; targetElement.fastClickScrollParent = parentElement; break; } parentElement = parentElement.parentElement; } while (parentElement); } // Always update the scroll top tracker if possible. if (scrollParent) { scrollParent.fastClickLastScrollTop = scrollParent.scrollTop; } }; /** * @param {EventTarget} targetElement * @returns {Element|EventTarget} */ FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) { // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node. if (eventTarget.nodeType === Node.TEXT_NODE) { return eventTarget.parentNode; } return eventTarget; }; /** * On touch start, record the position and scroll offset. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchStart = function(event) { var targetElement, touch, selection; // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111). if (event.targetTouches.length > 1) { return true; } targetElement = this.getTargetElementFromEventTarget(event.target); touch = event.targetTouches[0]; if (deviceIsIOS) { // Only trusted events will deselect text on iOS (issue #49) selection = window.getSelection(); if (selection.rangeCount && !selection.isCollapsed) { return true; } if (!deviceIsIOS4) { // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23): // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched // with the same identifier as the touch event that previously triggered the click that triggered the alert. // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform. // Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string, // which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long, // random integers, it's safe to to continue if the identifier is 0 here. if (touch.identifier && touch.identifier === this.lastTouchIdentifier) { event.preventDefault(); return false; } this.lastTouchIdentifier = touch.identifier; // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and: // 1) the user does a fling scroll on the scrollable layer // 2) the user stops the fling scroll with another tap // then the event.target of the last 'touchend' event will be the element that was under the user's finger // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42). this.updateScrollParent(targetElement); } } this.trackingClick = true; this.trackingClickStart = event.timeStamp; this.targetElement = targetElement; this.touchStartX = touch.pageX; this.touchStartY = touch.pageY; // Prevent phantom clicks on fast double-tap (issue #36) if ((event.timeStamp - this.lastClickTime) < this.tapDelay) { event.preventDefault(); } return true; }; /** * Based on a touchmove event object, check whether the touch has moved past a boundary since it started. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.touchHasMoved = function(event) { var touch = event.changedTouches[0], boundary = this.touchBoundary; if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) { return true; } return false; }; /** * Update the last position. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchMove = function(event) { if (!this.trackingClick) { return true; } // If the touch has moved, cancel the click tracking if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) { this.trackingClick = false; this.targetElement = null; } return true; }; /** * Attempt to find the labelled control for the given label element. * * @param {EventTarget|HTMLLabelElement} labelElement * @returns {Element|null} */ FastClick.prototype.findControl = function(labelElement) { // Fast path for newer browsers supporting the HTML5 control attribute if (labelElement.control !== undefined) { return labelElement.control; } // All browsers under test that support touch events also support the HTML5 htmlFor attribute if (labelElement.htmlFor) { return document.getElementById(labelElement.htmlFor); } // If no for attribute exists, attempt to retrieve the first labellable descendant element // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea'); }; /** * On touch end, determine whether to send a click event at once. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchEnd = function(event) { var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement; if (!this.trackingClick) { return true; } // Prevent phantom clicks on fast double-tap (issue #36) if ((event.timeStamp - this.lastClickTime) < this.tapDelay) { this.cancelNextClick = true; return true; } if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) { return true; } // Reset to prevent wrong click cancel on input (issue #156). this.cancelNextClick = false; this.lastClickTime = event.timeStamp; trackingClickStart = this.trackingClickStart; this.trackingClick = false; this.trackingClickStart = 0; // On some iOS devices, the targetElement supplied with the event is invalid if the layer // is performing a transition or scroll, and has to be re-detected manually. Note that // for this to function correctly, it must be called *after* the event target is checked! // See issue #57; also filed as rdar://13048589 . if (deviceIsIOSWithBadTarget) { touch = event.changedTouches[0]; // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement; targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent; } targetTagName = targetElement.tagName.toLowerCase(); if (targetTagName === 'label') { forElement = this.findControl(targetElement); if (forElement) { this.focus(targetElement); if (deviceIsAndroid) { return false; } targetElement = forElement; } } else if (this.needsFocus(targetElement)) { // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through. // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37). if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) { this.targetElement = null; return false; } this.focus(targetElement); this.sendClick(targetElement, event); // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open. // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others) if (!deviceIsIOS || targetTagName !== 'select') { this.targetElement = null; event.preventDefault(); } return false; } if (deviceIsIOS && !deviceIsIOS4) { // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42). scrollParent = targetElement.fastClickScrollParent; if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) { return true; } } // Prevent the actual click from going though - unless the target node is marked as requiring // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted. if (!this.needsClick(targetElement)) { event.preventDefault(); this.sendClick(targetElement, event); } return false; }; /** * On touch cancel, stop tracking the click. * * @returns {void} */ FastClick.prototype.onTouchCancel = function() { this.trackingClick = false; this.targetElement = null; }; /** * Determine mouse events which should be permitted. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onMouse = function(event) { // If a target element was never set (because a touch event was never fired) allow the event if (!this.targetElement) { return true; } if (event.forwardedTouchEvent) { return true; } // Programmatically generated events targeting a specific element should be permitted if (!event.cancelable) { return true; } // Derive and check the target element to see whether the mouse event needs to be permitted; // unless explicitly enabled, prevent non-touch click events from triggering actions, // to prevent ghost/doubleclicks. if (!this.needsClick(this.targetElement) || this.cancelNextClick) { // Prevent any user-added listeners declared on FastClick element from being fired. if (event.stopImmediatePropagation) { event.stopImmediatePropagation(); } else { // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) event.propagationStopped = true; } // Cancel the event event.stopPropagation(); event.preventDefault(); return false; } // If the mouse event is permitted, return true for the action to go through. return true; }; /** * On actual clicks, determine whether this is a touch-generated click, a click action occurring * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or * an actual click which should be permitted. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onClick = function(event) { var permitted; // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early. if (this.trackingClick) { this.targetElement = null; this.trackingClick = false; return true; } // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target. if (event.target.type === 'submit' && event.detail === 0) { return true; } permitted = this.onMouse(event); // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through. if (!permitted) { this.targetElement = null; } // If clicks are permitted, return true for the action to go through. return permitted; }; /** * Remove all FastClick's event listeners. * * @returns {void} */ FastClick.prototype.destroy = function() { var layer = this.layer; if (deviceIsAndroid) { layer.removeEventListener('mouseover', this.onMouse, true); layer.removeEventListener('mousedown', this.onMouse, true); layer.removeEventListener('mouseup', this.onMouse, true); } layer.removeEventListener('click', this.onClick, true); layer.removeEventListener('touchstart', this.onTouchStart, false); layer.removeEventListener('touchmove', this.onTouchMove, false); layer.removeEventListener('touchend', this.onTouchEnd, false); layer.removeEventListener('touchcancel', this.onTouchCancel, false); }; /** * Check whether FastClick is needed. * * @param {Element} layer The layer to listen on */ FastClick.notNeeded = function(layer) { var metaViewport; var chromeVersion; var blackberryVersion; var firefoxVersion; // Devices that don't support touch don't need FastClick if (typeof window.ontouchstart === 'undefined') { return true; } // Chrome version - zero for other browsers chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1]; if (chromeVersion) { if (deviceIsAndroid) { metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport) { // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89) if (metaViewport.content.indexOf('user-scalable=no') !== -1) { return true; } // Chrome 32 and above with width=device-width or less don't need FastClick if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) { return true; } } // Chrome desktop doesn't need FastClick (issue #15) } else { return true; } } if (deviceIsBlackBerry10) { blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/); // BlackBerry 10.3+ does not require Fastclick library. // https://github.com/ftlabs/fastclick/issues/251 if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) { metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport) { // user-scalable=no eliminates click delay. if (metaViewport.content.indexOf('user-scalable=no') !== -1) { return true; } // width=device-width (or less than device-width) eliminates click delay. if (document.documentElement.scrollWidth <= window.outerWidth) { return true; } } } } // IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97) if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') { return true; } // Firefox version - zero for other browsers firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1]; if (firefoxVersion >= 27) { // Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896 metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) { return true; } } // IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version // http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') { return true; } return false; }; /** * Factory method for creating a FastClick object * * @param {Element} layer The layer to listen on * @param {Object} [options={}] The options to override the defaults */ FastClick.attach = function(layer, options) { return new FastClick(layer, options); }; if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) { // AMD. Register as an anonymous module. define(function() { return FastClick; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = FastClick.attach; module.exports.FastClick = FastClick; } else { window.FastClick = FastClick; } }());
294coder/Efficient-MIF
12,685
utils/loss_landscape/net_plotter.py
""" Manipulate network parameters and setup random directions with normalization. """ import torch import copy from os.path import exists, commonprefix import h5py import h5_util import model_loader import os ################################################################################ # Supporting functions for weights manipulation ################################################################################ def get_weights(net): """ Extract parameters from net, and return a list of tensors""" return [p.data for p in net.parameters()] def set_weights(net, weights, directions=None, step=None): """ Overwrite the network's weights with a specified list of tensors or change weights along directions with a step size. """ if directions is None: # You cannot specify a step length without a direction. for (p, w) in zip(net.parameters(), weights): p.data.copy_(w.type(type(p.data))) else: assert step is not None, 'If a direction is specified then step must be specified as well' if len(directions) == 2: dx = directions[0] dy = directions[1] changes = [d0*step[0] + d1*step[1] for (d0, d1) in zip(dx, dy)] else: changes = [d*step for d in directions[0]] for (p, w, d) in zip(net.parameters(), weights, changes): p.data = w + torch.Tensor(d).type(type(w)) def set_states(net, states, directions=None, step=None): """ Overwrite the network's state_dict or change it along directions with a step size. """ if directions is None: net.load_state_dict(states) else: assert step is not None, 'If direction is provided then the step must be specified as well' if len(directions) == 2: dx = directions[0] dy = directions[1] changes = [d0*step[0] + d1*step[1] for (d0, d1) in zip(dx, dy)] else: changes = [d*step for d in directions[0]] new_states = copy.deepcopy(states) assert (len(new_states) == len(changes)) for (k, v), d in zip(new_states.items(), changes): d = torch.tensor(d) v.add_(d.type(v.type())) net.load_state_dict(new_states) def get_random_weights(weights): """ Produce a random direction that is a list of random Gaussian tensors with the same shape as the network's weights, so one direction entry per weight. """ return [torch.randn(w.size()) for w in weights] def get_random_states(states): """ Produce a random direction that is a list of random Gaussian tensors with the same shape as the network's state_dict(), so one direction entry per weight, including BN's running_mean/var. """ return [torch.randn(w.size()) for k, w in states.items()] def get_diff_weights(weights, weights2): """ Produce a direction from 'weights' to 'weights2'.""" return [w2 - w for (w, w2) in zip(weights, weights2)] def get_diff_states(states, states2): """ Produce a direction from 'states' to 'states2'.""" return [v2 - v for (k, v), (k2, v2) in zip(states.items(), states2.items())] ################################################################################ # Normalization Functions ################################################################################ def normalize_direction(direction, weights, norm='filter'): """ Rescale the direction so that it has similar norm as their corresponding model in different levels. Args: direction: a variables of the random direction for one layer weights: a variable of the original model for one layer norm: normalization method, 'filter' | 'layer' | 'weight' """ if norm == 'filter': # Rescale the filters (weights in group) in 'direction' so that each # filter has the same norm as its corresponding filter in 'weights'. for d, w in zip(direction, weights): d.mul_(w.norm()/(d.norm() + 1e-10)) elif norm == 'layer': # Rescale the layer variables in the direction so that each layer has # the same norm as the layer variables in weights. direction.mul_(weights.norm()/direction.norm()) elif norm == 'weight': # Rescale the entries in the direction so that each entry has the same # scale as the corresponding weight. direction.mul_(weights) elif norm == 'dfilter': # Rescale the entries in the direction so that each filter direction # has the unit norm. for d in direction: d.div_(d.norm() + 1e-10) elif norm == 'dlayer': # Rescale the entries in the direction so that each layer direction has # the unit norm. direction.div_(direction.norm()) def normalize_directions_for_weights(direction, weights, norm='filter', ignore='biasbn'): """ The normalization scales the direction entries according to the entries of weights. """ assert(len(direction) == len(weights)) for d, w in zip(direction, weights): if d.dim() <= 1: if ignore == 'biasbn': d.fill_(0) # ignore directions for weights with 1 dimension else: d.copy_(w) # keep directions for weights/bias that are only 1 per node else: normalize_direction(d, w, norm) def normalize_directions_for_states(direction, states, norm='filter', ignore='ignore'): assert(len(direction) == len(states)) for d, (k, w) in zip(direction, states.items()): if d.dim() <= 1: if ignore == 'biasbn': d.fill_(0) # ignore directions for weights with 1 dimension else: d.copy_(w) # keep directions for weights/bias that are only 1 per node else: normalize_direction(d, w, norm) def ignore_biasbn(directions): """ Set bias and bn parameters in directions to zero """ for d in directions: if d.dim() <= 1: d.fill_(0) ################################################################################ # Create directions ################################################################################ def create_target_direction(net, net2, dir_type='states'): """ Setup a target direction from one model to the other Args: net: the source model net2: the target model with the same architecture as net. dir_type: 'weights' or 'states', type of directions. Returns: direction: the target direction from net to net2 with the same dimension as weights or states. """ assert (net2 is not None) # direction between net2 and net if dir_type == 'weights': w = get_weights(net) w2 = get_weights(net2) direction = get_diff_weights(w, w2) elif dir_type == 'states': s = net.state_dict() s2 = net2.state_dict() direction = get_diff_states(s, s2) return direction def create_random_direction(net, dir_type='weights', ignore='biasbn', norm='filter'): """ Setup a random (normalized) direction with the same dimension as the weights or states. Args: net: the given trained model dir_type: 'weights' or 'states', type of directions. ignore: 'biasbn', ignore biases and BN parameters. norm: direction normalization method, including 'filter" | 'layer' | 'weight' | 'dlayer' | 'dfilter' Returns: direction: a random direction with the same dimension as weights or states. """ # random direction if dir_type == 'weights': weights = get_weights(net) # a list of parameters. direction = get_random_weights(weights) normalize_directions_for_weights(direction, weights, norm, ignore) elif dir_type == 'states': states = net.state_dict() # a dict of parameters, including BN's running mean/var. direction = get_random_states(states) normalize_directions_for_states(direction, states, norm, ignore) return direction def setup_direction(args, dir_file, net): """ Setup the h5 file to store the directions. - xdirection, ydirection: The pertubation direction added to the mdoel. The direction is a list of tensors. """ print('-------------------------------------------------------------------') print('setup_direction') print('-------------------------------------------------------------------') # Setup env for preventing lock on h5py file for newer h5py versions os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE" # Skip if the direction file already exists if exists(dir_file): f = h5py.File(dir_file, 'r') if (args.y and 'ydirection' in f.keys()) or 'xdirection' in f.keys(): f.close() print ("%s is already setted up" % dir_file) return f.close() # Create the plotting directions f = h5py.File(dir_file,'w') # create file, fail if exists if not args.dir_file: print("Setting up the plotting directions...") if args.model_file2: net2 = model_loader.load(args.dataset, args.model, args.model_file2) xdirection = create_target_direction(net, net2, args.dir_type) else: xdirection = create_random_direction(net, args.dir_type, args.xignore, args.xnorm) h5_util.write_list(f, 'xdirection', xdirection) if args.y: if args.same_dir: ydirection = xdirection elif args.model_file3: net3 = model_loader.load(args.dataset, args.model, args.model_file3) ydirection = create_target_direction(net, net3, args.dir_type) else: ydirection = create_random_direction(net, args.dir_type, args.yignore, args.ynorm) h5_util.write_list(f, 'ydirection', ydirection) f.close() print ("direction file created: %s" % dir_file) def name_direction_file(args): """ Name the direction file that stores the random directions. """ if args.dir_file: assert exists(args.dir_file), "%s does not exist!" % args.dir_file return args.dir_file dir_file = "" file1, file2, file3 = args.model_file, args.model_file2, args.model_file3 # name for xdirection if file2: # 1D linear interpolation between two models assert exists(file2), file2 + " does not exist!" if file1[:file1.rfind('/')] == file2[:file2.rfind('/')]: # model_file and model_file2 are under the same folder dir_file += file1 + '_' + file2[file2.rfind('/')+1:] else: # model_file and model_file2 are under different folders prefix = commonprefix([file1, file2]) prefix = prefix[0:prefix.rfind('/')] dir_file += file1[:file1.rfind('/')] + '_' + file1[file1.rfind('/')+1:] + '_' + \ file2[len(prefix)+1: file2.rfind('/')] + '_' + file2[file2.rfind('/')+1:] else: dir_file += file1 dir_file += '_' + args.dir_type if args.xignore: dir_file += '_xignore=' + args.xignore if args.xnorm: dir_file += '_xnorm=' + args.xnorm # name for ydirection if args.y: if file3: assert exists(file3), "%s does not exist!" % file3 if file1[:file1.rfind('/')] == file3[:file3.rfind('/')]: dir_file += file3 else: # model_file and model_file3 are under different folders dir_file += file3[:file3.rfind('/')] + '_' + file3[file3.rfind('/')+1:] else: if args.yignore: dir_file += '_yignore=' + args.yignore if args.ynorm: dir_file += '_ynorm=' + args.ynorm if args.same_dir: # ydirection is the same as xdirection dir_file += '_same_dir' # index number if args.idx > 0: dir_file += '_idx=' + str(args.idx) dir_file += ".h5" return dir_file def load_directions(dir_file): """ Load direction(s) from the direction file.""" f = h5py.File(dir_file, 'r') if 'ydirection' in f.keys(): # If this is a 2D plot xdirection = h5_util.read_list(f, 'xdirection') ydirection = h5_util.read_list(f, 'ydirection') directions = [xdirection, ydirection] else: directions = [h5_util.read_list(f, 'xdirection')] return directions
29jitender/Spotlight
4,971
gradlew
#!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
2881099/FreeSql.AdminLTE
7,009
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/sparklines/sparkline.js
(function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.Sparkline = factory(); } }(window, function () { function extend(specific, general) { var obj = {}; for (var key in general) { obj[key] = key in specific ? specific[key] : general[key]; } return obj; } function Sparkline(element, options) { this.element = element; this.options = extend(options || {}, Sparkline.options); init: { this.element.innerHTML = "<canvas></canvas>"; this.canvas = this.element.firstChild; this.context = this.canvas.getContext("2d"); this.ratio = window.devicePixelRatio || 1; if (this.options.tooltip) { this.canvas.style.position = "relative"; this.canvas.onmousemove = showTooltip.bind(this); } } } Sparkline.options = { width: 100, height: null, lineColor: "black", lineWidth: 1.5, startColor: "transparent", endColor: "black", maxColor: "transparent", minColor: "transparent", minValue: null, maxValue: null, minMaxValue: null, maxMinValue: null, dotRadius: 2.5, tooltip: null, fillBelow: true, fillLighten: 0.5, startLine: false, endLine: false, minLine: false, maxLine: false, bottomLine: false, topLine: false, averageLine: false }; Sparkline.init = function (element, options) { return new Sparkline(element, options); }; Sparkline.draw = function (element, points, options) { var sparkline = new Sparkline(element, options); sparkline.draw(points); return sparkline; } function getY(minValue, maxValue, offsetY, height, index) { var range = maxValue - minValue; if (range == 0) { return offsetY + height / 2; } else { return (offsetY + height) - ((this[index] - minValue) / range) * height; } } function drawDot(radius, x1, x2, color, line, x, y) { this.context.beginPath(); this.context.fillStyle = color; this.context.arc(x, y, radius, 0, Math.PI * 2, false); this.context.fill(); drawLine.call(this, x1, x2, line, x, y); } function drawLine(x1, x2, style, x, y){ if(!style) return; this.context.save(); this.context.strokeStyle = style.color || 'black'; this.context.lineWidth = (style.width || 1) * this.ratio; this.context.globalAlpha = style.alpha || 1; this.context.beginPath(); this.context.moveTo(style.direction != 'right' ? x1 : x, y); this.context.lineTo(style.direction != 'left' ? x2 : x, y); this.context.stroke(); this.context.restore(); } function showTooltip(e) { var x = e.offsetX || e.layerX || 0; var delta = ((this.options.width - this.options.dotRadius * 2) / (this.points.length - 1)); var index = minmax(0, Math.round((x - this.options.dotRadius) / delta), this.points.length - 1); this.canvas.title = this.options.tooltip(this.points[index], index, this.points); } Sparkline.prototype.draw = function (points) { points = points || []; this.points = points; this.canvas.width = this.options.width * this.ratio; this.canvas.style.width = this.options.width + 'px'; var pxHeight = this.options.height || this.element.offsetHeight; this.canvas.height = pxHeight * this.ratio; this.canvas.style.height = pxHeight + 'px'; var lineWidth = this.options.lineWidth * this.ratio; var offsetX = Math.max(this.options.dotRadius * this.ratio, lineWidth/2); var offsetY = Math.max(this.options.dotRadius * this.ratio, lineWidth/2); var width = this.canvas.width - offsetX * 2; var height = this.canvas.height - offsetY * 2; var minValue = Math.min.apply(Math, points); var maxValue = Math.max.apply(Math, points); var bottomValue = this.options.minValue != undefined ? this.options.minValue : Math.min(minValue, this.options.maxMinValue != undefined ? this.options.maxMinValue : minValue); var topValue = this.options.maxValue != undefined ? this.options.maxValue : Math.max(maxValue, this.options.minMaxValue != undefined ? this.options.minMaxValue : maxValue); var minX = offsetX; var maxX = offsetX; var x = offsetX; var y = getY.bind(points, bottomValue, topValue, offsetY, height); var delta = width / (points.length - 1); var dot = drawDot.bind(this, this.options.dotRadius * this.ratio, offsetX, width + offsetX); var line = drawLine.bind(this, offsetX, width + offsetX); this.context.save(); this.context.strokeStyle = this.options.lineColor; this.context.fillStyle = this.options.lineColor; this.context.lineWidth = lineWidth; this.context.lineCap = 'round'; this.context.lineJoin = 'round'; if(this.options.fillBelow && points.length > 1){ this.context.save(); this.context.beginPath(); this.context.moveTo(x, y(0)); for (var i = 1; i < points.length; i++) { x += delta; minX = points[i] == minValue ? x : minX; maxX = points[i] == maxValue ? x : maxX; this.context.lineTo(x, y(i)); } this.context.lineTo(width+offsetX, height + offsetY + lineWidth/2); this.context.lineTo(offsetX, height + offsetY + lineWidth/2); this.context.fill(); if(this.options.fillLighten > 0){ this.context.fillStyle = 'white'; this.context.globalAlpha = this.options.fillLighten; this.context.fill(); this.context.globalAlpha = 1; }else if(this.options.fillLighten < 0){ this.context.fillStyle = 'black'; this.context.globalAlpha = -this.options.fillLighten; this.context.fill(); } this.context.restore(); } x = offsetX; this.context.beginPath(); this.context.moveTo(x, y(0)); for (var i = 1; i < points.length; i++) { x += delta; this.context.lineTo(x, y(i)); } this.context.stroke(); this.context.restore(); line(this.options.bottomLine, 0, offsetY); line(this.options.topLine, 0, height + offsetY+lineWidth/2); dot(this.options.startColor, this.options.startLine, offsetX + (points.length == 1 ? width / 2 : 0), y(0)); dot(this.options.endColor, this.options.endLine, offsetX + (points.length == 1 ? width / 2 : width), y(points.length-1)); dot(this.options.minColor, this.options.minLine, minX + (points.length == 1 ? width / 2 : 0), y(points.indexOf(minValue))); dot(this.options.maxColor, this.options.maxLine, maxX + (points.length == 1 ? width / 2 : 0), y(points.indexOf(maxValue))); //line(this.options.averageLine, ) } function minmax(a, b, c) { return Math.max(a, Math.min(b, c)); } return Sparkline; }));
29jitender/Spotlight
1,135
app/build.gradle
apply plugin: 'com.android.application' apply plugin: 'android-apt' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.example.spotlight" minSdkVersion 11 targetSdkVersion 23 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile project(':Spotlight-library') compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' compile 'com.jakewharton:butterknife:8.0.1' apt 'com.jakewharton:butterknife-compiler:8.0.1' testCompile 'junit:junit:4.12' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2' androidTestCompile 'com.android.support.test:runner:0.5' androidTestCompile 'com.android.support:support-annotations:23.4.0' }
294coder/Efficient-MIF
11,571
utils/loss_landscape/h52vtp.py
""" Convert h5 files to vtp files in VTK XML format that can be opened by ParaView. The data type of the vtp file is "vtkPolyData", each PolyData piece specifies a set of points and cells independently from the other pieces. The points are described explicitly by the Points element. The cells are described explicitly by the Verts, Lines, Strips, and Polys elements. <VTKFile type="PolyData" ...> <PolyData> <Piece NumberOfPoints="#" NumberOfVerts="#" NumberOfLines="#" NumberOfStrips="#" NumberOfPolys="#"> <PointData>...</PointData> <CellData>...</CellData> <Points>...</Points> <Verts>...</Verts> <Lines>...</Lines> <Strips>...</Strips> <Polys>...</Polys> </Piece> </PolyData> </VTKFile> """ import math import argparse import h5py import numpy as np from scipy import interpolate def h5_to_vtp(surf_file, surf_name='train_loss', log=False, zmax=-1, interp=-1): #set this to True to generate points show_points = False #set this to True to generate polygons show_polys = True f = h5py.File(surf_file,'r') [xcoordinates, ycoordinates] = np.meshgrid(f['xcoordinates'][:], f['ycoordinates'][:][:]) vals = f[surf_name] x_array = xcoordinates[:].ravel() y_array = ycoordinates[:].ravel() z_array = vals[:].ravel() # Interpolate the resolution up to the desired amount if interp > 0: m = interpolate.interp2d(xcoordinates[0,:], ycoordinates[:,0], vals, kind='cubic') x_array = np.linspace(min(x_array), max(x_array), interp) y_array = np.linspace(min(y_array), max(y_array), interp) z_array = m(x_array, y_array).ravel() x_array, y_array = np.meshgrid(x_array, y_array) x_array = x_array.ravel() y_array = y_array.ravel() vtp_file = surf_file + "_" + surf_name if zmax > 0: z_array[z_array > zmax] = zmax vtp_file += "_zmax=" + str(zmax) if log: z_array = np.log(z_array + 0.1) vtp_file += "_log" vtp_file += ".vtp" print("Here's your output file:{}".format(vtp_file)) number_points = len(z_array) print("number_points = {} points".format(number_points)) matrix_size = int(math.sqrt(number_points)) print("matrix_size = {} x {}".format(matrix_size, matrix_size)) poly_size = matrix_size - 1 print("poly_size = {} x {}".format(poly_size, poly_size)) number_polys = poly_size * poly_size print("number_polys = {}".format(number_polys)) min_value_array = [min(x_array), min(y_array), min(z_array)] max_value_array = [max(x_array), max(y_array), max(z_array)] min_value = min(min_value_array) max_value = max(max_value_array) averaged_z_value_array = [] poly_count = 0 for column_count in range(poly_size): stride_value = column_count * matrix_size for row_count in range(poly_size): temp_index = stride_value + row_count averaged_z_value = (z_array[temp_index] + z_array[temp_index + 1] + z_array[temp_index + matrix_size] + z_array[temp_index + matrix_size + 1]) / 4.0 averaged_z_value_array.append(averaged_z_value) poly_count += 1 avg_min_value = min(averaged_z_value_array) avg_max_value = max(averaged_z_value_array) output_file = open(vtp_file, 'w') output_file.write('<VTKFile type="PolyData" version="1.0" byte_order="LittleEndian" header_type="UInt64">\n') output_file.write(' <PolyData>\n') if (show_points and show_polys): output_file.write(' <Piece NumberOfPoints="{}" NumberOfVerts="{}" NumberOfLines="0" NumberOfStrips="0" NumberOfPolys="{}">\n'.format(number_points, number_points, number_polys)) elif (show_polys): output_file.write(' <Piece NumberOfPoints="{}" NumberOfVerts="0" NumberOfLines="0" NumberOfStrips="0" NumberOfPolys="{}">\n'.format(number_points, number_polys)) else: output_file.write(' <Piece NumberOfPoints="{}" NumberOfVerts="{}" NumberOfLines="0" NumberOfStrips="0" NumberOfPolys="">\n'.format(number_points, number_points)) # <PointData> output_file.write(' <PointData>\n') output_file.write(' <DataArray type="Float32" Name="zvalue" NumberOfComponents="1" format="ascii" RangeMin="{}" RangeMax="{}">\n'.format(min_value_array[2], max_value_array[2])) for vertexcount in range(number_points): if (vertexcount % 6) is 0: output_file.write(' ') output_file.write('{}'.format(z_array[vertexcount])) if (vertexcount % 6) is 5: output_file.write('\n') else: output_file.write(' ') if (vertexcount % 6) is not 5: output_file.write('\n') output_file.write(' </DataArray>\n') output_file.write(' </PointData>\n') # <CellData> output_file.write(' <CellData>\n') if (show_polys and not show_points): output_file.write(' <DataArray type="Float32" Name="averaged zvalue" NumberOfComponents="1" format="ascii" RangeMin="{}" RangeMax="{}">\n'.format(avg_min_value, avg_max_value)) for vertexcount in range(number_polys): if (vertexcount % 6) is 0: output_file.write(' ') output_file.write('{}'.format(averaged_z_value_array[vertexcount])) if (vertexcount % 6) is 5: output_file.write('\n') else: output_file.write(' ') if (vertexcount % 6) is not 5: output_file.write('\n') output_file.write(' </DataArray>\n') output_file.write(' </CellData>\n') # <Points> output_file.write(' <Points>\n') output_file.write(' <DataArray type="Float32" Name="Points" NumberOfComponents="3" format="ascii" RangeMin="{}" RangeMax="{}">\n'.format(min_value, max_value)) for vertexcount in range(number_points): if (vertexcount % 2) is 0: output_file.write(' ') output_file.write('{} {} {}'.format(x_array[vertexcount], y_array[vertexcount], z_array[vertexcount])) if (vertexcount % 2) is 1: output_file.write('\n') else: output_file.write(' ') if (vertexcount % 2) is not 1: output_file.write('\n') output_file.write(' </DataArray>\n') output_file.write(' </Points>\n') # <Verts> output_file.write(' <Verts>\n') output_file.write(' <DataArray type="Int64" Name="connectivity" format="ascii" RangeMin="0" RangeMax="{}">\n'.format(number_points - 1)) if (show_points): for vertexcount in range(number_points): if (vertexcount % 6) is 0: output_file.write(' ') output_file.write('{}'.format(vertexcount)) if (vertexcount % 6) is 5: output_file.write('\n') else: output_file.write(' ') if (vertexcount % 6) is not 5: output_file.write('\n') output_file.write(' </DataArray>\n') output_file.write(' <DataArray type="Int64" Name="offsets" format="ascii" RangeMin="1" RangeMax="{}">\n'.format(number_points)) if (show_points): for vertexcount in range(number_points): if (vertexcount % 6) is 0: output_file.write(' ') output_file.write('{}'.format(vertexcount + 1)) if (vertexcount % 6) is 5: output_file.write('\n') else: output_file.write(' ') if (vertexcount % 6) is not 5: output_file.write('\n') output_file.write(' </DataArray>\n') output_file.write(' </Verts>\n') # <Lines> output_file.write(' <Lines>\n') output_file.write(' <DataArray type="Int64" Name="connectivity" format="ascii" RangeMin="0" RangeMax="{}">\n'.format(number_polys - 1)) output_file.write(' </DataArray>\n') output_file.write(' <DataArray type="Int64" Name="offsets" format="ascii" RangeMin="1" RangeMax="{}">\n'.format(number_polys)) output_file.write(' </DataArray>\n') output_file.write(' </Lines>\n') # <Strips> output_file.write(' <Strips>\n') output_file.write(' <DataArray type="Int64" Name="connectivity" format="ascii" RangeMin="0" RangeMax="{}">\n'.format(number_polys - 1)) output_file.write(' </DataArray>\n') output_file.write(' <DataArray type="Int64" Name="offsets" format="ascii" RangeMin="1" RangeMax="{}">\n'.format(number_polys)) output_file.write(' </DataArray>\n') output_file.write(' </Strips>\n') # <Polys> output_file.write(' <Polys>\n') output_file.write(' <DataArray type="Int64" Name="connectivity" format="ascii" RangeMin="0" RangeMax="{}">\n'.format(number_polys - 1)) if (show_polys): polycount = 0 for column_count in range(poly_size): stride_value = column_count * matrix_size for row_count in range(poly_size): temp_index = stride_value + row_count if (polycount % 2) is 0: output_file.write(' ') output_file.write('{} {} {} {}'.format(temp_index, (temp_index + 1), (temp_index + matrix_size + 1), (temp_index + matrix_size))) if (polycount % 2) is 1: output_file.write('\n') else: output_file.write(' ') polycount += 1 if (polycount % 2) is 1: output_file.write('\n') output_file.write(' </DataArray>\n') output_file.write(' <DataArray type="Int64" Name="offsets" format="ascii" RangeMin="1" RangeMax="{}">\n'.format(number_polys)) if (show_polys): for polycount in range(number_polys): if (polycount % 6) is 0: output_file.write(' ') output_file.write('{}'.format((polycount + 1) * 4)) if (polycount % 6) is 5: output_file.write('\n') else: output_file.write(' ') if (polycount % 6) is not 5: output_file.write('\n') output_file.write(' </DataArray>\n') output_file.write(' </Polys>\n') output_file.write(' </Piece>\n') output_file.write(' </PolyData>\n') output_file.write('</VTKFile>\n') output_file.write('') output_file.close() print("Done with file:{}".format(vtp_file)) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert h5 file to XML-based VTK file that can be opened with ParaView') parser.add_argument('--surf_file', '-f', default='', help='The h5 file that contains surface values') parser.add_argument('--surf_name', default='train_loss', help='The type of surface to plot: train_loss | test_loss | train_acc | test_acc ') parser.add_argument('--zmax', default=-1, type=float, help='Maximum z value to map') parser.add_argument('--interp', default=-1, type=int, help='Interpolate the surface to this resolution (1000 recommended)') parser.add_argument('--log', action='store_true', default=False, help='log scale') args = parser.parse_args() h5_to_vtp(args.surf_file, args.surf_name, log=args.log, zmax=args.zmax, interp=args.interp)
2881099/FreeSql.AdminLTE
6,079
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/sparklines/sparkline.mjs
export default class Sparkline { constructor(element, options = {}) { this.element = element; this.options = { ...Sparkline.options, ...options }; init: { this.element.innerHTML = "<canvas></canvas>"; this.canvas = this.element.firstChild; this.context = this.canvas.getContext("2d"); this.ratio = window.devicePixelRatio || 1; if (this.options.tooltip) { this.canvas.style.position = "relative"; this.canvas.addEventListener('mousemove', e => { const x = e.offsetX || e.layerX || 0; const delta = ((this.options.width - this.options.dotRadius * 2) / (this._points.length - 1)); const index = minmax(0, Math.round((x - this.options.dotRadius) / delta), this._points.length - 1); this.canvas.title = this.options.tooltip(this._points[index], index, this._points); }, false); } } } set points(points) { this.draw(points); } get points() { return this._points; } draw(points = []) { this._points = points; this.canvas.width = this.options.width * this.ratio; this.canvas.style.width = `${this.options.width}px`; const pxHeight = this.options.height || this.element.offsetHeight; this.canvas.height = pxHeight * this.ratio; this.canvas.style.height = `${pxHeight}px`; const lineWidth = this.options.lineWidth * this.ratio; const offsetX = Math.max(this.options.dotRadius * this.ratio, lineWidth / 2); const offsetY = Math.max(this.options.dotRadius * this.ratio, lineWidth / 2); const width = this.canvas.width - offsetX * 2; const height = this.canvas.height - offsetY * 2; const minValue = Math.min.apply(Math, points); const maxValue = Math.max.apply(Math, points); const bottomValue = this.options.minValue != undefined ? this.options.minValue : Math.min(minValue, this.options.maxMinValue != undefined ? this.options.maxMinValue : minValue); const topValue = this.options.maxValue != undefined ? this.options.maxValue : Math.max(maxValue, this.options.minMaxValue != undefined ? this.options.minMaxValue : maxValue); let minX = offsetX; let maxX = offsetX; let x = offsetX; const y = index => (topValue === bottomValue) ? offsetY + height / 2 : (offsetY + height) - ((points[index] - bottomValue) / (topValue - bottomValue)) * height; const delta = width / (points.length - 1); const line = (style, x, y) => { if (!style) return; this.context.save(); this.context.strokeStyle = style.color || 'black'; this.context.lineWidth = (style.width || 1) * this.ratio; this.context.globalAlpha = style.alpha || 1; this.context.beginPath(); this.context.moveTo(style.direction != 'right' ? offsetX : x, y); this.context.lineTo(style.direction != 'left' ? width + offsetX : x, y); this.context.stroke(); this.context.restore(); } const dot = (color, lineStyle, x, y) => { this.context.beginPath(); this.context.fillStyle = color; this.context.arc(x, y, this.options.dotRadius * this.ratio, 0, Math.PI * 2, false); this.context.fill(); line(lineStyle, x, y); } this.context.save(); this.context.strokeStyle = this.options.lineColor; this.context.fillStyle = this.options.lineColor; this.context.lineWidth = lineWidth; this.context.lineCap = 'round'; this.context.lineJoin = 'round'; if (this.options.fillBelow && points.length > 1) { this.context.save(); this.context.beginPath(); this.context.moveTo(x, y(0)); for (let i = 1; i < points.length; i++) { x += delta; minX = points[i] == minValue ? x : minX; maxX = points[i] == maxValue ? x : maxX; this.context.lineTo(x, y(i)); } this.context.lineTo(width + offsetX, height + offsetY + lineWidth / 2); this.context.lineTo(offsetX, height + offsetY + lineWidth / 2); this.context.fill(); if (this.options.fillLighten > 0) { this.context.fillStyle = 'white'; this.context.globalAlpha = this.options.fillLighten; this.context.fill(); this.context.globalAlpha = 1; } else if (this.options.fillLighten < 0) { this.context.fillStyle = 'black'; this.context.globalAlpha = -this.options.fillLighten; this.context.fill(); } this.context.restore(); } x = offsetX; this.context.beginPath(); this.context.moveTo(x, y(0)); for (let i = 1; i < points.length; i++) { x += delta; this.context.lineTo(x, y(i)); } this.context.stroke(); this.context.restore(); line(this.options.bottomLine, 0, offsetY); line(this.options.topLine, 0, height + offsetY + lineWidth / 2); dot(this.options.startColor, this.options.startLine, offsetX + (points.length == 1 ? width / 2 : 0), y(0)); dot(this.options.endColor, this.options.endLine, offsetX + (points.length == 1 ? width / 2 : width), y(points.length - 1)); dot(this.options.minColor, this.options.minLine, minX + (points.length == 1 ? width / 2 : 0), y(points.indexOf(minValue))); dot(this.options.maxColor, this.options.maxLine, maxX + (points.length == 1 ? width / 2 : 0), y(points.indexOf(maxValue))); } static init(element, options) { return new Sparkline(element, options); } static draw(element, points, options) { const sparkline = new Sparkline(element, options); sparkline.draw(points); return sparkline; } } Sparkline.options = { width: 100, height: null, lineColor: "black", lineWidth: 1.5, startColor: "transparent", endColor: "black", maxColor: "transparent", minColor: "transparent", minValue: null, maxValue: null, minMaxValue: null, maxMinValue: null, dotRadius: 2.5, tooltip: null, fillBelow: true, fillLighten: 0.5, startLine: false, endLine: false, minLine: false, maxLine: false, bottomLine: false, topLine: false, averageLine: false }; function minmax(a, b, c) { return Math.max(a, Math.min(b, c)); }
281677160/openwrt-package
44,343
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_http_dynamic.c
/* * Copyright (C) AlexWoo(Wu Jie) [email protected] */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #include "ngx_dynamic_conf.h" #include "ngx_http_dynamic.h" static void *ngx_http_dynamic_create_conf(ngx_conf_t *cf); static void *ngx_http_dynamic_core_create_main_conf(ngx_conf_t *cf); static char *ngx_http_dynamic_core_init_main_conf(ngx_conf_t *cf, void *conf); static void *ngx_http_dynamic_core_create_srv_conf(ngx_conf_t *cf); static char *ngx_http_dynamic_core_init_srv_conf(ngx_conf_t *cf, void *conf); static void *ngx_http_dynamic_core_create_loc_conf(ngx_conf_t *cf); static char *ngx_http_dynamic_core_init_loc_conf(ngx_conf_t *cf, void *conf); static char *ngx_http_dynamic_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static char *ngx_http_dynamic_core_server(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static char *ngx_http_dynamic_core_server_name(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static char *ngx_http_dynamic_core_location(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); typedef struct ngx_http_dynamic_location_tree_node_s ngx_http_dynamic_location_tree_node_t; typedef struct ngx_http_dynamic_core_loc_conf_s ngx_http_dynamic_core_loc_conf_t; struct ngx_http_dynamic_core_loc_conf_s { ngx_str_t name; /* location name */ #if (NGX_PCRE) ngx_dynamic_regex_t *regex; #endif unsigned exact_match:1; unsigned noregex:1; ngx_queue_t *locations; ngx_http_dynamic_location_tree_node_t *static_locations; #if (NGX_PCRE) ngx_http_dynamic_core_loc_conf_t **regex_locations; #endif void **loc_conf; }; typedef struct { ngx_queue_t queue; ngx_http_dynamic_core_loc_conf_t *exact; ngx_http_dynamic_core_loc_conf_t *inclusive; ngx_str_t *name; u_char *file_name; ngx_uint_t line; ngx_queue_t list; } ngx_http_dynamic_location_queue_t; struct ngx_http_dynamic_location_tree_node_s { ngx_http_dynamic_location_tree_node_t *left; ngx_http_dynamic_location_tree_node_t *right; ngx_http_dynamic_location_tree_node_t *tree; ngx_http_dynamic_core_loc_conf_t *exact; ngx_http_dynamic_core_loc_conf_t *inclusive; u_char len; u_char name[1]; }; typedef struct { /* array of the ngx_http_dynamic_server_name_t, "server_name" directive */ ngx_array_t server_names; ngx_http_dynamic_core_loc_conf_t *hdclcf; void **srv_conf; } ngx_http_dynamic_core_srv_conf_t; typedef struct { #if (NGX_PCRE) ngx_dynamic_regex_t *regex; #endif ngx_http_dynamic_core_srv_conf_t *server; /* virtual name server conf */ ngx_str_t name; } ngx_http_dynamic_server_name_t; typedef struct { /* ngx_http_dynamic_srv_conf_t */ ngx_array_t servers; ngx_uint_t server_names_hash_max_size; ngx_uint_t server_names_hash_bucket_size; /* the default server configuration for this address:port */ ngx_http_dynamic_core_srv_conf_t *default_server; ngx_hash_combined_t names; #if (NGX_PCRE) ngx_uint_t nregex; ngx_http_dynamic_server_name_t *regex; #endif } ngx_http_dynamic_core_main_conf_t; typedef struct { void **main_conf; } ngx_http_dynamic_conf_t; static ngx_core_module_t ngx_http_dynamic_module_ctx = { ngx_string("http_dynamic"), NULL, NULL }; static ngx_command_t ngx_http_dynamic_dcommands[] = { { ngx_string("http"), NGX_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_NOARGS, ngx_http_dynamic_block, 0, 0, NULL }, ngx_null_command }; static ngx_dynamic_core_module_t ngx_http_dynamic_module_dctx = { ngx_string("http_dynamic"), ngx_http_dynamic_create_conf, NULL }; ngx_module_t ngx_http_dynamic_module = { NGX_MODULE_V1, &ngx_http_dynamic_module_ctx, /* module context */ NULL, /* module directives */ NGX_CORE_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ (uintptr_t) &ngx_http_dynamic_module_dctx, /* module dynamic context */ (uintptr_t) ngx_http_dynamic_dcommands, /* module dynamic directives */ NGX_MODULE_V1_DYNAMIC_PADDING }; static ngx_http_module_t ngx_http_dynamic_core_module_ctx = { NULL, /* preconfiguration */ NULL, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ NULL, /* create location configuration */ NULL /* merge location configuration */ }; static ngx_command_t ngx_http_dynamic_core_dcommands[] = { { ngx_string("server_names_hash_max_size"), NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1, ngx_conf_set_num_slot, 0, offsetof(ngx_http_dynamic_core_main_conf_t, server_names_hash_max_size), NULL }, { ngx_string("server_names_hash_bucket_size"), NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1, ngx_conf_set_num_slot, 0, offsetof(ngx_http_dynamic_core_main_conf_t, server_names_hash_bucket_size), NULL }, { ngx_string("server"), NGX_HTTP_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_NOARGS, ngx_http_dynamic_core_server, 0, 0, NULL }, { ngx_string("server_name"), NGX_HTTP_SRV_CONF|NGX_CONF_1MORE, ngx_http_dynamic_core_server_name, 0, 0, NULL }, { ngx_string("location"), NGX_HTTP_SRV_CONF|NGX_CONF_BLOCK|NGX_CONF_TAKE12, ngx_http_dynamic_core_location, 0, 0, NULL }, ngx_null_command }; static ngx_http_dynamic_module_t ngx_http_dynamic_core_module_dctx = { ngx_http_dynamic_core_create_main_conf, /* create main configuration */ ngx_http_dynamic_core_init_main_conf, /* init main configuration */ ngx_http_dynamic_core_create_srv_conf, /* create server configuration */ ngx_http_dynamic_core_init_srv_conf, /* init server configuration */ ngx_http_dynamic_core_create_loc_conf, /* create location configuration */ ngx_http_dynamic_core_init_loc_conf /* init location configuration */ }; ngx_module_t ngx_http_dynamic_core_module = { NGX_MODULE_V1, &ngx_http_dynamic_core_module_ctx, /* module context */ NULL, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ (uintptr_t) &ngx_http_dynamic_core_module_dctx, /* module dynamic context */ (uintptr_t) ngx_http_dynamic_core_dcommands, /* module dynamic directives */ NGX_MODULE_V1_DYNAMIC_PADDING }; static void * ngx_http_dynamic_create_conf(ngx_conf_t *cf) { ngx_http_dynamic_conf_t *hdccf; hdccf = ngx_pcalloc(cf->pool, sizeof(ngx_http_dynamic_conf_t)); if (hdccf == NULL) { return NULL; } return hdccf; } static void * ngx_http_dynamic_core_create_main_conf(ngx_conf_t *cf) { ngx_http_dynamic_core_main_conf_t *hdcmcf; hdcmcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_dynamic_core_main_conf_t)); if (hdcmcf == NULL) { return NULL; } if (ngx_array_init(&hdcmcf->servers, cf->pool, 4, sizeof(ngx_http_dynamic_core_srv_conf_t *)) != NGX_OK) { return NULL; } hdcmcf->server_names_hash_max_size = NGX_CONF_UNSET_UINT; hdcmcf->server_names_hash_bucket_size = NGX_CONF_UNSET_UINT; return hdcmcf; } static char * ngx_http_dynamic_core_init_main_conf(ngx_conf_t *cf, void *conf) { ngx_http_dynamic_core_main_conf_t *hdcmcf; hdcmcf = conf; ngx_conf_init_uint_value(hdcmcf->server_names_hash_max_size, 512); ngx_conf_init_uint_value(hdcmcf->server_names_hash_bucket_size, ngx_cacheline_size); return NGX_CONF_OK; } static void * ngx_http_dynamic_core_create_srv_conf(ngx_conf_t *cf) { ngx_http_dynamic_core_srv_conf_t *hdcscf; hdcscf = ngx_pcalloc(cf->pool, sizeof(ngx_http_dynamic_core_srv_conf_t)); if (hdcscf == NULL) { return NULL; } if (ngx_array_init(&hdcscf->server_names, cf->pool, 4, sizeof(ngx_http_dynamic_server_name_t)) != NGX_OK) { return NULL; } return hdcscf; } static char * ngx_http_dynamic_core_init_srv_conf(ngx_conf_t *cf, void *conf) { return NGX_CONF_OK; } static void * ngx_http_dynamic_core_create_loc_conf(ngx_conf_t *cf) { ngx_http_dynamic_core_loc_conf_t *hdclcf; hdclcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_dynamic_core_loc_conf_t)); if (hdclcf == NULL) { return NULL; } return hdclcf; } static char * ngx_http_dynamic_core_init_loc_conf(ngx_conf_t *cf, void *conf) { return NGX_CONF_OK; } static ngx_int_t ngx_http_dynamic_core_regex_location(ngx_conf_t *cf, ngx_http_dynamic_core_loc_conf_t *hdclcf, ngx_str_t *regex, ngx_uint_t caseless) { #if (NGX_PCRE) ngx_regex_compile_t rc; u_char errstr[NGX_MAX_CONF_ERRSTR]; ngx_memzero(&rc, sizeof(ngx_regex_compile_t)); rc.pattern = *regex; rc.err.len = NGX_MAX_CONF_ERRSTR; rc.err.data = errstr; #if (NGX_HAVE_CASELESS_FILESYSTEM) rc.options = NGX_REGEX_CASELESS; #else rc.options = caseless ? NGX_REGEX_CASELESS : 0; #endif hdclcf->regex = ngx_dynamic_regex_compile(cf, &rc); if (hdclcf->regex == NULL) { return NGX_ERROR; } hdclcf->name = *regex; return NGX_OK; #else ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "using regex \"%V\" requires PCRE library", regex); return NGX_ERROR; #endif } static ngx_int_t ngx_http_dynamic_core_predeal_location(ngx_conf_t *cf, ngx_http_dynamic_core_loc_conf_t *hdclcf) { ngx_str_t *value, *name; size_t len; u_char *mod; value = cf->args->elts; if (cf->args->nelts == 3) { len = value[1].len; mod = value[1].data; name = &value[2]; if (len == 1 && mod[0] == '=') { hdclcf->name = *name; hdclcf->exact_match = 1; } else if (len == 2 && mod[0] == '^' && mod[1] == '~') { hdclcf->name = *name; hdclcf->noregex = 1; } else if (len == 1 && mod[0] == '~') { if (ngx_http_dynamic_core_regex_location(cf, hdclcf, name, 0) != NGX_OK) { return NGX_ERROR; } } else if (len == 2 && mod[0] == '~' && mod[1] == '*') { if (ngx_http_dynamic_core_regex_location(cf, hdclcf, name, 1) != NGX_OK) { return NGX_ERROR; } } else { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "invalid location modifier \"%V\"", &value[1]); return NGX_ERROR; } } else { /* cf->args->nelts == 2 */ name = &value[1]; if (name->data[0] == '=') { hdclcf->name.len = name->len - 1; hdclcf->name.data = name->data + 1; hdclcf->exact_match = 1; } else if (name->data[0] == '^' && name->data[1] == '~') { hdclcf->name.len = name->len - 2; hdclcf->name.data = name->data + 2; hdclcf->noregex = 1; } else if (name->data[0] == '~') { name->len--; name->data++; if (name->data[0] == '*') { name->len--; name->data++; if (ngx_http_dynamic_core_regex_location(cf, hdclcf, name, 1) != NGX_OK) { return NGX_ERROR; } } else { if (ngx_http_dynamic_core_regex_location(cf, hdclcf, name, 0) != NGX_OK) { return NGX_ERROR; } } } else { hdclcf->name = *name; } } return NGX_OK; } static ngx_int_t ngx_http_dynamic_core_cmp_locations(const ngx_queue_t *one, const ngx_queue_t *two) { ngx_int_t rc; ngx_http_dynamic_core_loc_conf_t *first, *second; ngx_http_dynamic_location_queue_t *lq1, *lq2; lq1 = (ngx_http_dynamic_location_queue_t *) one; lq2 = (ngx_http_dynamic_location_queue_t *) two; first = lq1->exact ? lq1->exact : lq1->inclusive; second = lq2->exact ? lq2->exact : lq2->inclusive; #if (NGX_PCRE) if (first->regex && !second->regex) { /* shift the regex matches to the end */ return 1; } if (!first->regex && second->regex) { /* shift the regex matches to the end */ return -1; } if (first->regex || second->regex) { /* do not sort the regex matches */ return 0; } #endif rc = ngx_filename_cmp(first->name.data, second->name.data, ngx_min(first->name.len, second->name.len) + 1); if (rc == 0 && !first->exact_match && second->exact_match) { /* an exact match must be before the same inclusive one */ return 1; } return rc; } static ngx_int_t ngx_http_dynamic_core_join_exact_locations(ngx_conf_t *cf, ngx_queue_t *locations) { ngx_queue_t *q, *x; ngx_http_dynamic_location_queue_t *lq, *lx; q = ngx_queue_head(locations); while (q != ngx_queue_last(locations)) { x = ngx_queue_next(q); lq = (ngx_http_dynamic_location_queue_t *) q; lx = (ngx_http_dynamic_location_queue_t *) x; if (lq->name->len == lx->name->len && ngx_filename_cmp(lq->name->data, lx->name->data, lx->name->len) == 0) { if ((lq->exact && lx->exact) || (lq->inclusive && lx->inclusive)) { ngx_log_error(NGX_LOG_EMERG, cf->log, 0, "duplicate location \"%V\" in %s:%ui", lx->name, lx->file_name, lx->line); return NGX_ERROR; } lq->inclusive = lx->inclusive; ngx_queue_remove(x); continue; } q = ngx_queue_next(q); } return NGX_OK; } static void ngx_http_dynamic_core_create_locations_list(ngx_queue_t *locations, ngx_queue_t *q) { u_char *name; size_t len; ngx_queue_t *x, tail; ngx_http_dynamic_location_queue_t *lq, *lx; if (q == ngx_queue_last(locations)) { return; } lq = (ngx_http_dynamic_location_queue_t *) q; if (lq->inclusive == NULL) { ngx_http_dynamic_core_create_locations_list(locations, ngx_queue_next(q)); return; } len = lq->name->len; name = lq->name->data; for (x = ngx_queue_next(q); x != ngx_queue_sentinel(locations); x = ngx_queue_next(x)) { lx = (ngx_http_dynamic_location_queue_t *) x; if (len > lx->name->len || ngx_filename_cmp(name, lx->name->data, len) != 0) { break; } } q = ngx_queue_next(q); if (q == x) { ngx_http_dynamic_core_create_locations_list(locations, x); return; } ngx_queue_split(locations, q, &tail); ngx_queue_add(&lq->list, &tail); if (x == ngx_queue_sentinel(locations)) { ngx_http_dynamic_core_create_locations_list(&lq->list, ngx_queue_head(&lq->list)); return; } ngx_queue_split(&lq->list, x, &tail); ngx_queue_add(locations, &tail); ngx_http_dynamic_core_create_locations_list(&lq->list, ngx_queue_head(&lq->list)); ngx_http_dynamic_core_create_locations_list(locations, x); } /* * to keep cache locality for left leaf nodes, allocate nodes in following * order: node, left subtree, right subtree, inclusive subtree */ static ngx_http_dynamic_location_tree_node_t * ngx_http_dynamic_core_create_locations_tree(ngx_conf_t *cf, ngx_queue_t *locations, size_t prefix) { size_t len; ngx_queue_t *q, tail; ngx_http_dynamic_location_queue_t *lq; ngx_http_dynamic_location_tree_node_t *node; q = ngx_queue_middle(locations); lq = (ngx_http_dynamic_location_queue_t *) q; len = lq->name->len - prefix; node = ngx_palloc(cf->pool, offsetof(ngx_http_dynamic_location_tree_node_t, name) + len); if (node == NULL) { return NULL; } node->left = NULL; node->right = NULL; node->tree = NULL; node->exact = lq->exact; node->inclusive = lq->inclusive; node->len = (u_char) len; ngx_memcpy(node->name, &lq->name->data[prefix], len); ngx_queue_split(locations, q, &tail); if (ngx_queue_empty(locations)) { /* * ngx_queue_split() insures that if left part is empty, * then right one is empty too */ goto inclusive; } node->left = ngx_http_dynamic_core_create_locations_tree(cf, locations, prefix); if (node->left == NULL) { return NULL; } ngx_queue_remove(q); if (ngx_queue_empty(&tail)) { goto inclusive; } node->right = ngx_http_dynamic_core_create_locations_tree(cf, &tail, prefix); if (node->right == NULL) { return NULL; } inclusive: if (ngx_queue_empty(&lq->list)) { return node; } node->tree = ngx_http_dynamic_core_create_locations_tree(cf, &lq->list, prefix + len); if (node->tree == NULL) { return NULL; } return node; } static ngx_int_t ngx_http_dynamic_core_init_locations(ngx_conf_t *cf, ngx_http_dynamic_core_loc_conf_t *phdclcf) { ngx_queue_t *q, *locations, tail; ngx_http_dynamic_core_loc_conf_t *hdclcf; ngx_http_dynamic_location_queue_t *lq; ngx_http_dynamic_core_loc_conf_t **hdclcfp; #if (NGX_PCRE) ngx_uint_t r; ngx_queue_t *regex; #endif locations = phdclcf->locations; if (locations == NULL) { return NGX_OK; } ngx_queue_sort(locations, ngx_http_dynamic_core_cmp_locations); #if (NGX_PCRE) regex = NULL; r = 0; #endif for (q = ngx_queue_head(locations); q != ngx_queue_sentinel(locations); q = ngx_queue_next(q)) { lq = (ngx_http_dynamic_location_queue_t *) q; hdclcf = lq->exact ? lq->exact : lq->inclusive; #if (NGX_PCRE) if (hdclcf->regex) { r++; if (regex == NULL) { regex = q; } continue; } #endif } if (q != ngx_queue_sentinel(locations)) { ngx_queue_split(locations, q, &tail); } #if (NGX_PCRE) if (regex) { hdclcfp = ngx_palloc(cf->pool, (r + 1) * sizeof(ngx_http_dynamic_core_loc_conf_t *)); if (hdclcfp == NULL) { return NGX_ERROR; } phdclcf->regex_locations = hdclcfp; for (q = regex; q != ngx_queue_sentinel(locations); q = ngx_queue_next(q)) { lq = (ngx_http_dynamic_location_queue_t *) q; *(hdclcfp++) = lq->exact; } *hdclcfp = NULL; ngx_queue_split(locations, regex, &tail); } #endif return NGX_OK; } static ngx_int_t ngx_http_dynamic_core_init_static_location_trees(ngx_conf_t *cf, ngx_http_dynamic_core_loc_conf_t *phdclcf) { ngx_queue_t *locations; locations = phdclcf->locations; if (locations == NULL) { return NGX_OK; } if (ngx_queue_empty(locations)) { return NGX_OK; } if (ngx_http_dynamic_core_join_exact_locations(cf, locations) != NGX_OK) { return NGX_ERROR; } ngx_http_dynamic_core_create_locations_list(locations, ngx_queue_head(locations)); phdclcf->static_locations = ngx_http_dynamic_core_create_locations_tree(cf, locations, 0); if (phdclcf->static_locations == NULL) { return NGX_ERROR; } return NGX_OK; } static ngx_int_t ngx_http_dynamic_core_add_location(ngx_conf_t *cf, ngx_queue_t **locations, ngx_http_dynamic_core_loc_conf_t *hdclcf) { ngx_http_dynamic_location_queue_t *lq; if (ngx_http_dynamic_core_predeal_location(cf, hdclcf) != NGX_OK) { return NGX_ERROR; } if (*locations == NULL) { *locations = ngx_pcalloc(cf->temp_pool, sizeof(ngx_http_location_queue_t)); if (*locations == NULL) { return NGX_ERROR; } ngx_queue_init(*locations); } lq = ngx_pcalloc(cf->temp_pool, sizeof(ngx_http_location_queue_t)); if (lq == NULL) { return NGX_ERROR; } if (hdclcf->exact_match #if (NGX_PCRE) || hdclcf->regex #endif ) { lq->exact = hdclcf; lq->inclusive = NULL; } else { lq->exact = NULL; lq->inclusive = hdclcf; } lq->name = &hdclcf->name; lq->file_name = cf->conf_file->file.name.data; lq->line = cf->conf_file->line; ngx_queue_init(&lq->list); ngx_queue_insert_tail(*locations, &lq->queue); return NGX_OK; } /* * NGX_OK - exact or regex match * NGX_AGAIN - inclusive match * NGX_DECLINED - no match */ static ngx_int_t ngx_http_dynamic_core_find_static_location(ngx_http_request_t *r, ngx_http_dynamic_core_loc_conf_t *phdclcf, ngx_http_dynamic_core_loc_conf_t **hdclcf) { ngx_http_dynamic_location_tree_node_t *node; u_char *uri; size_t len, n; ngx_int_t rc, rv; len = r->uri.len; uri = r->uri.data; rv = NGX_DECLINED; node = phdclcf->static_locations; for ( ;; ) { if (node == NULL) { return rv; } ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "test location: \"%*s\"", (size_t) node->len, node->name); n = (len <= (size_t) node->len) ? len : node->len; rc = ngx_filename_cmp(uri, node->name, n); if (rc != 0) { node = (rc < 0) ? node->left : node->right; continue; } if (len > (size_t) node->len) { if (node->inclusive) { *hdclcf = node->inclusive-> loc_conf[ngx_http_dynamic_core_module.ctx_index]; rv = NGX_AGAIN; node = node->tree; uri += n; len -= n; continue; } /* exact only */ node = node->right; continue; } if (len == (size_t) node->len) { if (node->exact) { *hdclcf = node->exact-> loc_conf[ngx_http_dynamic_core_module.ctx_index]; return NGX_OK; } else { *hdclcf = node->inclusive-> loc_conf[ngx_http_dynamic_core_module.ctx_index]; return NGX_AGAIN; } } /* len < node->len */ node = node->left; } } /* * NGX_OK - exact or regex match * NGX_AGAIN - inclusive match * NGX_ERROR - regex error * NGX_DECLINED - no match */ static ngx_int_t ngx_http_dynamic_core_find_location(ngx_http_request_t *r, ngx_http_dynamic_core_srv_conf_t *hdcscf, ngx_http_dynamic_core_loc_conf_t **hdclcf) { ngx_int_t rc; ngx_http_dynamic_core_loc_conf_t *phdclcf; #if (NGX_PCRE) ngx_int_t n; ngx_uint_t noregex; ngx_http_dynamic_core_loc_conf_t **hdclcfp; noregex = 0; #endif phdclcf = hdcscf->hdclcf; rc = ngx_http_dynamic_core_find_static_location(r, phdclcf, hdclcf); if (rc == NGX_AGAIN) { #if (NGX_PCRE) noregex = (*hdclcf)->noregex; #endif } if (rc == NGX_OK || rc == NGX_DONE) { return rc; } /* rc == NGX_DECLINED or rc == NGX_AGAIN in nested location */ #if (NGX_PCRE) if (noregex == 0 && phdclcf->regex_locations) { for (hdclcfp = phdclcf->regex_locations; *hdclcfp; hdclcfp++) { ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "test location: ~ \"%V\"", &(*hdclcfp)->name); n = ngx_regex_exec((*hdclcfp)->regex->regex, &r->uri, NULL, 0); if (n == NGX_OK) { *hdclcf = (*hdclcfp)-> loc_conf[ngx_http_dynamic_core_module.ctx_index]; return NGX_OK; } if (n == NGX_REGEX_NO_MATCHED) { continue; } return NGX_ERROR; } } #endif return rc; } static ngx_int_t ngx_http_dynamic_core_init_virtual_servers(ngx_conf_t *cf, ngx_http_dynamic_conf_t *hdcf) { ngx_http_dynamic_core_main_conf_t *hdcmcf; ngx_http_dynamic_core_srv_conf_t **hdcscfp; ngx_hash_init_t hash; ngx_hash_keys_arrays_t ha; ngx_http_dynamic_server_name_t *name; ngx_uint_t s, n; ngx_int_t rc; #if (NGX_PCRE) ngx_uint_t regex, i; regex = 0; #endif hdcmcf = hdcf->main_conf[ngx_http_dynamic_core_module.ctx_index]; ngx_memzero(&ha, sizeof(ngx_hash_keys_arrays_t)); ha.temp_pool = ngx_create_pool(NGX_DEFAULT_POOL_SIZE, cf->log); if (ha.temp_pool == NULL) { return NGX_ERROR; } ha.pool = cf->pool; if (ngx_hash_keys_array_init(&ha, NGX_HASH_LARGE) != NGX_OK) { goto failed; } hdcscfp = hdcmcf->servers.elts; hdcmcf->default_server = hdcscfp[0]; for (s = 0; s < hdcmcf->servers.nelts; ++s) { name = hdcscfp[s]->server_names.elts; for (n = 0; n < hdcscfp[s]->server_names.nelts; ++n) { #if (NGX_PCRE) if (name[n].regex) { ++regex; continue; } #endif rc = ngx_hash_add_key(&ha, &name[n].name, name[n].server, NGX_HASH_WILDCARD_KEY); if (rc == NGX_ERROR) { return NGX_ERROR; } if (rc == NGX_DECLINED) { ngx_log_error(NGX_LOG_EMERG, cf->log, 0, "invalid server name or wildcard \"%V\"", &name[n].name); return NGX_ERROR; } if (rc == NGX_BUSY) { ngx_log_error(NGX_LOG_WARN, cf->log, 0, "conflicting server name \"%V\", ignored", &name[n].name); } } } hash.key = ngx_hash_key_lc; hash.max_size = hdcmcf->server_names_hash_max_size; hash.bucket_size = hdcmcf->server_names_hash_bucket_size; hash.name = "http_dynamic_server_names_hash"; hash.pool = cf->pool; if (ha.keys.nelts) { hash.hash = &hdcmcf->names.hash; hash.temp_pool = NULL; if (ngx_hash_init(&hash, ha.keys.elts, ha.keys.nelts) != NGX_OK) { goto failed; } } if (ha.dns_wc_head.nelts) { ngx_qsort(ha.dns_wc_head.elts, (size_t) ha.dns_wc_head.nelts, sizeof(ngx_hash_key_t), ngx_dynamic_cmp_dns_wildcards); hash.hash = NULL; hash.temp_pool = ha.temp_pool; if (ngx_hash_wildcard_init(&hash, ha.dns_wc_head.elts, ha.dns_wc_head.nelts) != NGX_OK) { goto failed; } hdcmcf->names.wc_head = (ngx_hash_wildcard_t *) hash.hash; } if (ha.dns_wc_tail.nelts) { ngx_qsort(ha.dns_wc_tail.elts, (size_t) ha.dns_wc_tail.nelts, sizeof(ngx_hash_key_t), ngx_dynamic_cmp_dns_wildcards); hash.hash = NULL; hash.temp_pool = ha.temp_pool; if (ngx_hash_wildcard_init(&hash, ha.dns_wc_tail.elts, ha.dns_wc_tail.nelts) != NGX_OK) { goto failed; } hdcmcf->names.wc_tail = (ngx_hash_wildcard_t *) hash.hash; } ngx_destroy_pool(ha.temp_pool); #if (NGX_PCRE) if (regex == 0) { return NGX_OK; } hdcmcf->nregex = regex; hdcmcf->regex = ngx_pcalloc(cf->pool, regex * sizeof(ngx_http_dynamic_server_name_t)); if (hdcmcf->regex == NULL) { return NGX_ERROR; } i = 0; for (s = 0; s < hdcmcf->servers.nelts; ++s) { name = hdcscfp[s]->server_names.elts; for (n = 0; n < hdcscfp[s]->server_names.nelts; ++n) { if (name[n].regex) { hdcmcf->regex[i++] = name[n]; } } } #endif return NGX_OK; failed: ngx_destroy_pool(ha.temp_pool); return NGX_ERROR; } static ngx_int_t ngx_http_dynamic_core_find_virtual_server(ngx_http_request_t *r, ngx_http_dynamic_core_main_conf_t *hdcmcf, ngx_http_dynamic_core_srv_conf_t **hdcscfp) { ngx_http_dynamic_core_srv_conf_t *hdcscf; ngx_str_t *server; server = &r->headers_in.server; hdcscf = ngx_hash_find_combined(&hdcmcf->names, ngx_hash_key(server->data, server->len), server->data, server->len); if (hdcscf) { *hdcscfp = hdcscf; return NGX_OK; } #if (NGX_PCRE) if (server->len && hdcmcf->nregex) { ngx_int_t n; ngx_uint_t i; ngx_http_dynamic_server_name_t *sn; sn = hdcmcf->regex; for (i = 0; i < hdcmcf->nregex; ++i) { n = ngx_regex_exec(sn[i].regex->regex, server, NULL, 0); if (n == NGX_REGEX_NO_MATCHED) { continue; } if (n >= 0) { *hdcscfp = sn[i].server; return NGX_OK; } return NGX_ERROR; } } #endif return NGX_DECLINED; } static char * ngx_http_dynamic_core_location(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_dynamic_module_t *module; ngx_http_dynamic_core_loc_conf_t *hdclcf, *phdclcf; ngx_http_dynamic_core_srv_conf_t *hdcscf; ngx_conf_t pcf; void *mconf, **loc_conf; ngx_uint_t i, ci; char *rv = NULL; hdcscf = conf; phdclcf = hdcscf->hdclcf; /* loc_conf is temp cause hdclcf does not created now */ loc_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module); if (loc_conf == NULL) { return NGX_CONF_ERROR; } for (i = 0; cf->cycle->modules[i]; ++i) { if (cf->cycle->modules[i]->type != NGX_HTTP_MODULE) { continue; } module = (ngx_http_dynamic_module_t *) cf->cycle->modules[i]->spare_hook0; if (module == NULL) { continue; } if (module->create_loc_conf) { mconf = module->create_loc_conf(cf); if (mconf == NULL) { return NGX_CONF_ERROR; } loc_conf[cf->cycle->modules[i]->ctx_index] = mconf; } } hdclcf = loc_conf[ngx_http_dynamic_core_module.ctx_index]; hdclcf->loc_conf = loc_conf; if (ngx_http_dynamic_core_add_location(cf, &phdclcf->locations, hdclcf) != NGX_OK) { return NGX_CONF_ERROR; } pcf = *cf; cf->ctx = hdclcf->loc_conf; cf->cmd_type = NGX_HTTP_LOC_CONF; if (ngx_dynamic_conf_parse(cf, 0) != NGX_OK) { goto failed; } for (i = 0; cf->cycle->modules[i]; ++i) { if (cf->cycle->modules[i]->type != NGX_HTTP_MODULE) { continue; } module = (ngx_http_dynamic_module_t *) cf->cycle->modules[i]->spare_hook0; ci = cf->cycle->modules[i]->ctx_index; if (module == NULL) { continue; } if (module->init_loc_conf) { rv = module->init_loc_conf(cf, hdclcf->loc_conf[ci]); if (rv != NGX_CONF_OK) { goto failed; } } } *cf = pcf; return NGX_CONF_OK; failed: *cf = pcf; if (rv) { return rv; } return NGX_CONF_ERROR; } static char * ngx_http_dynamic_core_server_name(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_dynamic_core_srv_conf_t *hdcscf; u_char ch; ngx_str_t *value; ngx_uint_t i; ngx_http_dynamic_server_name_t *sn; hdcscf = conf; value = cf->args->elts; for (i = 1; i < cf->args->nelts; i++) { ch = value[i].data[0]; if ((ch == '*' && (value[i].len < 3 || value[i].data[1] != '.')) || (ch == '.' && value[i].len < 2)) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "server name \"%V\" is invalid", &value[i]); return NGX_CONF_ERROR; } if (ngx_strchr(value[i].data, '/')) { ngx_conf_log_error(NGX_LOG_WARN, cf, 0, "server name \"%V\" has suspicious symbols", &value[i]); } sn = ngx_array_push(&hdcscf->server_names); if (sn == NULL) { return NGX_CONF_ERROR; } #if (NGX_PCRE) sn->regex = NULL; #endif sn->server = hdcscf; if (ngx_strcasecmp(value[i].data, (u_char *) "$hostname") == 0) { sn->name = cf->cycle->hostname; } else { sn->name = value[i]; } if (value[i].data[0] != '~') { ngx_strlow(sn->name.data, sn->name.data, sn->name.len); continue; } #if (NGX_PCRE) { u_char *p; ngx_regex_compile_t rc; u_char errstr[NGX_MAX_CONF_ERRSTR]; if (value[i].len == 1) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "empty regex in server name \"%V\"", &value[i]); return NGX_CONF_ERROR; } value[i].len--; value[i].data++; ngx_memzero(&rc, sizeof(ngx_regex_compile_t)); rc.pattern = value[i]; rc.err.len = NGX_MAX_CONF_ERRSTR; rc.err.data = errstr; for (p = value[i].data; p < value[i].data + value[i].len; p++) { if (*p >= 'A' && *p <= 'Z') { rc.options = NGX_REGEX_CASELESS; break; } } sn->regex = ngx_dynamic_regex_compile(cf, &rc); if (sn->regex == NULL) { return NGX_CONF_ERROR; } sn->name = value[i]; } #else ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "using regex \"%V\" " "requires PCRE library", &value[i]); return NGX_CONF_ERROR; #endif } return NGX_CONF_OK; } static char * ngx_http_dynamic_core_server(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_dynamic_module_t *module; ngx_http_dynamic_core_main_conf_t *hdcmcf; ngx_http_dynamic_core_srv_conf_t *hdcscf, **hdcscfp; ngx_http_dynamic_core_loc_conf_t *phdclcf; ngx_conf_t pcf; void *mconf, **srv_conf; ngx_uint_t i, ci; char *rv = NULL; hdcmcf = conf; /* srv_conf is temp cause hdcscf does not created now */ srv_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module); if (srv_conf == NULL) { return NGX_CONF_ERROR; } for (i = 0; cf->cycle->modules[i]; ++i) { if (cf->cycle->modules[i]->type != NGX_HTTP_MODULE) { continue; } module = (ngx_http_dynamic_module_t *) cf->cycle->modules[i]->spare_hook0; if (module == NULL) { continue; } if (module->create_srv_conf) { mconf = module->create_srv_conf(cf); if (mconf == NULL) { return NGX_CONF_ERROR; } srv_conf[cf->cycle->modules[i]->ctx_index] = mconf; } } hdcscf = srv_conf[ngx_http_dynamic_core_module.ctx_index]; hdcscf->srv_conf = srv_conf; hdcscf->hdclcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_dynamic_core_loc_conf_t)); /* save hdcscf into hdcmcf */ hdcscfp = ngx_array_push(&hdcmcf->servers); if (hdcscfp == NULL) { return NGX_CONF_ERROR; } *hdcscfp = hdcscf; pcf = *cf; cf->ctx = hdcscf->srv_conf; cf->cmd_type = NGX_HTTP_SRV_CONF; if (ngx_dynamic_conf_parse(cf, 0) != NGX_OK) { goto failed; } for (i = 0; cf->cycle->modules[i]; ++i) { if (cf->cycle->modules[i]->type != NGX_HTTP_MODULE) { continue; } module = (ngx_http_dynamic_module_t *) cf->cycle->modules[i]->spare_hook0; ci = cf->cycle->modules[i]->ctx_index; if (module == NULL) { continue; } if (module->init_srv_conf) { rv = module->init_srv_conf(cf, hdcscf->srv_conf[ci]); if (rv != NGX_CONF_OK) { goto failed; } } } *cf = pcf; phdclcf = hdcscf->hdclcf; if (ngx_http_dynamic_core_init_locations(cf, phdclcf) != NGX_OK) { return NGX_CONF_ERROR; } if (ngx_http_dynamic_core_init_static_location_trees(cf, phdclcf) != NGX_OK) { return NGX_CONF_ERROR; } return NGX_CONF_OK; failed: *cf = pcf; if (rv) { return rv; } return NGX_CONF_ERROR; } static char * ngx_http_dynamic_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_dynamic_conf_t *hdccf; ngx_http_dynamic_module_t *module; ngx_conf_t pcf; ngx_uint_t i, ci; char *rv = NULL; hdccf = conf; /* create main_conf ctx */ hdccf->main_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module); if (hdccf->main_conf == NULL) { return NGX_CONF_ERROR; } /* create http dynamic conf for all http module */ for (i = 0; cf->cycle->modules[i]; ++i) { if (cf->cycle->modules[i]->type != NGX_HTTP_MODULE) { continue; } module = (ngx_http_dynamic_module_t *) cf->cycle->modules[i]->spare_hook0; ci = cf->cycle->modules[i]->ctx_index; if (module == NULL) { continue; } if (module->create_main_conf) { hdccf->main_conf[ci] = module->create_main_conf(cf); if (hdccf->main_conf[ci] == NULL) { return NGX_CONF_ERROR; } } } /* save conf for recovery */ pcf = *cf; cf->ctx = hdccf->main_conf; cf->module_type = NGX_HTTP_MODULE; cf->cmd_type = NGX_HTTP_MAIN_CONF; if (ngx_dynamic_conf_parse(cf, 0) != NGX_OK) { goto failed; } for (i = 0; cf->cycle->modules[i]; ++i) { if (cf->cycle->modules[i]->type != NGX_HTTP_MODULE) { continue; } module = (ngx_http_dynamic_module_t *) cf->cycle->modules[i]->spare_hook0; ci = cf->cycle->modules[i]->ctx_index; if (module == NULL) { continue; } if (module->init_main_conf) { rv = module->init_main_conf(cf, hdccf->main_conf[ci]); if (rv != NGX_CONF_OK) { goto failed; } } } if (ngx_http_dynamic_core_init_virtual_servers(cf, hdccf) != NGX_OK) { goto failed; } *cf = pcf; return NGX_CONF_OK; failed: *cf = pcf; if (rv) { return rv; } return NGX_CONF_ERROR; } /* interface from here */ void * ngx_http_get_module_main_dconf(ngx_http_request_t *r, ngx_module_t *m) { ngx_http_dynamic_conf_t *hdcf; hdcf = ngx_get_dconf(&ngx_http_dynamic_module); if (hdcf == NULL) { return NULL; } return hdcf->main_conf[m->ctx_index]; } void * ngx_http_get_module_srv_dconf(ngx_http_request_t *r, ngx_module_t *m) { ngx_http_dynamic_core_main_conf_t *hdcmcf; ngx_http_dynamic_core_srv_conf_t *hdcscf; ngx_int_t rc; hdcmcf = ngx_http_get_module_main_dconf(r, &ngx_http_dynamic_core_module); if (hdcmcf == NULL) { return NULL; } rc = ngx_http_dynamic_core_find_virtual_server(r, hdcmcf, &hdcscf); switch (rc) { case NGX_ERROR: return NULL; case NGX_DECLINED: /* virtual server not found */ return hdcmcf->default_server->srv_conf[m->ctx_index]; default: return hdcscf->srv_conf[m->ctx_index]; } } void * ngx_http_get_module_loc_dconf(ngx_http_request_t *r, ngx_module_t *m) { ngx_http_dynamic_core_srv_conf_t *hdcscf; ngx_http_dynamic_core_loc_conf_t *hdclcf; ngx_int_t rc; hdcscf = ngx_http_get_module_srv_dconf(r, &ngx_http_dynamic_core_module); if (hdcscf == NULL) { return NULL; } hdclcf = NULL; rc = ngx_http_dynamic_core_find_location(r, hdcscf, &hdclcf); if (rc == NGX_ERROR) { return NULL; } if (hdclcf) { return hdclcf->loc_conf[m->ctx_index]; } return NULL; }
294coder/Efficient-MIF
8,203
utils/loss_landscape/README.md
# Visualizing the Loss Landscape of Neural Nets This repository contains the PyTorch code for the paper > Hao Li, Zheng Xu, Gavin Taylor, Christoph Studer and Tom Goldstein. [*Visualizing the Loss Landscape of Neural Nets*](https://arxiv.org/abs/1712.09913). NIPS, 2018. An [interactive 3D visualizer](http://www.telesens.co/loss-landscape-viz/viewer.html) for loss surfaces has been provided by [telesens](http://www.telesens.co/2019/01/16/neural-network-loss-visualization/). Given a network architecture and its pre-trained parameters, this tool calculates and visualizes the loss surface along random direction(s) near the optimal parameters. The calculation can be done in parallel with multiple GPUs per node, and multiple nodes. The random direction(s) and loss surface values are stored in HDF5 (`.h5`) files after they are produced. ## Setup **Environment**: One or more multi-GPU node(s) with the following software/libraries installed: - [PyTorch 0.4](https://pytorch.org/) - [openmpi 3.1.2](https://www.open-mpi.org/) - [mpi4py 2.0.0](https://mpi4py.scipy.org/docs/usrman/install.html) - [numpy 1.15.1](https://docs.scipy.org/doc/numpy/user/quickstart.html) - [h5py 2.7.0](http://docs.h5py.org/en/stable/build.html#install) - [matplotlib 2.0.2](https://matplotlib.org/users/installing.html) - [scipy 0.19](https://www.scipy.org/install.html) **Pre-trained models**: The code accepts pre-trained PyTorch models for the CIFAR-10 dataset. To load the pre-trained model correctly, the model file should contain `state_dict`, which is saved from the `state_dict()` method. The default path for pre-trained networks is `cifar10/trained_nets`. Some of the pre-trained models and plotted figures can be downloaded here: - [VGG-9](https://drive.google.com/open?id=1jikD79HGbp6mN1qSGojsXOZEM5VAq3tH) (349 MB) - [ResNet-56](https://drive.google.com/a/cs.umd.edu/file/d/12oxkvfaKcPyyHiOevVNTBzaQ1zAFlNPX/view?usp=sharing) (10 MB) - [ResNet-56-noshort](https://drive.google.com/a/cs.umd.edu/file/d/1eUvYy3HaiCVHTzi3MHEZGgrGOPACLMkR/view?usp=sharing) (20 MB) - [DenseNet-121](https://drive.google.com/a/cs.umd.edu/file/d/1oU0nDFv9CceYM4uW6RcOULYS-rnWxdVl/view?usp=sharing) (75 MB) **Data preprocessing**: The data pre-processing method used for visualization should be consistent with the one used for model training. No data augmentation (random cropping or horizontal flipping) is used in calculating the loss values. ## Visualizing 1D loss curve ### Creating 1D linear interpolations The 1D linear interpolation method [1] evaluates the loss values along the direction between two minimizers of the same network loss function. This method has been used to compare the flatness of minimizers trained with different batch sizes [2]. A 1D linear interpolation plot is produced using the `plot_surface.py` method. ``` mpirun -n 4 python plot_surface.py --mpi --cuda --model vgg9 --x=-0.5:1.5:401 --dir_type states \ --model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=128_wd=0.0_save_epoch=1/model_300.t7 \ --model_file2 cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=8192_wd=0.0_save_epoch=1/model_300.t7 --plot ``` - `--x=-0.5:1.5:401` sets the range and resolution for the plot. The x-coordinates in the plot will run from -0.5 to 1.5 (the minimizers are located at 0 and 1), and the loss value will be evaluated at 401 locations along this line. - `--dir_type states` indicates the direction contains dimensions for all parameters as well as the statistics of the BN layers (`running_mean` and `running_var`). Note that ignoring `running_mean` and `running_var` cannot produce correct loss values when plotting two solutions togeather in the same figure. - The two model files contain network parameters describing the two distinct minimizers of the loss function. The plot will interpolate between these two minima. ![VGG-9 SGD, WD=0](doc/images/vgg9_sgd_lr=0.1_bs=128_wd=0.0_save_epoch=1_model_300.t7_vgg9_sgd_lr=0.1_bs=8192_wd=0.0_save_epoch=1_model_300.t7_states.h5_[-1.0,1.0,401].h5_1d_loss_acc.jpg) ### Producing plots along random normalized directions A random direction with the same dimension as the model parameters is created and "filter normalized." Then we can sample loss values along this direction. ``` mpirun -n 4 python plot_surface.py --mpi --cuda --model vgg9 --x=-1:1:51 \ --model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=128_wd=0.0_save_epoch=1/model_300.t7 \ --dir_type weights --xnorm filter --xignore biasbn --plot ``` - `--dir_type weights` indicates the direction has the same dimensions as the learned parameters, including bias and parameters in the BN layers. - `--xnorm filter` normalizes the random direction at the filter level. Here, a "filter" refers to the parameters that produce a single feature map. For fully connected layers, a "filter" contains the weights that contribute to a single neuron. - `--xignore biasbn` ignores the direction corresponding to bias and BN parameters (fill the corresponding entries in the random vector with zeros). ![VGG-9 SGD, WD=0](doc/images/vgg9_sgd_lr=0.1_bs=128_wd=0.0_save_epoch=1/model_300.t7_weights_xignore=biasbn_xnorm=filter.h5_[-1.0,1.0,51].h5_1d_loss_acc.jpg) We can also customize the appearance of the 1D plots by calling `plot_1D.py` once the surface file is available. ## Visualizing 2D loss contours To plot the loss contours, we choose two random directions and normalize them in the same way as the 1D plotting. ``` mpirun -n 4 python plot_surface.py --mpi --cuda --model resnet56 --x=-1:1:51 --y=-1:1:51 \ --model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=128_wd=0.0005/model_300.t7 \ --dir_type weights --xnorm filter --xignore biasbn --ynorm filter --yignore biasbn --plot ``` ![ResNet-56](doc/images/resnet56_sgd_lr=0.1_bs=128_wd=0.0005/model_300.t7_weights_xignore=biasbn_xnorm=filter_yignore=biasbn_ynorm=filter.h5_[-1.0,1.0,51]x[-1.0,1.0,51].h5_train_loss_2dcontour.jpg) Once a surface is generated and stored in a `.h5` file, we can produce and customize a contour plot using the script `plot_2D.py`. ``` python plot_2D.py --surf_file path_to_surf_file --surf_name train_loss ``` - `--surf_name` specifies the type of surface. The default choice is `train_loss`, - `--vmin` and `--vmax` sets the range of values to be plotted. - `--vlevel` sets the step of the contours. ## Visualizing 3D loss surface `plot_2D.py` can make a basic 3D loss surface plot with `matplotlib`. If you want a more detailed rendering that uses lighting to display details, you can render the loss surface with [ParaView](http://paraview.org). ![ResNet-56-noshort](doc/images/resnet56_noshort_small.jpg) ![ResNet-56](doc/images/resnet56_small.jpg) To do this, you must 1. Convert the surface `.h5` file to a `.vtp` file. ``` python h52vtp.py --surf_file path_to_surf_file --surf_name train_loss --zmax 10 --log ``` This will generate a [VTK](https://www.kitware.com/products/books/VTKUsersGuide.pdf) file containing the loss surface with max value 10 in the log scale. 2. Open the `.vtp` file with ParaView. In ParaView, open the `.vtp` file with the VTK reader. Click the eye icon in the `Pipeline Browser` to make the figure show up. You can drag the surface around, and change the colors in the `Properties` window. 3. If the surface appears extremely skinny and needle-like, you may need to adjust the "transforming" parameters in the left control panel. Enter numbers larger than 1 in the "scale" fields to widen the plot. 4. Select `Save screenshot` in the File menu to save the image. ## Reference [1] Ian J Goodfellow, Oriol Vinyals, and Andrew M Saxe. Qualitatively characterizing neural network optimization problems. ICLR, 2015. [2] Nitish Shirish Keskar, Dheevatsa Mudigere, Jorge Nocedal, Mikhail Smelyanskiy, and Ping Tak Peter Tang. On large-batch training for deep learning: Generalization gap and sharp minima. ICLR, 2017. ## Citation If you find this code useful in your research, please cite: ``` @inproceedings{visualloss, title={Visualizing the Loss Landscape of Neural Nets}, author={Li, Hao and Xu, Zheng and Taylor, Gavin and Studer, Christoph and Goldstein, Tom}, booktitle={Neural Information Processing Systems}, year={2018} } ```
2881099/FreeSql.AdminLTE
34,543
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/jsgrid/jsgrid-theme.css
/* * jsGrid v1.5.3 (http://js-grid.com) * (c) 2016 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ .jsgrid-grid-header, .jsgrid-grid-body, .jsgrid-header-row > .jsgrid-header-cell, .jsgrid-filter-row > .jsgrid-cell, .jsgrid-insert-row > .jsgrid-cell, .jsgrid-edit-row > .jsgrid-cell { border: 1px solid #e9e9e9; } .jsgrid-header-row > .jsgrid-header-cell { border-top: 0; } .jsgrid-header-row > .jsgrid-header-cell, .jsgrid-filter-row > .jsgrid-cell, .jsgrid-insert-row > .jsgrid-cell { border-bottom: 0; } .jsgrid-header-row > .jsgrid-header-cell:first-child, .jsgrid-filter-row > .jsgrid-cell:first-child, .jsgrid-insert-row > .jsgrid-cell:first-child { border-left: none; } .jsgrid-header-row > .jsgrid-header-cell:last-child, .jsgrid-filter-row > .jsgrid-cell:last-child, .jsgrid-insert-row > .jsgrid-cell:last-child { border-right: none; } .jsgrid-header-row .jsgrid-align-right, .jsgrid-header-row .jsgrid-align-left { text-align: center; } .jsgrid-grid-header { background: #f9f9f9; } .jsgrid-header-scrollbar { scrollbar-arrow-color: #f1f1f1; scrollbar-base-color: #f1f1f1; scrollbar-3dlight-color: #f1f1f1; scrollbar-highlight-color: #f1f1f1; scrollbar-track-color: #f1f1f1; scrollbar-shadow-color: #f1f1f1; scrollbar-dark-shadow-color: #f1f1f1; } .jsgrid-header-scrollbar::-webkit-scrollbar { visibility: hidden; } .jsgrid-header-scrollbar::-webkit-scrollbar-track { background: #f1f1f1; } .jsgrid-header-sortable:hover { cursor: pointer; background: #fcfcfc; } .jsgrid-header-row .jsgrid-header-sort { background: #c4e2ff; } .jsgrid-header-sort:before { content: " "; display: block; float: left; width: 0; height: 0; border-style: solid; } .jsgrid-header-sort-asc:before { border-width: 0 5px 5px 5px; border-color: transparent transparent #009a67 transparent; } .jsgrid-header-sort-desc:before { border-width: 5px 5px 0 5px; border-color: #009a67 transparent transparent transparent; } .jsgrid-grid-body { border-top: none; } .jsgrid-cell { border: #f3f3f3 1px solid; } .jsgrid-grid-body .jsgrid-row:first-child .jsgrid-cell, .jsgrid-grid-body .jsgrid-alt-row:first-child .jsgrid-cell { border-top: none; } .jsgrid-grid-body .jsgrid-cell:first-child { border-left: none; } .jsgrid-grid-body .jsgrid-cell:last-child { border-right: none; } .jsgrid-row > .jsgrid-cell { background: #fff; } .jsgrid-alt-row > .jsgrid-cell { background: #fcfcfc; } .jsgrid-header-row > .jsgrid-header-cell { background: #f9f9f9; } .jsgrid-filter-row > .jsgrid-cell { background: #fcfcfc; } .jsgrid-insert-row > .jsgrid-cell { background: #e3ffe5; } .jsgrid-edit-row > .jsgrid-cell { background: #fdffe3; } .jsgrid-selected-row > .jsgrid-cell { background: #c4e2ff; border-color: #c4e2ff; } .jsgrid-nodata-row > .jsgrid-cell { background: #fff; } .jsgrid-invalid input, .jsgrid-invalid select, .jsgrid-invalid textarea { background: #ffe3e5; border: 1px solid #ff808a; } .jsgrid-pager-current-page { font-weight: bold; } .jsgrid-pager-nav-inactive-button a { color: #d3d3d3; } .jsgrid-button + .jsgrid-button { margin-left: 5px; } .jsgrid-button:hover { opacity: .5; transition: opacity 200ms linear; } .jsgrid .jsgrid-button { width: 16px; height: 16px; border: none; cursor: pointer; background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAFgEAYAAADx4WWjAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAZjElEQVR42u2deVyU1f7HzzyzDzCA7MgihCsY7uYOiZIamebVFl/Wy8zSxLTQuld/lmIuCGIu9cruLa9lXlNTUQsVUgQRNBbZF5F9lWEbZpj9/P74doQZ87LMDHjvPe9/vj7MPOf5fp6zjc/3e86D0H8rNTVRUd988/rrxpZTV3f48PHjixb1m+N5eVOmvP76hQtXryKEEMYVFWFhERG7dvW2nIKC4OBVq/71L1JOWdk774SHb9tmcoc1mpaWtjYLi6Ki+fPff/+f/7x2DS6YlobQpEkYJyQgxOViXFGxYUNExN693ZVXWDh//urV339/8yZCQiGUM3EixqTcqqq//e3gwQ8+MJkAnU6tVqvZbKk0KSkj47nnfv/d2nrcOInk1i2EHBw6HSBCyss3btyz53Eh4PiJEwkJCAkEGKenIzRlCsaJiQhZW2OcmentHRhYUCCX5+Tcv+/nZ/KaIKjVlZUSibPz3bu2tv7+jY1JSQjZ22P8++8ITZiA8c2bCIlEGNfU7Njx9dcbN5aXv/fe55/v2kXueFfHrawwzsjw8po1Kz9fp5PJVCoOx9T+sp4spLq6qcnJKTPTzy8wMDtbpWpurqlxcBAIEPL2RkihQKi8HCEWCyEOByGBACEPD4RkMoSysxGyshoxYtKkvLxnn83IiI3192cYoZDL1WjMduefhEbT2Njebm2dnT1x4sKFt26lpCDk7Q01Mm5cp719GyEPD4zz8+fNe/PNixcx1moxZhhz+9ftBTgce3tLy9ZWodDT08enqEirRUguh89YrE6r1SLU3o6QWDx27HPP3bjBYrHZLJZO1+933JDCwnnzVq8+eZJ0xvR0hKZNwzg5GSF3d4xJjXRt+2IxxpWVYWFRUX/964A5npc3e/aKFT/+aNg5k5IQsrPDOC9v/PjXX09Nzcpyc3vhhbKy5GSEXFygSY0fD6MWj4dxRcWmTZGRW7b0m+P5+dOnr1jx00+Gw+HNmwhZWmKcmTliRFBQdjb5vlrd1NTSYm2dmsrnDx0qlycnI+TsrC9EIMC4ouKDDyIitm41ucNqtUTS3GxlVVQ0f/66dZ0TWUYGQjNmQJPo6rhOp1RqtWy2YTkKRUFBVdXQoampPN7QoR0dt26BkPR0hCZPxpjMyDCRbdxoMgE6nUqlVnO5UmlSUmbmtGl374rFY8c2NcXFwQXv3RsxIigoKwtjpVKr7X5UUSgKCiorfXxSU0Wi4cOl0vh4KCcz08srMPD+fbk8O7u4+NlnTV4ThI6OrKzS0qFDc3JCQpYuPX1ap+vo0Ggev+PdIZPduVNY6O+flRUUFBLyyy9arVSqUAiFZnPcEI2mrq611cbG2HJUqrKyhgZX135znEKhUCgUCoVCoVAoFAqFQvlP4FGIyd//wIGYGPL0eOFCsOSRooWF/jHG3RT7R7kkwNHeDpY8W7106d69DRteesn4p9UGQbdZs8BOmAD26FGwajVYS8veFd/RAZbExtatA6tUgjW5gFdfBXv4MFhnZ7hTpEZ6D9TsiRNwFBsL9u23jXWc8FiUEi5IwqFlZWBLSkAIqaGeOn7uHBzNnAl2yBAoRyo1lYDHnvfDBUiV+/qCfeYZcOjs2Z45/s03cBQQAHbUKFM7TmB19wVwyNMTjlJSwCYlgW1tBUtqjM8HGxwMdsYMcDw319SOE7qNuIAD5eVwtGwZ2CVLwFpbgyU1RvrQypXmdrzHAvQhTaCoCOzy5eDoqlVwnJEBtqnJ3I73UQAJEQkEYG1t9T8nf++/UJKRqQBsNvSR3sfQBkiASPTHaX+cV1sLTUirhWNWt4PCAAuorQU7aBDYpUv1P5fJwJo+rcZoAfqjyvvvgz18GJpQXh4cjxkD1vTjvdEC9IUcOwZHZDglwyyEtREqLu4vARQKhUKhUCgUCoVCoVAoFMp/JL1+GAuLe0isbM8esCScum/fhAkIpaWdP9/vAsCxyEg4mjsX7MOHYA2XEE6ZAtbKSv/vJBx786b+eVwuWEdHsHFxINT4xUAGT5G9vMA6O4NtbgZrbw+WPJVOTARLHrMTS+LC48aBbWsD29gI1sFB/zrGYyCAhIpIXJgE927fBktCSCtXgv31V/07v3gx2DVrwA4dCjYwEOzp02DPnDGTAJJSQCLq48eDhdVlCB05Apa0fdKESFxg506wOTlgSVDwtdfAkiaZkAC2vt5YAQaP10kA4949/b8/KcWARGQMAxrk76TJEFJTwVZWGuv4YwKgU5FQEYn/EkjwjrRxQwyTP8ioRM4j1NTAdQzLN4EAfVpa9I9JDSgUYEmb77ogtyvkcxL4Jpg+cvMEASTiQiBtndQQEWIogNQE+Zz0KYLp48dPEFBSon9MhlUS/yXDIhk+iQDSxFQqsGKxfjkkQG52AWT8N1yRTZYmks8N5wHSREjc2MlJ/3zTdd5uBJBF54Zt1s4OLJmgyJ0nAkjNkBwKMgOTpkfOM7sAMkoYdmYyqvzZqvquDhKhBJJy9qRRzIQCYJgjna2qSv9TMk+QpkCakkSi/33iMIFMWGQiMx3dRNQNL0gi825uYEeNAks6rYsL2Dfe0D+PjP9kxu43Afn5YOfNAxsSApYMk6SzkiZE/u7tDZb8GjWc2SkUCoVCoVAoFAqFQqFQKBTjMNuiHViaMmQIHJFNgqOjYQVIRcVTKwAcJ2swydJFEuEhi0sDAvRXCPYdk20pC46TQAiJIxgG/0iN/PILfN/DY8AF6C8WTU8Hu3YtWPIQ2HBNJXko/MMPxl6/z+u9wHGSOhATA5Y8nSZbnhcWgiXLch88AEtibl9/bayAXvcBcHzwYDgiKQfdpQ6Q9cW//AKWy4U+QCL3/SAAHCc5EyRyTxa+9RQfH3DcMIjYd7ptQvqdjaQIkM7YHSQ2tmSJqR3vVgA4TqKMpI331HHCokXg+MWLpnb8iQL0R5UbN/rm+MKF5nacYLAxBgkVVVeDJaNKT1m8GBwnuxmYH7b+cEi21ScB7qlT//3ppI2TO06aWv/xx0Tm7g72wgWwZCOLjz7689NITgS545cu9bfjBI6+Q6TTkt8wpEZIqtknn4B95ZWBuuOG/FEDZC8VAo8HliRnkJ8IU6eC46SmBp4/aoC0ebKnyq1bYElKQWEhOE5+GlAoFAqFQqFQKBQKhUKhUCgDi8nCrKdOFRffuTN+/LJlMTEREdevIyQUkuAqPPPu6JBKEbp6ddmy7dtDQubOdXPz9SUBk75jsk0dWSwWi8Xi8xFiGDbbygpsVwFwzGIhxGIZLpB7CgQAGg1CGMOjYmIJXY/JmhvjMfu7U80NFTDQUAEEnc6w0/6HCfDyEovt7auru442+oJ0Oq0WITc3CwtbW7Kk0Xg4P/10//6dO7D4n8Uiq097/mJkPp/N5nC02t9+q6rKzx89GiGBgIzyMP6zWGB5PKEQoZMni4tTUwMCLl4sLc3MFAg6OrRatbrn2z5DTTMMl8swDKNUshCKilqyBOPOiae3TYE4yGZDdpBAALkoGOvfBhYLFu12dMCaV6iR3l+PnMflCgQdHRyY8lUqEMDj9b5A8m0ixNDxzu/B36EmOq/T272qQQCbzeUKhUolB4oATX3b9rr3Z5Gm1Sm99+fDOVotB35kCYXGNyFyvlBImhD5BrnT0IRUKlhtbFwT0mi0Wo1m0CDWtWuVlbm5s2aBI2TRf8/fJ8/lMgybrVbn5zc319b6+a1Zc/36t98ePtzZJ4jjSqVcjlBExKxZK1Zs3jxpkqOjl9edO2q1TqfVksGjezDGGGMOh81msRhGJuPMmePuboqftZmZjY3l5QUFCKlUCsXhw11HI7jDarVKhVBIiKenv39MzMiRtrYuLsbHnU02D+TmNjXV1np6du2c+m2bYRgGoaoqmay5meRmGI/JBEBT+jPHzQv9LTTQUAEDjcn+Tww/srjczgmKWDJrwjHGCGFM8pGeIgHw61Au5/G4XIGgoYFhuFyBoPPXjk6n0ajVLBZMQP33hggKhUKhUCgUCoVCoVAoFAoFIYTQhx8mJHz//dq1CO3b9/LLLS0IRUQsXNjSsm3b7ds//fThh/3tT6+fzEFekK0t/Ivsbkw+M9ws2Pz04eEuxhgrlX+eF0S2rH2qBTxd9FrAk5I6GKZ/Q0uEXvcBFxdLSxuburquj9ExRsjBgc+3sGho6HcBH32UkHD8eGgoxHOFQmjThlkOGNvYCARCYXt7XFx1dUHBCy8gJBTC1vBQH2fPlpZmZISE7NiRknLmDIvV2qpSKRQWFlBeZ91AnJdhWCyGYRiZLCpq5szly8mbJXoPC6F9+xYuxBghFotE6v8810Gng78LBJBOKRLpj0FyOWx4rlBAJB7Cqo9DymcYCG+HhZ092/fGx3k8v+dJof/HR50/vyxxsOt9//flGANn27bp05cv37wZxnUSWyepBp0vRrCzEwgsLEgTCgq6eLGkJC1twQIiPDjY03PMmCtX5s718Bg16sqVtjalsqNDJAInSV3AkU7H4bBYLBab3d6+fTtCP/9svJAeExWVlnbx4vLlCO3Z8+KLGCO0e/eCBRgfOZKRERv77rv96ArUQG9PKC9va5NInJ07kzmgKdTXKxRSKdmfov/o9TzA4zFM/72F3gwCIEw60G530ut7CeO4QNB1tOkcVQzfO/MUCmCzGYbNbmyEcby1lQhgGIZhsfp/JqZQKBQKhUKhUCgUCoVCofxv0uPAQmNjW1tbm5NTfX1ra3Pzyy9LJFKpVDp9Oiy/cnXV6XQ6na69ncfj8bjcjAw7O0tLK6vz5729nZ1dXDIzzSWg2ydzKSlFRfn5lpbNzTKZVLpwYUtLe3t7+xtvqFQajUYzdqxWi5BOZ2mJMUTN1GqdTqcjb0cXiUpL6+vr6trbvbycnJyd79/vtxqorJRIHj4cOTI7u7y8rOz0aY1Gq9VqfX0h0I0Ql8tmczgPH8Kz0oICCIU4OkIUc/hwEIgQj8fhcDgajY+Pi4uLyzvvDBvm6urmduyYqQQ89nS6rq6lpalpzJi8vMrKioq4OHDI11ck4vEEghs3LCz4fIFgzhxwzNNz3rxx4yZMmDmTx+NyudyRIwUCHo/HGz5cLBaJRKIjR0AuhwM34rvvSkrq6mprN240Ww1cuZKenpaWmalUajQajb+/lZVQKBB8+WVg4OjR/v7vv9/bC1y/np19797LL0ON/PxzR4darVKxWFOnDh8+cuS0aY6O1tY2NsnJfa4BuVyhUCjc3cvLGxrq69evl8tVKqXS318k4vN5vOvX++o4Ac4/fx5q7IMPSHShpKS2trZ23z5ja4ApL29sbGgIDq6qamqSSF56ic2G8CjYnTuNvYC+kEOHBAIul8stK2tr6+iQy6dOLStraKir6+17DLoIaG6WyWSyoCCFQq1Wq6dO5XI5HA6npgbu0+3bphLw6IIMwzDMtWtk1WtDQ0tLS8vEiX0uD9anOzoyDEKdK7rJjt+mzz6BUaywkAReVSqtVqcj7+TogwCtVqfT6eRyksQBw6GDA3xsrnCevb3+XghqdZ8FQGdNT+dwGIZh8vNBkK8vCOnt+we6B2bsqVPBImRjIxKJRH2f4BgvLwcHJ6cLF5ydbW1tbGJjVSqtVqMhaTVhYaZyPD4+MzM9fc4cjQZjjGfOtLQUi8XikhJfXw+PIUN+/bXPAmxtraysrNLS7O3FYmvrL7+EO9/erlSq1Wp1aOj16zk5WVmQUtA3x+/dy8iwsdHptFqtNjqax3N0dHREaNiwIUO8vDZvNvbGPJqJ7eysrMTi+/dHjHBzc3ffvFmhUKlUKoRUKrVarT53Diakdevi47OyMjO73wsF7viMGRhrtVptQoKFxZgxY8b4+ra0XLp0+TJCpaV790ZEGN/Hnvhb6MGDurra2vXrc3MrKysqoqNJ0gaPx2az2ZWVMBxevgyjSlkZhFutraHpzZ4N6SKTJgkEDg4ODghJJBcvXryIUEXFRx9t2oSQTCaXy+UIBQVFRkZGrls3bVpYWFhY7/OGuv05XVvb1NTUNHFicXFtbU3NoUMKhVqtUk2eDD/iyLDY+X2MoXNaWg4aZGf34IG7u6urq2tYWE7O6tXvvhsQcPfusWPHjq1fb23t7e3tjZBUWl1dXY3QvHmHDh06tGHDhAmrV69e/cUXJhNgSFWVRNLY6OtbXS2RSCQTJqjVsEUI5GApldbWIpFIVFDg6enu7uGRlGRpyWKxWJ27msXFbdmyZcvBgykpUVFRUaGhYrG7u7s7Qm1tICQ4ODIyMnLTpokT165duzYyss9ty9xcv/7ZZ599duDAzp1CoVCIcVSUm5ubG8bkOCkpIiIiYseOgfazWxISwsPDw6Ojw8N5PB4P46iowYMHD8Z4506RSCTCODFx9+7du033m8xsgKO7du3cKRAIBBgfPOjj4+PTKeTKlbCwsLC9ewfaz25JSTl06NCh8PDwcD6fz8d49247Ozs7jD/5hM1mszHOyzt79uzZ0FC5vKGhoWHIkKcuc/e550JDQ0P/7/+Cg/fv379/yxadDuYjS0sLCwsLhLhcoVAolEoRYrPZbKVyoP19IgpFa2trq739jz+GhISEnDhx8uTixYsXHz/e0dHc3NxsazvQ/lEoFAqFQqFQKBQKhUKhUChG0U2ERiBob1cqFYp9+ySStjapdP58iGa2tdnbW1uLxTt3jhzp5ubhcfbsUyMgL6+qqqIiKKisrKGhvv7YMUg5GDwY4jFlZbDlu7W1VouxTicUWltbWFhYXL7s7m5nZ2+/dKmHh4ODo2PP319gLI8e7hYV1dRUVQUGlpc3NDQ0XLum1ep0GJeWwtLDCRMglDRsGJvNZjPM4MEcDofD4Xz4YX19S0tz8yuv1NQ0NUkksbH9XgUymULR0WFvD2k29fUxMXfupKQkJvb0/Bs3cnKysvz8zp9PTU1OxhjygvovIMEUF9fV1dZu3QrRRUdHCws+n8/v+crsgAA/v2efzcnhcjkcLvf0aYlEKm1tXbPm/v3a2urqnu9q32cBLS3t7TLZsmWwGrW8fPZsf/+xY/PyelsQZLlcuaLVarUYI1Rd3dTU3Gz+Fd4MQgixWCT3zdLyt9+yszMze79NAkTibW2hHB5PKOTxeDzymngzCvDxcXZ2cgoP1+lg7wKVSqPRalev7m1BGHO5XO6qVba2Hh7u7ikpkyYNHTpsWHOzuQU84s6d4uKCgpiY06eTkxMTMYbOOWpUd+fFxxcW5udv356QUF9fW4txeXlZWWlp3zOwesujplJd3dTU2CgQlJXV1zc0nD/f1NTeLpUGB8OmL6dPw7B57RpE4p2ctFoej8t99VWRaNAgOztf39zc5ctXrECIzy8vLy8/dWrSpC1btmxZvtzff+XKlSt7/kqM3vJoHhg8eNAge3uFYtq0kSNHjXrhBVdXW1s7ux07RCI+n8+fOBEmtM8/hy3KQ0OHDHnmGR+fqioXl4cPJZIXX9Tp0tLS0lJSiopKSkpKli0rKrp69erVc+dyck6dOnWq/9faP0ZiYl5ebq6bW2pqQUF+/uM7OV27tm5daKit7YkTISEhIUlJkEiD8fHjwcHBwcnJKSkHDx482PfUsn7jzp2vvvrqKzu7b78NCAgIyMjYtIkImT179uz4+Nu3o6Ojo21sBtrPbklOjoyMjLS0PH48KCgoKC5u/XoQcvTojBkzZmRkyGR1dXV1gwcbex2z7dExdWpYWFhYe3tVVWpqaurChTKZVCqVPniAsUaj0bi58flisVjc92Q/swsguLlNnjx5skx26dKqVatW/eMfarVGo9HodAzD5/P5Eom5r0+hUCgUCoVCoVAoFAqFQqH8b3PsWHFxauqLLx49mp+fmLho0UD702Nyc1ta6urc3RHas2fBAowR2rkzOBjjTz+9e/fCBeO3ZzDbKiaZTKNRqRgmIOD06e3bb95EiMuFMIdGo1Ih9N13hYXJyatWPbUCnn/+3Lndu2NjHz5sbKyoGDKEOO7q6uHh51dRkZPzl7989tnkyU+dgDfeiI//+9+/+CI1tbDw1q05cxDi80UihBiGz7ew0Gji4195ZevW558Xi/l8oRD2yX8q2LUrMzM29r33EAoPDwrCGKEvvnjtNYwR2rVrwQKMY2OrqwsKnn/ebA6MHn3y5JYtiYlTppw6tW1bz9e4x8RUVOTkzJpFNpFH6MABcBw6a3R0Ts5vv61dazbH58y5dGn//h9+QGjr1mnTOi88evQPP3z88Y0bdXUKhUz2eJQxL6+lpa7OzQ2h6OhXX1WpEIqOXroUY4R27JgzB+OVKxMSjh//6iuzOf4HzPTpzs5Dh2ZmImRt7eSEEEIikViMUHZ2dXVBwaxZfn7ffbd+fV7egwetrQ0NnUsAAwLOnAkPv3ULIY1GqeRyEZLL29oQmjnTzy8wMD7+229nzVqxYs0acwt4FOi+cqWqKi8vIGDRonPndu+OiZHLOzqkUisr8ioKe3t7e0/PsjIPDyurQYNKS9PTy8uzsgIDEVKrlUqEXF3t7T08KisfPHjrrQMHvLwEAjabwyFv6e4HAYQHD6RSicTNbc6cM2d27IiLKympqSksHD4cISsre3uEEMIY3IL9JxBiGDZbpyspefvtI0e8vJ55xsrKzq6iwtyOEx4bRr29razs7KqqcnLefHP//tGj584dOXLmzMuXEWptra8HAbDDgVqtUCD0669Llnz66dy5/e14r3nrrbi4o0ePHkXo44/HjcN4796srGvXNmwYaL96TVxcZWVu7owZA+3Hfw3/D73/bnBl1mLvAAAAAElFTkSuQmCC); background-repeat: no-repeat; background-color: transparent; } @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) { .jsgrid .jsgrid-button { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAALAEAYAAACFny30AAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAA6CUlEQVR42u2dZ2AUZRPH53rLpVdSKSGhgwoIqIgKiBRFBGwooQjoC9KbSEdFqoIiNhDBQhdEQBABIShNCCUhpEF6T+5yuX77fhgejhwc6dkE5/dl2LvN7uz8n/4cOwAEQVSCmJjOnZ97bunSK1eeeWbo0G7d+Pbn2rWBA8eMmTnz8uWuXQcPfughvv2pLMKKnpiY+Oqrs2Z16lRampwcGzt6tNlcWFhQMGwYX45nZCxe/O23kZEazb///vPPuHEWS3FxQcGrr/LlT62RlBQV9d574eGnT/v6tm6dkREdDRAUxHHR0WJxSAjHXb3ar9+wYcuX15U/WVkrV27e7Od35kzjxg8/fP36iRMA3t4cd+qUUNikCcfFxHTs+Pzzc+fyHbdqk5T02muzZnXu/M8/Xl6RkXl5p04BNGnCcefOAXTrxnFnzgC0a8dxJ08KBL6+HBcb26/fsGEffVRb/mRmLlu2aVNk5JkzjRq1b5+WdvIkQKNGHHf+vN2f9u05LjpaIAgO5rhLlzp1euGFOXP4jmN5CBw/SEgYMWLq1CefzM/fseOXX7Zv57jiYgAvL4kEwMsLgOMATCYAgQBAIgGw2QAMBgCTSSjMygLw9OzXr3fvFStatNizZ9OmqVOr62BW1sqVW7YEBNy8+ckny5YdP26x3LiRnd2smUwGEBZW1h+RyH5sNgsEGg2AQhEZ2bTpqlVisYuLu/tPP7VufebMtm2nT/MdeMZdfYBQqFZLpX376nTFxdeve3mJxQCurvgdx9nP4zgAiwVAKASQyQCkUpvN3x+goGDv3gMHpkyJje3b9/XXP/64qo5hiW/VKjV1+fJly86fN5tv3MjJadZMLi8b+Hv5o1IBWK0cp9EAGI0aTVrapElicWCgi8srr/Ad8HIF8PcfPjwqatas0NBRo2bM+PjjkhKACxewpBuNWNLE4rIPbrXig8vlAFIpx6EQ+/cfPjxtWmzsc8+9/vqqVRV1iJX41NS1a1eu3LPHbM7IyM7295fLAUJD0Y87A3/7QW7d32AASEkBkMmCgwMCCgsbNRo1auzYHj1cXTt16tp15ky+A+6IoLwTbt6cNu3DDxcsSE5etmzevLlzFQqA5s2xuqtUKIDZfOtiAntTwAQzmQSCzEwAT88+fXr1WrGiRYvfftu8+e6mCQPPSvzhwyZTRkZOjr+/QlF+4KVSDPzNmwAiUXCwWp2bGxIyefL06U8+GRAwadKIEVev8h1oZ5Q7DA0JWbZs1qx580JDp02bM2fx4tJSgLg4DIheb+8LGM5rxIEDhw9PmRIb27//G2+sWMHOz8xcuvTrr93dU1PXrFm5cu/eypR4mcweeLE4MFCtLiwMDn777cmTn3++vgeeUW4NcOTmzVmzli9fsCAp6cMPZ86cO1epBIiMvH+NEApRFKMRwGoVCktKANTqDh06dPjsM7M5MzM3t1s3vT4jIympfXu5HCA4uGIlPiUFS7yra05OcPC7706b1qNHo0ZTp44aVf8DX2UBGCkpU6cuWLBoUUrK8uWLFs2Zo1IBtGyJAVIo7J3i7Rvd0TSZzSiIRmOvQRIJgLu7/fvyAi+RhIZ6excUBAWNHz95ct++AQFTp0ZF/f033wGtMwEYWCPmzMEasWhReTWizM1vHd85unKEBV6vB0hKApBIGjf28cnODgubO3fBgu7dfX2jogYNunaN70BWlQovRTgjJOTDD6dOXbw4LGzmzPnz583T6wHi48v2EXeOmu6kIoE3GABu3ACQSkND/fwKCsLCZs6cN+/55xt64BnVrgGOpKUtWrR27ciRaWmLF69atXatSGQ0qlRyuUCAAQW4f+AZVitASQmARBIR4eV17lxQ0JQp7777yiu+vm+9NXTo9et8B66mqHYNcEShCAlp1mzrVrHY3d3VtbCQ1YTKIBBgDSotBVCpGjdu3/7IkQct8IwaEyAjY8mSb75p2zY5efbs9967csViyc4uKQkIEIsBPD3xnIqUfHaeWAzg7Q1QWPjXX4cOvftufPzAgW+/PXEi3wGraaotQE7OmjU//RQUlJb25Zdr1uzZYzKlp6enBwdLJBh4Ni+4F4L7NICsDxAIdDqxWCrNzd29e9euVavi44cMGT9+yhS+A1dTVLkPSE+fO/fzz9u1y8zcuHHDhoMHjcabN9PT/fzKm7my4ajVCqDV4rFcXrazttnufb5Oh4tseXkAvr6DBg0ZMmVKePj27WvWrFzJdyCrSqUFSEoaPXru3NDQ3Ny9e3fuPH7cZsvKKi4OCZFKAYKC7l4kuzOQYjHODQoLAQQCmQznBUaj0Yjfubvbz3OsOWy+wIQzmwWCggIAH5/Bg196aebM5s23bl2zZulSvgNaWUQVD/ybb86e3aFDbu7u3Tt2HDtms+Xm6nSNGkmlAI0alR3v38mdw8mkJACpNDw8ICA9PSho8uQJE558Uiz28XF1LS4uLLx8+dChbt3EYgAPD/w7xxphs9mXIJhQWu3Vq2fOPPPMrFlDhowcWVKyZs2VK//8c+oU34GtKOXWgKSkkSPfey80NC9vz56dO0+csFpzc43GoCCZDMDXt2Iz1+RkALE4JMTbOz8/LGzevLlz+/Tx9R05csiQM2fY+deuvfrqmDE//piV9cMP33338ssqFUCrVvalDI67u2m6s0ZYLCJRYSGAt/dLLw0aNHNm8+Y//9wQaoRTARITX3tt1qyHHsrLO3Bg1679+zkuP99k8vWVSDDw5ZX4O2eu3t6ZmWFhc+YsXNi9u6/vyJGDBjkfTl6/PmzYhAkbNmRkfP/9+vXDhyuV9iUOiaTsEsedq69WKw5bLRahsKgIwM2ta9cuXaZPb9XqxIlt25Yt4zvQFRYgIWHEiGnTHnssL2/Hjt27t20DKC4G8Pe/c0esciV+1iws8ePG3VniyyMubsiQUaN+/DE7e+vWzZsrViPEYvsM3GJBzxWKVq0iIpYulUhUKnf3rVtbtTp9euvW8+f5DvztuN0dSFdXieTFF3FHzN9fLAZwc8Pv2APfOZ53LPFicePGXl4ZGWFh8+cvXPjoo5UNPCMycuvWr79+5ZVGjYYNGzPm2291OoDLl9EHi8Ve8pk/rGCIRABqtb1GGI2FhampM2YIhQEBSuWbb/Id8HIF8Pd/883hw2fMCAsbOXLGjM8+0+kALl60t/WspDmWeIkkJMTHJy8vLGz69HnzBgzw9R0x4sUXExKq62B4+Pfff/LJyJF+fkOGDBu2ZUtpKUBsrH2UdKc/bH/gxg0AmSww0N9fqw0IGD581KhevVxdH3740UdnzeI74JUmKWncuPffX7Hi6FEAiYTjzp4F6NiR46Kj8VcJp083btyqVVpaTs633+7c2aRJbfuDfcTXXx87BiCT4a80OnfmuFOnAEJCOO6ff4KDIyIKCjIyPvxw/foOHfiOX42RmDhy5LRpq1cfPgwAwHGnTwcFtWqVn5+dvW7dtm0PP1zX/ly7NnTo2LGbN//xB/rzzz8BAS1aaDTp6QsXrl37+ON8x6vWSEqaMGH27A8+SEv76KPPPuvShW9/rl2Linr77c8/T0mZPHnBgl69+PaHIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIIga4q5XF7drt3r1nj2PPYZHLAVh8+ZohcKytqI5MerscW49z53vWwfAtEIAAJMmXbw4ceKAASdO8O0pw0l+o9270Xp5oWVv8s/ORssCX5m0PLUJCzzLXMCO/fzQPvJI2efy9ubXXztOBGAl5Pnnyz7YBx+gPXQIbVAQ2jtfo80HrEampaHt2RMte2u6QlH2ueoPTgRgqcp37Cj7QC+8gPbIEazKR47w/QAMbDpbtCjrJws8KzD8pWB3htP8AfhArApv24aWvRI4MRFt794oBDuue9DPpk3x6OBBtOz4r7/QDh6MfrImtP7gNItSWYfHjEHL3rvPHnDnTgyAj09dO172vjt3lvWL+TlmTH0NPKPcNFb4ALGxeDR+PFqWAaNtW7Rbt2JAZLLadrjsfbZuLesH82v8+LJ+118qnEcMHyg6Go8mTUKbk4P2ySfRbtmCAWJtb81R9rpbtpS9L/ODDTOZn/WfSidywwfctw+PWGZsgwHtoEFoV6/GgMnl1XWw7HVWry57H3bfqVPL+tVwqHImPXzg77/HI1Yj2HzgrbfQvvdezbjJrsOuy+7DSjzzo+FRY9lUsaTOno1HS5agNRrRLl+O9uxZtGwC5ww272ATKFbTWNv/3nsYeDYvabjUeDpbFIItYTgm3ywpQVteH8Hyr7q4lP189WoMPKtxDR9x9S9xL2bMQMsCOGoUWhb4lBS0jjNoNqMNCyv7+ddfl73ug0ON5xPGEsqakD17yn7LlgL69EHLUqAwyz53XDLYs6fsdR8caqkGMBwT1rLOs6AAA5qfz77BpsvxPGfXeXCo8RpQFsfAsdRrzrLMs89Fovtf58GhlgUgyoME4BkSgGdIAJ4hAXimjgW4V0Lc/za1LIDjcJNNpEpL+X7w+kItC8ACzkp8y5ZonSUBZcnK/zs1pJZnwmz1k22QdOuGdv16nPn++ise79qFNiYGrVbLd2DqilqrAbjUkJmJR++8gxaz/wI0boyWbXH+9BPazZvRtm7t4OYDO1io9QdDIS5exKNXXkH78stoWcn39UX77LNoQ0PLXqX295r5grc1FmyC2HI1C/hrr6FlAl27hvbtt1HI5GS+/CUIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiB4otbfmHX2LMDDDz/1FB69+ipa9lZEsxkteycce2v67t2PPAJw7lzDS8pTWWr5rYkMlo21a1e0LPuRowAst0xCAtoHX4C7agCW2IcewqPISLQsjRQLWHk4ZrpYtAhteHjF/j43F+20aWWvJ65ggWE1ib2p9/JlrFEsw179wckD/fAD2ogIftxiKQo3bqyZ67GX/7ECVX9w8trKms+Exy/193mc1ICxY9G2aYO2qAgta7udpRRhiZJZJ5uXV/Z81iSwgLCSzs7T6dA6vqiVJZZmTQs7n13PWaoU9j5S9kbe+ofTURD2BSwQrBN1bFvZg3MctrGxsfh3rM9g2U0dA1NcjOffuIHnBwTg5yx9ruM7pFNS8HydDs9n/rBOm2X8Zv4wGx+Pf1fRvqvuKadTe/RRtCy/ESuJLNEaCyjHYWD69y8bOJZImWXUY2/AZZ/36oV2xQq07M26LGASCdpXX8Xrs9HR0aNoWU1iNdNxODtgANr9+/kOtDPKEcAxhzzDWZvKmiCWqI3h+Ophx2PHrEks8AyNBi0rAEplxfypv3mEGeW8O/rmTbSFhRW7nKsrWtZGs8A5UtG0VGz4yXLFq9UV+7usrLJ/V39xKkDZtpO9Bb08WAllTQJrqqoKa7pYDkp394r9HZtHsL+vv1Tw7ekVFcDTEy3LkFHdPADsOqwGenhUzt/6n/qwhgVgAaopAdiwlAng5lY5f1lNrL9UUADWppaHqys2XazpqX4NwOuxQQDrY8r3t+zf1V9qXICyx8464YrimOynogKwHPP1nwoKUNHhnGMnWVxcPfdY58twHH5W11/+qWQf4JiA2RE2A2ZUtwY4NmEV7QNSU2smPLVPJQWw5/+9N44ToorOH5zh2AQ5pjh3hA07q3vfuqOCArDhXHlV27EGVHce4FiDymuC2ATQsemqv1RQAFayyhNAKsU1GzbTrW4gHPuQ8gRgE7AHVoDyRkNsjYetCVW3DygsREHZ/EKluv/5rIBU9751R7kC4Hiadb4ZGfc/mwnAliSqLwBaNroqT4CcHPS3/i9BMCqZyK38JghtTQnANoLY6KeifUDDoZICsDbWGWxZmTUZ1Z0JMwHYKqjjMrUjFZ0w1h8qKUBFl3dZk8E60cqOhtgqbEEB2oouQ9f/5WdHKikAq+LlbfGxGsBKcGXzB7M2nNW4igrABGs4VFIANrwrr61lNaCiAjhu0DCBWSdcngCsrylvolj/qKIA5fUFHh44GmGBdwyMY8Adx+0lJfj3rAkrbyOGCd1wZsCMSgrAOtXyBPD3L3vs2Aew0RLDsXN1bOLYqMoZLPANrwmq9I9zcWLEfjnHfsXgCAtEfDzatm3RsmEkK/FXrqBlv1hjw03WB7Df84SEoGU/W3Hk6FGsMT168BnMqlDFH+eWVwPY1iT7WYsjbFGtc+d7f88mdB07Vswf1gQ1PKooAMuQzYRgM+TylqtrCvb7H/bLt1On6ua+BEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQDZB27Vav3rNn3jy0o0fz7U9lqfWEzrUFBnzDBjwaPrzstyNGXLw4ceKAAez7+kuDEwADz9Lcvvnm/c+u/0LUewEw4Oxti3v3omUp0itK/RWiku8NrXswcOwFsMHBVbvKt9+ikFFRfD+PI/VWAAzY0qVoIyNRCJbG9vDhql21/glR75qge3eu7M24ISEoREkJnsfS4j7zTNXu9vbbeL116/h63npTA+4/qmFvY79+Hc9zccHA9eyJn1e1RnTpwvdz8y7A/QPvCHsndXWFOHAA7aRJfD8/b01Q5QLvDJYxIzy8Yk3TgQN4Xp8+fD23I3UuQM0E3hFnQly9ip9bLPg5e4l4/aHOBKidwDvCkgyxJom9nZ0NZ+vq3dYVp9YFqJvAO/LjjxjwV1+tm/tVnVrrhPkJ/MGDaN96q27uV31qvAbwFXgs8c8+Wzf3qzlqTAAKfNWodhPET+DZcLLhBp5R5RrAb+Drzzi+ulRagMqtx9cUD17gGRUWgAJfOzgVAAPO8nt99RVaCnxNU04nPH8+Wgp8bXG7BmCJZwmTLRa0CgXaEyfQtmpVO2789wLPcKgBLOCXLqH19cXAtG5d9vOa4r8beIaDAGzzOzwc7bVrWDOYEGw1sbpCUOAZDgK0aXPv01JSakYICrwjDgK0bHnv01jTVFUhKPDOcBCgvE62PCHi4sqe//vvFPj7I8BAsgTLf/+NtlOnyl2GddLJyWgXLsTAT53K9wPWd27VgNBQtM76gPJge7BWKwW+ctxKZ9u9O1rWxLCEygkJaK9fR3v5clnLPmdpbcXisn9PlMetgLHN67Fj0f7zD9rERCzRLJU5QRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRDEf496l0mP0anTtm0LF3755enTqamXLr38skCgULi6lp+Eh+MAAAQCgOLi7GyBYNmyPn3Gj58xY9q0du169+YvY54zxHw74AyRSCgUCn19AUQiiUSt5jiRSFwpb4VCiQRAJAIQCt3d+X4eZ9RbATiO4zhOpwPgOCz3HIelu+JXsNmwRnCcwcD38ziD91SG/3VIAJ4hAXiGBOAZEoBnSACeIQF4hgTgGRKAZ0gAniEBeIYE4BkSgGfqrQAWi81mtQIACASCertrUX3qrQBubjKZUslxAFYrS6xYOXA5WqkUi6XS8jdy+KLeChAcrFJ5eOj1AFar2VyVK+AGTm6uwVBSUn9TsAgefXTbtgULvvwSQCgUidzdceOjao9cfTgOS6zFEh+v1ebmPvFEWppWm5/fuDHujFXmWlhzwsJcXb29z55t1kyt9va+eLGkxGw2GlmyorrHYrFYTCaZLCDAxcXTMy5OALBixeDBHAcgFuOWX2V3nmoamw0bDJkMM1tKpRgu1idUFIFAKAQAMJlKS9HivphQKOS13qMfKpWbm79/ZqZYIFAqXV2Li3HP1c2NfwFwSx2AbbBXNvAMtpUpkcjlaFm55/f5xGKZDMDLS6FwdU1Pr5d9QG0FiO+CdS9/6qUA/yVIAJ4hAXhGaP8lGVGXsLiLAYqKsrNdXe3DUJuN784K769S4e/ZZDKVCv2q3GhIKMTn0emKigAAjMaSEvyG3+JmNhsMAKmpAAJBcLBgxYoLFw4eHDcOQCgUCHAiBlD3vyQTCgUCgYDjpFKhUCw2mb79Njb2r79Gjjx3LiMjLu6hhwDkcheXylzRYNBqAZ5/PiLiscd++aVXr6Cgli1//91gsFrNZpmsrp+PgWtccrm7u1Qql6ekiKdMad++Pv5o9Z13jh797rs2bc6dS0w8c6YqApSWajQAgwc3afLQQ9u2vf568+ZdumzZwvdzOVJvO+ErVwoLMzNdXQFksqotHGATlJ2t12u1vr58P49TL/l2wBklJdhW4hoV397UHvVWALGYBZ7/pZHapN4K8F+BBOAZEoBnSACeIQF4hgTgGRKAZ0gAniEBeIYE4BkSgGdIAJ4hAXim3r4rQq+3WEwmT0/7L9rwB00VB//ObLbZrFa1mu/ncUa9FSAkxMXFw+Ps2cxMd3d//+BguVwuV6v1+vL+ji1dl5QIBAKBQuHuLpMplQkJfD8PQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRANl1pPZ9O9+65dH30UEXHpUk5OYuLhwwUFJpPBoFIJBBKJXG4wsJQ6HFdSUlioVLZp4+0dGpqYOGlSly4vvfTMMyNGNG/epUthId+Bqi1q/Y1ZAoFAIBDI5ZgJIygIQCQSiQA4jiVoYDmN8FggABAIwsLw3w9y7oxbT13bN+A4juM4kwn/ZTDYM2I4swAcp9FwnD0d54NMHb01kZXyimbw+u8klqPXVvIMCcAzJADPkAA8QwLwTK0LgOP6yv+dzfZgJ3Bj1LoAZrPNZrEA2Gz21wrfTxAc/wMoFGKxVMp3eGqfWhfAzU0mUyrz8hQKgUAotNnseYEdZbDZbDYAFxexWCo1m195pWnTRx4pKOA7QLWNuHv33bs//LB5cwAAoVChwBmpyYRfV31ChPmBLRa1WiqVy5s0EQgEAuEtue/dtEgkUilAfr7FYjZLpaNHHz363XcdOsTE5ObeuKHTyeUSiVQqFjv764r5w3FGo8ViNstkHh4ymUKh0ezb17//lClJSbwJcOlSVlZS0rFjuEbj61tTAuBajsViMtlsVqtYXFwsEAgEMpk9Q7ZjG69QqNUA8fGlpcXFISHp6VevHjt28qRSKRZLpVhrOE5c5bUrXJPiOJvNbDaZZDKVSiZTqWJj8dtWrXgToKDAbDYYXFwAbDaRSCjEwMjl1b80xwHgG/9RRizhzksw+1woFAoBdDqz2WxWKHQ6kwlfWl/d5QmBAK9gNptMACaTUCiR1MRzVg8xLgtrtbg66eJSm+lj7Ytt9/8eqenwMAEAhEIApVIikck0Gp2udp61ooixZHFc7S+AVVbWmvbHcUGwfiz4iXEjxMfHnrm6pmoAW0wWibDlVird3Mp+X/Y+rJNmf6fT4TaMzYbn2Utw1WB/b7EYjQC5uRaLxeLtXfshvj/itm29vYOD4+Jw+8PTEwNjNjOnK3tBFlSZTCgUiYzGkhKbzWJRqeLi9HqNJjDQHui7/9JqBRAIOA7Aao2I8PBo1Cg9XaUSiSQSk8lsttlsNomkegJwHMdZLCaTVCoWy2QqVUrKv//yK4Bg48b4+OhoDw90UCLBEFZdADbh8vZWKNRqozE3V6fTaiMjZ878889vvjl+PDfXZNLrlUo26rFTUlJQANCmjZdXcHBi4gcfPPXUiBHduxcVGQw6nUZjtXJcdQRgG59mM8dxnFSqVAqFQqFe/+qr4eGPPqrR8CWAePjw5s27dq29Pdfnntu7d+XK7Gxs4gQCAKEQmyTHeTE2STIZbkRqtSaTXp+ZOWxYeHjnzg/uzlitz4SzsvR6jcbV1WJhUzEcZt4NfmsycZzNJhYbjVarxeLuzneAaps6WIqQSpXKso1ZRTr5+jFGqX1qXQCb7b+wtV51aD+AZ0gAniEBeIYE4BkSgGfq4LehbHkBlwLsazJ2y860f85xbObKd4Bqm1oXwGCw2cxmmcxiMZtNJrmcrccD4LKwXQCz2WgEsFoxj7DZXL2lh4ZCrQvg4SGVyuU6nYeHTKZSxcQIBEKhRCKVSiQSiUxmNLJyr9GYzWazUuniIpe7uKSmymQikUTC1qQIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiCI/yx1/oLgggKtVqsVCvV6k8lkCg52dVUqlUq1mr24DN+0a7PpdEaj0VhQEBDg4eHpmZXFd6Bqi1oTICenuLioyNs7K6uwsLBw4ECdzmg0GHr2LC01Go3Gtm0NBpPJZGraFF9eJhbfKQBmELDZbDaNBrMnXb8uk0mlYvGZM35+bm4eHr/80rSpv39AwIEDfAewutSYAHl5Gk1xsb9/YmJWVlbWlCnFxaWlJSWjR5tMFovV6uYmFAqFAgGASIRvSReJ8C3qjhnz7C/txrfJWa2YQYmdhwmiAcRioVAkunzZ29vV1dX1888ffrhp0/Dwdev4DmhlqbYAV66kpt64MXbszZt5ebm5H31ktVqtVqubm1QqFkskGCjMzVSzjmMNATAazWazGUChkMmk0jNnmjcPCAgM/N//QkJ8fHx9T5/mK7AVpcoCREfHxV29unFjfr5Wq9G8+SYLuEQiFmO6tfvlomFt+qVLaDMy0BqNaF1c0DZtirZ9e7SYFutemM0Wi8UCoNfjazFbtgwKCgmJioqICAwMCtq4ke9AO6PSAhw9euXKpUt792o0Op1O16+fUimXy2T4DlCWj+luNm9G+/33aI8de/rptm3bt2cBd84ff8TEXLjQqBEe9emDdvRotJ07336QW09isWDNuFOI4ODx48PDAwICA9eu5TvgjlRYgDNnEhLi47/7LiOjoKCg4I03XFzkcud5vv7+G+3kyRjoU6dq2nEUZvhwPFq9Gq2bG8vearFg38GEaN8+LKxJk0GDQkN9fHx9d+6suxDfn3IFSErKysrKGj48JubmzeTkDRtcXGQyuZylBnQ8++uvMeCshNY+KETjxnjERkXNmzP/TCZsmrCJ4rju3Vu3btMmMNDVVaFQKjMz68pPZzh9eTcOFz08rl/PysrIWL9eJsM2HpNiOp79zTd1HXgG3jc5GY86dUKbksL6IKmU9UkAAALB1aupqTdvbthQ1346w6kACQlZWRkZ8+cbDCaT0SiVymQSCUtyZefffzEAo0bx/SDoR3ExHvXujRYHrxwHoFLJZDIZQE5OUVFRUe/e2dlFRYWF3brx7fddAuh0BoNe7+aGE6hx43Ai5GxU8/rrfD+AIyhEfDweLVzIPnecX6Sm5ufn5c2axbe/dwmQlpafn58/ZIjBYDabTBKJRMJSEd7J9u34oFev8v0A92fxYrQFBazwKBRYk/PzNRqNpm9frVav1+vZKKvuuUsArVavLy197jmhEGesLMV4WerfcM4RLCCYuxtg06bbDyzEiSEmdgbAecyzz/Ll520BNJrSUp1OLMYS0a6dWCwSYXLPO8nLQ3viBF8OV439+519U1JiMOj19vlEXVOmBggEgYFms9VqtQYH33u0c/582ZLVULh8GS1LHWFfi9LrjUaTqVkzvjy7LQC6o1bj+NlZ6nD+x81Vg+XKzM6+81OBgC1/l00rWpfcFqBiWYTLXzqon7Aae7f/LNc8X57dUQMEAqGwvKSDbJGsoYHZ7AFcXR2/4bj7LxvWNrcFwB2q3Fxcf9fp2JpKWdiUv6EREIDW15d9UnZfITeXL89uC4AbG7m5CoVUKpMlJ7PFrLJ06IBrL2WTk9d/HnnE8RObDVdNlUq5XC7nbz5z1zzAw0OlcnH5+2+z2Wq1WBy/Zeuf/fvz5XDVGDz4rge/tUPn5qZUKpV//cWXZ3cJ4OXl6urqun07wP1y+k6ZwpfDFQVranAwHj3/PPvcYrFarVYArOlFRV5earVaffgwX37eJUBgoKenl9fBg2q1QiGXp6WZTLjlV5b27fEBX3mFL8crBpux46xGIGB9HYCfn7u7h8d338lkEolUajDw5aHT1dDGjX19/f3nzjUYcD393p3yN9+U3bHiH/TnjTfwaMAA9jkr+TKZVCqR4PP5+S1dyre/TgUIC/P19fPbsMHbW61Wq2NjS0uNRoPBcSNGoUB7/Dg+uLc3Xw+C9+/VC4+++459znFYgKxWpVKpBGjdul279u3fflulksvlcv4nluVmU23dOiQkNHToUJsNF+XYDlPZGsE2z//+GwPRpk1dPQDeLyoKjw4eZJ9zHJZ4qTQ4ODgYwGC4fPnyZQCN5ueft21jPwbgnwrvCd+8mZubk/P66+fOJSUlJHz/vUqFW5M4jnZcNWX/mjcP7dq1uIbElgSqDgY8MhKP5s9HO3So/c6sqQkKCgoCsFgKCvLzAWJjhwx55RUAgyEpKSnJYOjR49NPP/100KAOHaKioqJ++63eC8BISsrOzsr63/9iYm7cSE5es4ZtVdp3zO41r8zPR/vzz2jZ6mRMTNnvWXevVKL180PbpQvavn3RDhp0y/3b/uMPGgHk8tDQ0FAAkykrKysLICnpf/8bPx7AYIiLu3YNgOPUarUaoLQ0Nzc3F6B793nz5s176aVHH50wYcKEHTvqvQCMtLT8/Ly8QYNQiO+/N5stFqtVoWBbf2w19f6TfBZw9jshtlrJljyYAPdw/FZfxH6GYrFgAdDrY2IuXQIoKPj00zVrsMQnJwPIZNgUMdFMJq1WqwXQ6bKzs7MBnnxywYIFC158sXPn8ePHj9+1q64EqHJG7aAgLy9v7x07nniiRYvWrVu3Dgjw8PDw2LULN/MBSkqw02YzznvD8gWz8TrrS5wHno1mNJrS0tJSAI4TCoVCgyEyMjAwKGj2bKXyyJE//9yyJT09Ojo6GkAqDQnBq3Mc9mOsb3BxcXEBUKl8fX19AY4cmTNnzpydO8+f//rrr79+6aW6EqDGf5ybmVlYWFDQu3daWl5eXt5bbxUUlJRotX37Yuctk7G+gq3Hs87csaawpoz9BJHNXFUqqVQmy8ry8XFzc3P7+efQUB8fP7/Vq/FX1ikp7O9/+WX06NGj9+27fPmHH3744bnnvLwiIiIi7Dti7PoCAdsh02g0GgCDobi4uBigT59PPvnkkzFjWrceOnTo0C+/bDACOKLR6PWlpWFhhYVarVb7xBMlJQaDwdC5M/5aulkzDIS7O2tS8HcMNhvuRWdlYZN27RoG+ORJT0+1Wq0+ehR/LKDVlnf/AwcmTpw4ccuWs2fXr1+//tVXvb0jIyMjAYRC3PFjQrDj0tKCgoICex/Rv/9XX3311ZgxrVsPGTJkSM0LUef/P4AvDh6cMmXKlE2bTp/+7LPPPhs2zMenRYsWLe4WQiDAY4OhsLCwEECny8nJyQHo12/9+vXrx45t0+bll19+ef36mvKryn1AQ6N37xUrVqx4441Ond555513Nm/OzY2NjY0FsFpxqYU1RayPUCg8PDw87H3E/v0TJkyY8MUXWJOmTq0pv/4zAjBQiGHDunadPHny5G++KShISEhIALBYDAac6bP/t4BCyOUohELh6enpCXDw4KRJkyYtWxYdvXLlypXvv19df/5zAjCefvqDDz74YNSoxx6bOXPmzE8/tQuBozjHGiGT4fzBzS0sLCwM4OjR+fPnz1+4EIWYO7eqfvxn+oDyOHZs0aJFi9asOXHio48++uh///PwaNy4cWMAsVihUCjsEz0mjNms0+l0AFotTvi6dZs+ffr0BQsef3zmzJkz2Qy9fEgAB44f/+CDDz745JO//lq8ePHiCRNYiZdKVSqV6m4hLBa9Xq8HKCq6cePGDYCHHho9evToTz559tmVK1eunDixvPuRAE44ffrzzz///P33Dx2aNm3atIUL3dxCQkJC7BO4u4XAPsQuxKhRo0atWYNCTJjg7D7/2T6gPDp1evvtt99etKhXr+XLly+fO1ejSU9PTwcwmbDpsfcRKIRYjEswHh5YY86eXbdu3brx42NitmzZsmXcOGf3IQHKoWPHcePGjVu0qGfPjz/++ON584qKkpOTk+0zZzZvYPMIkQiFYE3W1avbt2/fPn68s+uTABWkY8exY8eOXbiwX78vvvjii8mT2QTNYMCZM5vQsRm91YpbnyhIaSnf/j9wXL68devWrWPGLF3q6enpyXFLlqhUKpXdss9TUo4ePXqULaPfDXXC1eTmzejo6OjevS9c2LBhw4a33mKfd+gwYsSIEV9+GRzcpUuXLvadOoIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgiEpQY++Mi41NTb15s2lTtVqhUKmaNJHLpVKJRKGwWKxWi8VkSkzMysrKSklxcVEo5PLk5HbtwsKaNGmo6XFrjioLcP16RkZ6upubTmc0Go29emFChiefxKxKERESiVgsFstkVqvVarWazRqNXq/XJyS4u6tUSuWpU5hIeffujh2bNYuIqH52pYZKhQWIjU1PT00VCjEnzDvvZGTk5+fnT55ss3EcQFgYy76K+S/uTBCNSXMwI4Y9FQl+mp6O53z5ZUiIt7ePz8cfR0QEBgYH85dasK4pV4Bjx65cuXw5MNBqtdkslp07MUlPp05SqVgsFmMuGJGInc3y8rL0sCw9lVqNAW/bFmXx88NUJQBmMyaGwyYrNrZRIw8PL6/hwyMjg4KCg0+f5jtAtY1TAS5cSE5OSvL1xaQ8hw5hyW7bFnO3AOA7YmNj8ZW9LGnmzz9jwjYWeDuYgM3DA4/69sX3y06ciLXh4YexCQMQiUQikSg3t1WrkJDQ0MceCwnx8vLxiY/nO1C1hVMB/vzz8uWYmL//1ukMBr2+c2elUiqVy1nGvC++wLMmTcKAV73JQGGWLMGsSrNnY5Iflm725s2OHcPDw8Pbt3d1VSiUygevr7jr3dGJiVlZGRljxxYV6XQlJZ07KxRSqVTKAv/llxjwceOqG3gGXue99zBd1eLFLBGcVqvXl5aGhCQmZmZmZFQ9Q0V953YNKC7W6UpK1OqzZxMTr19PSMDMeL6+mKIwPr5HjzZt2rWLiKhth44ciYm5cOHwYcw79vTT+KnF0rFjeHjz5k2aeHmp1a6uqal8B66mEGZmFhbm54tE2NY/95zBYDZbLL6+OIxkeb2WL68rh7CTnjdPKsXUhEaj2Ww2i8WFhSUlJSUvvsh3wGoaIY7bGzfW681ms/mpp3Dczr5mbS5LwllXREfjqCk2ViQSi0UigLw8rba4uHt3vgNW0wix7W3cGHM0NmtWNmHzhQvYRms0deUQ3o/NIi5fZikPjUaz2WIJDT17NiEhPt4+8G3oCPEBVSqRSCAQCuXysl8XFPDrXk5O2cTRmIsS4AESwGKx2TjOaLRaOc5mY+lkGSytLF94epY9tlhwjm1vJBs6QoPBZDKZkpI4zmbjuOTksk1Qhw44Tlep6tox9KFNG6sVlzikUpFILMZ5QUTEAyQAhjslRamUy+XykydFIlyrQXx90T77bF05hIK3a4dNTatWFovVarMBeHqq1S4u0dF8B6ymEYaF+fr6+RmNmCZ2504cfhYV4TyAJaWZPbuuHML7zZ9vMplMJpNAgK09x/n7e3h4edV9yvHa5vZMuFEjDw9Pz8JCDw8XF7V61SqDwWw2mVhT8NBDWDLnzastR/7449KlixfHjrXZjEaT6YUXbDaVSqkEaNasbdu2bT//3M1NqVQqr1/nO2A1zV1LEU2a+Pr6+S1d6uHh4qJSXbtWXIyp+jAT9fz5KMTChTXlAF5vzBibzWAwGNatE4sbNfL3BxCJSkv1eptNJDp16u+/ay+jNd84XYzLyCgoyM9v1+7ixRs3kpOPHbNYLBar1c3NxUUuZ4tyAAcO4Goomyn/9ReO4x1HU3Yw4F27YlMzfrzNZjKZTC+/LJUGBQUFAYjFbm6urgCXLvXu3acPx5nNV65cvXrhwkMPzZw5c+aAAV27Tp06dWpaGt+Bq3UBGCkpOTnZ2eHhyck5OVlZu3drtaWlBkPLllKpWCwUAkilYrFEwtruK1dQmGvX8K8zM9F6eWFTFhGB33foYDJhImWOUyqVSgCBQKPRagFSU+fMef99AJMpJubSJQC9HmfCcrlarVbn5HTqNH78+PG9emGqwYsX+Q5grQvAKCjQarVaT8/ExKyszMxZs3C1dMwYvd5kMpnUapFIJBIKcYNGeKthE9xxdbbEwXbOZDKRSCw2mcLCWrVq1WrNmuzszz77/PO4uJMnp0yZOvWrr9RqTDnu4uLn5+cHkJ8fFxcXByCXe3p6et68+fTTS5YsWfL00y1aDBw4cGBCAt+BrHUBHElKysrKzGzWzGCwWMzmZ58tKSkt1esff1yvN5tNpqZN8SyFAq3RiFuSN296e7u5ubqePKlUSiQSyW+/BQV5e/v6XrnCrrtz5+DBQ4YMHJia+u+/58/v3Mk2N11dsYnKz4+Pj48HUCp9fHx8ioqefHL+/Pnz+/Rp2fLFF1988e+/+Q5onQngDFyrEYttNgAANqew2Tp2bNaseXOLpaLXOXBg0qRJkwYPjovbvXv37p9+wuylQiETIjf3ypUrVwDU6sDAwMCcnK5dp0+fPv2ZZ9q1e+211167dInvwFaUep/K8NChGTNmzOjT5+rVHTt27Ni3z2azWCwWgcDDIzQ0NBQgLw9TkWMfodU+/PC4cePGDRzYpcu777777h9/8O1/edT7bKo9ey5dunTp/v1t277++uuvv/CCSCSRSCQmE0uc7OUVHh4eDmAwFBcXF6vV586tX79+/a5dJ0+uXLlyZefOfPtfHvW+Bjhy4sTSpUuX9uhx/vxXX3311f79ZrNer9fLZJ6ezZo1awZQXIzCYBpZna5Jk549e/Z8+eW+fdeuXbv211/59t+Rel8DHHnssRkzZsz488+OHcePHz++f3+ZzNXV1bWkpKAgMTExEcDNDZsmq9VgMBhUqmvXfvnll1927jxzZt26deu6dePbf0canAAMbOMPHerWbfr06dOffhozWGs0ubmxsbGxAJ6ezZs3bw6AA2CJ5OLFTZs2bdq4kW+/HWmwAjA6dIiKioo6ffrxx2fPnj17wAC12t/f37+wMD393Llz5wBKSoqKiooAJBKlUqnU6fj294EnPv633377LSJi8+Z+/fr1279/8+b+/fv337//xo3jx48fDw/n2z+CIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiC4J11665ePXbskUdiYgoKMjLUar79+c9w8mR2dnJyWBjAokU9e3Kcp+cXX4waFRt74UJ+flqaqyvf/jnS4F5d7IzERK02L08qbdly48bJkxMSjEazWa8PDgYwm41GAIXCxcXTMzl5+/Z+/SZP7t+/b9/Q0LZt7a/N54sG/+JWxoABv/yyfPmhQ0ZjSUl+fnAwgFrt7Q0A4OkZGAig1xuNOl3jxn37bt06f/6FC3Pm/PPPrl0jR/Ltd4MX4Kmnfvll2bIvvrhyJTn5/PknngDw8goOBgDATB126+aGWdF0usJCsXj79qSks2dHjODb/wYrwIQJJ0/+9NO77x45cuXKn3+OGQPg4xMSAsAybtzxiLdy3ufm3rwJ0KhRcHDr1gkJZ84MGjRnTs+efD9HgxPgq6/i4k6c6Nnz00+PHPnmm9Wr7SWbBZpleGLHGk1uLoBIJJe7uBgMR4++9NL773fvrlZLpQpFaSnfz9NgBNiz58aNmJimTUeP3rt3xYoDBwBcXTHwEgnmgGUlXyDAJEJ6vVYLAGAy6fUA+/a99NL77z/1VPPmbm6+vhkZfD8PQ8y3A+WRkqLV5udLJC1afP/91KnHjwOwECuVOKhkbTxLQmqxYBaz4uLsbIBPPx04cNasUaOefTYoqGXLU6f4fh5H6n1e3q1bw8MNhj//LCwsLMzMbN0awMMjIADAHnhHcnNTUgDeeqt79zfeWLFi8eJOnV54YelSvp/DGfW2CerVa8+e5cvXr8/IyMpKSHjiCeeBt3eyKSkA3bu3afP007/99uWX3bu/8cbUqXw/R3k4FWDDhri4kycffbSuHRo37vjxzZsnTvz99/Pn9+176y0AL6/AQADWtd7h+q3A5+enpgKEhDRqFBkZH3/s2MCBs2b17VvXfleVuwTYsiUx8cyZbt2ion788b33Tp2KjNy0acqU33+vbUdWrbp8+ciR3r3XrYuO/umnVasAfHxCQwHsneq9RzcCgVzu4mI0Hj8+ePC8ed278x3QynJbgFOncnKSkxs1eu21nTs//PDQIQAPD39/gLi49PTY2J49g4K+/XbChNOno6Ozs5OSsDGoCfC+TZtOmvTrr6tWHTiAGcEAAKRSZ6MbjQaALTEcPDh48Lx5PXqEhanVXl5ZWXwHtLII4+OLirKyFIqBA/fsWbbs6FF8ZIUCQKXy8AAA8PYODQVIS8vPT03t2LFr182bp0+/cGHLlvj4U6ceeaSqN46PLy7OzpbJevXavn3RomPHAMRiqRQAQKVydwcAsNkwG5/j6KaoKDsbYPXqvn0nTRoxolevwMAWLerf6KbCAnTsuGPH4sWHD2dlpaZevRoebm9zHafy7u5+fgCYWdjX97XX9uxZtuzMmfff/+efnTtfeaWyNx4wYO/eVav++EOrLSrKzAwMtE+oHDtZVgPy8m7cABg37skn33xz2bKJE9u0eeqpDRv4DmB1ES5Z0qnTCy9s3IijDJsNIC8Ps/XaZ5YIK5EuLl5eAAAymVIJsGjRoUNffPHDD6NG/fHH11+/9155N+zZc8+eFSu++iou7saNCxe6dQPw9sYlBOejmxs3AJ54onXrZ57Zt2/duieeGDZs+nS+A1dT3F6OPnUqOzspqU2b55/fvfujj/bsycnJz09NDQtjTdCdayxl22SrFZuG/Py0NIDHHouIeOyxTZtOnBg8eO7cN99k1582LTp669ZJk5YtO3Lkm29WrgTw9sZFM5Y33rGTzctLTQUIDPTza9Lk2rX09BEjPv00MpLvgNWaAIysLL1eq3Vz69Nn587Fi/fu/fffpKTz5x9/HMDHJywMA4SBt3eOLGMq1pCiosxMgO7dIyMff/znn3v0aNQoImL//vnz//pry5aNGwHkcpUKAEAikcnuvI59dJOTAyAWi8UymV4fFxcV9cknTZs2a+bq6uPDEkQ/OJS7ITN06L59q1d/883PP5879+uvI0bY+wiJBLMFcxwGniVwZmmcdbqiIgAAqxWT2LLOVSSSSO78O1aTDAZcuyktLS4GOHx42LAVKzp3fuaZwMCIiNOn+Q5UbVHuTPjnn/v2nThx5Mjp0596asSIOXMAiopycgAA9PriYoC7VyFZiWZrNS4unp53nmcPPBvdGI0AAMXFubkAa9f27z91alTUgx54RqW3JDdsuHr1+PGhQ6Oi9u1bufKnn+wl2M3N3x8AwGareNpmAIDs7KQkHN1ERX388bp1Tzzx2mszZvAdmLqiynvCR49mZFy71rHjgAG7dn344b59Gk1xcU6Oj499Y4T1CY6wmpCdnZgI0KNH69ZPP713759/vvDCjBkDBvAdkLqm2pvyKSklJQUFfn79+u3YsWTJr79evpyaeunSI4/YO23W1LCagqObsDB//2bNYmNTUqKiVq9u2ZLvQPBFjf8qok+f3bs/+mjbtv37Y2IOH37pJQBfXxQCO1ehUCSSSPT6lJSRIz/7LCwsJMTFxcMDexWiBpk06dixTZs++ADg/fcff5zjAJYs6d2b4/74Iz09Lq7+pxp/YJgx48SJH36YM2fBgnPn9u2bNIlvfwiCIIjb/B/7w7TJ1Po+fAAAAABJRU5ErkJggg==); background-size: 24px 352px; } } .jsgrid .jsgrid-mode-button { width: 24px; height: 24px; } .jsgrid-mode-on-button { opacity: .5; } .jsgrid-cancel-edit-button { background-position: 0 0; width: 16px; height: 16px; } .jsgrid-clear-filter-button { background-position: 0 -40px; width: 16px; height: 16px; } .jsgrid-delete-button { background-position: 0 -80px; width: 16px; height: 16px; } .jsgrid-edit-button { background-position: 0 -120px; width: 16px; height: 16px; } .jsgrid-insert-mode-button { background-position: 0 -160px; width: 24px; height: 24px; } .jsgrid-insert-button { background-position: 0 -208px; width: 16px; height: 16px; } .jsgrid-search-mode-button { background-position: 0 -248px; width: 24px; height: 24px; } .jsgrid-search-button { background-position: 0 -296px; width: 16px; height: 16px; } .jsgrid-update-button { background-position: 0 -336px; width: 16px; height: 16px; } .jsgrid-load-shader { background: #ddd; opacity: .5; filter: alpha(opacity=50); } .jsgrid-load-panel { width: 15em; height: 5em; background: #fff; border: 1px solid #e9e9e9; padding-top: 3em; text-align: center; } .jsgrid-load-panel:before { content: ' '; position: absolute; top: .5em; left: 50%; margin-left: -1em; width: 2em; height: 2em; border: 2px solid #009a67; border-right-color: transparent; border-radius: 50%; -webkit-animation: indicator 1s linear infinite; animation: indicator 1s linear infinite; } @-webkit-keyframes indicator { from { -webkit-transform: rotate(0deg); } 50% { -webkit-transform: rotate(180deg); } to { -webkit-transform: rotate(360deg); } } @keyframes indicator { from { transform: rotate(0deg); } 50% { transform: rotate(180deg); } to { transform: rotate(360deg); } } /* old IE */ .jsgrid-load-panel { padding-top: 1.5em\9; } .jsgrid-load-panel:before { display: none\9; }
281677160/openwrt-package
1,758
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_rbuf.h
/* * Copyright (C) AlexWoo(Wu Jie) [email protected] */ #ifndef _NGX_RBUF_H_INCLUDED_ #define _NGX_RBUF_H_INCLUDED_ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> ngx_chain_t *ngx_get_chainbuf_debug(size_t size, ngx_flag_t alloc_rbuf, char *file, int line); void ngx_put_chainbuf_debug(ngx_chain_t *cl, char *file, int len); /* * paras: * size: buffer size for allocate * alloc_rbuf: whether alloc rbuf * return: * nginx chain */ #define ngx_get_chainbuf(size, alloc_rbuf) \ ngx_get_chainbuf_debug(size, alloc_rbuf, __FILE__, __LINE__); /* * paras: * cl: nginx chain return by ngx_rtmp_shared_get_chainbuf */ #define ngx_put_chainbuf(cl) \ ngx_put_chainbuf_debug(cl, __FILE__, __LINE__); /* * paras: * cl: nginx chain return by ngx_rtmp_shared_get_chainbuf */ #define ngx_put_chainbufs(cl) \ { \ ngx_chain_t *l; \ \ l = cl; \ while (l) { \ cl = l->next; \ ngx_put_chainbuf_debug(l, __FILE__, __LINE__); \ l = cl; \ } \ } /* * paras: * r: http request to query status of rbuf */ ngx_chain_t *ngx_rbuf_state(ngx_http_request_t *r, unsigned detail); #endif
294coder/Efficient-MIF
2,422
utils/loss_landscape/evaluation.py
""" The calculation to be performed at each point (modified model), evaluating the loss value, accuracy and eigen values of the hessian matrix """ import torch import torch.nn as nn import torch.nn.functional as F import time from torch.autograd.variable import Variable def eval_loss(net, criterion, loader, use_cuda=False): """ Evaluate the loss value for a given 'net' on the dataset provided by the loader. Args: net: the neural net model criterion: loss function loader: dataloader use_cuda: use cuda or not Returns: loss value and accuracy """ correct = 0 total_loss = 0 total = 0 # number of samples num_batch = len(loader) if use_cuda: net.cuda() net.eval() with torch.no_grad(): if isinstance(criterion, nn.CrossEntropyLoss): for batch_idx, (inputs, targets) in enumerate(loader): batch_size = inputs.size(0) total += batch_size inputs = Variable(inputs) targets = Variable(targets) if use_cuda: inputs, targets = inputs.cuda(), targets.cuda() outputs = net(inputs) loss = criterion(outputs, targets) total_loss += loss.item()*batch_size _, predicted = torch.max(outputs.data, 1) correct += predicted.eq(targets).sum().item() elif isinstance(criterion, nn.MSELoss): for batch_idx, (inputs, targets) in enumerate(loader): batch_size = inputs.size(0) total += batch_size inputs = Variable(inputs) one_hot_targets = torch.FloatTensor(batch_size, 10).zero_() one_hot_targets = one_hot_targets.scatter_(1, targets.view(batch_size, 1), 1.0) one_hot_targets = one_hot_targets.float() one_hot_targets = Variable(one_hot_targets) if use_cuda: inputs, one_hot_targets = inputs.cuda(), one_hot_targets.cuda() outputs = F.softmax(net(inputs)) loss = criterion(outputs, one_hot_targets) total_loss += loss.item()*batch_size _, predicted = torch.max(outputs.data, 1) correct += predicted.cpu().eq(targets).sum().item() return total_loss/total, 100.*correct/total
29jitender/Spotlight
43,928
Spotlight-library/src/main/java/com/wooplr/spotlight/SpotlightView.java
package com.wooplr.spotlight; import android.animation.Animator; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PathEffect; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffXfermode; import android.graphics.Typeface; import android.graphics.drawable.AnimatedVectorDrawable; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.support.annotation.Nullable; import android.support.graphics.drawable.AnimatedVectorDrawableCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.AppCompatImageView; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewAnimationUtils; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.TextView; import com.wooplr.spotlight.prefs.PreferencesManager; import com.wooplr.spotlight.shape.Circle; import com.wooplr.spotlight.shape.NormalLineAnimDrawable; import com.wooplr.spotlight.target.AnimPoint; import com.wooplr.spotlight.target.Target; import com.wooplr.spotlight.target.ViewTarget; import com.wooplr.spotlight.utils.SpotlightListener; import com.wooplr.spotlight.utils.Utils; import java.util.ArrayList; import java.util.List; /** * Created by jitender on 10/06/16. */ public class SpotlightView extends FrameLayout { /** * OverLay color */ private int maskColor = 0x70000000; /** * Intro Animation Duration */ private long introAnimationDuration = 400; /** * Toggel between reveal and fadein animation */ private boolean isRevealAnimationEnabled = true; /** * Final fadein text duration */ private long fadingTextDuration = 400; /** * Start intro once view is ready to show */ private boolean isReady; /** * Overlay circle above the view */ private Circle circleShape; /** * Target View */ private Target targetView; /** * Eraser to erase the circle area */ private Paint eraser; /** * Delay the intro view */ private Handler handler; private Bitmap bitmap; private Canvas canvas; /** * Padding for circle */ private int padding = 20; /** * View Width */ private int width; /** * View Height */ private int height; /** * Dismiss layout on touch */ private boolean dismissOnTouch; private boolean dismissOnBackPress; private boolean enableDismissAfterShown; private PreferencesManager preferencesManager; private String usageId; /** * Listener for spotLight when user clicks on the view */ private SpotlightListener listener; /** * Perform click when user clicks on the targetView */ private boolean isPerformClick; /** * Margin from left, right, top and bottom till the line will stop */ private int gutter = Utils.dpToPx(36); /** * Views Heading and sub-heading for spotlight */ private TextView subHeadingTv, headingTv; /** * Whether to show the arc at the end of the line that points to the target. */ private boolean showTargetArc = true; /** * Extra padding around the arc */ private int extraPaddingForArc = 24; /** * Defaults for heading TextView */ private int headingTvSize = 24; private int headingTvSizeDimenUnit = -1; private int headingTvColor = Color.parseColor("#eb273f"); private CharSequence headingTvText = "Hello"; /** * Defaults for sub-heading TextView */ private int subHeadingTvSize = 24; private int subHeadingTvSizeDimenUnit = -1; private int subHeadingTvColor = Color.parseColor("#ffffff"); private CharSequence subHeadingTvText = "Hello"; /** * Values for line animation */ private long lineAnimationDuration = 300; private int lineStroke; private PathEffect lineEffect; private int lineAndArcColor = Color.parseColor("#eb273f"); private Typeface mTypeface = null; private int softwareBtnHeight; private boolean dismissCalled = false; public SpotlightView(Context context) { super(context); init(context); } public SpotlightView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public SpotlightView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public SpotlightView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context); } private void init(Context context) { setWillNotDraw(false); setVisibility(INVISIBLE); lineStroke = Utils.dpToPx(4); isReady = false; isRevealAnimationEnabled = true; dismissOnTouch = false; isPerformClick = false; enableDismissAfterShown = false; dismissOnBackPress = false; handler = new Handler(); preferencesManager = new PreferencesManager(context); eraser = new Paint(); eraser.setColor(0xFFFFFFFF); eraser.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); eraser.setFlags(Paint.ANTI_ALIAS_FLAG); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); width = getMeasuredWidth(); height = getMeasuredHeight(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); try{ if (!isReady) return; if (bitmap == null || canvas == null) { if (bitmap != null) bitmap.recycle(); bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); this.canvas = new Canvas(bitmap); } this.canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); this.canvas.drawColor(maskColor); circleShape.draw(this.canvas, eraser, padding); canvas.drawBitmap(bitmap, 0, 0, null); }catch(Exception e){ e.printStackTrace(); } } @Override public boolean onTouchEvent(MotionEvent event) { float xT = event.getX(); float yT = event.getY(); int xV = circleShape.getPoint().x; int yV = circleShape.getPoint().y; int radius = circleShape.getRadius(); double dx = Math.pow(xT - xV, 2); double dy = Math.pow(yT - yV, 2); boolean isTouchOnFocus = (dx + dy) <= Math.pow(radius, 2); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (isTouchOnFocus && isPerformClick) { targetView.getView().setPressed(true); targetView.getView().invalidate(); } return true; case MotionEvent.ACTION_UP: if (isTouchOnFocus || dismissOnTouch) dismiss(); if (isTouchOnFocus && isPerformClick) { targetView.getView().performClick(); targetView.getView().setPressed(true); targetView.getView().invalidate(); targetView.getView().setPressed(false); targetView.getView().invalidate(); } return true; default: break; } return super.onTouchEvent(event); } /** * Show the view based on the configuration * Reveal is available only for Lollipop and above in other only fadein will work * To support reveal in older versions use github.com/ozodrukh/CircularReveal * * @param activity */ private void show(final Activity activity) { if (preferencesManager.isDisplayed(usageId)) return; ((ViewGroup) activity.getWindow().getDecorView()).addView(this); setReady(true); handler.postDelayed(new Runnable() { @Override public void run() { try{ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (isRevealAnimationEnabled) startRevealAnimation(activity); else { startFadinAnimation(activity); } } else { startFadinAnimation(activity); } }catch(Exception e){ e.printStackTrace(); } } } , 100); } /** * Dissmiss view with reverse animation */ private void dismiss() { if (dismissCalled) { return; } dismissCalled = true; preferencesManager.setDisplayed(usageId); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (isRevealAnimationEnabled) exitRevealAnimation(); else startFadeout(); } else { startFadeout(); } } /** * Revel animation from target center to screen width and height * * @param activity */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void startRevealAnimation(final Activity activity) { float finalRadius = (float) Math.hypot(getViewWidth(), getHeight()); Animator anim = ViewAnimationUtils.createCircularReveal(this, targetView.getPoint().x, targetView.getPoint().y, 0, finalRadius); anim.setInterpolator(AnimationUtils.loadInterpolator(activity, android.R.interpolator.fast_out_linear_in)); anim.setDuration(introAnimationDuration); anim.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { if (showTargetArc) { addArcAnimation(activity); } else { addPathAnimation(activity); } } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); setVisibility(View.VISIBLE); if (dismissOnBackPress) { requestFocus(); } anim.start(); } /** * Reverse reveal animation */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void exitRevealAnimation() { float finalRadius = (float) Math.hypot(getViewWidth(), getHeight()); Animator anim = ViewAnimationUtils.createCircularReveal(this, targetView.getPoint().x, targetView.getPoint().y, finalRadius, 0); anim.setInterpolator(AnimationUtils.loadInterpolator(getContext(), android.R.interpolator.accelerate_decelerate)); anim.setDuration(introAnimationDuration); anim.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { setVisibility(GONE); removeSpotlightView(); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); anim.start(); } private void startFadinAnimation(final Activity activity) { AlphaAnimation fadeIn = new AlphaAnimation(0.0f, 1.0f); fadeIn.setDuration(introAnimationDuration); fadeIn.setFillAfter(true); fadeIn.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (showTargetArc) { addArcAnimation(activity); } else { addPathAnimation(activity); } } @Override public void onAnimationRepeat(Animation animation) { } }); setVisibility(VISIBLE); if (dismissOnBackPress) { requestFocus(); } startAnimation(fadeIn); } private void startFadeout() { AlphaAnimation fadeIn = new AlphaAnimation(1.0f, 0.0f); fadeIn.setDuration(introAnimationDuration); fadeIn.setFillAfter(true); fadeIn.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { setVisibility(GONE); removeSpotlightView(); } @Override public void onAnimationRepeat(Animation animation) { } }); startAnimation(fadeIn); } /** * Add arc above/below the circular target overlay. */ private void addArcAnimation(final Activity activity) { AppCompatImageView mImageView = new AppCompatImageView(activity); mImageView.setImageResource(R.drawable.ic_spotlight_arc); LayoutParams params = new LayoutParams(2 * (circleShape.getRadius() + extraPaddingForArc), 2 * (circleShape.getRadius() + extraPaddingForArc)); if (targetView.getPoint().y > getHeight() / 2) {//bottom if (targetView.getPoint().x > getWidth() / 2) {//Right params.rightMargin = getWidth() - targetView.getPoint().x - circleShape.getRadius() - extraPaddingForArc; params.bottomMargin = getHeight() - targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc; params.gravity = Gravity.RIGHT | Gravity.BOTTOM; } else { params.leftMargin = targetView.getPoint().x - circleShape.getRadius() - extraPaddingForArc; params.bottomMargin = getHeight() - targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc; params.gravity = Gravity.LEFT | Gravity.BOTTOM; } } else {//up mImageView.setRotation(180); //Reverse the view if (targetView.getPoint().x > getWidth() / 2) {//Right params.rightMargin = getWidth() - targetView.getPoint().x - circleShape.getRadius() - extraPaddingForArc; params.bottomMargin = getHeight() - targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc; params.gravity = Gravity.RIGHT | Gravity.BOTTOM; } else { params.leftMargin = targetView.getPoint().x - circleShape.getRadius() - extraPaddingForArc; params.bottomMargin = getHeight() - targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc; params.gravity = Gravity.LEFT | Gravity.BOTTOM; } } mImageView.postInvalidate(); mImageView.setLayoutParams(params); addView(mImageView); PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(lineAndArcColor, PorterDuff.Mode.SRC_ATOP); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { AnimatedVectorDrawable avd = (AnimatedVectorDrawable) ContextCompat.getDrawable(activity, R.drawable.avd_spotlight_arc); avd.setColorFilter(porterDuffColorFilter); mImageView.setImageDrawable(avd); avd.start(); } else { AnimatedVectorDrawableCompat avdc = AnimatedVectorDrawableCompat.create(activity, R.drawable.avd_spotlight_arc); avdc.setColorFilter(porterDuffColorFilter); mImageView.setImageDrawable(avdc); avdc.start(); } new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { addPathAnimation(activity); } }, 400); } private void addPathAnimation(Activity activity) { View mView = new View(activity); LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.width = getViewWidth(); params.height = getViewHeight(); // params.width = getMeasuredWidth(); // params.height = getMeasuredHeight(); addView(mView, params); //Textviews headingTv = new TextView(activity); if (mTypeface != null) headingTv.setTypeface(mTypeface); if(headingTvSizeDimenUnit != -1) headingTv.setTextSize(headingTvSizeDimenUnit,headingTvSize); else headingTv.setTextSize(headingTvSize); headingTv.setVisibility(View.GONE); headingTv.setTextColor(headingTvColor); headingTv.setText(headingTvText); subHeadingTv = new TextView(activity); if (mTypeface != null) subHeadingTv.setTypeface(mTypeface); if(subHeadingTvSizeDimenUnit != -1) subHeadingTv.setTextSize(subHeadingTvSizeDimenUnit,subHeadingTvSize); else subHeadingTv.setTextSize(subHeadingTvSize); subHeadingTv.setTextColor(subHeadingTvColor); subHeadingTv.setVisibility(View.GONE); subHeadingTv.setText(subHeadingTvText); //Line animation Paint p = new Paint(); p.setAntiAlias(true); p.setDither(true); p.setStyle(Paint.Style.STROKE); p.setStrokeJoin(Paint.Join.ROUND); p.setStrokeCap(Paint.Cap.ROUND); p.setStrokeWidth(lineStroke); p.setColor(lineAndArcColor); p.setPathEffect(lineEffect); NormalLineAnimDrawable animDrawable1 = new NormalLineAnimDrawable(p); if (lineAnimationDuration > 0) animDrawable1.setLineAnimDuration(lineAnimationDuration); if (Build.VERSION.SDK_INT < 16) { mView.setBackgroundDrawable(animDrawable1); } else { mView.setBackground(animDrawable1); } animDrawable1.setPoints(checkLinePoint()); animDrawable1.playAnim(); animDrawable1.setmListner(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { AlphaAnimation fadeIn = new AlphaAnimation(0.0f, 1.0f); fadeIn.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if(enableDismissAfterShown) dismissOnTouch = true; } @Override public void onAnimationRepeat(Animation animation) { } }); fadeIn.setDuration(fadingTextDuration); fadeIn.setFillAfter(true); headingTv.startAnimation(fadeIn); subHeadingTv.startAnimation(fadeIn); headingTv.setVisibility(View.VISIBLE); subHeadingTv.setVisibility(View.VISIBLE); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); } private void enableDismissOnBackPress() { setFocusableInTouchMode(true); setFocusable(true); requestFocus(); } private List<AnimPoint> checkLinePoint() { //Screen Height int screenWidth = getWidth(); int screenHeight = getHeight(); List<AnimPoint> animPoints = new ArrayList<>(); //For TextViews LayoutParams headingParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); LayoutParams subHeadingParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); //Spaces above and below the line int spaceAboveLine = Utils.dpToPx(8); int spaceBelowLine = Utils.dpToPx(12); int extramargin = Utils.dpToPx(16); //check up or down if (targetView.getPoint().y > screenHeight / 2) {//Down TODO: add a logic for by 2 if (targetView.getPoint().x > screenWidth / 2) {//Right animPoints.add(new AnimPoint((targetView.getViewRight() - targetView.getViewWidth() / 2), targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc, (targetView.getViewRight() - targetView.getViewWidth() / 2), targetView.getViewTop() / 2 )); animPoints.add(new AnimPoint((targetView.getViewRight() - targetView.getViewWidth() / 2), targetView.getViewTop() / 2, gutter, targetView.getViewTop() / 2)); //TextViews headingParams.leftMargin = gutter; headingParams.rightMargin = screenWidth - (targetView.getViewRight() - targetView.getViewWidth() / 2) + extramargin; headingParams.bottomMargin = screenHeight - targetView.getViewTop() / 2 + spaceAboveLine; headingParams.topMargin = extramargin; headingParams.gravity = Gravity.BOTTOM | Gravity.LEFT; headingTv.setGravity(Gravity.LEFT); subHeadingParams.rightMargin = screenWidth - (targetView.getViewRight() - targetView.getViewWidth() / 2) + extramargin; subHeadingParams.leftMargin = gutter; subHeadingParams.bottomMargin = extramargin; subHeadingParams.topMargin = targetView.getViewTop() / 2 + spaceBelowLine; subHeadingParams.gravity = Gravity.LEFT; subHeadingTv.setGravity(Gravity.LEFT); } else {//left animPoints.add(new AnimPoint((targetView.getViewRight() - targetView.getViewWidth() / 2), targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc, (targetView.getViewRight() - targetView.getViewWidth() / 2), targetView.getViewTop() / 2 )); animPoints.add(new AnimPoint((targetView.getViewRight() - targetView.getViewWidth() / 2), targetView.getViewTop() / 2, screenWidth - ((screenHeight > screenWidth) ? gutter : (gutter + softwareBtnHeight)), targetView.getViewTop() / 2)); //TextViews if(screenHeight > screenWidth) headingParams.rightMargin = gutter;//portrait else headingParams.rightMargin = gutter + softwareBtnHeight;//landscape headingParams.leftMargin = (targetView.getViewRight() - targetView.getViewWidth() / 2) + extramargin; headingParams.bottomMargin = screenHeight - targetView.getViewTop() / 2 + spaceAboveLine; headingParams.topMargin = extramargin; headingParams.gravity = Gravity.BOTTOM | Gravity.RIGHT; headingTv.setGravity(Gravity.LEFT); if(screenHeight > screenWidth) subHeadingParams.rightMargin = gutter;//portrait else subHeadingParams.rightMargin = gutter + softwareBtnHeight;//landscape subHeadingParams.leftMargin = (targetView.getViewRight() - targetView.getViewWidth() / 2) + extramargin; subHeadingParams.topMargin = targetView.getViewTop() / 2 + spaceBelowLine; subHeadingParams.bottomMargin = extramargin; subHeadingParams.gravity = Gravity.RIGHT; subHeadingTv.setGravity(Gravity.LEFT); } } else {//top if (targetView.getPoint().x > screenWidth / 2) {//Right animPoints.add(new AnimPoint(targetView.getViewRight() - targetView.getViewWidth() / 2, targetView.getPoint().y + circleShape.getRadius() + extraPaddingForArc, targetView.getViewRight() - targetView.getViewWidth() / 2, (screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom())); animPoints.add(new AnimPoint(targetView.getViewRight() - targetView.getViewWidth() / 2, (screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom(), gutter, (screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom())); // //TextViews headingParams.leftMargin = gutter; headingParams.rightMargin = screenWidth - (targetView.getViewRight() - targetView.getViewWidth() / 2) + extramargin; headingParams.bottomMargin = screenHeight - ((screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()) + spaceAboveLine; headingParams.topMargin = extramargin; headingParams.gravity = Gravity.BOTTOM | Gravity.LEFT; headingTv.setGravity(Gravity.LEFT); subHeadingParams.leftMargin = gutter; subHeadingParams.rightMargin = screenWidth - targetView.getViewRight() + targetView.getViewWidth() / 2 + extramargin; subHeadingParams.bottomMargin = extramargin; subHeadingParams.topMargin = ((screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()) + spaceBelowLine; subHeadingParams.gravity = Gravity.LEFT; subHeadingTv.setGravity(Gravity.LEFT); } else {//left animPoints.add(new AnimPoint(targetView.getViewRight() - targetView.getViewWidth() / 2, targetView.getPoint().y + circleShape.getRadius() + extraPaddingForArc, targetView.getViewRight() - targetView.getViewWidth() / 2, (screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom())); animPoints.add(new AnimPoint(targetView.getViewRight() - targetView.getViewWidth() / 2, (screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom(), screenWidth - ((screenHeight > screenWidth) ? gutter : (gutter + softwareBtnHeight)), (screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom())); // //TextViews if(screenHeight > screenWidth) headingParams.rightMargin = gutter;//portrait else headingParams.rightMargin = gutter + softwareBtnHeight;//landscape headingParams.leftMargin = targetView.getViewRight() - targetView.getViewWidth() / 2 + extramargin; headingParams.bottomMargin = screenHeight - ((screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()) + spaceAboveLine; headingParams.topMargin = extramargin; headingParams.gravity = Gravity.BOTTOM | Gravity.RIGHT; headingTv.setGravity(Gravity.LEFT); if(screenHeight > screenWidth) subHeadingParams.rightMargin = gutter;//portrait else subHeadingParams.rightMargin = gutter + softwareBtnHeight;//landscape subHeadingParams.leftMargin = targetView.getViewRight() - targetView.getViewWidth() / 2 + extramargin; subHeadingParams.bottomMargin = extramargin; subHeadingParams.topMargin = ((screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()) + spaceBelowLine; subHeadingParams.gravity = Gravity.RIGHT; subHeadingTv.setGravity(Gravity.LEFT); } } addView(headingTv, headingParams); addView(subHeadingTv, subHeadingParams); return animPoints; } /** * Remove the spotlight view */ private void removeSpotlightView() { if (listener != null) listener.onUserClicked(usageId); if (getParent() != null) ((ViewGroup) getParent()).removeView(this); } /** * Remove the spotlight view * @param needOnUserClickedCallback true, if user wants a call back when this spotlight view is removed from parent. */ public void removeSpotlightView(boolean needOnUserClickedCallback) { try{ if(needOnUserClickedCallback && listener != null) listener.onUserClicked(usageId); if (getParent() != null) ((ViewGroup) getParent()).removeView(this); }catch(Exception e){ e.printStackTrace(); } } /** * Setters */ public void setListener(SpotlightListener listener) { this.listener = listener; } private void setMaskColor(int maskColor) { this.maskColor = maskColor; } public void setReady(boolean ready) { isReady = ready; } public void setPadding(int padding) { this.padding = padding; } public void setDismissOnTouch(boolean dismissOnTouch) { this.dismissOnTouch = dismissOnTouch; } public void setDismissOnBackPress(boolean dismissOnBackPress) { this.dismissOnBackPress = dismissOnBackPress; } public boolean isEnableDismissAfterShown() { return enableDismissAfterShown; } public void setEnableDismissAfterShown(boolean enableDismissAfterShown) { this.enableDismissAfterShown = enableDismissAfterShown; } public void setPerformClick(boolean performClick) { isPerformClick = performClick; } public void setExtraPaddingForArc(int extraPaddingForArc) { this.extraPaddingForArc = extraPaddingForArc; } /** * Whether to show the arc under/above the circular target overlay. * * @param show Set to true to show the arc line, false otherwise. */ public void setShowTargetArc(boolean show) { this.showTargetArc = show; } public void setIntroAnimationDuration(long introAnimationDuration) { this.introAnimationDuration = introAnimationDuration; } public void setRevealAnimationEnabled(boolean revealAnimationEnabled) { isRevealAnimationEnabled = revealAnimationEnabled; } public void setFadingTextDuration(long fadingTextDuration) { this.fadingTextDuration = fadingTextDuration; } public void setCircleShape(Circle circleShape) { this.circleShape = circleShape; } public void setTargetView(Target targetView) { this.targetView = targetView; } public void setUsageId(String usageId) { this.usageId = usageId; } public void setHeadingTvSize(int headingTvSize) { this.headingTvSize = headingTvSize; } public void setHeadingTvSize(int dimenUnit,int headingTvSize) { this.headingTvSizeDimenUnit = dimenUnit; this.headingTvSize = headingTvSize; } public void setHeadingTvColor(int headingTvColor) { this.headingTvColor = headingTvColor; } public void setHeadingTvText(CharSequence headingTvText) { this.headingTvText = headingTvText; } public void setSubHeadingTvSize(int subHeadingTvSize) { this.subHeadingTvSize = subHeadingTvSize; } public void setSubHeadingTvSize(int dimenUnit, int subHeadingTvSize) { this.subHeadingTvSizeDimenUnit = dimenUnit; this.subHeadingTvSize = subHeadingTvSize; } public void setSubHeadingTvColor(int subHeadingTvColor) { this.subHeadingTvColor = subHeadingTvColor; } public void setSubHeadingTvText(CharSequence subHeadingTvText) { this.subHeadingTvText = subHeadingTvText; } public void setLineAnimationDuration(long lineAnimationDuration) { this.lineAnimationDuration = lineAnimationDuration; } public void setLineAndArcColor(int lineAndArcColor) { this.lineAndArcColor = lineAndArcColor; } public void setLineStroke(int lineStroke) { this.lineStroke = lineStroke; } public void setLineEffect(PathEffect pathEffect) { this.lineEffect = pathEffect; } private void setSoftwareBtnHeight(int px){ this.softwareBtnHeight = px; } public void setTypeface(Typeface typeface) { this.mTypeface = typeface; } public void setConfiguration(SpotlightConfig configuration) { if (configuration != null) { this.maskColor = configuration.getMaskColor(); this.introAnimationDuration = configuration.getIntroAnimationDuration(); this.isRevealAnimationEnabled = configuration.isRevealAnimationEnabled(); this.fadingTextDuration = configuration.getFadingTextDuration(); this.padding = configuration.getPadding(); this.dismissOnTouch = configuration.isDismissOnTouch(); this.dismissOnBackPress = configuration.isDismissOnBackpress(); this.isPerformClick = configuration.isPerformClick(); this.headingTvSize = configuration.getHeadingTvSize(); this.headingTvSizeDimenUnit = configuration.getHeadingTvSizeDimenUnit(); this.headingTvColor = configuration.getHeadingTvColor(); this.headingTvText = configuration.getHeadingTvText(); this.subHeadingTvSize = configuration.getSubHeadingTvSize(); this.subHeadingTvSizeDimenUnit = configuration.getSubHeadingTvSizeDimenUnit(); this.subHeadingTvColor = configuration.getSubHeadingTvColor(); this.subHeadingTvText = configuration.getSubHeadingTvText(); this.lineAnimationDuration = configuration.getLineAnimationDuration(); this.lineStroke = configuration.getLineStroke(); this.lineAndArcColor = configuration.getLineAndArcColor(); } } /** * Builder Class */ public static class Builder { private SpotlightView spotlightView; private Activity activity; public Builder(Activity activity) { this.activity = activity; spotlightView = new SpotlightView(activity); spotlightView.setSoftwareBtnHeight(getSoftButtonsBarHeight(activity)); } public Builder maskColor(int maskColor) { spotlightView.setMaskColor(maskColor); return this; } public Builder introAnimationDuration(long delayMillis) { spotlightView.setIntroAnimationDuration(delayMillis); return this; } public Builder enableRevealAnimation(boolean isFadeAnimationEnabled) { spotlightView.setRevealAnimationEnabled(isFadeAnimationEnabled); return this; } public Builder target(View view) { spotlightView.setTargetView(new ViewTarget(view)); return this; } public Builder targetPadding(int padding) { spotlightView.setPadding(padding); return this; } public Builder dismissOnTouch(boolean dismissOnTouch) { spotlightView.setDismissOnTouch(dismissOnTouch); return this; } public Builder dismissOnBackPress(boolean dismissOnBackPress) { spotlightView.setDismissOnBackPress(dismissOnBackPress); return this; } public Builder usageId(String usageId) { spotlightView.setUsageId(usageId); return this; } public Builder setTypeface(Typeface typeface) { spotlightView.setTypeface(typeface); return this; } public Builder setListener(SpotlightListener spotlightListener) { spotlightView.setListener(spotlightListener); return this; } public Builder performClick(boolean isPerformClick) { spotlightView.setPerformClick(isPerformClick); return this; } public Builder fadeinTextDuration(long fadinTextDuration) { spotlightView.setFadingTextDuration(fadinTextDuration); return this; } public Builder headingTvSize(int headingTvSize) { spotlightView.setHeadingTvSize(headingTvSize); return this; } public Builder headingTvSize(int dimenUnit, int headingTvSize) { spotlightView.setHeadingTvSize(dimenUnit,headingTvSize); return this; } public Builder headingTvColor(int color) { spotlightView.setHeadingTvColor(color); return this; } public Builder headingTvText(CharSequence text) { spotlightView.setHeadingTvText(text); return this; } public Builder subHeadingTvSize(int headingTvSize) { spotlightView.setSubHeadingTvSize(headingTvSize); return this; } public Builder subHeadingTvSize(int dimenUnit, int headingTvSize) { spotlightView.setSubHeadingTvSize(dimenUnit,headingTvSize); return this; } public Builder subHeadingTvColor(int color) { spotlightView.setSubHeadingTvColor(color); return this; } public Builder subHeadingTvText(CharSequence text) { spotlightView.setSubHeadingTvText(text); return this; } public Builder lineAndArcColor(int color) { spotlightView.setLineAndArcColor(color); return this; } public Builder lineAnimDuration(long duration) { spotlightView.setLineAnimationDuration(duration); return this; } public Builder showTargetArc(boolean show) { spotlightView.setShowTargetArc(show); return this; } public Builder enableDismissAfterShown(boolean enable) { if (enable) { spotlightView.setEnableDismissAfterShown(enable); spotlightView.setDismissOnTouch(false); } return this; } public Builder lineStroke(int stroke) { spotlightView.setLineStroke(Utils.dpToPx(stroke)); return this; } public Builder lineEffect(@Nullable PathEffect pathEffect) { spotlightView.setLineEffect(pathEffect); return this; } public Builder setConfiguration(SpotlightConfig configuration) { spotlightView.setConfiguration(configuration); return this; } public SpotlightView build() { Circle circle = new Circle( spotlightView.targetView, spotlightView.padding); spotlightView.setCircleShape(circle); if (spotlightView.dismissOnBackPress) { spotlightView.enableDismissOnBackPress(); } return spotlightView; } public SpotlightView show() { build().show(activity); return spotlightView; } } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (dismissOnBackPress && event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if (event.getAction() == KeyEvent.ACTION_UP) { dismiss(); } return true; } return super.dispatchKeyEvent(event); } public void logger(String s) { Log.d("Spotlight", s); } private int getViewHeight(){ if(getWidth() > getHeight()){ //Landscape return getHeight(); }else{ //Portrait return (getHeight() - softwareBtnHeight); } } private int getViewWidth(){ if(getWidth() > getHeight()){ //Landscape return (getWidth() - softwareBtnHeight); }else{ //Portrait return getWidth(); } } private static int getSoftButtonsBarHeight(Activity activity) { try{ // getRealMetrics is only available with API 17 and + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { DisplayMetrics metrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); if(metrics.heightPixels > metrics.widthPixels) { //Portrait int usableHeight = metrics.heightPixels; activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics); int realHeight = metrics.heightPixels; if (realHeight > usableHeight) return realHeight - usableHeight; else return 0; }else{ //Landscape int usableHeight = metrics.widthPixels; activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics); int realHeight = metrics.widthPixels; if (realHeight > usableHeight) return realHeight - usableHeight; else return 0; } } }catch(Exception e){ e.printStackTrace(); } return 0; } /** * This will remove all usage ids from preferences. */ public void resetAllUsageIds(){ try{ preferencesManager.resetAll(); }catch(Exception e){ e.printStackTrace(); } } /** * This will remove given usage id from preferences. * @param id Spotlight usage id to be removed */ public void resetUsageId(String id){ try{ preferencesManager.reset(id); }catch(Exception e){ e.printStackTrace(); } } }
29jitender/Spotlight
6,004
Spotlight-library/src/main/java/com/wooplr/spotlight/SpotlightConfig.java
package com.wooplr.spotlight; import android.graphics.Color; import android.graphics.Typeface; import com.wooplr.spotlight.utils.Utils; /** * Created by jitender on 14/06/16. */ public class SpotlightConfig { private int maskColor; private long introAnimationDuration; private boolean isRevealAnimationEnabled = true; private long fadingTextDuration; private int padding; private boolean dismissOnTouch; private boolean dismissOnBackpress; private boolean isPerformClick; private int headingTvSize; private int headingTvSizeDimenUnit; private int headingTvColor; private CharSequence headingTvText; private int subHeadingTvSize; private int subHeadingTvSizeDimenUnit; private int subHeadingTvColor; private CharSequence subHeadingTvText; private long lineAnimationDuration; private int lineStroke; private int lineAndArcColor; private boolean showTargetArc; private Typeface typeface; public SpotlightConfig() { this.maskColor = 0x70000000; this.introAnimationDuration = 400; this.isRevealAnimationEnabled = true; this.fadingTextDuration = 400; this.padding = 20; this.dismissOnTouch = true; this.dismissOnBackpress=true; this.isPerformClick = true; this.headingTvSize = 24; this.headingTvSizeDimenUnit = -1; this.headingTvColor = Color.parseColor("#eb273f"); this.headingTvText = "Hello"; this.subHeadingTvSize = 24; this.subHeadingTvSizeDimenUnit = -1; this.subHeadingTvColor = Color.parseColor("#ffffff"); this.subHeadingTvText = "Hello"; this.lineAnimationDuration = 300; this.lineStroke = Utils.dpToPx(4); this.lineAndArcColor = Color.parseColor("#eb273f"); this.showTargetArc = true; } public int getMaskColor() { return maskColor; } public void setMaskColor(int maskColor) { this.maskColor = maskColor; } public long getIntroAnimationDuration() { return introAnimationDuration; } public void setIntroAnimationDuration(long introAnimationDuration) { this.introAnimationDuration = introAnimationDuration; } public boolean isRevealAnimationEnabled() { return isRevealAnimationEnabled; } public void setRevealAnimationEnabled(boolean revealAnimationEnabled) { isRevealAnimationEnabled = revealAnimationEnabled; } public long getFadingTextDuration() { return fadingTextDuration; } public void setFadingTextDuration(long fadingTextDuration) { this.fadingTextDuration = fadingTextDuration; } public int getPadding() { return padding; } public void setPadding(int padding) { this.padding = padding; } public boolean isDismissOnTouch() { return dismissOnTouch; } public void setDismissOnTouch(boolean dismissOnTouch) { this.dismissOnTouch = dismissOnTouch; } public boolean isPerformClick() { return isPerformClick; } public void setPerformClick(boolean performClick) { isPerformClick = performClick; } public int getHeadingTvSize() { return headingTvSize; } public void setHeadingTvSize(int headingTvSize) { this.headingTvSize = headingTvSize; } public void setHeadingTvSize(int dimenUnit, int size) { this.headingTvSizeDimenUnit = dimenUnit; this.headingTvSize = size; } public int getHeadingTvColor() { return headingTvColor; } public void setHeadingTvColor(int headingTvColor) { this.headingTvColor = headingTvColor; } public CharSequence getHeadingTvText() { return headingTvText; } public void setHeadingTvText(CharSequence headingTvText) { this.headingTvText = headingTvText; } public int getSubHeadingTvSize() { return subHeadingTvSize; } public void setSubHeadingTvSize(int subHeadingTvSize) { this.subHeadingTvSize = subHeadingTvSize; } public void setSubHeadingTvSize(int dimenUnit, int size) { this.subHeadingTvSizeDimenUnit = dimenUnit; this.subHeadingTvSize = size; } public int getSubHeadingTvColor() { return subHeadingTvColor; } public void setSubHeadingTvColor(int subHeadingTvColor) { this.subHeadingTvColor = subHeadingTvColor; } public CharSequence getSubHeadingTvText() { return subHeadingTvText; } public void setSubHeadingTvText(CharSequence subHeadingTvText) { this.subHeadingTvText = subHeadingTvText; } public long getLineAnimationDuration() { return lineAnimationDuration; } public void setLineAnimationDuration(long lineAnimationDuration) { this.lineAnimationDuration = lineAnimationDuration; } public int getLineStroke() { return lineStroke; } public void setLineStroke(int lineStroke) { this.lineStroke = lineStroke; } public int getLineAndArcColor() { return lineAndArcColor; } public void setLineAndArcColor(int lineAndArcColor) { this.lineAndArcColor = lineAndArcColor; } public boolean showTargetArc() { return showTargetArc; } public void setShowTargetArc(boolean showTargetArc) { this.showTargetArc = showTargetArc; } public Typeface getTypeface() { return typeface; } public void setTypeface(Typeface mTypeface) { this.typeface = mTypeface; } public boolean isDismissOnBackpress() { return dismissOnBackpress; } public void setDismissOnBackpress(boolean dismissOnBackpress) { this.dismissOnBackpress = dismissOnBackpress; } public int getHeadingTvSizeDimenUnit() { return headingTvSizeDimenUnit; } public int getSubHeadingTvSizeDimenUnit() { return subHeadingTvSizeDimenUnit; } }
281677160/openwrt-package
1,407
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_poold.h
/* * Copyright (C) AlexWoo(Wu Jie) [email protected] */ #ifndef _NGX_POOL_DEBUG_H_INCLUDED_ #define _NGX_POOL_DEBUG_H_INCLUDED_ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #define NGX_CREATE_POOL(size, log) \ ngx_create_pool_debug(size, log, __FILE__, __LINE__) #define NGX_DESTROY_POOL(pool) \ ngx_destroy_pool_debug(pool, __FILE__, __LINE__) /* * create pool and record where to create it for debugging * such as pool not destroy * * paras: * size: pool size for pool creating interface in raw ngx_create_pool * log: log for pool creating interface in raw ngx_create_pool * file: use __FILE__ for recording file * line: use __LINE__ for recording line * return: * pool for successd, NULL for failed */ ngx_pool_t *ngx_create_pool_debug(size_t size, ngx_log_t *log, char *file, int line); /* * destroy pool for debugging, use as pair for ngx_create_pool_debug * * paras: * pool: pool for pool destroying interface in ran ngx_destroy_pool * file: use __FILE__ for recording file * line: use __LINE__ for recording line */ void ngx_destroy_pool_debug(ngx_pool_t *pool, char *file, int line); /* * paras: * r: http request to query status of rbuf */ ngx_chain_t *ngx_poold_state(ngx_http_request_t *r, unsigned detail); #endif
2881099/FreeSql.AdminLTE
2,176
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/jsgrid/jsgrid.css
/* * jsGrid v1.5.3 (http://js-grid.com) * (c) 2016 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ .jsgrid { position: relative; overflow: hidden; font-size: 1em; } .jsgrid, .jsgrid *, .jsgrid *:before, .jsgrid *:after { box-sizing: border-box; } .jsgrid input, .jsgrid textarea, .jsgrid select { font-size: 1em; } .jsgrid-grid-header { overflow-x: hidden; overflow-y: scroll; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } .jsgrid-grid-body { overflow-x: auto; overflow-y: scroll; -webkit-overflow-scrolling: touch; } .jsgrid-table { width: 100%; table-layout: fixed; border-collapse: collapse; border-spacing: 0; } .jsgrid-cell { padding: 0.5em 0.5em; } .jsgrid-сell, .jsgrid-header-cell { box-sizing: border-box; } .jsgrid-align-left { text-align: left; } .jsgrid-align-center, .jsgrid-align-center input, .jsgrid-align-center textarea, .jsgrid-align-center select { text-align: center; } .jsgrid-align-right, .jsgrid-align-right input, .jsgrid-align-right textarea, .jsgrid-align-right select { text-align: right; } .jsgrid-header-cell { padding: .5em .5em; } .jsgrid-filter-row input, .jsgrid-filter-row textarea, .jsgrid-filter-row select, .jsgrid-edit-row input, .jsgrid-edit-row textarea, .jsgrid-edit-row select, .jsgrid-insert-row input, .jsgrid-insert-row textarea, .jsgrid-insert-row select { width: 100%; padding: .3em .5em; } .jsgrid-filter-row input[type='checkbox'], .jsgrid-edit-row input[type='checkbox'], .jsgrid-insert-row input[type='checkbox'] { width: auto; } .jsgrid-selected-row .jsgrid-cell { cursor: pointer; } .jsgrid-nodata-row .jsgrid-cell { padding: .5em 0; text-align: center; } .jsgrid-header-sort { cursor: pointer; } .jsgrid-pager { padding: .5em 0; } .jsgrid-pager-nav-button { padding: .2em .6em; } .jsgrid-pager-nav-inactive-button { display: none; pointer-events: none; } .jsgrid-pager-page { padding: .2em .6em; }
294coder/Efficient-MIF
7,975
utils/loss_landscape/projection.py
""" Project a model or multiple models to a plane spaned by given directions. """ import numpy as np import torch import os import copy import h5py import net_plotter import model_loader import h5_util from sklearn.decomposition import PCA def tensorlist_to_tensor(weights): """ Concatnate a list of tensors into one tensor. Args: weights: a list of parameter tensors, e.g. net_plotter.get_weights(net). Returns: concatnated 1D tensor """ return torch.cat([w.view(w.numel()) if w.dim() > 1 else torch.FloatTensor(w) for w in weights]) def nplist_to_tensor(nplist): """ Concatenate a list of numpy vectors into one tensor. Args: nplist: a list of numpy vectors, e.g., direction loaded from h5 file. Returns: concatnated 1D tensor """ v = [] for d in nplist: w = torch.tensor(d*np.float64(1.0)) # Ignoreing the scalar values (w.dim() = 0). if w.dim() > 1: v.append(w.view(w.numel())) elif w.dim() == 1: v.append(w) return torch.cat(v) def npvec_to_tensorlist(direction, params): """ Convert a numpy vector to a list of tensors with the same shape as "params". Args: direction: a list of numpy vectors, e.g., a direction loaded from h5 file. base: a list of parameter tensors from net Returns: a list of tensors with the same shape as base """ if isinstance(params, list): w2 = copy.deepcopy(params) idx = 0 for w in w2: w.copy_(torch.tensor(direction[idx:idx + w.numel()]).view(w.size())) idx += w.numel() assert(idx == len(direction)) return w2 else: s2 = [] idx = 0 for (k, w) in params.items(): s2.append(torch.Tensor(direction[idx:idx + w.numel()]).view(w.size())) idx += w.numel() assert(idx == len(direction)) return s2 def cal_angle(vec1, vec2): """ Calculate cosine similarities between two torch tensors or two ndarraies Args: vec1, vec2: two tensors or numpy ndarraies """ if isinstance(vec1, torch.Tensor) and isinstance(vec1, torch.Tensor): return torch.dot(vec1, vec2)/(vec1.norm()*vec2.norm()).item() elif isinstance(vec1, np.ndarray) and isinstance(vec2, np.ndarray): return np.ndarray.dot(vec1, vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2)) def project_1D(w, d): """ Project vector w to vector d and get the length of the projection. Args: w: vectorized weights d: vectorized direction Returns: the projection scalar """ assert len(w) == len(d), 'dimension does not match for w and ' scale = torch.dot(w, d)/d.norm() return scale.item() def project_2D(d, dx, dy, proj_method): """ Project vector d to the plane spanned by dx and dy. Args: d: vectorized weights dx: vectorized direction dy: vectorized direction proj_method: projection method Returns: x, y: the projection coordinates """ if proj_method == 'cos': # when dx and dy are orthorgonal x = project_1D(d, dx) y = project_1D(d, dy) elif proj_method == 'lstsq': # solve the least squre problem: Ax = d A = np.vstack([dx.numpy(), dy.numpy()]).T [x, y] = np.linalg.lstsq(A, d.numpy())[0] return x, y def project_trajectory(dir_file, w, s, dataset, model_name, model_files, dir_type='weights', proj_method='cos'): """ Project the optimization trajectory onto the given two directions. Args: dir_file: the h5 file that contains the directions w: weights of the final model s: states of the final model model_name: the name of the model model_files: the checkpoint files dir_type: the type of the direction, weights or states proj_method: cosine projection Returns: proj_file: the projection filename """ proj_file = dir_file + '_proj_' + proj_method + '.h5' if os.path.exists(proj_file): print('The projection file exists! No projection is performed unless %s is deleted' % proj_file) return proj_file # read directions and convert them to vectors directions = net_plotter.load_directions(dir_file) dx = nplist_to_tensor(directions[0]) dy = nplist_to_tensor(directions[1]) xcoord, ycoord = [], [] for model_file in model_files: net2 = model_loader.load(dataset, model_name, model_file) if dir_type == 'weights': w2 = net_plotter.get_weights(net2) d = net_plotter.get_diff_weights(w, w2) elif dir_type == 'states': s2 = net2.state_dict() d = net_plotter.get_diff_states(s, s2) d = tensorlist_to_tensor(d) x, y = project_2D(d, dx, dy, proj_method) print ("%s (%.4f, %.4f)" % (model_file, x, y)) xcoord.append(x) ycoord.append(y) f = h5py.File(proj_file, 'w') f['proj_xcoord'] = np.array(xcoord) f['proj_ycoord'] = np.array(ycoord) f.close() return proj_file def setup_PCA_directions(args, model_files, w, s): """ Find PCA directions for the optimization path from the initial model to the final trained model. Returns: dir_name: the h5 file that stores the directions. """ # Name the .h5 file that stores the PCA directions. folder_name = args.model_folder + '/PCA_' + args.dir_type if args.ignore: folder_name += '_ignore=' + args.ignore folder_name += '_save_epoch=' + str(args.save_epoch) os.system('mkdir ' + folder_name) dir_name = folder_name + '/directions.h5' # skip if the direction file exists if os.path.exists(dir_name): f = h5py.File(dir_name, 'a') if 'explained_variance_' in f.keys(): f.close() return dir_name # load models and prepare the optimization path matrix matrix = [] for model_file in model_files: print (model_file) net2 = model_loader.load(args.dataset, args.model, model_file) if args.dir_type == 'weights': w2 = net_plotter.get_weights(net2) d = net_plotter.get_diff_weights(w, w2) elif args.dir_type == 'states': s2 = net2.state_dict() d = net_plotter.get_diff_states(s, s2) if args.ignore == 'biasbn': net_plotter.ignore_biasbn(d) d = tensorlist_to_tensor(d) matrix.append(d.numpy()) # Perform PCA on the optimization path matrix print ("Perform PCA on the models") pca = PCA(n_components=2) pca.fit(np.array(matrix)) pc1 = np.array(pca.components_[0]) pc2 = np.array(pca.components_[1]) print("angle between pc1 and pc2: %f" % cal_angle(pc1, pc2)) print("pca.explained_variance_ratio_: %s" % str(pca.explained_variance_ratio_)) # convert vectorized directions to the same shape as models to save in h5 file. if args.dir_type == 'weights': xdirection = npvec_to_tensorlist(pc1, w) ydirection = npvec_to_tensorlist(pc2, w) elif args.dir_type == 'states': xdirection = npvec_to_tensorlist(pc1, s) ydirection = npvec_to_tensorlist(pc2, s) if args.ignore == 'biasbn': net_plotter.ignore_biasbn(xdirection) net_plotter.ignore_biasbn(ydirection) f = h5py.File(dir_name, 'w') h5_util.write_list(f, 'xdirection', xdirection) h5_util.write_list(f, 'ydirection', ydirection) f['explained_variance_ratio_'] = pca.explained_variance_ratio_ f['singular_values_'] = pca.singular_values_ f['explained_variance_'] = pca.explained_variance_ f.close() print ('PCA directions saved in: %s' % dir_name) return dir_name
29jitender/Spotlight
7,060
Spotlight-library/src/main/java/com/wooplr/spotlight/shape/NormalLineAnimDrawable.java
package com.wooplr.spotlight.shape; import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.Path; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import com.wooplr.spotlight.target.AnimPoint; import java.util.ArrayList; import java.util.List; /** * Adapted from github.com/dupengtao/LineAnimation */ public class NormalLineAnimDrawable extends Drawable implements ValueAnimator.AnimatorUpdateListener { private static final String FACTOR_X = "factorX"; private static final String FACTOR_Y = "factorY"; private final Path mPath2; private final Paint mPaint2; private float factorY, factorX; private AnimPoint curAnimPoint = null; private int moveTimes; private List<AnimPoint> mAnimPoints = new ArrayList<AnimPoint>(); private ObjectAnimator mLineAnim; private DisplayMode curDisplayMode = DisplayMode.Appear; private long lineAnimDuration = 400; private int lineColor = Color.parseColor("#eb273f"); private int lineStroke = 8; private Animator.AnimatorListener mListner; public NormalLineAnimDrawable() { this(null); } public NormalLineAnimDrawable(Paint paint) { mPath2 = new Path(); mPaint2 = paint == null ? getDefaultPaint() : paint; } private Paint getDefaultPaint() { Paint p = new Paint(); p.setAntiAlias(true); p.setDither(true); p.setStyle(Paint.Style.STROKE); p.setStrokeJoin(Paint.Join.ROUND); p.setStrokeCap(Paint.Cap.ROUND); p.setStrokeWidth(lineStroke); p.setColor(lineColor); return p; } private ObjectAnimator getLineAnim() { PropertyValuesHolder pvMoveY = PropertyValuesHolder.ofFloat(FACTOR_Y, 0f, 1f); PropertyValuesHolder pvMoveX = PropertyValuesHolder.ofFloat(FACTOR_X, 0f, 1f); ObjectAnimator lineAnim = ObjectAnimator.ofPropertyValuesHolder( this, pvMoveY, pvMoveX).setDuration(lineAnimDuration); lineAnim.setRepeatMode(ValueAnimator.RESTART); lineAnim.setRepeatCount(mAnimPoints.size() - 1); lineAnim.addUpdateListener(this); if (android.os.Build.VERSION.SDK_INT > 17) { lineAnim.setAutoCancel(true); } lineAnim.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { moveTimes = 0; curAnimPoint = mAnimPoints.get(moveTimes); if (mListner != null) mListner.onAnimationStart(animation); } @Override public void onAnimationEnd(Animator animation) { if (mListner != null) mListner.onAnimationEnd(animation); } @Override public void onAnimationCancel(Animator animation) { if (mListner != null) mListner.onAnimationCancel(animation); } @Override public void onAnimationRepeat(Animator animation) { moveTimes++; curAnimPoint = mAnimPoints.get(moveTimes); if (mListner != null) mListner.onAnimationRepeat(animation); } }); //lineAnim.addListener(mListner); return lineAnim; } @NonNull public void setmListner(Animator.AnimatorListener mListner) { this.mListner = mListner; } public void playAnim(List<AnimPoint> animPoints) { if (animPoints != null) { mAnimPoints = animPoints; } if (mLineAnim == null) { mLineAnim = getLineAnim(); } if (mLineAnim.isRunning()) { mLineAnim.cancel(); } mLineAnim.start(); } public void playAnim() { playAnim(null); } public float getFactorY() { return factorY; } public void setFactorY(float factorY) { this.factorY = factorY; } public float getFactorX() { return factorX; } public void setFactorX(float factorX) { this.factorX = factorX; } @Override public void onAnimationUpdate(ValueAnimator animation) { invalidateSelf(); } private void drawLine(List<AnimPoint> animPoints, int num) { drawLine(animPoints, num, animPoints.size()); } private void drawLine(List<AnimPoint> animPoints, int num, int size) { for (int i = num, j = size; i < j; i++) { AnimPoint p = animPoints.get(i); mPath2.moveTo(p.getCurX(), p.getCurY()); mPath2.lineTo(p.getMoveX(), p.getMoveY()); } } public DisplayMode getCurDisplayMode() { return curDisplayMode; } public void setCurDisplayMode(DisplayMode curDisplayMode) { this.curDisplayMode = curDisplayMode; } @Override public void draw(Canvas canvas) { if (curAnimPoint != null) { mPath2.rewind(); float curX = curAnimPoint.getCurX(); float curY = curAnimPoint.getCurY(); float moveX = curAnimPoint.getMoveX(); float moveY = curAnimPoint.getMoveY(); if (curDisplayMode == DisplayMode.Disappear) { mPath2.moveTo(curX == moveX ? moveX : curX + ((moveX - curX) * factorX), curY == moveY ? moveY : curY + ((moveY - curY) * factorY)); mPath2.lineTo(moveX, moveY); drawLine(mAnimPoints, moveTimes + 1); } else if (curDisplayMode == DisplayMode.Appear) { drawLine(mAnimPoints, 0, moveTimes); mPath2.moveTo(curX, curY); mPath2.lineTo(curX == moveX ? moveX : curX + ((moveX - curX) * factorX), curY == moveY ? moveY : curY + ((moveY - curY) * factorY)); } canvas.drawPath(mPath2, mPaint2); } else { canvas.drawPath(mPath2, mPaint2); } } @Override public void setAlpha(int alpha) { } @Override public void setColorFilter(ColorFilter cf) { } @Override public int getOpacity() { return 0; } public List<AnimPoint> getPoints() { return mAnimPoints; } public void setPoints(List<AnimPoint> animPoints) { mAnimPoints = animPoints; } public void setLineAnimDuration(long lineAnimDuration) { this.lineAnimDuration = lineAnimDuration; } public void setLineColor(int lineColor) { this.lineColor = lineColor; } public void setLineStroke(int lineStroke) { this.lineStroke = lineStroke; } /** * How to display the LineAnim */ public enum DisplayMode { Disappear, Appear, } }
281677160/openwrt-package
2,334
luci-app-nginx-pingos/modules/nginx-toolkit-module/config
ngx_addon_name=ngx_toolkit_module CORE_MODULES="$CORE_MODULES \ ngx_http_dynamic_module \ " EVENT_MODULES="$EVENT_MODULES \ ngx_event_timer_module \ ngx_dynamic_conf_module \ ngx_event_resolver_module \ ngx_dynamic_resolver_module \ " HTTP_MODULES="$HTTP_MODULES \ ngx_http_dynamic_core_module \ ngx_http_trace_module \ " NGX_ADDON_SRCS="$NGX_ADDON_SRCS \ $ngx_addon_dir/ngx_event_timer_module.c \ $ngx_addon_dir/ngx_event_resolver.c \ $ngx_addon_dir/ngx_dynamic_resolver.c \ $ngx_addon_dir/ngx_dynamic_conf.c \ $ngx_addon_dir/ngx_http_dynamic.c \ $ngx_addon_dir/ngx_toolkit_misc.c \ $ngx_addon_dir/ngx_map.c \ $ngx_addon_dir/ngx_rbuf.c \ $ngx_addon_dir/ngx_poold.c \ $ngx_addon_dir/ngx_timerd.c \ $ngx_addon_dir/ngx_http_trace_module.c \ " NGX_ADDON_DEPS="$NGX_ADDON_DEPS \ $ngx_addon_dir/ngx_event_timer_module.h \ $ngx_addon_dir/ngx_event_resolver.h \ $ngx_addon_dir/ngx_dynamic_resolver.h \ $ngx_addon_dir/ngx_dynamic_conf.h \ $ngx_addon_dir/ngx_http_dynamic.h \ $ngx_addon_dir/ngx_toolkit_misc.h \ $ngx_addon_dir/ngx_map.h \ $ngx_addon_dir/ngx_rbuf.h \ $ngx_addon_dir/ngx_poold.h \ $ngx_addon_dir/ngx_timerd.h \ " CFLAGS="$CFLAGS -I $ngx_addon_dir"
2881099/FreeSql.AdminLTE
33,450
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/jsgrid/jsgrid-theme.min.css
/* * jsGrid v1.5.3 (http://js-grid.com) * (c) 2016 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ .jsgrid-edit-row>.jsgrid-cell,.jsgrid-filter-row>.jsgrid-cell,.jsgrid-grid-body,.jsgrid-grid-header,.jsgrid-header-row>.jsgrid-header-cell,.jsgrid-insert-row>.jsgrid-cell{border:1px solid #e9e9e9}.jsgrid-header-row>.jsgrid-header-cell{border-top:0}.jsgrid-filter-row>.jsgrid-cell,.jsgrid-header-row>.jsgrid-header-cell,.jsgrid-insert-row>.jsgrid-cell{border-bottom:0}.jsgrid-filter-row>.jsgrid-cell:first-child,.jsgrid-header-row>.jsgrid-header-cell:first-child,.jsgrid-insert-row>.jsgrid-cell:first-child{border-left:none}.jsgrid-filter-row>.jsgrid-cell:last-child,.jsgrid-header-row>.jsgrid-header-cell:last-child,.jsgrid-insert-row>.jsgrid-cell:last-child{border-right:none}.jsgrid-header-row .jsgrid-align-left,.jsgrid-header-row .jsgrid-align-right{text-align:center}.jsgrid-grid-header{background:#f9f9f9}.jsgrid-header-scrollbar{scrollbar-arrow-color:#f1f1f1;scrollbar-base-color:#f1f1f1;scrollbar-3dlight-color:#f1f1f1;scrollbar-highlight-color:#f1f1f1;scrollbar-track-color:#f1f1f1;scrollbar-shadow-color:#f1f1f1;scrollbar-dark-shadow-color:#f1f1f1}.jsgrid-header-scrollbar::-webkit-scrollbar{visibility:hidden}.jsgrid-header-scrollbar::-webkit-scrollbar-track{background:#f1f1f1}.jsgrid-header-sortable:hover{cursor:pointer;background:#fcfcfc}.jsgrid-header-row .jsgrid-header-sort{background:#c4e2ff}.jsgrid-header-sort:before{content:" ";display:block;float:left;width:0;height:0;border-style:solid}.jsgrid-header-sort-asc:before{border-width:0 5px 5px;border-color:transparent transparent #009a67}.jsgrid-header-sort-desc:before{border-width:5px 5px 0;border-color:#009a67 transparent transparent}.jsgrid-grid-body{border-top:none}.jsgrid-cell{border:1px solid #f3f3f3}.jsgrid-grid-body .jsgrid-alt-row:first-child .jsgrid-cell,.jsgrid-grid-body .jsgrid-row:first-child .jsgrid-cell{border-top:none}.jsgrid-grid-body .jsgrid-cell:first-child{border-left:none}.jsgrid-grid-body .jsgrid-cell:last-child{border-right:none}.jsgrid-row>.jsgrid-cell{background:#fff}.jsgrid-alt-row>.jsgrid-cell{background:#fcfcfc}.jsgrid-header-row>.jsgrid-header-cell{background:#f9f9f9}.jsgrid-filter-row>.jsgrid-cell{background:#fcfcfc}.jsgrid-insert-row>.jsgrid-cell{background:#e3ffe5}.jsgrid-edit-row>.jsgrid-cell{background:#fdffe3}.jsgrid-selected-row>.jsgrid-cell{background:#c4e2ff;border-color:#c4e2ff}.jsgrid-nodata-row>.jsgrid-cell{background:#fff}.jsgrid-invalid input,.jsgrid-invalid select,.jsgrid-invalid textarea{background:#ffe3e5;border:1px solid #ff808a}.jsgrid-pager-current-page{font-weight:700}.jsgrid-pager-nav-inactive-button a{color:#d3d3d3}.jsgrid-button+.jsgrid-button{margin-left:5px}.jsgrid-button:hover{opacity:.5;transition:opacity 200ms linear}.jsgrid .jsgrid-button{width:16px;height:16px;border:none;cursor:pointer;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAFgEAYAAADx4WWjAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAZjElEQVR42u2deVyU1f7HzzyzDzCA7MgihCsY7uYOiZIamebVFl/Wy8zSxLTQuld/lmIuCGIu9cruLa9lXlNTUQsVUgQRNBbZF5F9lWEbZpj9/P74doQZ87LMDHjvPe9/vj7MPOf5fp6zjc/3e86D0H8rNTVRUd988/rrxpZTV3f48PHjixb1m+N5eVOmvP76hQtXryKEEMYVFWFhERG7dvW2nIKC4OBVq/71L1JOWdk774SHb9tmcoc1mpaWtjYLi6Ki+fPff/+f/7x2DS6YlobQpEkYJyQgxOViXFGxYUNExN693ZVXWDh//urV339/8yZCQiGUM3EixqTcqqq//e3gwQ8+MJkAnU6tVqvZbKk0KSkj47nnfv/d2nrcOInk1i2EHBw6HSBCyss3btyz53Eh4PiJEwkJCAkEGKenIzRlCsaJiQhZW2OcmentHRhYUCCX5+Tcv+/nZ/KaIKjVlZUSibPz3bu2tv7+jY1JSQjZ22P8++8ITZiA8c2bCIlEGNfU7Njx9dcbN5aXv/fe55/v2kXueFfHrawwzsjw8po1Kz9fp5PJVCoOx9T+sp4spLq6qcnJKTPTzy8wMDtbpWpurqlxcBAIEPL2RkihQKi8HCEWCyEOByGBACEPD4RkMoSysxGyshoxYtKkvLxnn83IiI3192cYoZDL1WjMduefhEbT2Njebm2dnT1x4sKFt26lpCDk7Q01Mm5cp719GyEPD4zz8+fNe/PNixcx1moxZhhz+9ftBTgce3tLy9ZWodDT08enqEirRUguh89YrE6r1SLU3o6QWDx27HPP3bjBYrHZLJZO1+933JDCwnnzVq8+eZJ0xvR0hKZNwzg5GSF3d4xJjXRt+2IxxpWVYWFRUX/964A5npc3e/aKFT/+aNg5k5IQsrPDOC9v/PjXX09Nzcpyc3vhhbKy5GSEXFygSY0fD6MWj4dxRcWmTZGRW7b0m+P5+dOnr1jx00+Gw+HNmwhZWmKcmTliRFBQdjb5vlrd1NTSYm2dmsrnDx0qlycnI+TsrC9EIMC4ouKDDyIitm41ucNqtUTS3GxlVVQ0f/66dZ0TWUYGQjNmQJPo6rhOp1RqtWy2YTkKRUFBVdXQoampPN7QoR0dt26BkPR0hCZPxpjMyDCRbdxoMgE6nUqlVnO5UmlSUmbmtGl374rFY8c2NcXFwQXv3RsxIigoKwtjpVKr7X5UUSgKCiorfXxSU0Wi4cOl0vh4KCcz08srMPD+fbk8O7u4+NlnTV4ThI6OrKzS0qFDc3JCQpYuPX1ap+vo0Ggev+PdIZPduVNY6O+flRUUFBLyyy9arVSqUAiFZnPcEI2mrq611cbG2HJUqrKyhgZX135znEKhUCgUCoVCoVAoFAqFQvlP4FGIyd//wIGYGPL0eOFCsOSRooWF/jHG3RT7R7kkwNHeDpY8W7106d69DRteesn4p9UGQbdZs8BOmAD26FGwajVYS8veFd/RAZbExtatA6tUgjW5gFdfBXv4MFhnZ7hTpEZ6D9TsiRNwFBsL9u23jXWc8FiUEi5IwqFlZWBLSkAIqaGeOn7uHBzNnAl2yBAoRyo1lYDHnvfDBUiV+/qCfeYZcOjs2Z45/s03cBQQAHbUKFM7TmB19wVwyNMTjlJSwCYlgW1tBUtqjM8HGxwMdsYMcDw319SOE7qNuIAD5eVwtGwZ2CVLwFpbgyU1RvrQypXmdrzHAvQhTaCoCOzy5eDoqlVwnJEBtqnJ3I73UQAJEQkEYG1t9T8nf++/UJKRqQBsNvSR3sfQBkiASPTHaX+cV1sLTUirhWNWt4PCAAuorQU7aBDYpUv1P5fJwJo+rcZoAfqjyvvvgz18GJpQXh4cjxkD1vTjvdEC9IUcOwZHZDglwyyEtREqLu4vARQKhUKhUCgUCoVCoVAoFMp/JL1+GAuLe0isbM8esCScum/fhAkIpaWdP9/vAsCxyEg4mjsX7MOHYA2XEE6ZAtbKSv/vJBx786b+eVwuWEdHsHFxINT4xUAGT5G9vMA6O4NtbgZrbw+WPJVOTARLHrMTS+LC48aBbWsD29gI1sFB/zrGYyCAhIpIXJgE927fBktCSCtXgv31V/07v3gx2DVrwA4dCjYwEOzp02DPnDGTAJJSQCLq48eDhdVlCB05Apa0fdKESFxg506wOTlgSVDwtdfAkiaZkAC2vt5YAQaP10kA4949/b8/KcWARGQMAxrk76TJEFJTwVZWGuv4YwKgU5FQEYn/EkjwjrRxQwyTP8ioRM4j1NTAdQzLN4EAfVpa9I9JDSgUYEmb77ogtyvkcxL4Jpg+cvMEASTiQiBtndQQEWIogNQE+Zz0KYLp48dPEFBSon9MhlUS/yXDIhk+iQDSxFQqsGKxfjkkQG52AWT8N1yRTZYmks8N5wHSREjc2MlJ/3zTdd5uBJBF54Zt1s4OLJmgyJ0nAkjNkBwKMgOTpkfOM7sAMkoYdmYyqvzZqvquDhKhBJJy9qRRzIQCYJgjna2qSv9TMk+QpkCakkSi/33iMIFMWGQiMx3dRNQNL0gi825uYEeNAks6rYsL2Dfe0D+PjP9kxu43Afn5YOfNAxsSApYMk6SzkiZE/u7tDZb8GjWc2SkUCoVCoVAoFAqFQqFQKBTjMNuiHViaMmQIHJFNgqOjYQVIRcVTKwAcJ2swydJFEuEhi0sDAvRXCPYdk20pC46TQAiJIxgG/0iN/PILfN/DY8AF6C8WTU8Hu3YtWPIQ2HBNJXko/MMPxl6/z+u9wHGSOhATA5Y8nSZbnhcWgiXLch88AEtibl9/bayAXvcBcHzwYDgiKQfdpQ6Q9cW//AKWy4U+QCL3/SAAHCc5EyRyTxa+9RQfH3DcMIjYd7ptQvqdjaQIkM7YHSQ2tmSJqR3vVgA4TqKMpI331HHCokXg+MWLpnb8iQL0R5UbN/rm+MKF5nacYLAxBgkVVVeDJaNKT1m8GBwnuxmYH7b+cEi21ScB7qlT//3ppI2TO06aWv/xx0Tm7g72wgWwZCOLjz7689NITgS545cu9bfjBI6+Q6TTkt8wpEZIqtknn4B95ZWBuuOG/FEDZC8VAo8HliRnkJ8IU6eC46SmBp4/aoC0ebKnyq1bYElKQWEhOE5+GlAoFAqFQqFQKBQKhUKhUCgDi8nCrKdOFRffuTN+/LJlMTEREdevIyQUkuAqPPPu6JBKEbp6ddmy7dtDQubOdXPz9SUBk75jsk0dWSwWi8Xi8xFiGDbbygpsVwFwzGIhxGIZLpB7CgQAGg1CGMOjYmIJXY/JmhvjMfu7U80NFTDQUAEEnc6w0/6HCfDyEovt7auru442+oJ0Oq0WITc3CwtbW7Kk0Xg4P/10//6dO7D4n8Uiq097/mJkPp/N5nC02t9+q6rKzx89GiGBgIzyMP6zWGB5PKEQoZMni4tTUwMCLl4sLc3MFAg6OrRatbrn2z5DTTMMl8swDKNUshCKilqyBOPOiae3TYE4yGZDdpBAALkoGOvfBhYLFu12dMCaV6iR3l+PnMflCgQdHRyY8lUqEMDj9b5A8m0ixNDxzu/B36EmOq/T272qQQCbzeUKhUolB4oATX3b9rr3Z5Gm1Sm99+fDOVotB35kCYXGNyFyvlBImhD5BrnT0IRUKlhtbFwT0mi0Wo1m0CDWtWuVlbm5s2aBI2TRf8/fJ8/lMgybrVbn5zc319b6+a1Zc/36t98ePtzZJ4jjSqVcjlBExKxZK1Zs3jxpkqOjl9edO2q1TqfVksGjezDGGGMOh81msRhGJuPMmePuboqftZmZjY3l5QUFCKlUCsXhw11HI7jDarVKhVBIiKenv39MzMiRtrYuLsbHnU02D+TmNjXV1np6du2c+m2bYRgGoaoqmay5meRmGI/JBEBT+jPHzQv9LTTQUAEDjcn+Tww/srjczgmKWDJrwjHGCGFM8pGeIgHw61Au5/G4XIGgoYFhuFyBoPPXjk6n0ajVLBZMQP33hggKhUKhUCgUCoVCoVAoFAoFIYTQhx8mJHz//dq1CO3b9/LLLS0IRUQsXNjSsm3b7ds//fThh/3tT6+fzEFekK0t/Ivsbkw+M9ws2Pz04eEuxhgrlX+eF0S2rH2qBTxd9FrAk5I6GKZ/Q0uEXvcBFxdLSxuburquj9ExRsjBgc+3sGho6HcBH32UkHD8eGgoxHOFQmjThlkOGNvYCARCYXt7XFx1dUHBCy8gJBTC1vBQH2fPlpZmZISE7NiRknLmDIvV2qpSKRQWFlBeZ91AnJdhWCyGYRiZLCpq5szly8mbJXoPC6F9+xYuxBghFotE6v8810Gng78LBJBOKRLpj0FyOWx4rlBAJB7Cqo9DymcYCG+HhZ092/fGx3k8v+dJof/HR50/vyxxsOt9//flGANn27bp05cv37wZxnUSWyepBp0vRrCzEwgsLEgTCgq6eLGkJC1twQIiPDjY03PMmCtX5s718Bg16sqVtjalsqNDJAInSV3AkU7H4bBYLBab3d6+fTtCP/9svJAeExWVlnbx4vLlCO3Z8+KLGCO0e/eCBRgfOZKRERv77rv96ArUQG9PKC9va5NInJ07kzmgKdTXKxRSKdmfov/o9TzA4zFM/72F3gwCIEw60G530ut7CeO4QNB1tOkcVQzfO/MUCmCzGYbNbmyEcby1lQhgGIZhsfp/JqZQKBQKhUKhUCgUCoVCofxv0uPAQmNjW1tbm5NTfX1ra3Pzyy9LJFKpVDp9Oiy/cnXV6XQ6na69ncfj8bjcjAw7O0tLK6vz5729nZ1dXDIzzSWg2ydzKSlFRfn5lpbNzTKZVLpwYUtLe3t7+xtvqFQajUYzdqxWi5BOZ2mJMUTN1GqdTqcjb0cXiUpL6+vr6trbvbycnJyd79/vtxqorJRIHj4cOTI7u7y8rOz0aY1Gq9VqfX0h0I0Ql8tmczgPH8Kz0oICCIU4OkIUc/hwEIgQj8fhcDgajY+Pi4uLyzvvDBvm6urmduyYqQQ89nS6rq6lpalpzJi8vMrKioq4OHDI11ck4vEEghs3LCz4fIFgzhxwzNNz3rxx4yZMmDmTx+NyudyRIwUCHo/HGz5cLBaJRKIjR0AuhwM34rvvSkrq6mprN240Ww1cuZKenpaWmalUajQajb+/lZVQKBB8+WVg4OjR/v7vv9/bC1y/np19797LL0ON/PxzR4darVKxWFOnDh8+cuS0aY6O1tY2NsnJfa4BuVyhUCjc3cvLGxrq69evl8tVKqXS318k4vN5vOvX++o4Ac4/fx5q7IMPSHShpKS2trZ23z5ja4ApL29sbGgIDq6qamqSSF56ic2G8CjYnTuNvYC+kEOHBAIul8stK2tr6+iQy6dOLStraKir6+17DLoIaG6WyWSyoCCFQq1Wq6dO5XI5HA6npgbu0+3bphLw6IIMwzDMtWtk1WtDQ0tLS8vEiX0uD9anOzoyDEKdK7rJjt+mzz6BUaywkAReVSqtVqcj7+TogwCtVqfT6eRyksQBw6GDA3xsrnCevb3+XghqdZ8FQGdNT+dwGIZh8vNBkK8vCOnt+we6B2bsqVPBImRjIxKJRH2f4BgvLwcHJ6cLF5ydbW1tbGJjVSqtVqMhaTVhYaZyPD4+MzM9fc4cjQZjjGfOtLQUi8XikhJfXw+PIUN+/bXPAmxtraysrNLS7O3FYmvrL7+EO9/erlSq1Wp1aOj16zk5WVmQUtA3x+/dy8iwsdHptFqtNjqax3N0dHREaNiwIUO8vDZvNvbGPJqJ7eysrMTi+/dHjHBzc3ffvFmhUKlUKoRUKrVarT53Diakdevi47OyMjO73wsF7viMGRhrtVptQoKFxZgxY8b4+ra0XLp0+TJCpaV790ZEGN/Hnvhb6MGDurra2vXrc3MrKysqoqNJ0gaPx2az2ZWVMBxevgyjSlkZhFutraHpzZ4N6SKTJgkEDg4ODghJJBcvXryIUEXFRx9t2oSQTCaXy+UIBQVFRkZGrls3bVpYWFhY7/OGuv05XVvb1NTUNHFicXFtbU3NoUMKhVqtUk2eDD/iyLDY+X2MoXNaWg4aZGf34IG7u6urq2tYWE7O6tXvvhsQcPfusWPHjq1fb23t7e3tjZBUWl1dXY3QvHmHDh06tGHDhAmrV69e/cUXJhNgSFWVRNLY6OtbXS2RSCQTJqjVsEUI5GApldbWIpFIVFDg6enu7uGRlGRpyWKxWJ27msXFbdmyZcvBgykpUVFRUaGhYrG7u7s7Qm1tICQ4ODIyMnLTpokT165duzYyss9ty9xcv/7ZZ599duDAzp1CoVCIcVSUm5ubG8bkOCkpIiIiYseOgfazWxISwsPDw6Ojw8N5PB4P46iowYMHD8Z4506RSCTCODFx9+7du033m8xsgKO7du3cKRAIBBgfPOjj4+PTKeTKlbCwsLC9ewfaz25JSTl06NCh8PDwcD6fz8d49247Ozs7jD/5hM1mszHOyzt79uzZ0FC5vKGhoWHIkKcuc/e550JDQ0P/7/+Cg/fv379/yxadDuYjS0sLCwsLhLhcoVAolEoRYrPZbKVyoP19IgpFa2trq739jz+GhISEnDhx8uTixYsXHz/e0dHc3NxsazvQ/lEoFAqFQqFQKBQKhUKhUChG0U2ERiBob1cqFYp9+ySStjapdP58iGa2tdnbW1uLxTt3jhzp5ubhcfbsUyMgL6+qqqIiKKisrKGhvv7YMUg5GDwY4jFlZbDlu7W1VouxTicUWltbWFhYXL7s7m5nZ2+/dKmHh4ODo2PP319gLI8e7hYV1dRUVQUGlpc3NDQ0XLum1ep0GJeWwtLDCRMglDRsGJvNZjPM4MEcDofD4Xz4YX19S0tz8yuv1NQ0NUkksbH9XgUymULR0WFvD2k29fUxMXfupKQkJvb0/Bs3cnKysvz8zp9PTU1OxhjygvovIMEUF9fV1dZu3QrRRUdHCws+n8/v+crsgAA/v2efzcnhcjkcLvf0aYlEKm1tXbPm/v3a2urqnu9q32cBLS3t7TLZsmWwGrW8fPZsf/+xY/PyelsQZLlcuaLVarUYI1Rd3dTU3Gz+Fd4MQgixWCT3zdLyt9+yszMze79NAkTibW2hHB5PKOTxeDzymngzCvDxcXZ2cgoP1+lg7wKVSqPRalev7m1BGHO5XO6qVba2Hh7u7ikpkyYNHTpsWHOzuQU84s6d4uKCgpiY06eTkxMTMYbOOWpUd+fFxxcW5udv356QUF9fW4txeXlZWWlp3zOwesujplJd3dTU2CgQlJXV1zc0nD/f1NTeLpUGB8OmL6dPw7B57RpE4p2ctFoej8t99VWRaNAgOztf39zc5ctXrECIzy8vLy8/dWrSpC1btmxZvtzff+XKlSt7/kqM3vJoHhg8eNAge3uFYtq0kSNHjXrhBVdXW1s7ux07RCI+n8+fOBEmtM8/hy3KQ0OHDHnmGR+fqioXl4cPJZIXX9Tp0tLS0lJSiopKSkpKli0rKrp69erVc+dyck6dOnWq/9faP0ZiYl5ebq6bW2pqQUF+/uM7OV27tm5daKit7YkTISEhIUlJkEiD8fHjwcHBwcnJKSkHDx482PfUsn7jzp2vvvrqKzu7b78NCAgIyMjYtIkImT179uz4+Nu3o6Ojo21sBtrPbklOjoyMjLS0PH48KCgoKC5u/XoQcvTojBkzZmRkyGR1dXV1gwcbex2z7dExdWpYWFhYe3tVVWpqaurChTKZVCqVPniAsUaj0bi58flisVjc92Q/swsguLlNnjx5skx26dKqVatW/eMfarVGo9HodAzD5/P5Eom5r0+hUCgUCoVCoVAoFAqFQqH8b3PsWHFxauqLLx49mp+fmLho0UD702Nyc1ta6urc3RHas2fBAowR2rkzOBjjTz+9e/fCBeO3ZzDbKiaZTKNRqRgmIOD06e3bb95EiMuFMIdGo1Ih9N13hYXJyatWPbUCnn/+3Lndu2NjHz5sbKyoGDKEOO7q6uHh51dRkZPzl7989tnkyU+dgDfeiI//+9+/+CI1tbDw1q05cxDi80UihBiGz7ew0Gji4195ZevW558Xi/l8oRD2yX8q2LUrMzM29r33EAoPDwrCGKEvvnjtNYwR2rVrwQKMY2OrqwsKnn/ebA6MHn3y5JYtiYlTppw6tW1bz9e4x8RUVOTkzJpFNpFH6MABcBw6a3R0Ts5vv61dazbH58y5dGn//h9+QGjr1mnTOi88evQPP3z88Y0bdXUKhUz2eJQxL6+lpa7OzQ2h6OhXX1WpEIqOXroUY4R27JgzB+OVKxMSjh//6iuzOf4HzPTpzs5Dh2ZmImRt7eSEEEIikViMUHZ2dXVBwaxZfn7ffbd+fV7egwetrQ0NnUsAAwLOnAkPv3ULIY1GqeRyEZLL29oQmjnTzy8wMD7+229nzVqxYs0acwt4FOi+cqWqKi8vIGDRonPndu+OiZHLOzqkUisr8ioKe3t7e0/PsjIPDyurQYNKS9PTy8uzsgIDEVKrlUqEXF3t7T08KisfPHjrrQMHvLwEAjabwyFv6e4HAYQHD6RSicTNbc6cM2d27IiLKympqSksHD4cISsre3uEEMIY3IL9JxBiGDZbpyspefvtI0e8vJ55xsrKzq6iwtyOEx4bRr29razs7KqqcnLefHP//tGj584dOXLmzMuXEWptra8HAbDDgVqtUCD0669Llnz66dy5/e14r3nrrbi4o0ePHkXo44/HjcN4796srGvXNmwYaL96TVxcZWVu7owZA+3Hfw3/D73/bnBl1mLvAAAAAElFTkSuQmCC);background-repeat:no-repeat;background-color:transparent}@media only screen and (-webkit-min-device-pixel-ratio:2),only screen and (min-device-pixel-ratio:2){.jsgrid .jsgrid-button{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAALAEAYAAACFny30AAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAA6CUlEQVR42u2dZ2AUZRPH53rLpVdSKSGhgwoIqIgKiBRFBGwooQjoC9KbSEdFqoIiNhDBQhdEQBABIShNCCUhpEF6T+5yuX77fhgejhwc6dkE5/dl2LvN7uz8n/4cOwAEQVSCmJjOnZ97bunSK1eeeWbo0G7d+Pbn2rWBA8eMmTnz8uWuXQcPfughvv2pLMKKnpiY+Oqrs2Z16lRampwcGzt6tNlcWFhQMGwYX45nZCxe/O23kZEazb///vPPuHEWS3FxQcGrr/LlT62RlBQV9d574eGnT/v6tm6dkREdDRAUxHHR0WJxSAjHXb3ar9+wYcuX15U/WVkrV27e7Od35kzjxg8/fP36iRMA3t4cd+qUUNikCcfFxHTs+Pzzc+fyHbdqk5T02muzZnXu/M8/Xl6RkXl5p04BNGnCcefOAXTrxnFnzgC0a8dxJ08KBL6+HBcb26/fsGEffVRb/mRmLlu2aVNk5JkzjRq1b5+WdvIkQKNGHHf+vN2f9u05LjpaIAgO5rhLlzp1euGFOXP4jmN5CBw/SEgYMWLq1CefzM/fseOXX7Zv57jiYgAvL4kEwMsLgOMATCYAgQBAIgGw2QAMBgCTSSjMygLw9OzXr3fvFStatNizZ9OmqVOr62BW1sqVW7YEBNy8+ckny5YdP26x3LiRnd2smUwGEBZW1h+RyH5sNgsEGg2AQhEZ2bTpqlVisYuLu/tPP7VufebMtm2nT/MdeMZdfYBQqFZLpX376nTFxdeve3mJxQCurvgdx9nP4zgAiwVAKASQyQCkUpvN3x+goGDv3gMHpkyJje3b9/XXP/64qo5hiW/VKjV1+fJly86fN5tv3MjJadZMLi8b+Hv5o1IBWK0cp9EAGI0aTVrapElicWCgi8srr/Ad8HIF8PcfPjwqatas0NBRo2bM+PjjkhKACxewpBuNWNLE4rIPbrXig8vlAFIpx6EQ+/cfPjxtWmzsc8+9/vqqVRV1iJX41NS1a1eu3LPHbM7IyM7295fLAUJD0Y87A3/7QW7d32AASEkBkMmCgwMCCgsbNRo1auzYHj1cXTt16tp15ky+A+6IoLwTbt6cNu3DDxcsSE5etmzevLlzFQqA5s2xuqtUKIDZfOtiAntTwAQzmQSCzEwAT88+fXr1WrGiRYvfftu8+e6mCQPPSvzhwyZTRkZOjr+/QlF+4KVSDPzNmwAiUXCwWp2bGxIyefL06U8+GRAwadKIEVev8h1oZ5Q7DA0JWbZs1qx580JDp02bM2fx4tJSgLg4DIheb+8LGM5rxIEDhw9PmRIb27//G2+sWMHOz8xcuvTrr93dU1PXrFm5cu/eypR4mcweeLE4MFCtLiwMDn777cmTn3++vgeeUW4NcOTmzVmzli9fsCAp6cMPZ86cO1epBIiMvH+NEApRFKMRwGoVCktKANTqDh06dPjsM7M5MzM3t1s3vT4jIympfXu5HCA4uGIlPiUFS7yra05OcPC7706b1qNHo0ZTp44aVf8DX2UBGCkpU6cuWLBoUUrK8uWLFs2Zo1IBtGyJAVIo7J3i7Rvd0TSZzSiIRmOvQRIJgLu7/fvyAi+RhIZ6excUBAWNHz95ct++AQFTp0ZF/f033wGtMwEYWCPmzMEasWhReTWizM1vHd85unKEBV6vB0hKApBIGjf28cnODgubO3fBgu7dfX2jogYNunaN70BWlQovRTgjJOTDD6dOXbw4LGzmzPnz583T6wHi48v2EXeOmu6kIoE3GABu3ACQSkND/fwKCsLCZs6cN+/55xt64BnVrgGOpKUtWrR27ciRaWmLF69atXatSGQ0qlRyuUCAAQW4f+AZVitASQmARBIR4eV17lxQ0JQp7777yiu+vm+9NXTo9et8B66mqHYNcEShCAlp1mzrVrHY3d3VtbCQ1YTKIBBgDSotBVCpGjdu3/7IkQct8IwaEyAjY8mSb75p2zY5efbs9967csViyc4uKQkIEIsBPD3xnIqUfHaeWAzg7Q1QWPjXX4cOvftufPzAgW+/PXEi3wGraaotQE7OmjU//RQUlJb25Zdr1uzZYzKlp6enBwdLJBh4Ni+4F4L7NICsDxAIdDqxWCrNzd29e9euVavi44cMGT9+yhS+A1dTVLkPSE+fO/fzz9u1y8zcuHHDhoMHjcabN9PT/fzKm7my4ajVCqDV4rFcXrazttnufb5Oh4tseXkAvr6DBg0ZMmVKePj27WvWrFzJdyCrSqUFSEoaPXru3NDQ3Ny9e3fuPH7cZsvKKi4OCZFKAYKC7l4kuzOQYjHODQoLAQQCmQznBUaj0Yjfubvbz3OsOWy+wIQzmwWCggIAH5/Bg196aebM5s23bl2zZulSvgNaWUQVD/ybb86e3aFDbu7u3Tt2HDtms+Xm6nSNGkmlAI0alR3v38mdw8mkJACpNDw8ICA9PSho8uQJE558Uiz28XF1LS4uLLx8+dChbt3EYgAPD/w7xxphs9mXIJhQWu3Vq2fOPPPMrFlDhowcWVKyZs2VK//8c+oU34GtKOXWgKSkkSPfey80NC9vz56dO0+csFpzc43GoCCZDMDXt2Iz1+RkALE4JMTbOz8/LGzevLlz+/Tx9R05csiQM2fY+deuvfrqmDE//piV9cMP33338ssqFUCrVvalDI67u2m6s0ZYLCJRYSGAt/dLLw0aNHNm8+Y//9wQaoRTARITX3tt1qyHHsrLO3Bg1679+zkuP99k8vWVSDDw5ZX4O2eu3t6ZmWFhc+YsXNi9u6/vyJGDBjkfTl6/PmzYhAkbNmRkfP/9+vXDhyuV9iUOiaTsEsedq69WKw5bLRahsKgIwM2ta9cuXaZPb9XqxIlt25Yt4zvQFRYgIWHEiGnTHnssL2/Hjt27t20DKC4G8Pe/c0esciV+1iws8ePG3VniyyMubsiQUaN+/DE7e+vWzZsrViPEYvsM3GJBzxWKVq0iIpYulUhUKnf3rVtbtTp9euvW8+f5DvztuN0dSFdXieTFF3FHzN9fLAZwc8Pv2APfOZ53LPFicePGXl4ZGWFh8+cvXPjoo5UNPCMycuvWr79+5ZVGjYYNGzPm2291OoDLl9EHi8Ve8pk/rGCIRABqtb1GGI2FhampM2YIhQEBSuWbb/Id8HIF8Pd/883hw2fMCAsbOXLGjM8+0+kALl60t/WspDmWeIkkJMTHJy8vLGz69HnzBgzw9R0x4sUXExKq62B4+Pfff/LJyJF+fkOGDBu2ZUtpKUBsrH2UdKc/bH/gxg0AmSww0N9fqw0IGD581KhevVxdH3740UdnzeI74JUmKWncuPffX7Hi6FEAiYTjzp4F6NiR46Kj8VcJp083btyqVVpaTs633+7c2aRJbfuDfcTXXx87BiCT4a80OnfmuFOnAEJCOO6ff4KDIyIKCjIyPvxw/foOHfiOX42RmDhy5LRpq1cfPgwAwHGnTwcFtWqVn5+dvW7dtm0PP1zX/ly7NnTo2LGbN//xB/rzzz8BAS1aaDTp6QsXrl37+ON8x6vWSEqaMGH27A8+SEv76KPPPuvShW9/rl2Linr77c8/T0mZPHnBgl69+PaHIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIIga4q5XF7drt3r1nj2PPYZHLAVh8+ZohcKytqI5MerscW49z53vWwfAtEIAAJMmXbw4ceKAASdO8O0pw0l+o9270Xp5oWVv8s/ORssCX5m0PLUJCzzLXMCO/fzQPvJI2efy9ubXXztOBGAl5Pnnyz7YBx+gPXQIbVAQ2jtfo80HrEampaHt2RMte2u6QlH2ueoPTgRgqcp37Cj7QC+8gPbIEazKR47w/QAMbDpbtCjrJws8KzD8pWB3htP8AfhArApv24aWvRI4MRFt794oBDuue9DPpk3x6OBBtOz4r7/QDh6MfrImtP7gNItSWYfHjEHL3rvPHnDnTgyAj09dO172vjt3lvWL+TlmTH0NPKPcNFb4ALGxeDR+PFqWAaNtW7Rbt2JAZLLadrjsfbZuLesH82v8+LJ+118qnEcMHyg6Go8mTUKbk4P2ySfRbtmCAWJtb81R9rpbtpS9L/ODDTOZn/WfSidywwfctw+PWGZsgwHtoEFoV6/GgMnl1XWw7HVWry57H3bfqVPL+tVwqHImPXzg77/HI1Yj2HzgrbfQvvdezbjJrsOuy+7DSjzzo+FRY9lUsaTOno1HS5agNRrRLl+O9uxZtGwC5ww272ATKFbTWNv/3nsYeDYvabjUeDpbFIItYTgm3ywpQVteH8Hyr7q4lP189WoMPKtxDR9x9S9xL2bMQMsCOGoUWhb4lBS0jjNoNqMNCyv7+ddfl73ug0ON5xPGEsqakD17yn7LlgL69EHLUqAwyz53XDLYs6fsdR8caqkGMBwT1rLOs6AAA5qfz77BpsvxPGfXeXCo8RpQFsfAsdRrzrLMs89Fovtf58GhlgUgyoME4BkSgGdIAJ4hAXimjgW4V0Lc/za1LIDjcJNNpEpL+X7w+kItC8ACzkp8y5ZonSUBZcnK/zs1pJZnwmz1k22QdOuGdv16nPn++ise79qFNiYGrVbLd2DqilqrAbjUkJmJR++8gxaz/wI0boyWbXH+9BPazZvRtm7t4OYDO1io9QdDIS5exKNXXkH78stoWcn39UX77LNoQ0PLXqX295r5grc1FmyC2HI1C/hrr6FlAl27hvbtt1HI5GS+/CUIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiB4otbfmHX2LMDDDz/1FB69+ipa9lZEsxkteycce2v67t2PPAJw7lzDS8pTWWr5rYkMlo21a1e0LPuRowAst0xCAtoHX4C7agCW2IcewqPISLQsjRQLWHk4ZrpYtAhteHjF/j43F+20aWWvJ65ggWE1ib2p9/JlrFEsw179wckD/fAD2ogIftxiKQo3bqyZ67GX/7ECVX9w8trKms+Exy/193mc1ICxY9G2aYO2qAgta7udpRRhiZJZJ5uXV/Z81iSwgLCSzs7T6dA6vqiVJZZmTQs7n13PWaoU9j5S9kbe+ofTURD2BSwQrBN1bFvZg3MctrGxsfh3rM9g2U0dA1NcjOffuIHnBwTg5yx9ruM7pFNS8HydDs9n/rBOm2X8Zv4wGx+Pf1fRvqvuKadTe/RRtCy/ESuJLNEaCyjHYWD69y8bOJZImWXUY2/AZZ/36oV2xQq07M26LGASCdpXX8Xrs9HR0aNoWU1iNdNxODtgANr9+/kOtDPKEcAxhzzDWZvKmiCWqI3h+Ophx2PHrEks8AyNBi0rAEplxfypv3mEGeW8O/rmTbSFhRW7nKsrWtZGs8A5UtG0VGz4yXLFq9UV+7usrLJ/V39xKkDZtpO9Bb08WAllTQJrqqoKa7pYDkp394r9HZtHsL+vv1Tw7ekVFcDTEy3LkFHdPADsOqwGenhUzt/6n/qwhgVgAaopAdiwlAng5lY5f1lNrL9UUADWppaHqys2XazpqX4NwOuxQQDrY8r3t+zf1V9qXICyx8464YrimOynogKwHPP1nwoKUNHhnGMnWVxcPfdY58twHH5W11/+qWQf4JiA2RE2A2ZUtwY4NmEV7QNSU2smPLVPJQWw5/+9N44ToorOH5zh2AQ5pjh3hA07q3vfuqOCArDhXHlV27EGVHce4FiDymuC2ATQsemqv1RQAFayyhNAKsU1GzbTrW4gHPuQ8gRgE7AHVoDyRkNsjYetCVW3DygsREHZ/EKluv/5rIBU9751R7kC4Hiadb4ZGfc/mwnAliSqLwBaNroqT4CcHPS3/i9BMCqZyK38JghtTQnANoLY6KeifUDDoZICsDbWGWxZmTUZ1Z0JMwHYKqjjMrUjFZ0w1h8qKUBFl3dZk8E60cqOhtgqbEEB2oouQ9f/5WdHKikAq+LlbfGxGsBKcGXzB7M2nNW4igrABGs4VFIANrwrr61lNaCiAjhu0DCBWSdcngCsrylvolj/qKIA5fUFHh44GmGBdwyMY8Adx+0lJfj3rAkrbyOGCd1wZsCMSgrAOtXyBPD3L3vs2Aew0RLDsXN1bOLYqMoZLPANrwmq9I9zcWLEfjnHfsXgCAtEfDzatm3RsmEkK/FXrqBlv1hjw03WB7Df84SEoGU/W3Hk6FGsMT168BnMqlDFH+eWVwPY1iT7WYsjbFGtc+d7f88mdB07Vswf1gQ1PKooAMuQzYRgM+TylqtrCvb7H/bLt1On6ua+BEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQBEEQDZB27Vav3rNn3jy0o0fz7U9lqfWEzrUFBnzDBjwaPrzstyNGXLw4ceKAAez7+kuDEwADz9Lcvvnm/c+u/0LUewEw4Oxti3v3omUp0itK/RWiku8NrXswcOwFsMHBVbvKt9+ikFFRfD+PI/VWAAzY0qVoIyNRCJbG9vDhql21/glR75qge3eu7M24ISEoREkJnsfS4j7zTNXu9vbbeL116/h63npTA+4/qmFvY79+Hc9zccHA9eyJn1e1RnTpwvdz8y7A/QPvCHsndXWFOHAA7aRJfD8/b01Q5QLvDJYxIzy8Yk3TgQN4Xp8+fD23I3UuQM0E3hFnQly9ip9bLPg5e4l4/aHOBKidwDvCkgyxJom9nZ0NZ+vq3dYVp9YFqJvAO/LjjxjwV1+tm/tVnVrrhPkJ/MGDaN96q27uV31qvAbwFXgs8c8+Wzf3qzlqTAAKfNWodhPET+DZcLLhBp5R5RrAb+Drzzi+ulRagMqtx9cUD17gGRUWgAJfOzgVAAPO8nt99RVaCnxNU04nPH8+Wgp8bXG7BmCJZwmTLRa0CgXaEyfQtmpVO2789wLPcKgBLOCXLqH19cXAtG5d9vOa4r8beIaDAGzzOzwc7bVrWDOYEGw1sbpCUOAZDgK0aXPv01JSakYICrwjDgK0bHnv01jTVFUhKPDOcBCgvE62PCHi4sqe//vvFPj7I8BAsgTLf/+NtlOnyl2GddLJyWgXLsTAT53K9wPWd27VgNBQtM76gPJge7BWKwW+ctxKZ9u9O1rWxLCEygkJaK9fR3v5clnLPmdpbcXisn9PlMetgLHN67Fj0f7zD9rERCzRLJU5QRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRDEf496l0mP0anTtm0LF3755enTqamXLr38skCgULi6lp+Eh+MAAAQCgOLi7GyBYNmyPn3Gj58xY9q0du169+YvY54zxHw74AyRSCgUCn19AUQiiUSt5jiRSFwpb4VCiQRAJAIQCt3d+X4eZ9RbATiO4zhOpwPgOCz3HIelu+JXsNmwRnCcwcD38ziD91SG/3VIAJ4hAXiGBOAZEoBnSACeIQF4hgTgGRKAZ0gAniEBeIYE4BkSgGfqrQAWi81mtQIACASCertrUX3qrQBubjKZUslxAFYrS6xYOXA5WqkUi6XS8jdy+KLeChAcrFJ5eOj1AFar2VyVK+AGTm6uwVBSUn9TsAgefXTbtgULvvwSQCgUidzdceOjao9cfTgOS6zFEh+v1ebmPvFEWppWm5/fuDHujFXmWlhzwsJcXb29z55t1kyt9va+eLGkxGw2GlmyorrHYrFYTCaZLCDAxcXTMy5OALBixeDBHAcgFuOWX2V3nmoamw0bDJkMM1tKpRgu1idUFIFAKAQAMJlKS9HivphQKOS13qMfKpWbm79/ZqZYIFAqXV2Li3HP1c2NfwFwSx2AbbBXNvAMtpUpkcjlaFm55/f5xGKZDMDLS6FwdU1Pr5d9QG0FiO+CdS9/6qUA/yVIAJ4hAXhGaP8lGVGXsLiLAYqKsrNdXe3DUJuN784K769S4e/ZZDKVCv2q3GhIKMTn0emKigAAjMaSEvyG3+JmNhsMAKmpAAJBcLBgxYoLFw4eHDcOQCgUCHAiBlD3vyQTCgUCgYDjpFKhUCw2mb79Njb2r79Gjjx3LiMjLu6hhwDkcheXylzRYNBqAZ5/PiLiscd++aVXr6Cgli1//91gsFrNZpmsrp+PgWtccrm7u1Qql6ekiKdMad++Pv5o9Z13jh797rs2bc6dS0w8c6YqApSWajQAgwc3afLQQ9u2vf568+ZdumzZwvdzOVJvO+ErVwoLMzNdXQFksqotHGATlJ2t12u1vr58P49TL/l2wBklJdhW4hoV397UHvVWALGYBZ7/pZHapN4K8F+BBOAZEoBnSACeIQF4hgTgGRKAZ0gAniEBeIYE4BkSgGdIAJ4hAXim3r4rQq+3WEwmT0/7L9rwB00VB//ObLbZrFa1mu/ncUa9FSAkxMXFw+Ps2cxMd3d//+BguVwuV6v1+vL+ji1dl5QIBAKBQuHuLpMplQkJfD8PQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRANl1pPZ9O9+65dH30UEXHpUk5OYuLhwwUFJpPBoFIJBBKJXG4wsJQ6HFdSUlioVLZp4+0dGpqYOGlSly4vvfTMMyNGNG/epUthId+Bqi1q/Y1ZAoFAIBDI5ZgJIygIQCQSiQA4jiVoYDmN8FggABAIwsLw3w9y7oxbT13bN+A4juM4kwn/ZTDYM2I4swAcp9FwnD0d54NMHb01kZXyimbw+u8klqPXVvIMCcAzJADPkAA8QwLwTK0LgOP6yv+dzfZgJ3Bj1LoAZrPNZrEA2Gz21wrfTxAc/wMoFGKxVMp3eGqfWhfAzU0mUyrz8hQKgUAotNnseYEdZbDZbDYAFxexWCo1m195pWnTRx4pKOA7QLWNuHv33bs//LB5cwAAoVChwBmpyYRfV31ChPmBLRa1WiqVy5s0EQgEAuEtue/dtEgkUilAfr7FYjZLpaNHHz363XcdOsTE5ObeuKHTyeUSiVQqFjv764r5w3FGo8ViNstkHh4ymUKh0ezb17//lClJSbwJcOlSVlZS0rFjuEbj61tTAuBajsViMtlsVqtYXFwsEAgEMpk9Q7ZjG69QqNUA8fGlpcXFISHp6VevHjt28qRSKRZLpVhrOE5c5bUrXJPiOJvNbDaZZDKVSiZTqWJj8dtWrXgToKDAbDYYXFwAbDaRSCjEwMjl1b80xwHgG/9RRizhzksw+1woFAoBdDqz2WxWKHQ6kwlfWl/d5QmBAK9gNptMACaTUCiR1MRzVg8xLgtrtbg66eJSm+lj7Ytt9/8eqenwMAEAhEIApVIikck0Gp2udp61ooixZHFc7S+AVVbWmvbHcUGwfiz4iXEjxMfHnrm6pmoAW0wWibDlVird3Mp+X/Y+rJNmf6fT4TaMzYbn2Utw1WB/b7EYjQC5uRaLxeLtXfshvj/itm29vYOD4+Jw+8PTEwNjNjOnK3tBFlSZTCgUiYzGkhKbzWJRqeLi9HqNJjDQHui7/9JqBRAIOA7Aao2I8PBo1Cg9XaUSiSQSk8lsttlsNomkegJwHMdZLCaTVCoWy2QqVUrKv//yK4Bg48b4+OhoDw90UCLBEFZdADbh8vZWKNRqozE3V6fTaiMjZ878889vvjl+PDfXZNLrlUo26rFTUlJQANCmjZdXcHBi4gcfPPXUiBHduxcVGQw6nUZjtXJcdQRgG59mM8dxnFSqVAqFQqFe/+qr4eGPPqrR8CWAePjw5s27dq29Pdfnntu7d+XK7Gxs4gQCAKEQmyTHeTE2STIZbkRqtSaTXp+ZOWxYeHjnzg/uzlitz4SzsvR6jcbV1WJhUzEcZt4NfmsycZzNJhYbjVarxeLuzneAaps6WIqQSpXKso1ZRTr5+jFGqX1qXQCb7b+wtV51aD+AZ0gAniEBeIYE4BkSgGfq4LehbHkBlwLsazJ2y860f85xbObKd4Bqm1oXwGCw2cxmmcxiMZtNJrmcrccD4LKwXQCz2WgEsFoxj7DZXL2lh4ZCrQvg4SGVyuU6nYeHTKZSxcQIBEKhRCKVSiQSiUxmNLJyr9GYzWazUuniIpe7uKSmymQikUTC1qQIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiAIgiCI/yx1/oLgggKtVqsVCvV6k8lkCg52dVUqlUq1mr24DN+0a7PpdEaj0VhQEBDg4eHpmZXFd6Bqi1oTICenuLioyNs7K6uwsLBw4ECdzmg0GHr2LC01Go3Gtm0NBpPJZGraFF9eJhbfKQBmELDZbDaNBrMnXb8uk0mlYvGZM35+bm4eHr/80rSpv39AwIEDfAewutSYAHl5Gk1xsb9/YmJWVlbWlCnFxaWlJSWjR5tMFovV6uYmFAqFAgGASIRvSReJ8C3qjhnz7C/txrfJWa2YQYmdhwmiAcRioVAkunzZ29vV1dX1888ffrhp0/Dwdev4DmhlqbYAV66kpt64MXbszZt5ebm5H31ktVqtVqubm1QqFkskGCjMzVSzjmMNATAazWazGUChkMmk0jNnmjcPCAgM/N//QkJ8fHx9T5/mK7AVpcoCREfHxV29unFjfr5Wq9G8+SYLuEQiFmO6tfvlomFt+qVLaDMy0BqNaF1c0DZtirZ9e7SYFutemM0Wi8UCoNfjazFbtgwKCgmJioqICAwMCtq4ke9AO6PSAhw9euXKpUt792o0Op1O16+fUimXy2T4DlCWj+luNm9G+/33aI8de/rptm3bt2cBd84ff8TEXLjQqBEe9emDdvRotJ07336QW09isWDNuFOI4ODx48PDAwICA9eu5TvgjlRYgDNnEhLi47/7LiOjoKCg4I03XFzkcud5vv7+G+3kyRjoU6dq2nEUZvhwPFq9Gq2bG8vearFg38GEaN8+LKxJk0GDQkN9fHx9d+6suxDfn3IFSErKysrKGj48JubmzeTkDRtcXGQyuZylBnQ8++uvMeCshNY+KETjxnjERkXNmzP/TCZsmrCJ4rju3Vu3btMmMNDVVaFQKjMz68pPZzh9eTcOFz08rl/PysrIWL9eJsM2HpNiOp79zTd1HXgG3jc5GY86dUKbksL6IKmU9UkAAALB1aupqTdvbthQ1346w6kACQlZWRkZ8+cbDCaT0SiVymQSCUtyZefffzEAo0bx/SDoR3ExHvXujRYHrxwHoFLJZDIZQE5OUVFRUe/e2dlFRYWF3brx7fddAuh0BoNe7+aGE6hx43Ai5GxU8/rrfD+AIyhEfDweLVzIPnecX6Sm5ufn5c2axbe/dwmQlpafn58/ZIjBYDabTBKJRMJSEd7J9u34oFev8v0A92fxYrQFBazwKBRYk/PzNRqNpm9frVav1+vZKKvuuUsArVavLy197jmhEGesLMV4WerfcM4RLCCYuxtg06bbDyzEiSEmdgbAecyzz/Ll520BNJrSUp1OLMYS0a6dWCwSYXLPO8nLQ3viBF8OV439+519U1JiMOj19vlEXVOmBggEgYFms9VqtQYH33u0c/582ZLVULh8GS1LHWFfi9LrjUaTqVkzvjy7LQC6o1bj+NlZ6nD+x81Vg+XKzM6+81OBgC1/l00rWpfcFqBiWYTLXzqon7Aae7f/LNc8X57dUQMEAqGwvKSDbJGsoYHZ7AFcXR2/4bj7LxvWNrcFwB2q3Fxcf9fp2JpKWdiUv6EREIDW15d9UnZfITeXL89uC4AbG7m5CoVUKpMlJ7PFrLJ06IBrL2WTk9d/HnnE8RObDVdNlUq5XC7nbz5z1zzAw0OlcnH5+2+z2Wq1WBy/Zeuf/fvz5XDVGDz4rge/tUPn5qZUKpV//cWXZ3cJ4OXl6urqun07wP1y+k6ZwpfDFQVranAwHj3/PPvcYrFarVYArOlFRV5earVaffgwX37eJUBgoKenl9fBg2q1QiGXp6WZTLjlV5b27fEBX3mFL8crBpux46xGIGB9HYCfn7u7h8d338lkEolUajDw5aHT1dDGjX19/f3nzjUYcD393p3yN9+U3bHiH/TnjTfwaMAA9jkr+TKZVCqR4PP5+S1dyre/TgUIC/P19fPbsMHbW61Wq2NjS0uNRoPBcSNGoUB7/Dg+uLc3Xw+C9+/VC4+++459znFYgKxWpVKpBGjdul279u3fflulksvlcv4nluVmU23dOiQkNHToUJsNF+XYDlPZGsE2z//+GwPRpk1dPQDeLyoKjw4eZJ9zHJZ4qTQ4ODgYwGC4fPnyZQCN5ueft21jPwbgnwrvCd+8mZubk/P66+fOJSUlJHz/vUqFW5M4jnZcNWX/mjcP7dq1uIbElgSqDgY8MhKP5s9HO3So/c6sqQkKCgoCsFgKCvLzAWJjhwx55RUAgyEpKSnJYOjR49NPP/100KAOHaKioqJ++63eC8BISsrOzsr63/9iYm7cSE5es4ZtVdp3zO41r8zPR/vzz2jZ6mRMTNnvWXevVKL180PbpQvavn3RDhp0y/3b/uMPGgHk8tDQ0FAAkykrKysLICnpf/8bPx7AYIiLu3YNgOPUarUaoLQ0Nzc3F6B793nz5s176aVHH50wYcKEHTvqvQCMtLT8/Ly8QYNQiO+/N5stFqtVoWBbf2w19f6TfBZw9jshtlrJljyYAPdw/FZfxH6GYrFgAdDrY2IuXQIoKPj00zVrsMQnJwPIZNgUMdFMJq1WqwXQ6bKzs7MBnnxywYIFC158sXPn8ePHj9+1q64EqHJG7aAgLy9v7x07nniiRYvWrVu3Dgjw8PDw2LULN/MBSkqw02YzznvD8gWz8TrrS5wHno1mNJrS0tJSAI4TCoVCgyEyMjAwKGj2bKXyyJE//9yyJT09Ojo6GkAqDQnBq3Mc9mOsb3BxcXEBUKl8fX19AY4cmTNnzpydO8+f//rrr79+6aW6EqDGf5ybmVlYWFDQu3daWl5eXt5bbxUUlJRotX37Yuctk7G+gq3Hs87csaawpoz9BJHNXFUqqVQmy8ry8XFzc3P7+efQUB8fP7/Vq/FX1ikp7O9/+WX06NGj9+27fPmHH3744bnnvLwiIiIi7Dti7PoCAdsh02g0GgCDobi4uBigT59PPvnkkzFjWrceOnTo0C+/bDACOKLR6PWlpWFhhYVarVb7xBMlJQaDwdC5M/5aulkzDIS7O2tS8HcMNhvuRWdlYZN27RoG+ORJT0+1Wq0+ehR/LKDVlnf/AwcmTpw4ccuWs2fXr1+//tVXvb0jIyMjAYRC3PFjQrDj0tKCgoICex/Rv/9XX3311ZgxrVsPGTJkSM0LUef/P4AvDh6cMmXKlE2bTp/+7LPPPhs2zMenRYsWLe4WQiDAY4OhsLCwEECny8nJyQHo12/9+vXrx45t0+bll19+ef36mvKryn1AQ6N37xUrVqx4441Ond555513Nm/OzY2NjY0FsFpxqYU1RayPUCg8PDw87H3E/v0TJkyY8MUXWJOmTq0pv/4zAjBQiGHDunadPHny5G++KShISEhIALBYDAac6bP/t4BCyOUohELh6enpCXDw4KRJkyYtWxYdvXLlypXvv19df/5zAjCefvqDDz74YNSoxx6bOXPmzE8/tQuBozjHGiGT4fzBzS0sLCwM4OjR+fPnz1+4EIWYO7eqfvxn+oDyOHZs0aJFi9asOXHio48++uh///PwaNy4cWMAsVihUCjsEz0mjNms0+l0AFotTvi6dZs+ffr0BQsef3zmzJkz2Qy9fEgAB44f/+CDDz745JO//lq8ePHiCRNYiZdKVSqV6m4hLBa9Xq8HKCq6cePGDYCHHho9evToTz559tmVK1eunDixvPuRAE44ffrzzz///P33Dx2aNm3atIUL3dxCQkJC7BO4u4XAPsQuxKhRo0atWYNCTJjg7D7/2T6gPDp1evvtt99etKhXr+XLly+fO1ejSU9PTwcwmbDpsfcRKIRYjEswHh5YY86eXbdu3brx42NitmzZsmXcOGf3IQHKoWPHcePGjVu0qGfPjz/++ON584qKkpOTk+0zZzZvYPMIkQiFYE3W1avbt2/fPn68s+uTABWkY8exY8eOXbiwX78vvvjii8mT2QTNYMCZM5vQsRm91YpbnyhIaSnf/j9wXL68devWrWPGLF3q6enpyXFLlqhUKpXdss9TUo4ePXqULaPfDXXC1eTmzejo6OjevS9c2LBhw4a33mKfd+gwYsSIEV9+GRzcpUuXLvadOoIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgCIIgiEpQY++Mi41NTb15s2lTtVqhUKmaNJHLpVKJRKGwWKxWi8VkSkzMysrKSklxcVEo5PLk5HbtwsKaNGmo6XFrjioLcP16RkZ6upubTmc0Go29emFChiefxKxKERESiVgsFstkVqvVarWazRqNXq/XJyS4u6tUSuWpU5hIeffujh2bNYuIqH52pYZKhQWIjU1PT00VCjEnzDvvZGTk5+fnT55ss3EcQFgYy76K+S/uTBCNSXMwI4Y9FQl+mp6O53z5ZUiIt7ePz8cfR0QEBgYH85dasK4pV4Bjx65cuXw5MNBqtdkslp07MUlPp05SqVgsFmMuGJGInc3y8rL0sCw9lVqNAW/bFmXx88NUJQBmMyaGwyYrNrZRIw8PL6/hwyMjg4KCg0+f5jtAtY1TAS5cSE5OSvL1xaQ8hw5hyW7bFnO3AOA7YmNj8ZW9LGnmzz9jwjYWeDuYgM3DA4/69sX3y06ciLXh4YexCQMQiUQikSg3t1WrkJDQ0MceCwnx8vLxiY/nO1C1hVMB/vzz8uWYmL//1ukMBr2+c2elUiqVy1nGvC++wLMmTcKAV73JQGGWLMGsSrNnY5Iflm725s2OHcPDw8Pbt3d1VSiUygevr7jr3dGJiVlZGRljxxYV6XQlJZ07KxRSqVTKAv/llxjwceOqG3gGXue99zBd1eLFLBGcVqvXl5aGhCQmZmZmZFQ9Q0V953YNKC7W6UpK1OqzZxMTr19PSMDMeL6+mKIwPr5HjzZt2rWLiKhth44ciYm5cOHwYcw79vTT+KnF0rFjeHjz5k2aeHmp1a6uqal8B66mEGZmFhbm54tE2NY/95zBYDZbLL6+OIxkeb2WL68rh7CTnjdPKsXUhEaj2Ww2i8WFhSUlJSUvvsh3wGoaIY7bGzfW681ms/mpp3Dczr5mbS5LwllXREfjqCk2ViQSi0UigLw8rba4uHt3vgNW0wix7W3cGHM0NmtWNmHzhQvYRms0deUQ3o/NIi5fZikPjUaz2WIJDT17NiEhPt4+8G3oCPEBVSqRSCAQCuXysl8XFPDrXk5O2cTRmIsS4AESwGKx2TjOaLRaOc5mY+lkGSytLF94epY9tlhwjm1vJBs6QoPBZDKZkpI4zmbjuOTksk1Qhw44Tlep6tox9KFNG6sVlzikUpFILMZ5QUTEAyQAhjslRamUy+XykydFIlyrQXx90T77bF05hIK3a4dNTatWFovVarMBeHqq1S4u0dF8B6ymEYaF+fr6+RmNmCZ2504cfhYV4TyAJaWZPbuuHML7zZ9vMplMJpNAgK09x/n7e3h4edV9yvHa5vZMuFEjDw9Pz8JCDw8XF7V61SqDwWw2mVhT8NBDWDLnzastR/7449KlixfHjrXZjEaT6YUXbDaVSqkEaNasbdu2bT//3M1NqVQqr1/nO2A1zV1LEU2a+Pr6+S1d6uHh4qJSXbtWXIyp+jAT9fz5KMTChTXlAF5vzBibzWAwGNatE4sbNfL3BxCJSkv1eptNJDp16u+/ay+jNd84XYzLyCgoyM9v1+7ixRs3kpOPHbNYLBar1c3NxUUuZ4tyAAcO4Goomyn/9ReO4x1HU3Yw4F27YlMzfrzNZjKZTC+/LJUGBQUFAYjFbm6urgCXLvXu3acPx5nNV65cvXrhwkMPzZw5c+aAAV27Tp06dWpaGt+Bq3UBGCkpOTnZ2eHhyck5OVlZu3drtaWlBkPLllKpWCwUAkilYrFEwtruK1dQmGvX8K8zM9F6eWFTFhGB33foYDJhImWOUyqVSgCBQKPRagFSU+fMef99AJMpJubSJQC9HmfCcrlarVbn5HTqNH78+PG9emGqwYsX+Q5grQvAKCjQarVaT8/ExKyszMxZs3C1dMwYvd5kMpnUapFIJBIKcYNGeKthE9xxdbbEwXbOZDKRSCw2mcLCWrVq1WrNmuzszz77/PO4uJMnp0yZOvWrr9RqTDnu4uLn5+cHkJ8fFxcXByCXe3p6et68+fTTS5YsWfL00y1aDBw4cGBCAt+BrHUBHElKysrKzGzWzGCwWMzmZ58tKSkt1esff1yvN5tNpqZN8SyFAq3RiFuSN296e7u5ubqePKlUSiQSyW+/BQV5e/v6XrnCrrtz5+DBQ4YMHJia+u+/58/v3Mk2N11dsYnKz4+Pj48HUCp9fHx8ioqefHL+/Pnz+/Rp2fLFF1988e+/+Q5onQngDFyrEYttNgAANqew2Tp2bNaseXOLpaLXOXBg0qRJkwYPjovbvXv37p9+wuylQiETIjf3ypUrVwDU6sDAwMCcnK5dp0+fPv2ZZ9q1e+211167dInvwFaUep/K8NChGTNmzOjT5+rVHTt27Ni3z2azWCwWgcDDIzQ0NBQgLw9TkWMfodU+/PC4cePGDRzYpcu777777h9/8O1/edT7bKo9ey5dunTp/v1t277++uuvv/CCSCSRSCQmE0uc7OUVHh4eDmAwFBcXF6vV586tX79+/a5dJ0+uXLlyZefOfPtfHvW+Bjhy4sTSpUuX9uhx/vxXX3311f79ZrNer9fLZJ6ezZo1awZQXIzCYBpZna5Jk549e/Z8+eW+fdeuXbv211/59t+Rel8DHHnssRkzZsz488+OHcePHz++f3+ZzNXV1bWkpKAgMTExEcDNDZsmq9VgMBhUqmvXfvnll1927jxzZt26deu6dePbf0canAAMbOMPHerWbfr06dOffhozWGs0ubmxsbGxAJ6ezZs3bw6AA2CJ5OLFTZs2bdq4kW+/HWmwAjA6dIiKioo6ffrxx2fPnj17wAC12t/f37+wMD393Llz5wBKSoqKiooAJBKlUqnU6fj294EnPv633377LSJi8+Z+/fr1279/8+b+/fv337//xo3jx48fDw/n2z+CIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiCIAiC4J11665ePXbskUdiYgoKMjLUar79+c9w8mR2dnJyWBjAokU9e3Kcp+cXX4waFRt74UJ+flqaqyvf/jnS4F5d7IzERK02L08qbdly48bJkxMSjEazWa8PDgYwm41GAIXCxcXTMzl5+/Z+/SZP7t+/b9/Q0LZt7a/N54sG/+JWxoABv/yyfPmhQ0ZjSUl+fnAwgFrt7Q0A4OkZGAig1xuNOl3jxn37bt06f/6FC3Pm/PPPrl0jR/Ltd4MX4Kmnfvll2bIvvrhyJTn5/PknngDw8goOBgDATB126+aGWdF0usJCsXj79qSks2dHjODb/wYrwIQJJ0/+9NO77x45cuXKn3+OGQPg4xMSAsAybtzxiLdy3ufm3rwJ0KhRcHDr1gkJZ84MGjRnTs+efD9HgxPgq6/i4k6c6Nnz00+PHPnmm9Wr7SWbBZpleGLHGk1uLoBIJJe7uBgMR4++9NL773fvrlZLpQpFaSnfz9NgBNiz58aNmJimTUeP3rt3xYoDBwBcXTHwEgnmgGUlXyDAJEJ6vVYLAGAy6fUA+/a99NL77z/1VPPmbm6+vhkZfD8PQ8y3A+WRkqLV5udLJC1afP/91KnHjwOwECuVOKhkbTxLQmqxYBaz4uLsbIBPPx04cNasUaOefTYoqGXLU6f4fh5H6n1e3q1bw8MNhj//LCwsLMzMbN0awMMjIADAHnhHcnNTUgDeeqt79zfeWLFi8eJOnV54YelSvp/DGfW2CerVa8+e5cvXr8/IyMpKSHjiCeeBt3eyKSkA3bu3afP007/99uWX3bu/8cbUqXw/R3k4FWDDhri4kycffbSuHRo37vjxzZsnTvz99/Pn9+176y0AL6/AQADWtd7h+q3A5+enpgKEhDRqFBkZH3/s2MCBs2b17VvXfleVuwTYsiUx8cyZbt2ion788b33Tp2KjNy0acqU33+vbUdWrbp8+ciR3r3XrYuO/umnVasAfHxCQwHsneq9RzcCgVzu4mI0Hj8+ePC8ed278x3QynJbgFOncnKSkxs1eu21nTs//PDQIQAPD39/gLi49PTY2J49g4K+/XbChNOno6Ozs5OSsDGoCfC+TZtOmvTrr6tWHTiAGcEAAKRSZ6MbjQaALTEcPDh48Lx5PXqEhanVXl5ZWXwHtLII4+OLirKyFIqBA/fsWbbs6FF8ZIUCQKXy8AAA8PYODQVIS8vPT03t2LFr182bp0+/cGHLlvj4U6ceeaSqN46PLy7OzpbJevXavn3RomPHAMRiqRQAQKVydwcAsNkwG5/j6KaoKDsbYPXqvn0nTRoxolevwMAWLerf6KbCAnTsuGPH4sWHD2dlpaZevRoebm9zHafy7u5+fgCYWdjX97XX9uxZtuzMmfff/+efnTtfeaWyNx4wYO/eVav++EOrLSrKzAwMtE+oHDtZVgPy8m7cABg37skn33xz2bKJE9u0eeqpDRv4DmB1ES5Z0qnTCy9s3IijDJsNIC8Ps/XaZ5YIK5EuLl5eAAAymVIJsGjRoUNffPHDD6NG/fHH11+/9155N+zZc8+eFSu++iou7saNCxe6dQPw9sYlBOejmxs3AJ54onXrZ57Zt2/duieeGDZs+nS+A1dT3F6OPnUqOzspqU2b55/fvfujj/bsycnJz09NDQtjTdCdayxl22SrFZuG/Py0NIDHHouIeOyxTZtOnBg8eO7cN99k1582LTp669ZJk5YtO3Lkm29WrgTw9sZFM5Y33rGTzctLTQUIDPTza9Lk2rX09BEjPv00MpLvgNWaAIysLL1eq3Vz69Nn587Fi/fu/fffpKTz5x9/HMDHJywMA4SBt3eOLGMq1pCiosxMgO7dIyMff/znn3v0aNQoImL//vnz//pry5aNGwHkcpUKAEAikcnuvI59dJOTAyAWi8UymV4fFxcV9cknTZs2a+bq6uPDEkQ/OJS7ITN06L59q1d/883PP5879+uvI0bY+wiJBLMFcxwGniVwZmmcdbqiIgAAqxWT2LLOVSSSSO78O1aTDAZcuyktLS4GOHx42LAVKzp3fuaZwMCIiNOn+Q5UbVHuTPjnn/v2nThx5Mjp0596asSIOXMAiopycgAA9PriYoC7VyFZiWZrNS4unp53nmcPPBvdGI0AAMXFubkAa9f27z91alTUgx54RqW3JDdsuHr1+PGhQ6Oi9u1bufKnn+wl2M3N3x8AwGareNpmAIDs7KQkHN1ERX388bp1Tzzx2mszZvAdmLqiynvCR49mZFy71rHjgAG7dn344b59Gk1xcU6Oj499Y4T1CY6wmpCdnZgI0KNH69ZPP713759/vvDCjBkDBvAdkLqm2pvyKSklJQUFfn79+u3YsWTJr79evpyaeunSI4/YO23W1LCagqObsDB//2bNYmNTUqKiVq9u2ZLvQPBFjf8qok+f3bs/+mjbtv37Y2IOH37pJQBfXxQCO1ehUCSSSPT6lJSRIz/7LCwsJMTFxcMDexWiBpk06dixTZs++ADg/fcff5zjAJYs6d2b4/74Iz09Lq7+pxp/YJgx48SJH36YM2fBgnPn9u2bNIlvfwiCIIjb/B/7w7TJ1Po+fAAAAABJRU5ErkJggg==);background-size:24px 352px}}.jsgrid .jsgrid-mode-button{width:24px;height:24px}.jsgrid-mode-on-button{opacity:.5}.jsgrid-cancel-edit-button{background-position:0 0;width:16px;height:16px}.jsgrid-clear-filter-button{background-position:0 -40px;width:16px;height:16px}.jsgrid-delete-button{background-position:0 -80px;width:16px;height:16px}.jsgrid-edit-button{background-position:0 -120px;width:16px;height:16px}.jsgrid-insert-mode-button{background-position:0 -160px;width:24px;height:24px}.jsgrid-insert-button{background-position:0 -208px;width:16px;height:16px}.jsgrid-search-mode-button{background-position:0 -248px;width:24px;height:24px}.jsgrid-search-button{background-position:0 -296px;width:16px;height:16px}.jsgrid-update-button{background-position:0 -336px;width:16px;height:16px}.jsgrid-load-shader{background:#ddd;opacity:.5;filter:alpha(opacity=50)}.jsgrid-load-panel{width:15em;height:5em;background:#fff;border:1px solid #e9e9e9;padding-top:3em;text-align:center}.jsgrid-load-panel:before{content:' ';position:absolute;top:.5em;left:50%;margin-left:-1em;width:2em;height:2em;border:2px solid #009a67;border-right-color:transparent;border-radius:50%;-webkit-animation:indicator 1s linear infinite;animation:indicator 1s linear infinite}@-webkit-keyframes indicator{from{-webkit-transform:rotate(0deg)}50%{-webkit-transform:rotate(180deg)}to{-webkit-transform:rotate(360deg)}}@keyframes indicator{from{transform:rotate(0deg)}50%{transform:rotate(180deg)}to{transform:rotate(360deg)}}
294coder/Efficient-MIF
3,463
utils/loss_landscape/mpi4pytorch.py
""" mpi4pytorch.py This module contains convenience methods that make it easy to use mpi4py. The available functions handle memory allocation and other data formatting tasks so that tensors can be easily reduced/broadcast using 1 line of code. """ import numpy as np import mpi4py def setup_MPI(): try: from mpi4py import MPI comm = MPI.COMM_WORLD # Convert the Object to a Class so that it is possible to add attributes later class A(mpi4py.MPI.Intracomm): pass comm = A(comm) except: comm = None return comm def print_once(comm, *message): if not comm or comm.Get_rank()==0: print (''.join(str(i) for i in message)) def is_master(comm): return not comm or comm.Get_rank()==0 def allreduce_max(comm, array, display_info=False): if not comm: return array array = np.asarray(array, dtype='d') total = np.zeros_like(array) float_min = np.finfo(np.float).min total.fill(float_min) if display_info: print ("(%d): sum=%f : size=%d"%(get_rank(comm), np.sum(array), array.nbytes)) rows = str(comm.gather(array.shape[0])) cols = str(comm.gather(array.shape[1])) print_once(comm, "reduce: %s, %s"%(rows, cols)) comm.Allreduce(array, total, op=mpi4py.MPI.MAX) return total def allreduce_min(comm, array, display_info=False): if not comm: return array array = np.asarray(array, dtype='d') total = np.zeros_like(array) float_max = np.finfo(np.float).max total.fill(float_max) if display_info: print ("(%d): sum=%f : size=%d"%(get_rank(comm), np.sum(array), array.nbytes)) rows = str(comm.gather(array.shape[0])) cols = str(comm.gather(array.shape[1])) print_once(comm, "reduce: %s, %s"%(rows, cols)) comm.Allreduce(array, total, op=mpi4py.MPI.MIN) return total def reduce_max(comm, array, display_info=False): if not comm: return array array = np.asarray(array, dtype='d') total = np.zeros_like(array) float_min = np.finfo(np.float).min total.fill(float_min) if display_info: print ("(%d): sum=%f : size=%d"%(get_rank(comm), np.sum(array), array.nbytes)) rows = str(comm.gather(array.shape[0])) cols = str(comm.gather(array.shape[1])) print_once(comm, "reduce: %s, %s"%(rows, cols)) comm.Reduce(array, total, op=mpi4py.MPI.MAX, root=0) return total def reduce_min(comm, array, display_info=False): if not comm: return array array = np.asarray(array, dtype='d') total = np.zeros_like(array) float_max = np.finfo(np.float).max total.fill(float_max) if display_info: print ("(%d): sum=%f : size=%d"%(get_rank(comm), np.sum(array), array.nbytes)) rows = str(comm.gather(array.shape[0])) cols = str(comm.gather(array.shape[1])) print_once(comm, "reduce: %s, %s"%(rows, cols)) comm.Reduce(array, total, op=mpi4py.MPI.MIN, root=0) return total def barrier(comm): if not comm: return comm.barrier() def get_mpi_info(): try: return mpi4py.MPI.get_vendor() except ImportError: return "none" def get_rank(comm): try: return comm.Get_rank() except ImportError: return 0 def get_num_procs(comm): try: return comm.Get_size() except ImportError: return 1
29jitender/Spotlight
1,417
Spotlight-library/src/main/java/com/wooplr/spotlight/shape/Circle.java
package com.wooplr.spotlight.shape; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import com.wooplr.spotlight.target.Target; /** * Created by jitender on 10/06/16. */ public class Circle { private Target target; private int radius; private Point circlePoint; private int padding = 20; public Circle(Target target, int padding) { this.target = target; this.padding = padding; circlePoint = getFocusPoint(); calculateRadius(padding); } public void draw(Canvas canvas, Paint eraser, int padding) { calculateRadius(padding); circlePoint = getFocusPoint(); canvas.drawCircle(circlePoint.x, circlePoint.y, radius, eraser); } private Point getFocusPoint() { return target.getPoint(); } public void reCalculateAll() { calculateRadius(padding); circlePoint = getFocusPoint(); } private void calculateRadius(int padding) { int side; int minSide = Math.min(target.getRect().width() / 2, target.getRect().height() / 2); int maxSide = Math.max(target.getRect().width() / 2, target.getRect().height() / 2); side = (minSide + maxSide) / 2; radius = side + padding; } public int getRadius() { return radius; } public Point getPoint() { return circlePoint; } }
29jitender/Spotlight
6,153
Spotlight-library/src/main/java/com/wooplr/spotlight/utils/SpotlightSequence.java
package com.wooplr.spotlight.utils; /** * Created by Carlos Reyna on 30/07/16. */ import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.View; import com.wooplr.spotlight.SpotlightConfig; import com.wooplr.spotlight.SpotlightView; import com.wooplr.spotlight.prefs.PreferencesManager; import java.util.LinkedList; import java.util.Queue; /** * Class responsible for performing a sequence of * spotlight animations one after the other. */ public class SpotlightSequence { private Activity activity; private SpotlightConfig config; private Queue<SpotlightView.Builder> queue; private static SpotlightSequence instance; private final String TAG = "Tour Sequence"; /** * Creates an instance of SpotlightSequence * with an empty queue and a {@link SpotlightConfig} configuration * @param activity where this sequence will be executed * @param config {@link SpotlightConfig} */ private SpotlightSequence(Activity activity, SpotlightConfig config){ Log.d(TAG,"NEW TOUR_SEQUENCE INSTANCE"); this.activity = activity; setConfig(config); queue = new LinkedList<>(); } /** * Retriebes the current instance of SpotlightSequence * @param activity where this sequence will be executed * @param config {@link SpotlightConfig} * @return If no instance was found. {@link SpotlightSequence()} will be called. */ public static SpotlightSequence getInstance(Activity activity, SpotlightConfig config){ if(instance == null){ instance = new SpotlightSequence(activity,config); } return instance; } /** * Adds a new SpotlightView.Builder object to {@link this.queue} * @param target View where the spotlight will focus * @param title Spotlight title * @param subtitle Spotlight subtitle * * @param usageId id used to store the SpotlightView in {@link PreferencesManager} * @return SpotlightSequence instance */ public SpotlightSequence addSpotlight(View target, String title, String subtitle, String usageId){ Log.d(TAG, "Adding " + usageId); SpotlightView.Builder builder = new SpotlightView.Builder(activity) .setConfiguration(config) .headingTvText(title) .usageId(usageId) .subHeadingTvText(subtitle) .target(target) .setListener(new SpotlightListener() { @Override public void onUserClicked(String s) { playNext(); } }) .enableDismissAfterShown(true); queue.add(builder); return instance; } /** * Adds a new SpotlightView.Builder object to {@link this.queue} * @param target View where the spotlight will focus * @param titleResId Spotlight title * @param subTitleResId Spotlight subtitle * @param usageId id used to store the SpotlightView in {@link PreferencesManager} * @return SpotlightSequence instance */ public SpotlightSequence addSpotlight(@NonNull View target, int titleResId, int subTitleResId, String usageId){ String title = activity.getString(titleResId); String subtitle = activity.getString(subTitleResId); SpotlightView.Builder builder = new SpotlightView.Builder(activity) .setConfiguration(config) .headingTvText(title) .usageId(usageId) .subHeadingTvText(subtitle) .target(target) .setListener(new SpotlightListener() { @Override public void onUserClicked(String s) { playNext(); } }) .enableDismissAfterShown(true); queue.add(builder); return instance; } /** * Starts the sequence. */ public void startSequence(){ if(queue.isEmpty()) { Log.d(TAG, "EMPTY SEQUENCE"); }else{ queue.poll().show(); } } /** * Free variables. Executed when the tour has finished */ private void resetTour() { instance = null; queue.clear(); this.activity = null; config = null; } /** * Executes the next Spotlight animation in the queue. * If no more animations are found, resetTour()is called. */ private void playNext(){ SpotlightView.Builder next = queue.poll(); if(next != null){ // Log.d(TAG,"PLAYING NEXT SPOTLIGHT"); next.show().setReady(true); }else { Log.d(TAG, "END OF QUEUE"); resetTour(); } } /** * Clear all Spotlights usageId from shared preferences. * @param context */ public static void resetSpotlights(@NonNull Context context){ new PreferencesManager(context).resetAll(); } /** * Sets the specified {@link SpotlightConfig} configuration * as the configuration to use. * If no configuration is specified, the default configuration is used. * @param config {@link SpotlightConfig} */ private void setConfig(@Nullable SpotlightConfig config) { if(config == null){ config = new SpotlightConfig(); config.setLineAndArcColor(Color.parseColor("#eb273f")); config.setDismissOnTouch(true); config.setMaskColor(Color.argb(240,0,0,0)); config.setHeadingTvColor(Color.parseColor("#eb273f")); config.setHeadingTvSize(32); config.setSubHeadingTvSize(16); config.setSubHeadingTvColor(Color.parseColor("#ffffff")); config.setPerformClick(false); config.setRevealAnimationEnabled(true); config.setLineAnimationDuration(400); } this.config = config; } }
294coder/Efficient-MIF
6,367
utils/loss_landscape/plot_1D.py
""" 1D plotting routines """ from matplotlib import pyplot as pp import h5py import argparse import numpy as np def plot_1d_loss_err(surf_file, xmin=-1.0, xmax=1.0, loss_max=5, log=False, show=False): print('------------------------------------------------------------------') print('plot_1d_loss_err') print('------------------------------------------------------------------') f = h5py.File(surf_file,'r') print(f.keys()) x = f['xcoordinates'][:] assert 'train_loss' in f.keys(), "'train_loss' does not exist" train_loss = f['train_loss'][:] train_acc = f['train_acc'][:] print("train_loss") print(train_loss) print("train_acc") print(train_acc) xmin = xmin if xmin != -1.0 else min(x) xmax = xmax if xmax != 1.0 else max(x) # loss and accuracy map fig, ax1 = pp.subplots() ax2 = ax1.twinx() if log: tr_loss, = ax1.semilogy(x, train_loss, 'b-', label='Training loss', linewidth=1) else: tr_loss, = ax1.plot(x, train_loss, 'b-', label='Training loss', linewidth=1) tr_acc, = ax2.plot(x, train_acc, 'r-', label='Training accuracy', linewidth=1) if 'test_loss' in f.keys(): test_loss = f['test_loss'][:] test_acc = f['test_acc'][:] if log: te_loss, = ax1.semilogy(x, test_loss, 'b--', label='Test loss', linewidth=1) else: te_loss, = ax1.plot(x, test_loss, 'b--', label='Test loss', linewidth=1) te_acc, = ax2.plot(x, test_acc, 'r--', label='Test accuracy', linewidth=1) pp.xlim(xmin, xmax) ax1.set_ylabel('Loss', color='b', fontsize='xx-large') ax1.tick_params('y', colors='b', labelsize='x-large') ax1.tick_params('x', labelsize='x-large') ax1.set_ylim(0, loss_max) ax2.set_ylabel('Accuracy', color='r', fontsize='xx-large') ax2.tick_params('y', colors='r', labelsize='x-large') ax2.set_ylim(0, 100) pp.savefig(surf_file + '_1d_loss_acc' + ('_log' if log else '') + '.pdf', dpi=300, bbox_inches='tight', format='pdf') # train_loss curve pp.figure() if log: pp.semilogy(x, train_loss) else: pp.plot(x, train_loss) pp.ylabel('Training Loss', fontsize='xx-large') pp.xlim(xmin, xmax) pp.ylim(0, loss_max) pp.savefig(surf_file + '_1d_train_loss' + ('_log' if log else '') + '.pdf', dpi=300, bbox_inches='tight', format='pdf') # train_err curve pp.figure() pp.plot(x, 100 - train_acc) pp.xlim(xmin, xmax) pp.ylim(0, 100) pp.ylabel('Training Error', fontsize='xx-large') pp.savefig(surf_file + '_1d_train_err.pdf', dpi=300, bbox_inches='tight', format='pdf') if show: pp.show() f.close() def plot_1d_loss_err_repeat(prefix, idx_min=1, idx_max=10, xmin=-1.0, xmax=1.0, loss_max=5, show=False): """ Plotting multiple 1D loss surface with different directions in one figure. """ fig, ax1 = pp.subplots() ax2 = ax1.twinx() for idx in range(idx_min, idx_max + 1): # The file format should be prefix_{idx}.h5 f = h5py.File(prefix + '_' + str(idx) + '.h5','r') x = f['xcoordinates'][:] train_loss = f['train_loss'][:] train_acc = f['train_acc'][:] test_loss = f['test_loss'][:] test_acc = f['test_acc'][:] xmin = xmin if xmin != -1.0 else min(x) xmax = xmax if xmax != 1.0 else max(x) tr_loss, = ax1.plot(x, train_loss, 'b-', label='Training loss', linewidth=1) te_loss, = ax1.plot(x, test_loss, 'b--', label='Testing loss', linewidth=1) tr_acc, = ax2.plot(x, train_acc, 'r-', label='Training accuracy', linewidth=1) te_acc, = ax2.plot(x, test_acc, 'r--', label='Testing accuracy', linewidth=1) pp.xlim(xmin, xmax) ax1.set_ylabel('Loss', color='b', fontsize='xx-large') ax1.tick_params('y', colors='b', labelsize='x-large') ax1.tick_params('x', labelsize='x-large') ax1.set_ylim(0, loss_max) ax2.set_ylabel('Accuracy', color='r', fontsize='xx-large') ax2.tick_params('y', colors='r', labelsize='x-large') ax2.set_ylim(0, 100) pp.savefig(prefix + '_1d_loss_err_repeat.pdf', dpi=300, bbox_inches='tight', format='pdf') if show: pp.show() def plot_1d_eig_ratio(surf_file, xmin=-1.0, xmax=1.0, val_1='min_eig', val_2='max_eig', ymax=1, show=False): print('------------------------------------------------------------------') print('plot_1d_eig_ratio') print('------------------------------------------------------------------') f = h5py.File(surf_file,'r') x = f['xcoordinates'][:] Z1 = np.array(f[val_1][:]) Z2 = np.array(f[val_2][:]) abs_ratio = np.absolute(np.divide(Z1, Z2)) pp.plot(x, abs_ratio) pp.xlim(xmin, xmax) pp.ylim(0, ymax) pp.savefig(surf_file + '_1d_eig_abs_ratio.pdf', dpi=300, bbox_inches='tight', format='pdf') ratio = np.divide(Z1, Z2) pp.plot(x, ratio) pp.xlim(xmin, xmax) pp.ylim(0, ymax) pp.savefig(surf_file + '_1d_eig_ratio.pdf', dpi=300, bbox_inches='tight', format='pdf') f.close() if show: pp.show() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Plott 1D loss and error curves') parser.add_argument('--surf_file', '-f', default='', help='The h5 file contains loss values') parser.add_argument('--log', action='store_true', default=False, help='logarithm plot') parser.add_argument('--xmin', default=-1, type=float, help='xmin value') parser.add_argument('--xmax', default=1, type=float, help='xmax value') parser.add_argument('--loss_max', default=5, type=float, help='ymax value') parser.add_argument('--show', action='store_true', default=False, help='show plots') parser.add_argument('--prefix', default='', help='The common prefix for surface files') parser.add_argument('--idx_min', default=1, type=int, help='min index for the surface file') parser.add_argument('--idx_max', default=10, type=int, help='max index for the surface file') args = parser.parse_args() if args.prefix: plot_1d_loss_err_repeat(args.prefix, args.idx_min, args.idx_max, args.xmin, args.xmax, args.loss_max, args.show) else: plot_1d_loss_err(args.surf_file, args.xmin, args.xmax, args.loss_max, args.log, args.show)
281677160/openwrt-package
6,459
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_event_timer_module.c
/* * Copyright (C) AlexWoo(Wu Jie) [email protected] */ #include "ngx_event_timer_module.h" static ngx_int_t ngx_event_timer_process_init(ngx_cycle_t *cycle); static void *ngx_event_timer_create_conf(ngx_cycle_t *cycle); static char *ngx_event_timer_init_conf(ngx_cycle_t *cycle, void *conf); typedef struct { ngx_uint_t timerid; ngx_event_t event; ngx_timer_handler_pt handler; void *data; } ngx_event_timer_ctx_t; typedef struct { ngx_uint_t timer_n; ngx_event_timer_ctx_t *timer_ctx; /* array to store timers */ ngx_event_timer_ctx_t *free_timers; /* timer unused */ ngx_uint_t free_timer_n; } ngx_event_timer_conf_t; static ngx_str_t event_timer_name = ngx_string("event_timer"); static ngx_command_t ngx_event_timer_commands[] = { { ngx_string("worker_timers"), NGX_EVENT_CONF|NGX_CONF_TAKE1, ngx_conf_set_num_slot, 0, offsetof(ngx_event_timer_conf_t, timer_n), NULL }, ngx_null_command }; ngx_event_module_t ngx_event_timer_module_ctx = { &event_timer_name, ngx_event_timer_create_conf, /* create configuration */ ngx_event_timer_init_conf, /* init configuration */ { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL } }; /* this module use ngx_cycle->log */ ngx_module_t ngx_event_timer_module = { NGX_MODULE_V1, &ngx_event_timer_module_ctx, /* module context */ ngx_event_timer_commands, /* module directives */ NGX_EVENT_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ ngx_event_timer_process_init, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static void * ngx_event_timer_create_conf(ngx_cycle_t *cycle) { ngx_event_timer_conf_t *conf; conf = ngx_pcalloc(cycle->pool, sizeof(ngx_event_timer_conf_t)); if (conf == NULL) { return NULL; } conf->timer_n = NGX_CONF_UNSET_UINT; return conf; } static char * ngx_event_timer_init_conf(ngx_cycle_t *cycle, void *conf) { ngx_event_timer_conf_t *etcf = conf; ngx_conf_init_uint_value(etcf->timer_n, 1024); return NGX_CONF_OK; } static ngx_int_t ngx_event_timer_process_init(ngx_cycle_t *cycle) { ngx_event_timer_conf_t *etcf; ngx_event_timer_ctx_t *t, *next; ngx_uint_t i; etcf = ngx_event_get_conf(cycle->conf_ctx, ngx_event_timer_module); if (etcf->timer_n == 0) { return NGX_OK; } etcf->timer_ctx = ngx_alloc(sizeof(ngx_event_timer_ctx_t) * etcf->timer_n, cycle->log); if (etcf->timer_ctx == NULL) { return NGX_ERROR; } t = etcf->timer_ctx; i = etcf->timer_n; next = NULL; do { --i; t[i].timerid = i; t[i].event.timer_set = 0; t[i].event.log = NULL; t[i].handler = NULL; t[i].data = next; next = &t[i]; } while (i); etcf->free_timers = next; etcf->free_timer_n = etcf->timer_n; return NGX_OK; } static ngx_event_timer_ctx_t * ngx_event_timer_get_timer() { ngx_event_timer_conf_t *etcf; ngx_event_timer_ctx_t *free; etcf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_event_timer_module); free = etcf->free_timers; if (etcf->free_timer_n == 0) { ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, 0, "nginx event timer module, no free timer"); return NULL; } etcf->free_timers = free->data; --etcf->free_timer_n; return free; } static void ngx_event_timer_free_timer(ngx_event_timer_ctx_t *ctx) { ngx_event_timer_conf_t *etcf; etcf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_event_timer_module); ctx->data = etcf->free_timers; etcf->free_timers = ctx; ++etcf->free_timer_n; } static void ngx_event_timer_event_handler(ngx_event_t *e) { ngx_event_timer_ctx_t *ctx; ctx = e->data; if (ctx->handler) { ctx->handler(ctx->data); } ngx_event_timer_free_timer(ctx); } ngx_int_t ngx_event_timer_add_timer(ngx_msec_t tv, ngx_timer_handler_pt h, void *data) { ngx_event_timer_ctx_t *ctx; if (h == NULL) { return NGX_ERROR; } ctx = ngx_event_timer_get_timer(); if (ctx == NULL) { return NGX_ERROR; } ctx->event.handler = ngx_event_timer_event_handler; ctx->event.data = ctx; ctx->handler = h; ctx->data = data; if (ctx->event.log == NULL) { ctx->event.log = ngx_cycle->log; } ngx_event_add_timer(&ctx->event, tv); return ctx->timerid; } void ngx_event_timer_del_timer(ngx_uint_t timerid) { ngx_event_timer_ctx_t *ctx; ngx_event_timer_conf_t *etcf; etcf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_event_timer_module); ctx = &etcf->timer_ctx[timerid]; if (!ctx->event.timer_set) { ngx_log_debug0(NGX_LOG_DEBUG_EVENT, ngx_cycle->log, 0, "timer has already deleted"); return; } ngx_event_del_timer(&ctx->event); ngx_event_timer_free_timer(ctx); } ngx_chain_t * ngx_event_timer_state(ngx_http_request_t *r) { ngx_event_timer_conf_t *etcf; ngx_chain_t *cl; ngx_buf_t *b; size_t len; etcf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_event_timer_module); len = sizeof("##########event timer state##########\n") - 1 + sizeof("ngx_event_timer alloc: \n") - 1 + NGX_OFF_T_LEN + sizeof("ngx_event_timer free: \n") - 1 + NGX_OFF_T_LEN; cl = ngx_alloc_chain_link(r->pool); if (cl == NULL) { return NULL; } cl->next = NULL; b = ngx_create_temp_buf(r->pool, len); if (b == NULL) { return NULL; } cl->buf = b; b->last = ngx_snprintf(b->last, len, "##########event timer state##########\n" "ngx_event_timer alloc: %ui\nngx_event_timer free: %ui\n", etcf->timer_n, etcf->free_timer_n); return cl; }
2881099/FreeSql.AdminLTE
75,998
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/jsgrid/jsgrid.js
/* * jsGrid v1.5.3 (http://js-grid.com) * (c) 2016 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ (function(window, $, undefined) { var JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID, JSGRID_ROW_DATA_KEY = "JSGridItem", JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow", SORT_ORDER_ASC = "asc", SORT_ORDER_DESC = "desc", FIRST_PAGE_PLACEHOLDER = "{first}", PAGES_PLACEHOLDER = "{pages}", PREV_PAGE_PLACEHOLDER = "{prev}", NEXT_PAGE_PLACEHOLDER = "{next}", LAST_PAGE_PLACEHOLDER = "{last}", PAGE_INDEX_PLACEHOLDER = "{pageIndex}", PAGE_COUNT_PLACEHOLDER = "{pageCount}", ITEM_COUNT_PLACEHOLDER = "{itemCount}", EMPTY_HREF = "javascript:void(0);"; var getOrApply = function(value, context) { if($.isFunction(value)) { return value.apply(context, $.makeArray(arguments).slice(2)); } return value; }; var normalizePromise = function(promise) { var d = $.Deferred(); if(promise && promise.then) { promise.then(function() { d.resolve.apply(d, arguments); }, function() { d.reject.apply(d, arguments); }); } else { d.resolve(promise); } return d.promise(); }; var defaultController = { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }; function Grid(element, config) { var $element = $(element); $element.data(JSGRID_DATA_KEY, this); this._container = $element; this.data = []; this.fields = []; this._editingRow = null; this._sortField = null; this._sortOrder = SORT_ORDER_ASC; this._firstDisplayingPage = 1; this._init(config); this.render(); } Grid.prototype = { width: "auto", height: "auto", updateOnResize: true, rowClass: $.noop, rowRenderer: null, rowClick: function(args) { if(this.editing) { this.editItem($(args.event.target).closest("tr")); } }, rowDoubleClick: $.noop, noDataContent: "Not found", noDataRowClass: "jsgrid-nodata-row", heading: true, headerRowRenderer: null, headerRowClass: "jsgrid-header-row", headerCellClass: "jsgrid-header-cell", filtering: false, filterRowRenderer: null, filterRowClass: "jsgrid-filter-row", inserting: false, insertRowRenderer: null, insertRowClass: "jsgrid-insert-row", editing: false, editRowRenderer: null, editRowClass: "jsgrid-edit-row", confirmDeleting: true, deleteConfirm: "Are you sure?", selecting: true, selectedRowClass: "jsgrid-selected-row", oddRowClass: "jsgrid-row", evenRowClass: "jsgrid-alt-row", cellClass: "jsgrid-cell", sorting: false, sortableClass: "jsgrid-header-sortable", sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc", sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc", paging: false, pagerContainer: null, pageIndex: 1, pageSize: 20, pageButtonCount: 15, pagerFormat: "Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}", pagePrevText: "Prev", pageNextText: "Next", pageFirstText: "First", pageLastText: "Last", pageNavigatorNextText: "...", pageNavigatorPrevText: "...", pagerContainerClass: "jsgrid-pager-container", pagerClass: "jsgrid-pager", pagerNavButtonClass: "jsgrid-pager-nav-button", pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button", pageClass: "jsgrid-pager-page", currentPageClass: "jsgrid-pager-current-page", customLoading: false, pageLoading: false, autoload: false, controller: defaultController, loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, invalidMessage: "Invalid data entered!", invalidNotify: function(args) { var messages = $.map(args.errors, function(error) { return error.message || null; }); window.alert([this.invalidMessage].concat(messages).join("\n")); }, onInit: $.noop, onRefreshing: $.noop, onRefreshed: $.noop, onPageChanged: $.noop, onItemDeleting: $.noop, onItemDeleted: $.noop, onItemInserting: $.noop, onItemInserted: $.noop, onItemEditing: $.noop, onItemUpdating: $.noop, onItemUpdated: $.noop, onItemInvalid: $.noop, onDataLoading: $.noop, onDataLoaded: $.noop, onOptionChanging: $.noop, onOptionChanged: $.noop, onError: $.noop, invalidClass: "jsgrid-invalid", containerClass: "jsgrid", tableClass: "jsgrid-table", gridHeaderClass: "jsgrid-grid-header", gridBodyClass: "jsgrid-grid-body", _init: function(config) { $.extend(this, config); this._initLoadStrategy(); this._initController(); this._initFields(); this._attachWindowLoadResize(); this._attachWindowResizeCallback(); this._callEventHandler(this.onInit) }, loadStrategy: function() { return this.pageLoading ? new jsGrid.loadStrategies.PageLoadingStrategy(this) : new jsGrid.loadStrategies.DirectLoadingStrategy(this); }, _initLoadStrategy: function() { this._loadStrategy = getOrApply(this.loadStrategy, this); }, _initController: function() { this._controller = $.extend({}, defaultController, getOrApply(this.controller, this)); }, renderTemplate: function(source, context, config) { args = []; for(var key in config) { args.push(config[key]); } args.unshift(source, context); source = getOrApply.apply(null, args); return (source === undefined || source === null) ? "" : source; }, loadIndicator: function(config) { return new jsGrid.LoadIndicator(config); }, validation: function(config) { return jsGrid.Validation && new jsGrid.Validation(config); }, _initFields: function() { var self = this; self.fields = $.map(self.fields, function(field) { if($.isPlainObject(field)) { var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field; field = new fieldConstructor(field); } field._grid = self; return field; }); }, _attachWindowLoadResize: function() { $(window).on("load", $.proxy(this._refreshSize, this)); }, _attachWindowResizeCallback: function() { if(this.updateOnResize) { $(window).on("resize", $.proxy(this._refreshSize, this)); } }, _detachWindowResizeCallback: function() { $(window).off("resize", this._refreshSize); }, option: function(key, value) { var optionChangingEventArgs, optionChangedEventArgs; if(arguments.length === 1) return this[key]; optionChangingEventArgs = { option: key, oldValue: this[key], newValue: value }; this._callEventHandler(this.onOptionChanging, optionChangingEventArgs); this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue); optionChangedEventArgs = { option: optionChangingEventArgs.option, value: optionChangingEventArgs.newValue }; this._callEventHandler(this.onOptionChanged, optionChangedEventArgs); }, fieldOption: function(field, key, value) { field = this._normalizeField(field); if(arguments.length === 2) return field[key]; field[key] = value; this._renderGrid(); }, _handleOptionChange: function(name, value) { this[name] = value; switch(name) { case "width": case "height": this._refreshSize(); break; case "rowClass": case "rowRenderer": case "rowClick": case "rowDoubleClick": case "noDataRowClass": case "noDataContent": case "selecting": case "selectedRowClass": case "oddRowClass": case "evenRowClass": this._refreshContent(); break; case "pageButtonCount": case "pagerFormat": case "pagePrevText": case "pageNextText": case "pageFirstText": case "pageLastText": case "pageNavigatorNextText": case "pageNavigatorPrevText": case "pagerClass": case "pagerNavButtonClass": case "pageClass": case "currentPageClass": case "pagerRenderer": this._refreshPager(); break; case "fields": this._initFields(); this.render(); break; case "data": case "editing": case "heading": case "filtering": case "inserting": case "paging": this.refresh(); break; case "loadStrategy": case "pageLoading": this._initLoadStrategy(); this.search(); break; case "pageIndex": this.openPage(value); break; case "pageSize": this.refresh(); this.search(); break; case "editRowRenderer": case "editRowClass": this.cancelEdit(); break; case "updateOnResize": this._detachWindowResizeCallback(); this._attachWindowResizeCallback(); break; case "invalidNotify": case "invalidMessage": break; default: this.render(); break; } }, destroy: function() { this._detachWindowResizeCallback(); this._clear(); this._container.removeData(JSGRID_DATA_KEY); }, render: function() { this._renderGrid(); return this.autoload ? this.loadData() : $.Deferred().resolve().promise(); }, _renderGrid: function() { this._clear(); this._container.addClass(this.containerClass) .css("position", "relative") .append(this._createHeader()) .append(this._createBody()); this._pagerContainer = this._createPagerContainer(); this._loadIndicator = this._createLoadIndicator(); this._validation = this._createValidation(); this.refresh(); }, _createLoadIndicator: function() { return getOrApply(this.loadIndicator, this, { message: this.loadMessage, shading: this.loadShading, container: this._container }); }, _createValidation: function() { return getOrApply(this.validation, this); }, _clear: function() { this.cancelEdit(); clearTimeout(this._loadingTimer); this._pagerContainer && this._pagerContainer.empty(); this._container.empty() .css({ position: "", width: "", height: "" }); }, _createHeader: function() { var $headerRow = this._headerRow = this._createHeaderRow(), $filterRow = this._filterRow = this._createFilterRow(), $insertRow = this._insertRow = this._createInsertRow(); var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass) .append($headerRow) .append($filterRow) .append($insertRow); var $header = this._header = $("<div>").addClass(this.gridHeaderClass) .addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "") .append($headerGrid); return $header; }, _createBody: function() { var $content = this._content = $("<tbody>"); var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass) .append($content); var $body = this._body = $("<div>").addClass(this.gridBodyClass) .append($bodyGrid) .on("scroll", $.proxy(function(e) { this._header.scrollLeft(e.target.scrollLeft); }, this)); return $body; }, _createPagerContainer: function() { var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container); return $(pagerContainer).addClass(this.pagerContainerClass); }, _eachField: function(callBack) { var self = this; $.each(this.fields, function(index, field) { if(field.visible) { callBack.call(self, field, index); } }); }, _createHeaderRow: function() { if($.isFunction(this.headerRowRenderer)) return $(this.renderTemplate(this.headerRowRenderer, this)); var $result = $("<tr>").addClass(this.headerRowClass); this._eachField(function(field, index) { var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass) .append(this.renderTemplate(field.headerTemplate, field)) .appendTo($result); if(this.sorting && field.sorting) { $th.addClass(this.sortableClass) .on("click", $.proxy(function() { this.sort(index); }, this)); } }); return $result; }, _prepareCell: function(cell, field, cssprop, cellClass) { return $(cell).css("width", field.width) .addClass(cellClass || this.cellClass) .addClass((cssprop && field[cssprop]) || field.css) .addClass(field.align ? ("jsgrid-align-" + field.align) : ""); }, _createFilterRow: function() { if($.isFunction(this.filterRowRenderer)) return $(this.renderTemplate(this.filterRowRenderer, this)); var $result = $("<tr>").addClass(this.filterRowClass); this._eachField(function(field) { this._prepareCell("<td>", field, "filtercss") .append(this.renderTemplate(field.filterTemplate, field)) .appendTo($result); }); return $result; }, _createInsertRow: function() { if($.isFunction(this.insertRowRenderer)) return $(this.renderTemplate(this.insertRowRenderer, this)); var $result = $("<tr>").addClass(this.insertRowClass); this._eachField(function(field) { this._prepareCell("<td>", field, "insertcss") .append(this.renderTemplate(field.insertTemplate, field)) .appendTo($result); }); return $result; }, _callEventHandler: function(handler, eventParams) { handler.call(this, $.extend(eventParams, { grid: this })); return eventParams; }, reset: function() { this._resetSorting(); this._resetPager(); return this._loadStrategy.reset(); }, _resetPager: function() { this._firstDisplayingPage = 1; this._setPage(1); }, _resetSorting: function() { this._sortField = null; this._sortOrder = SORT_ORDER_ASC; this._clearSortingCss(); }, refresh: function() { this._callEventHandler(this.onRefreshing); this.cancelEdit(); this._refreshHeading(); this._refreshFiltering(); this._refreshInserting(); this._refreshContent(); this._refreshPager(); this._refreshSize(); this._callEventHandler(this.onRefreshed); }, _refreshHeading: function() { this._headerRow.toggle(this.heading); }, _refreshFiltering: function() { this._filterRow.toggle(this.filtering); }, _refreshInserting: function() { this._insertRow.toggle(this.inserting); }, _refreshContent: function() { var $content = this._content; $content.empty(); if(!this.data.length) { $content.append(this._createNoDataRow()); return this; } var indexFrom = this._loadStrategy.firstDisplayIndex(); var indexTo = this._loadStrategy.lastDisplayIndex(); for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) { var item = this.data[itemIndex]; $content.append(this._createRow(item, itemIndex)); } }, _createNoDataRow: function() { var amountOfFields = 0; this._eachField(function() { amountOfFields++; }); return $("<tr>").addClass(this.noDataRowClass) .append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields) .append(this.renderTemplate(this.noDataContent, this))); }, _createRow: function(item, itemIndex) { var $result; if($.isFunction(this.rowRenderer)) { $result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex }); } else { $result = $("<tr>"); this._renderCells($result, item); } $result.addClass(this._getRowClasses(item, itemIndex)) .data(JSGRID_ROW_DATA_KEY, item) .on("click", $.proxy(function(e) { this.rowClick({ item: item, itemIndex: itemIndex, event: e }); }, this)) .on("dblclick", $.proxy(function(e) { this.rowDoubleClick({ item: item, itemIndex: itemIndex, event: e }); }, this)); if(this.selecting) { this._attachRowHover($result); } return $result; }, _getRowClasses: function(item, itemIndex) { var classes = []; classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass); classes.push(getOrApply(this.rowClass, this, item, itemIndex)); return classes.join(" "); }, _attachRowHover: function($row) { var selectedRowClass = this.selectedRowClass; $row.hover(function() { $(this).addClass(selectedRowClass); }, function() { $(this).removeClass(selectedRowClass); } ); }, _renderCells: function($row, item) { this._eachField(function(field) { $row.append(this._createCell(item, field)); }); return this; }, _createCell: function(item, field) { var $result; var fieldValue = this._getItemFieldValue(item, field); var args = { value: fieldValue, item : item }; if($.isFunction(field.cellRenderer)) { $result = this.renderTemplate(field.cellRenderer, field, args); } else { $result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args)); } return this._prepareCell($result, field); }, _getItemFieldValue: function(item, field) { var props = field.name.split('.'); var result = item[props.shift()]; while(result && props.length) { result = result[props.shift()]; } return result; }, _setItemFieldValue: function(item, field, value) { var props = field.name.split('.'); var current = item; var prop = props[0]; while(current && props.length) { item = current; prop = props.shift(); current = item[prop]; } if(!current) { while(props.length) { item = item[prop] = {}; prop = props.shift(); } } item[prop] = value; }, sort: function(field, order) { if($.isPlainObject(field)) { order = field.order; field = field.field; } this._clearSortingCss(); this._setSortingParams(field, order); this._setSortingCss(); return this._loadStrategy.sort(); }, _clearSortingCss: function() { this._headerRow.find("th") .removeClass(this.sortAscClass) .removeClass(this.sortDescClass); }, _setSortingParams: function(field, order) { field = this._normalizeField(field); order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC); this._sortField = field; this._sortOrder = order; }, _normalizeField: function(field) { if($.isNumeric(field)) { return this.fields[field]; } if(typeof field === "string") { return $.grep(this.fields, function(f) { return f.name === field; })[0]; } return field; }, _reversedSortOrder: function(order) { return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC); }, _setSortingCss: function() { var fieldIndex = this._visibleFieldIndex(this._sortField); this._headerRow.find("th").eq(fieldIndex) .addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass); }, _visibleFieldIndex: function(field) { return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; })); }, _sortData: function() { var sortFactor = this._sortFactor(), sortField = this._sortField; if(sortField) { this.data.sort(function(item1, item2) { return sortFactor * sortField.sortingFunc(item1[sortField.name], item2[sortField.name]); }); } }, _sortFactor: function() { return this._sortOrder === SORT_ORDER_ASC ? 1 : -1; }, _itemsCount: function() { return this._loadStrategy.itemsCount(); }, _pagesCount: function() { var itemsCount = this._itemsCount(), pageSize = this.pageSize; return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0); }, _refreshPager: function() { var $pagerContainer = this._pagerContainer; $pagerContainer.empty(); if(this.paging) { $pagerContainer.append(this._createPager()); } var showPager = this.paging && this._pagesCount() > 1; $pagerContainer.toggle(showPager); }, _createPager: function() { var $result; if($.isFunction(this.pagerRenderer)) { $result = $(this.pagerRenderer({ pageIndex: this.pageIndex, pageCount: this._pagesCount() })); } else { $result = $("<div>").append(this._createPagerByFormat()); } $result.addClass(this.pagerClass); return $result; }, _createPagerByFormat: function() { var pageIndex = this.pageIndex, pageCount = this._pagesCount(), itemCount = this._itemsCount(), pagerParts = this.pagerFormat.split(" "); return $.map(pagerParts, $.proxy(function(pagerPart) { var result = pagerPart; if(pagerPart === PAGES_PLACEHOLDER) { result = this._createPages(); } else if(pagerPart === FIRST_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1); } else if(pagerPart === PREV_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1); } else if(pagerPart === NEXT_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount); } else if(pagerPart === LAST_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount); } else if(pagerPart === PAGE_INDEX_PLACEHOLDER) { result = pageIndex; } else if(pagerPart === PAGE_COUNT_PLACEHOLDER) { result = pageCount; } else if(pagerPart === ITEM_COUNT_PLACEHOLDER) { result = itemCount; } return $.isArray(result) ? result.concat([" "]) : [result, " "]; }, this)); }, _createPages: function() { var pageCount = this._pagesCount(), pageButtonCount = this.pageButtonCount, firstDisplayingPage = this._firstDisplayingPage, pages = []; if(firstDisplayingPage > 1) { pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages)); } for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) { pages.push(pageNumber === this.pageIndex ? this._createPagerCurrentPage() : this._createPagerPage(pageNumber)); } if((firstDisplayingPage + pageButtonCount - 1) < pageCount) { pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages)); } return pages; }, _createPagerNavButton: function(text, pageIndex, isActive) { return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass), isActive ? function() { this.openPage(pageIndex); } : $.noop); }, _createPagerPageNavButton: function(text, handler) { return this._createPagerButton(text, this.pagerNavButtonClass, handler); }, _createPagerPage: function(pageIndex) { return this._createPagerButton(pageIndex, this.pageClass, function() { this.openPage(pageIndex); }); }, _createPagerButton: function(text, css, handler) { var $link = $("<a>").attr("href", EMPTY_HREF) .html(text) .on("click", $.proxy(handler, this)); return $("<span>").addClass(css).append($link); }, _createPagerCurrentPage: function() { return $("<span>") .addClass(this.pageClass) .addClass(this.currentPageClass) .text(this.pageIndex); }, _refreshSize: function() { this._refreshHeight(); this._refreshWidth(); }, _refreshWidth: function() { var width = (this.width === "auto") ? this._getAutoWidth() : this.width; this._container.width(width); }, _getAutoWidth: function() { var $headerGrid = this._headerGrid, $header = this._header; $headerGrid.width("auto"); var contentWidth = $headerGrid.outerWidth(); var borderWidth = $header.outerWidth() - $header.innerWidth(); $headerGrid.width(""); return contentWidth + borderWidth; }, _scrollBarWidth: (function() { var result; return function() { if(result === undefined) { var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"); var $ghostContent = $("<div style='height:100px;'></div>"); $ghostContainer.append($ghostContent).appendTo("body"); var width = $ghostContent.innerWidth(); $ghostContainer.css("overflow-y", "auto"); var widthExcludingScrollBar = $ghostContent.innerWidth(); $ghostContainer.remove(); result = width - widthExcludingScrollBar; } return result; }; })(), _refreshHeight: function() { var container = this._container, pagerContainer = this._pagerContainer, height = this.height, nonBodyHeight; container.height(height); if(height !== "auto") { height = container.height(); nonBodyHeight = this._header.outerHeight(true); if(pagerContainer.parents(container).length) { nonBodyHeight += pagerContainer.outerHeight(true); } this._body.outerHeight(height - nonBodyHeight); } }, showPrevPages: function() { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount; this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1; this._refreshPager(); }, showNextPages: function() { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount, pageCount = this._pagesCount(); this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount) ? pageCount - pageButtonCount + 1 : firstDisplayingPage + pageButtonCount; this._refreshPager(); }, openPage: function(pageIndex) { if(pageIndex < 1 || pageIndex > this._pagesCount()) return; this._setPage(pageIndex); this._loadStrategy.openPage(pageIndex); }, _setPage: function(pageIndex) { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount; this.pageIndex = pageIndex; if(pageIndex < firstDisplayingPage) { this._firstDisplayingPage = pageIndex; } if(pageIndex > firstDisplayingPage + pageButtonCount - 1) { this._firstDisplayingPage = pageIndex - pageButtonCount + 1; } this._callEventHandler(this.onPageChanged, { pageIndex: pageIndex }); }, _controllerCall: function(method, param, isCanceled, doneCallback) { if(isCanceled) return $.Deferred().reject().promise(); this._showLoading(); var controller = this._controller; if(!controller || !controller[method]) { throw Error("controller has no method '" + method + "'"); } return normalizePromise(controller[method](param)) .done($.proxy(doneCallback, this)) .fail($.proxy(this._errorHandler, this)) .always($.proxy(this._hideLoading, this)); }, _errorHandler: function() { this._callEventHandler(this.onError, { args: $.makeArray(arguments) }); }, _showLoading: function() { if(!this.loadIndication) return; clearTimeout(this._loadingTimer); this._loadingTimer = setTimeout($.proxy(function() { this._loadIndicator.show(); }, this), this.loadIndicationDelay); }, _hideLoading: function() { if(!this.loadIndication) return; clearTimeout(this._loadingTimer); this._loadIndicator.hide(); }, search: function(filter) { this._resetSorting(); this._resetPager(); return this.loadData(filter); }, loadData: function(filter) { filter = filter || (this.filtering ? this.getFilter() : {}); $.extend(filter, this._loadStrategy.loadParams(), this._sortingParams()); var args = this._callEventHandler(this.onDataLoading, { filter: filter }); return this._controllerCall("loadData", filter, args.cancel, function(loadedData) { if(!loadedData) return; this._loadStrategy.finishLoad(loadedData); this._callEventHandler(this.onDataLoaded, { data: loadedData }); }); }, getFilter: function() { var result = {}; this._eachField(function(field) { if(field.filtering) { this._setItemFieldValue(result, field, field.filterValue()); } }); return result; }, _sortingParams: function() { if(this.sorting && this._sortField) { return { sortField: this._sortField.name, sortOrder: this._sortOrder }; } return {}; }, getSorting: function() { var sortingParams = this._sortingParams(); return { field: sortingParams.sortField, order: sortingParams.sortOrder }; }, clearFilter: function() { var $filterRow = this._createFilterRow(); this._filterRow.replaceWith($filterRow); this._filterRow = $filterRow; return this.search(); }, insertItem: function(item) { var insertingItem = item || this._getValidatedInsertItem(); if(!insertingItem) return $.Deferred().reject().promise(); var args = this._callEventHandler(this.onItemInserting, { item: insertingItem }); return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) { insertedItem = insertedItem || insertingItem; this._loadStrategy.finishInsert(insertedItem); this._callEventHandler(this.onItemInserted, { item: insertedItem }); }); }, _getValidatedInsertItem: function() { var item = this._getInsertItem(); return this._validateItem(item, this._insertRow) ? item : null; }, _getInsertItem: function() { var result = {}; this._eachField(function(field) { if(field.inserting) { this._setItemFieldValue(result, field, field.insertValue()); } }); return result; }, _validateItem: function(item, $row) { var validationErrors = []; var args = { item: item, itemIndex: this._rowIndex($row), row: $row }; this._eachField(function(field) { if(!field.validate || ($row === this._insertRow && !field.inserting) || ($row === this._getEditRow() && !field.editing)) return; var fieldValue = this._getItemFieldValue(item, field); var errors = this._validation.validate($.extend({ value: fieldValue, rules: field.validate }, args)); this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors); if(!errors.length) return; validationErrors.push.apply(validationErrors, $.map(errors, function(message) { return { field: field, message: message }; })); }); if(!validationErrors.length) return true; var invalidArgs = $.extend({ errors: validationErrors }, args); this._callEventHandler(this.onItemInvalid, invalidArgs); this.invalidNotify(invalidArgs); return false; }, _setCellValidity: function($cell, errors) { $cell .toggleClass(this.invalidClass, !!errors.length) .attr("title", errors.join("\n")); }, clearInsert: function() { var insertRow = this._createInsertRow(); this._insertRow.replaceWith(insertRow); this._insertRow = insertRow; this.refresh(); }, editItem: function(item) { var $row = this.rowByItem(item); if($row.length) { this._editRow($row); } }, rowByItem: function(item) { if(item.jquery || item.nodeType) return $(item); return this._content.find("tr").filter(function() { return $.data(this, JSGRID_ROW_DATA_KEY) === item; }); }, _editRow: function($row) { if(!this.editing) return; var item = $row.data(JSGRID_ROW_DATA_KEY); var args = this._callEventHandler(this.onItemEditing, { row: $row, item: item, itemIndex: this._itemIndex(item) }); if(args.cancel) return; if(this._editingRow) { this.cancelEdit(); } var $editRow = this._createEditRow(item); this._editingRow = $row; $row.hide(); $editRow.insertBefore($row); $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow); }, _createEditRow: function(item) { if($.isFunction(this.editRowRenderer)) { return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) })); } var $result = $("<tr>").addClass(this.editRowClass); this._eachField(function(field) { var fieldValue = this._getItemFieldValue(item, field); this._prepareCell("<td>", field, "editcss") .append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item })) .appendTo($result); }); return $result; }, updateItem: function(item, editedItem) { if(arguments.length === 1) { editedItem = item; } var $row = item ? this.rowByItem(item) : this._editingRow; editedItem = editedItem || this._getValidatedEditedItem(); if(!editedItem) return; return this._updateRow($row, editedItem); }, _getValidatedEditedItem: function() { var item = this._getEditedItem(); return this._validateItem(item, this._getEditRow()) ? item : null; }, _updateRow: function($updatingRow, editedItem) { var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY), updatingItemIndex = this._itemIndex(updatingItem), updatedItem = $.extend(true, {}, updatingItem, editedItem); var args = this._callEventHandler(this.onItemUpdating, { row: $updatingRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: updatingItem }); return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) { var previousItem = $.extend(true, {}, updatingItem); updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem); var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex); this._callEventHandler(this.onItemUpdated, { row: $updatedRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: previousItem }); }); }, _rowIndex: function(row) { return this._content.children().index($(row)); }, _itemIndex: function(item) { return $.inArray(item, this.data); }, _finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) { this.cancelEdit(); this.data[updatedItemIndex] = updatedItem; var $updatedRow = this._createRow(updatedItem, updatedItemIndex); $updatingRow.replaceWith($updatedRow); return $updatedRow; }, _getEditedItem: function() { var result = {}; this._eachField(function(field) { if(field.editing) { this._setItemFieldValue(result, field, field.editValue()); } }); return result; }, cancelEdit: function() { if(!this._editingRow) return; this._getEditRow().remove(); this._editingRow.show(); this._editingRow = null; }, _getEditRow: function() { return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY); }, deleteItem: function(item) { var $row = this.rowByItem(item); if(!$row.length) return; if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row); }, _deleteRow: function($row) { var deletingItem = $row.data(JSGRID_ROW_DATA_KEY), deletingItemIndex = this._itemIndex(deletingItem); var args = this._callEventHandler(this.onItemDeleting, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); return this._controllerCall("deleteItem", deletingItem, args.cancel, function() { this._loadStrategy.finishDelete(deletingItem, deletingItemIndex); this._callEventHandler(this.onItemDeleted, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); }); } }; $.fn.jsGrid = function(config) { var args = $.makeArray(arguments), methodArgs = args.slice(1), result = this; this.each(function() { var $element = $(this), instance = $element.data(JSGRID_DATA_KEY), methodResult; if(instance) { if(typeof config === "string") { methodResult = instance[config].apply(instance, methodArgs); if(methodResult !== undefined && methodResult !== instance) { result = methodResult; return false; } } else { instance._detachWindowResizeCallback(); instance._init(config); instance.render(); } } else { new Grid($element, config); } }); return result; }; var fields = {}; var setDefaults = function(config) { var componentPrototype; if($.isPlainObject(config)) { componentPrototype = Grid.prototype; } else { componentPrototype = fields[config].prototype; config = arguments[1] || {}; } $.extend(componentPrototype, config); }; var locales = {}; var locale = function(lang) { var localeConfig = $.isPlainObject(lang) ? lang : locales[lang]; if(!localeConfig) throw Error("unknown locale " + lang); setLocale(jsGrid, localeConfig); }; var setLocale = function(obj, localeConfig) { $.each(localeConfig, function(field, value) { if($.isPlainObject(value)) { setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value); return; } if(obj.hasOwnProperty(field)) { obj[field] = value; } else { obj.prototype[field] = value; } }); }; window.jsGrid = { Grid: Grid, fields: fields, setDefaults: setDefaults, locales: locales, locale: locale, version: '1.5.3' }; }(window, jQuery)); (function(jsGrid, $, undefined) { function LoadIndicator(config) { this._init(config); } LoadIndicator.prototype = { container: "body", message: "Loading...", shading: true, zIndex: 1000, shaderClass: "jsgrid-load-shader", loadPanelClass: "jsgrid-load-panel", _init: function(config) { $.extend(true, this, config); this._initContainer(); this._initShader(); this._initLoadPanel(); }, _initContainer: function() { this._container = $(this.container); }, _initShader: function() { if(!this.shading) return; this._shader = $("<div>").addClass(this.shaderClass) .hide() .css({ position: "absolute", top: 0, right: 0, bottom: 0, left: 0, zIndex: this.zIndex }) .appendTo(this._container); }, _initLoadPanel: function() { this._loadPanel = $("<div>").addClass(this.loadPanelClass) .text(this.message) .hide() .css({ position: "absolute", top: "50%", left: "50%", zIndex: this.zIndex }) .appendTo(this._container); }, show: function() { var $loadPanel = this._loadPanel.show(); var actualWidth = $loadPanel.outerWidth(); var actualHeight = $loadPanel.outerHeight(); $loadPanel.css({ marginTop: -actualHeight / 2, marginLeft: -actualWidth / 2 }); this._shader.show(); }, hide: function() { this._loadPanel.hide(); this._shader.hide(); } }; jsGrid.LoadIndicator = LoadIndicator; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { function DirectLoadingStrategy(grid) { this._grid = grid; } DirectLoadingStrategy.prototype = { firstDisplayIndex: function() { var grid = this._grid; return grid.option("paging") ? (grid.option("pageIndex") - 1) * grid.option("pageSize") : 0; }, lastDisplayIndex: function() { var grid = this._grid; var itemsCount = grid.option("data").length; return grid.option("paging") ? Math.min(grid.option("pageIndex") * grid.option("pageSize"), itemsCount) : itemsCount; }, itemsCount: function() { return this._grid.option("data").length; }, openPage: function(index) { this._grid.refresh(); }, loadParams: function() { return {}; }, sort: function() { this._grid._sortData(); this._grid.refresh(); return $.Deferred().resolve().promise(); }, reset: function() { this._grid.refresh(); return $.Deferred().resolve().promise(); }, finishLoad: function(loadedData) { this._grid.option("data", loadedData); }, finishInsert: function(insertedItem) { var grid = this._grid; grid.option("data").push(insertedItem); grid.refresh(); }, finishDelete: function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.reset(); } }; function PageLoadingStrategy(grid) { this._grid = grid; this._itemsCount = 0; } PageLoadingStrategy.prototype = { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return this._grid.option("data").length; }, itemsCount: function() { return this._itemsCount; }, openPage: function(index) { this._grid.loadData(); }, loadParams: function() { var grid = this._grid; return { pageIndex: grid.option("pageIndex"), pageSize: grid.option("pageSize") }; }, reset: function() { return this._grid.loadData(); }, sort: function() { return this._grid.loadData(); }, finishLoad: function(loadedData) { this._itemsCount = loadedData.itemsCount; this._grid.option("data", loadedData.data); }, finishInsert: function(insertedItem) { this._grid.search(); }, finishDelete: function(deletedItem, deletedItemIndex) { this._grid.search(); } }; jsGrid.loadStrategies = { DirectLoadingStrategy: DirectLoadingStrategy, PageLoadingStrategy: PageLoadingStrategy }; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var isDefined = function(val) { return typeof(val) !== "undefined" && val !== null; }; var sortStrategies = { string: function(str1, str2) { if(!isDefined(str1) && !isDefined(str2)) return 0; if(!isDefined(str1)) return -1; if(!isDefined(str2)) return 1; return ("" + str1).localeCompare("" + str2); }, number: function(n1, n2) { return n1 - n2; }, date: function(dt1, dt2) { return dt1 - dt2; }, numberAsString: function(n1, n2) { return parseFloat(n1) - parseFloat(n2); } }; jsGrid.sortStrategies = sortStrategies; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { function Validation(config) { this._init(config); } Validation.prototype = { _init: function(config) { $.extend(true, this, config); }, validate: function(args) { var errors = []; $.each(this._normalizeRules(args.rules), function(_, rule) { if(rule.validator(args.value, args.item, rule.param)) return; var errorMessage = $.isFunction(rule.message) ? rule.message(args.value, args.item) : rule.message; errors.push(errorMessage); }); return errors; }, _normalizeRules: function(rules) { if(!$.isArray(rules)) rules = [rules]; return $.map(rules, $.proxy(function(rule) { return this._normalizeRule(rule); }, this)); }, _normalizeRule: function(rule) { if(typeof rule === "string") rule = { validator: rule }; if($.isFunction(rule)) rule = { validator: rule }; if($.isPlainObject(rule)) rule = $.extend({}, rule); else throw Error("wrong validation config specified"); if($.isFunction(rule.validator)) return rule; return this._applyNamedValidator(rule, rule.validator); }, _applyNamedValidator: function(rule, validatorName) { delete rule.validator; var validator = validators[validatorName]; if(!validator) throw Error("unknown validator \"" + validatorName + "\""); if($.isFunction(validator)) { validator = { validator: validator }; } return $.extend({}, validator, rule); } }; jsGrid.Validation = Validation; var validators = { required: { message: "Field is required", validator: function(value) { return value !== undefined && value !== null && value !== ""; } }, rangeLength: { message: "Field value length is out of the defined range", validator: function(value, _, param) { return value.length >= param[0] && value.length <= param[1]; } }, minLength: { message: "Field value is too short", validator: function(value, _, param) { return value.length >= param; } }, maxLength: { message: "Field value is too long", validator: function(value, _, param) { return value.length <= param; } }, pattern: { message: "Field value is not matching the defined pattern", validator: function(value, _, param) { if(typeof param === "string") { param = new RegExp("^(?:" + param + ")$"); } return param.test(value); } }, range: { message: "Field value is out of the defined range", validator: function(value, _, param) { return value >= param[0] && value <= param[1]; } }, min: { message: "Field value is too small", validator: function(value, _, param) { return value >= param; } }, max: { message: "Field value is too large", validator: function(value, _, param) { return value <= param; } } }; jsGrid.validators = validators; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { function Field(config) { $.extend(true, this, config); this.sortingFunc = this._getSortingFunc(); } Field.prototype = { name: "", title: null, css: "", align: "", width: 100, visible: true, filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", // name of SortStrategy or function to compare elements headerTemplate: function() { return (this.title === undefined || this.title === null) ? this.name : this.title; }, itemTemplate: function(value, item) { return value; }, filterTemplate: function() { return ""; }, insertTemplate: function() { return ""; }, editTemplate: function(value, item) { this._value = value; return this.itemTemplate(value, item); }, filterValue: function() { return ""; }, insertValue: function() { return ""; }, editValue: function() { return this._value; }, _getSortingFunc: function() { var sorter = this.sorter; if($.isFunction(sorter)) { return sorter; } if(typeof sorter === "string") { return jsGrid.sortStrategies[sorter]; } throw Error("wrong sorter for the field \"" + this.name + "\"!"); } }; jsGrid.Field = Field; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var Field = jsGrid.Field; function TextField(config) { Field.call(this, config); } TextField.prototype = new Field({ autosearch: true, readOnly: false, filterTemplate: function() { if(!this.filtering) return ""; var grid = this._grid, $result = this.filterControl = this._createTextBox(); if(this.autosearch) { $result.on("keypress", function(e) { if(e.which === 13) { grid.search(); e.preventDefault(); } }); } return $result; }, insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createTextBox(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createTextBox(); $result.val(value); return $result; }, filterValue: function() { return this.filterControl.val(); }, insertValue: function() { return this.insertControl.val(); }, editValue: function() { return this.editControl.val(); }, _createTextBox: function() { return $("<input>").attr("type", "text") .prop("readonly", !!this.readOnly); } }); jsGrid.fields.text = jsGrid.TextField = TextField; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var TextField = jsGrid.TextField; function NumberField(config) { TextField.call(this, config); } NumberField.prototype = new TextField({ sorter: "number", align: "right", readOnly: false, filterValue: function() { return this.filterControl.val() ? parseInt(this.filterControl.val() || 0, 10) : undefined; }, insertValue: function() { return this.insertControl.val() ? parseInt(this.insertControl.val() || 0, 10) : undefined; }, editValue: function() { return this.editControl.val() ? parseInt(this.editControl.val() || 0, 10) : undefined; }, _createTextBox: function() { return $("<input>").attr("type", "number") .prop("readonly", !!this.readOnly); } }); jsGrid.fields.number = jsGrid.NumberField = NumberField; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var TextField = jsGrid.TextField; function TextAreaField(config) { TextField.call(this, config); } TextAreaField.prototype = new TextField({ insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createTextArea(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createTextArea(); $result.val(value); return $result; }, _createTextArea: function() { return $("<textarea>").prop("readonly", !!this.readOnly); } }); jsGrid.fields.textarea = jsGrid.TextAreaField = TextAreaField; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var NumberField = jsGrid.NumberField; var numberValueType = "number"; var stringValueType = "string"; function SelectField(config) { this.items = []; this.selectedIndex = -1; this.valueField = ""; this.textField = ""; if(config.valueField && config.items.length) { var firstItemValue = config.items[0][config.valueField]; this.valueType = (typeof firstItemValue) === numberValueType ? numberValueType : stringValueType; } this.sorter = this.valueType; NumberField.call(this, config); } SelectField.prototype = new NumberField({ align: "center", valueType: numberValueType, itemTemplate: function(value) { var items = this.items, valueField = this.valueField, textField = this.textField, resultItem; if(valueField) { resultItem = $.grep(items, function(item, index) { return item[valueField] === value; })[0] || {}; } else { resultItem = items[value]; } var result = (textField ? resultItem[textField] : resultItem); return (result === undefined || result === null) ? "" : result; }, filterTemplate: function() { if(!this.filtering) return ""; var grid = this._grid, $result = this.filterControl = this._createSelect(); if(this.autosearch) { $result.on("change", function(e) { grid.search(); }); } return $result; }, insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createSelect(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createSelect(); (value !== undefined) && $result.val(value); return $result; }, filterValue: function() { var val = this.filterControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, insertValue: function() { var val = this.insertControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, editValue: function() { var val = this.editControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, _createSelect: function() { var $result = $("<select>"), valueField = this.valueField, textField = this.textField, selectedIndex = this.selectedIndex; $.each(this.items, function(index, item) { var value = valueField ? item[valueField] : index, text = textField ? item[textField] : item; var $option = $("<option>") .attr("value", value) .text(text) .appendTo($result); $option.prop("selected", (selectedIndex === index)); }); $result.prop("disabled", !!this.readOnly); return $result; } }); jsGrid.fields.select = jsGrid.SelectField = SelectField; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var Field = jsGrid.Field; function CheckboxField(config) { Field.call(this, config); } CheckboxField.prototype = new Field({ sorter: "number", align: "center", autosearch: true, itemTemplate: function(value) { return this._createCheckbox().prop({ checked: value, disabled: true }); }, filterTemplate: function() { if(!this.filtering) return ""; var grid = this._grid, $result = this.filterControl = this._createCheckbox(); $result.prop({ readOnly: true, indeterminate: true }); $result.on("click", function() { var $cb = $(this); if($cb.prop("readOnly")) { $cb.prop({ checked: false, readOnly: false }); } else if(!$cb.prop("checked")) { $cb.prop({ readOnly: true, indeterminate: true }); } }); if(this.autosearch) { $result.on("click", function() { grid.search(); }); } return $result; }, insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createCheckbox(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createCheckbox(); $result.prop("checked", value); return $result; }, filterValue: function() { return this.filterControl.get(0).indeterminate ? undefined : this.filterControl.is(":checked"); }, insertValue: function() { return this.insertControl.is(":checked"); }, editValue: function() { return this.editControl.is(":checked"); }, _createCheckbox: function() { return $("<input>").attr("type", "checkbox"); } }); jsGrid.fields.checkbox = jsGrid.CheckboxField = CheckboxField; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var Field = jsGrid.Field; function ControlField(config) { Field.call(this, config); this._configInitialized = false; } ControlField.prototype = new Field({ css: "jsgrid-control-field", align: "center", width: 50, filtering: false, inserting: false, editing: false, sorting: false, buttonClass: "jsgrid-button", modeButtonClass: "jsgrid-mode-button", modeOnButtonClass: "jsgrid-mode-on-button", searchModeButtonClass: "jsgrid-search-mode-button", insertModeButtonClass: "jsgrid-insert-mode-button", editButtonClass: "jsgrid-edit-button", deleteButtonClass: "jsgrid-delete-button", searchButtonClass: "jsgrid-search-button", clearFilterButtonClass: "jsgrid-clear-filter-button", insertButtonClass: "jsgrid-insert-button", updateButtonClass: "jsgrid-update-button", cancelEditButtonClass: "jsgrid-cancel-edit-button", searchModeButtonTooltip: "Switch to searching", insertModeButtonTooltip: "Switch to inserting", editButtonTooltip: "Edit", deleteButtonTooltip: "Delete", searchButtonTooltip: "Search", clearFilterButtonTooltip: "Clear filter", insertButtonTooltip: "Insert", updateButtonTooltip: "Update", cancelEditButtonTooltip: "Cancel edit", editButton: true, deleteButton: true, clearFilterButton: true, modeSwitchButton: true, _initConfig: function() { this._hasFiltering = this._grid.filtering; this._hasInserting = this._grid.inserting; if(this._hasInserting && this.modeSwitchButton) { this._grid.inserting = false; } this._configInitialized = true; }, headerTemplate: function() { if(!this._configInitialized) { this._initConfig(); } var hasFiltering = this._hasFiltering; var hasInserting = this._hasInserting; if(!this.modeSwitchButton || (!hasFiltering && !hasInserting)) return ""; if(hasFiltering && !hasInserting) return this._createFilterSwitchButton(); if(hasInserting && !hasFiltering) return this._createInsertSwitchButton(); return this._createModeSwitchButton(); }, itemTemplate: function(value, item) { var $result = $([]); if(this.editButton) { $result = $result.add(this._createEditButton(item)); } if(this.deleteButton) { $result = $result.add(this._createDeleteButton(item)); } return $result; }, filterTemplate: function() { var $result = this._createSearchButton(); return this.clearFilterButton ? $result.add(this._createClearFilterButton()) : $result; }, insertTemplate: function() { return this._createInsertButton(); }, editTemplate: function() { return this._createUpdateButton().add(this._createCancelEditButton()); }, _createFilterSwitchButton: function() { return this._createOnOffSwitchButton("filtering", this.searchModeButtonClass, true); }, _createInsertSwitchButton: function() { return this._createOnOffSwitchButton("inserting", this.insertModeButtonClass, false); }, _createOnOffSwitchButton: function(option, cssClass, isOnInitially) { var isOn = isOnInitially; var updateButtonState = $.proxy(function() { $button.toggleClass(this.modeOnButtonClass, isOn); }, this); var $button = this._createGridButton(this.modeButtonClass + " " + cssClass, "", function(grid) { isOn = !isOn; grid.option(option, isOn); updateButtonState(); }); updateButtonState(); return $button; }, _createModeSwitchButton: function() { var isInserting = false; var updateButtonState = $.proxy(function() { $button.attr("title", isInserting ? this.searchModeButtonTooltip : this.insertModeButtonTooltip) .toggleClass(this.insertModeButtonClass, !isInserting) .toggleClass(this.searchModeButtonClass, isInserting); }, this); var $button = this._createGridButton(this.modeButtonClass, "", function(grid) { isInserting = !isInserting; grid.option("inserting", isInserting); grid.option("filtering", !isInserting); updateButtonState(); }); updateButtonState(); return $button; }, _createEditButton: function(item) { return this._createGridButton(this.editButtonClass, this.editButtonTooltip, function(grid, e) { grid.editItem(item); e.stopPropagation(); }); }, _createDeleteButton: function(item) { return this._createGridButton(this.deleteButtonClass, this.deleteButtonTooltip, function(grid, e) { grid.deleteItem(item); e.stopPropagation(); }); }, _createSearchButton: function() { return this._createGridButton(this.searchButtonClass, this.searchButtonTooltip, function(grid) { grid.search(); }); }, _createClearFilterButton: function() { return this._createGridButton(this.clearFilterButtonClass, this.clearFilterButtonTooltip, function(grid) { grid.clearFilter(); }); }, _createInsertButton: function() { return this._createGridButton(this.insertButtonClass, this.insertButtonTooltip, function(grid) { grid.insertItem().done(function() { grid.clearInsert(); }); }); }, _createUpdateButton: function() { return this._createGridButton(this.updateButtonClass, this.updateButtonTooltip, function(grid, e) { grid.updateItem(); e.stopPropagation(); }); }, _createCancelEditButton: function() { return this._createGridButton(this.cancelEditButtonClass, this.cancelEditButtonTooltip, function(grid, e) { grid.cancelEdit(); e.stopPropagation(); }); }, _createGridButton: function(cls, tooltip, clickHandler) { var grid = this._grid; return $("<input>").addClass(this.buttonClass) .addClass(cls) .attr({ type: "button", title: tooltip }) .on("click", function(e) { clickHandler(grid, e); }); }, editValue: function() { return ""; } }); jsGrid.fields.control = jsGrid.ControlField = ControlField; }(jsGrid, jQuery));
2881099/FreeSql.AdminLTE
37,211
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/jsgrid/jsgrid.min.js
/* * jsGrid v1.5.3 (http://js-grid.com) * (c) 2016 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ !function(a,b,c){function d(a,c){var d=b(a);d.data(f,this),this._container=d,this.data=[],this.fields=[],this._editingRow=null,this._sortField=null,this._sortOrder=i,this._firstDisplayingPage=1,this._init(c),this.render()}var e="JSGrid",f=e,g="JSGridItem",h="JSGridEditRow",i="asc",j="desc",k="{first}",l="{pages}",m="{prev}",n="{next}",o="{last}",p="{pageIndex}",q="{pageCount}",r="{itemCount}",s="javascript:void(0);",t=function(a,c){return b.isFunction(a)?a.apply(c,b.makeArray(arguments).slice(2)):a},u=function(a){var c=b.Deferred();return a&&a.then?a.then(function(){c.resolve.apply(c,arguments)},function(){c.reject.apply(c,arguments)}):c.resolve(a),c.promise()},v={loadData:b.noop,insertItem:b.noop,updateItem:b.noop,deleteItem:b.noop};d.prototype={width:"auto",height:"auto",updateOnResize:!0,rowClass:b.noop,rowRenderer:null,rowClick:function(a){this.editing&&this.editItem(b(a.event.target).closest("tr"))},rowDoubleClick:b.noop,noDataContent:"Not found",noDataRowClass:"jsgrid-nodata-row",heading:!0,headerRowRenderer:null,headerRowClass:"jsgrid-header-row",headerCellClass:"jsgrid-header-cell",filtering:!1,filterRowRenderer:null,filterRowClass:"jsgrid-filter-row",inserting:!1,insertRowRenderer:null,insertRowClass:"jsgrid-insert-row",editing:!1,editRowRenderer:null,editRowClass:"jsgrid-edit-row",confirmDeleting:!0,deleteConfirm:"Are you sure?",selecting:!0,selectedRowClass:"jsgrid-selected-row",oddRowClass:"jsgrid-row",evenRowClass:"jsgrid-alt-row",cellClass:"jsgrid-cell",sorting:!1,sortableClass:"jsgrid-header-sortable",sortAscClass:"jsgrid-header-sort jsgrid-header-sort-asc",sortDescClass:"jsgrid-header-sort jsgrid-header-sort-desc",paging:!1,pagerContainer:null,pageIndex:1,pageSize:20,pageButtonCount:15,pagerFormat:"Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}",pagePrevText:"Prev",pageNextText:"Next",pageFirstText:"First",pageLastText:"Last",pageNavigatorNextText:"...",pageNavigatorPrevText:"...",pagerContainerClass:"jsgrid-pager-container",pagerClass:"jsgrid-pager",pagerNavButtonClass:"jsgrid-pager-nav-button",pagerNavButtonInactiveClass:"jsgrid-pager-nav-inactive-button",pageClass:"jsgrid-pager-page",currentPageClass:"jsgrid-pager-current-page",customLoading:!1,pageLoading:!1,autoload:!1,controller:v,loadIndication:!0,loadIndicationDelay:500,loadMessage:"Please, wait...",loadShading:!0,invalidMessage:"Invalid data entered!",invalidNotify:function(c){var d=b.map(c.errors,function(a){return a.message||null});a.alert([this.invalidMessage].concat(d).join("\n"))},onInit:b.noop,onRefreshing:b.noop,onRefreshed:b.noop,onPageChanged:b.noop,onItemDeleting:b.noop,onItemDeleted:b.noop,onItemInserting:b.noop,onItemInserted:b.noop,onItemEditing:b.noop,onItemUpdating:b.noop,onItemUpdated:b.noop,onItemInvalid:b.noop,onDataLoading:b.noop,onDataLoaded:b.noop,onOptionChanging:b.noop,onOptionChanged:b.noop,onError:b.noop,invalidClass:"jsgrid-invalid",containerClass:"jsgrid",tableClass:"jsgrid-table",gridHeaderClass:"jsgrid-grid-header",gridBodyClass:"jsgrid-grid-body",_init:function(a){b.extend(this,a),this._initLoadStrategy(),this._initController(),this._initFields(),this._attachWindowLoadResize(),this._attachWindowResizeCallback(),this._callEventHandler(this.onInit)},loadStrategy:function(){return this.pageLoading?new jsGrid.loadStrategies.PageLoadingStrategy(this):new jsGrid.loadStrategies.DirectLoadingStrategy(this)},_initLoadStrategy:function(){this._loadStrategy=t(this.loadStrategy,this)},_initController:function(){this._controller=b.extend({},v,t(this.controller,this))},renderTemplate:function(a,b,d){args=[];for(var e in d)args.push(d[e]);return args.unshift(a,b),a=t.apply(null,args),a===c||null===a?"":a},loadIndicator:function(a){return new jsGrid.LoadIndicator(a)},validation:function(a){return jsGrid.Validation&&new jsGrid.Validation(a)},_initFields:function(){var a=this;a.fields=b.map(a.fields,function(c){if(b.isPlainObject(c)){var d=c.type&&jsGrid.fields[c.type]||jsGrid.Field;c=new d(c)}return c._grid=a,c})},_attachWindowLoadResize:function(){b(a).on("load",b.proxy(this._refreshSize,this))},_attachWindowResizeCallback:function(){this.updateOnResize&&b(a).on("resize",b.proxy(this._refreshSize,this))},_detachWindowResizeCallback:function(){b(a).off("resize",this._refreshSize)},option:function(a,b){var c,d;return 1===arguments.length?this[a]:(c={option:a,oldValue:this[a],newValue:b},this._callEventHandler(this.onOptionChanging,c),this._handleOptionChange(c.option,c.newValue),d={option:c.option,value:c.newValue},void this._callEventHandler(this.onOptionChanged,d))},fieldOption:function(a,b,c){return a=this._normalizeField(a),2===arguments.length?a[b]:(a[b]=c,void this._renderGrid())},_handleOptionChange:function(a,b){switch(this[a]=b,a){case"width":case"height":this._refreshSize();break;case"rowClass":case"rowRenderer":case"rowClick":case"rowDoubleClick":case"noDataRowClass":case"noDataContent":case"selecting":case"selectedRowClass":case"oddRowClass":case"evenRowClass":this._refreshContent();break;case"pageButtonCount":case"pagerFormat":case"pagePrevText":case"pageNextText":case"pageFirstText":case"pageLastText":case"pageNavigatorNextText":case"pageNavigatorPrevText":case"pagerClass":case"pagerNavButtonClass":case"pageClass":case"currentPageClass":case"pagerRenderer":this._refreshPager();break;case"fields":this._initFields(),this.render();break;case"data":case"editing":case"heading":case"filtering":case"inserting":case"paging":this.refresh();break;case"loadStrategy":case"pageLoading":this._initLoadStrategy(),this.search();break;case"pageIndex":this.openPage(b);break;case"pageSize":this.refresh(),this.search();break;case"editRowRenderer":case"editRowClass":this.cancelEdit();break;case"updateOnResize":this._detachWindowResizeCallback(),this._attachWindowResizeCallback();break;case"invalidNotify":case"invalidMessage":break;default:this.render()}},destroy:function(){this._detachWindowResizeCallback(),this._clear(),this._container.removeData(f)},render:function(){return this._renderGrid(),this.autoload?this.loadData():b.Deferred().resolve().promise()},_renderGrid:function(){this._clear(),this._container.addClass(this.containerClass).css("position","relative").append(this._createHeader()).append(this._createBody()),this._pagerContainer=this._createPagerContainer(),this._loadIndicator=this._createLoadIndicator(),this._validation=this._createValidation(),this.refresh()},_createLoadIndicator:function(){return t(this.loadIndicator,this,{message:this.loadMessage,shading:this.loadShading,container:this._container})},_createValidation:function(){return t(this.validation,this)},_clear:function(){this.cancelEdit(),clearTimeout(this._loadingTimer),this._pagerContainer&&this._pagerContainer.empty(),this._container.empty().css({position:"",width:"",height:""})},_createHeader:function(){var a=this._headerRow=this._createHeaderRow(),c=this._filterRow=this._createFilterRow(),d=this._insertRow=this._createInsertRow(),e=this._headerGrid=b("<table>").addClass(this.tableClass).append(a).append(c).append(d),f=this._header=b("<div>").addClass(this.gridHeaderClass).addClass(this._scrollBarWidth()?"jsgrid-header-scrollbar":"").append(e);return f},_createBody:function(){var a=this._content=b("<tbody>"),c=this._bodyGrid=b("<table>").addClass(this.tableClass).append(a),d=this._body=b("<div>").addClass(this.gridBodyClass).append(c).on("scroll",b.proxy(function(a){this._header.scrollLeft(a.target.scrollLeft)},this));return d},_createPagerContainer:function(){var a=this.pagerContainer||b("<div>").appendTo(this._container);return b(a).addClass(this.pagerContainerClass)},_eachField:function(a){var c=this;b.each(this.fields,function(b,d){d.visible&&a.call(c,d,b)})},_createHeaderRow:function(){if(b.isFunction(this.headerRowRenderer))return b(this.renderTemplate(this.headerRowRenderer,this));var a=b("<tr>").addClass(this.headerRowClass);return this._eachField(function(c,d){var e=this._prepareCell("<th>",c,"headercss",this.headerCellClass).append(this.renderTemplate(c.headerTemplate,c)).appendTo(a);this.sorting&&c.sorting&&e.addClass(this.sortableClass).on("click",b.proxy(function(){this.sort(d)},this))}),a},_prepareCell:function(a,c,d,e){return b(a).css("width",c.width).addClass(e||this.cellClass).addClass(d&&c[d]||c.css).addClass(c.align?"jsgrid-align-"+c.align:"")},_createFilterRow:function(){if(b.isFunction(this.filterRowRenderer))return b(this.renderTemplate(this.filterRowRenderer,this));var a=b("<tr>").addClass(this.filterRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"filtercss").append(this.renderTemplate(b.filterTemplate,b)).appendTo(a)}),a},_createInsertRow:function(){if(b.isFunction(this.insertRowRenderer))return b(this.renderTemplate(this.insertRowRenderer,this));var a=b("<tr>").addClass(this.insertRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"insertcss").append(this.renderTemplate(b.insertTemplate,b)).appendTo(a)}),a},_callEventHandler:function(a,c){return a.call(this,b.extend(c,{grid:this})),c},reset:function(){return this._resetSorting(),this._resetPager(),this._loadStrategy.reset()},_resetPager:function(){this._firstDisplayingPage=1,this._setPage(1)},_resetSorting:function(){this._sortField=null,this._sortOrder=i,this._clearSortingCss()},refresh:function(){this._callEventHandler(this.onRefreshing),this.cancelEdit(),this._refreshHeading(),this._refreshFiltering(),this._refreshInserting(),this._refreshContent(),this._refreshPager(),this._refreshSize(),this._callEventHandler(this.onRefreshed)},_refreshHeading:function(){this._headerRow.toggle(this.heading)},_refreshFiltering:function(){this._filterRow.toggle(this.filtering)},_refreshInserting:function(){this._insertRow.toggle(this.inserting)},_refreshContent:function(){var a=this._content;if(a.empty(),!this.data.length)return a.append(this._createNoDataRow()),this;for(var b=this._loadStrategy.firstDisplayIndex(),c=this._loadStrategy.lastDisplayIndex(),d=b;c>d;d++){var e=this.data[d];a.append(this._createRow(e,d))}},_createNoDataRow:function(){var a=0;return this._eachField(function(){a++}),b("<tr>").addClass(this.noDataRowClass).append(b("<td>").addClass(this.cellClass).attr("colspan",a).append(this.renderTemplate(this.noDataContent,this)))},_createRow:function(a,c){var d;return b.isFunction(this.rowRenderer)?d=this.renderTemplate(this.rowRenderer,this,{item:a,itemIndex:c}):(d=b("<tr>"),this._renderCells(d,a)),d.addClass(this._getRowClasses(a,c)).data(g,a).on("click",b.proxy(function(b){this.rowClick({item:a,itemIndex:c,event:b})},this)).on("dblclick",b.proxy(function(b){this.rowDoubleClick({item:a,itemIndex:c,event:b})},this)),this.selecting&&this._attachRowHover(d),d},_getRowClasses:function(a,b){var c=[];return c.push((b+1)%2?this.oddRowClass:this.evenRowClass),c.push(t(this.rowClass,this,a,b)),c.join(" ")},_attachRowHover:function(a){var c=this.selectedRowClass;a.hover(function(){b(this).addClass(c)},function(){b(this).removeClass(c)})},_renderCells:function(a,b){return this._eachField(function(c){a.append(this._createCell(b,c))}),this},_createCell:function(a,c){var d,e=this._getItemFieldValue(a,c),f={value:e,item:a};return d=b.isFunction(c.cellRenderer)?this.renderTemplate(c.cellRenderer,c,f):b("<td>").append(this.renderTemplate(c.itemTemplate||e,c,f)),this._prepareCell(d,c)},_getItemFieldValue:function(a,b){for(var c=b.name.split("."),d=a[c.shift()];d&&c.length;)d=d[c.shift()];return d},_setItemFieldValue:function(a,b,c){for(var d=b.name.split("."),e=a,f=d[0];e&&d.length;)a=e,f=d.shift(),e=a[f];if(!e)for(;d.length;)a=a[f]={},f=d.shift();a[f]=c},sort:function(a,c){return b.isPlainObject(a)&&(c=a.order,a=a.field),this._clearSortingCss(),this._setSortingParams(a,c),this._setSortingCss(),this._loadStrategy.sort()},_clearSortingCss:function(){this._headerRow.find("th").removeClass(this.sortAscClass).removeClass(this.sortDescClass)},_setSortingParams:function(a,b){a=this._normalizeField(a),b=b||(this._sortField===a?this._reversedSortOrder(this._sortOrder):i),this._sortField=a,this._sortOrder=b},_normalizeField:function(a){return b.isNumeric(a)?this.fields[a]:"string"==typeof a?b.grep(this.fields,function(b){return b.name===a})[0]:a},_reversedSortOrder:function(a){return a===i?j:i},_setSortingCss:function(){var a=this._visibleFieldIndex(this._sortField);this._headerRow.find("th").eq(a).addClass(this._sortOrder===i?this.sortAscClass:this.sortDescClass)},_visibleFieldIndex:function(a){return b.inArray(a,b.grep(this.fields,function(a){return a.visible}))},_sortData:function(){var a=this._sortFactor(),b=this._sortField;b&&this.data.sort(function(c,d){return a*b.sortingFunc(c[b.name],d[b.name])})},_sortFactor:function(){return this._sortOrder===i?1:-1},_itemsCount:function(){return this._loadStrategy.itemsCount()},_pagesCount:function(){var a=this._itemsCount(),b=this.pageSize;return Math.floor(a/b)+(a%b?1:0)},_refreshPager:function(){var a=this._pagerContainer;a.empty(),this.paging&&a.append(this._createPager());var b=this.paging&&this._pagesCount()>1;a.toggle(b)},_createPager:function(){var a;return a=b.isFunction(this.pagerRenderer)?b(this.pagerRenderer({pageIndex:this.pageIndex,pageCount:this._pagesCount()})):b("<div>").append(this._createPagerByFormat()),a.addClass(this.pagerClass),a},_createPagerByFormat:function(){var a=this.pageIndex,c=this._pagesCount(),d=this._itemsCount(),e=this.pagerFormat.split(" ");return b.map(e,b.proxy(function(e){var f=e;return e===l?f=this._createPages():e===k?f=this._createPagerNavButton(this.pageFirstText,1,a>1):e===m?f=this._createPagerNavButton(this.pagePrevText,a-1,a>1):e===n?f=this._createPagerNavButton(this.pageNextText,a+1,c>a):e===o?f=this._createPagerNavButton(this.pageLastText,c,c>a):e===p?f=a:e===q?f=c:e===r&&(f=d),b.isArray(f)?f.concat([" "]):[f," "]},this))},_createPages:function(){var a=this._pagesCount(),b=this.pageButtonCount,c=this._firstDisplayingPage,d=[];c>1&&d.push(this._createPagerPageNavButton(this.pageNavigatorPrevText,this.showPrevPages));for(var e=0,f=c;b>e&&a>=f;e++,f++)d.push(f===this.pageIndex?this._createPagerCurrentPage():this._createPagerPage(f));return a>c+b-1&&d.push(this._createPagerPageNavButton(this.pageNavigatorNextText,this.showNextPages)),d},_createPagerNavButton:function(a,c,d){return this._createPagerButton(a,this.pagerNavButtonClass+(d?"":" "+this.pagerNavButtonInactiveClass),d?function(){this.openPage(c)}:b.noop)},_createPagerPageNavButton:function(a,b){return this._createPagerButton(a,this.pagerNavButtonClass,b)},_createPagerPage:function(a){return this._createPagerButton(a,this.pageClass,function(){this.openPage(a)})},_createPagerButton:function(a,c,d){var e=b("<a>").attr("href",s).html(a).on("click",b.proxy(d,this));return b("<span>").addClass(c).append(e)},_createPagerCurrentPage:function(){return b("<span>").addClass(this.pageClass).addClass(this.currentPageClass).text(this.pageIndex)},_refreshSize:function(){this._refreshHeight(),this._refreshWidth()},_refreshWidth:function(){var a="auto"===this.width?this._getAutoWidth():this.width;this._container.width(a)},_getAutoWidth:function(){var a=this._headerGrid,b=this._header;a.width("auto");var c=a.outerWidth(),d=b.outerWidth()-b.innerWidth();return a.width(""),c+d},_scrollBarWidth:function(){var a;return function(){if(a===c){var d=b("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"),e=b("<div style='height:100px;'></div>");d.append(e).appendTo("body");var f=e.innerWidth();d.css("overflow-y","auto");var g=e.innerWidth();d.remove(),a=f-g}return a}}(),_refreshHeight:function(){var a,b=this._container,c=this._pagerContainer,d=this.height;b.height(d),"auto"!==d&&(d=b.height(),a=this._header.outerHeight(!0),c.parents(b).length&&(a+=c.outerHeight(!0)),this._body.outerHeight(d-a))},showPrevPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount;this._firstDisplayingPage=a>b?a-b:1,this._refreshPager()},showNextPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount,c=this._pagesCount();this._firstDisplayingPage=a+2*b>c?c-b+1:a+b,this._refreshPager()},openPage:function(a){1>a||a>this._pagesCount()||(this._setPage(a),this._loadStrategy.openPage(a))},_setPage:function(a){var b=this._firstDisplayingPage,c=this.pageButtonCount;this.pageIndex=a,b>a&&(this._firstDisplayingPage=a),a>b+c-1&&(this._firstDisplayingPage=a-c+1),this._callEventHandler(this.onPageChanged,{pageIndex:a})},_controllerCall:function(a,c,d,e){if(d)return b.Deferred().reject().promise();this._showLoading();var f=this._controller;if(!f||!f[a])throw Error("controller has no method '"+a+"'");return u(f[a](c)).done(b.proxy(e,this)).fail(b.proxy(this._errorHandler,this)).always(b.proxy(this._hideLoading,this))},_errorHandler:function(){this._callEventHandler(this.onError,{args:b.makeArray(arguments)})},_showLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadingTimer=setTimeout(b.proxy(function(){this._loadIndicator.show()},this),this.loadIndicationDelay))},_hideLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadIndicator.hide())},search:function(a){return this._resetSorting(),this._resetPager(),this.loadData(a)},loadData:function(a){a=a||(this.filtering?this.getFilter():{}),b.extend(a,this._loadStrategy.loadParams(),this._sortingParams());var c=this._callEventHandler(this.onDataLoading,{filter:a});return this._controllerCall("loadData",a,c.cancel,function(a){a&&(this._loadStrategy.finishLoad(a),this._callEventHandler(this.onDataLoaded,{data:a}))})},getFilter:function(){var a={};return this._eachField(function(b){b.filtering&&this._setItemFieldValue(a,b,b.filterValue())}),a},_sortingParams:function(){return this.sorting&&this._sortField?{sortField:this._sortField.name,sortOrder:this._sortOrder}:{}},getSorting:function(){var a=this._sortingParams();return{field:a.sortField,order:a.sortOrder}},clearFilter:function(){var a=this._createFilterRow();return this._filterRow.replaceWith(a),this._filterRow=a,this.search()},insertItem:function(a){var c=a||this._getValidatedInsertItem();if(!c)return b.Deferred().reject().promise();var d=this._callEventHandler(this.onItemInserting,{item:c});return this._controllerCall("insertItem",c,d.cancel,function(a){a=a||c,this._loadStrategy.finishInsert(a),this._callEventHandler(this.onItemInserted,{item:a})})},_getValidatedInsertItem:function(){var a=this._getInsertItem();return this._validateItem(a,this._insertRow)?a:null},_getInsertItem:function(){var a={};return this._eachField(function(b){b.inserting&&this._setItemFieldValue(a,b,b.insertValue())}),a},_validateItem:function(a,c){var d=[],e={item:a,itemIndex:this._rowIndex(c),row:c};if(this._eachField(function(f){if(f.validate&&(c!==this._insertRow||f.inserting)&&(c!==this._getEditRow()||f.editing)){var g=this._getItemFieldValue(a,f),h=this._validation.validate(b.extend({value:g,rules:f.validate},e));this._setCellValidity(c.children().eq(this._visibleFieldIndex(f)),h),h.length&&d.push.apply(d,b.map(h,function(a){return{field:f,message:a}}))}}),!d.length)return!0;var f=b.extend({errors:d},e);return this._callEventHandler(this.onItemInvalid,f),this.invalidNotify(f),!1},_setCellValidity:function(a,b){a.toggleClass(this.invalidClass,!!b.length).attr("title",b.join("\n"))},clearInsert:function(){var a=this._createInsertRow();this._insertRow.replaceWith(a),this._insertRow=a,this.refresh()},editItem:function(a){var b=this.rowByItem(a);b.length&&this._editRow(b)},rowByItem:function(a){return a.jquery||a.nodeType?b(a):this._content.find("tr").filter(function(){return b.data(this,g)===a})},_editRow:function(a){if(this.editing){var b=a.data(g),c=this._callEventHandler(this.onItemEditing,{row:a,item:b,itemIndex:this._itemIndex(b)});if(!c.cancel){this._editingRow&&this.cancelEdit();var d=this._createEditRow(b);this._editingRow=a,a.hide(),d.insertBefore(a),a.data(h,d)}}},_createEditRow:function(a){if(b.isFunction(this.editRowRenderer))return b(this.renderTemplate(this.editRowRenderer,this,{item:a,itemIndex:this._itemIndex(a)}));var c=b("<tr>").addClass(this.editRowClass);return this._eachField(function(b){var d=this._getItemFieldValue(a,b);this._prepareCell("<td>",b,"editcss").append(this.renderTemplate(b.editTemplate||"",b,{value:d,item:a})).appendTo(c)}),c},updateItem:function(a,b){1===arguments.length&&(b=a);var c=a?this.rowByItem(a):this._editingRow;return(b=b||this._getValidatedEditedItem())?this._updateRow(c,b):void 0},_getValidatedEditedItem:function(){var a=this._getEditedItem();return this._validateItem(a,this._getEditRow())?a:null},_updateRow:function(a,c){var d=a.data(g),e=this._itemIndex(d),f=b.extend(!0,{},d,c),h=this._callEventHandler(this.onItemUpdating,{row:a,item:f,itemIndex:e,previousItem:d});return this._controllerCall("updateItem",f,h.cancel,function(g){var h=b.extend(!0,{},d);f=g||b.extend(!0,d,c);var i=this._finishUpdate(a,f,e);this._callEventHandler(this.onItemUpdated,{row:i,item:f,itemIndex:e,previousItem:h})})},_rowIndex:function(a){return this._content.children().index(b(a))},_itemIndex:function(a){return b.inArray(a,this.data)},_finishUpdate:function(a,b,c){this.cancelEdit(),this.data[c]=b;var d=this._createRow(b,c);return a.replaceWith(d),d},_getEditedItem:function(){var a={};return this._eachField(function(b){b.editing&&this._setItemFieldValue(a,b,b.editValue())}),a},cancelEdit:function(){this._editingRow&&(this._getEditRow().remove(),this._editingRow.show(),this._editingRow=null)},_getEditRow:function(){return this._editingRow&&this._editingRow.data(h)},deleteItem:function(b){var c=this.rowByItem(b);if(c.length&&(!this.confirmDeleting||a.confirm(t(this.deleteConfirm,this,c.data(g)))))return this._deleteRow(c)},_deleteRow:function(a){var b=a.data(g),c=this._itemIndex(b),d=this._callEventHandler(this.onItemDeleting,{row:a,item:b,itemIndex:c});return this._controllerCall("deleteItem",b,d.cancel,function(){this._loadStrategy.finishDelete(b,c),this._callEventHandler(this.onItemDeleted,{row:a,item:b,itemIndex:c})})}},b.fn.jsGrid=function(a){var e=b.makeArray(arguments),g=e.slice(1),h=this;return this.each(function(){var e,i=b(this),j=i.data(f);if(j)if("string"==typeof a){if(e=j[a].apply(j,g),e!==c&&e!==j)return h=e,!1}else j._detachWindowResizeCallback(),j._init(a),j.render();else new d(i,a)}),h};var w={},x=function(a){var c;b.isPlainObject(a)?c=d.prototype:(c=w[a].prototype,a=arguments[1]||{}),b.extend(c,a)},y={},z=function(a){var c=b.isPlainObject(a)?a:y[a];if(!c)throw Error("unknown locale "+a);A(jsGrid,c)},A=function(a,c){b.each(c,function(c,d){return b.isPlainObject(d)?void A(a[c]||a[c[0].toUpperCase()+c.slice(1)],d):void(a.hasOwnProperty(c)?a[c]=d:a.prototype[c]=d)})};a.jsGrid={Grid:d,fields:w,setDefaults:x,locales:y,locale:z,version:"1.5.3"}}(window,jQuery),function(a,b){function c(a){this._init(a)}c.prototype={container:"body",message:"Loading...",shading:!0,zIndex:1e3,shaderClass:"jsgrid-load-shader",loadPanelClass:"jsgrid-load-panel",_init:function(a){b.extend(!0,this,a),this._initContainer(),this._initShader(),this._initLoadPanel()},_initContainer:function(){this._container=b(this.container)},_initShader:function(){this.shading&&(this._shader=b("<div>").addClass(this.shaderClass).hide().css({position:"absolute",top:0,right:0,bottom:0,left:0,zIndex:this.zIndex}).appendTo(this._container))},_initLoadPanel:function(){this._loadPanel=b("<div>").addClass(this.loadPanelClass).text(this.message).hide().css({position:"absolute",top:"50%",left:"50%",zIndex:this.zIndex}).appendTo(this._container)},show:function(){var a=this._loadPanel.show(),b=a.outerWidth(),c=a.outerHeight();a.css({marginTop:-c/2,marginLeft:-b/2}),this._shader.show()},hide:function(){this._loadPanel.hide(),this._shader.hide()}},a.LoadIndicator=c}(jsGrid,jQuery),function(a,b){function c(a){this._grid=a}function d(a){this._grid=a,this._itemsCount=0}c.prototype={firstDisplayIndex:function(){var a=this._grid;return a.option("paging")?(a.option("pageIndex")-1)*a.option("pageSize"):0},lastDisplayIndex:function(){var a=this._grid,b=a.option("data").length;return a.option("paging")?Math.min(a.option("pageIndex")*a.option("pageSize"),b):b},itemsCount:function(){return this._grid.option("data").length},openPage:function(){this._grid.refresh()},loadParams:function(){return{}},sort:function(){return this._grid._sortData(),this._grid.refresh(),b.Deferred().resolve().promise()},reset:function(){return this._grid.refresh(),b.Deferred().resolve().promise()},finishLoad:function(a){this._grid.option("data",a)},finishInsert:function(a){var b=this._grid;b.option("data").push(a),b.refresh()},finishDelete:function(a,b){var c=this._grid;c.option("data").splice(b,1),c.reset()}},d.prototype={firstDisplayIndex:function(){return 0},lastDisplayIndex:function(){return this._grid.option("data").length},itemsCount:function(){return this._itemsCount},openPage:function(){this._grid.loadData()},loadParams:function(){var a=this._grid;return{pageIndex:a.option("pageIndex"),pageSize:a.option("pageSize")}},reset:function(){return this._grid.loadData()},sort:function(){return this._grid.loadData()},finishLoad:function(a){this._itemsCount=a.itemsCount,this._grid.option("data",a.data)},finishInsert:function(){this._grid.search()},finishDelete:function(){this._grid.search()}},a.loadStrategies={DirectLoadingStrategy:c,PageLoadingStrategy:d}}(jsGrid,jQuery),function(a){var b=function(a){return"undefined"!=typeof a&&null!==a},c={string:function(a,c){return b(a)||b(c)?b(a)?b(c)?(""+a).localeCompare(""+c):1:-1:0},number:function(a,b){return a-b},date:function(a,b){return a-b},numberAsString:function(a,b){return parseFloat(a)-parseFloat(b)}};a.sortStrategies=c}(jsGrid,jQuery),function(a,b,c){function d(a){this._init(a)}d.prototype={_init:function(a){b.extend(!0,this,a)},validate:function(a){var c=[];return b.each(this._normalizeRules(a.rules),function(d,e){if(!e.validator(a.value,a.item,e.param)){var f=b.isFunction(e.message)?e.message(a.value,a.item):e.message;c.push(f)}}),c},_normalizeRules:function(a){return b.isArray(a)||(a=[a]),b.map(a,b.proxy(function(a){return this._normalizeRule(a)},this))},_normalizeRule:function(a){if("string"==typeof a&&(a={validator:a}),b.isFunction(a)&&(a={validator:a}),!b.isPlainObject(a))throw Error("wrong validation config specified");return a=b.extend({},a),b.isFunction(a.validator)?a:this._applyNamedValidator(a,a.validator)},_applyNamedValidator:function(a,c){delete a.validator;var d=e[c];if(!d)throw Error('unknown validator "'+c+'"');return b.isFunction(d)&&(d={validator:d}),b.extend({},d,a)}},a.Validation=d;var e={required:{message:"Field is required",validator:function(a){return a!==c&&null!==a&&""!==a}},rangeLength:{message:"Field value length is out of the defined range",validator:function(a,b,c){return a.length>=c[0]&&a.length<=c[1]}},minLength:{message:"Field value is too short",validator:function(a,b,c){return a.length>=c}},maxLength:{message:"Field value is too long",validator:function(a,b,c){return a.length<=c}},pattern:{message:"Field value is not matching the defined pattern",validator:function(a,b,c){return"string"==typeof c&&(c=new RegExp("^(?:"+c+")$")),c.test(a)}},range:{message:"Field value is out of the defined range",validator:function(a,b,c){return a>=c[0]&&a<=c[1]}},min:{message:"Field value is too small",validator:function(a,b,c){return a>=c}},max:{message:"Field value is too large",validator:function(a,b,c){return c>=a}}};a.validators=e}(jsGrid,jQuery),function(a,b,c){function d(a){b.extend(!0,this,a),this.sortingFunc=this._getSortingFunc()}d.prototype={name:"",title:null,css:"",align:"",width:100,visible:!0,filtering:!0,inserting:!0,editing:!0,sorting:!0,sorter:"string",headerTemplate:function(){return this.title===c||null===this.title?this.name:this.title},itemTemplate:function(a){return a},filterTemplate:function(){return""},insertTemplate:function(){return""},editTemplate:function(a,b){return this._value=a,this.itemTemplate(a,b)},filterValue:function(){return""},insertValue:function(){return""},editValue:function(){return this._value},_getSortingFunc:function(){var c=this.sorter;if(b.isFunction(c))return c;if("string"==typeof c)return a.sortStrategies[c];throw Error('wrong sorter for the field "'+this.name+'"!')}},a.Field=d}(jsGrid,jQuery),function(a,b){function c(a){d.call(this,a)}var d=a.Field;c.prototype=new d({autosearch:!0,readOnly:!1,filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createTextBox();return this.autosearch&&b.on("keypress",function(b){13===b.which&&(a.search(),b.preventDefault())}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createTextBox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextBox();return b.val(a),b},filterValue:function(){return this.filterControl.val()},insertValue:function(){return this.insertControl.val()},editValue:function(){return this.editControl.val()},_createTextBox:function(){return b("<input>").attr("type","text").prop("readonly",!!this.readOnly)}}),a.fields.text=a.TextField=c}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.TextField;d.prototype=new e({sorter:"number",align:"right",readOnly:!1,filterValue:function(){return this.filterControl.val()?parseInt(this.filterControl.val()||0,10):c},insertValue:function(){return this.insertControl.val()?parseInt(this.insertControl.val()||0,10):c},editValue:function(){return this.editControl.val()?parseInt(this.editControl.val()||0,10):c},_createTextBox:function(){return b("<input>").attr("type","number").prop("readonly",!!this.readOnly)}}),a.fields.number=a.NumberField=d}(jsGrid,jQuery),function(a,b){function c(a){d.call(this,a)}var d=a.TextField;c.prototype=new d({insertTemplate:function(){return this.inserting?this.insertControl=this._createTextArea():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextArea();return b.val(a),b},_createTextArea:function(){return b("<textarea>").prop("readonly",!!this.readOnly)}}),a.fields.textarea=a.TextAreaField=c}(jsGrid,jQuery),function(a,b,c){function d(a){if(this.items=[],this.selectedIndex=-1,this.valueField="",this.textField="",a.valueField&&a.items.length){var b=a.items[0][a.valueField];this.valueType=typeof b===f?f:g}this.sorter=this.valueType,e.call(this,a)}var e=a.NumberField,f="number",g="string";d.prototype=new e({align:"center",valueType:f,itemTemplate:function(a){var d,e=this.items,f=this.valueField,g=this.textField;d=f?b.grep(e,function(b){return b[f]===a})[0]||{}:e[a];var h=g?d[g]:d;return h===c||null===h?"":h},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createSelect();return this.autosearch&&b.on("change",function(){a.search()}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createSelect():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createSelect();return a!==c&&b.val(a),b},filterValue:function(){var a=this.filterControl.val();return this.valueType===f?parseInt(a||0,10):a},insertValue:function(){var a=this.insertControl.val();return this.valueType===f?parseInt(a||0,10):a},editValue:function(){var a=this.editControl.val();return this.valueType===f?parseInt(a||0,10):a},_createSelect:function(){var a=b("<select>"),c=this.valueField,d=this.textField,e=this.selectedIndex;return b.each(this.items,function(f,g){var h=c?g[c]:f,i=d?g[d]:g,j=b("<option>").attr("value",h).text(i).appendTo(a);j.prop("selected",e===f)}),a.prop("disabled",!!this.readOnly),a}}),a.fields.select=a.SelectField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.Field;d.prototype=new e({sorter:"number",align:"center",autosearch:!0,itemTemplate:function(a){return this._createCheckbox().prop({checked:a,disabled:!0})},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,c=this.filterControl=this._createCheckbox();return c.prop({readOnly:!0,indeterminate:!0}),c.on("click",function(){var a=b(this); a.prop("readOnly")?a.prop({checked:!1,readOnly:!1}):a.prop("checked")||a.prop({readOnly:!0,indeterminate:!0})}),this.autosearch&&c.on("click",function(){a.search()}),c},insertTemplate:function(){return this.inserting?this.insertControl=this._createCheckbox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createCheckbox();return b.prop("checked",a),b},filterValue:function(){return this.filterControl.get(0).indeterminate?c:this.filterControl.is(":checked")},insertValue:function(){return this.insertControl.is(":checked")},editValue:function(){return this.editControl.is(":checked")},_createCheckbox:function(){return b("<input>").attr("type","checkbox")}}),a.fields.checkbox=a.CheckboxField=d}(jsGrid,jQuery),function(a,b){function c(a){d.call(this,a),this._configInitialized=!1}var d=a.Field;c.prototype=new d({css:"jsgrid-control-field",align:"center",width:50,filtering:!1,inserting:!1,editing:!1,sorting:!1,buttonClass:"jsgrid-button",modeButtonClass:"jsgrid-mode-button",modeOnButtonClass:"jsgrid-mode-on-button",searchModeButtonClass:"jsgrid-search-mode-button",insertModeButtonClass:"jsgrid-insert-mode-button",editButtonClass:"jsgrid-edit-button",deleteButtonClass:"jsgrid-delete-button",searchButtonClass:"jsgrid-search-button",clearFilterButtonClass:"jsgrid-clear-filter-button",insertButtonClass:"jsgrid-insert-button",updateButtonClass:"jsgrid-update-button",cancelEditButtonClass:"jsgrid-cancel-edit-button",searchModeButtonTooltip:"Switch to searching",insertModeButtonTooltip:"Switch to inserting",editButtonTooltip:"Edit",deleteButtonTooltip:"Delete",searchButtonTooltip:"Search",clearFilterButtonTooltip:"Clear filter",insertButtonTooltip:"Insert",updateButtonTooltip:"Update",cancelEditButtonTooltip:"Cancel edit",editButton:!0,deleteButton:!0,clearFilterButton:!0,modeSwitchButton:!0,_initConfig:function(){this._hasFiltering=this._grid.filtering,this._hasInserting=this._grid.inserting,this._hasInserting&&this.modeSwitchButton&&(this._grid.inserting=!1),this._configInitialized=!0},headerTemplate:function(){this._configInitialized||this._initConfig();var a=this._hasFiltering,b=this._hasInserting;return this.modeSwitchButton&&(a||b)?a&&!b?this._createFilterSwitchButton():b&&!a?this._createInsertSwitchButton():this._createModeSwitchButton():""},itemTemplate:function(a,c){var d=b([]);return this.editButton&&(d=d.add(this._createEditButton(c))),this.deleteButton&&(d=d.add(this._createDeleteButton(c))),d},filterTemplate:function(){var a=this._createSearchButton();return this.clearFilterButton?a.add(this._createClearFilterButton()):a},insertTemplate:function(){return this._createInsertButton()},editTemplate:function(){return this._createUpdateButton().add(this._createCancelEditButton())},_createFilterSwitchButton:function(){return this._createOnOffSwitchButton("filtering",this.searchModeButtonClass,!0)},_createInsertSwitchButton:function(){return this._createOnOffSwitchButton("inserting",this.insertModeButtonClass,!1)},_createOnOffSwitchButton:function(a,c,d){var e=d,f=b.proxy(function(){g.toggleClass(this.modeOnButtonClass,e)},this),g=this._createGridButton(this.modeButtonClass+" "+c,"",function(b){e=!e,b.option(a,e),f()});return f(),g},_createModeSwitchButton:function(){var a=!1,c=b.proxy(function(){d.attr("title",a?this.searchModeButtonTooltip:this.insertModeButtonTooltip).toggleClass(this.insertModeButtonClass,!a).toggleClass(this.searchModeButtonClass,a)},this),d=this._createGridButton(this.modeButtonClass,"",function(b){a=!a,b.option("inserting",a),b.option("filtering",!a),c()});return c(),d},_createEditButton:function(a){return this._createGridButton(this.editButtonClass,this.editButtonTooltip,function(b,c){b.editItem(a),c.stopPropagation()})},_createDeleteButton:function(a){return this._createGridButton(this.deleteButtonClass,this.deleteButtonTooltip,function(b,c){b.deleteItem(a),c.stopPropagation()})},_createSearchButton:function(){return this._createGridButton(this.searchButtonClass,this.searchButtonTooltip,function(a){a.search()})},_createClearFilterButton:function(){return this._createGridButton(this.clearFilterButtonClass,this.clearFilterButtonTooltip,function(a){a.clearFilter()})},_createInsertButton:function(){return this._createGridButton(this.insertButtonClass,this.insertButtonTooltip,function(a){a.insertItem().done(function(){a.clearInsert()})})},_createUpdateButton:function(){return this._createGridButton(this.updateButtonClass,this.updateButtonTooltip,function(a,b){a.updateItem(),b.stopPropagation()})},_createCancelEditButton:function(){return this._createGridButton(this.cancelEditButtonClass,this.cancelEditButtonTooltip,function(a,b){a.cancelEdit(),b.stopPropagation()})},_createGridButton:function(a,c,d){var e=this._grid;return b("<input>").addClass(this.buttonClass).addClass(a).attr({type:"button",title:c}).on("click",function(a){d(e,a)})},editValue:function(){return""}}),a.fields.control=a.ControlField=c}(jsGrid,jQuery);
294coder/Efficient-MIF
8,645
utils/loss_landscape/plot_2D.py
""" 2D plotting funtions """ from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt from matplotlib import cm import h5py import argparse import numpy as np from os.path import exists import seaborn as sns def plot_2d_contour(surf_file, surf_name='train_loss', vmin=0.1, vmax=10, vlevel=0.5, show=False): """Plot 2D contour map and 3D surface.""" f = h5py.File(surf_file, 'r') x = np.array(f['xcoordinates'][:]) y = np.array(f['ycoordinates'][:]) X, Y = np.meshgrid(x, y) if surf_name in f.keys(): Z = np.array(f[surf_name][:]) elif surf_name == 'train_err' or surf_name == 'test_err' : Z = 100 - np.array(f[surf_name][:]) else: print ('%s is not found in %s' % (surf_name, surf_file)) print('------------------------------------------------------------------') print('plot_2d_contour') print('------------------------------------------------------------------') print("loading surface file: " + surf_file) print('len(xcoordinates): %d len(ycoordinates): %d' % (len(x), len(y))) print('max(%s) = %f \t min(%s) = %f' % (surf_name, np.max(Z), surf_name, np.min(Z))) print(Z) if (len(x) <= 1 or len(y) <= 1): print('The length of coordinates is not enough for plotting contours') return # -------------------------------------------------------------------- # Plot 2D contours # -------------------------------------------------------------------- fig = plt.figure() CS = plt.contour(X, Y, Z, cmap='summer', levels=np.arange(vmin, vmax, vlevel)) plt.clabel(CS, inline=1, fontsize=8) fig.savefig(surf_file + '_' + surf_name + '_2dcontour' + '.pdf', dpi=300, bbox_inches='tight', format='pdf') fig = plt.figure() print(surf_file + '_' + surf_name + '_2dcontourf' + '.pdf') CS = plt.contourf(X, Y, Z, cmap='summer', levels=np.arange(vmin, vmax, vlevel)) fig.savefig(surf_file + '_' + surf_name + '_2dcontourf' + '.pdf', dpi=300, bbox_inches='tight', format='pdf') # -------------------------------------------------------------------- # Plot 2D heatmaps # -------------------------------------------------------------------- fig = plt.figure() sns_plot = sns.heatmap(Z, cmap='viridis', cbar=True, vmin=vmin, vmax=vmax, xticklabels=False, yticklabels=False) sns_plot.invert_yaxis() sns_plot.get_figure().savefig(surf_file + '_' + surf_name + '_2dheat.pdf', dpi=300, bbox_inches='tight', format='pdf') # -------------------------------------------------------------------- # Plot 3D surface # -------------------------------------------------------------------- fig = plt.figure() ax = Axes3D(fig) surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) fig.colorbar(surf, shrink=0.5, aspect=5) fig.savefig(surf_file + '_' + surf_name + '_3dsurface.pdf', dpi=300, bbox_inches='tight', format='pdf') f.close() if show: plt.show() def plot_trajectory(proj_file, dir_file, show=False): """ Plot optimization trajectory on the plane spanned by given directions.""" assert exists(proj_file), 'Projection file does not exist.' f = h5py.File(proj_file, 'r') fig = plt.figure() plt.plot(f['proj_xcoord'], f['proj_ycoord'], marker='.') plt.tick_params('y', labelsize='x-large') plt.tick_params('x', labelsize='x-large') f.close() if exists(dir_file): f2 = h5py.File(dir_file,'r') if 'explained_variance_ratio_' in f2.keys(): ratio_x = f2['explained_variance_ratio_'][0] ratio_y = f2['explained_variance_ratio_'][1] plt.xlabel('1st PC: %.2f %%' % (ratio_x*100), fontsize='xx-large') plt.ylabel('2nd PC: %.2f %%' % (ratio_y*100), fontsize='xx-large') f2.close() fig.savefig(proj_file + '.pdf', dpi=300, bbox_inches='tight', format='pdf') if show: plt.show() def plot_contour_trajectory(surf_file, dir_file, proj_file, surf_name='loss_vals', vmin=0.1, vmax=10, vlevel=0.5, show=False): """2D contour + trajectory""" assert exists(surf_file) and exists(proj_file) and exists(dir_file) # plot contours f = h5py.File(surf_file,'r') x = np.array(f['xcoordinates'][:]) y = np.array(f['ycoordinates'][:]) X, Y = np.meshgrid(x, y) if surf_name in f.keys(): Z = np.array(f[surf_name][:]) fig = plt.figure() CS1 = plt.contour(X, Y, Z, levels=np.arange(vmin, vmax, vlevel)) CS2 = plt.contour(X, Y, Z, levels=np.logspace(1, 8, num=8)) # plot trajectories pf = h5py.File(proj_file, 'r') plt.plot(pf['proj_xcoord'], pf['proj_ycoord'], marker='.') # plot red points when learning rate decays # for e in [150, 225, 275]: # plt.plot([pf['proj_xcoord'][e]], [pf['proj_ycoord'][e]], marker='.', color='r') # add PCA notes df = h5py.File(dir_file,'r') ratio_x = df['explained_variance_ratio_'][0] ratio_y = df['explained_variance_ratio_'][1] plt.xlabel('1st PC: %.2f %%' % (ratio_x*100), fontsize='xx-large') plt.ylabel('2nd PC: %.2f %%' % (ratio_y*100), fontsize='xx-large') df.close() plt.clabel(CS1, inline=1, fontsize=6) plt.clabel(CS2, inline=1, fontsize=6) fig.savefig(proj_file + '_' + surf_name + '_2dcontour_proj.pdf', dpi=300, bbox_inches='tight', format='pdf') pf.close() if show: plt.show() def plot_2d_eig_ratio(surf_file, val_1='min_eig', val_2='max_eig', show=False): """ Plot the heatmap of eigenvalue ratios, i.e., |min_eig/max_eig| of hessian """ print('------------------------------------------------------------------') print('plot_2d_eig_ratio') print('------------------------------------------------------------------') print("loading surface file: " + surf_file) f = h5py.File(surf_file,'r') x = np.array(f['xcoordinates'][:]) y = np.array(f['ycoordinates'][:]) X, Y = np.meshgrid(x, y) Z1 = np.array(f[val_1][:]) Z2 = np.array(f[val_2][:]) # Plot 2D heatmaps with color bar using seaborn abs_ratio = np.absolute(np.divide(Z1, Z2)) print(abs_ratio) fig = plt.figure() sns_plot = sns.heatmap(abs_ratio, cmap='viridis', vmin=0, vmax=.5, cbar=True, xticklabels=False, yticklabels=False) sns_plot.invert_yaxis() sns_plot.get_figure().savefig(surf_file + '_' + val_1 + '_' + val_2 + '_abs_ratio_heat_sns.pdf', dpi=300, bbox_inches='tight', format='pdf') # Plot 2D heatmaps with color bar using seaborn ratio = np.divide(Z1, Z2) print(ratio) fig = plt.figure() sns_plot = sns.heatmap(ratio, cmap='viridis', cbar=True, xticklabels=False, yticklabels=False) sns_plot.invert_yaxis() sns_plot.get_figure().savefig(surf_file + '_' + val_1 + '_' + val_2 + '_ratio_heat_sns.pdf', dpi=300, bbox_inches='tight', format='pdf') f.close() if show: plt.show() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Plot 2D loss surface') parser.add_argument('--surf_file', '-f', default='', help='The h5 file that contains surface values') parser.add_argument('--dir_file', default='', help='The h5 file that contains directions') parser.add_argument('--proj_file', default='', help='The h5 file that contains the projected trajectories') parser.add_argument('--surf_name', default='train_loss', help='The type of surface to plot') parser.add_argument('--vmax', default=10, type=float, help='Maximum value to map') parser.add_argument('--vmin', default=0.1, type=float, help='Miminum value to map') parser.add_argument('--vlevel', default=0.5, type=float, help='plot contours every vlevel') parser.add_argument('--zlim', default=10, type=float, help='Maximum loss value to show') parser.add_argument('--show', action='store_true', default=False, help='show plots') args = parser.parse_args() if exists(args.surf_file) and exists(args.proj_file) and exists(args.dir_file): plot_contour_trajectory(args.surf_file, args.dir_file, args.proj_file, args.surf_name, args.vmin, args.vmax, args.vlevel, args.show) elif exists(args.proj_file) and exists(args.dir_file): plot_trajectory(args.proj_file, args.dir_file, args.show) elif exists(args.surf_file): plot_2d_contour(args.surf_file, args.surf_name, args.vmin, args.vmax, args.vlevel, args.show)
281677160/openwrt-package
1,605
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_timerd.h
/* * Copyright (C) AlexWoo(Wu Jie) [email protected] */ #ifndef _NGX_TIMER_DEBUG_H_INCLUDED_ #define _NGX_TIMER_DEBUG_H_INCLUDED_ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #define NGX_ADD_TIMER(ev, timer, fpoff) \ ngx_add_timer_debug(ev, timer, fpoff, __FILE__, __LINE__) #define NGX_DEL_TIMER(ev, footprint) \ ngx_del_timer_debug(ev, footprint, __FILE__, __LINE__) /* * generate a new footprint * * return: * footprint */ ngx_uint_t ngx_timerd_footprint(); /* * add timer and record where to add it for debugging * such as timer not destroy * * paras: * ev: nginx event for timer * timer: timer interval for triggering timer * fpoff: footprint offset in event data * file: use __FILE__ for recording file * line: use __LINE__ for recording line * return: * pool for successd, NULL for failed */ void ngx_add_timer_debug(ngx_event_t *ev, ngx_msec_t timer, off_t fpoff, char *file, int line); /* * destroy pool for debugging, use as pair for ngx_create_pool_debug * * paras: * ev: nginx event for timer * footprint: footprint value in user event data * file: use __FILE__ for recording file * line: use __LINE__ for recording line */ void ngx_del_timer_debug(ngx_event_t *ev, ngx_uint_t footprint, char *file, int line); /* * paras: * r: http request to query status of rbuf */ ngx_chain_t *ngx_timerd_state(ngx_http_request_t *r, unsigned detail); #endif
294coder/Efficient-MIF
2,706
utils/utils_modules/unet5.py
import torch import torch.nn as nn from torch.nn import functional as F class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels): super(ConvBlock, self).__init__() self.conv = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=True), nn.BatchNorm2d(out_channels), nn.ReLU(), nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=True), nn.BatchNorm2d(out_channels), nn.ReLU() ) def forward(self, x): out = self.conv(x) return out class UNet5(nn.Module): def __init__(self, input_channel=1): super(UNet5, self).__init__() self.down_sample=nn.MaxPool2d(2) self.down1 = ConvBlock(input_channel, 64) self.down2 = ConvBlock(64, 128) self.down3 = ConvBlock(128, 256) self.down4 = ConvBlock(256, 512) self.down5 = ConvBlock(512, 1024) self.up_sample5=nn.Sequential( nn.ConvTranspose2d(1024,512, 4, 2, 1, bias=False), nn.ReLU() ) self.up4 = ConvBlock(1024,512) self.up_sample4 = nn.Sequential( nn.ConvTranspose2d(512,256, 4, 2, 1, bias=False), nn.ReLU() ) self.up3 = ConvBlock(512,256) self.up_sample3 = nn.Sequential( nn.ConvTranspose2d(256,128, 4, 2, 1, bias=False), nn.ReLU() ) self.up2 = ConvBlock(256,128) self.up_sample2 = nn.Sequential( nn.ConvTranspose2d(128,64, 4, 2, 1, bias=False), nn.ReLU() ) self.up1 = ConvBlock(128,64) self.last = nn.Sequential( nn.Conv2d(64, 1, kernel_size=3, stride=1, padding=1), nn.Sigmoid() ) def forward(self, x): # check size first sz = x.shape if sz[-1] % 32 != 0 or sz[-2] % 32 != 0: x = F.interpolate(x, size=(128, 128), mode='bilinear', align_corners=False) d1 = self.down1(x) d2 = self.down2(self.down_sample(d1)) d3 = self.down3(self.down_sample(d2)) d4 = self.down4(self.down_sample(d3)) out = self.down5(self.down_sample(d4)) out = self.up4(torch.cat((self.up_sample5(out),d4),1)) out = self.up3(torch.cat((self.up_sample4(out),d3),1)) out = self.up2(torch.cat((self.up_sample3(out),d2),1)) out = self.up1(torch.cat((self.up_sample2(out),d1),1)) out = self.last(out) if sz[-1] % 32 != 0 or sz[-2] % 32 != 0: out = F.interpolate(out, size=sz[-2:], mode='bilinear', align_corners=False) return out
2881099/FreeSql.AdminLTE
1,801
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/jsgrid/jsgrid.min.css
/* * jsGrid v1.5.3 (http://js-grid.com) * (c) 2016 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ .jsgrid{position:relative;overflow:hidden;font-size:1em}.jsgrid,.jsgrid *,.jsgrid :after,.jsgrid :before{box-sizing:border-box}.jsgrid input,.jsgrid select,.jsgrid textarea{font-size:1em}.jsgrid-grid-header{overflow-x:hidden;overflow-y:scroll;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none}.jsgrid-grid-body{overflow-x:auto;overflow-y:scroll;-webkit-overflow-scrolling:touch}.jsgrid-table{width:100%;table-layout:fixed;border-collapse:collapse;border-spacing:0}.jsgrid-cell{padding:.5em}.jsgrid-header-cell,.jsgrid-сell{box-sizing:border-box}.jsgrid-align-left{text-align:left}.jsgrid-align-center,.jsgrid-align-center input,.jsgrid-align-center select,.jsgrid-align-center textarea{text-align:center}.jsgrid-align-right,.jsgrid-align-right input,.jsgrid-align-right select,.jsgrid-align-right textarea{text-align:right}.jsgrid-header-cell{padding:.5em}.jsgrid-edit-row input,.jsgrid-edit-row select,.jsgrid-edit-row textarea,.jsgrid-filter-row input,.jsgrid-filter-row select,.jsgrid-filter-row textarea,.jsgrid-insert-row input,.jsgrid-insert-row select,.jsgrid-insert-row textarea{width:100%;padding:.3em .5em}.jsgrid-edit-row input[type=checkbox],.jsgrid-filter-row input[type=checkbox],.jsgrid-insert-row input[type=checkbox]{width:auto}.jsgrid-selected-row .jsgrid-cell{cursor:pointer}.jsgrid-nodata-row .jsgrid-cell{padding:.5em 0;text-align:center}.jsgrid-header-sort{cursor:pointer}.jsgrid-pager{padding:.5em 0}.jsgrid-pager-nav-button{padding:.2em .6em}.jsgrid-pager-nav-inactive-button{display:none;pointer-events:none}.jsgrid-pager-page{padding:.2em .6em}
281677160/openwrt-package
7,017
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_rbuf.c
/* * Copyright (C) AlexWoo(Wu Jie) [email protected] */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #include "ngx_map.h" static ngx_pool_t *ngx_rbuf_pool; static ngx_map_t ngx_rbuf_map; static ngx_chain_t *ngx_rbuf_free_chain; static ngx_uint_t ngx_rbuf_nalloc_node; static ngx_uint_t ngx_rbuf_nalloc_buf; static ngx_uint_t ngx_rbuf_nfree_buf; static ngx_uint_t ngx_rbuf_nalloc_chain; static ngx_uint_t ngx_rbuf_nfree_chain; static ngx_map_t ngx_rbuf_using; #define ngx_rbuf_buf(b) \ (ngx_rbuf_t *) ((u_char *) (b) - offsetof(ngx_rbuf_t, buf)) typedef struct ngx_rbuf_s ngx_rbuf_t; struct ngx_rbuf_s { size_t size; ngx_rbuf_t *next; u_char buf[]; }; typedef struct { ngx_map_node_t node; ngx_rbuf_t *rbuf; } ngx_rbuf_node_t; typedef struct { ngx_chain_t cl; ngx_buf_t buf; unsigned alloc; ngx_map_node_t node; char *file; int line; } ngx_chainbuf_t; static ngx_int_t ngx_rbuf_init() { ngx_rbuf_pool = ngx_create_pool(4096, ngx_cycle->log); if (ngx_rbuf_pool == NULL) { return NGX_ERROR; } ngx_map_init(&ngx_rbuf_map, ngx_map_hash_uint, ngx_cmp_uint); ngx_map_init(&ngx_rbuf_using, ngx_map_hash_uint, ngx_cmp_uint); ngx_rbuf_nalloc_node = 0; ngx_rbuf_nalloc_buf = 0; ngx_rbuf_nfree_buf = 0; ngx_rbuf_nalloc_chain = 0; ngx_rbuf_nfree_chain = 0; return NGX_OK; } static ngx_rbuf_t * ngx_rbuf_get_buf(size_t key) { ngx_rbuf_node_t *rn; ngx_map_node_t *node; ngx_rbuf_t *rb; node = ngx_map_find(&ngx_rbuf_map, key); if (node == NULL) { /* new key */ rn = ngx_pcalloc(ngx_rbuf_pool, sizeof(ngx_rbuf_node_t)); if (rn == NULL) { return NULL; } node = &rn->node; node->raw_key = key; ngx_map_insert(&ngx_rbuf_map, node, 0); ++ngx_rbuf_nalloc_node; } else { rn = (ngx_rbuf_node_t *) node; } rb = rn->rbuf; if (rb == NULL) { rb = ngx_pcalloc(ngx_rbuf_pool, sizeof(ngx_rbuf_t) + key); if (rb == NULL) { return NULL; } rb->size = key; ++ngx_rbuf_nalloc_buf; } else { rn->rbuf = rb->next; rb->next = NULL; --ngx_rbuf_nfree_buf; } return rb; } static void ngx_rbuf_put_buf(ngx_rbuf_t *rb) { ngx_rbuf_node_t *rn; ngx_map_node_t *node; node = ngx_map_find(&ngx_rbuf_map, rb->size); if (node == NULL) { return; } rn = (ngx_rbuf_node_t *) node; rb->next = rn->rbuf; rn->rbuf = rb; ++ngx_rbuf_nfree_buf; } static u_char * ngx_rbuf_alloc(size_t size) { ngx_rbuf_t *rb; rb = ngx_rbuf_get_buf(size); return rb->buf; } static void ngx_rbuf_free(u_char *rb) { ngx_rbuf_t *rbuf; rbuf = ngx_rbuf_buf(rb); ngx_rbuf_put_buf(rbuf); } ngx_chain_t * ngx_get_chainbuf_debug(size_t size, ngx_flag_t alloc_rbuf, char *file, int line) { ngx_chainbuf_t *cb; ngx_chain_t *cl; if (ngx_rbuf_pool == NULL) { ngx_rbuf_init(); } cl = ngx_rbuf_free_chain; if (cl) { ngx_rbuf_free_chain = cl->next; cl->next = NULL; cb = (ngx_chainbuf_t *) cl; --ngx_rbuf_nfree_chain; } else { cb = ngx_pcalloc(ngx_rbuf_pool, sizeof(ngx_chainbuf_t)); if (cb == NULL) { return NULL; } cl = &cb->cl; cl->buf = &cb->buf; ++ngx_rbuf_nalloc_chain; } if (alloc_rbuf) { cl->buf->last = cl->buf->pos = cl->buf->start = ngx_rbuf_alloc(size); cl->buf->end = cl->buf->start + size; cb->alloc = 1; } else { cl->buf->pos = cl->buf->last = cl->buf->start = cl->buf->end = NULL; cb->alloc = 0; } cl->buf->memory = 1; // record chainbuf in using map cb->file = file; cb->line = line; cb->node.raw_key = (intptr_t) cl; ngx_map_insert(&ngx_rbuf_using, &cb->node, 0); return cl; } void ngx_put_chainbuf_debug(ngx_chain_t *cl, char *file, int line) { ngx_chainbuf_t *cb; if (ngx_rbuf_pool == NULL) { return; } if (cl == NULL) { return; } cb = (ngx_chainbuf_t *) cl; if (cb->alloc) { ngx_rbuf_free(cl->buf->start); } cl->next = ngx_rbuf_free_chain; ngx_rbuf_free_chain = cl; ++ngx_rbuf_nfree_chain; // delete chainbuf from using map if (ngx_map_find(&ngx_rbuf_using, (intptr_t) cl) == NULL) { ngx_log_error(NGX_LOG_EMERG, ngx_cycle->log, 0, "destroy chainbuf twice: %s:%d", file, line); return; } ngx_map_delete(&ngx_rbuf_using, (intptr_t) cl); } ngx_chain_t * ngx_rbuf_state(ngx_http_request_t *r, unsigned detail) { ngx_chain_t *cl; ngx_buf_t *b; size_t len, len1; ngx_uint_t n; ngx_chainbuf_t *cb; ngx_map_node_t *node; len = sizeof("##########ngx rbuf state##########\n") - 1 + sizeof("ngx_rbuf nalloc node: \n") - 1 + NGX_OFF_T_LEN + sizeof("ngx_rbuf nalloc buf: \n") - 1 + NGX_OFF_T_LEN + sizeof("ngx_rbuf nfree buf: \n") - 1 + NGX_OFF_T_LEN + sizeof("ngx_rbuf nalloc chain: \n") - 1 + NGX_OFF_T_LEN + sizeof("ngx_rbuf nfree chain: \n") - 1 + NGX_OFF_T_LEN; len1 = 0; if (detail) { n = ngx_rbuf_nalloc_chain - ngx_rbuf_nfree_chain; /* " file:line\n" */ len1 = 4 + 256 + 1 + NGX_OFF_T_LEN + 1; len += len1 * n; } cl = ngx_alloc_chain_link(r->pool); if (cl == NULL) { return NULL; } cl->next = NULL; b = ngx_create_temp_buf(r->pool, len); if (b == NULL) { return NULL; } cl->buf = b; b->last = ngx_snprintf(b->last, len, "##########ngx rbuf state##########\nngx_rbuf nalloc node: %ui\n" "ngx_rbuf nalloc buf: %ui\nngx_rbuf nfree buf: %ui\n" "ngx_rbuf nalloc chain: %ui\nngx_rbuf nfree chain: %ui\n", ngx_rbuf_nalloc_node, ngx_rbuf_nalloc_buf, ngx_rbuf_nfree_buf, ngx_rbuf_nalloc_chain, ngx_rbuf_nfree_chain); if (detail) { for (node = ngx_map_begin(&ngx_rbuf_using); node; node = ngx_map_next(node)) { cb = (ngx_chainbuf_t *) ((char *) node - offsetof(ngx_chainbuf_t, node)); b->last = ngx_snprintf(b->last, len1, " %s:%d\n", cb->file, cb->line); } } return cl; }
29jitender/Spotlight
2,847
app/src/main/res/layout/content_main.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_main"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/switchAnimation" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#FFA5A5" android:foreground="?attr/selectableItemBackground" android:gravity="center" android:text="Switch to Fadein" android:textSize="20sp" android:textStyle="bold" /> <TextView android:id="@+id/reset" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#FFFFC2" android:foreground="?attr/selectableItemBackground" android:gravity="center" android:text="Reset Preference" android:textSize="20sp" android:textStyle="bold" /> <TextView android:id="@+id/resetAndPlay" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#C8E7ED" android:foreground="?attr/selectableItemBackground" android:gravity="center" android:text="Play Again" android:textSize="20sp" android:textStyle="bold" /> <TextView android:id="@+id/changePosAndPlay" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#BFCFFF" android:foreground="?attr/selectableItemBackground" android:gravity="center" android:text="Change Position and Play" android:textSize="20sp" android:textStyle="bold" /> <TextView android:id="@+id/startSequence" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#808167F4" android:foreground="?attr/selectableItemBackground" android:gravity="center" android:text="Start Sequence" android:textSize="20sp" android:textStyle="bold" /> </LinearLayout> </FrameLayout>
294coder/Efficient-MIF
13,763
utils/utils_modules/adam_mini.py
import torch from torch.optim.optimizer import Optimizer import math import torch.distributed as dist device = 'cuda' if torch.cuda.is_available() else 'cpu' from torch.distributed._tensor import Replicate class Adam_mini(Optimizer): def __init__( self, model=None, weight_decay=0.1, lr=1, betas=(0.9, 0.999), eps=1e-8, model_sharding=False, n_feature=2048, n_head=32, n_kv_head=None, ): ''' model: the model you are training. model_sharding: set to True if you are using model parallelism with more than 1 GPU, including FSDP and zero_1,2,3 in Deepspeed. Set to False if otherwise. n_feature: dimension for hidden feature. Could be unspecified if you are training non-transformer models. n_head: number of attention heads. Could be unspecified if you are training non-transformer models. n_kv_head: number of head for Key and Value. Or equivalently, number of query groups in Group query Attention. Also known as "n_query_groups". If not specified, it will be equal to n_head. Could be unspecified if you are training non-transformer models. ''' self.n_feature = n_feature self.n_head = n_head if n_kv_head is not None: self.n_kv_head = n_kv_head assert self.n_head % self.n_kv_head == 0 else: self.n_kv_head = self.n_head self.model = model self.world_size = torch.cuda.device_count() self.model_sharding = model_sharding if self.model_sharding: print("=====>>> Adam-mini is using model_sharding") optim_groups = [] count_embd = 0 count_output = 0 count_q = 0 count_k = 0 for name, param in self.model.named_parameters(): print('Detected param blocks by Adam-mini:', name, param.size()) if param.requires_grad: dic = {} dic["name"] = name dic["params"] = param if ("norm" in name or "ln_f" in name): dic["weight_decay"] = 0 else: dic["weight_decay"] = weight_decay if ("embed" in name or "wte" in name or "embd" in name): count_embd += 1 if ("lm_head.weight" in name or "output.weight" in name): count_output += 1 if ("q_proj.weight" in name or "wq.weight" in name): count_q += 1 dic["parameter_per_head"] = self.n_feature * self.n_feature // self.n_head if (self.n_feature * self.n_feature % self.n_head) != 0: raise ValueError("'n_feature * n_feature' is not a multiple of n_head ") if ("k_proj.weight" in name or "wk.weight" in name): count_k += 1 dic["parameter_per_head"] = self.n_feature * self.n_feature // self.n_head if (self.n_feature * self.n_feature % self.n_head) != 0: raise ValueError("'n_feature * n_feature' is not a multiple of n_head ") optim_groups.append(dic) print( f'Adam-mini found {count_embd} embedding layers, {count_output} output layers, {count_q} Querys, {count_k} Keys.') if count_embd == 0: # warning print( "=====>>> Warning by Adam-mini: No embedding layer found. If you are training Transformers, please check the name of your embedding layer and manually add them to 'self.embd_blocks' of Adam-mini.") if count_output == 0: # warning print( "=====>>> Warning by Adam-mini: No output layer found. If you are training Transformers (without weight-tying), please check the name of your output layer and manually add them to 'self.embd_blocks' of Adam-mini. Please ignore this warning if you are using weight-tying.") if count_q == 0: # warning print( "=====>>> Warning by Adam-mini: No Query found. If you are training Transformers, please check the name of your Query in attention blocks and manually add them to 'self.qk_blocks' of Adam-mini") if count_k == 0: # warning print( "=====>>> Warning by Adam-mini: No Key found. If you are training Transformers, please check the name of your Key in attention blocks and manually add them to 'self.qk_blocks' of Adam-mini") if count_output + count_embd + count_q + count_k == 0: print( "=====>>> Warning by Adam-mini: you are using default PyTorch partition for Adam-mini. It can cause training instability on large-scale Transformers.") # embd_blocks, including embd and output layers. Use normal adamW updates for these blocks self.embd_blocks = { "embed", "embd", "wte", "lm_head.weight", "output.weight" } # Query and Keys, will assign lrs by heads self.qk_blocks = { "k_proj.weight", "q_proj.weight", "wq.weight", "wk.weight" } if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= betas[0] < 1.0: raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) if not 0.0 <= betas[1] < 1.0: raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if not self.n_feature == int(self.n_feature): raise ValueError("Invalid n_feature value: {}".format(self.n_feature)) if not self.n_head == int(self.n_head): raise ValueError("Invalid n_head value: {}".format(self.n_head)) if not self.n_kv_head == int(self.n_kv_head): raise ValueError("Invalid n_kv_head value: {}".format(self.n_kv_head)) defaults = dict(lr=lr, beta1=betas[0], beta2=betas[1], eps=eps) super(Adam_mini, self).__init__(optim_groups, defaults) def step(self, *args, **kwargs): with torch.no_grad(): for group in self.param_groups: beta1 = group["beta1"] beta2 = group["beta2"] lr = group["lr"] name = group["name"] eps = group["eps"] for p in group["params"]: state = self.state[p] if any(block in name for block in self.embd_blocks): # this is for embedding and output layer if p.grad is None: continue if len(state) == 0: state["m"] = torch.zeros_like(p.data).to(torch.float32) state["iteration"] = 0 state["v"] = torch.zeros_like(p.data).to(torch.float32) grad = p.grad.data.to(torch.float32) state["v"].mul_(beta2).addcmul_(grad, grad.conj(), value=1 - beta2) state["iteration"] += 1 if group["weight_decay"] != 0: p.data.mul_(1 - lr * group["weight_decay"]) state["m"].lerp_(grad, 1 - beta1) bias_correction_1 = 1 - beta1 ** state["iteration"] bias_correction_2 = 1 - beta2 ** state["iteration"] bias_correction_2_sqrt = math.sqrt(bias_correction_2) h = (state["v"].sqrt() / bias_correction_2_sqrt).add_(eps) stepsize = lr / bias_correction_1 p.addcdiv_(state["m"], h, value=-stepsize) elif any(block in name for block in self.qk_blocks): # this is for query and key if p.grad is None: continue dim = group["parameter_per_head"] if (len(state) == 0): state["m"] = torch.zeros_like(p.data).to(torch.float32) state["m"] = state["m"].view(-1, dim) state["head"] = state['m'].shape[0] state["iteration"] = 0 # to reconcile with DTensor state["vmean"] = torch.zeros_like(state["m"][0:state["head"], 0:1]).to(device) grad = p.grad.data.to(torch.float32) head = state['head'] grad = grad.view(head, dim) tmp_lr = torch.mean(grad * grad, dim=1).unsqueeze(1).to( device) # unsqueeze to size([head, 1]) to match the size of vmean state["vmean"].mul_(beta2).add_(tmp_lr, alpha=1 - beta2) v = state["vmean"] state["iteration"] += 1 if group["weight_decay"] != 0: p.data.mul_(1 - lr * group["weight_decay"]) state["m"].lerp_(grad, 1 - beta1) bias_correction_1 = 1 - beta1 ** state["iteration"] bias_correction_2 = 1 - beta2 ** state["iteration"] bias_correction_2_sqrt = math.sqrt(bias_correction_2) h = (v.sqrt() / bias_correction_2_sqrt).add_(eps) stepsize = ((1 / bias_correction_1) / h).view(head, 1) update = state["m"] * (stepsize.to(state['m'].device)) if p.dim() > 1: d0, d1 = p.size() update = update.view(d0, d1) else: update = update.view(-1) update.mul_(lr) p.add_(-update) else: # other blocks if (len(state) == 0): dimension = torch.tensor(p.data.numel()).to(device).to(torch.float32) reduced = False if (self.world_size > 1) and (self.model_sharding is True): tensor_list = [torch.zeros_like(dimension) for _ in range(self.world_size)] dist.all_gather(tensor_list, dimension) s = 0 dimension = 0 for d in tensor_list: if (d > 0): s = s + 1 dimension = dimension + d if (s >= 2): reduced = True state["m"] = torch.zeros_like(p.data).to(torch.float32) state["iteration"] = 0 state["reduced"] = reduced # actually this is just tensor(0.0), but this implementation is compatible with more general # types of tensor such as DTensor in Titan state["vmean"] = torch.zeros_like(torch.sum(p.data * p.data)).to(device) state["dimension"] = dimension.item() if p.grad is None: # actually this is just tensor(0.0), but this implementation is compatible with more general # types of tensor such as DTensor in Titan tmp_lr = torch.zeros_like(torch.sum(p.data * p.data)).to(device) else: grad = p.grad.data.to(torch.float32) tmp_lr = torch.sum(grad * grad).to(device) if (state["reduced"]): if "device_mesh" in dir(tmp_lr): # when tmp_lr is a DTensor in TorchTitan lr_local = tmp_lr.to_local() dist.all_reduce(lr_local, op=dist.ReduceOp.SUM) tmp_lr.redistribute(placements=[Replicate()]) else: # when tmp_lr is a standard tensor # print(f"...... dist all reduce.......") dist.all_reduce(tmp_lr, op=dist.ReduceOp.SUM) if (p.grad is None): continue tmp_lr = tmp_lr / (state["dimension"]) tmp_lr = tmp_lr.to(grad.device) if group["weight_decay"] != 0: p.data.mul_(1 - lr * group["weight_decay"]) state["iteration"] += 1 state["m"].lerp_(grad, 1 - beta1) bias_correction_1 = 1 - beta1 ** state["iteration"] bias_correction_2 = 1 - beta2 ** state["iteration"] bias_correction_2_sqrt = math.sqrt(bias_correction_2) state["vmean"] = (1 - beta2) * tmp_lr + beta2 * state["vmean"] h = (state["vmean"].sqrt() / bias_correction_2_sqrt).add_(eps) stepsize = (1 / bias_correction_1) / h update = state["m"] * (stepsize.to(state['m'].device)) update.mul_(lr) p.add_(-update)
294coder/Efficient-MIF
8,807
utils/sharpening_index/indexes_evaluation_FS.py
# GPL License # Copyright (C) UESTC # All Rights Reserved # @Author : Xiao Wu # @reference: # import numpy as np import torch from scipy import signal, ndimage, misc import cv2 from .HQNR import HQNR from .my_D_s import D_s as my_Ds def mtf_resize(img, satellite='QuickBird', scale=4): # satellite GNyq scale = int(scale) if satellite == 'QuickBird': GNyq = [0.34, 0.32, 0.30, 0.22] # Band Order: B,G,R,NIR GNyqPan = 0.15 elif satellite == 'IKONOS': GNyq = [0.26, 0.28, 0.29, 0.28] # Band Order: B,G,R,NIR GNyqPan = 0.17 elif satellite == 'WV3': GNyq = [0.325, 0.355, 0.360, 0.350, 0.365, 0.360, 0.335, 0.315] # Band Order: B,G,R,NIR GNyqPan = 0.14 else: raise NotImplementedError('satellite: QuickBird or IKONOS or WV3') # lowpass img_ = img.squeeze() img_ = img_.astype(np.float64) if img_.ndim == 2: # Pan H, W = img_.shape lowpass = GNyq2win(GNyqPan, scale, N=41) elif img_.ndim == 3: # MS H, W, _ = img.shape lowpass = [GNyq2win(gnyq, scale, N=41) for gnyq in GNyq] lowpass = np.stack(lowpass, axis=-1) img_ = ndimage.filters.correlate(img_, lowpass, mode='nearest') # downsampling output_size = (H // scale, W // scale) img_ = cv2.resize(img_, dsize=output_size, interpolation=cv2.INTER_NEAREST) return img_ def gaussian2d(N, std): t = np.arange(-(N - 1) // 2, (N + 2) // 2) t1, t2 = np.meshgrid(t, t) std = np.double(std) w = np.exp(-0.5 * (t1 / std) ** 2) * np.exp(-0.5 * (t2 / std) ** 2) return w def kaiser2d(N, beta): t = np.arange(-(N - 1) // 2, (N + 2) // 2) / np.double(N - 1) t1, t2 = np.meshgrid(t, t) t12 = np.sqrt(t1 * t1 + t2 * t2) w1 = np.kaiser(N, beta) w = np.interp(t12, t, w1) w[t12 > t[-1]] = 0 w[t12 < t[0]] = 0 return w def fir_filter_wind(Hd, w): """ compute fir (finite impulse response) filter with window method Hd: desired freqeuncy response (2D) w: window (2D) """ hd = np.rot90(np.fft.fftshift(np.rot90(Hd, 2)), 2) h = np.fft.fftshift(np.fft.ifft2(hd)) h = np.rot90(h, 2) h = h * w h = h / np.sum(h) return h def GNyq2win(GNyq, scale=4, N=41): """Generate a 2D convolutional window from a given GNyq GNyq: Nyquist frequency scale: spatial size of PAN / spatial size of MS """ # fir filter with window method fcut = 1 / scale alpha = np.sqrt(((N - 1) * (fcut / 2)) ** 2 / (-2 * np.log(GNyq))) H = gaussian2d(N, alpha) Hd = H / np.max(H) w = kaiser2d(N, 0.5) h = fir_filter_wind(Hd, w) return np.real(h) def _qindex(img1, img2, block_size=8): """Q-index for 2D (one-band) image, shape (H, W); uint or float [0, 1]""" assert block_size > 1, 'block_size shold be greater than 1!' img1_ = img1.astype(np.float64) img2_ = img2.astype(np.float64) window = np.ones((block_size, block_size)) / (block_size ** 2) # window_size = block_size**2 # filter, valid pad_topleft = int(np.floor(block_size / 2)) pad_bottomright = block_size - 1 - pad_topleft mu1 = cv2.filter2D(img1_, -1, window)[pad_topleft:-pad_bottomright, pad_topleft:-pad_bottomright] mu2 = cv2.filter2D(img2_, -1, window)[pad_topleft:-pad_bottomright, pad_topleft:-pad_bottomright] mu1_sq = mu1 ** 2 mu2_sq = mu2 ** 2 mu1_mu2 = mu1 * mu2 sigma1_sq = cv2.filter2D(img1_ ** 2, -1, window)[pad_topleft:-pad_bottomright, pad_topleft:-pad_bottomright] - mu1_sq sigma2_sq = cv2.filter2D(img2_ ** 2, -1, window)[pad_topleft:-pad_bottomright, pad_topleft:-pad_bottomright] - mu2_sq # print(mu1_mu2.shape) # print(sigma2_sq.shape) sigma12 = cv2.filter2D(img1_ * img2_, -1, window)[pad_topleft:-pad_bottomright, pad_topleft:-pad_bottomright] - mu1_mu2 # all = 1, include the case of simga == mu == 0 qindex_map = np.ones(sigma12.shape) # sigma == 0 and mu != 0 idx = ((sigma1_sq + sigma2_sq) == 0) * ((mu1_sq + mu2_sq) != 0) qindex_map[idx] = 2 * mu1_mu2[idx] / (mu1_sq + mu2_sq)[idx] # sigma !=0 and mu == 0 idx = ((sigma1_sq + sigma2_sq) != 0) * ((mu1_sq + mu2_sq) == 0) qindex_map[idx] = 2 * sigma12[idx] / (sigma1_sq + sigma2_sq)[idx] # sigma != 0 and mu != 0 idx = ((sigma1_sq + sigma2_sq) != 0) * ((mu1_sq + mu2_sq) != 0) qindex_map[idx] = ((2 * mu1_mu2[idx]) * (2 * sigma12[idx])) / ( (mu1_sq + mu2_sq)[idx] * (sigma1_sq + sigma2_sq)[idx]) return np.mean(qindex_map) def qindex(img1, img2, block_size=8): """Q-index for 2D (H, W) or 3D (H, W, C) image; uint or float [0, 1]""" if not img1.shape == img2.shape: raise ValueError('Input images must have the same dimensions.') if img1.ndim == 2: return _qindex(img1, img2, block_size) elif img1.ndim == 3: qindexs = [_qindex(img1[..., i], img2[..., i], block_size) for i in range(img1.shape[2])] return np.array(qindexs).mean() else: raise ValueError('Wrong input image dimensions.') def D_lambda(img_fake, img_lm, block_size=32, p=1): """Spectral distortion img_fake, generated HRMS img_lm, LRMS""" assert img_fake.ndim == img_lm.ndim == 3, 'Images must be 3D!' H_f, W_f, C_f = img_fake.shape H_r, W_r, C_r = img_lm.shape assert C_f == C_r, 'Fake and lm should have the same number of bands!' # D_lambda Q_fake = [] Q_lm = [] for i in range(C_f): for j in range(i + 1, C_f): # for fake band1 = img_fake[..., i] band2 = img_fake[..., j] Q_fake.append(_qindex(band1, band2, block_size=block_size)) # for real band1 = img_lm[..., i] band2 = img_lm[..., j] Q_lm.append(_qindex(band1, band2, block_size=block_size)) Q_fake = np.array(Q_fake) Q_lm = np.array(Q_lm) D_lambda_index = (np.abs(Q_fake - Q_lm) ** p).mean() return D_lambda_index ** (1 / p) def D_s(img_fake, img_lm, pan, satellite='QuickBird', scale=4, block_size=32, q=1): """Spatial distortion img_fake, generated HRMS img_lm, LRMS pan, HRPan""" # fake and lm assert img_fake.ndim == img_lm.ndim == 3, 'MS images must be 3D!' H_f, W_f, C_f = img_fake.shape H_r, W_r, C_r = img_lm.shape assert H_f // H_r == W_f // W_r == scale, 'Spatial resolution should be compatible with scale' assert C_f == C_r, 'Fake and lm should have the same number of bands!' # fake and pan assert pan.ndim == 3, 'Panchromatic image must be 3D!' H_p, W_p, C_p = pan.shape assert C_p == 1, 'size of 3rd dim of Panchromatic image must be 1' assert H_f == H_p and W_f == W_p, "Pan's and fake's spatial resolution should be the same" # get LRPan, 2D pan_lr = mtf_resize(pan, satellite=satellite, scale=scale) # print(pan_lr.shape) # D_s Q_hr = [] Q_lr = [] for i in range(C_f): # for HR fake band1 = img_fake[..., i] band2 = pan[..., 0] # the input PAN is 3D with size=1 along 3rd dim # print(band1.shape) # print(band2.shape) Q_hr.append(_qindex(band1, band2, block_size=block_size)) band1 = img_lm[..., i] band2 = pan_lr # this is 2D # print(band1.shape) # print(band2.shape) Q_lr.append(_qindex(band1, band2, block_size=block_size)) Q_hr = np.array(Q_hr) Q_lr = np.array(Q_lr) D_s_index = (np.abs(Q_hr - Q_lr) ** q).mean() return D_s_index ** (1 / q) def qnr(ps_ms, ms, msexp, pan, ratio, S, p=1, q=1, alpha=1, beta=1): """QNR - No reference IQA""" if pan.ndim == 2: pan = pan[:, :, None] D_lambda_idx = D_lambda(ps_ms, msexp, S, p) D_s_idx = D_s(ps_ms, ms, pan, 'WV3', ratio, S, q) QNR_idx = (1 - D_lambda_idx) ** alpha * (1 - D_s_idx) ** beta return QNR_idx, D_lambda_idx, D_s_idx def my_qnr(ps_ms, ms, msexp, pan, ratio, S, p=1, q=1, alpha=1, beta=1): """QNR - No reference IQA""" # D_lambda_idx = D_lambda(img_fake, img_lm, block_size, p) # D_s_idx = D_s(img_fake, img_lm, pan, satellite, scale, block_size, q) D_lambda_idx = D_lambda(ps_ms, msexp, S, p) D_s_idx = my_Ds(ps_ms, msexp, ms, pan, ratio, S, q) QNR_idx = (1 - D_lambda_idx) ** alpha * (1 - D_s_idx) ** beta return QNR_idx, D_lambda_idx, D_s_idx def indexes_evaluation_FS(I_F, I_MS_LR, I_PAN, L, th_values, I_MS, sensor, ratio, Qblocks_size, flagQNR): if th_values == 1: I_F[I_F > 2 ** L] = 2 ** L I_F[I_F < 0] = 0 if flagQNR: QNR_index, D_lambda, D_S = my_qnr(I_F, I_MS_LR, I_MS, I_PAN, ratio, Qblocks_size) else: QNR_index, D_lambda, D_S = HQNR(I_F, I_MS_LR, I_MS, I_PAN, Qblocks_size, sensor, ratio) return QNR_index, D_lambda, D_S
281677160/openwrt-package
2,378
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_dynamic_conf.h
/* * Copyright (C) AlexWoo(Wu Jie) [email protected] */ #ifndef _NGX_DYNAMIC_COMMAND_H_INCLUDED_ #define _NGX_DYNAMIC_COMMAND_H_INCLUDED_ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_event.h> typedef struct { ngx_str_t name; void *(*create_conf)(ngx_conf_t *cf); char *(*init_conf)(ngx_conf_t *cf, void *conf); } ngx_dynamic_core_module_t; #if (NGX_PCRE) typedef struct { ngx_regex_t *regex; ngx_str_t name; } ngx_dynamic_regex_t; #endif #if 0 /* * if use dynamic conf, module define should use * NGX_MODULE_V1_DYNAMIC_PADDING and set * module dynamic context and * module dynamic directives as bellow */ ngx_module_t ngx_test_module = { NGX_MODULE_V1, &ngx_test_module_ctx, /* module context */ ngx_test_commands, /* module directives */ NGX_CORE_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ &ngx_test_module_dctx, /* module dynamic context */ ngx_test_dcommands, /* module dynamic directives */ NGX_MODULE_V1_DYNAMIC_PADDING }; #endif #define NGX_MODULE_V1_DYNAMIC_PADDING 0, 0, 0, 0, 0, 0 extern ngx_uint_t ngx_core_max_module; /* * return value: * return NGX_OK for successd, NGX_ERROR for failed * paras: * cf: ngx_conf_t passed from ngx_dynamic_conf_load_conf * init: only ngx_dynamic_conf_load_conf set 1, otherwise set 0 */ ngx_int_t ngx_dynamic_conf_parse(ngx_conf_t *cf, unsigned init); /* * return value: * return regex context * paras: * cf: ngx_conf_t passed in dynamic cmd handler * rc: regex options */ #if (NGX_PCRE) ngx_dynamic_regex_t *ngx_dynamic_regex_compile(ngx_conf_t *cf, ngx_regex_compile_t *rc); #endif int ngx_dynamic_cmp_dns_wildcards(const void *one, const void *two); void *ngx_get_dconf(ngx_module_t *m); #endif
29jitender/Spotlight
7,221
app/src/main/java/com/example/spotlight/MainActivity.java
package com.example.spotlight; import android.content.res.Configuration; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.wooplr.spotlight.SpotlightView; import com.wooplr.spotlight.prefs.PreferencesManager; import com.wooplr.spotlight.utils.SpotlightSequence; import com.wooplr.spotlight.utils.Utils; import java.util.Random; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // static { // AppCompatDelegate.setCompatVectorFromSourcesEnabled(true); // } private FloatingActionButton fab; private static final String INTRO_CARD = "fab_intro"; private static final String INTRO_SWITCH = "switch_intro"; private static final String INTRO_RESET = "reset_intro"; private static final String INTRO_REPEAT = "repeat_intro"; private static final String INTRO_CHANGE_POSITION = "change_position_intro"; private static final String INTRO_SEQUENCE = "sequence_intro"; private boolean isRevealEnabled = true; private SpotlightView spotLight; @BindView(R.id.switchAnimation) TextView switchAnimation; @BindView(R.id.reset) TextView reset; @BindView(R.id.resetAndPlay) TextView resetAndPlay; @BindView(R.id.changePosAndPlay) TextView changePosAndPlay; @BindView(R.id.startSequence) TextView startSequence; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "Fab Clicked!", Toast.LENGTH_LONG).show(); } }); switchAnimation.setOnClickListener(this); reset.setOnClickListener(this); resetAndPlay.setOnClickListener(this); changePosAndPlay.setOnClickListener(this); startSequence.setOnClickListener(this); new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { showIntro(fab, INTRO_CARD); } }, 2400); } @Override public void onClick(View view) { PreferencesManager mPreferencesManager = new PreferencesManager(MainActivity.this); DisplayMetrics displaymetrics = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int screenWidth = displaymetrics.widthPixels; int screenHeight = displaymetrics.heightPixels; switch (view.getId()) { case R.id.switchAnimation: if (isRevealEnabled) { switchAnimation.setText("Switch to Reveal"); isRevealEnabled = false; } else { switchAnimation.setText("Switch to Fadein"); isRevealEnabled = true; } mPreferencesManager.resetAll(); break; case R.id.reset: mPreferencesManager.resetAll(); break; case R.id.resetAndPlay: mPreferencesManager.resetAll(); new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { showIntro(fab, INTRO_CARD); } }, 400); break; case R.id.changePosAndPlay: mPreferencesManager.resetAll(); Random r = new Random(); int right = r.nextInt((screenWidth - Utils.dpToPx(16)) - 16) + 16; int bottom = r.nextInt((screenHeight - Utils.dpToPx(16)) - 16) + 16; CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) fab.getLayoutParams(); params.setMargins(Utils.dpToPx(16), Utils.dpToPx(16), right, bottom); fab.setLayoutParams(params); break; case R.id.startSequence: mPreferencesManager.resetAll(); new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { SpotlightSequence.getInstance(MainActivity.this,null) .addSpotlight(switchAnimation, "Switch Animation", "Click to swtich the animation", INTRO_SWITCH) .addSpotlight(reset, "Reset ", "Click here to reset preferences", INTRO_RESET) .addSpotlight(resetAndPlay, "Play Again", "Click here to play again", INTRO_REPEAT) .addSpotlight(changePosAndPlay, "Change Position", "Click here to change position and replay", INTRO_CHANGE_POSITION) .addSpotlight(startSequence, "Start sequence", "Well.. you just clicked here", INTRO_SEQUENCE) .addSpotlight(fab,"Love", "Like the picture?\n" + "Let others know.", INTRO_CARD) .startSequence(); } },400); break; } } private void showIntro(View view, String usageId) { spotLight = new SpotlightView.Builder(this) .introAnimationDuration(400) .enableRevealAnimation(isRevealEnabled) .performClick(true) .fadeinTextDuration(400) //.setTypeface(FontUtil.get(this, "RemachineScript_Personal_Use")) .headingTvColor(Color.parseColor("#eb273f")) .headingTvSize(32) .headingTvText("Love") .subHeadingTvColor(Color.parseColor("#ffffff")) .subHeadingTvSize(16) .subHeadingTvText("Like the picture?\nLet others know.") .maskColor(Color.parseColor("#dc000000")) .target(view) .lineAnimDuration(400) .lineAndArcColor(Color.parseColor("#eb273f")) .dismissOnTouch(true) .dismissOnBackPress(true) .enableDismissAfterShown(true) .usageId(usageId) //UNIQUE ID .show(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if(spotLight.isShown()){ spotLight.removeSpotlightView(false);//Remove current spotlight view from parent resetAndPlay.performClick();//Show it again in new orientation if required. } } }
294coder/Efficient-MIF
1,194
utils/sharpening_index/tools.py
# -*- coding: utf-8 -*- """ Copyright (c) 2020 Vivone Gemine. All rights reserved. This work should only be used for nonprofit purposes. @author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home ) Adapted versions of the functions used in: Python Code on GitHub: https://github.com/sergiovitale/pansharpening-cnn-python-version Copyright (c) 2018 Image Processing Research Group of University Federico II of Naples ('GRIP-UNINA'). """ import numpy as np def fir_filter_wind(Hd,w): hd=np.rot90(np.fft.fftshift(np.rot90(Hd,2)),2) h=np.fft.fftshift(np.fft.ifft2(hd)) h=np.rot90(h,2) h=h*w #h=h/np.sum(h) return h def gaussian2d (N, std): t=np.arange(-(N-1)/2,(N+1)/2) #t=np.arange(-(N-1)/2,(N+2)/2) t1,t2=np.meshgrid(t,t) std=np.double(std) w = np.exp(-0.5*(t1/std)**2)*np.exp(-0.5*(t2/std)**2) return w def kaiser2d (N, beta): t=np.arange(-(N-1)/2,(N+1)/2)/np.double(N-1) #t=np.arange(-(N-1)/2,(N+2)/2)/np.double(N-1) t1,t2=np.meshgrid(t,t) t12=np.sqrt(t1*t1+t2*t2) w1=np.kaiser(N,beta) w=np.interp(t12,t,w1) w[t12>t[-1]]=0 w[t12<t[0]]=0 return w
2881099/FreeSql.AdminLTE
99,426
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/inputmask/jquery.inputmask.min.js
/*! * dist/jquery.inputmask.min * https://github.com/RobinHerbots/Inputmask * Copyright (c) 2010 - 2021 Robin Herbots * Licensed under the MIT license * Version: 5.0.7 */ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("jquery"));else if("function"==typeof define&&define.amd)define(["jquery"],t);else{var i="object"==typeof exports?t(require("jquery")):t(e.jQuery);for(var a in i)("object"==typeof exports?exports:e)[a]=i[a]}}(self,(function(e){return function(){"use strict";var t={3046:function(e,t,i){var a;Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,i(3851),i(219),i(207),i(5296);var n=((a=i(2394))&&a.__esModule?a:{default:a}).default;t.default=n},8741:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=!("undefined"==typeof window||!window.document||!window.document.createElement);t.default=i},3976:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a,n=(a=i(5581))&&a.__esModule?a:{default:a};var r={_maxTestPos:500,placeholder:"_",optionalmarker:["[","]"],quantifiermarker:["{","}"],groupmarker:["(",")"],alternatormarker:"|",escapeChar:"\\",mask:null,regex:null,oncomplete:function(){},onincomplete:function(){},oncleared:function(){},repeat:0,greedy:!1,autoUnmask:!1,removeMaskOnSubmit:!1,clearMaskOnLostFocus:!0,insertMode:!0,insertModeVisual:!0,clearIncomplete:!1,alias:null,onKeyDown:function(){},onBeforeMask:null,onBeforePaste:function(e,t){return"function"==typeof t.onBeforeMask?t.onBeforeMask.call(this,e,t):e},onBeforeWrite:null,onUnMask:null,showMaskOnFocus:!0,showMaskOnHover:!0,onKeyValidation:function(){},skipOptionalPartCharacter:" ",numericInput:!1,rightAlign:!1,undoOnEscape:!0,radixPoint:"",_radixDance:!1,groupSeparator:"",keepStatic:null,positionCaretOnTab:!0,tabThrough:!1,supportsInputType:["text","tel","url","password","search"],ignorables:[n.default.BACKSPACE,n.default.TAB,n.default["PAUSE/BREAK"],n.default.ESCAPE,n.default.PAGE_UP,n.default.PAGE_DOWN,n.default.END,n.default.HOME,n.default.LEFT,n.default.UP,n.default.RIGHT,n.default.DOWN,n.default.INSERT,n.default.DELETE,93,112,113,114,115,116,117,118,119,120,121,122,123,0,229],isComplete:null,preValidation:null,postValidation:null,staticDefinitionSymbol:void 0,jitMasking:!1,nullable:!0,inputEventOnly:!1,noValuePatching:!1,positionCaretOnClick:"lvp",casing:null,inputmode:"text",importDataAttributes:!0,shiftPositions:!0,usePrototypeDefinitions:!0,validationEventTimeOut:3e3,substitutes:{}};t.default=r},7392:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default={9:{validator:"[0-9\uff10-\uff19]",definitionSymbol:"*"},a:{validator:"[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",definitionSymbol:"*"},"*":{validator:"[0-9\uff10-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]"}}},3287:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a,n=(a=i(2047))&&a.__esModule?a:{default:a};if(void 0===n.default)throw"jQuery not loaded!";var r=n.default;t.default=r},9845:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.ua=t.mobile=t.iphone=t.iemobile=t.ie=void 0;var a,n=(a=i(9380))&&a.__esModule?a:{default:a};var r=n.default.navigator&&n.default.navigator.userAgent||"",o=r.indexOf("MSIE ")>0||r.indexOf("Trident/")>0,s="ontouchstart"in n.default,l=/iemobile/i.test(r),u=/iphone/i.test(r)&&!l;t.iphone=u,t.iemobile=l,t.mobile=s,t.ie=o,t.ua=r},7184:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e.replace(i,"\\$1")};var i=new RegExp("(\\"+["/",".","*","+","?","|","(",")","[","]","{","}","\\","$","^"].join("|\\")+")","gim")},6030:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.EventHandlers=void 0;var a,n=i(8711),r=(a=i(5581))&&a.__esModule?a:{default:a},o=i(9845),s=i(7215),l=i(7760),u=i(4713);function c(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(!e)return;if("string"==typeof e)return f(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return f(e,t)}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var a=0,n=function(){};return{s:n,n:function(){return a>=e.length?{done:!0}:{done:!1,value:e[a++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,s=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){s=!0,r=e},f:function(){try{o||null==i.return||i.return()}finally{if(s)throw r}}}}function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,a=new Array(t);i<t;i++)a[i]=e[i];return a}var d={keydownEvent:function(e){var t=this.inputmask,i=t.opts,a=t.dependencyLib,c=t.maskset,f=this,d=a(f),p=e.keyCode,h=n.caret.call(t,f),m=i.onKeyDown.call(this,e,n.getBuffer.call(t),h,i);if(void 0!==m)return m;if(p===r.default.BACKSPACE||p===r.default.DELETE||o.iphone&&p===r.default.BACKSPACE_SAFARI||e.ctrlKey&&p===r.default.X&&!("oncut"in f))e.preventDefault(),s.handleRemove.call(t,f,p,h),(0,l.writeBuffer)(f,n.getBuffer.call(t,!0),c.p,e,f.inputmask._valueGet()!==n.getBuffer.call(t).join(""));else if(p===r.default.END||p===r.default.PAGE_DOWN){e.preventDefault();var v=n.seekNext.call(t,n.getLastValidPosition.call(t));n.caret.call(t,f,e.shiftKey?h.begin:v,v,!0)}else p===r.default.HOME&&!e.shiftKey||p===r.default.PAGE_UP?(e.preventDefault(),n.caret.call(t,f,0,e.shiftKey?h.begin:0,!0)):i.undoOnEscape&&p===r.default.ESCAPE&&!0!==e.altKey?((0,l.checkVal)(f,!0,!1,t.undoValue.split("")),d.trigger("click")):p!==r.default.INSERT||e.shiftKey||e.ctrlKey||void 0!==t.userOptions.insertMode?!0===i.tabThrough&&p===r.default.TAB?!0===e.shiftKey?(h.end=n.seekPrevious.call(t,h.end,!0),!0===u.getTest.call(t,h.end-1).match.static&&h.end--,h.begin=n.seekPrevious.call(t,h.end,!0),h.begin>=0&&h.end>0&&(e.preventDefault(),n.caret.call(t,f,h.begin,h.end))):(h.begin=n.seekNext.call(t,h.begin,!0),h.end=n.seekNext.call(t,h.begin,!0),h.end<c.maskLength&&h.end--,h.begin<=c.maskLength&&(e.preventDefault(),n.caret.call(t,f,h.begin,h.end))):e.shiftKey||i.insertModeVisual&&!1===i.insertMode&&(p===r.default.RIGHT?setTimeout((function(){var e=n.caret.call(t,f);n.caret.call(t,f,e.begin)}),0):p===r.default.LEFT&&setTimeout((function(){var e=n.translatePosition.call(t,f.inputmask.caretPos.begin);n.translatePosition.call(t,f.inputmask.caretPos.end);t.isRTL?n.caret.call(t,f,e+(e===c.maskLength?0:1)):n.caret.call(t,f,e-(0===e?0:1))}),0)):s.isSelection.call(t,h)?i.insertMode=!i.insertMode:(i.insertMode=!i.insertMode,n.caret.call(t,f,h.begin,h.begin));t.ignorable=i.ignorables.includes(p)},keypressEvent:function(e,t,i,a,o){var u=this.inputmask||this,c=u.opts,f=u.dependencyLib,d=u.maskset,p=u.el,h=f(p),m=e.keyCode;if(!(!0===t||e.ctrlKey&&e.altKey)&&(e.ctrlKey||e.metaKey||u.ignorable))return m===r.default.ENTER&&u.undoValue!==u._valueGet(!0)&&(u.undoValue=u._valueGet(!0),setTimeout((function(){h.trigger("change")}),0)),u.skipInputEvent=!0,!0;if(m){44!==m&&46!==m||3!==e.location||""===c.radixPoint||(m=c.radixPoint.charCodeAt(0));var v,g=t?{begin:o,end:o}:n.caret.call(u,p),k=String.fromCharCode(m);k=c.substitutes[k]||k,d.writeOutBuffer=!0;var y=s.isValid.call(u,g,k,a,void 0,void 0,void 0,t);if(!1!==y&&(n.resetMaskSet.call(u,!0),v=void 0!==y.caret?y.caret:n.seekNext.call(u,y.pos.begin?y.pos.begin:y.pos),d.p=v),v=c.numericInput&&void 0===y.caret?n.seekPrevious.call(u,v):v,!1!==i&&(setTimeout((function(){c.onKeyValidation.call(p,m,y)}),0),d.writeOutBuffer&&!1!==y)){var b=n.getBuffer.call(u);(0,l.writeBuffer)(p,b,v,e,!0!==t)}if(e.preventDefault(),t)return!1!==y&&(y.forwardPosition=v),y}},keyupEvent:function(e){var t=this.inputmask;!t.isComposing||e.keyCode!==r.default.KEY_229&&e.keyCode!==r.default.ENTER||t.$el.trigger("input")},pasteEvent:function(e){var t,i=this.inputmask,a=i.opts,r=i._valueGet(!0),o=n.caret.call(i,this);i.isRTL&&(t=o.end,o.end=n.translatePosition.call(i,o.begin),o.begin=n.translatePosition.call(i,t));var s=r.substr(0,o.begin),u=r.substr(o.end,r.length);if(s==(i.isRTL?n.getBufferTemplate.call(i).slice().reverse():n.getBufferTemplate.call(i)).slice(0,o.begin).join("")&&(s=""),u==(i.isRTL?n.getBufferTemplate.call(i).slice().reverse():n.getBufferTemplate.call(i)).slice(o.end).join("")&&(u=""),window.clipboardData&&window.clipboardData.getData)r=s+window.clipboardData.getData("Text")+u;else{if(!e.clipboardData||!e.clipboardData.getData)return!0;r=s+e.clipboardData.getData("text/plain")+u}var f=r;if(i.isRTL){f=f.split("");var d,p=c(n.getBufferTemplate.call(i));try{for(p.s();!(d=p.n()).done;){var h=d.value;f[0]===h&&f.shift()}}catch(e){p.e(e)}finally{p.f()}f=f.join("")}if("function"==typeof a.onBeforePaste){if(!1===(f=a.onBeforePaste.call(i,f,a)))return!1;f||(f=r)}(0,l.checkVal)(this,!0,!1,f.toString().split(""),e),e.preventDefault()},inputFallBackEvent:function(e){var t=this.inputmask,i=t.opts,a=t.dependencyLib;var s=this,c=s.inputmask._valueGet(!0),f=(t.isRTL?n.getBuffer.call(t).slice().reverse():n.getBuffer.call(t)).join(""),p=n.caret.call(t,s,void 0,void 0,!0);if(f!==c){c=function(e,i,a){if(o.iemobile){var r=i.replace(n.getBuffer.call(t).join(""),"");if(1===r.length){var s=i.split("");s.splice(a.begin,0,r),i=s.join("")}}return i}(0,c,p);var h=function(e,a,r){for(var o,s,l,c=e.substr(0,r.begin).split(""),f=e.substr(r.begin).split(""),d=a.substr(0,r.begin).split(""),p=a.substr(r.begin).split(""),h=c.length>=d.length?c.length:d.length,m=f.length>=p.length?f.length:p.length,v="",g=[],k="~";c.length<h;)c.push(k);for(;d.length<h;)d.push(k);for(;f.length<m;)f.unshift(k);for(;p.length<m;)p.unshift(k);var y=c.concat(f),b=d.concat(p);for(s=0,o=y.length;s<o;s++)switch(l=u.getPlaceholder.call(t,n.translatePosition.call(t,s)),v){case"insertText":b[s-1]===y[s]&&r.begin==y.length-1&&g.push(y[s]),s=o;break;case"insertReplacementText":case"deleteContentBackward":y[s]===k?r.end++:s=o;break;default:y[s]!==b[s]&&(y[s+1]!==k&&y[s+1]!==l&&void 0!==y[s+1]||(b[s]!==l||b[s+1]!==k)&&b[s]!==k?b[s+1]===k&&b[s]===y[s+1]?(v="insertText",g.push(y[s]),r.begin--,r.end--):y[s]!==l&&y[s]!==k&&(y[s+1]===k||b[s]!==y[s]&&b[s+1]===y[s+1])?(v="insertReplacementText",g.push(y[s]),r.begin--):y[s]===k?(v="deleteContentBackward",(n.isMask.call(t,n.translatePosition.call(t,s),!0)||b[s]===i.radixPoint)&&r.end++):s=o:(v="insertText",g.push(y[s]),r.begin--,r.end--))}return{action:v,data:g,caret:r}}(c,f,p);switch((s.inputmask.shadowRoot||s.ownerDocument).activeElement!==s&&s.focus(),(0,l.writeBuffer)(s,n.getBuffer.call(t)),n.caret.call(t,s,p.begin,p.end,!0),h.action){case"insertText":case"insertReplacementText":h.data.forEach((function(e,i){var n=new a.Event("keypress");n.keyCode=e.charCodeAt(0),t.ignorable=!1,d.keypressEvent.call(s,n)})),setTimeout((function(){t.$el.trigger("keyup")}),0);break;case"deleteContentBackward":var m=new a.Event("keydown");m.keyCode=r.default.BACKSPACE,d.keydownEvent.call(s,m);break;default:(0,l.applyInputValue)(s,c)}e.preventDefault()}},compositionendEvent:function(e){var t=this.inputmask;t.isComposing=!1,t.$el.trigger("input")},setValueEvent:function(e){var t=this.inputmask,i=this,a=e&&e.detail?e.detail[0]:arguments[1];void 0===a&&(a=i.inputmask._valueGet(!0)),(0,l.applyInputValue)(i,a),(e.detail&&void 0!==e.detail[1]||void 0!==arguments[2])&&n.caret.call(t,i,e.detail?e.detail[1]:arguments[2])},focusEvent:function(e){var t=this.inputmask,i=t.opts,a=this,r=a.inputmask._valueGet();i.showMaskOnFocus&&r!==n.getBuffer.call(t).join("")&&(0,l.writeBuffer)(a,n.getBuffer.call(t),n.seekNext.call(t,n.getLastValidPosition.call(t))),!0!==i.positionCaretOnTab||!1!==t.mouseEnter||s.isComplete.call(t,n.getBuffer.call(t))&&-1!==n.getLastValidPosition.call(t)||d.clickEvent.apply(a,[e,!0]),t.undoValue=t._valueGet(!0)},invalidEvent:function(e){this.inputmask.validationEvent=!0},mouseleaveEvent:function(){var e=this.inputmask,t=e.opts,i=this;e.mouseEnter=!1,t.clearMaskOnLostFocus&&(i.inputmask.shadowRoot||i.ownerDocument).activeElement!==i&&(0,l.HandleNativePlaceholder)(i,e.originalPlaceholder)},clickEvent:function(e,t){var i=this.inputmask,a=this;if((a.inputmask.shadowRoot||a.ownerDocument).activeElement===a){var r=n.determineNewCaretPosition.call(i,n.caret.call(i,a),t);void 0!==r&&n.caret.call(i,a,r)}},cutEvent:function(e){var t=this.inputmask,i=t.maskset,a=this,o=n.caret.call(t,a),u=t.isRTL?n.getBuffer.call(t).slice(o.end,o.begin):n.getBuffer.call(t).slice(o.begin,o.end),c=t.isRTL?u.reverse().join(""):u.join("");window.navigator.clipboard?window.navigator.clipboard.writeText(c):window.clipboardData&&window.clipboardData.getData&&window.clipboardData.setData("Text",c),s.handleRemove.call(t,a,r.default.DELETE,o),(0,l.writeBuffer)(a,n.getBuffer.call(t),i.p,e,t.undoValue!==t._valueGet(!0))},blurEvent:function(e){var t=this.inputmask,i=t.opts,a=(0,t.dependencyLib)(this),r=this;if(r.inputmask){(0,l.HandleNativePlaceholder)(r,t.originalPlaceholder);var o=r.inputmask._valueGet(),u=n.getBuffer.call(t).slice();""!==o&&(i.clearMaskOnLostFocus&&(-1===n.getLastValidPosition.call(t)&&o===n.getBufferTemplate.call(t).join("")?u=[]:l.clearOptionalTail.call(t,u)),!1===s.isComplete.call(t,u)&&(setTimeout((function(){a.trigger("incomplete")}),0),i.clearIncomplete&&(n.resetMaskSet.call(t),u=i.clearMaskOnLostFocus?[]:n.getBufferTemplate.call(t).slice())),(0,l.writeBuffer)(r,u,void 0,e)),t.undoValue!==t._valueGet(!0)&&(t.undoValue=t._valueGet(!0),a.trigger("change"))}},mouseenterEvent:function(){var e=this.inputmask,t=e.opts,i=this;if(e.mouseEnter=!0,(i.inputmask.shadowRoot||i.ownerDocument).activeElement!==i){var a=(e.isRTL?n.getBufferTemplate.call(e).slice().reverse():n.getBufferTemplate.call(e)).join("");e.placeholder!==a&&i.placeholder!==e.originalPlaceholder&&(e.originalPlaceholder=i.placeholder),t.showMaskOnHover&&(0,l.HandleNativePlaceholder)(i,a)}},submitEvent:function(){var e=this.inputmask,t=e.opts;e.undoValue!==e._valueGet(!0)&&e.$el.trigger("change"),-1===n.getLastValidPosition.call(e)&&e._valueGet&&e._valueGet()===n.getBufferTemplate.call(e).join("")&&e._valueSet(""),t.clearIncomplete&&!1===s.isComplete.call(e,n.getBuffer.call(e))&&e._valueSet(""),t.removeMaskOnSubmit&&(e._valueSet(e.unmaskedvalue(),!0),setTimeout((function(){(0,l.writeBuffer)(e.el,n.getBuffer.call(e))}),0))},resetEvent:function(){var e=this.inputmask;e.refreshValue=!0,setTimeout((function(){(0,l.applyInputValue)(e.el,e._valueGet(!0))}),0)}};t.EventHandlers=d},9716:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.EventRuler=void 0;var a=s(i(2394)),n=s(i(5581)),r=i(8711),o=i(7760);function s(e){return e&&e.__esModule?e:{default:e}}var l={on:function(e,t,i){var s=e.inputmask.dependencyLib,l=function(t){t.originalEvent&&(t=t.originalEvent||t,arguments[0]=t);var l,u=this,c=u.inputmask,f=c?c.opts:void 0;if(void 0===c&&"FORM"!==this.nodeName){var d=s.data(u,"_inputmask_opts");s(u).off(),d&&new a.default(d).mask(u)}else{if(["submit","reset","setvalue"].includes(t.type)||"FORM"===this.nodeName||!(u.disabled||u.readOnly&&!("keydown"===t.type&&t.ctrlKey&&67===t.keyCode||!1===f.tabThrough&&t.keyCode===n.default.TAB))){switch(t.type){case"input":if(!0===c.skipInputEvent||t.inputType&&"insertCompositionText"===t.inputType)return c.skipInputEvent=!1,t.preventDefault();break;case"keydown":c.skipKeyPressEvent=!1,c.skipInputEvent=c.isComposing=t.keyCode===n.default.KEY_229;break;case"keyup":case"compositionend":c.isComposing&&(c.skipInputEvent=!1);break;case"keypress":if(!0===c.skipKeyPressEvent)return t.preventDefault();c.skipKeyPressEvent=!0;break;case"click":case"focus":return c.validationEvent?(c.validationEvent=!1,e.blur(),(0,o.HandleNativePlaceholder)(e,(c.isRTL?r.getBufferTemplate.call(c).slice().reverse():r.getBufferTemplate.call(c)).join("")),setTimeout((function(){e.focus()}),f.validationEventTimeOut),!1):(l=arguments,setTimeout((function(){e.inputmask&&i.apply(u,l)}),0),!1)}var p=i.apply(u,arguments);return!1===p&&(t.preventDefault(),t.stopPropagation()),p}t.preventDefault()}};["submit","reset"].includes(t)?(l=l.bind(e),null!==e.form&&s(e.form).on(t,l)):s(e).on(t,l),e.inputmask.events[t]=e.inputmask.events[t]||[],e.inputmask.events[t].push(l)},off:function(e,t){if(e.inputmask&&e.inputmask.events){var i=e.inputmask.dependencyLib,a=e.inputmask.events;for(var n in t&&((a=[])[t]=e.inputmask.events[t]),a){for(var r=a[n];r.length>0;){var o=r.pop();["submit","reset"].includes(n)?null!==e.form&&i(e.form).off(n,o):i(e).off(n,o)}delete e.inputmask.events[n]}}}};t.EventRuler=l},219:function(e,t,i){var a=d(i(2394)),n=d(i(5581)),r=d(i(7184)),o=i(8711),s=i(4713);function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function u(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==i)return;var a,n,r=[],o=!0,s=!1;try{for(i=i.call(e);!(o=(a=i.next()).done)&&(r.push(a.value),!t||r.length!==t);o=!0);}catch(e){s=!0,n=e}finally{try{o||null==i.return||i.return()}finally{if(s)throw n}}return r}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return c(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return c(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,a=new Array(t);i<t;i++)a[i]=e[i];return a}function f(e,t){for(var i=0;i<t.length;i++){var a=t[i];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}function d(e){return e&&e.__esModule?e:{default:e}}var p=a.default.dependencyLib,h=function(){function e(t,i,a){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.mask=t,this.format=i,this.opts=a,this._date=new Date(1,0,1),this.initDateObject(t,this.opts)}var t,i,a;return t=e,(i=[{key:"date",get:function(){return void 0===this._date&&(this._date=new Date(1,0,1),this.initDateObject(void 0,this.opts)),this._date}},{key:"initDateObject",value:function(e,t){var i;for(P(t).lastIndex=0;i=P(t).exec(this.format);){var a=new RegExp("\\d+$").exec(i[0]),n=a?i[0][0]+"x":i[0],r=void 0;if(void 0!==e){if(a){var o=P(t).lastIndex,s=O(i.index,t);P(t).lastIndex=o,r=e.slice(0,e.indexOf(s.nextMatch[0]))}else r=e.slice(0,n.length);e=e.slice(r.length)}Object.prototype.hasOwnProperty.call(g,n)&&this.setValue(this,r,n,g[n][2],g[n][1])}}},{key:"setValue",value:function(e,t,i,a,n){if(void 0!==t&&(e[a]="ampm"===a?t:t.replace(/[^0-9]/g,"0"),e["raw"+a]=t.replace(/\s/g,"_")),void 0!==n){var r=e[a];("day"===a&&29===parseInt(r)||"month"===a&&2===parseInt(r))&&(29!==parseInt(e.day)||2!==parseInt(e.month)||""!==e.year&&void 0!==e.year||e._date.setFullYear(2012,1,29)),"day"===a&&(v=!0,0===parseInt(r)&&(r=1)),"month"===a&&(v=!0),"year"===a&&(v=!0,r.length<4&&(r=w(r,4,!0))),""===r||isNaN(r)||n.call(e._date,r),"ampm"===a&&n.call(e._date,r)}}},{key:"reset",value:function(){this._date=new Date(1,0,1)}},{key:"reInit",value:function(){this._date=void 0,this.date}}])&&f(t.prototype,i),a&&f(t,a),Object.defineProperty(t,"prototype",{writable:!1}),e}(),m=(new Date).getFullYear(),v=!1,g={d:["[1-9]|[12][0-9]|3[01]",Date.prototype.setDate,"day",Date.prototype.getDate],dd:["0[1-9]|[12][0-9]|3[01]",Date.prototype.setDate,"day",function(){return w(Date.prototype.getDate.call(this),2)}],ddd:[""],dddd:[""],m:["[1-9]|1[012]",function(e){var t=e?parseInt(e):0;return t>0&&t--,Date.prototype.setMonth.call(this,t)},"month",function(){return Date.prototype.getMonth.call(this)+1}],mm:["0[1-9]|1[012]",function(e){var t=e?parseInt(e):0;return t>0&&t--,Date.prototype.setMonth.call(this,t)},"month",function(){return w(Date.prototype.getMonth.call(this)+1,2)}],mmm:[""],mmmm:[""],yy:["[0-9]{2}",Date.prototype.setFullYear,"year",function(){return w(Date.prototype.getFullYear.call(this),2)}],yyyy:["[0-9]{4}",Date.prototype.setFullYear,"year",function(){return w(Date.prototype.getFullYear.call(this),4)}],h:["[1-9]|1[0-2]",Date.prototype.setHours,"hours",Date.prototype.getHours],hh:["0[1-9]|1[0-2]",Date.prototype.setHours,"hours",function(){return w(Date.prototype.getHours.call(this),2)}],hx:[function(e){return"[0-9]{".concat(e,"}")},Date.prototype.setHours,"hours",function(e){return Date.prototype.getHours}],H:["1?[0-9]|2[0-3]",Date.prototype.setHours,"hours",Date.prototype.getHours],HH:["0[0-9]|1[0-9]|2[0-3]",Date.prototype.setHours,"hours",function(){return w(Date.prototype.getHours.call(this),2)}],Hx:[function(e){return"[0-9]{".concat(e,"}")},Date.prototype.setHours,"hours",function(e){return function(){return w(Date.prototype.getHours.call(this),e)}}],M:["[1-5]?[0-9]",Date.prototype.setMinutes,"minutes",Date.prototype.getMinutes],MM:["0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]",Date.prototype.setMinutes,"minutes",function(){return w(Date.prototype.getMinutes.call(this),2)}],s:["[1-5]?[0-9]",Date.prototype.setSeconds,"seconds",Date.prototype.getSeconds],ss:["0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]",Date.prototype.setSeconds,"seconds",function(){return w(Date.prototype.getSeconds.call(this),2)}],l:["[0-9]{3}",Date.prototype.setMilliseconds,"milliseconds",function(){return w(Date.prototype.getMilliseconds.call(this),3)}],L:["[0-9]{2}",Date.prototype.setMilliseconds,"milliseconds",function(){return w(Date.prototype.getMilliseconds.call(this),2)}],t:["[ap]",y,"ampm",b,1],tt:["[ap]m",y,"ampm",b,2],T:["[AP]",y,"ampm",b,1],TT:["[AP]M",y,"ampm",b,2],Z:[".*",void 0,"Z",function(){var e=this.toString().match(/\((.+)\)/)[1];e.includes(" ")&&(e=(e=e.replace("-"," ").toUpperCase()).split(" ").map((function(e){return u(e,1)[0]})).join(""));return e}],o:[""],S:[""]},k={isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:ss",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"};function y(e){var t=this.getHours();e.toLowerCase().includes("p")?this.setHours(t+12):e.toLowerCase().includes("a")&&t>=12&&this.setHours(t-12)}function b(){var e=this.getHours();return(e=e||12)>=12?"PM":"AM"}function x(e){var t=new RegExp("\\d+$").exec(e[0]);if(t&&void 0!==t[0]){var i=g[e[0][0]+"x"].slice("");return i[0]=i[0](t[0]),i[3]=i[3](t[0]),i}if(g[e[0]])return g[e[0]]}function P(e){if(!e.tokenizer){var t=[],i=[];for(var a in g)if(/\.*x$/.test(a)){var n=a[0]+"\\d+";-1===i.indexOf(n)&&i.push(n)}else-1===t.indexOf(a[0])&&t.push(a[0]);e.tokenizer="("+(i.length>0?i.join("|")+"|":"")+t.join("+|")+")+?|.",e.tokenizer=new RegExp(e.tokenizer,"g")}return e.tokenizer}function E(e,t,i){if(!v)return!0;if(void 0===e.rawday||!isFinite(e.rawday)&&new Date(e.date.getFullYear(),isFinite(e.rawmonth)?e.month:e.date.getMonth()+1,0).getDate()>=e.day||"29"==e.day&&(!isFinite(e.rawyear)||void 0===e.rawyear||""===e.rawyear)||new Date(e.date.getFullYear(),isFinite(e.rawmonth)?e.month:e.date.getMonth()+1,0).getDate()>=e.day)return t;if("29"==e.day){var a=O(t.pos,i);if("yyyy"===a.targetMatch[0]&&t.pos-a.targetMatchIndex==2)return t.remove=t.pos+1,t}else if("02"==e.month&&"30"==e.day&&void 0!==t.c)return e.day="03",e.date.setDate(3),e.date.setMonth(1),t.insert=[{pos:t.pos,c:"0"},{pos:t.pos+1,c:t.c}],t.caret=o.seekNext.call(this,t.pos+1),t;return!1}function S(e,t,i,a){var n,o,s="";for(P(i).lastIndex=0;n=P(i).exec(e);){if(void 0===t)if(o=x(n))s+="("+o[0]+")";else switch(n[0]){case"[":s+="(";break;case"]":s+=")?";break;default:s+=(0,r.default)(n[0])}else if(o=x(n))if(!0!==a&&o[3])s+=o[3].call(t.date);else o[2]?s+=t["raw"+o[2]]:s+=n[0];else s+=n[0]}return s}function w(e,t,i){for(e=String(e),t=t||2;e.length<t;)e=i?e+"0":"0"+e;return e}function _(e,t,i){return"string"==typeof e?new h(e,t,i):e&&"object"===l(e)&&Object.prototype.hasOwnProperty.call(e,"date")?e:void 0}function M(e,t){return S(t.inputFormat,{date:e},t)}function O(e,t){var i,a,n=0,r=0;for(P(t).lastIndex=0;a=P(t).exec(t.inputFormat);){var o=new RegExp("\\d+$").exec(a[0]);if((n+=r=o?parseInt(o[0]):a[0].length)>=e+1){i=a,a=P(t).exec(t.inputFormat);break}}return{targetMatchIndex:n-r,nextMatch:a,targetMatch:i}}a.default.extendAliases({datetime:{mask:function(e){return e.numericInput=!1,g.S=e.i18n.ordinalSuffix.join("|"),e.inputFormat=k[e.inputFormat]||e.inputFormat,e.displayFormat=k[e.displayFormat]||e.displayFormat||e.inputFormat,e.outputFormat=k[e.outputFormat]||e.outputFormat||e.inputFormat,e.placeholder=""!==e.placeholder?e.placeholder:e.inputFormat.replace(/[[\]]/,""),e.regex=S(e.inputFormat,void 0,e),e.min=_(e.min,e.inputFormat,e),e.max=_(e.max,e.inputFormat,e),null},placeholder:"",inputFormat:"isoDateTime",displayFormat:null,outputFormat:null,min:null,max:null,skipOptionalPartCharacter:"",i18n:{dayNames:["Mon","Tue","Wed","Thu","Fri","Sat","Sun","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],ordinalSuffix:["st","nd","rd","th"]},preValidation:function(e,t,i,a,n,r,o,s){if(s)return!0;if(isNaN(i)&&e[t]!==i){var l=O(t,n);if(l.nextMatch&&l.nextMatch[0]===i&&l.targetMatch[0].length>1){var u=g[l.targetMatch[0]][0];if(new RegExp(u).test("0"+e[t-1]))return e[t]=e[t-1],e[t-1]="0",{fuzzy:!0,buffer:e,refreshFromBuffer:{start:t-1,end:t+1},pos:t+1}}}return!0},postValidation:function(e,t,i,a,n,r,o,l){var u,c;if(o)return!0;if(!1===a&&(((u=O(t+1,n)).targetMatch&&u.targetMatchIndex===t&&u.targetMatch[0].length>1&&void 0!==g[u.targetMatch[0]]||(u=O(t+2,n)).targetMatch&&u.targetMatchIndex===t+1&&u.targetMatch[0].length>1&&void 0!==g[u.targetMatch[0]])&&(c=g[u.targetMatch[0]][0]),void 0!==c&&(void 0!==r.validPositions[t+1]&&new RegExp(c).test(i+"0")?(e[t]=i,e[t+1]="0",a={pos:t+2,caret:t}):new RegExp(c).test("0"+i)&&(e[t]="0",e[t+1]=i,a={pos:t+2})),!1===a))return a;if(a.fuzzy&&(e=a.buffer,t=a.pos),(u=O(t,n)).targetMatch&&u.targetMatch[0]&&void 0!==g[u.targetMatch[0]]){var f=g[u.targetMatch[0]];c=f[0];var d=e.slice(u.targetMatchIndex,u.targetMatchIndex+u.targetMatch[0].length);if(!1===new RegExp(c).test(d.join(""))&&2===u.targetMatch[0].length&&r.validPositions[u.targetMatchIndex]&&r.validPositions[u.targetMatchIndex+1]&&(r.validPositions[u.targetMatchIndex+1].input="0"),"year"==f[2])for(var p=s.getMaskTemplate.call(this,!1,1,void 0,!0),h=t+1;h<e.length;h++)e[h]=p[h],delete r.validPositions[h]}var v=a,k=_(e.join(""),n.inputFormat,n);return v&&k.date.getTime()==k.date.getTime()&&(n.prefillYear&&(v=function(e,t,i){if(e.year!==e.rawyear){var a=m.toString(),n=e.rawyear.replace(/[^0-9]/g,""),r=a.slice(0,n.length),o=a.slice(n.length);if(2===n.length&&n===r){var s=new Date(m,e.month-1,e.day);e.day==s.getDate()&&(!i.max||i.max.date.getTime()>=s.getTime())&&(e.date.setFullYear(m),e.year=a,t.insert=[{pos:t.pos+1,c:o[0]},{pos:t.pos+2,c:o[1]}])}}return t}(k,v,n)),v=function(e,t,i,a,n){if(!t)return t;if(t&&i.min&&i.min.date.getTime()==i.min.date.getTime()){var r;for(e.reset(),P(i).lastIndex=0;r=P(i).exec(i.inputFormat);){var o;if((o=x(r))&&o[3]){for(var s=o[1],l=e[o[2]],u=i.min[o[2]],c=i.max?i.max[o[2]]:u,f=[],d=!1,p=0;p<u.length;p++)void 0!==a.validPositions[p+r.index]||d?(f[p]=l[p],d=d||l[p]>u[p]):(f[p]=u[p],"year"===o[2]&&l.length-1==p&&u!=c&&(f=(parseInt(f.join(""))+1).toString().split("")),"ampm"===o[2]&&u!=c&&i.min.date.getTime()>e.date.getTime()&&(f[p]=c[p]));s.call(e._date,f.join(""))}}t=i.min.date.getTime()<=e.date.getTime(),e.reInit()}return t&&i.max&&i.max.date.getTime()==i.max.date.getTime()&&(t=i.max.date.getTime()>=e.date.getTime()),t}(k,v=E.call(this,k,v,n),n,r)),void 0!==t&&v&&a.pos!==t?{buffer:S(n.inputFormat,k,n).split(""),refreshFromBuffer:{start:t,end:a.pos},pos:a.caret||a.pos}:v},onKeyDown:function(e,t,i,a){e.ctrlKey&&e.keyCode===n.default.RIGHT&&(this.inputmask._valueSet(M(new Date,a)),p(this).trigger("setvalue"))},onUnMask:function(e,t,i){return t?S(i.outputFormat,_(e,i.inputFormat,i),i,!0):t},casing:function(e,t,i,a){return 0==t.nativeDef.indexOf("[ap]")?e.toLowerCase():0==t.nativeDef.indexOf("[AP]")?e.toUpperCase():e},onBeforeMask:function(e,t){return"[object Date]"===Object.prototype.toString.call(e)&&(e=M(e,t)),e},insertMode:!1,shiftPositions:!1,keepStatic:!1,inputmode:"numeric",prefillYear:!0}})},3851:function(e,t,i){var a,n=(a=i(2394))&&a.__esModule?a:{default:a},r=i(8711),o=i(4713);n.default.extendDefinitions({A:{validator:"[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",casing:"upper"},"&":{validator:"[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",casing:"upper"},"#":{validator:"[0-9A-Fa-f]",casing:"upper"}});var s=new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]");function l(e,t,i,a,n){return i-1>-1&&"."!==t.buffer[i-1]?(e=t.buffer[i-1]+e,e=i-2>-1&&"."!==t.buffer[i-2]?t.buffer[i-2]+e:"0"+e):e="00"+e,s.test(e)}n.default.extendAliases({cssunit:{regex:"[+-]?[0-9]+\\.?([0-9]+)?(px|em|rem|ex|%|in|cm|mm|pt|pc)"},url:{regex:"(https?|ftp)://.*",autoUnmask:!1,keepStatic:!1,tabThrough:!0},ip:{mask:"i{1,3}.j{1,3}.k{1,3}.l{1,3}",definitions:{i:{validator:l},j:{validator:l},k:{validator:l},l:{validator:l}},onUnMask:function(e,t,i){return e},inputmode:"decimal",substitutes:{",":"."}},email:{mask:function(e){var t="*{1,64}[.*{1,64}][.*{1,64}][.*{1,63}]@-{1,63}.-{1,63}[.-{1,63}][.-{1,63}]",i=t;if(e.separator)for(var a=0;a<e.quantifier;a++)i+="[".concat(e.separator).concat(t,"]");return i},greedy:!1,casing:"lower",separator:null,quantifier:5,skipOptionalPartCharacter:"",onBeforePaste:function(e,t){return(e=e.toLowerCase()).replace("mailto:","")},definitions:{"*":{validator:"[0-9\uff11-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5!#$%&'*+/=?^_`{|}~-]"},"-":{validator:"[0-9A-Za-z-]"}},onUnMask:function(e,t,i){return e},inputmode:"email"},mac:{mask:"##:##:##:##:##:##"},vin:{mask:"V{13}9{4}",definitions:{V:{validator:"[A-HJ-NPR-Za-hj-npr-z\\d]",casing:"upper"}},clearIncomplete:!0,autoUnmask:!0},ssn:{mask:"999-99-9999",postValidation:function(e,t,i,a,n,s,l){var u=o.getMaskTemplate.call(this,!0,r.getLastValidPosition.call(this),!0,!0);return/^(?!219-09-9999|078-05-1120)(?!666|000|9.{2}).{3}-(?!00).{2}-(?!0{4}).{4}$/.test(u.join(""))}}})},207:function(e,t,i){var a=s(i(2394)),n=s(i(5581)),r=s(i(7184)),o=i(8711);function s(e){return e&&e.__esModule?e:{default:e}}var l=a.default.dependencyLib;function u(e,t){for(var i="",n=0;n<e.length;n++)a.default.prototype.definitions[e.charAt(n)]||t.definitions[e.charAt(n)]||t.optionalmarker[0]===e.charAt(n)||t.optionalmarker[1]===e.charAt(n)||t.quantifiermarker[0]===e.charAt(n)||t.quantifiermarker[1]===e.charAt(n)||t.groupmarker[0]===e.charAt(n)||t.groupmarker[1]===e.charAt(n)||t.alternatormarker===e.charAt(n)?i+="\\"+e.charAt(n):i+=e.charAt(n);return i}function c(e,t,i,a){if(e.length>0&&t>0&&(!i.digitsOptional||a)){var n=e.indexOf(i.radixPoint),r=!1;i.negationSymbol.back===e[e.length-1]&&(r=!0,e.length--),-1===n&&(e.push(i.radixPoint),n=e.length-1);for(var o=1;o<=t;o++)isFinite(e[n+o])||(e[n+o]="0")}return r&&e.push(i.negationSymbol.back),e}function f(e,t){var i=0;if("+"===e){for(i in t.validPositions);i=o.seekNext.call(this,parseInt(i))}for(var a in t.tests)if((a=parseInt(a))>=i)for(var n=0,r=t.tests[a].length;n<r;n++)if((void 0===t.validPositions[a]||"-"===e)&&t.tests[a][n].match.def===e)return a+(void 0!==t.validPositions[a]&&"-"!==e?1:0);return i}function d(e,t){var i=-1;for(var a in t.validPositions){var n=t.validPositions[a];if(n&&n.match.def===e){i=parseInt(a);break}}return i}function p(e,t,i,a,n){var r=t.buffer?t.buffer.indexOf(n.radixPoint):-1,o=(-1!==r||a&&n.jitMasking)&&new RegExp(n.definitions[9].validator).test(e);return n._radixDance&&-1!==r&&o&&null==t.validPositions[r]?{insert:{pos:r===i?r+1:r,c:n.radixPoint},pos:i}:o}a.default.extendAliases({numeric:{mask:function(e){e.repeat=0,e.groupSeparator===e.radixPoint&&e.digits&&"0"!==e.digits&&("."===e.radixPoint?e.groupSeparator=",":","===e.radixPoint?e.groupSeparator=".":e.groupSeparator="")," "===e.groupSeparator&&(e.skipOptionalPartCharacter=void 0),e.placeholder.length>1&&(e.placeholder=e.placeholder.charAt(0)),"radixFocus"===e.positionCaretOnClick&&""===e.placeholder&&(e.positionCaretOnClick="lvp");var t="0",i=e.radixPoint;!0===e.numericInput&&void 0===e.__financeInput?(t="1",e.positionCaretOnClick="radixFocus"===e.positionCaretOnClick?"lvp":e.positionCaretOnClick,e.digitsOptional=!1,isNaN(e.digits)&&(e.digits=2),e._radixDance=!1,i=","===e.radixPoint?"?":"!",""!==e.radixPoint&&void 0===e.definitions[i]&&(e.definitions[i]={},e.definitions[i].validator="["+e.radixPoint+"]",e.definitions[i].placeholder=e.radixPoint,e.definitions[i].static=!0,e.definitions[i].generated=!0)):(e.__financeInput=!1,e.numericInput=!0);var a,n="[+]";if(n+=u(e.prefix,e),""!==e.groupSeparator?(void 0===e.definitions[e.groupSeparator]&&(e.definitions[e.groupSeparator]={},e.definitions[e.groupSeparator].validator="["+e.groupSeparator+"]",e.definitions[e.groupSeparator].placeholder=e.groupSeparator,e.definitions[e.groupSeparator].static=!0,e.definitions[e.groupSeparator].generated=!0),n+=e._mask(e)):n+="9{+}",void 0!==e.digits&&0!==e.digits){var o=e.digits.toString().split(",");isFinite(o[0])&&o[1]&&isFinite(o[1])?n+=i+t+"{"+e.digits+"}":(isNaN(e.digits)||parseInt(e.digits)>0)&&(e.digitsOptional||e.jitMasking?(a=n+i+t+"{0,"+e.digits+"}",e.keepStatic=!0):n+=i+t+"{"+e.digits+"}")}else e.inputmode="numeric";return n+=u(e.suffix,e),n+="[-]",a&&(n=[a+u(e.suffix,e)+"[-]",n]),e.greedy=!1,function(e){void 0===e.parseMinMaxOptions&&(null!==e.min&&(e.min=e.min.toString().replace(new RegExp((0,r.default)(e.groupSeparator),"g"),""),","===e.radixPoint&&(e.min=e.min.replace(e.radixPoint,".")),e.min=isFinite(e.min)?parseFloat(e.min):NaN,isNaN(e.min)&&(e.min=Number.MIN_VALUE)),null!==e.max&&(e.max=e.max.toString().replace(new RegExp((0,r.default)(e.groupSeparator),"g"),""),","===e.radixPoint&&(e.max=e.max.replace(e.radixPoint,".")),e.max=isFinite(e.max)?parseFloat(e.max):NaN,isNaN(e.max)&&(e.max=Number.MAX_VALUE)),e.parseMinMaxOptions="done")}(e),""!==e.radixPoint&&(e.substitutes["."==e.radixPoint?",":"."]=e.radixPoint),n},_mask:function(e){return"("+e.groupSeparator+"999){+|1}"},digits:"*",digitsOptional:!0,enforceDigitsOnBlur:!1,radixPoint:".",positionCaretOnClick:"radixFocus",_radixDance:!0,groupSeparator:"",allowMinus:!0,negationSymbol:{front:"-",back:""},prefix:"",suffix:"",min:null,max:null,SetMaxOnOverflow:!1,step:1,inputType:"text",unmaskAsNumber:!1,roundingFN:Math.round,inputmode:"decimal",shortcuts:{k:"1000",m:"1000000"},placeholder:"0",greedy:!1,rightAlign:!0,insertMode:!0,autoUnmask:!1,skipOptionalPartCharacter:"",usePrototypeDefinitions:!1,stripLeadingZeroes:!0,definitions:{0:{validator:p},1:{validator:p,definitionSymbol:"9"},9:{validator:"[0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]",definitionSymbol:"*"},"+":{validator:function(e,t,i,a,n){return n.allowMinus&&("-"===e||e===n.negationSymbol.front)}},"-":{validator:function(e,t,i,a,n){return n.allowMinus&&e===n.negationSymbol.back}}},preValidation:function(e,t,i,a,n,r,o,s){if(!1!==n.__financeInput&&i===n.radixPoint)return!1;var l=e.indexOf(n.radixPoint),u=t;if(t=function(e,t,i,a,n){return n._radixDance&&n.numericInput&&t!==n.negationSymbol.back&&e<=i&&(i>0||t==n.radixPoint)&&(void 0===a.validPositions[e-1]||a.validPositions[e-1].input!==n.negationSymbol.back)&&(e-=1),e}(t,i,l,r,n),"-"===i||i===n.negationSymbol.front){if(!0!==n.allowMinus)return!1;var c=!1,p=d("+",r),h=d("-",r);return-1!==p&&(c=[p,h]),!1!==c?{remove:c,caret:u-n.negationSymbol.back.length}:{insert:[{pos:f.call(this,"+",r),c:n.negationSymbol.front,fromIsValid:!0},{pos:f.call(this,"-",r),c:n.negationSymbol.back,fromIsValid:void 0}],caret:u+n.negationSymbol.back.length}}if(i===n.groupSeparator)return{caret:u};if(s)return!0;if(-1!==l&&!0===n._radixDance&&!1===a&&i===n.radixPoint&&void 0!==n.digits&&(isNaN(n.digits)||parseInt(n.digits)>0)&&l!==t)return{caret:n._radixDance&&t===l-1?l+1:l};if(!1===n.__financeInput)if(a){if(n.digitsOptional)return{rewritePosition:o.end};if(!n.digitsOptional){if(o.begin>l&&o.end<=l)return i===n.radixPoint?{insert:{pos:l+1,c:"0",fromIsValid:!0},rewritePosition:l}:{rewritePosition:l+1};if(o.begin<l)return{rewritePosition:o.begin-1}}}else if(!n.showMaskOnHover&&!n.showMaskOnFocus&&!n.digitsOptional&&n.digits>0&&""===this.__valueGet.call(this.el))return{rewritePosition:l};return{rewritePosition:t}},postValidation:function(e,t,i,a,n,r,o){if(!1===a)return a;if(o)return!0;if(null!==n.min||null!==n.max){var s=n.onUnMask(e.slice().reverse().join(""),void 0,l.extend({},n,{unmaskAsNumber:!0}));if(null!==n.min&&s<n.min&&(s.toString().length>n.min.toString().length||s<0))return!1;if(null!==n.max&&s>n.max)return!!n.SetMaxOnOverflow&&{refreshFromBuffer:!0,buffer:c(n.max.toString().replace(".",n.radixPoint).split(""),n.digits,n).reverse()}}return a},onUnMask:function(e,t,i){if(""===t&&!0===i.nullable)return t;var a=e.replace(i.prefix,"");return a=(a=a.replace(i.suffix,"")).replace(new RegExp((0,r.default)(i.groupSeparator),"g"),""),""!==i.placeholder.charAt(0)&&(a=a.replace(new RegExp(i.placeholder.charAt(0),"g"),"0")),i.unmaskAsNumber?(""!==i.radixPoint&&-1!==a.indexOf(i.radixPoint)&&(a=a.replace(r.default.call(this,i.radixPoint),".")),a=(a=a.replace(new RegExp("^"+(0,r.default)(i.negationSymbol.front)),"-")).replace(new RegExp((0,r.default)(i.negationSymbol.back)+"$"),""),Number(a)):a},isComplete:function(e,t){var i=(t.numericInput?e.slice().reverse():e).join("");return i=(i=(i=(i=(i=i.replace(new RegExp("^"+(0,r.default)(t.negationSymbol.front)),"-")).replace(new RegExp((0,r.default)(t.negationSymbol.back)+"$"),"")).replace(t.prefix,"")).replace(t.suffix,"")).replace(new RegExp((0,r.default)(t.groupSeparator)+"([0-9]{3})","g"),"$1"),","===t.radixPoint&&(i=i.replace((0,r.default)(t.radixPoint),".")),isFinite(i)},onBeforeMask:function(e,t){var i=t.radixPoint||",";isFinite(t.digits)&&(t.digits=parseInt(t.digits)),"number"!=typeof e&&"number"!==t.inputType||""===i||(e=e.toString().replace(".",i));var a="-"===e.charAt(0)||e.charAt(0)===t.negationSymbol.front,n=e.split(i),o=n[0].replace(/[^\-0-9]/g,""),s=n.length>1?n[1].replace(/[^0-9]/g,""):"",l=n.length>1;e=o+(""!==s?i+s:s);var u=0;if(""!==i&&(u=t.digitsOptional?t.digits<s.length?t.digits:s.length:t.digits,""!==s||!t.digitsOptional)){var f=Math.pow(10,u||1);e=e.replace((0,r.default)(i),"."),isNaN(parseFloat(e))||(e=(t.roundingFN(parseFloat(e)*f)/f).toFixed(u)),e=e.toString().replace(".",i)}if(0===t.digits&&-1!==e.indexOf(i)&&(e=e.substring(0,e.indexOf(i))),null!==t.min||null!==t.max){var d=e.toString().replace(i,".");null!==t.min&&d<t.min?e=t.min.toString().replace(".",i):null!==t.max&&d>t.max&&(e=t.max.toString().replace(".",i))}return a&&"-"!==e.charAt(0)&&(e="-"+e),c(e.toString().split(""),u,t,l).join("")},onBeforeWrite:function(e,t,i,a){function n(e,t){if(!1!==a.__financeInput||t){var i=e.indexOf(a.radixPoint);-1!==i&&e.splice(i,1)}if(""!==a.groupSeparator)for(;-1!==(i=e.indexOf(a.groupSeparator));)e.splice(i,1);return e}var o,s;if(a.stripLeadingZeroes&&(s=function(e,t){var i=new RegExp("(^"+(""!==t.negationSymbol.front?(0,r.default)(t.negationSymbol.front)+"?":"")+(0,r.default)(t.prefix)+")(.*)("+(0,r.default)(t.suffix)+(""!=t.negationSymbol.back?(0,r.default)(t.negationSymbol.back)+"?":"")+"$)").exec(e.slice().reverse().join("")),a=i?i[2]:"",n=!1;return a&&(a=a.split(t.radixPoint.charAt(0))[0],n=new RegExp("^[0"+t.groupSeparator+"]*").exec(a)),!(!n||!(n[0].length>1||n[0].length>0&&n[0].length<a.length))&&n}(t,a)))for(var u=t.join("").lastIndexOf(s[0].split("").reverse().join(""))-(s[0]==s.input?0:1),f=s[0]==s.input?1:0,d=s[0].length-f;d>0;d--)delete this.maskset.validPositions[u+d],delete t[u+d];if(e)switch(e.type){case"blur":case"checkval":if(null!==a.min){var p=a.onUnMask(t.slice().reverse().join(""),void 0,l.extend({},a,{unmaskAsNumber:!0}));if(null!==a.min&&p<a.min)return{refreshFromBuffer:!0,buffer:c(a.min.toString().replace(".",a.radixPoint).split(""),a.digits,a).reverse()}}if(t[t.length-1]===a.negationSymbol.front){var h=new RegExp("(^"+(""!=a.negationSymbol.front?(0,r.default)(a.negationSymbol.front)+"?":"")+(0,r.default)(a.prefix)+")(.*)("+(0,r.default)(a.suffix)+(""!=a.negationSymbol.back?(0,r.default)(a.negationSymbol.back)+"?":"")+"$)").exec(n(t.slice(),!0).reverse().join(""));0==(h?h[2]:"")&&(o={refreshFromBuffer:!0,buffer:[0]})}else if(""!==a.radixPoint){t.indexOf(a.radixPoint)===a.suffix.length&&(o&&o.buffer?o.buffer.splice(0,1+a.suffix.length):(t.splice(0,1+a.suffix.length),o={refreshFromBuffer:!0,buffer:n(t)}))}if(a.enforceDigitsOnBlur){var m=(o=o||{})&&o.buffer||t.slice().reverse();o.refreshFromBuffer=!0,o.buffer=c(m,a.digits,a,!0).reverse()}}return o},onKeyDown:function(e,t,i,a){var r,o,s=l(this),u=String.fromCharCode(e.keyCode).toLowerCase();if((o=a.shortcuts&&a.shortcuts[u])&&o.length>1)return this.inputmask.__valueSet.call(this,parseFloat(this.inputmask.unmaskedvalue())*parseInt(o)),s.trigger("setvalue"),!1;if(e.ctrlKey)switch(e.keyCode){case n.default.UP:return this.inputmask.__valueSet.call(this,parseFloat(this.inputmask.unmaskedvalue())+parseInt(a.step)),s.trigger("setvalue"),!1;case n.default.DOWN:return this.inputmask.__valueSet.call(this,parseFloat(this.inputmask.unmaskedvalue())-parseInt(a.step)),s.trigger("setvalue"),!1}if(!e.shiftKey&&(e.keyCode===n.default.DELETE||e.keyCode===n.default.BACKSPACE||e.keyCode===n.default.BACKSPACE_SAFARI)&&i.begin!==t.length){if(t[e.keyCode===n.default.DELETE?i.begin-1:i.end]===a.negationSymbol.front)return r=t.slice().reverse(),""!==a.negationSymbol.front&&r.shift(),""!==a.negationSymbol.back&&r.pop(),s.trigger("setvalue",[r.join(""),i.begin]),!1;if(!0===a._radixDance){var f=t.indexOf(a.radixPoint);if(a.digitsOptional){if(0===f)return(r=t.slice().reverse()).pop(),s.trigger("setvalue",[r.join(""),i.begin>=r.length?r.length:i.begin]),!1}else if(-1!==f&&(i.begin<f||i.end<f||e.keyCode===n.default.DELETE&&i.begin===f))return i.begin!==i.end||e.keyCode!==n.default.BACKSPACE&&e.keyCode!==n.default.BACKSPACE_SAFARI||i.begin++,(r=t.slice().reverse()).splice(r.length-i.begin,i.begin-i.end+1),r=c(r,a.digits,a).join(""),s.trigger("setvalue",[r,i.begin>=r.length?f+1:i.begin]),!1}}}},currency:{prefix:"",groupSeparator:",",alias:"numeric",digits:2,digitsOptional:!1},decimal:{alias:"numeric"},integer:{alias:"numeric",inputmode:"numeric",digits:0},percentage:{alias:"numeric",min:0,max:100,suffix:" %",digits:0,allowMinus:!1},indianns:{alias:"numeric",_mask:function(e){return"("+e.groupSeparator+"99){*|1}("+e.groupSeparator+"999){1|1}"},groupSeparator:",",radixPoint:".",placeholder:"0",digits:2,digitsOptional:!1}})},9380:function(e,t,i){var a;Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=((a=i(8741))&&a.__esModule?a:{default:a}).default?window:{};t.default=n},7760:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.HandleNativePlaceholder=function(e,t){var i=e?e.inputmask:this;if(l.ie){if(e.inputmask._valueGet()!==t&&(e.placeholder!==t||""===e.placeholder)){var a=o.getBuffer.call(i).slice(),n=e.inputmask._valueGet();if(n!==t){var r=o.getLastValidPosition.call(i);-1===r&&n===o.getBufferTemplate.call(i).join("")?a=[]:-1!==r&&f.call(i,a),p(e,a)}}}else e.placeholder!==t&&(e.placeholder=t,""===e.placeholder&&e.removeAttribute("placeholder"))},t.applyInputValue=c,t.checkVal=d,t.clearOptionalTail=f,t.unmaskedvalue=function(e){var t=e?e.inputmask:this,i=t.opts,a=t.maskset;if(e){if(void 0===e.inputmask)return e.value;e.inputmask&&e.inputmask.refreshValue&&c(e,e.inputmask._valueGet(!0))}var n=[],r=a.validPositions;for(var s in r)r[s]&&r[s].match&&(1!=r[s].match.static||Array.isArray(a.metadata)&&!0!==r[s].generatedInput)&&n.push(r[s].input);var l=0===n.length?"":(t.isRTL?n.reverse():n).join("");if("function"==typeof i.onUnMask){var u=(t.isRTL?o.getBuffer.call(t).slice().reverse():o.getBuffer.call(t)).join("");l=i.onUnMask.call(t,u,l,i)}return l},t.writeBuffer=p;var a,n=(a=i(5581))&&a.__esModule?a:{default:a},r=i(4713),o=i(8711),s=i(7215),l=i(9845),u=i(6030);function c(e,t){var i=e?e.inputmask:this,a=i.opts;e.inputmask.refreshValue=!1,"function"==typeof a.onBeforeMask&&(t=a.onBeforeMask.call(i,t,a)||t),d(e,!0,!1,t=t.toString().split("")),i.undoValue=i._valueGet(!0),(a.clearMaskOnLostFocus||a.clearIncomplete)&&e.inputmask._valueGet()===o.getBufferTemplate.call(i).join("")&&-1===o.getLastValidPosition.call(i)&&e.inputmask._valueSet("")}function f(e){e.length=0;for(var t,i=r.getMaskTemplate.call(this,!0,0,!0,void 0,!0);void 0!==(t=i.shift());)e.push(t);return e}function d(e,t,i,a,n){var l=e?e.inputmask:this,c=l.maskset,f=l.opts,d=l.dependencyLib,h=a.slice(),m="",v=-1,g=void 0,k=f.skipOptionalPartCharacter;f.skipOptionalPartCharacter="",o.resetMaskSet.call(l),c.tests={},v=f.radixPoint?o.determineNewCaretPosition.call(l,{begin:0,end:0},!1,!1===f.__financeInput?"radixFocus":void 0).begin:0,c.p=v,l.caretPos={begin:v};var y=[],b=l.caretPos;if(h.forEach((function(e,t){if(void 0!==e){var a=new d.Event("_checkval");a.keyCode=e.toString().charCodeAt(0),m+=e;var n=o.getLastValidPosition.call(l,void 0,!0);!function(e,t){for(var i=r.getMaskTemplate.call(l,!0,0).slice(e,o.seekNext.call(l,e,!1,!1)).join("").replace(/'/g,""),a=i.indexOf(t);a>0&&" "===i[a-1];)a--;var n=0===a&&!o.isMask.call(l,e)&&(r.getTest.call(l,e).match.nativeDef===t.charAt(0)||!0===r.getTest.call(l,e).match.static&&r.getTest.call(l,e).match.nativeDef==="'"+t.charAt(0)||" "===r.getTest.call(l,e).match.nativeDef&&(r.getTest.call(l,e+1).match.nativeDef===t.charAt(0)||!0===r.getTest.call(l,e+1).match.static&&r.getTest.call(l,e+1).match.nativeDef==="'"+t.charAt(0)));if(!n&&a>0&&!o.isMask.call(l,e,!1,!0)){var s=o.seekNext.call(l,e);l.caretPos.begin<s&&(l.caretPos={begin:s})}return n}(v,m)?(g=u.EventHandlers.keypressEvent.call(l,a,!0,!1,i,l.caretPos.begin))&&(v=l.caretPos.begin+1,m=""):g=u.EventHandlers.keypressEvent.call(l,a,!0,!1,i,n+1),g?(void 0!==g.pos&&c.validPositions[g.pos]&&!0===c.validPositions[g.pos].match.static&&void 0===c.validPositions[g.pos].alternation&&(y.push(g.pos),l.isRTL||(g.forwardPosition=g.pos+1)),p.call(l,void 0,o.getBuffer.call(l),g.forwardPosition,a,!1),l.caretPos={begin:g.forwardPosition,end:g.forwardPosition},b=l.caretPos):void 0===c.validPositions[t]&&h[t]===r.getPlaceholder.call(l,t)&&o.isMask.call(l,t,!0)?l.caretPos.begin++:l.caretPos=b}})),y.length>0){var x,P,E=o.seekNext.call(l,-1,void 0,!1);if(!s.isComplete.call(l,o.getBuffer.call(l))&&y.length<=E||s.isComplete.call(l,o.getBuffer.call(l))&&y.length>0&&y.length!==E&&0===y[0])for(var S=E;void 0!==(x=y.shift());){var w=new d.Event("_checkval");if((P=c.validPositions[x]).generatedInput=!0,w.keyCode=P.input.charCodeAt(0),(g=u.EventHandlers.keypressEvent.call(l,w,!0,!1,i,S))&&void 0!==g.pos&&g.pos!==x&&c.validPositions[g.pos]&&!0===c.validPositions[g.pos].match.static)y.push(g.pos);else if(!g)break;S++}}t&&p.call(l,e,o.getBuffer.call(l),g?g.forwardPosition:l.caretPos.begin,n||new d.Event("checkval"),n&&("input"===n.type&&l.undoValue!==o.getBuffer.call(l).join("")||"paste"===n.type)),f.skipOptionalPartCharacter=k}function p(e,t,i,a,r){var l=e?e.inputmask:this,u=l.opts,c=l.dependencyLib;if(a&&"function"==typeof u.onBeforeWrite){var f=u.onBeforeWrite.call(l,a,t,i,u);if(f){if(f.refreshFromBuffer){var d=f.refreshFromBuffer;s.refreshFromBuffer.call(l,!0===d?d:d.start,d.end,f.buffer||t),t=o.getBuffer.call(l,!0)}void 0!==i&&(i=void 0!==f.caret?f.caret:i)}}if(void 0!==e&&(e.inputmask._valueSet(t.join("")),void 0===i||void 0!==a&&"blur"===a.type||o.caret.call(l,e,i,void 0,void 0,void 0!==a&&"keydown"===a.type&&(a.keyCode===n.default.DELETE||a.keyCode===n.default.BACKSPACE)),!0===r)){var p=c(e),h=e.inputmask._valueGet();e.inputmask.skipInputEvent=!0,p.trigger("input"),setTimeout((function(){h===o.getBufferTemplate.call(l).join("")?p.trigger("cleared"):!0===s.isComplete.call(l,t)&&p.trigger("complete")}),0)}}},2394:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,i(7149),i(3194);var a=i(157),n=v(i(3287)),r=v(i(9380)),o=i(2391),s=i(4713),l=i(8711),u=i(7215),c=i(7760),f=i(9716),d=v(i(7392)),p=v(i(3976)),h=v(i(8741));function m(e){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},m(e)}function v(e){return e&&e.__esModule?e:{default:e}}var g=r.default.document,k="_inputmask_opts";function y(e,t,i){if(h.default){if(!(this instanceof y))return new y(e,t,i);this.dependencyLib=n.default,this.el=void 0,this.events={},this.maskset=void 0,!0!==i&&("[object Object]"===Object.prototype.toString.call(e)?t=e:(t=t||{},e&&(t.alias=e)),this.opts=n.default.extend(!0,{},this.defaults,t),this.noMasksCache=t&&void 0!==t.definitions,this.userOptions=t||{},b(this.opts.alias,t,this.opts)),this.refreshValue=!1,this.undoValue=void 0,this.$el=void 0,this.skipKeyPressEvent=!1,this.skipInputEvent=!1,this.validationEvent=!1,this.ignorable=!1,this.maxLength,this.mouseEnter=!1,this.originalPlaceholder=void 0,this.isComposing=!1}}function b(e,t,i){var a=y.prototype.aliases[e];return a?(a.alias&&b(a.alias,void 0,i),n.default.extend(!0,i,a),n.default.extend(!0,i,t),!0):(null===i.mask&&(i.mask=e),!1)}y.prototype={dataAttribute:"data-inputmask",defaults:p.default,definitions:d.default,aliases:{},masksCache:{},get isRTL(){return this.opts.isRTL||this.opts.numericInput},mask:function(e){var t=this;return"string"==typeof e&&(e=g.getElementById(e)||g.querySelectorAll(e)),(e=e.nodeName?[e]:Array.isArray(e)?e:Array.from(e)).forEach((function(e,i){var s=n.default.extend(!0,{},t.opts);if(function(e,t,i,a){function o(t,n){var o=""===a?t:a+"-"+t;null!==(n=void 0!==n?n:e.getAttribute(o))&&("string"==typeof n&&(0===t.indexOf("on")?n=r.default[n]:"false"===n?n=!1:"true"===n&&(n=!0)),i[t]=n)}if(!0===t.importDataAttributes){var s,l,u,c,f=e.getAttribute(a);if(f&&""!==f&&(f=f.replace(/'/g,'"'),l=JSON.parse("{"+f+"}")),l)for(c in u=void 0,l)if("alias"===c.toLowerCase()){u=l[c];break}for(s in o("alias",u),i.alias&&b(i.alias,i,t),t){if(l)for(c in u=void 0,l)if(c.toLowerCase()===s.toLowerCase()){u=l[c];break}o(s,u)}}n.default.extend(!0,t,i),("rtl"===e.dir||t.rightAlign)&&(e.style.textAlign="right");("rtl"===e.dir||t.numericInput)&&(e.dir="ltr",e.removeAttribute("dir"),t.isRTL=!0);return Object.keys(i).length}(e,s,n.default.extend(!0,{},t.userOptions),t.dataAttribute)){var l=(0,o.generateMaskSet)(s,t.noMasksCache);void 0!==l&&(void 0!==e.inputmask&&(e.inputmask.opts.autoUnmask=!0,e.inputmask.remove()),e.inputmask=new y(void 0,void 0,!0),e.inputmask.opts=s,e.inputmask.noMasksCache=t.noMasksCache,e.inputmask.userOptions=n.default.extend(!0,{},t.userOptions),e.inputmask.el=e,e.inputmask.$el=(0,n.default)(e),e.inputmask.maskset=l,n.default.data(e,k,t.userOptions),a.mask.call(e.inputmask))}})),e&&e[0]&&e[0].inputmask||this},option:function(e,t){return"string"==typeof e?this.opts[e]:"object"===m(e)?(n.default.extend(this.userOptions,e),this.el&&!0!==t&&this.mask(this.el),this):void 0},unmaskedvalue:function(e){if(this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache),void 0===this.el||void 0!==e){var t=("function"==typeof this.opts.onBeforeMask&&this.opts.onBeforeMask.call(this,e,this.opts)||e).split("");c.checkVal.call(this,void 0,!1,!1,t),"function"==typeof this.opts.onBeforeWrite&&this.opts.onBeforeWrite.call(this,void 0,l.getBuffer.call(this),0,this.opts)}return c.unmaskedvalue.call(this,this.el)},remove:function(){if(this.el){n.default.data(this.el,k,null);var e=this.opts.autoUnmask?(0,c.unmaskedvalue)(this.el):this._valueGet(this.opts.autoUnmask);e!==l.getBufferTemplate.call(this).join("")?this._valueSet(e,this.opts.autoUnmask):this._valueSet(""),f.EventRuler.off(this.el),Object.getOwnPropertyDescriptor&&Object.getPrototypeOf?Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this.el),"value")&&this.__valueGet&&Object.defineProperty(this.el,"value",{get:this.__valueGet,set:this.__valueSet,configurable:!0}):g.__lookupGetter__&&this.el.__lookupGetter__("value")&&this.__valueGet&&(this.el.__defineGetter__("value",this.__valueGet),this.el.__defineSetter__("value",this.__valueSet)),this.el.inputmask=void 0}return this.el},getemptymask:function(){return this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache),l.getBufferTemplate.call(this).join("")},hasMaskedValue:function(){return!this.opts.autoUnmask},isComplete:function(){return this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache),u.isComplete.call(this,l.getBuffer.call(this))},getmetadata:function(){if(this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache),Array.isArray(this.maskset.metadata)){var e=s.getMaskTemplate.call(this,!0,0,!1).join("");return this.maskset.metadata.forEach((function(t){return t.mask!==e||(e=t,!1)})),e}return this.maskset.metadata},isValid:function(e){if(this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache),e){var t=("function"==typeof this.opts.onBeforeMask&&this.opts.onBeforeMask.call(this,e,this.opts)||e).split("");c.checkVal.call(this,void 0,!0,!1,t)}else e=this.isRTL?l.getBuffer.call(this).slice().reverse().join(""):l.getBuffer.call(this).join("");for(var i=l.getBuffer.call(this),a=l.determineLastRequiredPosition.call(this),n=i.length-1;n>a&&!l.isMask.call(this,n);n--);return i.splice(a,n+1-a),u.isComplete.call(this,i)&&e===(this.isRTL?l.getBuffer.call(this).slice().reverse().join(""):l.getBuffer.call(this).join(""))},format:function(e,t){this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache);var i=("function"==typeof this.opts.onBeforeMask&&this.opts.onBeforeMask.call(this,e,this.opts)||e).split("");c.checkVal.call(this,void 0,!0,!1,i);var a=this.isRTL?l.getBuffer.call(this).slice().reverse().join(""):l.getBuffer.call(this).join("");return t?{value:a,metadata:this.getmetadata()}:a},setValue:function(e){this.el&&(0,n.default)(this.el).trigger("setvalue",[e])},analyseMask:o.analyseMask},y.extendDefaults=function(e){n.default.extend(!0,y.prototype.defaults,e)},y.extendDefinitions=function(e){n.default.extend(!0,y.prototype.definitions,e)},y.extendAliases=function(e){n.default.extend(!0,y.prototype.aliases,e)},y.format=function(e,t,i){return y(t).format(e,i)},y.unmask=function(e,t){return y(t).unmaskedvalue(e)},y.isValid=function(e,t){return y(t).isValid(e)},y.remove=function(e){"string"==typeof e&&(e=g.getElementById(e)||g.querySelectorAll(e)),(e=e.nodeName?[e]:e).forEach((function(e){e.inputmask&&e.inputmask.remove()}))},y.setValue=function(e,t){"string"==typeof e&&(e=g.getElementById(e)||g.querySelectorAll(e)),(e=e.nodeName?[e]:e).forEach((function(e){e.inputmask?e.inputmask.setValue(t):(0,n.default)(e).trigger("setvalue",[t])}))},y.dependencyLib=n.default,r.default.Inputmask=y;var x=y;t.default=x},5296:function(e,t,i){function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}var n=h(i(9380)),r=h(i(2394)),o=h(i(8741));function s(e,t){for(var i=0;i<t.length;i++){var a=t[i];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}function l(e,t){if(t&&("object"===a(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function u(e){var t="function"==typeof Map?new Map:void 0;return u=function(e){if(null===e||(i=e,-1===Function.toString.call(i).indexOf("[native code]")))return e;var i;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,a)}function a(){return c(e,arguments,p(this).constructor)}return a.prototype=Object.create(e.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),d(a,e)},u(e)}function c(e,t,i){return c=f()?Reflect.construct:function(e,t,i){var a=[null];a.push.apply(a,t);var n=new(Function.bind.apply(e,a));return i&&d(n,i.prototype),n},c.apply(null,arguments)}function f(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function d(e,t){return d=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},d(e,t)}function p(e){return p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},p(e)}function h(e){return e&&e.__esModule?e:{default:e}}var m=n.default.document;if(o.default&&m&&m.head&&m.head.attachShadow&&n.default.customElements&&void 0===n.default.customElements.get("input-mask")){var v=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");Object.defineProperty(e,"prototype",{value:Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),writable:!1}),t&&d(e,t)}(c,e);var t,i,a,n,o,u=(t=c,i=f(),function(){var e,a=p(t);if(i){var n=p(this).constructor;e=Reflect.construct(a,arguments,n)}else e=a.apply(this,arguments);return l(this,e)});function c(){var e;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,c);var t=(e=u.call(this)).getAttributeNames(),i=e.attachShadow({mode:"closed"}),a=m.createElement("input");for(var n in a.type="text",i.appendChild(a),t)Object.prototype.hasOwnProperty.call(t,n)&&a.setAttribute(t[n],e.getAttribute(t[n]));var o=new r.default;return o.dataAttribute="",o.mask(a),a.inputmask.shadowRoot=i,e}return a=c,n&&s(a.prototype,n),o&&s(a,o),Object.defineProperty(a,"prototype",{writable:!1}),a}(u(HTMLElement));n.default.customElements.define("input-mask",v)}},443:function(e,t,i){var a=o(i(2047)),n=o(i(2394));function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function o(e){return e&&e.__esModule?e:{default:e}}void 0===a.default.fn.inputmask&&(a.default.fn.inputmask=function(e,t){var i,o=this[0];if(void 0===t&&(t={}),"string"==typeof e)switch(e){case"unmaskedvalue":return o&&o.inputmask?o.inputmask.unmaskedvalue():(0,a.default)(o).val();case"remove":return this.each((function(){this.inputmask&&this.inputmask.remove()}));case"getemptymask":return o&&o.inputmask?o.inputmask.getemptymask():"";case"hasMaskedValue":return!(!o||!o.inputmask)&&o.inputmask.hasMaskedValue();case"isComplete":return!o||!o.inputmask||o.inputmask.isComplete();case"getmetadata":return o&&o.inputmask?o.inputmask.getmetadata():void 0;case"setvalue":n.default.setValue(o,t);break;case"option":if("string"!=typeof t)return this.each((function(){if(void 0!==this.inputmask)return this.inputmask.option(t)}));if(o&&void 0!==o.inputmask)return o.inputmask.option(t);break;default:return t.alias=e,i=new n.default(t),this.each((function(){i.mask(this)}))}else{if(Array.isArray(e))return t.alias=e,i=new n.default(t),this.each((function(){i.mask(this)}));if("object"==r(e))return i=new n.default(e),void 0===e.mask&&void 0===e.alias?this.each((function(){if(void 0!==this.inputmask)return this.inputmask.option(e);i.mask(this)})):this.each((function(){i.mask(this)}));if(void 0===e)return this.each((function(){(i=new n.default(t)).mask(this)}))}})},2391:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.analyseMask=function(e,t,i){var a,o,s,l,u,c,f=/(?:[?*+]|\{[0-9+*]+(?:,[0-9+*]*)?(?:\|[0-9+*]*)?\})|[^.?*+^${[]()|\\]+|./g,d=/\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g,p=!1,h=new n.default,m=[],v=[],g=!1;function k(e,a,n){n=void 0!==n?n:e.matches.length;var o=e.matches[n-1];if(t)0===a.indexOf("[")||p&&/\\d|\\s|\\w/i.test(a)||"."===a?e.matches.splice(n++,0,{fn:new RegExp(a,i.casing?"i":""),static:!1,optionality:!1,newBlockMarker:void 0===o?"master":o.def!==a,casing:null,def:a,placeholder:void 0,nativeDef:a}):(p&&(a=a[a.length-1]),a.split("").forEach((function(t,a){o=e.matches[n-1],e.matches.splice(n++,0,{fn:/[a-z]/i.test(i.staticDefinitionSymbol||t)?new RegExp("["+(i.staticDefinitionSymbol||t)+"]",i.casing?"i":""):null,static:!0,optionality:!1,newBlockMarker:void 0===o?"master":o.def!==t&&!0!==o.static,casing:null,def:i.staticDefinitionSymbol||t,placeholder:void 0!==i.staticDefinitionSymbol?t:void 0,nativeDef:(p?"'":"")+t})}))),p=!1;else{var s=i.definitions&&i.definitions[a]||i.usePrototypeDefinitions&&r.default.prototype.definitions[a];s&&!p?e.matches.splice(n++,0,{fn:s.validator?"string"==typeof s.validator?new RegExp(s.validator,i.casing?"i":""):new function(){this.test=s.validator}:new RegExp("."),static:s.static||!1,optionality:s.optional||!1,newBlockMarker:void 0===o||s.optional?"master":o.def!==(s.definitionSymbol||a),casing:s.casing,def:s.definitionSymbol||a,placeholder:s.placeholder,nativeDef:a,generated:s.generated}):(e.matches.splice(n++,0,{fn:/[a-z]/i.test(i.staticDefinitionSymbol||a)?new RegExp("["+(i.staticDefinitionSymbol||a)+"]",i.casing?"i":""):null,static:!0,optionality:!1,newBlockMarker:void 0===o?"master":o.def!==a&&!0!==o.static,casing:null,def:i.staticDefinitionSymbol||a,placeholder:void 0!==i.staticDefinitionSymbol?a:void 0,nativeDef:(p?"'":"")+a}),p=!1)}}function y(){if(m.length>0){if(k(l=m[m.length-1],o),l.isAlternator){u=m.pop();for(var e=0;e<u.matches.length;e++)u.matches[e].isGroup&&(u.matches[e].isGroup=!1);m.length>0?(l=m[m.length-1]).matches.push(u):h.matches.push(u)}}else k(h,o)}function b(e){var t=new n.default(!0);return t.openGroup=!1,t.matches=e,t}function x(){if((s=m.pop()).openGroup=!1,void 0!==s)if(m.length>0){if((l=m[m.length-1]).matches.push(s),l.isAlternator){for(var e=(u=m.pop()).matches[0].matches?u.matches[0].matches.length:1,t=0;t<u.matches.length;t++)u.matches[t].isGroup=!1,u.matches[t].alternatorGroup=!1,null===i.keepStatic&&e<(u.matches[t].matches?u.matches[t].matches.length:1)&&(i.keepStatic=!0),e=u.matches[t].matches?u.matches[t].matches.length:1;m.length>0?(l=m[m.length-1]).matches.push(u):h.matches.push(u)}}else h.matches.push(s);else y()}function P(e){var t=e.pop();return t.isQuantifier&&(t=b([e.pop(),t])),t}t&&(i.optionalmarker[0]=void 0,i.optionalmarker[1]=void 0);for(;a=t?d.exec(e):f.exec(e);){if(o=a[0],t){switch(o.charAt(0)){case"?":o="{0,1}";break;case"+":case"*":o="{"+o+"}";break;case"|":if(0===m.length){var E=b(h.matches);E.openGroup=!0,m.push(E),h.matches=[],g=!0}}if("\\d"===o)o="[0-9]"}if(p)y();else switch(o.charAt(0)){case"$":case"^":t||y();break;case i.escapeChar:p=!0,t&&y();break;case i.optionalmarker[1]:case i.groupmarker[1]:x();break;case i.optionalmarker[0]:m.push(new n.default(!1,!0));break;case i.groupmarker[0]:m.push(new n.default(!0));break;case i.quantifiermarker[0]:var S=new n.default(!1,!1,!0),w=(o=o.replace(/[{}?]/g,"")).split("|"),_=w[0].split(","),M=isNaN(_[0])?_[0]:parseInt(_[0]),O=1===_.length?M:isNaN(_[1])?_[1]:parseInt(_[1]),T=isNaN(w[1])?w[1]:parseInt(w[1]);"*"!==M&&"+"!==M||(M="*"===O?0:1),S.quantifier={min:M,max:O,jit:T};var A=m.length>0?m[m.length-1].matches:h.matches;if((a=A.pop()).isAlternator){A.push(a),A=a.matches;var C=new n.default(!0),D=A.pop();A.push(C),A=C.matches,a=D}a.isGroup||(a=b([a])),A.push(a),A.push(S);break;case i.alternatormarker:if(m.length>0){var j=(l=m[m.length-1]).matches[l.matches.length-1];c=l.openGroup&&(void 0===j.matches||!1===j.isGroup&&!1===j.isAlternator)?m.pop():P(l.matches)}else c=P(h.matches);if(c.isAlternator)m.push(c);else if(c.alternatorGroup?(u=m.pop(),c.alternatorGroup=!1):u=new n.default(!1,!1,!1,!0),u.matches.push(c),m.push(u),c.openGroup){c.openGroup=!1;var B=new n.default(!0);B.alternatorGroup=!0,m.push(B)}break;default:y()}}g&&x();for(;m.length>0;)s=m.pop(),h.matches.push(s);h.matches.length>0&&(!function e(a){a&&a.matches&&a.matches.forEach((function(n,r){var o=a.matches[r+1];(void 0===o||void 0===o.matches||!1===o.isQuantifier)&&n&&n.isGroup&&(n.isGroup=!1,t||(k(n,i.groupmarker[0],0),!0!==n.openGroup&&k(n,i.groupmarker[1]))),e(n)}))}(h),v.push(h));(i.numericInput||i.isRTL)&&function e(t){for(var a in t.matches=t.matches.reverse(),t.matches)if(Object.prototype.hasOwnProperty.call(t.matches,a)){var n=parseInt(a);if(t.matches[a].isQuantifier&&t.matches[n+1]&&t.matches[n+1].isGroup){var r=t.matches[a];t.matches.splice(a,1),t.matches.splice(n+1,0,r)}void 0!==t.matches[a].matches?t.matches[a]=e(t.matches[a]):t.matches[a]=((o=t.matches[a])===i.optionalmarker[0]?o=i.optionalmarker[1]:o===i.optionalmarker[1]?o=i.optionalmarker[0]:o===i.groupmarker[0]?o=i.groupmarker[1]:o===i.groupmarker[1]&&(o=i.groupmarker[0]),o)}var o;return t}(v[0]);return v},t.generateMaskSet=function(e,t){var i;function n(e,i,n){var o,s,l=!1;if(null!==e&&""!==e||((l=null!==n.regex)?e=(e=n.regex).replace(/^(\^)(.*)(\$)$/,"$2"):(l=!0,e=".*")),1===e.length&&!1===n.greedy&&0!==n.repeat&&(n.placeholder=""),n.repeat>0||"*"===n.repeat||"+"===n.repeat){var u="*"===n.repeat?0:"+"===n.repeat?1:n.repeat;e=n.groupmarker[0]+e+n.groupmarker[1]+n.quantifiermarker[0]+u+","+n.repeat+n.quantifiermarker[1]}return s=l?"regex_"+n.regex:n.numericInput?e.split("").reverse().join(""):e,null!==n.keepStatic&&(s="ks_"+n.keepStatic+s),void 0===r.default.prototype.masksCache[s]||!0===t?(o={mask:e,maskToken:r.default.prototype.analyseMask(e,l,n),validPositions:{},_buffer:void 0,buffer:void 0,tests:{},excludes:{},metadata:i,maskLength:void 0,jitOffset:{}},!0!==t&&(r.default.prototype.masksCache[s]=o,o=a.default.extend(!0,{},r.default.prototype.masksCache[s]))):o=a.default.extend(!0,{},r.default.prototype.masksCache[s]),o}"function"==typeof e.mask&&(e.mask=e.mask(e));if(Array.isArray(e.mask)){if(e.mask.length>1){null===e.keepStatic&&(e.keepStatic=!0);var o=e.groupmarker[0];return(e.isRTL?e.mask.reverse():e.mask).forEach((function(t){o.length>1&&(o+=e.alternatormarker),void 0!==t.mask&&"function"!=typeof t.mask?o+=t.mask:o+=t})),n(o+=e.groupmarker[1],e.mask,e)}e.mask=e.mask.pop()}i=e.mask&&void 0!==e.mask.mask&&"function"!=typeof e.mask.mask?n(e.mask.mask,e.mask,e):n(e.mask,e.mask,e);null===e.keepStatic&&(e.keepStatic=!1);return i};var a=o(i(3287)),n=o(i(9695)),r=o(i(2394));function o(e){return e&&e.__esModule?e:{default:e}}},157:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.mask=function(){var e=this,t=this.opts,i=this.el,a=this.dependencyLib;s.EventRuler.off(i);var f=function(t,i){"textarea"!==t.tagName.toLowerCase()&&i.ignorables.push(n.default.ENTER);var l=t.getAttribute("type"),u="input"===t.tagName.toLowerCase()&&i.supportsInputType.includes(l)||t.isContentEditable||"textarea"===t.tagName.toLowerCase();if(!u)if("input"===t.tagName.toLowerCase()){var c=document.createElement("input");c.setAttribute("type",l),u="text"===c.type,c=null}else u="partial";return!1!==u?function(t){var n,l;function u(){return this.inputmask?this.inputmask.opts.autoUnmask?this.inputmask.unmaskedvalue():-1!==r.getLastValidPosition.call(e)||!0!==i.nullable?(this.inputmask.shadowRoot||this.ownerDocument).activeElement===this&&i.clearMaskOnLostFocus?(e.isRTL?o.clearOptionalTail.call(e,r.getBuffer.call(e).slice()).reverse():o.clearOptionalTail.call(e,r.getBuffer.call(e).slice())).join(""):n.call(this):"":n.call(this)}function c(e){l.call(this,e),this.inputmask&&(0,o.applyInputValue)(this,e)}if(!t.inputmask.__valueGet){if(!0!==i.noValuePatching){if(Object.getOwnPropertyDescriptor){var f=Object.getPrototypeOf?Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),"value"):void 0;f&&f.get&&f.set?(n=f.get,l=f.set,Object.defineProperty(t,"value",{get:u,set:c,configurable:!0})):"input"!==t.tagName.toLowerCase()&&(n=function(){return this.textContent},l=function(e){this.textContent=e},Object.defineProperty(t,"value",{get:u,set:c,configurable:!0}))}else document.__lookupGetter__&&t.__lookupGetter__("value")&&(n=t.__lookupGetter__("value"),l=t.__lookupSetter__("value"),t.__defineGetter__("value",u),t.__defineSetter__("value",c));t.inputmask.__valueGet=n,t.inputmask.__valueSet=l}t.inputmask._valueGet=function(t){return e.isRTL&&!0!==t?n.call(this.el).split("").reverse().join(""):n.call(this.el)},t.inputmask._valueSet=function(t,i){l.call(this.el,null==t?"":!0!==i&&e.isRTL?t.split("").reverse().join(""):t)},void 0===n&&(n=function(){return this.value},l=function(e){this.value=e},function(t){if(a.valHooks&&(void 0===a.valHooks[t]||!0!==a.valHooks[t].inputmaskpatch)){var n=a.valHooks[t]&&a.valHooks[t].get?a.valHooks[t].get:function(e){return e.value},s=a.valHooks[t]&&a.valHooks[t].set?a.valHooks[t].set:function(e,t){return e.value=t,e};a.valHooks[t]={get:function(t){if(t.inputmask){if(t.inputmask.opts.autoUnmask)return t.inputmask.unmaskedvalue();var a=n(t);return-1!==r.getLastValidPosition.call(e,void 0,void 0,t.inputmask.maskset.validPositions)||!0!==i.nullable?a:""}return n(t)},set:function(e,t){var i=s(e,t);return e.inputmask&&(0,o.applyInputValue)(e,t),i},inputmaskpatch:!0}}}(t.type),function(t){s.EventRuler.on(t,"mouseenter",(function(){var t=this.inputmask._valueGet(!0);t!==(e.isRTL?r.getBuffer.call(e).reverse():r.getBuffer.call(e)).join("")&&(0,o.applyInputValue)(this,t)}))}(t))}}(t):t.inputmask=void 0,u}(i,t);if(!1!==f){e.originalPlaceholder=i.placeholder,e.maxLength=void 0!==i?i.maxLength:void 0,-1===e.maxLength&&(e.maxLength=void 0),"inputMode"in i&&null===i.getAttribute("inputmode")&&(i.inputMode=t.inputmode,i.setAttribute("inputmode",t.inputmode)),!0===f&&(t.showMaskOnFocus=t.showMaskOnFocus&&-1===["cc-number","cc-exp"].indexOf(i.autocomplete),l.iphone&&(t.insertModeVisual=!1),s.EventRuler.on(i,"submit",c.EventHandlers.submitEvent),s.EventRuler.on(i,"reset",c.EventHandlers.resetEvent),s.EventRuler.on(i,"blur",c.EventHandlers.blurEvent),s.EventRuler.on(i,"focus",c.EventHandlers.focusEvent),s.EventRuler.on(i,"invalid",c.EventHandlers.invalidEvent),s.EventRuler.on(i,"click",c.EventHandlers.clickEvent),s.EventRuler.on(i,"mouseleave",c.EventHandlers.mouseleaveEvent),s.EventRuler.on(i,"mouseenter",c.EventHandlers.mouseenterEvent),s.EventRuler.on(i,"paste",c.EventHandlers.pasteEvent),s.EventRuler.on(i,"cut",c.EventHandlers.cutEvent),s.EventRuler.on(i,"complete",t.oncomplete),s.EventRuler.on(i,"incomplete",t.onincomplete),s.EventRuler.on(i,"cleared",t.oncleared),!0!==t.inputEventOnly&&(s.EventRuler.on(i,"keydown",c.EventHandlers.keydownEvent),s.EventRuler.on(i,"keypress",c.EventHandlers.keypressEvent),s.EventRuler.on(i,"keyup",c.EventHandlers.keyupEvent)),(l.mobile||t.inputEventOnly)&&i.removeAttribute("maxLength"),s.EventRuler.on(i,"input",c.EventHandlers.inputFallBackEvent),s.EventRuler.on(i,"compositionend",c.EventHandlers.compositionendEvent)),s.EventRuler.on(i,"setvalue",c.EventHandlers.setValueEvent),r.getBufferTemplate.call(e).join(""),e.undoValue=e._valueGet(!0);var d=(i.inputmask.shadowRoot||i.ownerDocument).activeElement;if(""!==i.inputmask._valueGet(!0)||!1===t.clearMaskOnLostFocus||d===i){(0,o.applyInputValue)(i,i.inputmask._valueGet(!0),t);var p=r.getBuffer.call(e).slice();!1===u.isComplete.call(e,p)&&t.clearIncomplete&&r.resetMaskSet.call(e),t.clearMaskOnLostFocus&&d!==i&&(-1===r.getLastValidPosition.call(e)?p=[]:o.clearOptionalTail.call(e,p)),(!1===t.clearMaskOnLostFocus||t.showMaskOnFocus&&d===i||""!==i.inputmask._valueGet(!0))&&(0,o.writeBuffer)(i,p),d===i&&r.caret.call(e,i,r.seekNext.call(e,r.getLastValidPosition.call(e)))}}};var a,n=(a=i(5581))&&a.__esModule?a:{default:a},r=i(8711),o=i(7760),s=i(9716),l=i(9845),u=i(7215),c=i(6030)},9695:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,i,a){this.matches=[],this.openGroup=e||!1,this.alternatorGroup=!1,this.isGroup=e||!1,this.isOptional=t||!1,this.isQuantifier=i||!1,this.isAlternator=a||!1,this.quantifier={min:1,max:1}}},3194:function(){Array.prototype.includes||Object.defineProperty(Array.prototype,"includes",{value:function(e,t){if(null==this)throw new TypeError('"this" is null or not defined');var i=Object(this),a=i.length>>>0;if(0===a)return!1;for(var n=0|t,r=Math.max(n>=0?n:a-Math.abs(n),0);r<a;){if(i[r]===e)return!0;r++}return!1}})},7149:function(){function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}"function"!=typeof Object.getPrototypeOf&&(Object.getPrototypeOf="object"===e("test".__proto__)?function(e){return e.__proto__}:function(e){return e.constructor.prototype})},8711:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.caret=function(e,t,i,a,n){var r,o=this,s=this.opts;if(void 0===t)return"selectionStart"in e&&"selectionEnd"in e?(t=e.selectionStart,i=e.selectionEnd):window.getSelection?(r=window.getSelection().getRangeAt(0)).commonAncestorContainer.parentNode!==e&&r.commonAncestorContainer!==e||(t=r.startOffset,i=r.endOffset):document.selection&&document.selection.createRange&&(r=document.selection.createRange(),t=0-r.duplicate().moveStart("character",-e.inputmask._valueGet().length),i=t+r.text.length),{begin:a?t:u.call(o,t),end:a?i:u.call(o,i)};if(Array.isArray(t)&&(i=o.isRTL?t[0]:t[1],t=o.isRTL?t[1]:t[0]),void 0!==t.begin&&(i=o.isRTL?t.begin:t.end,t=o.isRTL?t.end:t.begin),"number"==typeof t){t=a?t:u.call(o,t),i="number"==typeof(i=a?i:u.call(o,i))?i:t;var l=parseInt(((e.ownerDocument.defaultView||window).getComputedStyle?(e.ownerDocument.defaultView||window).getComputedStyle(e,null):e.currentStyle).fontSize)*i;if(e.scrollLeft=l>e.scrollWidth?l:0,e.inputmask.caretPos={begin:t,end:i},s.insertModeVisual&&!1===s.insertMode&&t===i&&(n||i++),e===(e.inputmask.shadowRoot||e.ownerDocument).activeElement)if("setSelectionRange"in e)e.setSelectionRange(t,i);else if(window.getSelection){if(r=document.createRange(),void 0===e.firstChild||null===e.firstChild){var c=document.createTextNode("");e.appendChild(c)}r.setStart(e.firstChild,t<e.inputmask._valueGet().length?t:e.inputmask._valueGet().length),r.setEnd(e.firstChild,i<e.inputmask._valueGet().length?i:e.inputmask._valueGet().length),r.collapse(!0);var f=window.getSelection();f.removeAllRanges(),f.addRange(r)}else e.createTextRange&&((r=e.createTextRange()).collapse(!0),r.moveEnd("character",i),r.moveStart("character",t),r.select())}},t.determineLastRequiredPosition=function(e){var t,i,r=this,s=this.maskset,l=this.dependencyLib,u=a.getMaskTemplate.call(r,!0,o.call(r),!0,!0),c=u.length,f=o.call(r),d={},p=s.validPositions[f],h=void 0!==p?p.locator.slice():void 0;for(t=f+1;t<u.length;t++)i=a.getTestTemplate.call(r,t,h,t-1),h=i.locator.slice(),d[t]=l.extend(!0,{},i);var m=p&&void 0!==p.alternation?p.locator[p.alternation]:void 0;for(t=c-1;t>f&&(((i=d[t]).match.optionality||i.match.optionalQuantifier&&i.match.newBlockMarker||m&&(m!==d[t].locator[p.alternation]&&1!=i.match.static||!0===i.match.static&&i.locator[p.alternation]&&n.checkAlternationMatch.call(r,i.locator[p.alternation].toString().split(","),m.toString().split(","))&&""!==a.getTests.call(r,t)[0].def))&&u[t]===a.getPlaceholder.call(r,t,i.match));t--)c--;return e?{l:c,def:d[c]?d[c].match:void 0}:c},t.determineNewCaretPosition=function(e,t,i){var n=this,u=this.maskset,c=this.opts;t&&(n.isRTL?e.end=e.begin:e.begin=e.end);if(e.begin===e.end){switch(i=i||c.positionCaretOnClick){case"none":break;case"select":e={begin:0,end:r.call(n).length};break;case"ignore":e.end=e.begin=l.call(n,o.call(n));break;case"radixFocus":if(function(e){if(""!==c.radixPoint&&0!==c.digits){var t=u.validPositions;if(void 0===t[e]||t[e].input===a.getPlaceholder.call(n,e)){if(e<l.call(n,-1))return!0;var i=r.call(n).indexOf(c.radixPoint);if(-1!==i){for(var o in t)if(t[o]&&i<o&&t[o].input!==a.getPlaceholder.call(n,o))return!1;return!0}}}return!1}(e.begin)){var f=r.call(n).join("").indexOf(c.radixPoint);e.end=e.begin=c.numericInput?l.call(n,f):f;break}default:var d=e.begin,p=o.call(n,d,!0),h=l.call(n,-1!==p||s.call(n,0)?p:-1);if(d<=h)e.end=e.begin=s.call(n,d,!1,!0)?d:l.call(n,d);else{var m=u.validPositions[p],v=a.getTestTemplate.call(n,h,m?m.match.locator:void 0,m),g=a.getPlaceholder.call(n,h,v.match);if(""!==g&&r.call(n)[h]!==g&&!0!==v.match.optionalQuantifier&&!0!==v.match.newBlockMarker||!s.call(n,h,c.keepStatic,!0)&&v.match.def===g){var k=l.call(n,h);(d>=k||d===h)&&(h=k)}e.end=e.begin=h}}return e}},t.getBuffer=r,t.getBufferTemplate=function(){var e=this.maskset;void 0===e._buffer&&(e._buffer=a.getMaskTemplate.call(this,!1,1),void 0===e.buffer&&(e.buffer=e._buffer.slice()));return e._buffer},t.getLastValidPosition=o,t.isMask=s,t.resetMaskSet=function(e){var t=this.maskset;t.buffer=void 0,!0!==e&&(t.validPositions={},t.p=0)},t.seekNext=l,t.seekPrevious=function(e,t){var i=this,n=e-1;if(e<=0)return 0;for(;n>0&&(!0===t&&(!0!==a.getTest.call(i,n).match.newBlockMarker||!s.call(i,n,void 0,!0))||!0!==t&&!s.call(i,n,void 0,!0));)n--;return n},t.translatePosition=u;var a=i(4713),n=i(7215);function r(e){var t=this.maskset;return void 0!==t.buffer&&!0!==e||(t.buffer=a.getMaskTemplate.call(this,!0,o.call(this),!0),void 0===t._buffer&&(t._buffer=t.buffer.slice())),t.buffer}function o(e,t,i){var a=this.maskset,n=-1,r=-1,o=i||a.validPositions;for(var s in void 0===e&&(e=-1),o){var l=parseInt(s);o[l]&&(t||!0!==o[l].generatedInput)&&(l<=e&&(n=l),l>=e&&(r=l))}return-1===n||n==e?r:-1==r||e-n<r-e?n:r}function s(e,t,i){var n=this,r=this.maskset,o=a.getTestTemplate.call(n,e).match;if(""===o.def&&(o=a.getTest.call(n,e).match),!0!==o.static)return o.fn;if(!0===i&&void 0!==r.validPositions[e]&&!0!==r.validPositions[e].generatedInput)return!0;if(!0!==t&&e>-1){if(i){var s=a.getTests.call(n,e);return s.length>1+(""===s[s.length-1].match.def?1:0)}var l=a.determineTestTemplate.call(n,e,a.getTests.call(n,e)),u=a.getPlaceholder.call(n,e,l.match);return l.match.def!==u}return!1}function l(e,t,i){var n=this;void 0===i&&(i=!0);for(var r=e+1;""!==a.getTest.call(n,r).match.def&&(!0===t&&(!0!==a.getTest.call(n,r).match.newBlockMarker||!s.call(n,r,void 0,!0))||!0!==t&&!s.call(n,r,void 0,i));)r++;return r}function u(e){var t=this.opts,i=this.el;return!this.isRTL||"number"!=typeof e||t.greedy&&""===t.placeholder||!i||(e=Math.abs(this._valueGet().length-e)),e}},4713:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.determineTestTemplate=u,t.getDecisionTaker=o,t.getMaskTemplate=function(e,t,i,a,n){var r=this,o=this.opts,c=this.maskset,f=o.greedy;n&&o.greedy&&(o.greedy=!1,r.maskset.tests={});t=t||0;var p,h,m,v,g=[],k=0;do{if(!0===e&&c.validPositions[k])m=n&&c.validPositions[k].match.optionality&&void 0===c.validPositions[k+1]&&(!0===c.validPositions[k].generatedInput||c.validPositions[k].input==o.skipOptionalPartCharacter&&k>0)?u.call(r,k,d.call(r,k,p,k-1)):c.validPositions[k],h=m.match,p=m.locator.slice(),g.push(!0===i?m.input:!1===i?h.nativeDef:s.call(r,k,h));else{m=l.call(r,k,p,k-1),h=m.match,p=m.locator.slice();var y=!0!==a&&(!1!==o.jitMasking?o.jitMasking:h.jit);(v=(v&&h.static&&h.def!==o.groupSeparator&&null===h.fn||c.validPositions[k-1]&&h.static&&h.def!==o.groupSeparator&&null===h.fn)&&c.tests[k]&&1===c.tests[k].length)||!1===y||void 0===y||"number"==typeof y&&isFinite(y)&&y>k?g.push(!1===i?h.nativeDef:s.call(r,k,h)):v=!1}k++}while(!0!==h.static||""!==h.def||t>k);""===g[g.length-1]&&g.pop();!1===i&&void 0!==c.maskLength||(c.maskLength=k-1);return o.greedy=f,g},t.getPlaceholder=s,t.getTest=c,t.getTestTemplate=l,t.getTests=d,t.isSubsetOf=f;var a,n=(a=i(2394))&&a.__esModule?a:{default:a};function r(e,t){var i=(null!=e.alternation?e.mloc[o(e)]:e.locator).join("");if(""!==i)for(;i.length<t;)i+="0";return i}function o(e){var t=e.locator[e.alternation];return"string"==typeof t&&t.length>0&&(t=t.split(",")[0]),void 0!==t?t.toString():""}function s(e,t,i){var a=this.opts,n=this.maskset;if(void 0!==(t=t||c.call(this,e).match).placeholder||!0===i)return"function"==typeof t.placeholder?t.placeholder(a):t.placeholder;if(!0===t.static){if(e>-1&&void 0===n.validPositions[e]){var r,o=d.call(this,e),s=[];if(o.length>1+(""===o[o.length-1].match.def?1:0))for(var l=0;l<o.length;l++)if(""!==o[l].match.def&&!0!==o[l].match.optionality&&!0!==o[l].match.optionalQuantifier&&(!0===o[l].match.static||void 0===r||!1!==o[l].match.fn.test(r.match.def,n,e,!0,a))&&(s.push(o[l]),!0===o[l].match.static&&(r=o[l]),s.length>1&&/[0-9a-bA-Z]/.test(s[0].match.def)))return a.placeholder.charAt(e%a.placeholder.length)}return t.def}return a.placeholder.charAt(e%a.placeholder.length)}function l(e,t,i){return this.maskset.validPositions[e]||u.call(this,e,d.call(this,e,t?t.slice():t,i))}function u(e,t){var i=this.opts,a=function(e,t){var i=0,a=!1;t.forEach((function(e){e.match.optionality&&(0!==i&&i!==e.match.optionality&&(a=!0),(0===i||i>e.match.optionality)&&(i=e.match.optionality))})),i&&(0==e||1==t.length?i=0:a||(i=0));return i}(e,t);e=e>0?e-1:0;var n,o,s,l=r(c.call(this,e));i.greedy&&t.length>1&&""===t[t.length-1].match.def&&t.pop();for(var u=0;u<t.length;u++){var f=t[u];n=r(f,l.length);var d=Math.abs(n-l);(void 0===o||""!==n&&d<o||s&&!i.greedy&&s.match.optionality&&s.match.optionality-a>0&&"master"===s.match.newBlockMarker&&(!f.match.optionality||f.match.optionality-a<1||!f.match.newBlockMarker)||s&&!i.greedy&&s.match.optionalQuantifier&&!f.match.optionalQuantifier)&&(o=d,s=f)}return s}function c(e,t){var i=this.maskset;return i.validPositions[e]?i.validPositions[e]:(t||d.call(this,e))[0]}function f(e,t,i){function a(e){for(var t,i=[],a=-1,n=0,r=e.length;n<r;n++)if("-"===e.charAt(n))for(t=e.charCodeAt(n+1);++a<t;)i.push(String.fromCharCode(a));else a=e.charCodeAt(n),i.push(e.charAt(n));return i.join("")}return e.match.def===t.match.nativeDef||!(!(i.regex||e.match.fn instanceof RegExp&&t.match.fn instanceof RegExp)||!0===e.match.static||!0===t.match.static)&&-1!==a(t.match.fn.toString().replace(/[[\]/]/g,"")).indexOf(a(e.match.fn.toString().replace(/[[\]/]/g,"")))}function d(e,t,i){var a,r,o=this,s=this.dependencyLib,l=this.maskset,c=this.opts,d=this.el,p=l.maskToken,h=t?i:0,m=t?t.slice():[0],v=[],g=!1,k=t?t.join(""):"";function y(t,i,r,o){function s(r,o,u){function p(e,t){var i=0===t.matches.indexOf(e);return i||t.matches.every((function(a,n){return!0===a.isQuantifier?i=p(e,t.matches[n-1]):Object.prototype.hasOwnProperty.call(a,"matches")&&(i=p(e,a)),!i})),i}function m(e,t,i){var a,n;if((l.tests[e]||l.validPositions[e])&&(l.tests[e]||[l.validPositions[e]]).every((function(e,r){if(e.mloc[t])return a=e,!1;var o=void 0!==i?i:e.alternation,s=void 0!==e.locator[o]?e.locator[o].toString().indexOf(t):-1;return(void 0===n||s<n)&&-1!==s&&(a=e,n=s),!0})),a){var r=a.locator[a.alternation];return(a.mloc[t]||a.mloc[r]||a.locator).slice((void 0!==i?i:a.alternation)+1)}return void 0!==i?m(e,t):void 0}function b(e,t){var i=e.alternation,a=void 0===t||i===t.alternation&&-1===e.locator[i].toString().indexOf(t.locator[i]);if(!a&&i>t.alternation)for(var n=t.alternation;n<i;n++)if(e.locator[n]!==t.locator[n]){i=n,a=!0;break}if(a){e.mloc=e.mloc||{};var r=e.locator[i];if(void 0!==r){if("string"==typeof r&&(r=r.split(",")[0]),void 0===e.mloc[r]&&(e.mloc[r]=e.locator.slice()),void 0!==t){for(var o in t.mloc)"string"==typeof o&&(o=o.split(",")[0]),void 0===e.mloc[o]&&(e.mloc[o]=t.mloc[o]);e.locator[i]=Object.keys(e.mloc).join(",")}return!0}e.alternation=void 0}return!1}function x(e,t){if(e.locator.length!==t.locator.length)return!1;for(var i=e.alternation+1;i<e.locator.length;i++)if(e.locator[i]!==t.locator[i])return!1;return!0}if(h>e+c._maxTestPos)throw"Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. "+l.mask;if(h===e&&void 0===r.matches){if(v.push({match:r,locator:o.reverse(),cd:k,mloc:{}}),!r.optionality||void 0!==u||!(c.definitions&&c.definitions[r.nativeDef]&&c.definitions[r.nativeDef].optional||n.default.prototype.definitions[r.nativeDef]&&n.default.prototype.definitions[r.nativeDef].optional))return!0;g=!0,h=e}else if(void 0!==r.matches){if(r.isGroup&&u!==r){if(r=s(t.matches[t.matches.indexOf(r)+1],o,u))return!0}else if(r.isOptional){var P=r,E=v.length;if(r=y(r,i,o,u)){if(v.forEach((function(e,t){t>=E&&(e.match.optionality=e.match.optionality?e.match.optionality+1:1)})),a=v[v.length-1].match,void 0!==u||!p(a,P))return!0;g=!0,h=e}}else if(r.isAlternator){var S,w=r,_=[],M=v.slice(),O=o.length,T=!1,A=i.length>0?i.shift():-1;if(-1===A||"string"==typeof A){var C,D=h,j=i.slice(),B=[];if("string"==typeof A)B=A.split(",");else for(C=0;C<w.matches.length;C++)B.push(C.toString());if(void 0!==l.excludes[e]){for(var R=B.slice(),L=0,I=l.excludes[e].length;L<I;L++){var F=l.excludes[e][L].toString().split(":");o.length==F[1]&&B.splice(B.indexOf(F[0]),1)}0===B.length&&(delete l.excludes[e],B=R)}(!0===c.keepStatic||isFinite(parseInt(c.keepStatic))&&D>=c.keepStatic)&&(B=B.slice(0,1));for(var N=0;N<B.length;N++){C=parseInt(B[N]),v=[],i="string"==typeof A&&m(h,C,O)||j.slice();var V=w.matches[C];if(V&&s(V,[C].concat(o),u))r=!0;else if(0===N&&(T=!0),V&&V.matches&&V.matches.length>w.matches[0].matches.length)break;S=v.slice(),h=D,v=[];for(var G=0;G<S.length;G++){var H=S[G],K=!1;H.match.jit=H.match.jit||T,H.alternation=H.alternation||O,b(H);for(var U=0;U<_.length;U++){var $=_[U];if("string"!=typeof A||void 0!==H.alternation&&B.includes(H.locator[H.alternation].toString())){if(H.match.nativeDef===$.match.nativeDef){K=!0,b($,H);break}if(f(H,$,c)){b(H,$)&&(K=!0,_.splice(_.indexOf($),0,H));break}if(f($,H,c)){b($,H);break}if(Z=$,!0===(W=H).match.static&&!0!==Z.match.static&&Z.match.fn.test(W.match.def,l,e,!1,c,!1)){x(H,$)||void 0!==d.inputmask.userOptions.keepStatic?b(H,$)&&(K=!0,_.splice(_.indexOf($),0,H)):c.keepStatic=!0;break}}}K||_.push(H)}}v=M.concat(_),h=e,g=v.length>0,r=_.length>0,i=j.slice()}else r=s(w.matches[A]||t.matches[A],[A].concat(o),u);if(r)return!0}else if(r.isQuantifier&&u!==t.matches[t.matches.indexOf(r)-1])for(var q=r,z=i.length>0?i.shift():0;z<(isNaN(q.quantifier.max)?z+1:q.quantifier.max)&&h<=e;z++){var Q=t.matches[t.matches.indexOf(q)-1];if(r=s(Q,[z].concat(o),Q)){if((a=v[v.length-1].match).optionalQuantifier=z>=q.quantifier.min,a.jit=(z+1)*(Q.matches.indexOf(a)+1)>q.quantifier.jit,a.optionalQuantifier&&p(a,Q)){g=!0,h=e;break}return a.jit&&(l.jitOffset[e]=Q.matches.length-Q.matches.indexOf(a)),!0}}else if(r=y(r,i,o,u))return!0}else h++;var W,Z}for(var u=i.length>0?i.shift():0;u<t.matches.length;u++)if(!0!==t.matches[u].isQuantifier){var p=s(t.matches[u],[u].concat(r),o);if(p&&h===e)return p;if(h>e)break}}if(e>-1){if(void 0===t){for(var b,x=e-1;void 0===(b=l.validPositions[x]||l.tests[x])&&x>-1;)x--;void 0!==b&&x>-1&&(m=function(e,t){var i,a=[];return Array.isArray(t)||(t=[t]),t.length>0&&(void 0===t[0].alternation||!0===c.keepStatic?0===(a=u.call(o,e,t.slice()).locator.slice()).length&&(a=t[0].locator.slice()):t.forEach((function(e){""!==e.def&&(0===a.length?(i=e.alternation,a=e.locator.slice()):e.locator[i]&&-1===a[i].toString().indexOf(e.locator[i])&&(a[i]+=","+e.locator[i]))}))),a}(x,b),k=m.join(""),h=x)}if(l.tests[e]&&l.tests[e][0].cd===k)return l.tests[e];for(var P=m.shift();P<p.length;P++){if(y(p[P],m,[P])&&h===e||h>e)break}}return(0===v.length||g)&&v.push({match:{fn:null,static:!0,optionality:!1,casing:null,def:"",placeholder:""},locator:[],mloc:{},cd:k}),void 0!==t&&l.tests[e]?r=s.extend(!0,[],v):(l.tests[e]=s.extend(!0,[],v),r=l.tests[e]),v.forEach((function(e){e.match.optionality=!1})),r}},7215:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.alternate=l,t.checkAlternationMatch=function(e,t,i){for(var a,n=this.opts.greedy?t:t.slice(0,1),r=!1,o=void 0!==i?i.split(","):[],s=0;s<o.length;s++)-1!==(a=e.indexOf(o[s]))&&e.splice(a,1);for(var l=0;l<e.length;l++)if(n.includes(e[l])){r=!0;break}return r},t.handleRemove=function(e,t,i,a,s){var u=this,c=this.maskset,f=this.opts;if((f.numericInput||u.isRTL)&&(t===r.default.BACKSPACE?t=r.default.DELETE:t===r.default.DELETE&&(t=r.default.BACKSPACE),u.isRTL)){var d=i.end;i.end=i.begin,i.begin=d}var p,h=o.getLastValidPosition.call(u,void 0,!0);i.end>=o.getBuffer.call(u).length&&h>=i.end&&(i.end=h+1);t===r.default.BACKSPACE?i.end-i.begin<1&&(i.begin=o.seekPrevious.call(u,i.begin)):t===r.default.DELETE&&i.begin===i.end&&(i.end=o.isMask.call(u,i.end,!0,!0)?i.end+1:o.seekNext.call(u,i.end)+1);if(!1!==(p=v.call(u,i))){if(!0!==a&&!1!==f.keepStatic||null!==f.regex&&-1!==n.getTest.call(u,i.begin).match.def.indexOf("|")){var m=l.call(u,!0);if(m){var g=void 0!==m.caret?m.caret:m.pos?o.seekNext.call(u,m.pos.begin?m.pos.begin:m.pos):o.getLastValidPosition.call(u,-1,!0);(t!==r.default.DELETE||i.begin>g)&&i.begin}}!0!==a&&(c.p=t===r.default.DELETE?i.begin+p:i.begin,c.p=o.determineNewCaretPosition.call(u,{begin:c.p,end:c.p},!1,!1===f.insertMode&&t===r.default.BACKSPACE?"none":void 0).begin)}},t.isComplete=c,t.isSelection=f,t.isValid=d,t.refreshFromBuffer=h,t.revalidateMask=v;var a,n=i(4713),r=(a=i(5581))&&a.__esModule?a:{default:a},o=i(8711),s=i(6030);function l(e,t,i,a,r,s){var u,c,f,p,h,m,v,g,k,y,b,x=this,P=this.dependencyLib,E=this.opts,S=x.maskset,w=P.extend(!0,{},S.validPositions),_=P.extend(!0,{},S.tests),M=!1,O=!1,T=void 0!==r?r:o.getLastValidPosition.call(x);if(s&&(y=s.begin,b=s.end,s.begin>s.end&&(y=s.end,b=s.begin)),-1===T&&void 0===r)u=0,c=(p=n.getTest.call(x,u)).alternation;else for(;T>=0;T--)if((f=S.validPositions[T])&&void 0!==f.alternation){if(p&&p.locator[f.alternation]!==f.locator[f.alternation])break;u=T,c=S.validPositions[u].alternation,p=f}if(void 0!==c){v=parseInt(u),S.excludes[v]=S.excludes[v]||[],!0!==e&&S.excludes[v].push((0,n.getDecisionTaker)(p)+":"+p.alternation);var A=[],C=-1;for(h=v;h<o.getLastValidPosition.call(x,void 0,!0)+1;h++)-1===C&&e<=h&&void 0!==t&&(A.push(t),C=A.length-1),(m=S.validPositions[h])&&!0!==m.generatedInput&&(void 0===s||h<y||h>=b)&&A.push(m.input),delete S.validPositions[h];for(-1===C&&void 0!==t&&(A.push(t),C=A.length-1);void 0!==S.excludes[v]&&S.excludes[v].length<10;){for(S.tests={},o.resetMaskSet.call(x,!0),M=!0,h=0;h<A.length&&(g=M.caret||o.getLastValidPosition.call(x,void 0,!0)+1,k=A[h],M=d.call(x,g,k,!1,a,!0));h++)h===C&&(O=M),1==e&&M&&(O={caretPos:h});if(M)break;if(o.resetMaskSet.call(x),p=n.getTest.call(x,v),S.validPositions=P.extend(!0,{},w),S.tests=P.extend(!0,{},_),!S.excludes[v]){O=l.call(x,e,t,i,a,v-1,s);break}var D=(0,n.getDecisionTaker)(p);if(-1!==S.excludes[v].indexOf(D+":"+p.alternation)){O=l.call(x,e,t,i,a,v-1,s);break}for(S.excludes[v].push(D+":"+p.alternation),h=v;h<o.getLastValidPosition.call(x,void 0,!0)+1;h++)delete S.validPositions[h]}}return O&&!1===E.keepStatic||delete S.excludes[v],O}function u(e,t,i){var a=this.opts,n=this.maskset;switch(a.casing||t.casing){case"upper":e=e.toUpperCase();break;case"lower":e=e.toLowerCase();break;case"title":var o=n.validPositions[i-1];e=0===i||o&&o.input===String.fromCharCode(r.default.SPACE)?e.toUpperCase():e.toLowerCase();break;default:if("function"==typeof a.casing){var s=Array.prototype.slice.call(arguments);s.push(n.validPositions),e=a.casing.apply(this,s)}}return e}function c(e){var t=this,i=this.opts,a=this.maskset;if("function"==typeof i.isComplete)return i.isComplete(e,i);if("*"!==i.repeat){var r=!1,s=o.determineLastRequiredPosition.call(t,!0),l=o.seekPrevious.call(t,s.l);if(void 0===s.def||s.def.newBlockMarker||s.def.optionality||s.def.optionalQuantifier){r=!0;for(var u=0;u<=l;u++){var c=n.getTestTemplate.call(t,u).match;if(!0!==c.static&&void 0===a.validPositions[u]&&!0!==c.optionality&&!0!==c.optionalQuantifier||!0===c.static&&e[u]!==n.getPlaceholder.call(t,u,c)){r=!1;break}}}return r}}function f(e){var t=this.opts.insertMode?0:1;return this.isRTL?e.begin-e.end>t:e.end-e.begin>t}function d(e,t,i,a,r,s,p){var g=this,k=this.dependencyLib,y=this.opts,b=g.maskset;i=!0===i;var x=e;function P(e){if(void 0!==e){if(void 0!==e.remove&&(Array.isArray(e.remove)||(e.remove=[e.remove]),e.remove.sort((function(e,t){return t.pos-e.pos})).forEach((function(e){v.call(g,{begin:e,end:e+1})})),e.remove=void 0),void 0!==e.insert&&(Array.isArray(e.insert)||(e.insert=[e.insert]),e.insert.sort((function(e,t){return e.pos-t.pos})).forEach((function(e){""!==e.c&&d.call(g,e.pos,e.c,void 0===e.strict||e.strict,void 0!==e.fromIsValid?e.fromIsValid:a)})),e.insert=void 0),e.refreshFromBuffer&&e.buffer){var t=e.refreshFromBuffer;h.call(g,!0===t?t:t.start,t.end,e.buffer),e.refreshFromBuffer=void 0}void 0!==e.rewritePosition&&(x=e.rewritePosition,e=!0)}return e}function E(t,i,r){var s=!1;return n.getTests.call(g,t).every((function(l,c){var d=l.match;if(o.getBuffer.call(g,!0),!1!==(s=(!d.jit||void 0!==b.validPositions[o.seekPrevious.call(g,t)])&&(null!=d.fn?d.fn.test(i,b,t,r,y,f.call(g,e)):(i===d.def||i===y.skipOptionalPartCharacter)&&""!==d.def&&{c:n.getPlaceholder.call(g,t,d,!0)||d.def,pos:t}))){var p=void 0!==s.c?s.c:i,h=t;return p=p===y.skipOptionalPartCharacter&&!0===d.static?n.getPlaceholder.call(g,t,d,!0)||d.def:p,!0!==(s=P(s))&&void 0!==s.pos&&s.pos!==t&&(h=s.pos),!0!==s&&void 0===s.pos&&void 0===s.c?!1:(!1===v.call(g,e,k.extend({},l,{input:u.call(g,p,d,h)}),a,h)&&(s=!1),!1)}return!0})),s}void 0!==e.begin&&(x=g.isRTL?e.end:e.begin);var S=!0,w=k.extend(!0,{},b.validPositions);if(!1===y.keepStatic&&void 0!==b.excludes[x]&&!0!==r&&!0!==a)for(var _=x;_<(g.isRTL?e.begin:e.end);_++)void 0!==b.excludes[_]&&(b.excludes[_]=void 0,delete b.tests[_]);if("function"==typeof y.preValidation&&!0!==a&&!0!==s&&(S=P(S=y.preValidation.call(g,o.getBuffer.call(g),x,t,f.call(g,e),y,b,e,i||r))),!0===S){if(S=E(x,t,i),(!i||!0===a)&&!1===S&&!0!==s){var M=b.validPositions[x];if(!M||!0!==M.match.static||M.match.def!==t&&t!==y.skipOptionalPartCharacter){if(y.insertMode||void 0===b.validPositions[o.seekNext.call(g,x)]||e.end>x){var O=!1;if(b.jitOffset[x]&&void 0===b.validPositions[o.seekNext.call(g,x)]&&!1!==(S=d.call(g,x+b.jitOffset[x],t,!0,!0))&&(!0!==r&&(S.caret=x),O=!0),e.end>x&&(b.validPositions[x]=void 0),!O&&!o.isMask.call(g,x,y.keepStatic&&0===x))for(var T=x+1,A=o.seekNext.call(g,x,!1,0!==x);T<=A;T++)if(!1!==(S=E(T,t,i))){S=m.call(g,x,void 0!==S.pos?S.pos:T)||S,x=T;break}}}else S={caret:o.seekNext.call(g,x)}}!1!==S||!y.keepStatic||!c.call(g,o.getBuffer.call(g))&&0!==x||i||!0===r?f.call(g,e)&&b.tests[x]&&b.tests[x].length>1&&y.keepStatic&&!i&&!0!==r&&(S=l.call(g,!0)):S=l.call(g,x,t,i,a,void 0,e),!0===S&&(S={pos:x})}if("function"==typeof y.postValidation&&!0!==a&&!0!==s){var C=y.postValidation.call(g,o.getBuffer.call(g,!0),void 0!==e.begin?g.isRTL?e.end:e.begin:e,t,S,y,b,i,p);void 0!==C&&(S=!0===C?S:C)}S&&void 0===S.pos&&(S.pos=x),!1===S||!0===s?(o.resetMaskSet.call(g,!0),b.validPositions=k.extend(!0,{},w)):m.call(g,void 0,x,!0);var D=P(S);void 0!==g.maxLength&&(o.getBuffer.call(g).length>g.maxLength&&!a&&(o.resetMaskSet.call(g,!0),b.validPositions=k.extend(!0,{},w),D=!1));return D}function p(e,t,i){for(var a=this.maskset,r=!1,o=n.getTests.call(this,e),s=0;s<o.length;s++){if(o[s].match&&(o[s].match.nativeDef===t.match[i.shiftPositions?"def":"nativeDef"]&&(!i.shiftPositions||!t.match.static)||o[s].match.nativeDef===t.match.nativeDef||i.regex&&!o[s].match.static&&o[s].match.fn.test(t.input))){r=!0;break}if(o[s].match&&o[s].match.def===t.match.nativeDef){r=void 0;break}}return!1===r&&void 0!==a.jitOffset[e]&&(r=p.call(this,e+a.jitOffset[e],t,i)),r}function h(e,t,i){var a,n,r=this,l=this.maskset,u=this.opts,c=this.dependencyLib,f=u.skipOptionalPartCharacter,d=r.isRTL?i.slice().reverse():i;if(u.skipOptionalPartCharacter="",!0===e)o.resetMaskSet.call(r),l.tests={},e=0,t=i.length,n=o.determineNewCaretPosition.call(r,{begin:0,end:0},!1).begin;else{for(a=e;a<t;a++)delete l.validPositions[a];n=e}var p=new c.Event("keypress");for(a=e;a<t;a++){p.keyCode=d[a].toString().charCodeAt(0),r.ignorable=!1;var h=s.EventHandlers.keypressEvent.call(r,p,!0,!1,!1,n);!1!==h&&void 0!==h&&(n=h.forwardPosition)}u.skipOptionalPartCharacter=f}function m(e,t,i){var a=this,r=this.maskset,s=this.dependencyLib;if(void 0===e)for(e=t-1;e>0&&!r.validPositions[e];e--);for(var l=e;l<t;l++){if(void 0===r.validPositions[l]&&!o.isMask.call(a,l,!1))if(0==l?n.getTest.call(a,l):r.validPositions[l-1]){var u=n.getTests.call(a,l).slice();""===u[u.length-1].match.def&&u.pop();var c,f=n.determineTestTemplate.call(a,l,u);if(f&&(!0!==f.match.jit||"master"===f.match.newBlockMarker&&(c=r.validPositions[l+1])&&!0===c.match.optionalQuantifier)&&((f=s.extend({},f,{input:n.getPlaceholder.call(a,l,f.match,!0)||f.match.def})).generatedInput=!0,v.call(a,l,f,!0),!0!==i)){var p=r.validPositions[t].input;return r.validPositions[t]=void 0,d.call(a,t,p,!0,!0)}}}}function v(e,t,i,a){var r=this,s=this.maskset,l=this.opts,u=this.dependencyLib;function c(e,t,i){var a=t[e];if(void 0!==a&&!0===a.match.static&&!0!==a.match.optionality&&(void 0===t[0]||void 0===t[0].alternation)){var n=i.begin<=e-1?t[e-1]&&!0===t[e-1].match.static&&t[e-1]:t[e-1],r=i.end>e+1?t[e+1]&&!0===t[e+1].match.static&&t[e+1]:t[e+1];return n&&r}return!1}var f=0,h=void 0!==e.begin?e.begin:e,m=void 0!==e.end?e.end:e,v=!0;if(e.begin>e.end&&(h=e.end,m=e.begin),a=void 0!==a?a:h,h!==m||l.insertMode&&void 0!==s.validPositions[a]&&void 0===i||void 0===t||t.match.optionalQuantifier||t.match.optionality){var g,k=u.extend(!0,{},s.validPositions),y=o.getLastValidPosition.call(r,void 0,!0);for(s.p=h,g=y;g>=h;g--)delete s.validPositions[g],void 0===t&&delete s.tests[g+1];var b,x,P=a,E=P;for(t&&(s.validPositions[a]=u.extend(!0,{},t),E++,P++),g=t?m:m-1;g<=y;g++){if(void 0!==(b=k[g])&&!0!==b.generatedInput&&(g>=m||g>=h&&c(g,k,{begin:h,end:m}))){for(;""!==n.getTest.call(r,E).match.def;){if(!1!==(x=p.call(r,E,b,l))||"+"===b.match.def){"+"===b.match.def&&o.getBuffer.call(r,!0);var S=d.call(r,E,b.input,"+"!==b.match.def,!0);if(v=!1!==S,P=(S.pos||E)+1,!v&&x)break}else v=!1;if(v){void 0===t&&b.match.static&&g===e.begin&&f++;break}if(!v&&o.getBuffer.call(r),E>s.maskLength)break;E++}""==n.getTest.call(r,E).match.def&&(v=!1),E=P}if(!v)break}if(!v)return s.validPositions=u.extend(!0,{},k),o.resetMaskSet.call(r,!0),!1}else t&&n.getTest.call(r,a).match.cd===t.match.cd&&(s.validPositions[a]=u.extend(!0,{},t));return o.resetMaskSet.call(r,!0),f}},2047:function(t){t.exports=e},5581:function(e){e.exports=JSON.parse('{"BACKSPACE":8,"BACKSPACE_SAFARI":127,"DELETE":46,"DOWN":40,"END":35,"ENTER":13,"ESCAPE":27,"HOME":36,"INSERT":45,"LEFT":37,"PAGE_DOWN":34,"PAGE_UP":33,"RIGHT":39,"SPACE":32,"TAB":9,"UP":38,"X":88,"Z":90,"CONTROL":17,"PAUSE/BREAK":19,"WINDOWS_LEFT":91,"WINDOWS_RIGHT":92,"KEY_229":229}')}},i={};function a(e){var n=i[e];if(void 0!==n)return n.exports;var r=i[e]={exports:{}};return t[e](r,r.exports,a),r.exports}var n={};return function(){var e=n;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t,i=(t=a(3046))&&t.__esModule?t:{default:t};a(443);var r=i.default;e.default=r}(),n}()}));
281677160/openwrt-package
6,451
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_timerd.c
/* * Copyright (C) AlexWoo(Wu Jie) [email protected] */ #include "ngx_timerd.h" #include "ngx_map.h" typedef struct ngx_timerd_node_s ngx_timerd_node_t; static ngx_pool_t *ngx_timerd_pool; static ngx_map_t ngx_timerd_map; static ngx_timerd_node_t *ngx_timerd_free_node; static ngx_uint_t timerd_footprint; static ngx_uint_t ngx_timerd_nalloc; static ngx_uint_t ngx_timerd_nfree; struct ngx_timerd_node_s { ngx_map_node_t m; /* map node */ ngx_timerd_node_t *next; /* free node */ ngx_uint_t footprint; off_t fpoff; ngx_event_t ev; ngx_event_t *uev; char *file; /* file create pool */ int line; /* line create pool */ }; static ngx_int_t ngx_timerd_init() { ngx_timerd_pool = ngx_create_pool(4096, ngx_cycle->log); if (ngx_timerd_pool == NULL) { return NGX_ERROR; } ngx_map_init(&ngx_timerd_map, ngx_map_hash_uint, ngx_cmp_uint); ngx_timerd_free_node = NULL; ngx_timerd_nalloc = 0; ngx_timerd_nfree = 0; return NGX_OK; } static ngx_timerd_node_t * ngx_timerd_get_node() { ngx_timerd_node_t *n; n = ngx_timerd_free_node; if (n == NULL) { n = ngx_pcalloc(ngx_timerd_pool, sizeof(ngx_timerd_node_t)); if (n == NULL) { return NULL; } ++ngx_timerd_nalloc; } else { ngx_timerd_free_node = n->next; ngx_memzero(n, sizeof(ngx_timerd_node_t)); --ngx_timerd_nfree; } return n; } static void ngx_timerd_put_node(ngx_timerd_node_t *node) { if (ngx_timerd_pool == NULL) { return; } if (node == NULL) { return; } node->next = ngx_timerd_free_node; ngx_timerd_free_node = node; ++ngx_timerd_nfree; } static void ngx_timerd_wrap(ngx_event_t *ev) { ngx_timerd_node_t *node; ngx_event_t *uev; ngx_uint_t *fp; node = ev->data; uev = node->uev; fp = (ngx_uint_t *) ((char *) (uev->data) + node->fpoff); if (*fp != node->footprint) { ngx_log_error(NGX_LOG_EMERG, ngx_cycle->log, 0, "timer wrap, timer trigger but not timer owner: %s:%d", node->file, node->line); return; } ngx_map_delete(&ngx_timerd_map, (intptr_t) uev); uev->timer_set = 0; uev->timedout = 1; uev->handler(uev); ngx_timerd_put_node(node); } ngx_uint_t ngx_timerd_footprint() { return timerd_footprint++; } void ngx_add_timer_debug(ngx_event_t *ev, ngx_msec_t timer, off_t fpoff, char *file, int line) { ngx_timerd_node_t *node; ngx_map_node_t *m; ngx_uint_t *fp; if (ngx_timerd_pool == NULL) { ngx_timerd_init(); } fp = (ngx_uint_t *) ((char *) ev->data + fpoff); m = ngx_map_find(&ngx_timerd_map, (intptr_t) ev); if (m == NULL) { // first add node = ngx_timerd_get_node(); node->m.raw_key = (intptr_t) ev; ngx_map_insert(&ngx_timerd_map, &node->m, 0); node->footprint = *fp; node->fpoff = fpoff; node->ev.log = ngx_cycle->log; node->ev.data = node; node->ev.handler = ngx_timerd_wrap; node->uev = ev; node->file = file; node->line = line; } else { node = (ngx_timerd_node_t *) ((char *) m - offsetof(ngx_timerd_node_t, m)); if (node->footprint != *fp) { ngx_log_error(NGX_LOG_EMERG, ngx_cycle->log, 0, "add timer but not timer owner(%s:%d): %s:%d", node->file, node->line, file, line); return; } } ev->timer_set = 1; ngx_add_timer(&node->ev, timer); } void ngx_del_timer_debug(ngx_event_t *ev, ngx_uint_t footprint, char *file, int line) { ngx_timerd_node_t *node; ngx_map_node_t *m; /* get node by pool */ m = ngx_map_find(&ngx_timerd_map, (intptr_t) ev); if (m == NULL) { ngx_log_error(NGX_LOG_EMERG, ngx_cycle->log, 0, "delete timer twice: %s:%d", file, line); return; } node = (ngx_timerd_node_t *) ((char *) m - offsetof(ngx_timerd_node_t, m)); if (node->footprint != footprint) { ngx_log_error(NGX_LOG_EMERG, ngx_cycle->log, 0, "delete timer but not timer owner: %s:%d", file, line); return; } ngx_map_delete(&ngx_timerd_map, (intptr_t) ev); if (node->ev.timer_set) { ev->timer_set = 0; ngx_del_timer(&node->ev); } if (node->ev.posted) { ngx_delete_posted_event(&node->ev); } /* put node in timerd map */ ngx_timerd_put_node(node); } ngx_chain_t * ngx_timerd_state(ngx_http_request_t *r, unsigned detail) { ngx_chain_t *cl; ngx_buf_t *b; ngx_map_node_t *node; ngx_timerd_node_t *pn; size_t len, len1; ngx_uint_t n; len = sizeof("##########ngx debug pool##########\n") - 1 + sizeof("ngx_timerd nalloc node: \n") - 1 + NGX_OFF_T_LEN + sizeof("ngx_timerd nfree node: \n") - 1 + NGX_OFF_T_LEN; len1 = 0; /* node for create pool */ if (detail) { n = ngx_timerd_nalloc - ngx_timerd_nfree; /* " file:line\n" */ len1 = 4 + 256 + 1 + NGX_OFF_T_LEN + 1; len += len1 * n; } cl = ngx_alloc_chain_link(r->pool); if (cl == NULL) { return NULL; } cl->next = NULL; b = ngx_create_temp_buf(r->pool, len); if (b == NULL) { return NULL; } cl->buf = b; b->last = ngx_snprintf(b->last, len, "##########ngx debug pool##########\n" "ngx_timerd nalloc node: %ui\nngx_timerd nfree node: %ui\n", ngx_timerd_nalloc, ngx_timerd_nfree); if (detail) { for (node = ngx_map_begin(&ngx_timerd_map); node; node = ngx_map_next(node)) { /* m is first element of ngx_timerd_node_t */ pn = (ngx_timerd_node_t *) node; b->last = ngx_snprintf(b->last, len1, " %s:%d\n", pn->file, pn->line); } } return cl; }
294coder/Efficient-MIF
6,322
utils/sharpening_index/my_D_s.py
# GPL License # Copyright (C) UESTC # All Rights Reserved # @Author : Xiao Wu # @reference: # # -*- coding: utf-8 -*- """ Copyright (c) 2020 Vivone Gemine. All rights reserved. This work should only be used for nonprofit purposes. @author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home ) """ """ Description: Spatial distortion index. Interface: D_s_index = D_s(I_F,I_MS,I_MS_LR,I_PAN,ratio,S,q) Inputs: I_F: Pansharpened image; I_MS: MS image resampled to panchromatic scale; I_MS_LR: Original MS image; I_PAN: Panchromatic image; ratio: Scale ratio between MS and PAN. Pre-condition: Integer value; S: Block size; q: Exponent value (optional); Default value: q = 1. Outputs: D_s_index: Spatial distortion index. Notes: Results very close to the MATLAB toolbox's ones. In particular, the results are more accurate than the MATLAB toolbox's ones because the Q-index is applied in a sliding window way. Instead, for computational reasons, the MATLAB toolbox uses a distinct block implementation of the Q-index. References: G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021. G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021. """ import numpy as np from skimage.metrics import structural_similarity as ssim from .interp23 import interp23 from .imresize import imresize import torch from torch.nn import functional as F import math # # def gaussian(window_size, sigma): # gauss = torch.Tensor([math.exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)]) # return gauss / gauss.sum() def create_window(window_size, channel): # _1D_window = gaussian(window_size, sigma).unsqueeze(1) # _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0) _2D_window = torch.ones(window_size, window_size)#.uniform_(0, 1) window = _2D_window.expand(channel, 1, window_size, window_size).contiguous() return window def D_s(I_F, I_MS, I_MS_LR, I_PAN, ratio, S, q): """ if 0, Toolbox 1.0, otherwise, original QNR paper """ flag_orig_paper = 0 if (I_F.shape != I_MS.shape): print("The two images must have the same dimensions") return -1 N = I_F.shape[0] M = I_F.shape[1] Nb = I_F.shape[2] max_val = 1 if not isinstance(I_PAN, torch.Tensor): I_F = torch.from_numpy(I_F/max_val).permute(2, 0, 1).float()*max_val I_MS = torch.from_numpy(I_MS / max_val).permute(2, 0, 1).float() * max_val I_MS_LR = torch.from_numpy(I_MS_LR / max_val).permute(2, 0, 1).float() * max_val I_PAN = torch.from_numpy(I_PAN / max_val)[..., 0].float() if (flag_orig_paper == 0): """Opt. 1 (as toolbox 1.0)""" pan_filt = interp23(imresize(I_PAN, 1 / ratio), ratio) else: """ Opt. 2 (as paper QNR) """ pan_filt = imresize(I_PAN, 1 / ratio) pan_filt = torch.from_numpy(pan_filt / max_val).unsqueeze(0).float() I_PAN = I_PAN.unsqueeze(0) Q_high, Q_high_map = uqi_ssim(I_F, I_PAN, Nb, win_size=S) if (flag_orig_paper == 0): """ Opt. 1 (as toolbox 1.0) """ Q_low, Q_low_map = uqi_ssim(I_MS, pan_filt, Nb, win_size=S) else: """ Opt. 2 (as paper QNR) """ Q_low, Q_low_map = uqi_ssim(I_MS_LR, pan_filt, Nb, win_size=S) D_s_index = np.abs(Q_high - Q_low) ** q D_s_map = np.abs(Q_high_map - Q_low_map) ** q D_s_index = D_s_index.sum() D_s_index = (D_s_index / Nb) ** (1 / q) D_s_map = (D_s_map / Nb) ** (1 / q) return D_s_index.item(), D_s_map.numpy().transpose([1, 2, 0]) def uqi_ssim(x, y, Nb, win_size): # cov_norm = win_size**2 / (win_size**2 - 1) window_ms = create_window(win_size, Nb) / (win_size**2) window_pan = create_window(win_size, 1) / (win_size**2) mu1 = F.conv2d(x, window_ms, groups=Nb, stride=win_size) mu2 = F.conv2d(y, window_pan, stride=win_size) mu1_sq = mu1.pow(2) mu2_sq = mu2.pow(2) mu1_mu2 = mu1 * mu2 # 点乘产生误差 sigma1_sq = F.conv2d(x * x, window_ms, groups=Nb, stride=win_size) - mu1_sq # 点乘产生误差 sigma2_sq = F.conv2d(y * y, window_pan, stride=win_size) - mu2_sq sigma12 = F.conv2d(x * y, window_ms, groups=Nb, stride=win_size) - mu1_mu2 # 点乘产生误差 V1 = 2.0 * sigma12 # * cov_norm V2 = sigma1_sq + sigma2_sq Q = (2 * V1 * mu1_mu2) / (V2 * (mu1_sq + mu2_sq)) return Q.mean(1).mean(1), Q def cov(x, y): cov_xy = torch.matmul(x.transpose(-2, -1), y) / x.shape[-2] cov_yx = torch.matmul(y.transpose(-2, -1), x) / y.shape[-2] std_x = x.var(-2, keepdims=True) std_y = y.var(-2, keepdims=True) # print(cov_xy.shape, cov_yx.shape, std_x.shape, std_y.shape) return torch.cat([std_x, cov_xy, cov_yx, std_y], dim=-2) def uqi(x, y, Nb, win_size): C, H, W = x.shape x = F.unfold(x, kernel_size=win_size, stride=win_size) x = x.permute(1, 0).reshape(-1, C, win_size**2, 1) y = F.unfold(y, kernel_size=win_size, stride=win_size) y = y.permute(1, 0).reshape(-1, win_size**2, 1) num_patches = y.shape[0] # print(x.shape, y.shape, mx.shape, my.shape) Q = torch.zeros([num_patches, C]) for ii in range(Nb): xx = x[:, ii, ...]#.unsqueeze(1) mx = xx.mean(-2, keepdims=True) my = y.mean(-2, keepdims=True) # print(xx.shape, y.shape, mx.shape, my.shape) C = cov(xx-mx, y-my) # print(C.shape) C = C.reshape(num_patches, 2, 2) Q[:, ii, ...] = (4 * C[:, 0, 1] * mx[:, 0, 0]*my[:, 0, 0]) / ((C[:, 0, 0] + C[:, 1, 1]) * (mx[:, 0, 0]**2 + my[:, 0, 0]**2)) return Q.mean(0)
294coder/Efficient-MIF
3,021
utils/sharpening_index/interp23.py
# -*- coding: utf-8 -*- """ Copyright (c) 2020 Vivone Gemine. All rights reserved. This work should only be used for nonprofit purposes. @author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home ) """ """ Description: interp23 interpolates the image I_Interpolated using a polynomial with 23 coefficients interpolator. Interface: image = interp23(image,ratio) Inputs: image: Image to interpolate; ratio: Scale ratio between MS and PAN. Pre-condition: Resize factors power of 2. Outputs: image: Interpolated image. References: G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021. G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021. """ import numpy as np from scipy import ndimage def interp23(image, ratio): if (2**round(np.log2(ratio)) != ratio): print("Error: only resize factors of power 2") return -1 r = image.shape[0] c = image.shape[1] if (np.size(image.shape) == 3): b = image.shape[2] else: b = 1 CDF23 = 2*np.array([0.5, 0.305334091185, 0, -0.072698593239, 0, 0.021809577942, 0, -0.005192756653, 0, 0.000807762146, 0, -0.000060081482]) d = CDF23[::-1] CDF23 = np.insert(CDF23, 0, d[:-1]) BaseCoeff = CDF23 first = 1 for z in range(1, int(np.log2(ratio))+1): if (b == 1): I1LRU = np.zeros(((2**z)*r, (2**z)*c)) else: I1LRU = np.zeros(((2**z)*r, (2**z)*c, b)) if first: if (b == 1): I1LRU[1:I1LRU.shape[0]:2,1:I1LRU.shape[1]:2]=image else: I1LRU[1:I1LRU.shape[0]:2,1:I1LRU.shape[1]:2,:]=image first = 0 else: if (b == 1): I1LRU[0:I1LRU.shape[0]:2,0:I1LRU.shape[1]:2]=image else: I1LRU[0:I1LRU.shape[0]:2,0:I1LRU.shape[1]:2,:]=image for ii in range(b): if (b == 1): t = I1LRU else: t = I1LRU[:,:,ii] for j in range(0,t.shape[0]): t[j,:]=ndimage.correlate(t[j,:],BaseCoeff,mode='wrap') for k in range(0,t.shape[1]): t[:,k]=ndimage.correlate(t[:,k],BaseCoeff,mode='wrap') if (b == 1): I1LRU = t else: I1LRU[:,:,ii] = t image = I1LRU return image
281677160/openwrt-package
1,317
luci-app-nginx-pingos/modules/nginx-toolkit-module/COPYRIGHT
Copyright (C) 2016-2020, by Jie Wu "AlexWoo" <[email protected]>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
294coder/Efficient-MIF
2,295
utils/sharpening_index/D_lambda_K.py
# GPL License # Copyright (C) UESTC # All Rights Reserved # @Author : Xiao Wu # @reference: # -*- coding: utf-8 -*- """ Copyright (c) 2020 Vivone Gemine. All rights reserved. This work should only be used for nonprofit purposes. @author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home ) """ """ Description: Spectral distorsion index Interface: Dl = D_lambda_K(fused,ms,ratio,sensor,S) Inputs: fused: Pansharpened image; ms: Original MS image; ratio: Scale ratio between MS and PAN. Pre-condition: Integer value; sensor: String for type of sensor (e.g. 'WV2','IKONOS'); S: Block size. Output: Dl: Spectral distorsion index. References: G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021. G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021. """ from .MTF import MTF # from .q2n import q2n from .my_q2n import q2n def D_lambda_K(fused,ms,ratio,sensor,S): if (fused.shape[0] != (ms.shape[0]) or fused.shape[1] != ms.shape[1]) == 1: print("The two images must have the same dimensions") return -1 # N = fused.shape[0] # M = fused.shape[1] # if np.remainder(N,S-1) != 0: # print("Number of rows must be multiple of the block size") # return -1 # if np.remainder(M,S-1) != 0: # print("Number of columns must be multiple of the block size") # return -1 fused_degraded = MTF(fused,sensor,ratio) # fused_degraded = fused_degraded[int(ratio/2):-1:int(ratio),int(ratio/2):-1:int(ratio),:] Q2n_index, q2n_map = q2n(ms, fused_degraded, S, S) Dl = 1 - Q2n_index Dl_map = 1 - q2n_map return Dl, Dl_map
281677160/openwrt-package
6,560
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_map.c
/* * Copyright (C) AlexWoo(Wu Jie) [email protected] */ #include "ngx_map.h" static void ngx_map_rbtree_insert_value(ngx_rbtree_node_t *temp, ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel) { ngx_rbtree_node_t **p; intptr_t *raw_key, *raw_key_temp; ngx_map_t **map; for (;;) { if (node->key < temp->key) { p = &temp->left; } else if (node->key > temp->key) { p = &temp->right; } else { raw_key = (intptr_t *)((char *) node + offsetof(ngx_map_node_t, raw_key)); raw_key_temp = (intptr_t *)((char *) temp + offsetof(ngx_map_node_t, raw_key)); map = (ngx_map_t **)((char *) node + offsetof(ngx_map_node_t, map)); switch ((*map)->cmp(*raw_key, *raw_key_temp)) { case -1: p = &temp->left; break; case 1: p = &temp->right; break; default: /* key is duplicate */ return; } } if (*p == sentinel) { break; } temp = *p; } *p = node; node->parent = temp; node->left = sentinel; node->right = sentinel; ngx_rbt_red(node); } void ngx_map_init(ngx_map_t *map, ngx_map_hash_pt hash, ngx_cmp_pt cmp) { ngx_rbtree_init(&map->rbtree, &map->sentinel, ngx_map_rbtree_insert_value); map->hash = hash; map->cmp = cmp; } ngx_map_node_t * ngx_map_begin(ngx_map_t *map) { ngx_rbtree_node_t *p; if (ngx_map_empty(map)) { return NULL; } p = map->rbtree.root; for (;;) { if (p->left == map->rbtree.sentinel) { break; } p = p->left; } return (ngx_map_node_t *) p; } ngx_map_node_t * ngx_map_rbegin(ngx_map_t *map) { ngx_rbtree_node_t *p; if (ngx_map_empty(map)) { return NULL; } p = map->rbtree.root; for (;;) { if (p->right == map->rbtree.sentinel) { break; } p = p->right; } return (ngx_map_node_t *) p; } ngx_map_node_t * ngx_map_next(ngx_map_node_t *n) { ngx_map_t *map; ngx_rbtree_node_t *p, *top; map = n->map; p = &n->rn; top = NULL; if (p->right != map->rbtree.sentinel) { // current node has right subtree top = p->right; } else { for (;;) { if (p == map->rbtree.root) { return NULL; } if (p->parent->left == p) { return (ngx_map_node_t *) p->parent; } // p->parent->right == p p = p->parent; } } // get the mininum node p = top; for (;;) { if (p->left == map->rbtree.sentinel) { break; } p = p->left; } return (ngx_map_node_t *) p; } ngx_map_node_t * ngx_map_prev(ngx_map_node_t *n) { ngx_map_t *map; ngx_rbtree_node_t *p, *top; map = n->map; p = &n->rn; top = NULL; if (p->left != map->rbtree.sentinel) { // current node has left subtree top = p->left; } else { for (;;) { if (p == map->rbtree.root) { return NULL; } if (p->parent->right == p) { return (ngx_map_node_t *) p->parent; } // p->parent->left == p p = p->parent; } } // get the maximum node p = top; for (;;) { if (p->right == map->rbtree.sentinel) { break; } p = p->right; } return (ngx_map_node_t *) p; } void ngx_map_insert(ngx_map_t *map, ngx_map_node_t *node, ngx_flag_t covered) { ngx_map_node_t *n; node->rn.key = map->hash(node->raw_key); node->map = map; n = ngx_map_find(map, node->raw_key); if (n == NULL) { ngx_rbtree_insert(&map->rbtree, &node->rn); } else if (covered) { ngx_map_delete(map, node->raw_key); ngx_rbtree_insert(&map->rbtree, &node->rn); } } void ngx_map_delete(ngx_map_t *map, intptr_t key) { ngx_map_node_t *node; node = ngx_map_find(map, key); if (node) { ngx_rbtree_delete(&map->rbtree, &node->rn); } } ngx_map_node_t * ngx_map_find(ngx_map_t *map, intptr_t key) { ngx_rbtree_node_t *p; ngx_rbtree_key_t k; intptr_t *key_temp; if (ngx_map_empty(map)) { return NULL; } k = map->hash(key); p = map->rbtree.root; for (;;) { if (k < p->key) { p = p->left; } else if (k > p->key) { p = p->right; } else { key_temp = (intptr_t *)((char *) p + offsetof(ngx_map_node_t, raw_key)); switch (map->cmp(key, *key_temp)) { case -1: p = p->left; break; case 1: p = p->right; break; case 0: return (ngx_map_node_t *) p; } } if (p == map->rbtree.sentinel) { return NULL; } } } /* ngx_str_t */ ngx_rbtree_key_t ngx_map_hash_str(intptr_t key) { ngx_str_t *k; k = (ngx_str_t *) key; return ngx_hash_key(k->data, k->len); } int ngx_cmp_str(intptr_t key1, intptr_t key2) { ngx_str_t *k1, *k2; ngx_int_t rc; k1 = (ngx_str_t *) key1; k2 = (ngx_str_t *) key2; rc = ngx_memn2cmp(k1->data, k2->data, k1->len, k2->len); if (rc < 0) { return -1; } else if (rc > 0) { return 1; } else { return 0; } } /* ngx_uint_t */ ngx_rbtree_key_t ngx_map_hash_uint(intptr_t key) { return (ngx_rbtree_key_t) key; } int ngx_cmp_uint(intptr_t key1, intptr_t key2) { if ((ngx_uint_t) key1 < (ngx_uint_t) key2) { return -1; } else if ((ngx_uint_t) key1 > (ngx_uint_t) key2) { return 1; } else { return 0; } } /* ngx_int_t */ ngx_rbtree_key_t ngx_map_hash_int(intptr_t key) { return (ngx_rbtree_key_t) key; } int ngx_cmp_int(intptr_t key1, intptr_t key2) { if ((ngx_int_t) key1 < (ngx_int_t) key2) { return -1; } else if ((ngx_int_t) key1 > (ngx_int_t) key2) { return 1; } else { return 0; } }
294coder/Efficient-MIF
2,167
utils/sharpening_index/MTF.py
# -*- coding: utf-8 -*- """ Copyright (c) 2020 Vivone Gemine. All rights reserved. This work should only be used for nonprofit purposes. @author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home ) """ """ Description: MTF filters the image I_MS using a Gaussin filter matched with the Modulation Transfer Function (MTF) of the MultiSpectral (MS) sensor. Interface: I_Filtered = MTF(I_MS,sensor,ratio) Inputs: I_MS: MS image; sensor: String for type of sensor (e.g. 'WV2', 'IKONOS'); ratio: Scale ratio between MS and PAN. Outputs: I_Filtered: Output filtered MS image. Notes: The bottleneck of this function is the function scipy.filters.correlate that gets the same results as in the MATLAB toolbox but it is very slow with respect to fftconvolve that instead gets slightly different results References: G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021. G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021. """ from scipy import ndimage import numpy as np from .genMTF import genMTF def MTF(I_MS,sensor,ratio): h = genMTF(ratio, sensor,I_MS.shape[2]) I_MS_LP = np.zeros((I_MS.shape)) for ii in range(I_MS.shape[2]): I_MS_LP[:,:,ii] = ndimage.filters.correlate(I_MS[:,:,ii],h[:,:,ii],mode='nearest') ### This can speed-up the processing, but with slightly different results with respect to the MATLAB toolbox # hb = h[:,:,ii] # I_MS_LP[:,:,ii] = signal.fftconvolve(I_MS[:,:,ii],hb[::-1],mode='same') return np.double(I_MS_LP)