+ const html = `
${Slider.capitalizeFirstLetter(this._sliderLabel)} ${this._sliderDefaultValue}
`;
return html;
-
}
static capitalizeFirstLetter(string) {
@@ -144,5 +139,4 @@ class Slider {
set sliderDefaultValue(value) {
this._sliderDefaultValue = value;
}
-
}
diff --git a/apps/viewer/dataloaders.js b/apps/viewer/dataloaders.js
index 7899a7ef8..e719d4919 100644
--- a/apps/viewer/dataloaders.js
+++ b/apps/viewer/dataloaders.js
@@ -2,131 +2,128 @@
//
// function SlideDataLoader(){
-// function loadingSlideInfo(){
-
-// }
-// var checkCoreIsReady = setInterval(function () {
-// if($CAMIC) {
-// clearInterval(checkCoreIsReady);
-// //load data
-// loadingSlideInfo();
-// }
-// }, 1000);
+// function loadingSlideInfo(){
+
+// }
+// var checkCoreIsReady = setInterval(function () {
+// if($CAMIC) {
+// clearInterval(checkCoreIsReady);
+// //load data
+// loadingSlideInfo();
+// }
+// }, 1000);
// }
-function FormTempaltesLoader(){
-
- function loadingFormTemplates(){
-
- $CAMIC.store.findTemplate()
- //
- .then(function(temps){
- // get templates data
- $D.templates = temps;
- })
- //
- .catch(function(error){
- // templates schema
-
- console.error(error);
- })
- //
- .finally(function(){
- if($D.templates){
- // load UI
- }else{
- // set message
- $UI.message.addError('Loading Templates is Error');
-
- }
- });
- }
-
- var checkCoreIsReady = setInterval(function () {
- if($CAMIC) {
- clearInterval(checkCoreIsReady);
- //load data
- loadingFormTemplates();
- }
- }, 500);
+function FormTempaltesLoader() {
+ function loadingFormTemplates() {
+ $CAMIC.store.findTemplate()
+ //
+ .then(function(temps) {
+ // get templates data
+ $D.templates = temps;
+ })
+ //
+ .catch(function(error) {
+ // templates schema
+
+ console.error(error);
+ })
+ //
+ .finally(function() {
+ if ($D.templates) {
+ // load UI
+ } else {
+ // set message
+ $UI.message.addError('Loading Templates is Error');
+ }
+ });
+ }
+
+ var checkCoreIsReady = setInterval(function() {
+ if ($CAMIC) {
+ clearInterval(checkCoreIsReady);
+ // load data
+ loadingFormTemplates();
+ }
+ }, 500);
}
let _l = false;
-function OverlayersLoader(){
- function loadingOverlayers(){
- $CAMIC.store.findMarkTypes($D.params.slideId)
- //
- .then(function(layers){
- typeIds = {};
- if(!$D.overlayers) $D.overlayers = [];
- // convert part not nesscary
- for(let i = 0 ;i < layers.length;i++){
- $D.overlayers.push(covertToLayViewer(layers[i]));
- }
- _l = true;
-
- })
- //
- .catch(function(error){
- // overlayers schema
-
- console.error(error);
- })
- //
- .finally(function(){
- if($D.overlayers){
-
- }else{
- // set message
- $UI.message.addError('Loading Overlayers is Error');
-
- }
- });
- }
-
- var checkCoreIsReady = setInterval(function () {
- if($CAMIC && $D.params.data) {
- clearInterval(checkCoreIsReady);
- //load data
- loadingOverlayers();
- }
- }, 500);
+function OverlayersLoader() {
+ function loadingOverlayers() {
+ $CAMIC.store.findMarkTypes($D.params.slideId)
+ //
+ .then(function(layers) {
+ typeIds = {};
+ if (!$D.overlayers) $D.overlayers = [];
+ // convert part not nesscary
+ for (let i = 0; i < layers.length; i++) {
+ $D.overlayers.push(covertToLayViewer(layers[i]));
+ }
+ _l = true;
+ })
+ //
+ .catch(function(error) {
+ // overlayers schema
+
+ console.error(error);
+ })
+ //
+ .finally(function() {
+ if ($D.overlayers) {
+
+ } else {
+ // set message
+ $UI.message.addError('Loading Overlayers is Error');
+ }
+ });
+ }
+
+ var checkCoreIsReady = setInterval(function() {
+ if ($CAMIC && $D.params.data) {
+ clearInterval(checkCoreIsReady);
+ // load data
+ loadingOverlayers();
+ }
+ }, 500);
}
let _h = false; // loading heatmap
-function HeatmaplayersLoader(){
- function loadingHeatmapOverlayers(){
- $CAMIC.store.findHeatmapType($D.params.slideId)
- //
- .then(function(layers){
- if(!$D.overlayers)$D.overlayers = [];
- // convert and load heatmap layer
- const TypeId = randomId();
- for(let i = 0 ;i < layers.length;i++){
- const item = layers[i].provenance.analysis;
- $D.overlayers.push({id:item.execution_id,name:item.execution_id,typeId:TypeId,typeName:item.computation});
- }
- _h = true;
- })
- .catch(function(error){
- // overlayers schema
-
- console.error(error);
- })
- //
- .finally(function(){
- if($D.overlayers){
- }else{
- // set message
- $UI.message.addError('Loading heatmap Overlayers is Error');
-
- }
- });
- }
-
- var checkCoreIsReady = setInterval(function () {
- if($CAMIC && $D.params.data) {
- clearInterval(checkCoreIsReady);
- //load data
- loadingHeatmapOverlayers();
- }
- }, 500);
+function HeatmaplayersLoader() {
+ function loadingHeatmapOverlayers() {
+ $CAMIC.store.findHeatmapType($D.params.slideId)
+ //
+ .then(function(layers) {
+ if (!$D.overlayers)$D.overlayers = [];
+ // convert and load heatmap layer
+ const TypeId = randomId();
+ for (let i = 0; i < layers.length; i++) {
+ const item = layers[i].provenance.analysis;
+ $D.overlayers.push({id: item.execution_id,
+ name: item.execution_id,
+ typeId: TypeId,
+ typeName: item.computation});
+ }
+ _h = true;
+ })
+ .catch(function(error) {
+ // overlayers schema
+
+ console.error(error);
+ })
+ //
+ .finally(function() {
+ if ($D.overlayers) {
+ } else {
+ // set message
+ $UI.message.addError('Loading heatmap Overlayers is Error');
+ }
+ });
+ }
+
+ var checkCoreIsReady = setInterval(function() {
+ if ($CAMIC && $D.params.data) {
+ clearInterval(checkCoreIsReady);
+ // load data
+ loadingHeatmapOverlayers();
+ }
+ }, 500);
}
diff --git a/apps/viewer/init.js b/apps/viewer/init.js
index eab3d80c0..67fbb5fd8 100644
--- a/apps/viewer/init.js
+++ b/apps/viewer/init.js
@@ -2,7 +2,7 @@
// $CAMIC in there
let $CAMIC = null;
let tracker;
-let $minorCAMIC = {};
+const $minorCAMIC = {};
// for all instances of UI components
const $UI = new Map();
@@ -356,17 +356,16 @@ const $UI = new Map();
const $D = {
pages: {
- home: "../table.html",
- table: "../table.html"
+ home: '../table.html',
+ table: '../table.html',
},
params: null, // parameter from url - slide Id and status in it (object).
overlayers: null, // array for each layers
templates: null, // json schema for prue-form
- segments: []
+ segments: [],
};
-window.addEventListener("keydown", e => {
-
+window.addEventListener('keydown', (e) => {
if (!$CAMIC || !$CAMIC.viewer) return;
const keyCode = e.keyCode;
// escape key to close all operations
@@ -378,34 +377,34 @@ window.addEventListener("keydown", e => {
// open annotation (ctrl + a)
if (e.ctrlKey && keyCode == 65 && $CAMIC.viewer.canvasDrawInstance) {
- const li = $UI.toolbar.getSubTool("annotation");
- eventFire(li, "click");
+ const li = $UI.toolbar.getSubTool('annotation');
+ eventFire(li, 'click');
return;
}
// open magnifier (ctrl + m)
if (e.ctrlKey && keyCode == 77 && $UI.spyglass) {
- const li = $UI.toolbar.getSubTool("magnifier");
- const chk = li.querySelector("input[type=checkbox]");
+ const li = $UI.toolbar.getSubTool('magnifier');
+ const chk = li.querySelector('input[type=checkbox]');
chk.checked = !chk.checked;
- eventFire(chk, "change");
+ eventFire(chk, 'change');
return;
}
// open measurement (ctrl + r)
if (e.ctrlKey && keyCode == 82 && $CAMIC.viewer.measureInstance) {
e.preventDefault();
- const li = $UI.toolbar.getSubTool("measurement");
- const chk = li.querySelector("input[type=checkbox]");
+ const li = $UI.toolbar.getSubTool('measurement');
+ const chk = li.querySelector('input[type=checkbox]');
chk.checked = !chk.checked;
- eventFire(chk, "click");
+ eventFire(chk, 'click');
return;
}
// open side-by-side (ctrl + s)
if (e.ctrlKey && keyCode == 83) {
e.preventDefault();
- const li = $UI.toolbar.getSubTool("sbsviewer");
- const chk = li.querySelector("input[type=checkbox]");
+ const li = $UI.toolbar.getSubTool('sbsviewer');
+ const chk = li.querySelector('input[type=checkbox]');
chk.checked = !chk.checked;
- eventFire(chk, "click");
+ eventFire(chk, 'click');
return;
}
});
@@ -444,42 +443,42 @@ function initCore() {
btns: [
{
// annotation
- type: "btn",
- title: "Annotation",
- class: "material-icons",
- text: "description",
- callback: saveAnnotation
+ type: 'btn',
+ title: 'Annotation',
+ class: 'material-icons',
+ text: 'description',
+ callback: saveAnnotation,
},
{
// analytics
- type: "btn",
- title: "Analytics",
- class: "material-icons",
- text: "settings_backup_restore",
- callback: saveAnalytics
- }
- ]
- }
+ type: 'btn',
+ title: 'Analytics',
+ class: 'material-icons',
+ text: 'settings_backup_restore',
+ callback: saveAnalytics,
+ },
+ ],
+ },
};
// set states if exist
if ($D.params.states) {
opt.states = $D.params.states;
}
// pathdb home directly
- if ($D.params.mode == "pathdb") {
- $D.pages.home = "../../../";
- $D.pages.table = "../../../";
+ if ($D.params.mode == 'pathdb') {
+ $D.pages.home = '../../../';
+ $D.pages.table = '../../../';
}
try {
- let slideQuery = {};
+ const slideQuery = {};
slideQuery.id = $D.params.slideId;
slideQuery.name = $D.params.slide;
slideQuery.location = $D.params.location;
- $CAMIC = new CaMic("main_viewer", slideQuery, opt);
+ $CAMIC = new CaMic('main_viewer', slideQuery, opt);
} catch (error) {
Loading.close();
- $UI.message.addError("Core Initialization Failed");
+ $UI.message.addError('Core Initialization Failed');
console.error(error);
return;
}
@@ -493,7 +492,7 @@ function initCore() {
} else {
$D.params.data = e;
// popup panel
- $CAMIC.viewer.addHandler("canvas-lay-click", function(e) {
+ $CAMIC.viewer.addHandler('canvas-lay-click', function(e) {
if (!e.data) {
$UI.annotPopup.close();
return;
@@ -506,7 +505,7 @@ function initCore() {
let attributes;
let warning = null;
switch (type) {
- case "human":
+ case 'human':
let area;
let circumference;
if (data.geometries) {
@@ -514,19 +513,21 @@ function initCore() {
(data.selected != null || data.selected != undefined) &&
data.geometries.features[data.selected] &&
data.geometries.features[data.selected].properties.area
- )
+ ) {
area = `${Math.round(
- data.geometries.features[data.selected].properties.area
+ data.geometries.features[data.selected].properties.area,
)}μm^2`;
+ }
if (
(data.selected != null || data.selected != undefined) &&
data.geometries.features[data.selected] &&
data.geometries.features[data.selected].properties.circumference
- )
+ ) {
circumference = `${Math.round(
- data.geometries.features[data.selected].properties
- .circumference
+ data.geometries.features[data.selected].properties
+ .circumference,
)}μm`;
+ }
} // othereise, don't try to calculate area and circumference
// human
@@ -549,10 +550,10 @@ function initCore() {
$UI.annotPopup.showFooter();
break;
- case "computer":
+ case 'computer':
// handle data.provenance.analysis.computation = `segmentation`
attributes = data.properties.scalar_features[0].nv;
- body = { type: "map", data: attributes };
+ body = {type: 'map', data: attributes};
$UI.annotPopup.hideFooter();
break;
default:
@@ -564,7 +565,7 @@ function initCore() {
id: data.provenance.analysis.execution_id,
oid: data._id.$oid,
annotation: attributes,
- selected: e.data.selected
+ selected: e.data.selected,
};
$UI.annotPopup.setTitle(`id:${data.provenance.analysis.execution_id}`);
$UI.annotPopup.setBody(body);
@@ -576,21 +577,21 @@ function initCore() {
// create the message bar TODO for reading slide Info TODO
$UI.slideInfos = new CaMessage({
/* opts that need to think of*/
- id: "cames",
- defaultText: `Slide: ${$D.params.data.name}`
+ id: 'cames',
+ defaultText: `Slide: ${$D.params.data.name}`,
});
// spyglass
$UI.spyglass = new Spyglass({
targetViewer: $CAMIC.viewer,
- imgsrc: $D.params.data.url
+ imgsrc: $D.params.data.url,
});
}
});
- $CAMIC.viewer.addHandler("open", function() {
- $CAMIC.viewer.canvasDrawInstance.addHandler("start-drawing", startDrawing);
- $CAMIC.viewer.canvasDrawInstance.addHandler("stop-drawing", stopDrawing);
+ $CAMIC.viewer.addHandler('open', function() {
+ $CAMIC.viewer.canvasDrawInstance.addHandler('start-drawing', startDrawing);
+ $CAMIC.viewer.canvasDrawInstance.addHandler('stop-drawing', stopDrawing);
// init UI -- some of them need to wait data loader to load data
// because UI components need data to initialize
initUIcomponents();
@@ -605,30 +606,31 @@ async function initUIcomponents() {
/* create UI components */
$UI.modalbox = new ModalBox({
- id: "modalbox",
+ id: 'modalbox',
hasHeader: true,
- headerText: "HeatMap List",
- hasFooter: false
+ headerText: 'HeatMap List',
+ hasFooter: false,
});
const subToolsOpt = [];
// home
- if (ImgloaderMode == "iip")
+ if (ImgloaderMode == 'iip') {
subToolsOpt.push({
- name: "home",
- icon: "home", // material icons' name
- title: "Home",
- type: "btn", // btn/check/dropdown
- value: "home",
- callback: goHome
+ name: 'home',
+ icon: 'home', // material icons' name
+ title: 'Home',
+ type: 'btn', // btn/check/dropdown
+ value: 'home',
+ callback: goHome,
});
+ }
// pen
subToolsOpt.push({
- name: "annotation",
- icon: "create", // material icons' name
- title: "Draw",
- type: "multistates",
- callback: draw
+ name: 'annotation',
+ icon: 'create', // material icons' name
+ title: 'Draw',
+ type: 'multistates',
+ callback: draw,
});
// example for dropdownlist has icon in each item
@@ -680,178 +682,180 @@ async function initUIcomponents() {
// });
$D.preset_list = null;
- $D.preset_list = await $CAMIC.store.getConfigByName('preset_label').then(list=>list.length==0?null:list[0]);
- if($D.preset_list){
- subToolsOpt.push({
- name: "preset_label",
- icon: "colorize", // material icons' name
- title: "Preset Labels",
- type: "multi-dropdown",
- value: "prelabels",
- callback: drawLabel,
- dropdownList: $D.preset_list.configuration
- });
-}
+ $D.preset_list = await $CAMIC.store.getConfigByName('preset_label').then((list)=>list.length==0?null:list[0]);
+ if ($D.preset_list) {
+ subToolsOpt.push({
+ name: 'preset_label',
+ icon: 'colorize', // material icons' name
+ title: 'Preset Labels',
+ type: 'multi-dropdown',
+ value: 'prelabels',
+ callback: drawLabel,
+ dropdownList: $D.preset_list.configuration,
+ });
+ }
// magnifier
subToolsOpt.push({
- name: "magnifier",
- icon: "search",
- title: "Magnifier",
- type: "dropdown",
- value: "magn",
+ name: 'magnifier',
+ icon: 'search',
+ title: 'Magnifier',
+ type: 'dropdown',
+ value: 'magn',
dropdownList: [
{
value: 0.5,
- title: "0.5",
- checked: true
+ title: '0.5',
+ checked: true,
},
{
value: 1,
- title: "1.0"
+ title: '1.0',
},
{
value: 2,
- title: "2.0"
- }
+ title: '2.0',
+ },
],
- callback: toggleMagnifier
+ callback: toggleMagnifier,
});
// measurement tool
- if ($CAMIC.viewer.measureInstance)
+ if ($CAMIC.viewer.measureInstance) {
subToolsOpt.push({
- name: "measurement",
- icon: "space_bar",
- title: "Measurement",
- type: "check",
- value: "measure",
- callback: toggleMeasurement
+ name: 'measurement',
+ icon: 'space_bar',
+ title: 'Measurement',
+ type: 'check',
+ value: 'measure',
+ callback: toggleMeasurement,
});
+ }
// share
- if (ImgloaderMode == "iip")
+ if (ImgloaderMode == 'iip') {
subToolsOpt.push({
- name: "share",
- icon: "share",
- title: "Share View",
- type: "btn",
- value: "share",
- callback: shareURL
+ name: 'share',
+ icon: 'share',
+ title: 'Share View',
+ type: 'btn',
+ value: 'share',
+ callback: shareURL,
});
+ }
// side-by-side
subToolsOpt.push({
- name: "sbsviewer",
- icon: "view_carousel",
- title: "Side By Side Viewer",
- value: "dbviewers",
- type: "check",
- callback: toggleViewerMode
+ name: 'sbsviewer',
+ icon: 'view_carousel',
+ title: 'Side By Side Viewer',
+ value: 'dbviewers',
+ type: 'check',
+ callback: toggleViewerMode,
});
// heatmap
subToolsOpt.push({
- name: "heatmap",
- icon: "satellite",
- title: "Heat Map",
- value: "heatmap",
- type: "btn",
- callback: openHeatmap
+ name: 'heatmap',
+ icon: 'satellite',
+ title: 'Heat Map',
+ value: 'heatmap',
+ type: 'btn',
+ callback: openHeatmap,
});
subToolsOpt.push({
- name: "labeling",
- icon: "label",
- title: "Labeling",
- value: "labeling",
- type: "btn",
+ name: 'labeling',
+ icon: 'label',
+ title: 'Labeling',
+ value: 'labeling',
+ type: 'btn',
callback: function() {
window.location.href = `../labeling/labeling.html${window.location.search}`;
- }
+ },
});
subToolsOpt.push({
- name: "segment",
- icon: "timeline",
- type: "btn",
- value: "rect",
- title: "Segment",
+ name: 'segment',
+ icon: 'timeline',
+ type: 'btn',
+ value: 'rect',
+ title: 'Segment',
callback: function() {
if (window.location.search.length > 0) {
window.location.href =
- "../segment/segment.html" + window.location.search;
+ '../segment/segment.html' + window.location.search;
} else {
- window.location.href = "../segment/segment.html";
+ window.location.href = '../segment/segment.html';
}
- }
+ },
});
subToolsOpt.push({
- name: "model",
- icon: "aspect_ratio",
- type: "btn",
- value: "rect",
- title: "Predict",
+ name: 'model',
+ icon: 'aspect_ratio',
+ type: 'btn',
+ value: 'rect',
+ title: 'Predict',
callback: function() {
if (window.location.search.length > 0) {
- window.location.href = "../model/model.html" + window.location.search;
+ window.location.href = '../model/model.html' + window.location.search;
} else {
- window.location.href = "../model/model.html";
+ window.location.href = '../model/model.html';
}
- }
+ },
});
// -- For Nano borb Start -- //
- if (ImgloaderMode == "imgbox") {
+ if (ImgloaderMode == 'imgbox') {
// download
subToolsOpt.push({
- name: "downloadmarks",
- icon: "cloud_download",
- title: "Download Marks",
- type: "btn",
- value: "download",
- callback: Store.prototype.DownloadMarksToFile
+ name: 'downloadmarks',
+ icon: 'cloud_download',
+ title: 'Download Marks',
+ type: 'btn',
+ value: 'download',
+ callback: Store.prototype.DownloadMarksToFile,
});
subToolsOpt.push({
- name: "uploadmarks",
- icon: "cloud_upload",
- title: "Load Marks",
- type: "btn",
- value: "upload",
- callback: Store.prototype.LoadMarksFromFile
+ name: 'uploadmarks',
+ icon: 'cloud_upload',
+ title: 'Load Marks',
+ type: 'btn',
+ value: 'upload',
+ callback: Store.prototype.LoadMarksFromFile,
});
}
// -- For Nano borb End -- //
// bug report
subToolsOpt.push({
- name: "bugs",
- icon: "bug_report",
- title: "Bug Report",
- value: "bugs",
- type: "btn",
+ name: 'bugs',
+ icon: 'bug_report',
+ title: 'Bug Report',
+ value: 'bugs',
+ type: 'btn',
callback: () => {
- window.open("https://goo.gl/forms/mgyhx4ADH0UuEQJ53", "_blank").focus();
- }
+ window.open('https://goo.gl/forms/mgyhx4ADH0UuEQJ53', '_blank').focus();
+ },
});
// create the tool bar
$UI.toolbar = new CaToolbar({
/* opts that need to think of*/
- id: "ca_tools",
+ id: 'ca_tools',
zIndex: 601,
mainToolsCallback: mainMenuChange,
- subTools: subToolsOpt
+ subTools: subToolsOpt,
});
// create two side menus for tools
$UI.appsSideMenu = new SideMenu({
- id: "side_apps",
+ id: 'side_apps',
width: 300,
- //, isOpen:true
- callback: toggleSideMenu
+ // , isOpen:true
+ callback: toggleSideMenu,
});
$UI.layersSideMenu = new SideMenu({
- id: "side_layers",
+ id: 'side_layers',
width: 300,
contentPadding: 5,
- //, isOpen:true
- callback: toggleSideMenu
+ // , isOpen:true
+ callback: toggleSideMenu,
});
const loading = `
`;
$UI.layersSideMenu.addContent(loading);
@@ -866,12 +870,12 @@ async function initUIcomponents() {
// },
{
// delete
- title: "Delete",
- class: "material-icons",
- text: "delete_forever",
- callback: anno_delete
- }
- ]
+ title: 'Delete',
+ class: 'material-icons',
+ text: 'delete_forever',
+ callback: anno_delete,
+ },
+ ],
});
var checkOverlaysDataReady = setInterval(function() {
@@ -889,101 +893,101 @@ async function initUIcomponents() {
$CAMIC.viewer.createSegment({
store: $CAMIC.store,
slide: $D.params.data.slide,
- data: []
+ data: [],
});
// create control
// create main layer viewer items with states
- const mainViewerData = $D.overlayers.map(d => {
+ const mainViewerData = $D.overlayers.map((d) => {
const isShow =
$D.params.states &&
$D.params.states.l &&
- $D.params.states.l.includes(d.id)
- ? true
- : false;
- return { item: d, isShow: isShow };
+ $D.params.states.l.includes(d.id) ?
+ true :
+ false;
+ return {item: d, isShow: isShow};
});
// create monir layer viewer items
- const minorViewerData = $D.overlayers.map(d => {
- return { item: d, isShow: false };
+ const minorViewerData = $D.overlayers.map((d) => {
+ return {item: d, isShow: false};
});
// create UI and set data
$UI.layersViewer = createLayerViewer(
- "overlayers",
- mainViewerData,
- callback.bind("main")
+ 'overlayers',
+ mainViewerData,
+ callback.bind('main'),
);
// create UI and set data - minor
$UI.layersViewerMinor = createLayerViewer(
- "overlayersMinor",
- minorViewerData,
- callback.bind("minor")
+ 'overlayersMinor',
+ minorViewerData,
+ callback.bind('minor'),
);
//
if ($D.params.states && $D.params.states.l) {
- $D.params.states.l.forEach(id =>
- loadAnnotationById($CAMIC, $UI.layersViewer.getDataItemById(id), null)
+ $D.params.states.l.forEach((id) =>
+ loadAnnotationById($CAMIC, $UI.layersViewer.getDataItemById(id), null),
);
}
$UI.layersList = new CollapsibleList({
- id: "layerslist",
+ id: 'layerslist',
list: [
{
- id: "left",
- title: "Left Viewer",
+ id: 'left',
+ title: 'Left Viewer',
// icon:'border_color',
- content: "No Template Loaded" //$UI.annotOptPanel.elt
+ content: 'No Template Loaded', // $UI.annotOptPanel.elt
// isExpand:true
},
{
- id: "right",
+ id: 'right',
// icon:'find_replace',
- title: "Right Viewer",
- content: "No Template Loaded" //$UI.algOptPanel.elt,
- }
+ title: 'Right Viewer',
+ content: 'No Template Loaded', // $UI.algOptPanel.elt,
+ },
],
changeCallBack: function(e) {
// console.log(e);
- }
+ },
});
$UI.layersSideMenu.clearContent();
// add to layers side menu
- const title = document.createElement("div");
- title.classList.add("item_head");
- title.textContent = "Layers Manager";
+ const title = document.createElement('div');
+ title.classList.add('item_head');
+ title.textContent = 'Layers Manager';
$UI.layersSideMenu.addContent(title);
// zoom locker control
- $UI.lockerPanel = document.createElement("div");
- $UI.lockerPanel.classList.add("lock_panel");
- $UI.lockerPanel.style.display = "none";
+ $UI.lockerPanel = document.createElement('div');
+ $UI.lockerPanel.classList.add('lock_panel');
+ $UI.lockerPanel.style.display = 'none';
$UI.lockerPanel.innerHTML = `
Zoom Lock `;
$UI.lockerPanel
- .querySelector("input[type=checkbox]")
- .addEventListener("change", e => {
- isLock = !isLock;
- if (isLock) {
- $minorCAMIC.viewer.viewport.zoomTo(
- $CAMIC.viewer.viewport.getZoom(true),
- $CAMIC.viewer.viewport.getCenter(true),
- true
- );
- $CAMIC.viewer.controls.bottomright.style.display = "none";
- } else {
- $CAMIC.viewer.controls.bottomright.style.display = "";
- }
- });
+ .querySelector('input[type=checkbox]')
+ .addEventListener('change', (e) => {
+ isLock = !isLock;
+ if (isLock) {
+ $minorCAMIC.viewer.viewport.zoomTo(
+ $CAMIC.viewer.viewport.getZoom(true),
+ $CAMIC.viewer.viewport.getCenter(true),
+ true,
+ );
+ $CAMIC.viewer.controls.bottomright.style.display = 'none';
+ } else {
+ $CAMIC.viewer.controls.bottomright.style.display = '';
+ }
+ });
$UI.layersSideMenu.addContent($UI.lockerPanel);
- $UI.layersList.clearContent("left");
- $UI.layersList.addContent("left", $UI.layersViewer.elt);
- $UI.layersList.clearContent("right");
- $UI.layersList.addContent("right", $UI.layersViewerMinor.elt);
+ $UI.layersList.clearContent('left');
+ $UI.layersList.addContent('left', $UI.layersViewer.elt);
+ $UI.layersList.clearContent('right');
+ $UI.layersList.addContent('right', $UI.layersViewerMinor.elt);
$UI.layersList.elt.parentNode.removeChild($UI.layersList.elt);
closeMinorControlPanel();
@@ -994,32 +998,32 @@ async function initUIcomponents() {
var checkTemplateSchemasDataReady = setInterval(function() {
if ($D.templates) {
clearInterval(checkTemplateSchemasDataReady);
- const annotRegex = new RegExp("annotation", "gi");
- const annotSchemas = $D.templates.filter(item =>
- item.id.match(annotRegex)
+ const annotRegex = new RegExp('annotation', 'gi');
+ const annotSchemas = $D.templates.filter((item) =>
+ item.id.match(annotRegex),
);
/* annotation control */
$UI.annotOptPanel = new OperationPanel({
- //id:
- //element:
+ // id:
+ // element:
formSchemas: annotSchemas,
resetCallback: reset_callback,
action: {
- title: "Save",
- callback: anno_callback
- }
+ title: 'Save',
+ callback: anno_callback,
+ },
});
// START QUIP550 TEMPORARILY REMOVE Algorithm Panel //
// add to layers side menu
- const title = document.createElement("div");
- title.classList.add("item_head");
- title.textContent = "Annotation";
+ const title = document.createElement('div');
+ title.classList.add('item_head');
+ title.textContent = 'Annotation';
$UI.appsSideMenu.addContent(title);
- $UI.annotOptPanel.elt.classList.add("item_body");
+ $UI.annotOptPanel.elt.classList.add('item_body');
$UI.appsSideMenu.addContent($UI.annotOptPanel.elt);
- //$UI.appsList.clearContent('annotation');
- //$UI.appsList.addContent('annotation',$UI.annotOptPanel.elt);
+ // $UI.appsList.clearContent('annotation');
+ // $UI.appsList.addContent('annotation',$UI.annotOptPanel.elt);
/* algorithm control */
// const algoRegex = new RegExp('algo', 'gi');
// const algoSchemas = $D.templates.filter(item => item.id.match(algoRegex));
@@ -1085,14 +1089,14 @@ function createLayerViewer(id, viewerData, callback) {
data: viewerData,
removeCallback: removeCallback,
locationCallback: locationCallback,
- callback: callback
+ callback: callback,
});
layersViewer.elt.parentNode.removeChild(layersViewer.elt);
return layersViewer;
}
// create lay panel for side-by-side control
function createLayPanelControl() {
- $UI.layCtrlbar = document.createElement("div");
+ $UI.layCtrlbar = document.createElement('div');
$UI.layCtrlbar.style = `
display:none;
margin: .2rem;
@@ -1108,18 +1112,18 @@ function createLayPanelControl() {
createRadios();
$UI.layersSideMenu.addContent($UI.layCtrlbar);
// control
- const radios = $UI.layCtrlbar.querySelectorAll("input[name=ctrlPane]");
- radios.forEach(r => {
- r.addEventListener("change", function(e) {
+ const radios = $UI.layCtrlbar.querySelectorAll('input[name=ctrlPane]');
+ radios.forEach((r) => {
+ r.addEventListener('change', function(e) {
const val = e.target.value;
switch (val) {
- case "main":
- $UI.layersViewer.elt.style.display = "flex";
- $UI.layersViewerMinor.elt.style.display = "none";
+ case 'main':
+ $UI.layersViewer.elt.style.display = 'flex';
+ $UI.layersViewerMinor.elt.style.display = 'none';
break;
- case "minor":
- $UI.layersViewer.elt.style.display = "none";
- $UI.layersViewerMinor.elt.style.display = "flex";
+ case 'minor':
+ $UI.layersViewer.elt.style.display = 'none';
+ $UI.layersViewerMinor.elt.style.display = 'flex';
break;
default:
// statements_def
@@ -1139,7 +1143,7 @@ function createRadios() {
$UI.layCtrlbar.innerHTML = temp;
}
-function redirect(url, text = "", sec = 5) {
+function redirect(url, text = '', sec = 5) {
let timer = sec;
setInterval(function() {
if (!timer) {
diff --git a/apps/viewer/uicallbacks.js b/apps/viewer/uicallbacks.js
index e4dc1e874..755b87902 100644
--- a/apps/viewer/uicallbacks.js
+++ b/apps/viewer/uicallbacks.js
@@ -1,4 +1,4 @@
-//UI and Core callback and hook
+// UI and Core callback and hook
// all functions help the UI and Core part together that makes workflows.
/* UI callback functions list */
@@ -9,19 +9,19 @@ function toggleViewerMode(opt) {
toolsOff();
// turn off magnifier
- //magnifierOff();
+ // magnifierOff();
// turn off measurement
- //measurementOff();
+ // measurementOff();
- //open layers menu
+ // open layers menu
$UI.toolbar._main_tools[1].querySelector(
- "input[type=checkbox]"
+ 'input[type=checkbox]',
).checked = true;
$UI.layersSideMenu.open();
- //close apps menu
+ // close apps menu
$UI.toolbar._main_tools[0].querySelector(
- "input[type=checkbox]"
+ 'input[type=checkbox]',
).checked = false;
$UI.appsSideMenu.close();
@@ -35,20 +35,20 @@ function toggleViewerMode(opt) {
}
}
-//mainfest
+// mainfest
function multSelector_action(size) {
// hidden main viewer's bottom right control and get navigator
- $CAMIC.viewer.controls.bottomright.style.display = "none";
- $UI.lockerPanel.style.display = "";
- $UI.lockerPanel.querySelector("input[type=checkbox]").checked = true;
+ $CAMIC.viewer.controls.bottomright.style.display = 'none';
+ $UI.lockerPanel.style.display = '';
+ $UI.lockerPanel.querySelector('input[type=checkbox]').checked = true;
isLock = true;
// open new instance camic
try {
- let slideQuery = {};
+ const slideQuery = {};
slideQuery.id = $D.params.slideId;
slideQuery.name = $D.params.slide;
slideQuery.location = $D.params.location;
- $minorCAMIC = new CaMic("minor_viewer", slideQuery, {
+ $minorCAMIC = new CaMic('minor_viewer', slideQuery, {
// osd options
// mouseNavEnabled:false,
// panVertical:false,
@@ -57,8 +57,8 @@ function multSelector_action(size) {
// customized options
// hasZoomControl:false,
hasDrawLayer: false,
- //hasLayerManager:false,
- //hasScalebar:false,
+ // hasLayerManager:false,
+ // hasScalebar:false,
// states options
navigatorHeight: size.height,
navigatorWidth: size.width,
@@ -67,16 +67,16 @@ function multSelector_action(size) {
y:
$CAMIC.viewer.viewport.getCenter().y *
$CAMIC.viewer.imagingHelper.imgAspectRatio,
- z: $CAMIC.viewer.viewport.getZoom()
- }
+ z: $CAMIC.viewer.viewport.getZoom(),
+ },
});
// synchornic zoom and move
// coordinated Viewer - zoom
- $CAMIC.viewer.addHandler("zoom", synchornicView1, { type: "zoom" });
+ $CAMIC.viewer.addHandler('zoom', synchornicView1, {type: 'zoom'});
// coordinated Viewer - pan
- $CAMIC.viewer.addHandler("pan", synchornicView1, { type: "pan" });
+ $CAMIC.viewer.addHandler('pan', synchornicView1, {type: 'pan'});
// loading image
$minorCAMIC.loadImg(function(e) {
@@ -85,20 +85,20 @@ function multSelector_action(size) {
$UI.message.addError(e.message);
}
});
- $minorCAMIC.viewer.addOnceHandler("tile-drawing", function() {
- $minorCAMIC.viewer.addHandler("zoom", synchornicView2, { type: "zoom" });
- $minorCAMIC.viewer.addHandler("pan", synchornicView2, { type: "pan" });
+ $minorCAMIC.viewer.addOnceHandler('tile-drawing', function() {
+ $minorCAMIC.viewer.addHandler('zoom', synchornicView2, {type: 'zoom'});
+ $minorCAMIC.viewer.addHandler('pan', synchornicView2, {type: 'pan'});
// create segment display
$minorCAMIC.viewer.createSegment({
store: $minorCAMIC.store,
slide: $D.params.data.name,
- data: []
+ data: [],
});
});
} catch (error) {
Loading.close();
console.error(error);
- $UI.message.addError("Core Initialization Failed");
+ $UI.message.addError('Core Initialization Failed');
return;
}
}
@@ -110,16 +110,16 @@ function synchornicView1(data) {
if (active2) return;
active1 = true;
switch (data.userData.type) {
- case "zoom":
+ case 'zoom':
if (isLock) {
$minorCAMIC.viewer.viewport.zoomTo(data.zoom, data.refPoint);
} else {
$minorCAMIC.viewer.viewport.panTo(
- $CAMIC.viewer.viewport.getCenter(true)
+ $CAMIC.viewer.viewport.getCenter(true),
);
}
break;
- case "pan":
+ case 'pan':
$minorCAMIC.viewer.viewport.panTo(data.center);
break;
default:
@@ -134,16 +134,16 @@ function synchornicView2(data) {
if (active1) return;
active2 = true;
switch (data.userData.type) {
- case "zoom":
+ case 'zoom':
if (isLock) {
$CAMIC.viewer.viewport.zoomTo(data.zoom, data.refPoint);
} else {
$CAMIC.viewer.viewport.panTo(
- $minorCAMIC.viewer.viewport.getCenter(true)
+ $minorCAMIC.viewer.viewport.getCenter(true),
);
}
break;
- case "pan":
+ case 'pan':
$CAMIC.viewer.viewport.panTo(data.center);
break;
default:
@@ -157,20 +157,20 @@ function synchornicView2(data) {
function openSecondaryViewer() {
// ui changed
- const main = document.getElementById("main_viewer");
- const minor = document.getElementById("minor_viewer");
- main.classList.remove("main");
- main.classList.add("left");
+ const main = document.getElementById('main_viewer');
+ const minor = document.getElementById('minor_viewer');
+ main.classList.remove('main');
+ main.classList.add('left');
- minor.classList.remove("none");
+ minor.classList.remove('none');
// minor.classList.add('display');
- minor.classList.add("right");
+ minor.classList.add('right');
const nav_size = {
- height: $CAMIC.viewer.controls.bottomright.querySelector(".navigator").style
- .height,
- width: $CAMIC.viewer.controls.bottomright.querySelector(".navigator").style
- .width
+ height: $CAMIC.viewer.controls.bottomright.querySelector('.navigator').style
+ .height,
+ width: $CAMIC.viewer.controls.bottomright.querySelector('.navigator').style
+ .width,
};
setTimeout(function() {
multSelector_action(nav_size);
@@ -179,24 +179,24 @@ function openSecondaryViewer() {
function closeSecondaryViewer() {
// ui changed
- const main = document.getElementById("main_viewer");
- const minor = document.getElementById("minor_viewer");
- main.classList.add("main");
- main.classList.remove("left");
- minor.classList.add("none");
- minor.classList.remove("right");
- $CAMIC.viewer.controls.bottomright.style.display = "";
- $UI.lockerPanel.style.display = "none";
-
- const li = $UI.toolbar.getSubTool("sbsviewer");
+ const main = document.getElementById('main_viewer');
+ const minor = document.getElementById('minor_viewer');
+ main.classList.add('main');
+ main.classList.remove('left');
+ minor.classList.add('none');
+ minor.classList.remove('right');
+ $CAMIC.viewer.controls.bottomright.style.display = '';
+ $UI.lockerPanel.style.display = 'none';
+
+ const li = $UI.toolbar.getSubTool('sbsviewer');
li.querySelector('input[type="checkbox"]').checked = false;
Loading.close();
- //destory
+ // destory
if ($minorCAMIC) {
// remove handler
- $CAMIC.viewer.removeHandler("zoom", synchornicView1);
- $CAMIC.viewer.removeHandler("pan", synchornicView1);
+ $CAMIC.viewer.removeHandler('zoom', synchornicView1);
+ $CAMIC.viewer.removeHandler('pan', synchornicView1);
// destroy object
$minorCAMIC.destroy();
@@ -205,13 +205,13 @@ function closeSecondaryViewer() {
// hide on layersViewer
$UI.layersViewerMinor.toggleAllItems();
- $UI.layersViewerMinor.setting.data.forEach(d => delete d.layer);
+ $UI.layersViewerMinor.setting.data.forEach((d) => delete d.layer);
}
// side menu close callback
function toggleSideMenu(opt) {
if (!opt.isOpen) {
- const id = opt.target.id.split("_")[1];
+ const id = opt.target.id.split('_')[1];
$UI.toolbar.changeMainToolStatus(id, false);
}
}
@@ -221,16 +221,16 @@ function goHome(data) {
redirect($D.pages.home, `GO Home Page`, 0);
}
-//--- Annotation Tool ---//
+// --- Annotation Tool ---//
// pen draw callback
-const label = document.createElement("div");
-label.style.transformOrigin = "center";
+const label = document.createElement('div');
+label.style.transformOrigin = 'center';
label.style.height = 0;
label.style.width = 0;
function draw(e) {
if (!$CAMIC.viewer.canvasDrawInstance) {
- alert("Draw Doesn't Initialize");
+ alert('Draw Doesn\'t Initialize');
return;
}
const state = +e.state;
@@ -240,25 +240,25 @@ function draw(e) {
// on
// off magnifier
- //magnifierOff();
+ // magnifierOff();
// off measurement
- //measurementOff();
+ // measurementOff();
// turn off annotaiton
- if ($CAMIC.status == "normal") {
+ if ($CAMIC.status == 'normal') {
annotationOn.call(this, state, target);
return;
}
toolsOff();
var checkAllToolsOff = setInterval(
- function() {
- if ($CAMIC && $CAMIC.status == null) {
+ function() {
+ if ($CAMIC && $CAMIC.status == null) {
// all tool has turn off
- clearInterval(checkAllToolsOff);
- annotationOn.call(this, state, target);
- }
- }.bind(this),
- 100
+ clearInterval(checkAllToolsOff);
+ annotationOn.call(this, state, target);
+ }
+ }.bind(this),
+ 100,
);
} else {
// off
@@ -268,27 +268,27 @@ function draw(e) {
function drawLabel(e) {
if (!$CAMIC.viewer.canvasDrawInstance) {
- alert("Draw Doesn't Initialize");
+ alert('Draw Doesn\'t Initialize');
return;
}
if (e.status) {
- if ($CAMIC.status == "label") {
- presetLabelOn.call(this, { ...e.data });
+ if ($CAMIC.status == 'label') {
+ presetLabelOn.call(this, {...e.data});
return;
}
// turn off annotation
toolsOff();
var checkAllToolsOff = setInterval(
- function() {
- if ($CAMIC && $CAMIC.status == null) {
+ function() {
+ if ($CAMIC && $CAMIC.status == null) {
// all tool has turn off
- clearInterval(checkAllToolsOff);
- presetLabelOn.call(this, { ...e.data });
- }
- }.bind(this),
- 100
+ clearInterval(checkAllToolsOff);
+ presetLabelOn.call(this, {...e.data});
+ }
+ }.bind(this),
+ 100,
);
} else {
// off preset label
@@ -300,14 +300,15 @@ function presetLabelOn(label) {
if (!$CAMIC.viewer.canvasDrawInstance) return;
const canvasDraw = $CAMIC.viewer.canvasDrawInstance;
canvasDraw.drawMode = label.mode;
- if (label.mode == "grid")
+ if (label.mode == 'grid') {
canvasDraw.size = [parseInt(label.size), parseInt(label.size)];
+ }
canvasDraw.style.color = label.color;
canvasDraw.drawOn();
- $CAMIC.status = "label";
- $UI.toolbar.getSubTool("preset_label").querySelector("label").style.color =
+ $CAMIC.status = 'label';
+ $UI.toolbar.getSubTool('preset_label').querySelector('label').style.color =
label.color;
- //close layers menu
+ // close layers menu
$UI.layersSideMenu.close();
}
@@ -325,31 +326,31 @@ function presetLabelOff() {
canvasDraw.drawOff();
$UI.appsSideMenu.close();
$UI.toolbar
- .getSubTool("preset_label")
- .querySelector("input[type=checkbox]").checked = false;
- $UI.toolbar.getSubTool("preset_label").querySelector("label").style.color =
- "";
+ .getSubTool('preset_label')
+ .querySelector('input[type=checkbox]').checked = false;
+ $UI.toolbar.getSubTool('preset_label').querySelector('label').style.color =
+ '';
$CAMIC.status = null;
}
}
function toolsOff() {
switch ($CAMIC.status) {
- case "magnifier":
+ case 'magnifier':
magnifierOff();
break;
- case "measure":
+ case 'measure':
measurementOff();
break;
- case "normal":
+ case 'normal':
annotationOff();
break;
- case "label":
+ case 'label':
presetLabelOff();
break;
- case "brush":
+ case 'brush':
brushOff();
break;
}
@@ -358,8 +359,8 @@ function toolsOff() {
function annotationOn(state, target) {
if (!$CAMIC.viewer.canvasDrawInstance) return;
const canvasDraw = $CAMIC.viewer.canvasDrawInstance;
- const li = $UI.toolbar.getSubTool("annotation");
- const { style, model } = $CAMIC.drawContextmenu.getStyle();
+ const li = $UI.toolbar.getSubTool('annotation');
+ const {style, model} = $CAMIC.drawContextmenu.getStyle();
canvasDraw.drawMode = model;
canvasDraw.style.color = style.color;
@@ -367,17 +368,17 @@ function annotationOn(state, target) {
li.appendChild(label);
switch (state) {
case 1:
- $UI.annotOptPanel._action_.style.display = "none";
- label.style.transform = "translateY(-12px) translateX(18px)";
- label.textContent = "1";
- label.style.color = "";
+ $UI.annotOptPanel._action_.style.display = 'none';
+ label.style.transform = 'translateY(-12px) translateX(18px)';
+ label.textContent = '1';
+ label.style.color = '';
break;
case 2:
- $UI.annotOptPanel._action_.style.display = "";
+ $UI.annotOptPanel._action_.style.display = '';
label.style.transform =
- " rotate(-90deg) translateX(2px) translateY(13px)";
- label.textContent = "8";
- label.style.color = "white";
+ ' rotate(-90deg) translateX(2px) translateY(13px)';
+ label.textContent = '8';
+ label.style.color = 'white';
break;
default:
// statements_def
@@ -389,17 +390,17 @@ function annotationOn(state, target) {
$CAMIC.drawContextmenu.open({
x: this.clientX,
y: this.clientY,
- target: target
+ target: target,
});
- $CAMIC.status = "normal";
- //close layers menu
+ $CAMIC.status = 'normal';
+ // close layers menu
$UI.layersSideMenu.close();
// open annotation menu
$UI.appsSideMenu.open();
// -- START QUIP550 -- //
- //$UI.appsList.triggerContent('annotation','open');
+ // $UI.appsList.triggerContent('annotation','open');
// -- END QUIP550 -- //
- const input = $UI.annotOptPanel._form_.querySelector("#name");
+ const input = $UI.annotOptPanel._form_.querySelector('#name');
input.focus();
input.select();
}
@@ -424,18 +425,18 @@ function annotationOff() {
}
function toggleOffDrawBtns() {
- const li = $UI.toolbar.getSubTool("annotation");
- const lab = li.querySelector("label");
+ const li = $UI.toolbar.getSubTool('annotation');
+ const lab = li.querySelector('label');
const state = +lab.dataset.state;
lab.classList.remove(`s${state}`);
lab.dataset.state = 0;
lab.classList.add(`s0`);
if (label.parentNode) li.removeChild(label);
}
-//--- Brush Tool ---//
+// --- Brush Tool ---//
function toggleBrush(d) {
if (!$CAMIC.viewer.canvasDrawInstance) {
- alert("Draw Doesn't Initialize");
+ alert('Draw Doesn\'t Initialize');
return;
}
@@ -446,8 +447,8 @@ function toggleBrush(d) {
// magnifierOff();
// off measurement
// measurementOff();
- if ($CAMIC.status == "brush") {
- brushOn.call(this, { ...d.data });
+ if ($CAMIC.status == 'brush') {
+ brushOn.call(this, {...d.data});
return;
}
// turn off annotation
@@ -455,14 +456,14 @@ function toggleBrush(d) {
// turn off preset label
// presetLabelOff();
var checkAllToolsOff = setInterval(
- function() {
- if ($CAMIC && $CAMIC.status == null) {
+ function() {
+ if ($CAMIC && $CAMIC.status == null) {
// all tool has turn off
- clearInterval(checkAllToolsOff);
- brushOn.call(this, { ...d.data });
- }
- }.bind(this),
- 100
+ clearInterval(checkAllToolsOff);
+ brushOn.call(this, {...d.data});
+ }
+ }.bind(this),
+ 100,
);
} else {
// off preset label
@@ -472,8 +473,8 @@ function toggleBrush(d) {
function brushOn(d) {
if (!$CAMIC.viewer.canvasDrawInstance) return;
- const bctrl = document.getElementById("bctrl");
- bctrl.style.display = "block";
+ const bctrl = document.getElementById('bctrl');
+ bctrl.style.display = 'block';
const canvasDraw = $CAMIC.viewer.canvasDrawInstance;
canvasDraw.drawMode = d.mode;
@@ -481,9 +482,9 @@ function brushOn(d) {
canvasDraw.style.color = d.color;
canvasDraw.brushType = d.type;
canvasDraw.drawOn();
- $CAMIC.status = "brush";
+ $CAMIC.status = 'brush';
- $UI.toolbar.getSubTool("brush").querySelector("label").style.color = d.color;
+ $UI.toolbar.getSubTool('brush').querySelector('label').style.color = d.color;
// //close layers menu
// $UI.layersSideMenu.close();
}
@@ -502,28 +503,28 @@ function brushOff() {
canvasDraw.drawOff();
$UI.appsSideMenu.close();
$UI.toolbar
- .getSubTool("brush")
- .querySelector("input[type=checkbox]").checked = false;
- $UI.toolbar.getSubTool("brush").querySelector("label").style.color = "";
+ .getSubTool('brush')
+ .querySelector('input[type=checkbox]').checked = false;
+ $UI.toolbar.getSubTool('brush').querySelector('label').style.color = '';
- const bctrl = document.getElementById("bctrl");
- bctrl.style.display = "none";
+ const bctrl = document.getElementById('bctrl');
+ bctrl.style.display = 'none';
$CAMIC.status = null;
}
}
-//--- Measurement Tool ---//
+// --- Measurement Tool ---//
function toggleMeasurement(data) {
if (!$CAMIC.viewer.measureInstance) {
- console.warn("No Measurement Tool");
+ console.warn('No Measurement Tool');
return;
}
- //$UI.message.add(`Measument Tool ${data.checked?'ON':'OFF'}`);
+ // $UI.message.add(`Measument Tool ${data.checked?'ON':'OFF'}`);
if (data.checked) {
// trun off the main menu
$UI.layersSideMenu.close();
- if ($CAMIC.status == "measure") {
+ if ($CAMIC.status == 'measure') {
measurementOn();
return;
}
@@ -537,7 +538,7 @@ function toggleMeasurement(data) {
}
}, 100);
// turn off magnifier
- //magnifierOff();
+ // magnifierOff();
} else {
measurementOff();
}
@@ -546,23 +547,23 @@ function toggleMeasurement(data) {
function measurementOn() {
if (!$CAMIC.viewer.measureInstance) return;
$CAMIC.viewer.measureInstance.on();
- const li = $UI.toolbar.getSubTool("measurement");
- li.querySelector("input[type=checkbox]").checked = true;
- $CAMIC.status = "measure";
+ const li = $UI.toolbar.getSubTool('measurement');
+ li.querySelector('input[type=checkbox]').checked = true;
+ $CAMIC.status = 'measure';
}
function measurementOff() {
if (!$CAMIC.viewer.measureInstance) return;
$CAMIC.viewer.measureInstance.off();
- const li = $UI.toolbar.getSubTool("measurement");
- li.querySelector("input[type=checkbox]").checked = false;
+ const li = $UI.toolbar.getSubTool('measurement');
+ li.querySelector('input[type=checkbox]').checked = false;
$CAMIC.status = null;
}
-//--- toggle magnifier callback ---//
+// --- toggle magnifier callback ---//
function toggleMagnifier(data) {
if (data.checked) {
- if ($CAMIC.status == "magnifier") {
+ if ($CAMIC.status == 'magnifier') {
// all tool has turn off
clearInterval(checkAllToolsOff);
magnifierOn(+data.status, this.clientX, this.clientY);
@@ -574,20 +575,20 @@ function toggleMagnifier(data) {
// annotation off
toolsOff();
var checkAllToolsOff = setInterval(
- function() {
- if ($CAMIC && $CAMIC.status == null) {
+ function() {
+ if ($CAMIC && $CAMIC.status == null) {
// all tool has turn off
- clearInterval(checkAllToolsOff);
- magnifierOn(+data.status, this.clientX, this.clientY);
- // trun off the main menu
- $UI.layersSideMenu.close();
- $UI.appsSideMenu.close();
- }
- }.bind(this),
- 100
+ clearInterval(checkAllToolsOff);
+ magnifierOn(+data.status, this.clientX, this.clientY);
+ // trun off the main menu
+ $UI.layersSideMenu.close();
+ $UI.appsSideMenu.close();
+ }
+ }.bind(this),
+ 100,
);
// measurement off
- //measurementOff();
+ // measurementOff();
} else {
magnifierOff();
}
@@ -597,30 +598,30 @@ function magnifierOn(factor = 1, x = 0, y = 0) {
if (!$UI.spyglass) return;
$UI.spyglass.factor = factor;
$UI.spyglass.open(x, y);
- const li = $UI.toolbar.getSubTool("magnifier");
- li.querySelector("input[type=checkbox]").checked = true;
- $CAMIC.status = "magnifier";
+ const li = $UI.toolbar.getSubTool('magnifier');
+ li.querySelector('input[type=checkbox]').checked = true;
+ $CAMIC.status = 'magnifier';
}
function magnifierOff() {
if (!$UI.spyglass) return;
$UI.spyglass.close();
- const li = $UI.toolbar.getSubTool("magnifier");
- li.querySelector("input[type=checkbox]").checked = false;
+ const li = $UI.toolbar.getSubTool('magnifier');
+ li.querySelector('input[type=checkbox]').checked = false;
$CAMIC.status = null;
}
// image download
function imageDownload(data) {
// TODO functionality
- alert("Download Image");
+ alert('Download Image');
console.log(data);
}
// share url
function shareURL(data) {
const URL = StatesHelper.getCurrentStatesURL(true);
- window.prompt("Share this link", URL);
+ window.prompt('Share this link', URL);
}
// main menu changed
function mainMenuChange(data) {
@@ -638,14 +639,16 @@ function mainMenuChange(data) {
}
function convertHumanAnnotationToPopupBody(notes) {
- const rs = { type: "map", data: [] };
+ const rs = {type: 'map', data: []};
for (let field in notes) {
- const val = notes[field];
- field = field
- .split("_")
- .map(word => word.charAt(0).toUpperCase() + word.slice(1))
- .join(" ");
- rs.data.push({ key: field, value: val });
+ if (notes.hasOwnProperty(field)) {
+ const val = notes[field];
+ field = field
+ .split('_')
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(' ');
+ rs.data.push({key: field, value: val});
+ }
}
return rs;
}
@@ -653,7 +656,7 @@ function convertHumanAnnotationToPopupBody(notes) {
function anno_delete(data) {
if (!data.id) return;
const annotationData = $D.overlayers.find(
- d => d.data && d.data._id.$oid == data.oid
+ (d) => d.data && d.data._id.$oid == data.oid,
);
let message;
if (annotationData.data.geometries) {
@@ -664,39 +667,39 @@ function anno_delete(data) {
$UI.annotPopup.close();
if (!confirm(message)) return;
$CAMIC.store
- .deleteMark(data.oid, $D.params.data.slide)
- .then(datas => {
+ .deleteMark(data.oid, $D.params.data.slide)
+ .then((datas) => {
// server error
- if (datas.error) {
- const errorMessage = `${datas.text}: ${datas.url}`;
- $UI.message.addError(errorMessage, 5000);
- // close
- return;
- }
+ if (datas.error) {
+ const errorMessage = `${datas.text}: ${datas.url}`;
+ $UI.message.addError(errorMessage, 5000);
+ // close
+ return;
+ }
- // no data found
- if (!datas.rowsAffected || datas.rowsAffected < 1) {
- $UI.message.addWarning(`Delete Annotations Failed.`, 5000);
- return;
- }
+ // no data found
+ if (!datas.rowsAffected || datas.rowsAffected < 1) {
+ $UI.message.addWarning(`Delete Annotations Failed.`, 5000);
+ return;
+ }
- const index = $D.overlayers.findIndex(layer => layer.id == data.id);
-
- if (index == -1) return;
-
- data.index = index;
- const layer = $D.overlayers[data.index];
- // update UI
- if (Array.isArray(layer.data)) deleteCallback_old(data);
- else deleteCallback(data);
- })
- .catch(e => {
- $UI.message.addError(e);
- console.error(e);
- })
- .finally(() => {
- //console.log('delete end');
- });
+ const index = $D.overlayers.findIndex((layer) => layer.id == data.id);
+
+ if (index == -1) return;
+
+ data.index = index;
+ const layer = $D.overlayers[data.index];
+ // update UI
+ if (Array.isArray(layer.data)) deleteCallback_old(data);
+ else deleteCallback(data);
+ })
+ .catch((e) => {
+ $UI.message.addError(e);
+ console.error(e);
+ })
+ .finally(() => {
+ // console.log('delete end');
+ });
}
function deleteCallback(data) {
// remove overlay
@@ -706,10 +709,11 @@ function deleteCallback(data) {
$UI.layersViewerMinor.removeItemById(data.id);
$CAMIC.viewer.omanager.removeOverlay(data.id);
- if ($minorCAMIC && $minorCAMIC.viewer)
+ if ($minorCAMIC && $minorCAMIC.viewer) {
$minorCAMIC.viewer.omanager.removeOverlay(data.id);
+ }
// update layers Viewer
- //$UI.layersViewer.update();
+ // $UI.layersViewer.update();
// close popup panel
$UI.annotPopup.close();
}
@@ -718,7 +722,7 @@ function deleteCallback(data) {
function deleteCallback_old(data) {
const layer = $D.overlayers[data.index];
// for support QUIP2.0
- const idx = layer.data.findIndex(d => d._id.$oid === data.oid);
+ const idx = layer.data.findIndex((d) => d._id.$oid === data.oid);
if (idx == -1) return;
layer.data.splice(idx, 1);
@@ -741,66 +745,67 @@ function sort_change(sort) {
function reset_callback(data) {
if ($CAMIC.viewer.canvasDrawInstance._path_index === 0) return;
- if (confirm(`Do You Want To Clear Markups?`))
+ if (confirm(`Do You Want To Clear Markups?`)) {
$CAMIC.viewer.canvasDrawInstance.clear();
+ }
}
function convertToNormalized(points, size, viewer) {
const height = Math.round(viewer.imagingHelper.imgHeight);
const width = Math.round(viewer.imagingHelper.imgWidth);
// convert
- const normalized_points = points.map(p => [p[0] / width, p[1] / height]);
+ const normalized_points = points.map((p) => [p[0] / width, p[1] / height]);
const normalized_size = [size[0] / width, size[0] / height];
return {
points: normalized_points,
bound: getBounds(normalized_points),
- size: normalized_size
+ size: normalized_size,
};
}
function convertGeometries(features, data) {
- const { points, bound, size } = convertToNormalized(
- features,
- data.size,
- $CAMIC.viewer
+ const {points, bound, size} = convertToNormalized(
+ features,
+ data.size,
+ $CAMIC.viewer,
);
return {
- type: "FeatureCollection",
+ type: 'FeatureCollection',
features: [
{
- type: "Feature",
+ type: 'Feature',
properties: {
style: {
color: data.color,
- lineJoin: "round",
- lineCap: "round",
- isFill: true
+ lineJoin: 'round',
+ lineCap: 'round',
+ isFill: true,
},
- size: size
+ size: size,
},
geometry: {
- type: "LineString",
- coordinates: [points]
+ type: 'LineString',
+ coordinates: [points],
},
bound: {
- type: "Polygon",
- coordinates: [bound]
- }
- }
- ]
+ type: 'Polygon',
+ coordinates: [bound],
+ },
+ },
+ ],
};
}
function saveBrushLabel(isOff) {
if ($CAMIC.viewer.canvasDrawInstance._path_index === 0) {
- alert("No Brushed Markup On Annotation.");
+ alert('No Brushed Markup On Annotation.');
return;
}
// get all data
const features = $CAMIC.viewer.canvasDrawInstance.getImageFeatureCollection()
- .features;
+ .features;
// merge and reduce duplicated points
const map = features.reduce(function(map, f) {
@@ -810,20 +815,20 @@ function saveBrushLabel(isOff) {
if (!map.has(key)) map.set(key, new Set());
const set = map.get(key);
const values = getGrids(f.geometry.coordinates[0], f.properties.size);
- values.map(i => i.toString()).forEach(v => set.add(v));
+ values.map((i) => i.toString()).forEach((v) => set.add(v));
return map;
}, new Map());
// recreate annotation in the required json form
const annotJsons = [];
for (var [key, value] of map.entries()) {
- const [note, size, color] = key.split("|");
- const points = Array.from(value).map(d => d.split(","));
+ const [note, size, color] = key.split('|');
+ const points = Array.from(value).map((d) => d.split(','));
const exec_id = note + randomId();
const noteData = {
name: exec_id,
- notes: note
+ notes: note,
};
annotJsons.push({
@@ -831,132 +836,133 @@ function saveBrushLabel(isOff) {
created_date: new Date(),
provenance: {
image: {
- slide: $D.params.slideId
+ slide: $D.params.slideId,
},
analysis: {
- source: "human",
+ source: 'human',
execution_id: exec_id,
name: noteData.name,
- type: "label",
- isGrid: true
- }
+ type: 'label',
+ isGrid: true,
+ },
},
properties: {
- annotations: noteData
+ annotations: noteData,
},
geometries: convertGeometries(points, {
note: note,
- size: size.split(",").map(p => +p),
- color: color
- })
+ size: size.split(',').map((p) => +p),
+ color: color,
+ }),
});
}
- annotJsons.forEach(annotJson => {
+ annotJsons.forEach((annotJson) => {
$CAMIC.store
- .addMark(annotJson)
- .then(data => {
+ .addMark(annotJson)
+ .then((data) => {
// server error
- if (data.error) {
- $UI.message.addWarning(`${data.text}:${data.url}`);
- Loading.close();
- return;
- }
+ if (data.error) {
+ $UI.message.addWarning(`${data.text}:${data.url}`);
+ Loading.close();
+ return;
+ }
- // no data added
- if (data.count < 1) {
- Loading.close();
- $UI.message.addWarning(`Annotation Save Failed`);
- return;
- }
- // create layer data
- const exec_id = annotJson.provenance.analysis.execution_id;
- const new_item = {
- id: exec_id,
- name: annotJson.provenance.analysis.name,
- typeId: typeIds["human"],
- typeName: "human",
- data: null
- };
- $D.overlayers.push(new_item);
- $UI.layersViewer.addItem(new_item);
- $UI.layersViewerMinor.addItem(
- new_item,
- $minorCAMIC && $minorCAMIC.viewer ? true : false
- );
+ // no data added
+ if (data.count < 1) {
+ Loading.close();
+ $UI.message.addWarning(`Annotation Save Failed`);
+ return;
+ }
+ // create layer data
+ const exec_id = annotJson.provenance.analysis.execution_id;
+ const new_item = {
+ id: exec_id,
+ name: annotJson.provenance.analysis.name,
+ typeId: typeIds['human'],
+ typeName: 'human',
+ data: null,
+ };
+ $D.overlayers.push(new_item);
+ $UI.layersViewer.addItem(new_item);
+ $UI.layersViewerMinor.addItem(
+ new_item,
+ $minorCAMIC && $minorCAMIC.viewer ? true : false,
+ );
- //console.log($D.overlayers);
- // data for UI
- //return;
- loadAnnotationById(
- $CAMIC,
- $UI.layersViewer.getDataItemById(exec_id),
- saveBrushAnnotCallback.bind(isOff)
- );
- if ($minorCAMIC && $minorCAMIC.viewer)
+ // console.log($D.overlayers);
+ // data for UI
+ // return;
loadAnnotationById(
- $minorCAMIC,
- $UI.layersViewerMinor.getDataItemById(exec_id),
- null
+ $CAMIC,
+ $UI.layersViewer.getDataItemById(exec_id),
+ saveBrushAnnotCallback.bind(isOff),
);
- })
- .catch(e => {
- Loading.close();
- console.log("save failed");
- })
- .finally(() => {});
+ if ($minorCAMIC && $minorCAMIC.viewer) {
+ loadAnnotationById(
+ $minorCAMIC,
+ $UI.layersViewerMinor.getDataItemById(exec_id),
+ null,
+ );
+ }
+ })
+ .catch((e) => {
+ Loading.close();
+ console.log('save failed');
+ })
+ .finally(() => {});
});
}
function savePresetLabel() {
if ($CAMIC.viewer.canvasDrawInstance._path_index === 0) {
- alert("No Markup On Annotation. Try holding and dragging.");
+ alert('No Markup On Annotation. Try holding and dragging.');
return;
}
// save
const data = $UI.toolbar
- .getSubTool("preset_label")
- .querySelector("li.leaf.checked").dataset;
+ .getSubTool('preset_label')
+ .querySelector('li.leaf.checked').dataset;
const exec_id = data.type + randomId();
const noteData = {
name: exec_id,
- notes: data.type
+ notes: data.type,
};
const feature = $CAMIC.viewer.canvasDrawInstance.getImageFeatureCollection()
- .features[0];
+ .features[0];
let annotJson;
if (feature.properties.size) {
// brush
const values = getGrids(
- feature.geometry.coordinates[0],
- feature.properties.size
+ feature.geometry.coordinates[0],
+ feature.properties.size,
);
const set = new Set();
- values.map(i => i.toString()).forEach(v => set.add(v));
- const points = Array.from(set).map(d => d.split(","));
+ values.map((i) => i.toString()).forEach((v) => set.add(v));
+ const points = Array.from(set).map((d) => d.split(','));
annotJson = {
creator: getUserId(),
created_date: new Date(),
provenance: {
image: {
- slide: $D.params.slideId
+ slide: $D.params.slideId,
},
analysis: {
- source: "human",
+ source: 'human',
execution_id: exec_id,
name: noteData.name,
- type: "label",
- isGrid: true
- }
+ type: 'label',
+ isGrid: true,
+ },
},
properties: {
- annotations: noteData
+ annotations: noteData,
},
geometries: convertGeometries(points, {
note: data.type,
size: feature.properties.size,
- color: feature.properties.style.color
- })
+ color: feature.properties.style.color,
+ }),
};
} else {
// point / polygon / stringLine
@@ -965,85 +971,86 @@ function savePresetLabel() {
created_date: new Date(),
provenance: {
image: {
- slide: $D.params.slideId
+ slide: $D.params.slideId,
},
analysis: {
- source: "human",
+ source: 'human',
execution_id: exec_id,
name: noteData.name,
- type: "label"
- }
+ type: 'label',
+ },
},
properties: {
- annotations: noteData
+ annotations: noteData,
},
geometries: ImageFeaturesToVieweportFeatures(
- $CAMIC.viewer,
- $CAMIC.viewer.canvasDrawInstance.getImageFeatureCollection()
- )
+ $CAMIC.viewer,
+ $CAMIC.viewer.canvasDrawInstance.getImageFeatureCollection(),
+ ),
};
}
$CAMIC.store
- .addMark(annotJson)
- .then(data => {
+ .addMark(annotJson)
+ .then((data) => {
// server error
- if (data.error) {
- $UI.message.addWarning(`${data.text}:${data.url}`);
- Loading.close();
- return;
- }
+ if (data.error) {
+ $UI.message.addWarning(`${data.text}:${data.url}`);
+ Loading.close();
+ return;
+ }
- // no data added
- if (data.count < 1) {
- Loading.close();
- $UI.message.addWarning(`Annotation Save Failed`);
- return;
- }
- // create layer data
- const new_item = {
- id: exec_id,
- name: noteData.name,
- typeId: typeIds["human"],
- typeName: "human",
- data: null
- };
- $D.overlayers.push(new_item);
- $UI.layersViewer.addItem(new_item);
- $UI.layersViewerMinor.addItem(
- new_item,
- $minorCAMIC && $minorCAMIC.viewer ? true : false
- );
+ // no data added
+ if (data.count < 1) {
+ Loading.close();
+ $UI.message.addWarning(`Annotation Save Failed`);
+ return;
+ }
+ // create layer data
+ const new_item = {
+ id: exec_id,
+ name: noteData.name,
+ typeId: typeIds['human'],
+ typeName: 'human',
+ data: null,
+ };
+ $D.overlayers.push(new_item);
+ $UI.layersViewer.addItem(new_item);
+ $UI.layersViewerMinor.addItem(
+ new_item,
+ $minorCAMIC && $minorCAMIC.viewer ? true : false,
+ );
- // data for UI
- //return;
- loadAnnotationById(
- $CAMIC,
- $UI.layersViewer.getDataItemById(exec_id),
- saveLabelAnnotCallback
- );
- if ($minorCAMIC && $minorCAMIC.viewer)
+ // data for UI
+ // return;
loadAnnotationById(
- $minorCAMIC,
- $UI.layersViewerMinor.getDataItemById(exec_id),
- null
+ $CAMIC,
+ $UI.layersViewer.getDataItemById(exec_id),
+ saveLabelAnnotCallback,
);
- })
- .catch(e => {
- Loading.close();
- console.log("save failed");
- })
- .finally(() => {});
+ if ($minorCAMIC && $minorCAMIC.viewer) {
+ loadAnnotationById(
+ $minorCAMIC,
+ $UI.layersViewerMinor.getDataItemById(exec_id),
+ null,
+ );
+ }
+ })
+ .catch((e) => {
+ Loading.close();
+ console.log('save failed');
+ })
+ .finally(() => {});
}
function saveBrushAnnotCallback() {
/* reset as default */
// clear draw data and UI
- //$CAMIC.viewer.canvasDrawInstance.drawOff();
+ // $CAMIC.viewer.canvasDrawInstance.drawOff();
$CAMIC.drawContextmenu.off();
$CAMIC.viewer.canvasDrawInstance.clear();
// close app side
- $UI.toolbar._main_tools[0].querySelector("[type=checkbox]").checked = false;
+ $UI.toolbar._main_tools[0].querySelector('[type=checkbox]').checked = false;
$UI.appsSideMenu.close();
// $UI.toolbar._main_tools[1].querySelector('[type=checkbox]').checked = true;
// $UI.layersSideMenu.open();
@@ -1052,12 +1059,12 @@ function saveBrushAnnotCallback() {
if (this == true) {
// isOff
$UI.toolbar
- .getSubTool("brush")
- .querySelector("input[type=checkbox]").checked = false;
- $UI.toolbar.getSubTool("brush").querySelector("label").style.color = "";
+ .getSubTool('brush')
+ .querySelector('input[type=checkbox]').checked = false;
+ $UI.toolbar.getSubTool('brush').querySelector('label').style.color = '';
- const bctrl = document.getElementById("bctrl");
- bctrl.style.display = "none";
+ const bctrl = document.getElementById('bctrl');
+ bctrl.style.display = 'none';
$CAMIC.status = null;
}
}
@@ -1065,28 +1072,28 @@ function saveBrushAnnotCallback() {
function saveLabelAnnotCallback() {
/* reset as default */
// clear draw data and UI
- //$CAMIC.viewer.canvasDrawInstance.drawOff();
+ // $CAMIC.viewer.canvasDrawInstance.drawOff();
$CAMIC.drawContextmenu.off();
$CAMIC.viewer.canvasDrawInstance.clear();
// close app side
- $UI.toolbar._main_tools[0].querySelector("[type=checkbox]").checked = false;
+ $UI.toolbar._main_tools[0].querySelector('[type=checkbox]').checked = false;
$UI.appsSideMenu.close();
// $UI.toolbar._main_tools[1].querySelector('[type=checkbox]').checked = true;
// $UI.layersSideMenu.open();
$UI.layersViewer.update();
- //$CAMIC.status = null;
+ // $CAMIC.status = null;
}
function anno_callback(data) {
// is form ok?
const noteData = $UI.annotOptPanel._form_.value;
- if ($UI.annotOptPanel._action_.disabled || noteData.name == "") {
+ if ($UI.annotOptPanel._action_.disabled || noteData.name == '') {
// close layer silde
- $UI.toolbar._main_tools[1].querySelector("[type=checkbox]").checked = false;
+ $UI.toolbar._main_tools[1].querySelector('[type=checkbox]').checked = false;
$UI.layersSideMenu.close();
// open app silde
- $UI.toolbar._main_tools[0].querySelector("[type=checkbox]").checked = true;
+ $UI.toolbar._main_tools[0].querySelector('[type=checkbox]').checked = true;
$UI.appsSideMenu.open();
// open annotation list
@@ -1098,11 +1105,11 @@ function anno_callback(data) {
// has Path?
if ($CAMIC.viewer.canvasDrawInstance._path_index === 0) {
- alert("No Markup On Annotation. Try holding and dragging.");
+ alert('No Markup On Annotation. Try holding and dragging.');
return;
}
- //Add new lines to notes to prevent overflow
+ // Add new lines to notes to prevent overflow
str = noteData.notes;
var result_string = '';
while (str.length > 0) {
@@ -1113,7 +1120,7 @@ function anno_callback(data) {
// save
// provenance
- Loading.open($UI.annotOptPanel.elt, "Saving Annotation...");
+ Loading.open($UI.annotOptPanel.elt, 'Saving Annotation...');
const exec_id = randomId();
const annotJson = {
@@ -1121,74 +1128,75 @@ function anno_callback(data) {
created_date: new Date(),
provenance: {
image: {
- slide: $D.params.slideId
+ slide: $D.params.slideId,
},
analysis: {
- source: "human",
+ source: 'human',
execution_id: exec_id,
- name: noteData.name
- }
+ name: noteData.name,
+ },
},
properties: {
- annotations: noteData
+ annotations: noteData,
},
geometries: ImageFeaturesToVieweportFeatures(
- $CAMIC.viewer,
- $CAMIC.viewer.canvasDrawInstance.getImageFeatureCollection()
- )
+ $CAMIC.viewer,
+ $CAMIC.viewer.canvasDrawInstance.getImageFeatureCollection(),
+ ),
};
// save annotation
$CAMIC.store
- .addMark(annotJson)
- .then(data => {
+ .addMark(annotJson)
+ .then((data) => {
// server error
- if (data.error) {
- $UI.message.addWarning(`${data.text}:${data.url}`);
- Loading.close();
- return;
- }
+ if (data.error) {
+ $UI.message.addWarning(`${data.text}:${data.url}`);
+ Loading.close();
+ return;
+ }
- // no data added
- if (data.count < 1) {
- Loading.close();
- $UI.message.addWarning(`Annotation Save Failed`);
- return;
- }
- // create layer data
- const new_item = {
- id: exec_id,
- name: noteData.name,
- typeId: typeIds["human"],
- typeName: "human",
- data: null
- };
- $D.overlayers.push(new_item);
- $UI.layersViewer.addItem(new_item);
- $UI.layersViewerMinor.addItem(
- new_item,
- $minorCAMIC && $minorCAMIC.viewer ? true : false
- );
+ // no data added
+ if (data.count < 1) {
+ Loading.close();
+ $UI.message.addWarning(`Annotation Save Failed`);
+ return;
+ }
+ // create layer data
+ const new_item = {
+ id: exec_id,
+ name: noteData.name,
+ typeId: typeIds['human'],
+ typeName: 'human',
+ data: null,
+ };
+ $D.overlayers.push(new_item);
+ $UI.layersViewer.addItem(new_item);
+ $UI.layersViewerMinor.addItem(
+ new_item,
+ $minorCAMIC && $minorCAMIC.viewer ? true : false,
+ );
- // data for UI
- //return;
- loadAnnotationById(
- $CAMIC,
- $UI.layersViewer.getDataItemById(exec_id),
- saveAnnotCallback
- );
- if ($minorCAMIC && $minorCAMIC.viewer)
+ // data for UI
+ // return;
loadAnnotationById(
- $minorCAMIC,
- $UI.layersViewerMinor.getDataItemById(exec_id),
- null
+ $CAMIC,
+ $UI.layersViewer.getDataItemById(exec_id),
+ saveAnnotCallback,
);
- })
- .catch(e => {
- Loading.close();
- console.log("save failed");
- })
- .finally(() => {});
+ if ($minorCAMIC && $minorCAMIC.viewer) {
+ loadAnnotationById(
+ $minorCAMIC,
+ $UI.layersViewerMinor.getDataItemById(exec_id),
+ null,
+ );
+ }
+ })
+ .catch((e) => {
+ Loading.close();
+ console.log('save failed');
+ })
+ .finally(() => {});
}
function saveAnnotCallback() {
@@ -1199,18 +1207,18 @@ function saveAnnotCallback() {
toggleOffDrawBtns();
$CAMIC.viewer.canvasDrawInstance.clear();
// uncheck pen draw icon and checkbox
- //$UI.toolbar._sub_tools[1].querySelector('[type=checkbox]').checked = false;
+ // $UI.toolbar._sub_tools[1].querySelector('[type=checkbox]').checked = false;
// clear form
$UI.annotOptPanel.clear();
// close app side
- $UI.toolbar._main_tools[0].querySelector("[type=checkbox]").checked = false;
+ $UI.toolbar._main_tools[0].querySelector('[type=checkbox]').checked = false;
$UI.appsSideMenu.close();
// -- START QUIP550 -- //
- //$UI.appsList.triggerContent('annotation','close');
+ // $UI.appsList.triggerContent('annotation','close');
// -- END QUIP550 -- //
// open layer side
- $UI.toolbar._main_tools[1].querySelector("[type=checkbox]").checked = true;
+ $UI.toolbar._main_tools[1].querySelector('[type=checkbox]').checked = true;
$UI.layersSideMenu.open();
$UI.layersViewer.update();
$CAMIC.status = null;
@@ -1224,10 +1232,10 @@ async function callback(data) {
const viewerName = this.toString();
let camic = null;
switch (viewerName) {
- case "main":
+ case 'main':
camic = $CAMIC;
break;
- case "minor":
+ case 'minor':
camic = $minorCAMIC;
break;
default:
@@ -1236,9 +1244,9 @@ async function callback(data) {
data.forEach(function(d) {
const item = d.item;
- if (item.typeName == "segmentation") {
+ if (item.typeName == 'segmentation') {
if (d.isShow) {
- //add
+ // add
camic.viewer.segment.addSegmentId(item.id);
} else {
// remove
@@ -1246,7 +1254,7 @@ async function callback(data) {
}
return;
}
- if (item.typeName == "heatmap") {
+ if (item.typeName == 'heatmap') {
if (
$D.heatMapData &&
$D.heatMapData.provenance.analysis.execution_id == item.id &&
@@ -1263,80 +1271,84 @@ async function callback(data) {
$D.heatMapData.provenance.analysis.execution_id == item.id
) {
const opt = {
- opacity: 0.65, //inputs[2].value,
+ opacity: 0.65, // inputs[2].value,
coverOpacity: 0.001,
data: $D.heatMapData.data,
- //editedData:$D.editedDataClusters,
- mode: "binal",
+ // editedData:$D.editedDataClusters,
+ mode: 'binal',
size: $D.heatMapData.provenance.analysis.size,
fields: $D.heatMapData.provenance.analysis.fields,
- color: "#253494" //inputs[3].value
+ color: '#253494', // inputs[3].value
};
if ($D.heatMapData.provenance.analysis.setting) {
opt.mode = $D.heatMapData.provenance.analysis.setting.mode;
- if ($D.heatMapData.provenance.analysis.setting.field)
+ if ($D.heatMapData.provenance.analysis.setting.field) {
opt.currentFieldName =
$D.heatMapData.provenance.analysis.setting.field;
+ }
}
camic.viewer.createHeatmap(opt);
} else {
- Loading.open(document.body, "Loading Heatmap Data...");
+ Loading.open(document.body, 'Loading Heatmap Data...');
// load heatmap
camic.store
- .getHeatmap($D.params.slideId, item.id)
- .then(function(data) {
- if (Array.isArray(data) && data.length > 0) {
- $D.heatMapData = data[0];
- const opt = {
- opacity: 0.65, //inputs[2].value,
- coverOpacity: 0.001,
- data: $D.heatMapData.data,
- mode: "binal",
- //editedData:$D.editedDataClusters,
- size: $D.heatMapData.provenance.analysis.size,
- fields: $D.heatMapData.provenance.analysis.fields,
- color: "#253494" //inputs[3].value
- };
-
- if ($D.heatMapData.provenance.analysis.setting) {
- opt.mode = $D.heatMapData.provenance.analysis.setting.mode;
- if ($D.heatMapData.provenance.analysis.setting.field)
- opt.currentFieldName =
+ .getHeatmap($D.params.slideId, item.id)
+ .then(function(data) {
+ if (Array.isArray(data) && data.length > 0) {
+ $D.heatMapData = data[0];
+ const opt = {
+ opacity: 0.65, // inputs[2].value,
+ coverOpacity: 0.001,
+ data: $D.heatMapData.data,
+ mode: 'binal',
+ // editedData:$D.editedDataClusters,
+ size: $D.heatMapData.provenance.analysis.size,
+ fields: $D.heatMapData.provenance.analysis.fields,
+ color: '#253494', // inputs[3].value
+ };
+
+ if ($D.heatMapData.provenance.analysis.setting) {
+ opt.mode = $D.heatMapData.provenance.analysis.setting.mode;
+ if ($D.heatMapData.provenance.analysis.setting.field) {
+ opt.currentFieldName =
$D.heatMapData.provenance.analysis.setting.field;
+ }
+ }
+ camic.viewer.createHeatmap(opt);
}
- camic.viewer.createHeatmap(opt);
- }
- })
- .catch(function(error) {
+ })
+ .catch(function(error) {
// heatmap schema
- console.error(error);
- })
- .finally(function() {
- Loading.close();
- if ($D.overlayers) {
- } else {
+ console.error(error);
+ })
+ .finally(function() {
+ Loading.close();
+ if ($D.overlayers) {
+ } else {
// set message
- $UI.message.addError("Loading Heatmap Data Is Error");
- }
- });
+ $UI.message.addError('Loading Heatmap Data Is Error');
+ }
+ });
}
// rest other check box
const cates =
- viewerName == "main"
- ? $UI.layersViewer.setting.categoricalData
- : $UI.layersViewerMinor.setting.categoricalData;
+ viewerName == 'main' ?
+ $UI.layersViewer.setting.categoricalData :
+ $UI.layersViewerMinor.setting.categoricalData;
if (d.isShow) {
- for (let key in cates) {
- cate = cates[key];
- if (cate.item.name == "heatmap") {
- cate.items.forEach(i => {
- if (d !== i && i.isShow) {
- i.elt.querySelector("input[type=checkbox]").checked = false;
- i.isShow = false;
- }
- });
+ for (const key in cates) {
+ if (cates.hasOwnProperty(key)) {
+ cate = cates[key];
+ if (cate.item.name == 'heatmap') {
+ cate.items.forEach((i) => {
+ if (d !== i && i.isShow) {
+ i.elt.querySelector('input[type=checkbox]').checked = false;
+ i.isShow = false;
+ }
+ });
+ }
}
}
}
@@ -1358,103 +1370,103 @@ function minor_callback(data) {
}
function openMinorControlPanel() {
- $UI.layersList.displayContent("left", true, "head");
- $UI.layersList.triggerContent("left", "close");
- $UI.layersList.displayContent("right", true);
- $UI.layersList.triggerContent("right", "open");
+ $UI.layersList.displayContent('left', true, 'head');
+ $UI.layersList.triggerContent('left', 'close');
+ $UI.layersList.displayContent('right', true);
+ $UI.layersList.triggerContent('right', 'open');
}
function closeMinorControlPanel() {
- $UI.layersList.displayContent("left", false, "head");
- $UI.layersList.triggerContent("left", "open");
- $UI.layersList.displayContent("right", false);
- $UI.layersList.triggerContent("right", "close");
+ $UI.layersList.displayContent('left', false, 'head');
+ $UI.layersList.triggerContent('left', 'open');
+ $UI.layersList.displayContent('right', false);
+ $UI.layersList.triggerContent('right', 'close');
}
function loadAnnotationById(camic, layerData, callback) {
layerData.item.loading = true;
const item = layerData.item;
- Loading.open(document.body, "Loading Layers...");
+ Loading.open(document.body, 'Loading Layers...');
$CAMIC.store
- .getMarkByIds([item.id], $D.params.slideId)
- .then(data => {
- delete item.loading;
-
- // response error
- if (data.error) {
- const errorMessage = `${data.text}: ${data.url}`;
- console.error(errorMessage);
- $UI.message.addError(errorMessage, 5000);
- // delete item form layview
- removeElement($D.overlayers, item.id);
- $UI.layersViewer.removeItemById(item.id);
- $UI.layersViewerMinor.removeItemById(item.id);
- return;
- }
+ .getMarkByIds([item.id], $D.params.slideId)
+ .then((data) => {
+ delete item.loading;
- // no data found
- //if(data.length < 1){
- if (!data[0]) {
- console.warn(`Annotation: ${item.name}(${item.id}) doesn't exist.`);
- $UI.message.addWarning(
- `Annotation: ${item.name}(${item.id}) doesn't exist.`,
- 5000
- );
- // delete item form layview
- removeElement($D.overlayers, item.id);
- $UI.layersViewer.removeItemById(item.id);
- $UI.layersViewerMinor.removeItemById(item.id);
- return;
- }
- // for support quip 2.0 data model
- if (data[0].geometry) {
+ // response error
+ if (data.error) {
+ const errorMessage = `${data.text}: ${data.url}`;
+ console.error(errorMessage);
+ $UI.message.addError(errorMessage, 5000);
+ // delete item form layview
+ removeElement($D.overlayers, item.id);
+ $UI.layersViewer.removeItemById(item.id);
+ $UI.layersViewerMinor.removeItemById(item.id);
+ return;
+ }
+
+ // no data found
+ // if(data.length < 1){
+ if (!data[0]) {
+ console.warn(`Annotation: ${item.name}(${item.id}) doesn't exist.`);
+ $UI.message.addWarning(
+ `Annotation: ${item.name}(${item.id}) doesn't exist.`,
+ 5000,
+ );
+ // delete item form layview
+ removeElement($D.overlayers, item.id);
+ $UI.layersViewer.removeItemById(item.id);
+ $UI.layersViewerMinor.removeItemById(item.id);
+ return;
+ }
+ // for support quip 2.0 data model
+ if (data[0].geometry) {
// twist them
- var image = camic.viewer.world.getItemAt(0);
- this.imgWidth = image.source.dimensions.x;
- this.imgHeight = image.source.dimensions.y;
- item.data = data.map(d => {
- d.geometry.coordinates[0] = d.geometry.coordinates[0].map(point => {
- return [
- Math.round(point[0] * imgWidth),
- Math.round(point[1] * imgHeight)
- ];
+ var image = camic.viewer.world.getItemAt(0);
+ this.imgWidth = image.source.dimensions.x;
+ this.imgHeight = image.source.dimensions.y;
+ item.data = data.map((d) => {
+ d.geometry.coordinates[0] = d.geometry.coordinates[0].map((point) => {
+ return [
+ Math.round(point[0] * imgWidth),
+ Math.round(point[1] * imgHeight),
+ ];
+ });
+ d.properties.style = {
+ color: '#000080',
+ lineCap: 'round',
+ lineJoin: 'round',
+ isFill: false,
+ };
+ return {
+ _id: d._id,
+ provenance: d.provenance,
+ properties: d.properties,
+ geometry: d.geometry,
+ };
});
- d.properties.style = {
- color: "#000080",
- lineCap: "round",
- lineJoin: "round",
- isFill: false
- };
- return {
- _id: d._id,
- provenance: d.provenance,
- properties: d.properties,
- geometry: d.geometry
- };
- });
- // if(item) data[0].isShow = item.isShow;
- item.render = old_anno_render;
- item.clickable = false;
- item.hoverable = false;
- } else {
- data[0].geometries = VieweportFeaturesToImageFeatures(
- camic.viewer,
- data[0].geometries
- );
- if (data[0].provenance.analysis.isGrid) {
- const width = $CAMIC.viewer.imagingHelper.imgWidth;
- const height = $CAMIC.viewer.imagingHelper.imgHeight;
-
- const feature = data[0].geometries.features[0];
- const size = feature.properties.size;
- // const points = feature.geometry.coordinates[0];
- // const bounds = feature.bound.coordinates[0];
- feature.properties.size = [
- Math.round(size[0] * width),
- Math.round(size[1] * height)
- ];
+ // if(item) data[0].isShow = item.isShow;
+ item.render = old_anno_render;
+ item.clickable = false;
+ item.hoverable = false;
+ } else {
+ data[0].geometries = VieweportFeaturesToImageFeatures(
+ camic.viewer,
+ data[0].geometries,
+ );
+ if (data[0].provenance.analysis.isGrid) {
+ const width = $CAMIC.viewer.imagingHelper.imgWidth;
+ const height = $CAMIC.viewer.imagingHelper.imgHeight;
+
+ const feature = data[0].geometries.features[0];
+ const size = feature.properties.size;
+ // const points = feature.geometry.coordinates[0];
+ // const bounds = feature.bound.coordinates[0];
+ feature.properties.size = [
+ Math.round(size[0] * width),
+ Math.round(size[1] * height),
+ ];
// feature.geometry.coordinates[0] = points.map(p => [
// Math.round(p[0] * width),
// Math.round(p[1] * height)
@@ -1465,65 +1477,65 @@ function loadAnnotationById(camic, layerData, callback) {
// ]);
// item.data = data[0];
// item.render = anno_brush_render;
- } else {
+ } else {
// data[0].geometries = VieweportFeaturesToImageFeatures(
// camic.viewer,
// data[0].geometries
// );
// item.data = data[0];
// item.render = anno_render;
- }
+ }
- item.data = data[0];
- item.render = anno_render;
- }
+ item.data = data[0];
+ item.render = anno_render;
+ }
- // create lay and update view
- if (layerData.isShow) {
- layerData.layer = camic.viewer.omanager.addOverlay(item);
- camic.viewer.omanager.updateView();
- }
+ // create lay and update view
+ if (layerData.isShow) {
+ layerData.layer = camic.viewer.omanager.addOverlay(item);
+ camic.viewer.omanager.updateView();
+ }
- if (callback) callback.call(layerData);
- })
- .catch(e => {
- console.error(e);
- })
- .finally(() => {
- Loading.close();
- });
+ if (callback) callback.call(layerData);
+ })
+ .catch((e) => {
+ console.error(e);
+ })
+ .finally(() => {
+ Loading.close();
+ });
}
// delete annotation from layer manager view
function removeCallback(layerData) {
item = layerData.item;
- if (item.typeName !== "human") return;
+ if (item.typeName !== 'human') return;
if (!item.data) {
// load layer data
loadAnnotationById($CAMIC, layerData, function() {
anno_delete({
id: layerData.item.id,
oid: layerData.item.data._id.$oid,
- annotation: layerData.item.data.properties.annotation
+ annotation: layerData.item.data.properties.annotation,
});
});
} else {
anno_delete({
id: layerData.item.id,
oid: layerData.item.data._id.$oid,
- annotation: layerData.item.data.properties.annotation
+ annotation: layerData.item.data.properties.annotation,
});
}
}
function locationCallback(layerData) {
item = layerData.item;
- if (item.typeName !== "human" || item.data == null) return;
- if (item.data.geometries.features[0].geometry.type == "Point") {
+ if (item.typeName !== 'human' || item.data == null) return;
+ if (item.data.geometries.features[0].geometry.type == 'Point') {
const bound = item.data.geometries.features[0].bound.coordinates;
const center = $CAMIC.viewer.viewport.imageToViewportCoordinates(
- bound[0],
- bound[1]
+ bound[0],
+ bound[1],
);
$CAMIC.viewer.viewport.panTo(center);
} else {
@@ -1539,10 +1551,10 @@ function locateAnnotation(bound) {
const [minx, miny] = bound[0];
const [maxx, maxy] = bound[2];
const rectangle = $CAMIC.viewer.viewport.imageToViewportRectangle(
- minx,
- miny,
- maxx - minx,
- maxy - miny
+ minx,
+ miny,
+ maxx - minx,
+ maxy - miny,
);
const center = rectangle.getCenter();
$CAMIC.viewer.viewport.fitBounds(rectangle);
@@ -1550,21 +1562,21 @@ function locateAnnotation(bound) {
setTimeout(() => {
const max = $CAMIC.viewer.cazoomctrlInstance.getMaxImageZoom($CAMIC.viewer);
const current = $CAMIC.viewer.viewport.viewportToImageZoom(
- $CAMIC.viewer.viewport.getZoom()
+ $CAMIC.viewer.viewport.getZoom(),
);
if (current > max) {
$CAMIC.viewer.viewport.zoomTo(
- $CAMIC.viewer.viewport.imageToViewportZoom(max),
- center
+ $CAMIC.viewer.viewport.imageToViewportZoom(max),
+ center,
);
}
}, 50);
}
/*
- collapsible list
- 1. Annotation
- 2. Analytics
+ collapsible list
+ 1. Annotation
+ 2. Analytics
*/
function getCurrentItem(data) {
console.log(data);
@@ -1572,28 +1584,29 @@ function getCurrentItem(data) {
// some fake events callback for demo
function annotationSave() {
- $UI.message.add("Annotation Saved");
+ $UI.message.add('Annotation Saved');
}
function algoRun() {
- $UI.message.add("Algo is running...");
+ $UI.message.add('Algo is running...');
}
function saveAnnotation() {
anno_callback.call(null, {
id:
$UI.annotOptPanel.setting.formSchemas[$UI.annotOptPanel._select_.value]
- .id,
- data: $UI.annotOptPanel._form_.value
+ .id,
+ data: $UI.annotOptPanel._form_.value,
});
}
function saveAnalytics() {
- console.log("saveAnalytics");
+ console.log('saveAnalytics');
}
function startDrawing(e) {
if (
- $UI.toolbar.getSubTool("preset_label") && $UI.toolbar.getSubTool("preset_label").querySelector("input[type=checkbox]")
- .checked
+ $UI.toolbar.getSubTool('preset_label') &&
+ $UI.toolbar.getSubTool('preset_label').querySelector('input[type=checkbox]')
+ .checked
) {
// ||
// $UI.toolbar.getSubTool("brush").querySelector("input[type=checkbox]")
@@ -1613,15 +1626,15 @@ function startDrawing(e) {
function stopDrawing(e) {
// preset label annotation
if (
- $UI.toolbar.getSubTool("preset_label") && $UI.toolbar.getSubTool("preset_label").querySelector("input[type=checkbox]")
- .checked
+ $UI.toolbar.getSubTool('preset_label') &&
+ $UI.toolbar.getSubTool('preset_label').querySelector('input[type=checkbox]').checked
) {
// save preset label
savePresetLabel();
} else {
// annotation
- const li = $UI.toolbar.getSubTool("annotation");
- const state = +li.querySelector("label").dataset.state;
+ const li = $UI.toolbar.getSubTool('annotation');
+ const state = +li.querySelector('label').dataset.state;
if (
state === 1 &&
$CAMIC.viewer.canvasDrawInstance._draws_data_.length > 0
@@ -1633,11 +1646,11 @@ function stopDrawing(e) {
function openHeatmap() {
switch (ImgloaderMode) {
- case "iip":
+ case 'iip':
// hosted
hostedHeatmap();
break;
- case "imgbox":
+ case 'imgbox':
// nano borb
imgboxHeatmap();
break;
@@ -1650,41 +1663,41 @@ function hostedHeatmap() {
const slide = $D.params.slideId;
const slideName = $D.params.data.name;
$CAMIC.store
- .findHeatmapType(slide)
- //
- .then(function(list) {
- if (typeof list === "undefined") {
- list = [];
- }
- // get heatmap data
- if (!list.length) {
- alert(`${slideName} Has No Heatmap Data.`);
- return;
- }
- createHeatMapList(list);
- })
- //
- .catch(function(error) {
- console.error(error);
- })
- //
- .finally(function() {
- if ($D.templates) {
+ .findHeatmapType(slide)
+ //
+ .then(function(list) {
+ if (typeof list === 'undefined') {
+ list = [];
+ }
+ // get heatmap data
+ if (!list.length) {
+ alert(`${slideName} Has No Heatmap Data.`);
+ return;
+ }
+ createHeatMapList(list);
+ })
+ //
+ .catch(function(error) {
+ console.error(error);
+ })
+ //
+ .finally(function() {
+ if ($D.templates) {
// load UI
- } else {
+ } else {
// set message
- $UI.message.addError("HeatmapList");
- }
- });
+ $UI.message.addError('HeatmapList');
+ }
+ });
}
function imgboxHeatmap() {
let slide = $D.params.id;
slide = decodeURIComponent(slide);
// create file input
- var element = document.createElement("input");
- element.setAttribute("type", "file");
- element.style.display = "none";
+ var element = document.createElement('input');
+ element.setAttribute('type', 'file');
+ element.style.display = 'none';
document.body.appendChild(element);
element.onchange = function(event) {
@@ -1693,7 +1706,7 @@ function imgboxHeatmap() {
reader.onload = function() {
var text = reader.result;
try {
- let data = JSON.parse(text);
+ const data = JSON.parse(text);
var valid = $VALIDATION.heatmap(data);
if (!valid) {
@@ -1705,19 +1718,19 @@ function imgboxHeatmap() {
data.provenance.image.slide = slide;
const execId = data.provenance.analysis.execution_id;
- Loading.open(document.body, "Loading Heatmap...");
+ Loading.open(document.body, 'Loading Heatmap...');
$CAMIC.store
- .addHeatmap(data)
- .then(rs => {
- window.location.href = `../heatmap/heatmap.html${window.location.search}&execId=${execId}`;
- })
- .catch(e => {
- $UI.message.addError(e);
- console.error(e);
- })
- .finally(() => {
- Loading.close();
- });
+ .addHeatmap(data)
+ .then((rs) => {
+ window.location.href = `../heatmap/heatmap.html${window.location.search}&execId=${execId}`;
+ })
+ .catch((e) => {
+ $UI.message.addError(e);
+ console.error(e);
+ })
+ .finally(() => {
+ Loading.close();
+ });
} catch (e) {
console.error(e);
Loading.close();
@@ -1731,16 +1744,16 @@ function imgboxHeatmap() {
function createHeatMapList(list) {
empty($UI.modalbox.body);
- list.forEach(data => {
+ list.forEach((data) => {
const exec_id = data.provenance.analysis.execution_id;
- const a = document.createElement("a");
+ const a = document.createElement('a');
const params = getUrlVars();
- a.href = params.mode
- ? `../heatmap/heatmap.html?slideId=${$D.params.slideId}&execId=${exec_id}&mode=pathdb`
- : `../heatmap/heatmap.html?slideId=${$D.params.slideId}&execId=${exec_id}`;
+ a.href = params.mode ?
+ `../heatmap/heatmap.html?slideId=${$D.params.slideId}&execId=${exec_id}&mode=pathdb` :
+ `../heatmap/heatmap.html?slideId=${$D.params.slideId}&execId=${exec_id}`;
a.textContent = exec_id;
$UI.modalbox.body.appendChild(a);
- $UI.modalbox.body.appendChild(document.createElement("br"));
+ $UI.modalbox.body.appendChild(document.createElement('br'));
});
$UI.modalbox.open();
}
diff --git a/common/FileSaver.min.js b/common/FileSaver.min.js
old mode 100755
new mode 100644
diff --git a/common/ajv.js b/common/ajv.js
index 37631d535..23ef6baa5 100644
--- a/common/ajv.js
+++ b/common/ajv.js
@@ -5187,9 +5187,9 @@ function escapeJsonPtr(str) {
},{}],44:[function(require,module,exports){
/** @license URI.js v4.2.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */
(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (factory((global.URI = global.URI || {})));
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
+ (factory((global.URI = global.URI || {})));
}(this, (function (exports) { 'use strict';
function merge() {
@@ -5417,9 +5417,9 @@ var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
/** Error messages */
var errors = {
- 'overflow': 'Overflow: input needs wider integers to process',
- 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
- 'invalid-input': 'Invalid input'
+ 'overflow': 'Overflow: input needs wider integers to process',
+ 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
+ 'invalid-input': 'Invalid input'
};
/** Convenience shortcuts */
@@ -5436,7 +5436,7 @@ var stringFromCharCode = String.fromCharCode;
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error$1(type) {
- throw new RangeError(errors[type]);
+ throw new RangeError(errors[type]);
}
/**
@@ -5448,12 +5448,12 @@ function error$1(type) {
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
- var result = [];
- var length = array.length;
- while (length--) {
- result[length] = fn(array[length]);
- }
- return result;
+ var result = [];
+ var length = array.length;
+ while (length--) {
+ result[length] = fn(array[length]);
+ }
+ return result;
}
/**
@@ -5467,19 +5467,19 @@ function map(array, fn) {
* function.
*/
function mapDomain(string, fn) {
- var parts = string.split('@');
- var result = '';
- if (parts.length > 1) {
- // In email addresses, only the domain name should be punycoded. Leave
- // the local part (i.e. everything up to `@`) intact.
- result = parts[0] + '@';
- string = parts[1];
- }
- // Avoid `split(regex)` for IE8 compatibility. See #17.
- string = string.replace(regexSeparators, '\x2E');
- var labels = string.split('.');
- var encoded = map(labels, fn).join('.');
- return result + encoded;
+ var parts = string.split('@');
+ var result = '';
+ if (parts.length > 1) {
+ // In email addresses, only the domain name should be punycoded. Leave
+ // the local part (i.e. everything up to `@`) intact.
+ result = parts[0] + '@';
+ string = parts[1];
+ }
+ // Avoid `split(regex)` for IE8 compatibility. See #17.
+ string = string.replace(regexSeparators, '\x2E');
+ var labels = string.split('.');
+ var encoded = map(labels, fn).join('.');
+ return result + encoded;
}
/**
@@ -5496,28 +5496,28 @@ function mapDomain(string, fn) {
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
- var output = [];
- var counter = 0;
- var length = string.length;
- while (counter < length) {
- var value = string.charCodeAt(counter++);
- if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
- // It's a high surrogate, and there is a next character.
- var extra = string.charCodeAt(counter++);
- if ((extra & 0xFC00) == 0xDC00) {
- // Low surrogate.
- output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
- } else {
- // It's an unmatched surrogate; only append this code unit, in case the
- // next code unit is the high surrogate of a surrogate pair.
- output.push(value);
- counter--;
- }
- } else {
- output.push(value);
- }
- }
- return output;
+ var output = [];
+ var counter = 0;
+ var length = string.length;
+ while (counter < length) {
+ var value = string.charCodeAt(counter++);
+ if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
+ // It's a high surrogate, and there is a next character.
+ var extra = string.charCodeAt(counter++);
+ if ((extra & 0xFC00) == 0xDC00) {
+ // Low surrogate.
+ output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
+ } else {
+ // It's an unmatched surrogate; only append this code unit, in case the
+ // next code unit is the high surrogate of a surrogate pair.
+ output.push(value);
+ counter--;
+ }
+ } else {
+ output.push(value);
+ }
+ }
+ return output;
}
/**
@@ -5529,7 +5529,7 @@ function ucs2decode(string) {
* @returns {String} The new Unicode string (UCS-2).
*/
var ucs2encode = function ucs2encode(array) {
- return String.fromCodePoint.apply(String, toConsumableArray(array));
+ return String.fromCodePoint.apply(String, toConsumableArray(array));
};
/**
@@ -5542,16 +5542,16 @@ var ucs2encode = function ucs2encode(array) {
* the code point does not represent a value.
*/
var basicToDigit = function basicToDigit(codePoint) {
- if (codePoint - 0x30 < 0x0A) {
- return codePoint - 0x16;
- }
- if (codePoint - 0x41 < 0x1A) {
- return codePoint - 0x41;
- }
- if (codePoint - 0x61 < 0x1A) {
- return codePoint - 0x61;
- }
- return base;
+ if (codePoint - 0x30 < 0x0A) {
+ return codePoint - 0x16;
+ }
+ if (codePoint - 0x41 < 0x1A) {
+ return codePoint - 0x41;
+ }
+ if (codePoint - 0x61 < 0x1A) {
+ return codePoint - 0x61;
+ }
+ return base;
};
/**
@@ -5566,9 +5566,9 @@ var basicToDigit = function basicToDigit(codePoint) {
* if `flag` is non-zero and `digit` has no uppercase form.
*/
var digitToBasic = function digitToBasic(digit, flag) {
- // 0..25 map to ASCII a..z or A..Z
- // 26..35 map to ASCII 0..9
- return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
+ // 0..25 map to ASCII a..z or A..Z
+ // 26..35 map to ASCII 0..9
+ return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};
/**
@@ -5577,13 +5577,13 @@ var digitToBasic = function digitToBasic(digit, flag) {
* @private
*/
var adapt = function adapt(delta, numPoints, firstTime) {
- var k = 0;
- delta = firstTime ? floor(delta / damp) : delta >> 1;
- delta += floor(delta / numPoints);
- for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {
- delta = floor(delta / baseMinusTMin);
- }
- return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
+ var k = 0;
+ delta = firstTime ? floor(delta / damp) : delta >> 1;
+ delta += floor(delta / numPoints);
+ for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {
+ delta = floor(delta / baseMinusTMin);
+ }
+ return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};
/**
@@ -5594,85 +5594,85 @@ var adapt = function adapt(delta, numPoints, firstTime) {
* @returns {String} The resulting string of Unicode symbols.
*/
var decode = function decode(input) {
- // Don't use UCS-2.
- var output = [];
- var inputLength = input.length;
- var i = 0;
- var n = initialN;
- var bias = initialBias;
-
- // Handle the basic code points: let `basic` be the number of input code
- // points before the last delimiter, or `0` if there is none, then copy
- // the first basic code points to the output.
-
- var basic = input.lastIndexOf(delimiter);
- if (basic < 0) {
- basic = 0;
- }
-
- for (var j = 0; j < basic; ++j) {
- // if it's not a basic code point
- if (input.charCodeAt(j) >= 0x80) {
- error$1('not-basic');
- }
- output.push(input.charCodeAt(j));
- }
-
- // Main decoding loop: start just after the last delimiter if any basic code
- // points were copied; start at the beginning otherwise.
-
- for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{
-
- // `index` is the index of the next character to be consumed.
- // Decode a generalized variable-length integer into `delta`,
- // which gets added to `i`. The overflow checking is easier
- // if we increase `i` as we go, then subtract off its starting
- // value at the end to obtain `delta`.
- var oldi = i;
- for (var w = 1, k = base;; /* no condition */k += base) {
-
- if (index >= inputLength) {
- error$1('invalid-input');
- }
-
- var digit = basicToDigit(input.charCodeAt(index++));
-
- if (digit >= base || digit > floor((maxInt - i) / w)) {
- error$1('overflow');
- }
-
- i += digit * w;
- var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
-
- if (digit < t) {
- break;
- }
-
- var baseMinusT = base - t;
- if (w > floor(maxInt / baseMinusT)) {
- error$1('overflow');
- }
-
- w *= baseMinusT;
- }
-
- var out = output.length + 1;
- bias = adapt(i - oldi, out, oldi == 0);
-
- // `i` was supposed to wrap around from `out` to `0`,
- // incrementing `n` each time, so we'll fix that now:
- if (floor(i / out) > maxInt - n) {
- error$1('overflow');
- }
-
- n += floor(i / out);
- i %= out;
-
- // Insert `n` at position `i` of the output.
- output.splice(i++, 0, n);
- }
-
- return String.fromCodePoint.apply(String, output);
+ // Don't use UCS-2.
+ var output = [];
+ var inputLength = input.length;
+ var i = 0;
+ var n = initialN;
+ var bias = initialBias;
+
+ // Handle the basic code points: let `basic` be the number of input code
+ // points before the last delimiter, or `0` if there is none, then copy
+ // the first basic code points to the output.
+
+ var basic = input.lastIndexOf(delimiter);
+ if (basic < 0) {
+ basic = 0;
+ }
+
+ for (var j = 0; j < basic; ++j) {
+ // if it's not a basic code point
+ if (input.charCodeAt(j) >= 0x80) {
+ error$1('not-basic');
+ }
+ output.push(input.charCodeAt(j));
+ }
+
+ // Main decoding loop: start just after the last delimiter if any basic code
+ // points were copied; start at the beginning otherwise.
+
+ for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{
+
+ // `index` is the index of the next character to be consumed.
+ // Decode a generalized variable-length integer into `delta`,
+ // which gets added to `i`. The overflow checking is easier
+ // if we increase `i` as we go, then subtract off its starting
+ // value at the end to obtain `delta`.
+ var oldi = i;
+ for (var w = 1, k = base;; /* no condition */k += base) {
+
+ if (index >= inputLength) {
+ error$1('invalid-input');
+ }
+
+ var digit = basicToDigit(input.charCodeAt(index++));
+
+ if (digit >= base || digit > floor((maxInt - i) / w)) {
+ error$1('overflow');
+ }
+
+ i += digit * w;
+ var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
+
+ if (digit < t) {
+ break;
+ }
+
+ var baseMinusT = base - t;
+ if (w > floor(maxInt / baseMinusT)) {
+ error$1('overflow');
+ }
+
+ w *= baseMinusT;
+ }
+
+ var out = output.length + 1;
+ bias = adapt(i - oldi, out, oldi == 0);
+
+ // `i` was supposed to wrap around from `out` to `0`,
+ // incrementing `n` each time, so we'll fix that now:
+ if (floor(i / out) > maxInt - n) {
+ error$1('overflow');
+ }
+
+ n += floor(i / out);
+ i %= out;
+
+ // Insert `n` at position `i` of the output.
+ output.splice(i++, 0, n);
+ }
+
+ return String.fromCodePoint.apply(String, output);
};
/**
@@ -5683,152 +5683,152 @@ var decode = function decode(input) {
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
var encode = function encode(input) {
- var output = [];
-
- // Convert the input in UCS-2 to an array of Unicode code points.
- input = ucs2decode(input);
-
- // Cache the length.
- var inputLength = input.length;
-
- // Initialize the state.
- var n = initialN;
- var delta = 0;
- var bias = initialBias;
-
- // Handle the basic code points.
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
-
- try {
- for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _currentValue2 = _step.value;
-
- if (_currentValue2 < 0x80) {
- output.push(stringFromCharCode(_currentValue2));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
-
- var basicLength = output.length;
- var handledCPCount = basicLength;
-
- // `handledCPCount` is the number of code points that have been handled;
- // `basicLength` is the number of basic code points.
-
- // Finish the basic string with a delimiter unless it's empty.
- if (basicLength) {
- output.push(delimiter);
- }
-
- // Main encoding loop:
- while (handledCPCount < inputLength) {
-
- // All non-basic code points < n have been handled already. Find the next
- // larger one:
- var m = maxInt;
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
-
- try {
- for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var currentValue = _step2.value;
-
- if (currentValue >= n && currentValue < m) {
- m = currentValue;
- }
- }
-
- // Increase `delta` enough to advance the decoder's
state to ,
- // but guard against overflow.
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
-
- var handledCPCountPlusOne = handledCPCount + 1;
- if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
- error$1('overflow');
- }
-
- delta += (m - n) * handledCPCountPlusOne;
- n = m;
-
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
-
- try {
- for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var _currentValue = _step3.value;
-
- if (_currentValue < n && ++delta > maxInt) {
- error$1('overflow');
- }
- if (_currentValue == n) {
- // Represent delta as a generalized variable-length integer.
- var q = delta;
- for (var k = base;; /* no condition */k += base) {
- var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
- if (q < t) {
- break;
- }
- var qMinusT = q - t;
- var baseMinusT = base - t;
- output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
- q = floor(qMinusT / baseMinusT);
- }
-
- output.push(stringFromCharCode(digitToBasic(q, 0)));
- bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
- delta = 0;
- ++handledCPCount;
- }
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
-
- ++delta;
- ++n;
- }
- return output.join('');
+ var output = [];
+
+ // Convert the input in UCS-2 to an array of Unicode code points.
+ input = ucs2decode(input);
+
+ // Cache the length.
+ var inputLength = input.length;
+
+ // Initialize the state.
+ var n = initialN;
+ var delta = 0;
+ var bias = initialBias;
+
+ // Handle the basic code points.
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+
+ try {
+ for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var _currentValue2 = _step.value;
+
+ if (_currentValue2 < 0x80) {
+ output.push(stringFromCharCode(_currentValue2));
+ }
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+
+ var basicLength = output.length;
+ var handledCPCount = basicLength;
+
+ // `handledCPCount` is the number of code points that have been handled;
+ // `basicLength` is the number of basic code points.
+
+ // Finish the basic string with a delimiter unless it's empty.
+ if (basicLength) {
+ output.push(delimiter);
+ }
+
+ // Main encoding loop:
+ while (handledCPCount < inputLength) {
+
+ // All non-basic code points < n have been handled already. Find the next
+ // larger one:
+ var m = maxInt;
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+
+ try {
+ for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
+ var currentValue = _step2.value;
+
+ if (currentValue >= n && currentValue < m) {
+ m = currentValue;
+ }
+ }
+
+ // Increase `delta` enough to advance the decoder's state to ,
+ // but guard against overflow.
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2.return) {
+ _iterator2.return();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+
+ var handledCPCountPlusOne = handledCPCount + 1;
+ if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
+ error$1('overflow');
+ }
+
+ delta += (m - n) * handledCPCountPlusOne;
+ n = m;
+
+ var _iteratorNormalCompletion3 = true;
+ var _didIteratorError3 = false;
+ var _iteratorError3 = undefined;
+
+ try {
+ for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
+ var _currentValue = _step3.value;
+
+ if (_currentValue < n && ++delta > maxInt) {
+ error$1('overflow');
+ }
+ if (_currentValue == n) {
+ // Represent delta as a generalized variable-length integer.
+ var q = delta;
+ for (var k = base;; /* no condition */k += base) {
+ var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
+ if (q < t) {
+ break;
+ }
+ var qMinusT = q - t;
+ var baseMinusT = base - t;
+ output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
+ q = floor(qMinusT / baseMinusT);
+ }
+
+ output.push(stringFromCharCode(digitToBasic(q, 0)));
+ bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
+ delta = 0;
+ ++handledCPCount;
+ }
+ }
+ } catch (err) {
+ _didIteratorError3 = true;
+ _iteratorError3 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion3 && _iterator3.return) {
+ _iterator3.return();
+ }
+ } finally {
+ if (_didIteratorError3) {
+ throw _iteratorError3;
+ }
+ }
+ }
+
+ ++delta;
+ ++n;
+ }
+ return output.join('');
};
/**
@@ -5843,9 +5843,9 @@ var encode = function encode(input) {
* string.
*/
var toUnicode = function toUnicode(input) {
- return mapDomain(input, function (string) {
- return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
- });
+ return mapDomain(input, function (string) {
+ return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
+ });
};
/**
@@ -5860,36 +5860,36 @@ var toUnicode = function toUnicode(input) {
* email address.
*/
var toASCII = function toASCII(input) {
- return mapDomain(input, function (string) {
- return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
- });
+ return mapDomain(input, function (string) {
+ return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
+ });
};
/*--------------------------------------------------------------------------*/
/** Define the public API */
var punycode = {
- /**
+ /**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
- 'version': '2.1.0',
- /**
+ 'version': '2.1.0',
+ /**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see
* @memberOf punycode
* @type Object
*/
- 'ucs2': {
- 'decode': ucs2decode,
- 'encode': ucs2encode
- },
- 'decode': decode,
- 'encode': encode,
- 'toASCII': toASCII,
- 'toUnicode': toUnicode
+ 'ucs2': {
+ 'decode': ucs2decode,
+ 'encode': ucs2encode
+ },
+ 'decode': decode,
+ 'encode': encode,
+ 'toASCII': toASCII,
+ 'toUnicode': toUnicode
};
/**
diff --git a/common/colorSeparation.js b/common/colorSeparation.js
index 683d8b494..5e011619d 100644
--- a/common/colorSeparation.js
+++ b/common/colorSeparation.js
@@ -116,7 +116,7 @@ function colorDeconvolution(image, doIshow) {
//console.log("DeCon Values:",MODx,MODy,MODz,cosx,cosy,cosz,A,V,C,q);
let pixels = image.data;
- let newpixels = [];
+ let newpixels = [];
newpixels[0] = [];
newpixels[1] = [];
newpixels[2] = [];
@@ -178,7 +178,7 @@ function canvas2RGBArray(image,cols,rows) {
let arr=[];
for(j=0;j 0);
- }
-
- getCluster(index,name,value,color){
- return this.clusters.find(cluster => cluster.index==index&&cluster.name==name&&cluster.value==value&&cluster.color==color);
- }
-
- getClusterIndex(index,name,value,color){
- return this.clusters.findIndex(cluster => cluster.index==index&&cluster.name==name&&cluster.value==value&&cluster.color==color);
- }
- addCluster(cluster){
- this.clusters.push(cluster);
- }
- addEditDateForCluster(index, name, value, color, editData){
- if(!Array.isArray(editData)) return;
- let cluster = this.getCluster(index, name, value, color);
- if(!cluster){
- cluster = new EditDataCollection(index, name, value, color);
- this.clusters.push(cluster);
- }
- cluster.addEditData(editData)
- }
+
+ constructor(clusters=[]){
+ this.clusters = clusters;
+ }
+
+ isEmpty(){
+ return !(this.clusters&&this.clusters.length > 0);
+ }
+
+ getCluster(index,name,value,color){
+ return this.clusters.find(cluster => cluster.index==index&&cluster.name==name&&cluster.value==value&&cluster.color==color);
+ }
+
+ getClusterIndex(index,name,value,color){
+ return this.clusters.findIndex(cluster => cluster.index==index&&cluster.name==name&&cluster.value==value&&cluster.color==color);
+ }
+ addCluster(cluster){
+ this.clusters.push(cluster);
+ }
+ addEditDateForCluster(index, name, value, color, editData){
+ if(!Array.isArray(editData)) return;
+ let cluster = this.getCluster(index, name, value, color);
+ if(!cluster){
+ cluster = new EditDataCollection(index, name, value, color);
+ this.clusters.push(cluster);
+ }
+ cluster.addEditData(editData)
+ }
- removeEditDataForCluster(index,name,value,color, idx = null){
- const clusterIdx = this.getClusterIndex(index,name,value,color);
-
- if(clusterIdx ==-1) return;
- const cluster = this.clusters[clusterIdx];
- if(idx==null){ // remove all
- this.clusters.splice(clusterIdx,1);
- } else {
- cluster.removeEditDataByIndex(idx);
- if(cluster.editDataArray.length==0) this.clusters.splice(clusterIdx,1);
- }
- }
-
- toJSON(){
- const list = [];
- this.clusters.forEach(cluster=>{list.push(cluster.toJSON())});
- return list;
- }
+ removeEditDataForCluster(index,name,value,color, idx = null){
+ const clusterIdx = this.getClusterIndex(index,name,value,color);
+
+ if(clusterIdx ==-1) return;
+ const cluster = this.clusters[clusterIdx];
+ if(idx==null){ // remove all
+ this.clusters.splice(clusterIdx,1);
+ } else {
+ cluster.removeEditDataByIndex(idx);
+ if(cluster.editDataArray.length==0) this.clusters.splice(clusterIdx,1);
+ }
+ }
+
+ toJSON(){
+ const list = [];
+ this.clusters.forEach(cluster=>{list.push(cluster.toJSON())});
+ return list;
+ }
}
diff --git a/common/jszip.min.js b/common/jszip.min.js
old mode 100755
new mode 100644
diff --git a/common/paths.js b/common/paths.js
old mode 100755
new mode 100644
diff --git a/common/pureform/document-register-element.js b/common/pureform/document-register-element.js
old mode 100755
new mode 100644
diff --git a/common/pureform/pure-form.js b/common/pureform/pure-form.js
old mode 100755
new mode 100644
diff --git a/common/pureform/pure-form.min.js b/common/pureform/pure-form.min.js
old mode 100755
new mode 100644
diff --git a/common/rangeslider/rangeslider.js b/common/rangeslider/rangeslider.js
old mode 100755
new mode 100644
index 32f479808..8ff4efe6f
--- a/common/rangeslider/rangeslider.js
+++ b/common/rangeslider/rangeslider.js
@@ -1,367 +1,367 @@
(function () {
- 'use strict';
-
- var RS = function (conf) {
- this.input = null;
- this.inputDisplay = null;
- this.slider = null;
- this.sliderWidth = 0;
- this.sliderLeft = 0;
- this.pointerWidth = 0;
- this.pointerR = null;
- this.pointerL = null;
- this.activePointer = null;
- this.selected = null;
- this.scale = null;
- this.step = 0;
- this.tipL = null;
- this.tipR = null;
- this.timeout = null;
- this.valRange = false;
-
- this.values = {
- start: null,
- end: null
- };
- this.conf = {
- target: null,
- values: null,
- set: null,
- range: false,
- width: null,
- scale: true,
- labels: true,
- tooltip: true,
- step: null,
- disabled: false,
- onChange: null
- };
-
- this.cls = {
- container: 'rs-container',
- background: 'rs-bg',
- selected: 'rs-selected',
- pointer: 'rs-pointer',
- scale: 'rs-scale',
- noscale: 'rs-noscale',
- tip: 'rs-tooltip'
- };
-
- for (var i in this.conf) { if (conf.hasOwnProperty(i)) this.conf[i] = conf[i]; }
-
- this.init();
- };
- RS.prototype.display = function(isDisplay){
- this.slider.style.display = isDisplay?'':'none';
- }
- RS.prototype.init = function () {
- if (typeof this.conf.target === 'object') this.input = this.conf.target;
- else this.input = document.getElementById(this.conf.target.replace('#', ''));
-
- if (!this.input) return console.log('Cannot find target element...');
-
- this.inputDisplay = getComputedStyle(this.input, null).display;
- this.input.style.display = 'none';
- this.valRange = !(this.conf.values instanceof Array);
-
- if (this.valRange) {
- if (!this.conf.values.hasOwnProperty('min') || !this.conf.values.hasOwnProperty('max'))
- return console.log('Missing min or max value...');
- }
- return this.createSlider();
- };
-
- RS.prototype.createSlider = function () {
- this.slider = createElement('div', this.cls.container);
- this.slider.innerHTML = '
';
- this.selected = createElement('div', this.cls.selected);
- this.pointerL = createElement('div', this.cls.pointer, ['dir', 'left']);
- //this.scale = createElement('div', this.cls.scale);
-
- if (this.conf.tooltip) {
- this.tipL = createElement('div', this.cls.tip);
- this.tipR = createElement('div', this.cls.tip);
- this.pointerL.appendChild(this.tipL);
- }
- this.slider.appendChild(this.selected);
- //this.slider.appendChild(this.scale);
- this.slider.appendChild(this.pointerL);
-
- if (this.conf.range) {
- this.pointerR = createElement('div', this.cls.pointer, ['dir', 'right']);
- if (this.conf.tooltip) this.pointerR.appendChild(this.tipR);
- this.slider.appendChild(this.pointerR);
- }
-
- this.input.parentNode.insertBefore(this.slider, this.input.nextSibling);
+ 'use strict';
+
+ var RS = function (conf) {
+ this.input = null;
+ this.inputDisplay = null;
+ this.slider = null;
+ this.sliderWidth = 0;
+ this.sliderLeft = 0;
+ this.pointerWidth = 0;
+ this.pointerR = null;
+ this.pointerL = null;
+ this.activePointer = null;
+ this.selected = null;
+ this.scale = null;
+ this.step = 0;
+ this.tipL = null;
+ this.tipR = null;
+ this.timeout = null;
+ this.valRange = false;
+
+ this.values = {
+ start: null,
+ end: null
+ };
+ this.conf = {
+ target: null,
+ values: null,
+ set: null,
+ range: false,
+ width: null,
+ scale: true,
+ labels: true,
+ tooltip: true,
+ step: null,
+ disabled: false,
+ onChange: null
+ };
+
+ this.cls = {
+ container: 'rs-container',
+ background: 'rs-bg',
+ selected: 'rs-selected',
+ pointer: 'rs-pointer',
+ scale: 'rs-scale',
+ noscale: 'rs-noscale',
+ tip: 'rs-tooltip'
+ };
+
+ for (var i in this.conf) { if (conf.hasOwnProperty(i)) this.conf[i] = conf[i]; }
+
+ this.init();
+ };
+ RS.prototype.display = function(isDisplay){
+ this.slider.style.display = isDisplay?'':'none';
+ }
+ RS.prototype.init = function () {
+ if (typeof this.conf.target === 'object') this.input = this.conf.target;
+ else this.input = document.getElementById(this.conf.target.replace('#', ''));
+
+ if (!this.input) return console.log('Cannot find target element...');
+
+ this.inputDisplay = getComputedStyle(this.input, null).display;
+ this.input.style.display = 'none';
+ this.valRange = !(this.conf.values instanceof Array);
+
+ if (this.valRange) {
+ if (!this.conf.values.hasOwnProperty('min') || !this.conf.values.hasOwnProperty('max'))
+ return console.log('Missing min or max value...');
+ }
+ return this.createSlider();
+ };
+
+ RS.prototype.createSlider = function () {
+ this.slider = createElement('div', this.cls.container);
+ this.slider.innerHTML = '
';
+ this.selected = createElement('div', this.cls.selected);
+ this.pointerL = createElement('div', this.cls.pointer, ['dir', 'left']);
+ //this.scale = createElement('div', this.cls.scale);
+
+ if (this.conf.tooltip) {
+ this.tipL = createElement('div', this.cls.tip);
+ this.tipR = createElement('div', this.cls.tip);
+ this.pointerL.appendChild(this.tipL);
+ }
+ this.slider.appendChild(this.selected);
+ //this.slider.appendChild(this.scale);
+ this.slider.appendChild(this.pointerL);
+
+ if (this.conf.range) {
+ this.pointerR = createElement('div', this.cls.pointer, ['dir', 'right']);
+ if (this.conf.tooltip) this.pointerR.appendChild(this.tipR);
+ this.slider.appendChild(this.pointerR);
+ }
+
+ this.input.parentNode.insertBefore(this.slider, this.input.nextSibling);
if (this.conf.width) this.slider.style.width = parseInt(this.conf.width) + 'px';
- this.sliderLeft = this.slider.getBoundingClientRect().left;
- this.sliderWidth = this.slider.clientWidth;
- this.pointerWidth = this.pointerL.clientWidth;
+ this.sliderLeft = this.slider.getBoundingClientRect().left;
+ this.sliderWidth = this.slider.clientWidth;
+ this.pointerWidth = this.pointerL.clientWidth;
- if (!this.conf.scale) this.slider.classList.add(this.cls.noscale);
+ if (!this.conf.scale) this.slider.classList.add(this.cls.noscale);
- return this.setInitialValues();
- };
+ return this.setInitialValues();
+ };
- RS.prototype.setInitialValues = function () {
- this.disabled(this.conf.disabled);
+ RS.prototype.setInitialValues = function () {
+ this.disabled(this.conf.disabled);
- if (this.valRange) this.conf.values = prepareArrayValues(this.conf);
+ if (this.valRange) this.conf.values = prepareArrayValues(this.conf);
- this.values.start = 0;
- this.values.end = this.conf.range ? this.conf.values.length - 1 : 0;
+ this.values.start = 0;
+ this.values.end = this.conf.range ? this.conf.values.length - 1 : 0;
- if (this.conf.set && this.conf.set.length && checkInitial(this.conf)) {
- var vals = this.conf.set;
+ if (this.conf.set && this.conf.set.length && checkInitial(this.conf)) {
+ var vals = this.conf.set;
- if (this.conf.range) {
- this.values.start = this.conf.values.indexOf(vals[0]);
- this.values.end = this.conf.set[1] ? this.conf.values.indexOf(vals[1]) : null;
- }
- else this.values.end = this.conf.values.indexOf(vals[0]);
- }
- return this.createScale();
- };
+ if (this.conf.range) {
+ this.values.start = this.conf.values.indexOf(vals[0]);
+ this.values.end = this.conf.set[1] ? this.conf.values.indexOf(vals[1]) : null;
+ }
+ else this.values.end = this.conf.values.indexOf(vals[0]);
+ }
+ return this.createScale();
+ };
- RS.prototype.createScale = function (resize) {
- this.step = this.sliderWidth / (this.conf.values.length - 1);
+ RS.prototype.createScale = function (resize) {
+ this.step = this.sliderWidth / (this.conf.values.length - 1);
- //for (var i = 0, iLen = this.conf.values.length; i < iLen; i++) {
- //var span = createElement('span')
- //ins = createElement('ins');
+ //for (var i = 0, iLen = this.conf.values.length; i < iLen; i++) {
+ //var span = createElement('span')
+ //ins = createElement('ins');
- //span.appendChild(ins);
- //this.scale.appendChild(span);
+ //span.appendChild(ins);
+ //this.scale.appendChild(span);
- //span.style.width = i === iLen - 1 ? 0 : this.step + 'px';
+ //span.style.width = i === iLen - 1 ? 0 : this.step + 'px';
- // if (!this.conf.labels) {
- // if (i === 0 || i === iLen - 1) ins.innerHTML = this.conf.values[i]
- // }
- //else ins.innerHTML = this.conf.values[i];
+ // if (!this.conf.labels) {
+ // if (i === 0 || i === iLen - 1) ins.innerHTML = this.conf.values[i]
+ // }
+ //else ins.innerHTML = this.conf.values[i];
- //ins.style.marginLeft = (ins.clientWidth / 2) * - 1 + 'px';
- //}
- return this.addEvents();
- };
+ //ins.style.marginLeft = (ins.clientWidth / 2) * - 1 + 'px';
+ //}
+ return this.addEvents();
+ };
- RS.prototype.updateScale = function () {
- this.step = this.sliderWidth / (this.conf.values.length - 1);
+ RS.prototype.updateScale = function () {
+ this.step = this.sliderWidth / (this.conf.values.length - 1);
- var pieces = this.slider.querySelectorAll('span');
+ var pieces = this.slider.querySelectorAll('span');
- for (var i = 0, iLen = pieces.length; i < iLen; i++)
- pieces[i].style.width = this.step + 'px';
+ for (var i = 0, iLen = pieces.length; i < iLen; i++)
+ pieces[i].style.width = this.step + 'px';
- return this.setValues();
- };
+ return this.setValues();
+ };
- RS.prototype.addEvents = function () {
- var pointers = this.slider.querySelectorAll('.' + this.cls.pointer),
- pieces = this.slider.querySelectorAll('span');
+ RS.prototype.addEvents = function () {
+ var pointers = this.slider.querySelectorAll('.' + this.cls.pointer),
+ pieces = this.slider.querySelectorAll('span');
- createEvents(document, 'mousemove touchmove', this.move.bind(this));
- createEvents(document, 'mouseup touchend touchcancel', this.drop.bind(this));
+ createEvents(document, 'mousemove touchmove', this.move.bind(this));
+ createEvents(document, 'mouseup touchend touchcancel', this.drop.bind(this));
- for (var i = 0, iLen = pointers.length; i < iLen; i++)
- createEvents(pointers[i], 'mousedown touchstart', this.drag.bind(this));
+ for (var i = 0, iLen = pointers.length; i < iLen; i++)
+ createEvents(pointers[i], 'mousedown touchstart', this.drag.bind(this));
- for (var i = 0, iLen = pieces.length; i < iLen; i++)
- createEvents(pieces[i], 'click', this.onClickPiece.bind(this));
+ for (var i = 0, iLen = pieces.length; i < iLen; i++)
+ createEvents(pieces[i], 'click', this.onClickPiece.bind(this));
- window.addEventListener('resize', this.onResize.bind(this));
+ window.addEventListener('resize', this.onResize.bind(this));
- return this.setValues();
- };
+ return this.setValues();
+ };
- RS.prototype.drag = function (e) {
- e.preventDefault();
+ RS.prototype.drag = function (e) {
+ e.preventDefault();
- if (this.conf.disabled) return;
+ if (this.conf.disabled) return;
- var dir = e.target.getAttribute('data-dir');
- if (dir === 'left') this.activePointer = this.pointerL;
- if (dir === 'right') this.activePointer = this.pointerR;
+ var dir = e.target.getAttribute('data-dir');
+ if (dir === 'left') this.activePointer = this.pointerL;
+ if (dir === 'right') this.activePointer = this.pointerR;
- return this.slider.classList.add('sliding');
- };
+ return this.slider.classList.add('sliding');
+ };
- RS.prototype.move = function (e) {
- if (this.activePointer && !this.conf.disabled) {
- var coordX = e.type === 'touchmove' ? e.touches[0].clientX : e.pageX,
- index = coordX - this.sliderLeft - (this.pointerWidth / 2);
+ RS.prototype.move = function (e) {
+ if (this.activePointer && !this.conf.disabled) {
+ var coordX = e.type === 'touchmove' ? e.touches[0].clientX : e.pageX,
+ index = coordX - this.sliderLeft - (this.pointerWidth / 2);
- index = Math.round(index / this.step);
+ index = Math.round(index / this.step);
- if (index <= 0) index = 0;
- if (index > this.conf.values.length - 1) index = this.conf.values.length - 1;
+ if (index <= 0) index = 0;
+ if (index > this.conf.values.length - 1) index = this.conf.values.length - 1;
- if (this.conf.range) {
- if (this.activePointer === this.pointerL) this.values.start = index;
- if (this.activePointer === this.pointerR) this.values.end = index;
- }
- else this.values.end = index;
+ if (this.conf.range) {
+ if (this.activePointer === this.pointerL) this.values.start = index;
+ if (this.activePointer === this.pointerR) this.values.end = index;
+ }
+ else this.values.end = index;
- return this.setValues();
- }
- };
+ return this.setValues();
+ }
+ };
- RS.prototype.drop = function () {
- this.activePointer = null;
- };
+ RS.prototype.drop = function () {
+ this.activePointer = null;
+ };
- RS.prototype.setValues = function (start, end) {
- var activePointer = this.conf.range ? 'start' : 'end';
+ RS.prototype.setValues = function (start, end) {
+ var activePointer = this.conf.range ? 'start' : 'end';
- if (start && this.conf.values.indexOf(start) > -1)
- this.values[activePointer] = this.conf.values.indexOf(start);
+ if (start && this.conf.values.indexOf(start) > -1)
+ this.values[activePointer] = this.conf.values.indexOf(start);
- if (end && this.conf.values.indexOf(end) > -1)
- this.values.end = this.conf.values.indexOf(end);
+ if (end && this.conf.values.indexOf(end) > -1)
+ this.values.end = this.conf.values.indexOf(end);
- if (this.conf.range && this.values.start > this.values.end)
- this.values.start = this.values.end;
+ if (this.conf.range && this.values.start > this.values.end)
+ this.values.start = this.values.end;
- this.pointerL.style.left = (this.values[activePointer] * this.step - (this.pointerWidth / 2)) + 'px';
+ this.pointerL.style.left = (this.values[activePointer] * this.step - (this.pointerWidth / 2)) + 'px';
- if (this.conf.range) {
- if (this.conf.tooltip) {
- this.tipL.innerHTML = this.conf.values[this.values.start];
- this.tipR.innerHTML = this.conf.values[this.values.end];
- }
- this.input.value = this.conf.values[this.values.start] + ',' + this.conf.values[this.values.end];
- this.pointerR.style.left = (this.values.end * this.step - (this.pointerWidth / 2)) + 'px';
- this.pointerL.textContent = this.values.start/100;
- this.pointerR.textContent = this.values.end/100;
- }
- else {
- if (this.conf.tooltip)
- this.tipL.innerHTML = this.conf.values[this.values.end];
- this.input.value = this.conf.values[this.values.end];
- this.pointerL.textContent = this.values.end/100;
+ if (this.conf.range) {
+ if (this.conf.tooltip) {
+ this.tipL.innerHTML = this.conf.values[this.values.start];
+ this.tipR.innerHTML = this.conf.values[this.values.end];
+ }
+ this.input.value = this.conf.values[this.values.start] + ',' + this.conf.values[this.values.end];
+ this.pointerR.style.left = (this.values.end * this.step - (this.pointerWidth / 2)) + 'px';
+ this.pointerL.textContent = this.values.start/100;
+ this.pointerR.textContent = this.values.end/100;
+ }
+ else {
+ if (this.conf.tooltip)
+ this.tipL.innerHTML = this.conf.values[this.values.end];
+ this.input.value = this.conf.values[this.values.end];
+ this.pointerL.textContent = this.values.end/100;
- }
+ }
- if (this.values.end > this.conf.values.length - 1) this.values.end = this.conf.values.length - 1;
- if (this.values.start < 0) this.values.start = 0;
+ if (this.values.end > this.conf.values.length - 1) this.values.end = this.conf.values.length - 1;
+ if (this.values.start < 0) this.values.start = 0;
- this.selected.style.width = (this.values.end - this.values.start) * this.step + 'px';
- this.selected.style.left = this.values.start * this.step + 'px';
+ this.selected.style.width = (this.values.end - this.values.start) * this.step + 'px';
+ this.selected.style.left = this.values.start * this.step + 'px';
- if(this.isResize==undefined || this.isResize) {
- this.isResize = false;
- return;
- };
- this.isResize = false;
- return this.onChange();
- };
+ if(this.isResize==undefined || this.isResize) {
+ this.isResize = false;
+ return;
+ };
+ this.isResize = false;
+ return this.onChange();
+ };
- RS.prototype.onClickPiece = function (e) {
+ RS.prototype.onClickPiece = function (e) {
- if (this.conf.disabled) return;
+ if (this.conf.disabled) return;
- var idx = Math.round((e.clientX - this.sliderLeft) / this.step);
+ var idx = Math.round((e.clientX - this.sliderLeft) / this.step);
- if (idx > this.conf.values.length - 1) idx = this.conf.values.length - 1;
- if (idx < 0) idx = 0;
+ if (idx > this.conf.values.length - 1) idx = this.conf.values.length - 1;
+ if (idx < 0) idx = 0;
- if (this.conf.range) {
- if (idx - this.values.start <= this.values.end - idx) {
- this.values.start = idx;
- }
- else this.values.end = idx;
- }
- else this.values.end = idx;
-
- this.slider.classList.remove('sliding');
-
- return this.setValues();
- };
-
- RS.prototype.isDisabled = function(){
- return this.slider.classList.contains('disabled');
- }
-
- RS.prototype.onChange = function () {
- var _this = this;
-
- if (this.timeout) clearTimeout(this.timeout);
-
- this.timeout = setTimeout(function () {
- if (_this.conf.onChange && typeof _this.conf.onChange === 'function') {
- return _this.conf.range?_this.conf.onChange(_this.values.start/100,_this.values.end/100):_this.conf.onChange(_this.input.value);
- }
- }, 500);
- };
-
- RS.prototype.onResize = function () {
- this.isResize = true;
- this.sliderLeft = this.slider.getBoundingClientRect().left;
- this.sliderWidth = this.slider.clientWidth;
- this.pointerWidth = this.pointerL.clientWidth;
- return this.updateScale();
- };
-
- RS.prototype.disabled = function (disabled) {
- this.conf.disabled = disabled;
- this.slider.classList[disabled ? 'add' : 'remove']('disabled');
- };
-
- RS.prototype.getValue = function () {
- return this.conf.range?[this.values.start/100,this.values.end/100]:this.input.value;
- };
-
- RS.prototype.destroy = function () {
- this.input.style.display = this.inputDisplay;
- this.slider.remove();
- };
-
- var createElement = function (el, cls, dataAttr) {
- var element = document.createElement(el);
- if (cls) element.className = cls;
- if (dataAttr && dataAttr.length === 2)
- element.setAttribute('data-' + dataAttr[0], dataAttr[1]);
-
- return element;
- },
-
- createEvents = function (el, ev, callback) {
- var events = ev.split(' ');
-
- for (var i = 0, iLen = events.length; i < iLen; i++)
- el.addEventListener(events[i], callback);
- },
-
- prepareArrayValues = function (conf) {
- var values = [],
- range = conf.values.max - conf.values.min;
-
- if (!conf.step) {
- console.log('No step defined...');
- return [conf.values.min, conf.values.max];
- }
-
- for (var i = 0, iLen = (range / conf.step); i < iLen; i++)
- values.push(conf.values.min + i * conf.step);
-
- if (values.indexOf(conf.values.max) < 0) values.push(conf.values.max);
-
- return values;
- },
-
- checkInitial = function (conf) {
- if (!conf.set || conf.set.length < 1) return null;
- if (conf.values.indexOf(conf.set[0]) < 0) return null;
-
- if (conf.range) {
- if (conf.set.length < 2 || conf.values.indexOf(conf.set[1]) < 0) return null;
- }
- return true;
- };
-
- window.rangeSlider = RS;
+ if (this.conf.range) {
+ if (idx - this.values.start <= this.values.end - idx) {
+ this.values.start = idx;
+ }
+ else this.values.end = idx;
+ }
+ else this.values.end = idx;
+
+ this.slider.classList.remove('sliding');
+
+ return this.setValues();
+ };
+
+ RS.prototype.isDisabled = function(){
+ return this.slider.classList.contains('disabled');
+ }
+
+ RS.prototype.onChange = function () {
+ var _this = this;
+
+ if (this.timeout) clearTimeout(this.timeout);
+
+ this.timeout = setTimeout(function () {
+ if (_this.conf.onChange && typeof _this.conf.onChange === 'function') {
+ return _this.conf.range?_this.conf.onChange(_this.values.start/100,_this.values.end/100):_this.conf.onChange(_this.input.value);
+ }
+ }, 500);
+ };
+
+ RS.prototype.onResize = function () {
+ this.isResize = true;
+ this.sliderLeft = this.slider.getBoundingClientRect().left;
+ this.sliderWidth = this.slider.clientWidth;
+ this.pointerWidth = this.pointerL.clientWidth;
+ return this.updateScale();
+ };
+
+ RS.prototype.disabled = function (disabled) {
+ this.conf.disabled = disabled;
+ this.slider.classList[disabled ? 'add' : 'remove']('disabled');
+ };
+
+ RS.prototype.getValue = function () {
+ return this.conf.range?[this.values.start/100,this.values.end/100]:this.input.value;
+ };
+
+ RS.prototype.destroy = function () {
+ this.input.style.display = this.inputDisplay;
+ this.slider.remove();
+ };
+
+ var createElement = function (el, cls, dataAttr) {
+ var element = document.createElement(el);
+ if (cls) element.className = cls;
+ if (dataAttr && dataAttr.length === 2)
+ element.setAttribute('data-' + dataAttr[0], dataAttr[1]);
+
+ return element;
+ },
+
+ createEvents = function (el, ev, callback) {
+ var events = ev.split(' ');
+
+ for (var i = 0, iLen = events.length; i < iLen; i++)
+ el.addEventListener(events[i], callback);
+ },
+
+ prepareArrayValues = function (conf) {
+ var values = [],
+ range = conf.values.max - conf.values.min;
+
+ if (!conf.step) {
+ console.log('No step defined...');
+ return [conf.values.min, conf.values.max];
+ }
+
+ for (var i = 0, iLen = (range / conf.step); i < iLen; i++)
+ values.push(conf.values.min + i * conf.step);
+
+ if (values.indexOf(conf.values.max) < 0) values.push(conf.values.max);
+
+ return values;
+ },
+
+ checkInitial = function (conf) {
+ if (!conf.set || conf.set.length < 1) return null;
+ if (conf.values.indexOf(conf.set[0]) < 0) return null;
+
+ if (conf.range) {
+ if (conf.set.length < 2 || conf.values.indexOf(conf.set[1]) < 0) return null;
+ }
+ return true;
+ };
+
+ window.rangeSlider = RS;
})();
\ No newline at end of file
diff --git a/common/sortable/Sortable.js b/common/sortable/Sortable.js
old mode 100755
new mode 100644
index e4ca179c2..4a4afc2e1
--- a/common/sortable/Sortable.js
+++ b/common/sortable/Sortable.js
@@ -1,1562 +1,1562 @@
/**!
* Sortable
- * @author RubaXa
+ * @author RubaXa
* @license MIT
*/
(function sortableModule(factory) {
- "use strict";
-
- if (typeof define === "function" && define.amd) {
- define(factory);
- }
- else if (typeof module != "undefined" && typeof module.exports != "undefined") {
- module.exports = factory();
- }
- else {
- /* jshint sub:true */
- window["Sortable"] = factory();
- }
+ "use strict";
+
+ if (typeof define === "function" && define.amd) {
+ define(factory);
+ }
+ else if (typeof module != "undefined" && typeof module.exports != "undefined") {
+ module.exports = factory();
+ }
+ else {
+ /* jshint sub:true */
+ window["Sortable"] = factory();
+ }
})(function sortableFactory() {
- "use strict";
+ "use strict";
- if (typeof window === "undefined" || !window.document) {
- return function sortableError() {
- throw new Error("Sortable.js requires a window with a document");
- };
- }
+ if (typeof window === "undefined" || !window.document) {
+ return function sortableError() {
+ throw new Error("Sortable.js requires a window with a document");
+ };
+ }
- var dragEl,
- parentEl,
- ghostEl,
- cloneEl,
- rootEl,
- nextEl,
- lastDownEl,
-
- scrollEl,
- scrollParentEl,
- scrollCustomFn,
-
- lastEl,
- lastCSS,
- lastParentCSS,
-
- oldIndex,
- newIndex,
+ var dragEl,
+ parentEl,
+ ghostEl,
+ cloneEl,
+ rootEl,
+ nextEl,
+ lastDownEl,
+
+ scrollEl,
+ scrollParentEl,
+ scrollCustomFn,
+
+ lastEl,
+ lastCSS,
+ lastParentCSS,
+
+ oldIndex,
+ newIndex,
- activeGroup,
- putSortable,
-
- autoScroll = {},
-
- tapEvt,
- touchEvt,
+ activeGroup,
+ putSortable,
+
+ autoScroll = {},
+
+ tapEvt,
+ touchEvt,
- moved,
+ moved,
- forRepaintDummy,
+ forRepaintDummy,
- /** @const */
- R_SPACE = /\s+/g,
- R_FLOAT = /left|right|inline/,
+ /** @const */
+ R_SPACE = /\s+/g,
+ R_FLOAT = /left|right|inline/,
- expando = 'Sortable' + (new Date).getTime(),
+ expando = 'Sortable' + (new Date).getTime(),
- win = window,
- document = win.document,
- parseInt = win.parseInt,
- setTimeout = win.setTimeout,
+ win = window,
+ document = win.document,
+ parseInt = win.parseInt,
+ setTimeout = win.setTimeout,
- $ = win.jQuery || win.Zepto,
- Polymer = win.Polymer,
-
- captureMode = false,
- passiveMode = false,
-
- supportDraggable = ('draggable' in document.createElement('div')),
- supportCssPointerEvents = (function (el) {
- // false when IE11
- if (!!navigator.userAgent.match(/(?:Trident.*rv[ :]?11\.|msie)/i)) {
- return false;
- }
- el = document.createElement('x');
- el.style.cssText = 'pointer-events:auto';
- return el.style.pointerEvents === 'auto';
- })(),
-
- _silent = false,
-
- abs = Math.abs,
- min = Math.min,
-
- savedInputChecked = [],
- touchDragOverListeners = [],
-
- alwaysFalse = function () { return false; },
-
- _autoScroll = _throttle(function (/**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl) {
- // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
- if (rootEl && options.scroll) {
- var _this = rootEl[expando],
- el,
- rect,
- sens = options.scrollSensitivity,
- speed = options.scrollSpeed,
-
- x = evt.clientX,
- y = evt.clientY,
-
- winWidth = window.innerWidth,
- winHeight = window.innerHeight,
-
- vx,
- vy,
-
- scrollOffsetX,
- scrollOffsetY
- ;
-
- // Delect scrollEl
- if (scrollParentEl !== rootEl) {
- scrollEl = options.scroll;
- scrollParentEl = rootEl;
- scrollCustomFn = options.scrollFn;
-
- if (scrollEl === true) {
- scrollEl = rootEl;
-
- do {
- if ((scrollEl.offsetWidth < scrollEl.scrollWidth) ||
- (scrollEl.offsetHeight < scrollEl.scrollHeight)
- ) {
- break;
- }
- /* jshint boss:true */
- } while (scrollEl = scrollEl.parentNode);
- }
- }
-
- if (scrollEl) {
- el = scrollEl;
- rect = scrollEl.getBoundingClientRect();
- vx = (abs(rect.right - x) <= sens) - (abs(rect.left - x) <= sens);
- vy = (abs(rect.bottom - y) <= sens) - (abs(rect.top - y) <= sens);
- }
-
-
- if (!(vx || vy)) {
- vx = (winWidth - x <= sens) - (x <= sens);
- vy = (winHeight - y <= sens) - (y <= sens);
-
- /* jshint expr:true */
- (vx || vy) && (el = win);
- }
-
-
- if (autoScroll.vx !== vx || autoScroll.vy !== vy || autoScroll.el !== el) {
- autoScroll.el = el;
- autoScroll.vx = vx;
- autoScroll.vy = vy;
-
- clearInterval(autoScroll.pid);
-
- if (el) {
- autoScroll.pid = setInterval(function () {
- scrollOffsetY = vy ? vy * speed : 0;
- scrollOffsetX = vx ? vx * speed : 0;
-
- if ('function' === typeof(scrollCustomFn)) {
- if (scrollCustomFn.call(_this, scrollOffsetX, scrollOffsetY, evt, touchEvt, el) !== 'continue') {
- return;
- }
- }
-
- if (el === win) {
- win.scrollTo(win.pageXOffset + scrollOffsetX, win.pageYOffset + scrollOffsetY);
- } else {
- el.scrollTop += scrollOffsetY;
- el.scrollLeft += scrollOffsetX;
- }
- }, 24);
- }
- }
- }
- }, 30),
-
- _prepareGroup = function (options) {
- function toFn(value, pull) {
- if (value == null || value === true) {
- value = group.name;
- if (value == null) {
- return alwaysFalse;
- }
- }
-
- if (typeof value === 'function') {
- return value;
- } else {
- return function (to, from) {
- var fromGroup = from.options.group.name;
-
- return pull
- ? value
- : value && (value.join
- ? value.indexOf(fromGroup) > -1
- : (fromGroup == value)
- );
- };
- }
- }
-
- var group = {};
- var originalGroup = options.group;
-
- if (!originalGroup || typeof originalGroup != 'object') {
- originalGroup = {name: originalGroup};
- }
-
- group.name = originalGroup.name;
- group.checkPull = toFn(originalGroup.pull, true);
- group.checkPut = toFn(originalGroup.put);
- group.revertClone = originalGroup.revertClone;
-
- options.group = group;
- }
- ;
-
- // Detect support a passive mode
- try {
- window.addEventListener('test', null, Object.defineProperty({}, 'passive', {
- get: function () {
- // `false`, because everything starts to work incorrectly and instead of d'n'd,
- // begins the page has scrolled.
- passiveMode = false;
- captureMode = {
- capture: false,
- passive: passiveMode
- };
- }
- }));
- } catch (err) {}
-
- /**
- * @class Sortable
- * @param {HTMLElement} el
- * @param {Object} [options]
- */
- function Sortable(el, options) {
- if (!(el && el.nodeType && el.nodeType === 1)) {
- throw 'Sortable: `el` must be HTMLElement, and not ' + {}.toString.call(el);
- }
-
- this.el = el; // root element
- this.options = options = _extend({}, options);
-
-
- // Export instance
- el[expando] = this;
-
- // Default options
- var defaults = {
- group: null,
- sort: true,
- disabled: false,
- store: null,
- handle: null,
+ $ = win.jQuery || win.Zepto,
+ Polymer = win.Polymer,
+
+ captureMode = false,
+ passiveMode = false,
+
+ supportDraggable = ('draggable' in document.createElement('div')),
+ supportCssPointerEvents = (function (el) {
+ // false when IE11
+ if (!!navigator.userAgent.match(/(?:Trident.*rv[ :]?11\.|msie)/i)) {
+ return false;
+ }
+ el = document.createElement('x');
+ el.style.cssText = 'pointer-events:auto';
+ return el.style.pointerEvents === 'auto';
+ })(),
+
+ _silent = false,
+
+ abs = Math.abs,
+ min = Math.min,
+
+ savedInputChecked = [],
+ touchDragOverListeners = [],
+
+ alwaysFalse = function () { return false; },
+
+ _autoScroll = _throttle(function (/**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl) {
+ // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
+ if (rootEl && options.scroll) {
+ var _this = rootEl[expando],
+ el,
+ rect,
+ sens = options.scrollSensitivity,
+ speed = options.scrollSpeed,
+
+ x = evt.clientX,
+ y = evt.clientY,
+
+ winWidth = window.innerWidth,
+ winHeight = window.innerHeight,
+
+ vx,
+ vy,
+
+ scrollOffsetX,
+ scrollOffsetY
+ ;
+
+ // Delect scrollEl
+ if (scrollParentEl !== rootEl) {
+ scrollEl = options.scroll;
+ scrollParentEl = rootEl;
+ scrollCustomFn = options.scrollFn;
+
+ if (scrollEl === true) {
+ scrollEl = rootEl;
+
+ do {
+ if ((scrollEl.offsetWidth < scrollEl.scrollWidth) ||
+ (scrollEl.offsetHeight < scrollEl.scrollHeight)
+ ) {
+ break;
+ }
+ /* jshint boss:true */
+ } while (scrollEl = scrollEl.parentNode);
+ }
+ }
+
+ if (scrollEl) {
+ el = scrollEl;
+ rect = scrollEl.getBoundingClientRect();
+ vx = (abs(rect.right - x) <= sens) - (abs(rect.left - x) <= sens);
+ vy = (abs(rect.bottom - y) <= sens) - (abs(rect.top - y) <= sens);
+ }
+
+
+ if (!(vx || vy)) {
+ vx = (winWidth - x <= sens) - (x <= sens);
+ vy = (winHeight - y <= sens) - (y <= sens);
+
+ /* jshint expr:true */
+ (vx || vy) && (el = win);
+ }
+
+
+ if (autoScroll.vx !== vx || autoScroll.vy !== vy || autoScroll.el !== el) {
+ autoScroll.el = el;
+ autoScroll.vx = vx;
+ autoScroll.vy = vy;
+
+ clearInterval(autoScroll.pid);
+
+ if (el) {
+ autoScroll.pid = setInterval(function () {
+ scrollOffsetY = vy ? vy * speed : 0;
+ scrollOffsetX = vx ? vx * speed : 0;
+
+ if ('function' === typeof(scrollCustomFn)) {
+ if (scrollCustomFn.call(_this, scrollOffsetX, scrollOffsetY, evt, touchEvt, el) !== 'continue') {
+ return;
+ }
+ }
+
+ if (el === win) {
+ win.scrollTo(win.pageXOffset + scrollOffsetX, win.pageYOffset + scrollOffsetY);
+ } else {
+ el.scrollTop += scrollOffsetY;
+ el.scrollLeft += scrollOffsetX;
+ }
+ }, 24);
+ }
+ }
+ }
+ }, 30),
+
+ _prepareGroup = function (options) {
+ function toFn(value, pull) {
+ if (value == null || value === true) {
+ value = group.name;
+ if (value == null) {
+ return alwaysFalse;
+ }
+ }
+
+ if (typeof value === 'function') {
+ return value;
+ } else {
+ return function (to, from) {
+ var fromGroup = from.options.group.name;
+
+ return pull
+ ? value
+ : value && (value.join
+ ? value.indexOf(fromGroup) > -1
+ : (fromGroup == value)
+ );
+ };
+ }
+ }
+
+ var group = {};
+ var originalGroup = options.group;
+
+ if (!originalGroup || typeof originalGroup != 'object') {
+ originalGroup = {name: originalGroup};
+ }
+
+ group.name = originalGroup.name;
+ group.checkPull = toFn(originalGroup.pull, true);
+ group.checkPut = toFn(originalGroup.put);
+ group.revertClone = originalGroup.revertClone;
+
+ options.group = group;
+ }
+ ;
+
+ // Detect support a passive mode
+ try {
+ window.addEventListener('test', null, Object.defineProperty({}, 'passive', {
+ get: function () {
+ // `false`, because everything starts to work incorrectly and instead of d'n'd,
+ // begins the page has scrolled.
+ passiveMode = false;
+ captureMode = {
+ capture: false,
+ passive: passiveMode
+ };
+ }
+ }));
+ } catch (err) {}
+
+ /**
+ * @class Sortable
+ * @param {HTMLElement} el
+ * @param {Object} [options]
+ */
+ function Sortable(el, options) {
+ if (!(el && el.nodeType && el.nodeType === 1)) {
+ throw 'Sortable: `el` must be HTMLElement, and not ' + {}.toString.call(el);
+ }
+
+ this.el = el; // root element
+ this.options = options = _extend({}, options);
+
+
+ // Export instance
+ el[expando] = this;
+
+ // Default options
+ var defaults = {
+ group: null,
+ sort: true,
+ disabled: false,
+ store: null,
+ handle: null,
scroll: true,
- scrollSensitivity: 30,
- scrollSpeed: 10,
- draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*',
- ghostClass: 'sortable-ghost',
- chosenClass: 'sortable-chosen',
- dragClass: 'sortable-drag',
- ignore: 'a, img',
- filter: null,
- preventOnFilter: true,
- animation: 0,
- setData: function (dataTransfer, dragEl) {
- dataTransfer.setData('Text', dragEl.textContent);
- },
- dropBubble: false,
- dragoverBubble: false,
- dataIdAttr: 'data-id',
- delay: 0,
- touchStartThreshold: parseInt(window.devicePixelRatio, 10) || 1,
- forceFallback: false,
- fallbackClass: 'sortable-fallback',
- fallbackOnBody: false,
- fallbackTolerance: 0,
- fallbackOffset: {x: 0, y: 0},
- supportPointer: Sortable.supportPointer !== false
- };
-
-
- // Set default options
- for (var name in defaults) {
- !(name in options) && (options[name] = defaults[name]);
- }
-
- _prepareGroup(options);
-
- // Bind all private methods
- for (var fn in this) {
- if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
- this[fn] = this[fn].bind(this);
- }
- }
-
- // Setup drag mode
- this.nativeDraggable = options.forceFallback ? false : supportDraggable;
-
- // Bind events
- _on(el, 'mousedown', this._onTapStart);
- _on(el, 'touchstart', this._onTapStart);
- options.supportPointer && _on(el, 'pointerdown', this._onTapStart);
-
- if (this.nativeDraggable) {
- _on(el, 'dragover', this);
- _on(el, 'dragenter', this);
- }
-
- touchDragOverListeners.push(this._onDragOver);
-
- // Restore sorting
- options.store && this.sort(options.store.get(this));
- }
-
-
- Sortable.prototype = /** @lends Sortable.prototype */ {
- constructor: Sortable,
-
- _onTapStart: function (/** Event|TouchEvent */evt) {
- var _this = this,
- el = this.el,
- options = this.options,
- preventOnFilter = options.preventOnFilter,
- type = evt.type,
- touch = evt.touches && evt.touches[0],
- target = (touch || evt).target,
- originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0]) || target,
- filter = options.filter,
- startIndex;
-
- _saveInputCheckedState(el);
-
-
- // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.
- if (dragEl) {
- return;
- }
-
- if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {
- return; // only left button or enabled
- }
-
- // cancel dnd if original target is content editable
- if (originalTarget.isContentEditable) {
- return;
- }
-
- target = _closest(target, options.draggable, el);
-
- if (!target) {
- return;
- }
-
- if (lastDownEl === target) {
- // Ignoring duplicate `down`
- return;
- }
-
- // Get the index of the dragged element within its parent
- startIndex = _index(target, options.draggable);
-
- // Check filter
- if (typeof filter === 'function') {
- if (filter.call(this, evt, target, this)) {
- _dispatchEvent(_this, originalTarget, 'filter', target, el, el, startIndex);
- preventOnFilter && evt.preventDefault();
- return; // cancel dnd
- }
- }
- else if (filter) {
- filter = filter.split(',').some(function (criteria) {
- criteria = _closest(originalTarget, criteria.trim(), el);
-
- if (criteria) {
- _dispatchEvent(_this, criteria, 'filter', target, el, el, startIndex);
- return true;
- }
- });
-
- if (filter) {
- preventOnFilter && evt.preventDefault();
- return; // cancel dnd
- }
- }
-
- if (options.handle && !_closest(originalTarget, options.handle, el)) {
- return;
- }
-
- // Prepare `dragstart`
- this._prepareDragStart(evt, touch, target, startIndex);
- },
-
- _prepareDragStart: function (/** Event */evt, /** Touch */touch, /** HTMLElement */target, /** Number */startIndex) {
- var _this = this,
- el = _this.el,
- options = _this.options,
- ownerDocument = el.ownerDocument,
- dragStartFn;
-
- if (target && !dragEl && (target.parentNode === el)) {
- tapEvt = evt;
-
- rootEl = el;
- dragEl = target;
- parentEl = dragEl.parentNode;
- nextEl = dragEl.nextSibling;
- lastDownEl = target;
- activeGroup = options.group;
- oldIndex = startIndex;
-
- this._lastX = (touch || evt).clientX;
- this._lastY = (touch || evt).clientY;
-
- dragEl.style['will-change'] = 'all';
-
- dragStartFn = function () {
- // Delayed drag has been triggered
- // we can re-enable the events: touchmove/mousemove
- _this._disableDelayedDrag();
-
- // Make the element draggable
- dragEl.draggable = _this.nativeDraggable;
-
- // Chosen item
- _toggleClass(dragEl, options.chosenClass, true);
-
- // Bind the events: dragstart/dragend
- _this._triggerDragStart(evt, touch);
-
- // Drag start event
- _dispatchEvent(_this, rootEl, 'choose', dragEl, rootEl, rootEl, oldIndex);
- };
-
- // Disable "draggable"
- options.ignore.split(',').forEach(function (criteria) {
- _find(dragEl, criteria.trim(), _disableDraggable);
- });
-
- _on(ownerDocument, 'mouseup', _this._onDrop);
- _on(ownerDocument, 'touchend', _this._onDrop);
- _on(ownerDocument, 'touchcancel', _this._onDrop);
- _on(ownerDocument, 'selectstart', _this);
- options.supportPointer && _on(ownerDocument, 'pointercancel', _this._onDrop);
-
- if (options.delay) {
- // If the user moves the pointer or let go the click or touch
- // before the delay has been reached:
- // disable the delayed drag
- _on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
- _on(ownerDocument, 'touchend', _this._disableDelayedDrag);
- _on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
- _on(ownerDocument, 'mousemove', _this._disableDelayedDrag);
- _on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler);
- options.supportPointer && _on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler);
-
- _this._dragStartTimer = setTimeout(dragStartFn, options.delay);
- } else {
- dragStartFn();
- }
-
-
- }
- },
-
- _delayedDragTouchMoveHandler: function (/** TouchEvent|PointerEvent **/e) {
- if (min(abs(e.clientX - this._lastX), abs(e.clientY - this._lastY)) >= this.options.touchStartThreshold) {
- this._disableDelayedDrag();
- }
- },
-
- _disableDelayedDrag: function () {
- var ownerDocument = this.el.ownerDocument;
-
- clearTimeout(this._dragStartTimer);
- _off(ownerDocument, 'mouseup', this._disableDelayedDrag);
- _off(ownerDocument, 'touchend', this._disableDelayedDrag);
- _off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
- _off(ownerDocument, 'mousemove', this._disableDelayedDrag);
- _off(ownerDocument, 'touchmove', this._disableDelayedDrag);
- _off(ownerDocument, 'pointermove', this._disableDelayedDrag);
- },
-
- _triggerDragStart: function (/** Event */evt, /** Touch */touch) {
- touch = touch || (evt.pointerType == 'touch' ? evt : null);
-
- if (touch) {
- // Touch device support
- tapEvt = {
- target: dragEl,
- clientX: touch.clientX,
- clientY: touch.clientY
- };
-
- this._onDragStart(tapEvt, 'touch');
- }
- else if (!this.nativeDraggable) {
- this._onDragStart(tapEvt, true);
- }
- else {
- _on(dragEl, 'dragend', this);
- _on(rootEl, 'dragstart', this._onDragStart);
- }
-
- try {
- if (document.selection) {
- // Timeout necessary for IE9
- _nextTick(function () {
- document.selection.empty();
- });
- } else {
- window.getSelection().removeAllRanges();
- }
- } catch (err) {
- }
- },
-
- _dragStarted: function () {
- if (rootEl && dragEl) {
- var options = this.options;
-
- // Apply effect
- _toggleClass(dragEl, options.ghostClass, true);
- _toggleClass(dragEl, options.dragClass, false);
-
- Sortable.active = this;
-
- // Drag start event
- _dispatchEvent(this, rootEl, 'start', dragEl, rootEl, rootEl, oldIndex);
- } else {
- this._nulling();
- }
- },
-
- _emulateDragOver: function () {
- if (touchEvt) {
- if (this._lastX === touchEvt.clientX && this._lastY === touchEvt.clientY) {
- return;
- }
-
- this._lastX = touchEvt.clientX;
- this._lastY = touchEvt.clientY;
-
- if (!supportCssPointerEvents) {
- _css(ghostEl, 'display', 'none');
- }
-
- var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
- var parent = target;
- var i = touchDragOverListeners.length;
-
- while (target && target.shadowRoot) {
- target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
- parent = target;
- }
-
- if (parent) {
- do {
- if (parent[expando]) {
- while (i--) {
- touchDragOverListeners[i]({
- clientX: touchEvt.clientX,
- clientY: touchEvt.clientY,
- target: target,
- rootEl: parent
- });
- }
-
- break;
- }
-
- target = parent; // store last element
- }
- /* jshint boss:true */
- while (parent = parent.parentNode);
- }
-
- if (!supportCssPointerEvents) {
- _css(ghostEl, 'display', '');
- }
- }
- },
-
-
- _onTouchMove: function (/**TouchEvent*/evt) {
- if (tapEvt) {
- var options = this.options,
- fallbackTolerance = options.fallbackTolerance,
- fallbackOffset = options.fallbackOffset,
- touch = evt.touches ? evt.touches[0] : evt,
- dx = (touch.clientX - tapEvt.clientX) + fallbackOffset.x,
- dy = (touch.clientY - tapEvt.clientY) + fallbackOffset.y,
- translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)';
-
- // only set the status to dragging, when we are actually dragging
- if (!Sortable.active) {
- if (fallbackTolerance &&
- min(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY)) < fallbackTolerance
- ) {
- return;
- }
-
- this._dragStarted();
- }
-
- // as well as creating the ghost element on the document body
- this._appendGhost();
-
- moved = true;
- touchEvt = touch;
-
- _css(ghostEl, 'webkitTransform', translate3d);
- _css(ghostEl, 'mozTransform', translate3d);
- _css(ghostEl, 'msTransform', translate3d);
- _css(ghostEl, 'transform', translate3d);
-
- evt.preventDefault();
- }
- },
-
- _appendGhost: function () {
- if (!ghostEl) {
- var rect = dragEl.getBoundingClientRect(),
- css = _css(dragEl),
- options = this.options,
- ghostRect;
-
- ghostEl = dragEl.cloneNode(true);
-
- _toggleClass(ghostEl, options.ghostClass, false);
- _toggleClass(ghostEl, options.fallbackClass, true);
- _toggleClass(ghostEl, options.dragClass, true);
-
- _css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10));
- _css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10));
- _css(ghostEl, 'width', rect.width);
- _css(ghostEl, 'height', rect.height);
- _css(ghostEl, 'opacity', '0.8');
- _css(ghostEl, 'position', 'fixed');
- _css(ghostEl, 'zIndex', '100000');
- _css(ghostEl, 'pointerEvents', 'none');
-
- options.fallbackOnBody && document.body.appendChild(ghostEl) || rootEl.appendChild(ghostEl);
-
- // Fixing dimensions.
- ghostRect = ghostEl.getBoundingClientRect();
- _css(ghostEl, 'width', rect.width * 2 - ghostRect.width);
- _css(ghostEl, 'height', rect.height * 2 - ghostRect.height);
- }
- },
-
- _onDragStart: function (/**Event*/evt, /**boolean*/useFallback) {
- var _this = this;
- var dataTransfer = evt.dataTransfer;
- var options = _this.options;
-
- _this._offUpEvents();
-
- if (activeGroup.checkPull(_this, _this, dragEl, evt)) {
- cloneEl = _clone(dragEl);
-
- cloneEl.draggable = false;
- cloneEl.style['will-change'] = '';
-
- _css(cloneEl, 'display', 'none');
- _toggleClass(cloneEl, _this.options.chosenClass, false);
-
- // #1143: IFrame support workaround
- _this._cloneId = _nextTick(function () {
- rootEl.insertBefore(cloneEl, dragEl);
- _dispatchEvent(_this, rootEl, 'clone', dragEl);
- });
- }
-
- _toggleClass(dragEl, options.dragClass, true);
-
- if (useFallback) {
- if (useFallback === 'touch') {
- // Bind touch events
- _on(document, 'touchmove', _this._onTouchMove);
- _on(document, 'touchend', _this._onDrop);
- _on(document, 'touchcancel', _this._onDrop);
-
- if (options.supportPointer) {
- _on(document, 'pointermove', _this._onTouchMove);
- _on(document, 'pointerup', _this._onDrop);
- }
- } else {
- // Old brwoser
- _on(document, 'mousemove', _this._onTouchMove);
- _on(document, 'mouseup', _this._onDrop);
- }
-
- _this._loopId = setInterval(_this._emulateDragOver, 50);
- }
- else {
- if (dataTransfer) {
- dataTransfer.effectAllowed = 'move';
- options.setData && options.setData.call(_this, dataTransfer, dragEl);
- }
-
- _on(document, 'drop', _this);
-
- // #1143: Бывает элемент с IFrame внутри блокирует `drop`,
- // поэтому если вызвался `mouseover`, значит надо отменять весь d'n'd.
- // Breaking Chrome 62+
- // _on(document, 'mouseover', _this);
-
- _this._dragStartId = _nextTick(_this._dragStarted);
- }
- },
-
- _onDragOver: function (/**Event*/evt) {
- var el = this.el,
- target,
- dragRect,
- targetRect,
- revert,
- options = this.options,
- group = options.group,
- activeSortable = Sortable.active,
- isOwner = (activeGroup === group),
- isMovingBetweenSortable = false,
- canSort = options.sort;
-
- if (evt.preventDefault !== void 0) {
- evt.preventDefault();
- !options.dragoverBubble && evt.stopPropagation();
- }
-
- if (dragEl.animated) {
- return;
- }
-
- moved = true;
-
- if (activeSortable && !options.disabled &&
- (isOwner
- ? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list
- : (
- putSortable === this ||
- (
- (activeSortable.lastPullMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) &&
- group.checkPut(this, activeSortable, dragEl, evt)
- )
- )
- ) &&
- (evt.rootEl === void 0 || evt.rootEl === this.el) // touch fallback
- ) {
- // Smart auto-scrolling
- _autoScroll(evt, options, this.el);
-
- if (_silent) {
- return;
- }
-
- target = _closest(evt.target, options.draggable, el);
- dragRect = dragEl.getBoundingClientRect();
-
- if (putSortable !== this) {
- putSortable = this;
- isMovingBetweenSortable = true;
- }
-
- if (revert) {
- _cloneHide(activeSortable, true);
- parentEl = rootEl; // actualization
-
- if (cloneEl || nextEl) {
- rootEl.insertBefore(dragEl, cloneEl || nextEl);
- }
- else if (!canSort) {
- rootEl.appendChild(dragEl);
- }
-
- return;
- }
-
-
- if ((el.children.length === 0) || (el.children[0] === ghostEl) ||
- (el === evt.target) && (_ghostIsLast(el, evt))
- ) {
- //assign target only if condition is true
- if (el.children.length !== 0 && el.children[0] !== ghostEl && el === evt.target) {
- target = el.lastElementChild;
- }
-
- if (target) {
- if (target.animated) {
- return;
- }
-
- targetRect = target.getBoundingClientRect();
- }
-
- _cloneHide(activeSortable, isOwner);
-
- if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt) !== false) {
- if (!dragEl.contains(el)) {
- el.appendChild(dragEl);
- parentEl = el; // actualization
- }
-
- this._animate(dragRect, dragEl);
- target && this._animate(targetRect, target);
- }
- }
- else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) {
- if (lastEl !== target) {
- lastEl = target;
- lastCSS = _css(target);
- lastParentCSS = _css(target.parentNode);
- }
-
- targetRect = target.getBoundingClientRect();
-
- var width = targetRect.right - targetRect.left,
- height = targetRect.bottom - targetRect.top,
- floating = R_FLOAT.test(lastCSS.cssFloat + lastCSS.display)
- || (lastParentCSS.display == 'flex' && lastParentCSS['flex-direction'].indexOf('row') === 0),
- isWide = (target.offsetWidth > dragEl.offsetWidth),
- isLong = (target.offsetHeight > dragEl.offsetHeight),
- halfway = (floating ? (evt.clientX - targetRect.left) / width : (evt.clientY - targetRect.top) / height) > 0.5,
- nextSibling = target.nextElementSibling,
- after = false
- ;
-
- if (floating) {
- var elTop = dragEl.offsetTop,
- tgTop = target.offsetTop;
-
- if (elTop === tgTop) {
- after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
- }
- else if (target.previousElementSibling === dragEl || dragEl.previousElementSibling === target) {
- after = (evt.clientY - targetRect.top) / height > 0.5;
- } else {
- after = tgTop > elTop;
- }
- } else if (!isMovingBetweenSortable) {
- after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
- }
-
- var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);
-
- if (moveVector !== false) {
- if (moveVector === 1 || moveVector === -1) {
- after = (moveVector === 1);
- }
-
- _silent = true;
- setTimeout(_unsilent, 30);
-
- _cloneHide(activeSortable, isOwner);
-
- if (!dragEl.contains(el)) {
- if (after && !nextSibling) {
- el.appendChild(dragEl);
- } else {
- target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
- }
- }
-
- parentEl = dragEl.parentNode; // actualization
-
- this._animate(dragRect, dragEl);
- this._animate(targetRect, target);
- }
- }
- }
- },
-
- _animate: function (prevRect, target) {
- var ms = this.options.animation;
-
- if (ms) {
- var currentRect = target.getBoundingClientRect();
-
- if (prevRect.nodeType === 1) {
- prevRect = prevRect.getBoundingClientRect();
- }
-
- _css(target, 'transition', 'none');
- _css(target, 'transform', 'translate3d('
- + (prevRect.left - currentRect.left) + 'px,'
- + (prevRect.top - currentRect.top) + 'px,0)'
- );
-
- forRepaintDummy = target.offsetWidth; // repaint
-
- _css(target, 'transition', 'all ' + ms + 'ms');
- _css(target, 'transform', 'translate3d(0,0,0)');
-
- clearTimeout(target.animated);
- target.animated = setTimeout(function () {
- _css(target, 'transition', '');
- _css(target, 'transform', '');
- target.animated = false;
- }, ms);
- }
- },
-
- _offUpEvents: function () {
- var ownerDocument = this.el.ownerDocument;
-
- _off(document, 'touchmove', this._onTouchMove);
- _off(document, 'pointermove', this._onTouchMove);
- _off(ownerDocument, 'mouseup', this._onDrop);
- _off(ownerDocument, 'touchend', this._onDrop);
- _off(ownerDocument, 'pointerup', this._onDrop);
- _off(ownerDocument, 'touchcancel', this._onDrop);
- _off(ownerDocument, 'pointercancel', this._onDrop);
- _off(ownerDocument, 'selectstart', this);
- },
-
- _onDrop: function (/**Event*/evt) {
- var el = this.el,
- options = this.options;
-
- clearInterval(this._loopId);
- clearInterval(autoScroll.pid);
- clearTimeout(this._dragStartTimer);
-
- _cancelNextTick(this._cloneId);
- _cancelNextTick(this._dragStartId);
-
- // Unbind events
- _off(document, 'mouseover', this);
- _off(document, 'mousemove', this._onTouchMove);
-
- if (this.nativeDraggable) {
- _off(document, 'drop', this);
- _off(el, 'dragstart', this._onDragStart);
- }
-
- this._offUpEvents();
-
- if (evt) {
- if (moved) {
- evt.preventDefault();
- !options.dropBubble && evt.stopPropagation();
- }
-
- ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);
-
- if (rootEl === parentEl || Sortable.active.lastPullMode !== 'clone') {
- // Remove clone
- cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);
- }
-
- if (dragEl) {
- if (this.nativeDraggable) {
- _off(dragEl, 'dragend', this);
- }
-
- _disableDraggable(dragEl);
- dragEl.style['will-change'] = '';
-
- // Remove class's
- _toggleClass(dragEl, this.options.ghostClass, false);
- _toggleClass(dragEl, this.options.chosenClass, false);
-
- // Drag stop event
- _dispatchEvent(this, rootEl, 'unchoose', dragEl, parentEl, rootEl, oldIndex, null, evt);
-
- if (rootEl !== parentEl) {
- newIndex = _index(dragEl, options.draggable);
-
- if (newIndex >= 0) {
- // Add event
- _dispatchEvent(null, parentEl, 'add', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
-
- // Remove event
- _dispatchEvent(this, rootEl, 'remove', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
-
- // drag from one list and drop into another
- _dispatchEvent(null, parentEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
- _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
- }
- }
- else {
- if (dragEl.nextSibling !== nextEl) {
- // Get the index of the dragged element within its parent
- newIndex = _index(dragEl, options.draggable);
-
- if (newIndex >= 0) {
- // drag & drop within the same list
- _dispatchEvent(this, rootEl, 'update', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
- _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
- }
- }
- }
-
- if (Sortable.active) {
- /* jshint eqnull:true */
- if (newIndex == null || newIndex === -1) {
- newIndex = oldIndex;
- }
-
- _dispatchEvent(this, rootEl, 'end', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
-
- // Save sorting
- this.save();
- }
- }
-
- }
-
- this._nulling();
- },
-
- _nulling: function() {
- rootEl =
- dragEl =
- parentEl =
- ghostEl =
- nextEl =
- cloneEl =
- lastDownEl =
-
- scrollEl =
- scrollParentEl =
-
- tapEvt =
- touchEvt =
-
- moved =
- newIndex =
-
- lastEl =
- lastCSS =
-
- putSortable =
- activeGroup =
- Sortable.active = null;
-
- savedInputChecked.forEach(function (el) {
- el.checked = true;
- });
- savedInputChecked.length = 0;
- },
-
- handleEvent: function (/**Event*/evt) {
- switch (evt.type) {
- case 'drop':
- case 'dragend':
- this._onDrop(evt);
- break;
-
- case 'dragover':
- case 'dragenter':
- if (dragEl) {
- this._onDragOver(evt);
- _globalDragOver(evt);
- }
- break;
-
- case 'mouseover':
- this._onDrop(evt);
- break;
-
- case 'selectstart':
- evt.preventDefault();
- break;
- }
- },
-
-
- /**
- * Serializes the item into an array of string.
- * @returns {String[]}
- */
- toArray: function () {
- var order = [],
- el,
- children = this.el.children,
- i = 0,
- n = children.length,
- options = this.options;
-
- for (; i < n; i++) {
- el = children[i];
- if (_closest(el, options.draggable, this.el)) {
- order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
- }
- }
-
- return order;
- },
-
-
- /**
- * Sorts the elements according to the array.
- * @param {String[]} order order of the items
- */
- sort: function (order) {
- var items = {}, rootEl = this.el;
-
- this.toArray().forEach(function (id, i) {
- var el = rootEl.children[i];
-
- if (_closest(el, this.options.draggable, rootEl)) {
- items[id] = el;
- }
- }, this);
-
- order.forEach(function (id) {
- if (items[id]) {
- rootEl.removeChild(items[id]);
- rootEl.appendChild(items[id]);
- }
- });
- },
-
-
- /**
- * Save the current sorting
- */
- save: function () {
- var store = this.options.store;
- store && store.set(this);
- },
-
-
- /**
- * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
- * @param {HTMLElement} el
- * @param {String} [selector] default: `options.draggable`
- * @returns {HTMLElement|null}
- */
- closest: function (el, selector) {
- return _closest(el, selector || this.options.draggable, this.el);
- },
-
-
- /**
- * Set/get option
- * @param {string} name
- * @param {*} [value]
- * @returns {*}
- */
- option: function (name, value) {
- var options = this.options;
-
- if (value === void 0) {
- return options[name];
- } else {
- options[name] = value;
-
- if (name === 'group') {
- _prepareGroup(options);
- }
- }
- },
-
-
- /**
- * Destroy
- */
- destroy: function () {
- var el = this.el;
-
- el[expando] = null;
-
- _off(el, 'mousedown', this._onTapStart);
- _off(el, 'touchstart', this._onTapStart);
- _off(el, 'pointerdown', this._onTapStart);
-
- if (this.nativeDraggable) {
- _off(el, 'dragover', this);
- _off(el, 'dragenter', this);
- }
-
- // Remove draggable attributes
- Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
- el.removeAttribute('draggable');
- });
-
- touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);
-
- this._onDrop();
-
- this.el = el = null;
- }
- };
-
-
- function _cloneHide(sortable, state) {
- if (sortable.lastPullMode !== 'clone') {
- state = true;
- }
-
- if (cloneEl && (cloneEl.state !== state)) {
- _css(cloneEl, 'display', state ? 'none' : '');
-
- if (!state) {
- if (cloneEl.state) {
- if (sortable.options.group.revertClone) {
- rootEl.insertBefore(cloneEl, nextEl);
- sortable._animate(dragEl, cloneEl);
- } else {
- rootEl.insertBefore(cloneEl, dragEl);
- }
- }
- }
-
- cloneEl.state = state;
- }
- }
+ scrollSensitivity: 30,
+ scrollSpeed: 10,
+ draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*',
+ ghostClass: 'sortable-ghost',
+ chosenClass: 'sortable-chosen',
+ dragClass: 'sortable-drag',
+ ignore: 'a, img',
+ filter: null,
+ preventOnFilter: true,
+ animation: 0,
+ setData: function (dataTransfer, dragEl) {
+ dataTransfer.setData('Text', dragEl.textContent);
+ },
+ dropBubble: false,
+ dragoverBubble: false,
+ dataIdAttr: 'data-id',
+ delay: 0,
+ touchStartThreshold: parseInt(window.devicePixelRatio, 10) || 1,
+ forceFallback: false,
+ fallbackClass: 'sortable-fallback',
+ fallbackOnBody: false,
+ fallbackTolerance: 0,
+ fallbackOffset: {x: 0, y: 0},
+ supportPointer: Sortable.supportPointer !== false
+ };
+
+
+ // Set default options
+ for (var name in defaults) {
+ !(name in options) && (options[name] = defaults[name]);
+ }
+
+ _prepareGroup(options);
+
+ // Bind all private methods
+ for (var fn in this) {
+ if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
+ this[fn] = this[fn].bind(this);
+ }
+ }
+
+ // Setup drag mode
+ this.nativeDraggable = options.forceFallback ? false : supportDraggable;
+
+ // Bind events
+ _on(el, 'mousedown', this._onTapStart);
+ _on(el, 'touchstart', this._onTapStart);
+ options.supportPointer && _on(el, 'pointerdown', this._onTapStart);
+
+ if (this.nativeDraggable) {
+ _on(el, 'dragover', this);
+ _on(el, 'dragenter', this);
+ }
+
+ touchDragOverListeners.push(this._onDragOver);
+
+ // Restore sorting
+ options.store && this.sort(options.store.get(this));
+ }
+
+
+ Sortable.prototype = /** @lends Sortable.prototype */ {
+ constructor: Sortable,
+
+ _onTapStart: function (/** Event|TouchEvent */evt) {
+ var _this = this,
+ el = this.el,
+ options = this.options,
+ preventOnFilter = options.preventOnFilter,
+ type = evt.type,
+ touch = evt.touches && evt.touches[0],
+ target = (touch || evt).target,
+ originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0]) || target,
+ filter = options.filter,
+ startIndex;
+
+ _saveInputCheckedState(el);
+
+
+ // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.
+ if (dragEl) {
+ return;
+ }
+
+ if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {
+ return; // only left button or enabled
+ }
+
+ // cancel dnd if original target is content editable
+ if (originalTarget.isContentEditable) {
+ return;
+ }
+
+ target = _closest(target, options.draggable, el);
+
+ if (!target) {
+ return;
+ }
+
+ if (lastDownEl === target) {
+ // Ignoring duplicate `down`
+ return;
+ }
+
+ // Get the index of the dragged element within its parent
+ startIndex = _index(target, options.draggable);
+
+ // Check filter
+ if (typeof filter === 'function') {
+ if (filter.call(this, evt, target, this)) {
+ _dispatchEvent(_this, originalTarget, 'filter', target, el, el, startIndex);
+ preventOnFilter && evt.preventDefault();
+ return; // cancel dnd
+ }
+ }
+ else if (filter) {
+ filter = filter.split(',').some(function (criteria) {
+ criteria = _closest(originalTarget, criteria.trim(), el);
+
+ if (criteria) {
+ _dispatchEvent(_this, criteria, 'filter', target, el, el, startIndex);
+ return true;
+ }
+ });
+
+ if (filter) {
+ preventOnFilter && evt.preventDefault();
+ return; // cancel dnd
+ }
+ }
+
+ if (options.handle && !_closest(originalTarget, options.handle, el)) {
+ return;
+ }
+
+ // Prepare `dragstart`
+ this._prepareDragStart(evt, touch, target, startIndex);
+ },
+
+ _prepareDragStart: function (/** Event */evt, /** Touch */touch, /** HTMLElement */target, /** Number */startIndex) {
+ var _this = this,
+ el = _this.el,
+ options = _this.options,
+ ownerDocument = el.ownerDocument,
+ dragStartFn;
+
+ if (target && !dragEl && (target.parentNode === el)) {
+ tapEvt = evt;
+
+ rootEl = el;
+ dragEl = target;
+ parentEl = dragEl.parentNode;
+ nextEl = dragEl.nextSibling;
+ lastDownEl = target;
+ activeGroup = options.group;
+ oldIndex = startIndex;
+
+ this._lastX = (touch || evt).clientX;
+ this._lastY = (touch || evt).clientY;
+
+ dragEl.style['will-change'] = 'all';
+
+ dragStartFn = function () {
+ // Delayed drag has been triggered
+ // we can re-enable the events: touchmove/mousemove
+ _this._disableDelayedDrag();
+
+ // Make the element draggable
+ dragEl.draggable = _this.nativeDraggable;
+
+ // Chosen item
+ _toggleClass(dragEl, options.chosenClass, true);
+
+ // Bind the events: dragstart/dragend
+ _this._triggerDragStart(evt, touch);
+
+ // Drag start event
+ _dispatchEvent(_this, rootEl, 'choose', dragEl, rootEl, rootEl, oldIndex);
+ };
+
+ // Disable "draggable"
+ options.ignore.split(',').forEach(function (criteria) {
+ _find(dragEl, criteria.trim(), _disableDraggable);
+ });
+
+ _on(ownerDocument, 'mouseup', _this._onDrop);
+ _on(ownerDocument, 'touchend', _this._onDrop);
+ _on(ownerDocument, 'touchcancel', _this._onDrop);
+ _on(ownerDocument, 'selectstart', _this);
+ options.supportPointer && _on(ownerDocument, 'pointercancel', _this._onDrop);
+
+ if (options.delay) {
+ // If the user moves the pointer or let go the click or touch
+ // before the delay has been reached:
+ // disable the delayed drag
+ _on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
+ _on(ownerDocument, 'touchend', _this._disableDelayedDrag);
+ _on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
+ _on(ownerDocument, 'mousemove', _this._disableDelayedDrag);
+ _on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler);
+ options.supportPointer && _on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler);
+
+ _this._dragStartTimer = setTimeout(dragStartFn, options.delay);
+ } else {
+ dragStartFn();
+ }
+
+
+ }
+ },
+
+ _delayedDragTouchMoveHandler: function (/** TouchEvent|PointerEvent **/e) {
+ if (min(abs(e.clientX - this._lastX), abs(e.clientY - this._lastY)) >= this.options.touchStartThreshold) {
+ this._disableDelayedDrag();
+ }
+ },
+
+ _disableDelayedDrag: function () {
+ var ownerDocument = this.el.ownerDocument;
+
+ clearTimeout(this._dragStartTimer);
+ _off(ownerDocument, 'mouseup', this._disableDelayedDrag);
+ _off(ownerDocument, 'touchend', this._disableDelayedDrag);
+ _off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
+ _off(ownerDocument, 'mousemove', this._disableDelayedDrag);
+ _off(ownerDocument, 'touchmove', this._disableDelayedDrag);
+ _off(ownerDocument, 'pointermove', this._disableDelayedDrag);
+ },
+
+ _triggerDragStart: function (/** Event */evt, /** Touch */touch) {
+ touch = touch || (evt.pointerType == 'touch' ? evt : null);
+
+ if (touch) {
+ // Touch device support
+ tapEvt = {
+ target: dragEl,
+ clientX: touch.clientX,
+ clientY: touch.clientY
+ };
+
+ this._onDragStart(tapEvt, 'touch');
+ }
+ else if (!this.nativeDraggable) {
+ this._onDragStart(tapEvt, true);
+ }
+ else {
+ _on(dragEl, 'dragend', this);
+ _on(rootEl, 'dragstart', this._onDragStart);
+ }
+
+ try {
+ if (document.selection) {
+ // Timeout necessary for IE9
+ _nextTick(function () {
+ document.selection.empty();
+ });
+ } else {
+ window.getSelection().removeAllRanges();
+ }
+ } catch (err) {
+ }
+ },
+
+ _dragStarted: function () {
+ if (rootEl && dragEl) {
+ var options = this.options;
+
+ // Apply effect
+ _toggleClass(dragEl, options.ghostClass, true);
+ _toggleClass(dragEl, options.dragClass, false);
+
+ Sortable.active = this;
+
+ // Drag start event
+ _dispatchEvent(this, rootEl, 'start', dragEl, rootEl, rootEl, oldIndex);
+ } else {
+ this._nulling();
+ }
+ },
+
+ _emulateDragOver: function () {
+ if (touchEvt) {
+ if (this._lastX === touchEvt.clientX && this._lastY === touchEvt.clientY) {
+ return;
+ }
+
+ this._lastX = touchEvt.clientX;
+ this._lastY = touchEvt.clientY;
+
+ if (!supportCssPointerEvents) {
+ _css(ghostEl, 'display', 'none');
+ }
+
+ var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
+ var parent = target;
+ var i = touchDragOverListeners.length;
+
+ while (target && target.shadowRoot) {
+ target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
+ parent = target;
+ }
+
+ if (parent) {
+ do {
+ if (parent[expando]) {
+ while (i--) {
+ touchDragOverListeners[i]({
+ clientX: touchEvt.clientX,
+ clientY: touchEvt.clientY,
+ target: target,
+ rootEl: parent
+ });
+ }
+
+ break;
+ }
+
+ target = parent; // store last element
+ }
+ /* jshint boss:true */
+ while (parent = parent.parentNode);
+ }
+
+ if (!supportCssPointerEvents) {
+ _css(ghostEl, 'display', '');
+ }
+ }
+ },
+
+
+ _onTouchMove: function (/**TouchEvent*/evt) {
+ if (tapEvt) {
+ var options = this.options,
+ fallbackTolerance = options.fallbackTolerance,
+ fallbackOffset = options.fallbackOffset,
+ touch = evt.touches ? evt.touches[0] : evt,
+ dx = (touch.clientX - tapEvt.clientX) + fallbackOffset.x,
+ dy = (touch.clientY - tapEvt.clientY) + fallbackOffset.y,
+ translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)';
+
+ // only set the status to dragging, when we are actually dragging
+ if (!Sortable.active) {
+ if (fallbackTolerance &&
+ min(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY)) < fallbackTolerance
+ ) {
+ return;
+ }
+
+ this._dragStarted();
+ }
+
+ // as well as creating the ghost element on the document body
+ this._appendGhost();
+
+ moved = true;
+ touchEvt = touch;
+
+ _css(ghostEl, 'webkitTransform', translate3d);
+ _css(ghostEl, 'mozTransform', translate3d);
+ _css(ghostEl, 'msTransform', translate3d);
+ _css(ghostEl, 'transform', translate3d);
+
+ evt.preventDefault();
+ }
+ },
+
+ _appendGhost: function () {
+ if (!ghostEl) {
+ var rect = dragEl.getBoundingClientRect(),
+ css = _css(dragEl),
+ options = this.options,
+ ghostRect;
+
+ ghostEl = dragEl.cloneNode(true);
+
+ _toggleClass(ghostEl, options.ghostClass, false);
+ _toggleClass(ghostEl, options.fallbackClass, true);
+ _toggleClass(ghostEl, options.dragClass, true);
+
+ _css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10));
+ _css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10));
+ _css(ghostEl, 'width', rect.width);
+ _css(ghostEl, 'height', rect.height);
+ _css(ghostEl, 'opacity', '0.8');
+ _css(ghostEl, 'position', 'fixed');
+ _css(ghostEl, 'zIndex', '100000');
+ _css(ghostEl, 'pointerEvents', 'none');
+
+ options.fallbackOnBody && document.body.appendChild(ghostEl) || rootEl.appendChild(ghostEl);
+
+ // Fixing dimensions.
+ ghostRect = ghostEl.getBoundingClientRect();
+ _css(ghostEl, 'width', rect.width * 2 - ghostRect.width);
+ _css(ghostEl, 'height', rect.height * 2 - ghostRect.height);
+ }
+ },
+
+ _onDragStart: function (/**Event*/evt, /**boolean*/useFallback) {
+ var _this = this;
+ var dataTransfer = evt.dataTransfer;
+ var options = _this.options;
+
+ _this._offUpEvents();
+
+ if (activeGroup.checkPull(_this, _this, dragEl, evt)) {
+ cloneEl = _clone(dragEl);
+
+ cloneEl.draggable = false;
+ cloneEl.style['will-change'] = '';
+
+ _css(cloneEl, 'display', 'none');
+ _toggleClass(cloneEl, _this.options.chosenClass, false);
+
+ // #1143: IFrame support workaround
+ _this._cloneId = _nextTick(function () {
+ rootEl.insertBefore(cloneEl, dragEl);
+ _dispatchEvent(_this, rootEl, 'clone', dragEl);
+ });
+ }
+
+ _toggleClass(dragEl, options.dragClass, true);
+
+ if (useFallback) {
+ if (useFallback === 'touch') {
+ // Bind touch events
+ _on(document, 'touchmove', _this._onTouchMove);
+ _on(document, 'touchend', _this._onDrop);
+ _on(document, 'touchcancel', _this._onDrop);
+
+ if (options.supportPointer) {
+ _on(document, 'pointermove', _this._onTouchMove);
+ _on(document, 'pointerup', _this._onDrop);
+ }
+ } else {
+ // Old brwoser
+ _on(document, 'mousemove', _this._onTouchMove);
+ _on(document, 'mouseup', _this._onDrop);
+ }
+
+ _this._loopId = setInterval(_this._emulateDragOver, 50);
+ }
+ else {
+ if (dataTransfer) {
+ dataTransfer.effectAllowed = 'move';
+ options.setData && options.setData.call(_this, dataTransfer, dragEl);
+ }
+
+ _on(document, 'drop', _this);
+
+ // #1143: Бывает элемент с IFrame внутри блокирует `drop`,
+ // поэтому если вызвался `mouseover`, значит надо отменять весь d'n'd.
+ // Breaking Chrome 62+
+ // _on(document, 'mouseover', _this);
+
+ _this._dragStartId = _nextTick(_this._dragStarted);
+ }
+ },
+
+ _onDragOver: function (/**Event*/evt) {
+ var el = this.el,
+ target,
+ dragRect,
+ targetRect,
+ revert,
+ options = this.options,
+ group = options.group,
+ activeSortable = Sortable.active,
+ isOwner = (activeGroup === group),
+ isMovingBetweenSortable = false,
+ canSort = options.sort;
+
+ if (evt.preventDefault !== void 0) {
+ evt.preventDefault();
+ !options.dragoverBubble && evt.stopPropagation();
+ }
+
+ if (dragEl.animated) {
+ return;
+ }
+
+ moved = true;
+
+ if (activeSortable && !options.disabled &&
+ (isOwner
+ ? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list
+ : (
+ putSortable === this ||
+ (
+ (activeSortable.lastPullMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) &&
+ group.checkPut(this, activeSortable, dragEl, evt)
+ )
+ )
+ ) &&
+ (evt.rootEl === void 0 || evt.rootEl === this.el) // touch fallback
+ ) {
+ // Smart auto-scrolling
+ _autoScroll(evt, options, this.el);
+
+ if (_silent) {
+ return;
+ }
+
+ target = _closest(evt.target, options.draggable, el);
+ dragRect = dragEl.getBoundingClientRect();
+
+ if (putSortable !== this) {
+ putSortable = this;
+ isMovingBetweenSortable = true;
+ }
+
+ if (revert) {
+ _cloneHide(activeSortable, true);
+ parentEl = rootEl; // actualization
+
+ if (cloneEl || nextEl) {
+ rootEl.insertBefore(dragEl, cloneEl || nextEl);
+ }
+ else if (!canSort) {
+ rootEl.appendChild(dragEl);
+ }
+
+ return;
+ }
+
+
+ if ((el.children.length === 0) || (el.children[0] === ghostEl) ||
+ (el === evt.target) && (_ghostIsLast(el, evt))
+ ) {
+ //assign target only if condition is true
+ if (el.children.length !== 0 && el.children[0] !== ghostEl && el === evt.target) {
+ target = el.lastElementChild;
+ }
+
+ if (target) {
+ if (target.animated) {
+ return;
+ }
+
+ targetRect = target.getBoundingClientRect();
+ }
+
+ _cloneHide(activeSortable, isOwner);
+
+ if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt) !== false) {
+ if (!dragEl.contains(el)) {
+ el.appendChild(dragEl);
+ parentEl = el; // actualization
+ }
+
+ this._animate(dragRect, dragEl);
+ target && this._animate(targetRect, target);
+ }
+ }
+ else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) {
+ if (lastEl !== target) {
+ lastEl = target;
+ lastCSS = _css(target);
+ lastParentCSS = _css(target.parentNode);
+ }
+
+ targetRect = target.getBoundingClientRect();
+
+ var width = targetRect.right - targetRect.left,
+ height = targetRect.bottom - targetRect.top,
+ floating = R_FLOAT.test(lastCSS.cssFloat + lastCSS.display)
+ || (lastParentCSS.display == 'flex' && lastParentCSS['flex-direction'].indexOf('row') === 0),
+ isWide = (target.offsetWidth > dragEl.offsetWidth),
+ isLong = (target.offsetHeight > dragEl.offsetHeight),
+ halfway = (floating ? (evt.clientX - targetRect.left) / width : (evt.clientY - targetRect.top) / height) > 0.5,
+ nextSibling = target.nextElementSibling,
+ after = false
+ ;
+
+ if (floating) {
+ var elTop = dragEl.offsetTop,
+ tgTop = target.offsetTop;
+
+ if (elTop === tgTop) {
+ after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
+ }
+ else if (target.previousElementSibling === dragEl || dragEl.previousElementSibling === target) {
+ after = (evt.clientY - targetRect.top) / height > 0.5;
+ } else {
+ after = tgTop > elTop;
+ }
+ } else if (!isMovingBetweenSortable) {
+ after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
+ }
+
+ var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);
+
+ if (moveVector !== false) {
+ if (moveVector === 1 || moveVector === -1) {
+ after = (moveVector === 1);
+ }
+
+ _silent = true;
+ setTimeout(_unsilent, 30);
+
+ _cloneHide(activeSortable, isOwner);
+
+ if (!dragEl.contains(el)) {
+ if (after && !nextSibling) {
+ el.appendChild(dragEl);
+ } else {
+ target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
+ }
+ }
+
+ parentEl = dragEl.parentNode; // actualization
+
+ this._animate(dragRect, dragEl);
+ this._animate(targetRect, target);
+ }
+ }
+ }
+ },
+
+ _animate: function (prevRect, target) {
+ var ms = this.options.animation;
+
+ if (ms) {
+ var currentRect = target.getBoundingClientRect();
+
+ if (prevRect.nodeType === 1) {
+ prevRect = prevRect.getBoundingClientRect();
+ }
+
+ _css(target, 'transition', 'none');
+ _css(target, 'transform', 'translate3d('
+ + (prevRect.left - currentRect.left) + 'px,'
+ + (prevRect.top - currentRect.top) + 'px,0)'
+ );
+
+ forRepaintDummy = target.offsetWidth; // repaint
+
+ _css(target, 'transition', 'all ' + ms + 'ms');
+ _css(target, 'transform', 'translate3d(0,0,0)');
+
+ clearTimeout(target.animated);
+ target.animated = setTimeout(function () {
+ _css(target, 'transition', '');
+ _css(target, 'transform', '');
+ target.animated = false;
+ }, ms);
+ }
+ },
+
+ _offUpEvents: function () {
+ var ownerDocument = this.el.ownerDocument;
+
+ _off(document, 'touchmove', this._onTouchMove);
+ _off(document, 'pointermove', this._onTouchMove);
+ _off(ownerDocument, 'mouseup', this._onDrop);
+ _off(ownerDocument, 'touchend', this._onDrop);
+ _off(ownerDocument, 'pointerup', this._onDrop);
+ _off(ownerDocument, 'touchcancel', this._onDrop);
+ _off(ownerDocument, 'pointercancel', this._onDrop);
+ _off(ownerDocument, 'selectstart', this);
+ },
+
+ _onDrop: function (/**Event*/evt) {
+ var el = this.el,
+ options = this.options;
+
+ clearInterval(this._loopId);
+ clearInterval(autoScroll.pid);
+ clearTimeout(this._dragStartTimer);
+
+ _cancelNextTick(this._cloneId);
+ _cancelNextTick(this._dragStartId);
+
+ // Unbind events
+ _off(document, 'mouseover', this);
+ _off(document, 'mousemove', this._onTouchMove);
+
+ if (this.nativeDraggable) {
+ _off(document, 'drop', this);
+ _off(el, 'dragstart', this._onDragStart);
+ }
+
+ this._offUpEvents();
+
+ if (evt) {
+ if (moved) {
+ evt.preventDefault();
+ !options.dropBubble && evt.stopPropagation();
+ }
+
+ ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);
+
+ if (rootEl === parentEl || Sortable.active.lastPullMode !== 'clone') {
+ // Remove clone
+ cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);
+ }
+
+ if (dragEl) {
+ if (this.nativeDraggable) {
+ _off(dragEl, 'dragend', this);
+ }
+
+ _disableDraggable(dragEl);
+ dragEl.style['will-change'] = '';
+
+ // Remove class's
+ _toggleClass(dragEl, this.options.ghostClass, false);
+ _toggleClass(dragEl, this.options.chosenClass, false);
+
+ // Drag stop event
+ _dispatchEvent(this, rootEl, 'unchoose', dragEl, parentEl, rootEl, oldIndex, null, evt);
+
+ if (rootEl !== parentEl) {
+ newIndex = _index(dragEl, options.draggable);
+
+ if (newIndex >= 0) {
+ // Add event
+ _dispatchEvent(null, parentEl, 'add', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
+
+ // Remove event
+ _dispatchEvent(this, rootEl, 'remove', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
+
+ // drag from one list and drop into another
+ _dispatchEvent(null, parentEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
+ _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
+ }
+ }
+ else {
+ if (dragEl.nextSibling !== nextEl) {
+ // Get the index of the dragged element within its parent
+ newIndex = _index(dragEl, options.draggable);
+
+ if (newIndex >= 0) {
+ // drag & drop within the same list
+ _dispatchEvent(this, rootEl, 'update', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
+ _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
+ }
+ }
+ }
+
+ if (Sortable.active) {
+ /* jshint eqnull:true */
+ if (newIndex == null || newIndex === -1) {
+ newIndex = oldIndex;
+ }
+
+ _dispatchEvent(this, rootEl, 'end', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
+
+ // Save sorting
+ this.save();
+ }
+ }
+
+ }
+
+ this._nulling();
+ },
+
+ _nulling: function() {
+ rootEl =
+ dragEl =
+ parentEl =
+ ghostEl =
+ nextEl =
+ cloneEl =
+ lastDownEl =
+
+ scrollEl =
+ scrollParentEl =
+
+ tapEvt =
+ touchEvt =
+
+ moved =
+ newIndex =
+
+ lastEl =
+ lastCSS =
+
+ putSortable =
+ activeGroup =
+ Sortable.active = null;
+
+ savedInputChecked.forEach(function (el) {
+ el.checked = true;
+ });
+ savedInputChecked.length = 0;
+ },
+
+ handleEvent: function (/**Event*/evt) {
+ switch (evt.type) {
+ case 'drop':
+ case 'dragend':
+ this._onDrop(evt);
+ break;
+
+ case 'dragover':
+ case 'dragenter':
+ if (dragEl) {
+ this._onDragOver(evt);
+ _globalDragOver(evt);
+ }
+ break;
+
+ case 'mouseover':
+ this._onDrop(evt);
+ break;
+
+ case 'selectstart':
+ evt.preventDefault();
+ break;
+ }
+ },
+
+
+ /**
+ * Serializes the item into an array of string.
+ * @returns {String[]}
+ */
+ toArray: function () {
+ var order = [],
+ el,
+ children = this.el.children,
+ i = 0,
+ n = children.length,
+ options = this.options;
+
+ for (; i < n; i++) {
+ el = children[i];
+ if (_closest(el, options.draggable, this.el)) {
+ order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
+ }
+ }
+
+ return order;
+ },
+
+
+ /**
+ * Sorts the elements according to the array.
+ * @param {String[]} order order of the items
+ */
+ sort: function (order) {
+ var items = {}, rootEl = this.el;
+
+ this.toArray().forEach(function (id, i) {
+ var el = rootEl.children[i];
+
+ if (_closest(el, this.options.draggable, rootEl)) {
+ items[id] = el;
+ }
+ }, this);
+
+ order.forEach(function (id) {
+ if (items[id]) {
+ rootEl.removeChild(items[id]);
+ rootEl.appendChild(items[id]);
+ }
+ });
+ },
+
+
+ /**
+ * Save the current sorting
+ */
+ save: function () {
+ var store = this.options.store;
+ store && store.set(this);
+ },
+
+
+ /**
+ * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
+ * @param {HTMLElement} el
+ * @param {String} [selector] default: `options.draggable`
+ * @returns {HTMLElement|null}
+ */
+ closest: function (el, selector) {
+ return _closest(el, selector || this.options.draggable, this.el);
+ },
+
+
+ /**
+ * Set/get option
+ * @param {string} name
+ * @param {*} [value]
+ * @returns {*}
+ */
+ option: function (name, value) {
+ var options = this.options;
+
+ if (value === void 0) {
+ return options[name];
+ } else {
+ options[name] = value;
+
+ if (name === 'group') {
+ _prepareGroup(options);
+ }
+ }
+ },
+
+
+ /**
+ * Destroy
+ */
+ destroy: function () {
+ var el = this.el;
+
+ el[expando] = null;
+
+ _off(el, 'mousedown', this._onTapStart);
+ _off(el, 'touchstart', this._onTapStart);
+ _off(el, 'pointerdown', this._onTapStart);
+
+ if (this.nativeDraggable) {
+ _off(el, 'dragover', this);
+ _off(el, 'dragenter', this);
+ }
+
+ // Remove draggable attributes
+ Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
+ el.removeAttribute('draggable');
+ });
+
+ touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);
+
+ this._onDrop();
+
+ this.el = el = null;
+ }
+ };
+
+
+ function _cloneHide(sortable, state) {
+ if (sortable.lastPullMode !== 'clone') {
+ state = true;
+ }
+
+ if (cloneEl && (cloneEl.state !== state)) {
+ _css(cloneEl, 'display', state ? 'none' : '');
+
+ if (!state) {
+ if (cloneEl.state) {
+ if (sortable.options.group.revertClone) {
+ rootEl.insertBefore(cloneEl, nextEl);
+ sortable._animate(dragEl, cloneEl);
+ } else {
+ rootEl.insertBefore(cloneEl, dragEl);
+ }
+ }
+ }
+
+ cloneEl.state = state;
+ }
+ }
- function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) {
- if (el) {
- ctx = ctx || document;
+ function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) {
+ if (el) {
+ ctx = ctx || document;
- do {
- if ((selector === '>*' && el.parentNode === ctx) || _matches(el, selector)) {
- return el;
- }
- /* jshint boss:true */
- } while (el = _getParentOrHost(el));
- }
+ do {
+ if ((selector === '>*' && el.parentNode === ctx) || _matches(el, selector)) {
+ return el;
+ }
+ /* jshint boss:true */
+ } while (el = _getParentOrHost(el));
+ }
- return null;
- }
+ return null;
+ }
- function _getParentOrHost(el) {
- var parent = el.host;
+ function _getParentOrHost(el) {
+ var parent = el.host;
- return (parent && parent.nodeType) ? parent : el.parentNode;
- }
+ return (parent && parent.nodeType) ? parent : el.parentNode;
+ }
- function _globalDragOver(/**Event*/evt) {
- if (evt.dataTransfer) {
- evt.dataTransfer.dropEffect = 'move';
- }
- evt.preventDefault();
- }
+ function _globalDragOver(/**Event*/evt) {
+ if (evt.dataTransfer) {
+ evt.dataTransfer.dropEffect = 'move';
+ }
+ evt.preventDefault();
+ }
- function _on(el, event, fn) {
- el.addEventListener(event, fn, captureMode);
- }
+ function _on(el, event, fn) {
+ el.addEventListener(event, fn, captureMode);
+ }
- function _off(el, event, fn) {
- el.removeEventListener(event, fn, captureMode);
- }
+ function _off(el, event, fn) {
+ el.removeEventListener(event, fn, captureMode);
+ }
- function _toggleClass(el, name, state) {
- if (el) {
- if (el.classList) {
- el.classList[state ? 'add' : 'remove'](name);
- }
- else {
- var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');
- el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');
- }
- }
- }
+ function _toggleClass(el, name, state) {
+ if (el) {
+ if (el.classList) {
+ el.classList[state ? 'add' : 'remove'](name);
+ }
+ else {
+ var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');
+ el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');
+ }
+ }
+ }
- function _css(el, prop, val) {
- var style = el && el.style;
+ function _css(el, prop, val) {
+ var style = el && el.style;
- if (style) {
- if (val === void 0) {
- if (document.defaultView && document.defaultView.getComputedStyle) {
- val = document.defaultView.getComputedStyle(el, '');
- }
- else if (el.currentStyle) {
- val = el.currentStyle;
- }
+ if (style) {
+ if (val === void 0) {
+ if (document.defaultView && document.defaultView.getComputedStyle) {
+ val = document.defaultView.getComputedStyle(el, '');
+ }
+ else if (el.currentStyle) {
+ val = el.currentStyle;
+ }
- return prop === void 0 ? val : val[prop];
- }
- else {
- if (!(prop in style)) {
- prop = '-webkit-' + prop;
- }
+ return prop === void 0 ? val : val[prop];
+ }
+ else {
+ if (!(prop in style)) {
+ prop = '-webkit-' + prop;
+ }
- style[prop] = val + (typeof val === 'string' ? '' : 'px');
- }
- }
- }
+ style[prop] = val + (typeof val === 'string' ? '' : 'px');
+ }
+ }
+ }
- function _find(ctx, tagName, iterator) {
- if (ctx) {
- var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
+ function _find(ctx, tagName, iterator) {
+ if (ctx) {
+ var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
- if (iterator) {
- for (; i < n; i++) {
- iterator(list[i], i);
- }
- }
+ if (iterator) {
+ for (; i < n; i++) {
+ iterator(list[i], i);
+ }
+ }
- return list;
- }
+ return list;
+ }
- return [];
- }
+ return [];
+ }
- function _dispatchEvent(sortable, rootEl, name, targetEl, toEl, fromEl, startIndex, newIndex, originalEvt) {
- sortable = (sortable || rootEl[expando]);
+ function _dispatchEvent(sortable, rootEl, name, targetEl, toEl, fromEl, startIndex, newIndex, originalEvt) {
+ sortable = (sortable || rootEl[expando]);
- var evt = document.createEvent('Event'),
- options = sortable.options,
- onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);
+ var evt = document.createEvent('Event'),
+ options = sortable.options,
+ onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);
- evt.initEvent(name, true, true);
+ evt.initEvent(name, true, true);
- evt.to = toEl || rootEl;
- evt.from = fromEl || rootEl;
- evt.item = targetEl || rootEl;
- evt.clone = cloneEl;
+ evt.to = toEl || rootEl;
+ evt.from = fromEl || rootEl;
+ evt.item = targetEl || rootEl;
+ evt.clone = cloneEl;
- evt.oldIndex = startIndex;
- evt.newIndex = newIndex;
+ evt.oldIndex = startIndex;
+ evt.newIndex = newIndex;
- evt.originalEvent = originalEvt;
+ evt.originalEvent = originalEvt;
- rootEl.dispatchEvent(evt);
+ rootEl.dispatchEvent(evt);
- if (options[onName]) {
- options[onName].call(sortable, evt);
- }
- }
+ if (options[onName]) {
+ options[onName].call(sortable, evt);
+ }
+ }
- function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvt, willInsertAfter) {
- var evt,
- sortable = fromEl[expando],
- onMoveFn = sortable.options.onMove,
- retVal;
+ function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvt, willInsertAfter) {
+ var evt,
+ sortable = fromEl[expando],
+ onMoveFn = sortable.options.onMove,
+ retVal;
- evt = document.createEvent('Event');
- evt.initEvent('move', true, true);
-
- evt.to = toEl;
- evt.from = fromEl;
- evt.dragged = dragEl;
- evt.draggedRect = dragRect;
- evt.related = targetEl || toEl;
- evt.relatedRect = targetRect || toEl.getBoundingClientRect();
- evt.willInsertAfter = willInsertAfter;
-
- evt.originalEvent = originalEvt;
-
- fromEl.dispatchEvent(evt);
-
- if (onMoveFn) {
- retVal = onMoveFn.call(sortable, evt, originalEvt);
- }
-
- return retVal;
- }
+ evt = document.createEvent('Event');
+ evt.initEvent('move', true, true);
+
+ evt.to = toEl;
+ evt.from = fromEl;
+ evt.dragged = dragEl;
+ evt.draggedRect = dragRect;
+ evt.related = targetEl || toEl;
+ evt.relatedRect = targetRect || toEl.getBoundingClientRect();
+ evt.willInsertAfter = willInsertAfter;
+
+ evt.originalEvent = originalEvt;
+
+ fromEl.dispatchEvent(evt);
+
+ if (onMoveFn) {
+ retVal = onMoveFn.call(sortable, evt, originalEvt);
+ }
+
+ return retVal;
+ }
- function _disableDraggable(el) {
- el.draggable = false;
- }
-
-
- function _unsilent() {
- _silent = false;
- }
-
-
- /** @returns {HTMLElement|false} */
- function _ghostIsLast(el, evt) {
- var lastEl = el.lastElementChild,
- rect = lastEl.getBoundingClientRect();
-
- // 5 — min delta
- // abs — нельзя добавлять, а то глюки при наведении сверху
- return (evt.clientY - (rect.top + rect.height) > 5) ||
- (evt.clientX - (rect.left + rect.width) > 5);
- }
-
-
- /**
- * Generate id
- * @param {HTMLElement} el
- * @returns {String}
- * @private
- */
- function _generateId(el) {
- var str = el.tagName + el.className + el.src + el.href + el.textContent,
- i = str.length,
- sum = 0;
-
- while (i--) {
- sum += str.charCodeAt(i);
- }
-
- return sum.toString(36);
- }
-
- /**
- * Returns the index of an element within its parent for a selected set of
- * elements
- * @param {HTMLElement} el
- * @param {selector} selector
- * @return {number}
- */
- function _index(el, selector) {
- var index = 0;
-
- if (!el || !el.parentNode) {
- return -1;
- }
-
- while (el && (el = el.previousElementSibling)) {
- if ((el.nodeName.toUpperCase() !== 'TEMPLATE') && (selector === '>*' || _matches(el, selector))) {
- index++;
- }
- }
-
- return index;
- }
-
- function _matches(/**HTMLElement*/el, /**String*/selector) {
- if (el) {
- try {
- if (el.matches) {
- return el.matches(selector);
- } else if (el.msMatchesSelector) {
- return el.msMatchesSelector(selector);
- }
- } catch(_) {
- return false;
- }
- }
-
- return false;
- }
-
- function _throttle(callback, ms) {
- var args, _this;
-
- return function () {
- if (args === void 0) {
- args = arguments;
- _this = this;
-
- setTimeout(function () {
- if (args.length === 1) {
- callback.call(_this, args[0]);
- } else {
- callback.apply(_this, args);
- }
-
- args = void 0;
- }, ms);
- }
- };
- }
-
- function _extend(dst, src) {
- if (dst && src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) {
- dst[key] = src[key];
- }
- }
- }
-
- return dst;
- }
-
- function _clone(el) {
- if (Polymer && Polymer.dom) {
- return Polymer.dom(el).cloneNode(true);
- }
- else if ($) {
- return $(el).clone(true)[0];
- }
- else {
- return el.cloneNode(true);
- }
- }
-
- function _saveInputCheckedState(root) {
- savedInputChecked.length = 0;
-
- var inputs = root.getElementsByTagName('input');
- var idx = inputs.length;
-
- while (idx--) {
- var el = inputs[idx];
- el.checked && savedInputChecked.push(el);
- }
- }
-
- function _nextTick(fn) {
- return setTimeout(fn, 0);
- }
-
- function _cancelNextTick(id) {
- return clearTimeout(id);
- }
-
- // Fixed #973:
- _on(document, 'touchmove', function (evt) {
- if (Sortable.active) {
- evt.preventDefault();
- }
- });
-
- // Export utils
- Sortable.utils = {
- on: _on,
- off: _off,
- css: _css,
- find: _find,
- is: function (el, selector) {
- return !!_closest(el, selector, el);
- },
- extend: _extend,
- throttle: _throttle,
- closest: _closest,
- toggleClass: _toggleClass,
- clone: _clone,
- index: _index,
- nextTick: _nextTick,
- cancelNextTick: _cancelNextTick
- };
-
-
- /**
- * Create sortable instance
- * @param {HTMLElement} el
- * @param {Object} [options]
- */
- Sortable.create = function (el, options) {
- return new Sortable(el, options);
- };
-
-
- // Export
- Sortable.version = '1.7.0';
- return Sortable;
+ function _disableDraggable(el) {
+ el.draggable = false;
+ }
+
+
+ function _unsilent() {
+ _silent = false;
+ }
+
+
+ /** @returns {HTMLElement|false} */
+ function _ghostIsLast(el, evt) {
+ var lastEl = el.lastElementChild,
+ rect = lastEl.getBoundingClientRect();
+
+ // 5 — min delta
+ // abs — нельзя добавлять, а то глюки при наведении сверху
+ return (evt.clientY - (rect.top + rect.height) > 5) ||
+ (evt.clientX - (rect.left + rect.width) > 5);
+ }
+
+
+ /**
+ * Generate id
+ * @param {HTMLElement} el
+ * @returns {String}
+ * @private
+ */
+ function _generateId(el) {
+ var str = el.tagName + el.className + el.src + el.href + el.textContent,
+ i = str.length,
+ sum = 0;
+
+ while (i--) {
+ sum += str.charCodeAt(i);
+ }
+
+ return sum.toString(36);
+ }
+
+ /**
+ * Returns the index of an element within its parent for a selected set of
+ * elements
+ * @param {HTMLElement} el
+ * @param {selector} selector
+ * @return {number}
+ */
+ function _index(el, selector) {
+ var index = 0;
+
+ if (!el || !el.parentNode) {
+ return -1;
+ }
+
+ while (el && (el = el.previousElementSibling)) {
+ if ((el.nodeName.toUpperCase() !== 'TEMPLATE') && (selector === '>*' || _matches(el, selector))) {
+ index++;
+ }
+ }
+
+ return index;
+ }
+
+ function _matches(/**HTMLElement*/el, /**String*/selector) {
+ if (el) {
+ try {
+ if (el.matches) {
+ return el.matches(selector);
+ } else if (el.msMatchesSelector) {
+ return el.msMatchesSelector(selector);
+ }
+ } catch(_) {
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ function _throttle(callback, ms) {
+ var args, _this;
+
+ return function () {
+ if (args === void 0) {
+ args = arguments;
+ _this = this;
+
+ setTimeout(function () {
+ if (args.length === 1) {
+ callback.call(_this, args[0]);
+ } else {
+ callback.apply(_this, args);
+ }
+
+ args = void 0;
+ }, ms);
+ }
+ };
+ }
+
+ function _extend(dst, src) {
+ if (dst && src) {
+ for (var key in src) {
+ if (src.hasOwnProperty(key)) {
+ dst[key] = src[key];
+ }
+ }
+ }
+
+ return dst;
+ }
+
+ function _clone(el) {
+ if (Polymer && Polymer.dom) {
+ return Polymer.dom(el).cloneNode(true);
+ }
+ else if ($) {
+ return $(el).clone(true)[0];
+ }
+ else {
+ return el.cloneNode(true);
+ }
+ }
+
+ function _saveInputCheckedState(root) {
+ savedInputChecked.length = 0;
+
+ var inputs = root.getElementsByTagName('input');
+ var idx = inputs.length;
+
+ while (idx--) {
+ var el = inputs[idx];
+ el.checked && savedInputChecked.push(el);
+ }
+ }
+
+ function _nextTick(fn) {
+ return setTimeout(fn, 0);
+ }
+
+ function _cancelNextTick(id) {
+ return clearTimeout(id);
+ }
+
+ // Fixed #973:
+ _on(document, 'touchmove', function (evt) {
+ if (Sortable.active) {
+ evt.preventDefault();
+ }
+ });
+
+ // Export utils
+ Sortable.utils = {
+ on: _on,
+ off: _off,
+ css: _css,
+ find: _find,
+ is: function (el, selector) {
+ return !!_closest(el, selector, el);
+ },
+ extend: _extend,
+ throttle: _throttle,
+ closest: _closest,
+ toggleClass: _toggleClass,
+ clone: _clone,
+ index: _index,
+ nextTick: _nextTick,
+ cancelNextTick: _cancelNextTick
+ };
+
+
+ /**
+ * Create sortable instance
+ * @param {HTMLElement} el
+ * @param {Object} [options]
+ */
+ Sortable.create = function (el, options) {
+ return new Sortable(el, options);
+ };
+
+
+ // Export
+ Sortable.version = '1.7.0';
+ return Sortable;
});
diff --git a/common/sortable/Sortable.min.js b/common/sortable/Sortable.min.js
old mode 100755
new mode 100644
diff --git a/common/util.js b/common/util.js
index 990a4b19b..0d68a7c2c 100644
--- a/common/util.js
+++ b/common/util.js
@@ -76,14 +76,14 @@ function extend() {
}
/**
- remove /empty a DOM element
+ remove /empty a DOM element
*/
function empty(elt) {
while (elt.firstChild) elt.removeChild(elt.firstChild);
}
/*
- ID generator
+ ID generator
*/
function randomId() {
// Math.random should be unique because of its seeding algorithm.
diff --git a/components/camessage/camessage.js b/components/camessage/camessage.js
index cc27364a6..1dfbcfae1 100644
--- a/components/camessage/camessage.js
+++ b/components/camessage/camessage.js
@@ -1,5 +1,5 @@
// proposal:
-//
+//
// enhancement
// 1. add options to set the position such as top-right, top-left, bottom-right, bottom-left.
// 2. add functionality that message panel can show detail info.
@@ -8,92 +8,90 @@
/**
* CaMicroscope CaMessage. A message component that show the message permanently or temporarily
* @constructor
- * @param {Object} options
+ * @param {Object} options
* All required and optional settings for instantiating a new instance of a CaMessage.
* @param {String} options.id
* Id of the element to append the CaMessage's container element to.
*/
-function CaMessage(options){
- this.name = 'CaMessage';
- /**
+function CaMessage(options) {
+ this.name = 'CaMessage';
+ /**
* @property {Element} elt The element to append the CaMessage's container element to.
*/
- this.elt;
- this.setting = {
- // id
- defaultText: 'No Content',
- // size .font-size
- size:'1.3rem',
- // color - font color
- color:'#f6f6f6',
- // bgColor - background color
- bgColor:'#365f9c'
- }
- extend(this.setting, options);
- this.elt = document.getElementById(this.setting.id);
- if(!this.elt) {
- console.error(`${this.name}: No Main Element...`);
- return;
- }
+ this.elt;
+ this.setting = {
+ // id
+ defaultText: 'No Content',
+ // size .font-size
+ size: '1.3rem',
+ // color - font color
+ color: '#f6f6f6',
+ // bgColor - background color
+ bgColor: '#365f9c',
+ };
+ extend(this.setting, options);
+ this.elt = document.getElementById(this.setting.id);
+ if (!this.elt) {
+ console.error(`${this.name}: No Main Element...`);
+ return;
+ }
- this.elt.classList.add('camessage');
+ this.elt.classList.add('camessage');
- this.reset();
+ this.reset();
}
/**
- * reset the message's content to default
+ * reset the message's content to default
*/
-CaMessage.prototype.reset = function(){
-
- if(this.setting.defaultText) this.elt.textContent = this.setting.defaultText;
- this.elt.style.fontSize= this.setting.size;
- this.elt.style.color= this.setting.color;
- this.elt.style.backgroundColor= this.setting.bgColor;
-}
+CaMessage.prototype.reset = function() {
+ if (this.setting.defaultText) this.elt.textContent = this.setting.defaultText;
+ this.elt.style.fontSize= this.setting.size;
+ this.elt.style.color= this.setting.color;
+ this.elt.style.backgroundColor= this.setting.bgColor;
+};
/**
- * set the message's text
- * @param {String} txt
- * text that show on CaMessage
+ * set the message's text
+ * @param {String} txt
+ * text that show on CaMessage
*/
-CaMessage.prototype.changeTxt = function(txt){
- this.elt.textContent = txt;
-}
+CaMessage.prototype.changeTxt = function(txt) {
+ this.elt.textContent = txt;
+};
/*
- * change message's style
- * @param {Object} style
- * the style that applies on CaMessage
- * @param {String} [style.size] font size.
- * @param {String} [style.color] font color.
- * @param {String} [style.bgColor] background color.
- *
+ * change message's style
+ * @param {Object} style
+ * the style that applies on CaMessage
+ * @param {String} [style.size] font size.
+ * @param {String} [style.color] font color.
+ * @param {String} [style.bgColor] background color.
+ *
*/
-CaMessage.prototype.changeStyle = function(style){
- if(!style) return;
- if(style.size) this.elt.style.fontSize = style.size;
- if(style.color) this.elt.style.color = style.color;
- if(style.bgColor) this.elt.style.backgroundColor = style.bgColor;
-}
+CaMessage.prototype.changeStyle = function(style) {
+ if (!style) return;
+ if (style.size) this.elt.style.fontSize = style.size;
+ if (style.color) this.elt.style.color = style.color;
+ if (style.bgColor) this.elt.style.backgroundColor = style.bgColor;
+};
/*
- * temporarily change the text and the style of CaMessage by giving time[sec]
- * @param {String} txt
- * text content
- * @param {Object} style
- * the message style
- * @param {String} [style.size] font size.
- * @param {String} [style.color] font color.
- * @param {String} [style.bgColor] background color.
- * @param {number} time
- * The number of seconds to show the message.
+ * temporarily change the text and the style of CaMessage by giving time[sec]
+ * @param {String} txt
+ * text content
+ * @param {Object} style
+ * the message style
+ * @param {String} [style.size] font size.
+ * @param {String} [style.color] font color.
+ * @param {String} [style.bgColor] background color.
+ * @param {number} time
+ * The number of seconds to show the message.
*/
-CaMessage.prototype.sendMessage = function(txt,style,time){
- this.changeTxt(txt);
- if(style) this.changeStyle(style);
- if(time) setTimeout(this.reset.bind(this) ,time*1000);
-
-}
\ No newline at end of file
+CaMessage.prototype.sendMessage = function(txt, style, time) {
+ this.changeTxt(txt);
+ if (style) this.changeStyle(style);
+ if (time) setTimeout(this.reset.bind(this), time*1000);
+};
diff --git a/components/collapsiblelist/collapsiblelist.js b/components/collapsiblelist/collapsiblelist.js
index bd3a85c30..d1b5c6bc3 100644
--- a/components/collapsiblelist/collapsiblelist.js
+++ b/components/collapsiblelist/collapsiblelist.js
@@ -8,33 +8,34 @@
// callback
/* attributes in options
- options{
- id - element id
- list:[
- {
- id:identity for one specific item
- title: text display on head
- icon:google icon
- content: stting or DOM Element
- isExpand:
- }
- ]
- }
- // TODO a function
+ options{
+ id - element id
+ list:[
+ {
+ id:identity for one specific item
+ title: text display on head
+ icon:google icon
+ content: stting or DOM Element
+ isExpand:
+ }
+ ]
+ }
+ // TODO a function
*/
/**
- *
+ *
* CaMicroscope Collapsible List. the item in this list consists of the item's head and the item's body.
- * Click on the head, if item's body is collapsed then expand it, if not, then expand it. Only one of item can be expanded.
+ * Click on the head, if item's body is collapsed then expand it, if not, then expand it.
+ * Only one of item can be expanded.
* @constructor
- * @param {Object} options
+ * @param {Object} options
* All required and optional settings for instantiating a new instance of a Collapsible List.
* @param {String} options.id
* Id of the element to append the Collapsible List's container element to.
* @param {Object[]} list
- * The list of items in Collapsible List
+ * The list of items in Collapsible List
* @param {String} list.id
* Item id, which uses to query item
* @param {String} list.title
@@ -46,69 +47,69 @@
* @param {String} [list.isExpand = false]
* The content expand or not.
* @param {Function} [changeCallBack]
- * when the expanded item changes the event is fired. Return {id: item id,isExpand: the state of current item[expand or not]}
- *
+ * when the expanded item changes the event is fired.
+ * Return {id: item id,isExpand: the state of current item[expand or not]}
+ *
*/
-function CollapsibleList(options){
- this.name = 'CollapsibleList';
- /*
- [{
- id -
- head -
- content -
- }...]
- */
-
- /**
- * @property {Object[]} __v_models
+function CollapsibleList(options) {
+ this.name = 'CollapsibleList';
+ /*
+ [{
+ id -
+ head -
+ content -
+ }...]
+ */
+
+ /**
+ * @property {Object[]} __v_models
* The view model
* @property {String} __v_models.id
* the id that identifies the item
* @property {String} __v_models.title
- * the title that shows in the head part
+ * the title that shows in the head part
* @property {String} __v_models.icon
* The name of material-icons for the item icon
* @property {String} __v_models.content
* The content that the item body has.
* @property {String} [__v_models.isExpand = false]
- * The item is expanded or not.
+ * The item is expanded or not.
*/
- this.__v_models = [];
-
- /*
- list:[
- {
- id: ,
- title: ,
- icon: ,
- content:string
- isExpand:,
-
- }
- ]
- */
- this.setting = {
- }
-
- extend(this.setting, options);
-
- // attach container element
- this.elt = document.getElementById(this.setting.id);
- if(!this.elt && !this.setting.viewer) {
- console.error(`${this.name}: No Viewer or DOM Element`);
- return;
- }
-
- //create UI
- this.__refresh();
-
+ this.__v_models = [];
+
+ /*
+ list:[
+ {
+ id: ,
+ title: ,
+ icon: ,
+ content:string
+ isExpand:,
+
+ }
+ ]
+ */
+ this.setting = {
+ };
+
+ extend(this.setting, options);
+
+ // attach container element
+ this.elt = document.getElementById(this.setting.id);
+ if (!this.elt && !this.setting.viewer) {
+ console.error(`${this.name}: No Viewer or DOM Element`);
+ return;
+ }
+
+ // create UI
+ this.__refresh();
}
/**
* @private
* create items (head, content) for collapsible list by using options
* @param {Object[]} options
- * The list of items in Collapsible List
+ * The list of items in Collapsible List
* @param {String} options.id
* Item id, which uses to query item
* @param {String} options.title
@@ -120,74 +121,72 @@ function CollapsibleList(options){
* @param {String} [options.isExpand = false]
* The content expand or not.
*/
-CollapsibleList.prototype.__createItem = function(options){
-
- /*
- create the item head
- */
- // the head
- const head = document.createElement('div');
- head.classList.add('item_head');
-
- // the icon for expand/collapse
- const add_icon = document.createElement('i');
- add_icon.classList.add('material-icons');
- add_icon.classList.add('md-24');
- head.appendChild(add_icon);
-
- // the icon for customize
- let icon;
- if(options.icon){
- icon = document.createElement('i');
- icon.classList.add('material-icons');
- icon.classList.add('md-24');
- icon.textContent = options.icon;
- head.appendChild(icon);
- }
-
- // the title
- const title = document.createElement('span');
- title.textContent = options.title;
- head.appendChild(title);
-
- this.elt.appendChild(head);
-
-
- /*
- create the item content
- */
-
- // create item body
- const body = document.createElement('div');
- body.classList.add('item_body');
- if(options.isExpand) {
- add_icon.textContent = 'remove';
- body.classList.add('expand');
- } else {
- add_icon.textContent = 'add';
- body.classList.add('collapse');
- }
-
- // ceate item content
- const content = document.createElement('div');
- content.classList.add('item_content');
-
- // add content
- if(typeof options.content === 'string'){ // string template
- content.innerHTML = options.content;
- } else if(options.content instanceof Element){
- content.appendChild(options.content); // DOM element
- }
-
- body.appendChild(content);
- this.elt.appendChild(body);
-
-
- // events
- head.addEventListener('click', this.__click_head.bind(this));
-
- return {head:head,body:body};
-
+CollapsibleList.prototype.__createItem = function(options) {
+ /*
+ create the item head
+ */
+ // the head
+ const head = document.createElement('div');
+ head.classList.add('item_head');
+
+ // the icon for expand/collapse
+ const add_icon = document.createElement('i');
+ add_icon.classList.add('material-icons');
+ add_icon.classList.add('md-24');
+ head.appendChild(add_icon);
+
+ // the icon for customize
+ let icon;
+ if (options.icon) {
+ icon = document.createElement('i');
+ icon.classList.add('material-icons');
+ icon.classList.add('md-24');
+ icon.textContent = options.icon;
+ head.appendChild(icon);
+ }
+
+ // the title
+ const title = document.createElement('span');
+ title.textContent = options.title;
+ head.appendChild(title);
+
+ this.elt.appendChild(head);
+
+
+ /*
+ create the item content
+ */
+
+ // create item body
+ const body = document.createElement('div');
+ body.classList.add('item_body');
+ if (options.isExpand) {
+ add_icon.textContent = 'remove';
+ body.classList.add('expand');
+ } else {
+ add_icon.textContent = 'add';
+ body.classList.add('collapse');
+ }
+
+ // ceate item content
+ const content = document.createElement('div');
+ content.classList.add('item_content');
+
+ // add content
+ if (typeof options.content === 'string') { // string template
+ content.innerHTML = options.content;
+ } else if (options.content instanceof Element) {
+ content.appendChild(options.content); // DOM element
+ }
+
+ body.appendChild(content);
+ this.elt.appendChild(body);
+
+
+ // events
+ head.addEventListener('click', this.__click_head.bind(this));
+
+ return {head: head, body: body};
};
@@ -196,37 +195,36 @@ CollapsibleList.prototype.__createItem = function(options){
* the event that will be triggered when click on the head of a item.
* @param {Event} e click event
*/
-CollapsibleList.prototype.__click_head = function(e){
- const head = e.currentTarget;
- const body = head.nextElementSibling;
- for (var i = this.__v_models.length - 1; i >= 0; i--) {
- const item = this.__v_models[i];
- if(item.elt.head !== head) {
- item.elt.body.classList.remove('expand')
- item.elt.body.classList.add('collapse')
- item.elt.body.previousElementSibling.firstChild.innerHTML = 'add';
- }
-
- }
- if(body.classList.toggle('collapse')) head.querySelector('i').innerHTML = 'add';
- if(body.classList.toggle('expand')) head.querySelector('i').innerHTML = 'remove';
-
- if(this.setting.changeCallBack) {
- const data = this.__v_models.map( item => {
- return {
- id:item.id,
- isExpand:item.elt.body.classList.contains('expand')?true:false
- }
- });
-
- this.setting.changeCallBack.call(this, data);
- }
+CollapsibleList.prototype.__click_head = function(e) {
+ const head = e.currentTarget;
+ const body = head.nextElementSibling;
+ for (let i = this.__v_models.length - 1; i >= 0; i--) {
+ const item = this.__v_models[i];
+ if (item.elt.head !== head) {
+ item.elt.body.classList.remove('expand');
+ item.elt.body.classList.add('collapse');
+ item.elt.body.previousElementSibling.firstChild.innerHTML = 'add';
+ }
+ }
+ if (body.classList.toggle('collapse')) head.querySelector('i').innerHTML = 'add';
+ if (body.classList.toggle('expand')) head.querySelector('i').innerHTML = 'remove';
+
+ if (this.setting.changeCallBack) {
+ const data = this.__v_models.map( (item) => {
+ return {
+ id: item.id,
+ isExpand: item.elt.body.classList.contains('expand')?true:false,
+ };
+ });
+
+ this.setting.changeCallBack.call(this, data);
+ }
};
/**
* set the item list. UI refresh automatically.
* @param {object[]} list
- * The list of items in Collapsible List
+ * The list of items in Collapsible List
* @param {String} list.id
* Item id, which uses to query item
* @param {String} list.title
@@ -235,109 +233,107 @@ CollapsibleList.prototype.__click_head = function(e){
* The name of material-icons for the item icon
* @param {String|Element} list.content
* The content that the item body has.
- *
+ *
*/
-CollapsibleList.prototype.setList = function(list){
-
- if(list)this.setting.list = list;
- this.__refresh();
+CollapsibleList.prototype.setList = function(list) {
+ if (list) this.setting.list = list;
+ this.__refresh();
};
/**
* Render UI based on the options.
- *
+ *
*/
-CollapsibleList.prototype.__refresh = function(){
- // has item list
- if(!this.setting.list instanceof Array) {
- console.error(`${this.name}: No Data List`);
- return;
- }
-
- //
- empty(this.elt);
- this.elt.classList.add('clloapsible_container');
- // this.elt.style.flex = 1;
-
- this.__v_models = this.setting.list.slice();
- // create a list
- for (var i = 0; i < this.__v_models.length; i++) {
- const item_options = this.__v_models[i];
- item_options.elt = this.__createItem(item_options);
- }
+CollapsibleList.prototype.__refresh = function() {
+ // has item list
+ if (!this.setting.list instanceof Array) {
+ console.error(`${this.name}: No Data List`);
+ return;
+ }
+
+ //
+ empty(this.elt);
+ this.elt.classList.add('clloapsible_container');
+ // this.elt.style.flex = 1;
+
+ this.__v_models = this.setting.list.slice();
+ // create a list
+ for (let i = 0; i < this.__v_models.length; i++) {
+ const item_options = this.__v_models[i];
+ item_options.elt = this.__createItem(item_options);
+ }
};
-CollapsibleList.prototype.collapse = function(){
- for (var i = this.__v_models.length - 1; i >= 0; i--) {
- const item = this.__v_models[i];
- item.elt.body.classList.remove('expand');
- item.elt.body.classList.add('collapse');
-
- }
-}
+CollapsibleList.prototype.collapse = function() {
+ for (let i = this.__v_models.length - 1; i >= 0; i--) {
+ const item = this.__v_models[i];
+ item.elt.body.classList.remove('expand');
+ item.elt.body.classList.add('collapse');
+ }
+};
/*
- id: item's id
- action - open/close
+ id: item's id
+ action - open/close
*/
/**
- * trigger item that expands or collapses item's body.
+ * trigger item that expands or collapses item's body.
* @param {String} itemId
- * item id that identifies an item on the list
- * @param {String} [action='close']
+ * item id that identifies an item on the list
+ * @param {String} [action='close']
* two option: 'open' or 'close'
*/
-CollapsibleList.prototype.triggerContent = function(itemId, action = 'close'){
- if(action == 'open'){
- const item = this.__v_models.find(item => item.id===itemId);
- if(item) {
- this.collapse();
- item.elt.body.classList.remove('collapse');
- item.elt.body.classList.add('expand');
- item.elt.head.querySelector('i').textContent = 'remove';
- }
- }else if(action == 'close'){
- const item = this.__v_models.find(item => item.id===itemId);
- if(item) {
- item.elt.body.classList.remove('expand');
- item.elt.body.classList.add('collapse');
- item.elt.head.querySelector('i').textContent = 'add';
- }
- }else{
- console.log(`${this.name}:No actions`);
- return;
- }
- if(this.setting.changeCallBack) {
- const data = this.__v_models.map( item => {
- return {
- id:item.id,
- isExpand:item.elt.body.classList.contains('expand')?true:false
- }
- });
-
- this.setting.changeCallBack.call(this, data);
- }
+CollapsibleList.prototype.triggerContent = function(itemId, action = 'close') {
+ if (action == 'open') {
+ const item = this.__v_models.find((item) => item.id===itemId);
+ if (item) {
+ this.collapse();
+ item.elt.body.classList.remove('collapse');
+ item.elt.body.classList.add('expand');
+ item.elt.head.querySelector('i').textContent = 'remove';
+ }
+ } else if (action == 'close') {
+ const item = this.__v_models.find((item) => item.id===itemId);
+ if (item) {
+ item.elt.body.classList.remove('expand');
+ item.elt.body.classList.add('collapse');
+ item.elt.head.querySelector('i').textContent = 'add';
+ }
+ } else {
+ console.log(`${this.name}:No actions`);
+ return;
+ }
+ if (this.setting.changeCallBack) {
+ const data = this.__v_models.map( (item) => {
+ return {
+ id: item.id,
+ isExpand: item.elt.body.classList.contains('expand')?true:false,
+ };
+ });
+
+ this.setting.changeCallBack.call(this, data);
+ }
};
-CollapsibleList.prototype.displayContent = function(itemId, action = true, part = 'all'){
- const item = this.__v_models.find(item => item.id === itemId);
- if(item) {
- switch (part) {
- case 'head':
- item.elt.head.style.display = action?'block':'none';
- break;
- case 'body':
- item.elt.body.style.display = action?'block':'none';
- // statements_1
- break;
- default:
- item.elt.head.style.display = action?'block':'none';
- item.elt.body.style.display = action?'block':'none';
- // statements_def
- break;
- }
- }
-}
+CollapsibleList.prototype.displayContent = function(itemId, action = true, part = 'all') {
+ const item = this.__v_models.find((item) => item.id === itemId);
+ if (item) {
+ switch (part) {
+ case 'head':
+ item.elt.head.style.display = action?'block':'none';
+ break;
+ case 'body':
+ item.elt.body.style.display = action?'block':'none';
+ // statements_1
+ break;
+ default:
+ item.elt.head.style.display = action?'block':'none';
+ item.elt.body.style.display = action?'block':'none';
+ // statements_def
+ break;
+ }
+ }
+};
/**
* Add the content of a specific item body by using Id.
@@ -346,45 +342,41 @@ CollapsibleList.prototype.displayContent = function(itemId, action = true, part
* @param {String|ELement} elt
* The content that the item body has.
*/
-CollapsibleList.prototype.addContent = function(itemId, elt){
-
- const item = this.__v_models.find(one => one.id === itemId);
- if(item && item.elt){
- const content = item.elt.body.querySelector('.item_content');
- if(elt instanceof Element) content.appendChild(elt);
- if(typeof elt === 'string') {
- const div = document.createElement('div');
- div.innerHTML = elt;
- const childern = [...div.children];
-
- childern.forEach(child =>{
- content.appendChild(child);
- })
-
- };
- return true;
- }else{
- console.warn('id is invalid...');
- return false;
- }
+CollapsibleList.prototype.addContent = function(itemId, elt) {
+ const item = this.__v_models.find((one) => one.id === itemId);
+ if (item && item.elt) {
+ const content = item.elt.body.querySelector('.item_content');
+ if (elt instanceof Element) content.appendChild(elt);
+ if (typeof elt === 'string') {
+ const div = document.createElement('div');
+ div.innerHTML = elt;
+ const childern = [...div.children];
+
+ childern.forEach((child) =>{
+ content.appendChild(child);
+ });
+ };
+ return true;
+ } else {
+ console.warn('id is invalid...');
+ return false;
+ }
};
/**
* Clear the all content of a specific item body by using Id.
* @param {String} itemId
* item id that identifies an item on the list
- *
+ *
*/
-CollapsibleList.prototype.clearContent = function(itemId){
-
- const item = this.__v_models.find(one => one.id === itemId);
- if(item && item.elt){
- const content = item.elt.body.querySelector('.item_content');
- empty(content);
- return true;
- }else{
- console.warn('id is invalid...');
- return false;
- }
+CollapsibleList.prototype.clearContent = function(itemId) {
+ const item = this.__v_models.find((one) => one.id === itemId);
+ if (item && item.elt) {
+ const content = item.elt.body.querySelector('.item_content');
+ empty(content);
+ return true;
+ } else {
+ console.warn('id is invalid...');
+ return false;
+ }
};
-
diff --git a/components/heatmapcontrol/heatmapcontrol.js b/components/heatmapcontrol/heatmapcontrol.js
index ac18ec60a..34d02a169 100644
--- a/components/heatmapcontrol/heatmapcontrol.js
+++ b/components/heatmapcontrol/heatmapcontrol.js
@@ -1,352 +1,359 @@
// heatmapcontrol.js
//
-//Default Color List for gradient view
-const defaultColorList = ["#EAF2F8", "#D4E6F1", "#A9CCE3", "#7FB3D5", "#5499C7", "#2980B9", "#2471A3", "#1F618D", "#1A5276", "#154360"];
-//Regular Expression for testing valid color values
+// Default Color List for gradient view
+const defaultColorList = ['#EAF2F8',
+ '#D4E6F1',
+ '#A9CCE3',
+ '#7FB3D5',
+ '#5499C7',
+ '#2980B9',
+ '#2471A3',
+ '#1F618D',
+ '#1A5276',
+ '#154360'];
+// Regular Expression for testing valid color values
const cssHexRegExp = new RegExp('^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$');
-function HeatmapControl(options){
- this.name = 'HeatmapControl';
- /*
- list:[
- {
- id: ,
- title: ,
- icon: ,
- content:string
- isExpand:,
+function HeatmapControl(options) {
+ this.name = 'HeatmapControl';
+ /*
+ list:[
+ {
+ id: ,
+ title: ,
+ icon: ,
+ content:string
+ isExpand:,
- }
- ]
- */
- this.setting = {
- fields:null,
- mode:null,
- currentField:null,
- onChange:null,
- onOpacityChange:null
- }
+ }
+ ]
+ */
+ this.setting = {
+ fields: null,
+ mode: null,
+ currentField: null,
+ onChange: null,
+ onOpacityChange: null,
+ };
- extend(this.setting, options);
+ extend(this.setting, options);
- // attach container element
- this.elt = document.getElementById(this.setting.id);
- if(!this.elt && this.setting.element){
- this.elt = this.setting.element;
- }
+ // attach container element
+ this.elt = document.getElementById(this.setting.id);
+ if (!this.elt && this.setting.element) {
+ this.elt = this.setting.element;
+ }
- if(!this.elt){
- // create main
- this.elt = document.createElement('div');
- }
-
- //create UI
- this.__refresh();
+ if (!this.elt) {
+ // create main
+ this.elt = document.createElement('div');
+ }
+ // create UI
+ this.__refresh();
}
/**
* @private
* __refresh refresh UI part according to this.setting
*/
-HeatmapControl.prototype.__refresh = function(){
- empty(this.elt);
- this.elt.classList.add('hmc-container');
- this.rangeSliders = {};
- const template = `
-
+HeatmapControl.prototype.__refresh = function() {
+ empty(this.elt);
+ this.elt.classList.add('hmc-container');
+ this.rangeSliders = {};
+ const template = `
+
- Gradient
-
-
-
-
-
Properties:
-
-
-
-
-
- Color
-
-
- `;
- this.elt.innerHTML = template;
- const checkbox = this.elt.querySelector('.mode-panel input[type=checkbox]');
- checkbox.addEventListener('change', this._modeChanged.bind(this));
- //
- const color = this.elt.querySelector('.color-panel input[type=color]');
- color.addEventListener('input', this._colorChanged.bind(this));
+
Gradient
+
+
+
+
+ Properties:
+
- this.rangeSliders = {};
- createSelect(this.elt.querySelector('.sel-field-panel select') ,this.setting.fields,this.setting.currentField);
- this.elt.querySelector('.sel-field-panel select').addEventListener('change', this._selChanged.bind(this));
- if(this.setting.mode=='binal') this.elt.querySelector('.sel-field-panel').style.display='none';
+
+
+
+ Color
+
+
+ `;
+ this.elt.innerHTML = template;
+ const checkbox = this.elt.querySelector('.mode-panel input[type=checkbox]');
+ checkbox.addEventListener('change', this._modeChanged.bind(this));
+ //
+ const color = this.elt.querySelector('.color-panel input[type=color]');
+ color.addEventListener('input', this._colorChanged.bind(this));
+ this.rangeSliders = {};
+ createSelect(this.elt.querySelector('.sel-field-panel select'), this.setting.fields, this.setting.currentField);
+ this.elt.querySelector('.sel-field-panel select').addEventListener('change', this._selChanged.bind(this));
+ if (this.setting.mode=='binal') this.elt.querySelector('.sel-field-panel').style.display='none';
- const fieldsPanel = this.elt.querySelector('.fields-panel');
- this.setting.fields.forEach(f=>{
- this.rangeSliders[f.name] = createField(fieldsPanel,f,this.__change.bind(this));
- },this);
- this.opacitySliders = {};
- const opacitiesPanel = this.elt.querySelector('.opacity-panel');
- this.setting.opacities.forEach(f=>{
- this.opacitySliders[f.name] = createOpacities(opacitiesPanel,f,this.__opacityChange.bind(this));
- },this);
+ const fieldsPanel = this.elt.querySelector('.fields-panel');
+ this.setting.fields.forEach((f)=>{
+ this.rangeSliders[f.name] = createField(fieldsPanel, f, this.__change.bind(this));
+ }, this);
+ this.opacitySliders = {};
+ const opacitiesPanel = this.elt.querySelector('.opacity-panel');
+ this.setting.opacities.forEach((f)=>{
+ this.opacitySliders[f.name] = createOpacities(opacitiesPanel, f, this.__opacityChange.bind(this));
+ }, this);
- const colorsLegendPanel = this.elt.querySelector('.colors-legend-panel');
- //min max logic for valid number of intervals
- $(colorsLegendPanel).find('#legendIntervals').on('change', function(e){
- var min=parseFloat($(this).attr('min'));
- var max=parseFloat($(this).attr('max'));
- var curr=parseFloat($(this).val());
- if (curr > max) { $(this).val(max); var changed=true; }
- if (curr < min) { $(this).val(min); var changed=true; }
- if (changed) {
- $warning = $(colorsLegendPanel).find('.warning')
- $warning.text('Only values in ' + min + ' through ' + max + ' allowed.');
- $warning.show()
- $warning.fadeOut(4500);
- }
- });
-
- const legendIntervalsInput = colorsLegendPanel.querySelector("#legendIntervals");
- //Setting default value of intervals
- legendIntervalsInput.value = 5;
- const noOfIntervals = legendIntervalsInput.value;
+ const colorsLegendPanel = this.elt.querySelector('.colors-legend-panel');
+ // min max logic for valid number of intervals
+ $(colorsLegendPanel).find('#legendIntervals').on('change', function(e) {
+ const min=parseFloat($(this).attr('min'));
+ const max=parseFloat($(this).attr('max'));
+ const curr=parseFloat($(this).val());
+ if (curr > max) {
+ $(this).val(max); var changed=true;
+ }
+ if (curr < min) {
+ $(this).val(min); var changed=true;
+ }
+ if (changed) {
+ $warning = $(colorsLegendPanel).find('.warning');
+ $warning.text('Only values in ' + min + ' through ' + max + ' allowed.');
+ $warning.show();
+ $warning.fadeOut(4500);
+ }
+ });
- const legendsContainer = colorsLegendPanel.querySelector('.legends');
- createIntervalInputs(legendsContainer, noOfIntervals, this._legendColorsChanged.bind(this) );
- legendIntervalsInput.addEventListener('change', ()=>{
- createIntervalInputs(legendsContainer, legendIntervalsInput.value, this._legendColorsChanged.bind(this))
- this._legendColorsChanged();
- });
+ const legendIntervalsInput = colorsLegendPanel.querySelector('#legendIntervals');
+ // Setting default value of intervals
+ legendIntervalsInput.value = 5;
+ const noOfIntervals = legendIntervalsInput.value;
- this._modeChanged(false);
-}
+ const legendsContainer = colorsLegendPanel.querySelector('.legends');
+ createIntervalInputs(legendsContainer, noOfIntervals, this._legendColorsChanged.bind(this) );
+ legendIntervalsInput.addEventListener('change', ()=>{
+ createIntervalInputs(legendsContainer, legendIntervalsInput.value, this._legendColorsChanged.bind(this));
+ this._legendColorsChanged();
+ });
-HeatmapControl.prototype._modeChanged = function(flag = true){
- const mode = this.elt.querySelector(`.mode-panel input[type=checkbox]`).checked;
+ this._modeChanged(false);
+};
- if(!mode){// binal
- this.elt.querySelector('.color-panel').style.display='';
- this.elt.querySelector('.colors-legend-panel').style.display='none';
- this.elt.querySelector('.sel-field-panel').style.display='none';
- this.setting.fields.forEach( f=> {
- // statements
- this.rangeSliders[f.name].slider.parentNode.style.display='';
- this.rangeSliders[f.name].disabled(false);
- },this);
- }else{ // gradient
- this.elt.querySelector('.color-panel').style.display='none';
- this.elt.querySelector('.colors-legend-panel').style.display='';
- this.elt.querySelector('.sel-field-panel').style.display='';
- const selectedField = this.elt.querySelector('.sel-field-panel select').value;
- this.rangeSliders[selectedField].slider.parentNode.style.display='';
- this.rangeSliders[selectedField].disabled(false);
- this.setting.fields.forEach( f=> {
- // statements
- if(f.name !== selectedField) {
- this.rangeSliders[f.name].slider.parentNode.style.display='none';
- this.rangeSliders[f.name].disabled(true);
- }
+HeatmapControl.prototype._modeChanged = function(flag = true) {
+ const mode = this.elt.querySelector(`.mode-panel input[type=checkbox]`).checked;
- },this);
- }
- if(flag)this.__change.call(this);
-}
-//To validate and update heatmap color in binal mode
-HeatmapControl.prototype._colorChanged = function(){
- const color = this.elt.querySelector("#heatMapColor").value;
- if(cssHexRegExp.test(color)){
- this.__change.call(this);
- }
-}
-//To validate and update heatmap colors in gradient mode
-HeatmapControl.prototype._legendColorsChanged = function(){
- let valid = true;
- const colorLegendPanel = this.elt.querySelector('.colors-legend-panel');
- $(colorLegendPanel.querySelector('.legends'))
- .children()
- .each(function (index,colorDiv) {
- if(cssHexRegExp.test(colorDiv.querySelector('input').value)===false){
- valid = false;
- return;
- }
- });
- if(valid) this.__change.call(this);
-}
+ if (!mode) {// binal
+ this.elt.querySelector('.color-panel').style.display='';
+ this.elt.querySelector('.colors-legend-panel').style.display='none';
+ this.elt.querySelector('.sel-field-panel').style.display='none';
+ this.setting.fields.forEach( (f)=> {
+ // statements
+ this.rangeSliders[f.name].slider.parentNode.style.display='';
+ this.rangeSliders[f.name].disabled(false);
+ }, this);
+ } else { // gradient
+ this.elt.querySelector('.color-panel').style.display='none';
+ this.elt.querySelector('.colors-legend-panel').style.display='';
+ this.elt.querySelector('.sel-field-panel').style.display='';
+ const selectedField = this.elt.querySelector('.sel-field-panel select').value;
+ this.rangeSliders[selectedField].slider.parentNode.style.display='';
+ this.rangeSliders[selectedField].disabled(false);
+ this.setting.fields.forEach( (f)=> {
+ // statements
+ if (f.name !== selectedField) {
+ this.rangeSliders[f.name].slider.parentNode.style.display='none';
+ this.rangeSliders[f.name].disabled(true);
+ }
+ }, this);
+ }
+ if (flag) this.__change.call(this);
+};
+// To validate and update heatmap color in binal mode
+HeatmapControl.prototype._colorChanged = function() {
+ const color = this.elt.querySelector('#heatMapColor').value;
+ if (cssHexRegExp.test(color)) {
+ this.__change.call(this);
+ }
+};
+// To validate and update heatmap colors in gradient mode
+HeatmapControl.prototype._legendColorsChanged = function() {
+ let valid = true;
+ const colorLegendPanel = this.elt.querySelector('.colors-legend-panel');
+ $(colorLegendPanel.querySelector('.legends'))
+ .children()
+ .each(function(index, colorDiv) {
+ if (cssHexRegExp.test(colorDiv.querySelector('input').value)===false) {
+ valid = false;
+ return;
+ }
+ });
+ if (valid) this.__change.call(this);
+};
-HeatmapControl.prototype._selChanged = function(e){
- const selectedField = this.elt.querySelector('.sel-field-panel select').value;
- this.rangeSliders[selectedField].slider.parentNode.style.display = '';
- this.rangeSliders[selectedField].disabled(false);
- this.setting.fields.forEach( f=> {
- // statements
- if(f.name !== selectedField) {
- this.rangeSliders[f.name].slider.parentNode.style.display = 'none';
- this.rangeSliders[f.name].disabled(true);
- }
- },this);
- this.__change.call(this);
-}
-HeatmapControl.prototype.resize = function(){
- this.setting.fields.forEach( f => {
- // statements
- this.rangeSliders[f.name].onResize();
- },this);
+HeatmapControl.prototype._selChanged = function(e) {
+ const selectedField = this.elt.querySelector('.sel-field-panel select').value;
+ this.rangeSliders[selectedField].slider.parentNode.style.display = '';
+ this.rangeSliders[selectedField].disabled(false);
+ this.setting.fields.forEach( (f)=> {
+ // statements
+ if (f.name !== selectedField) {
+ this.rangeSliders[f.name].slider.parentNode.style.display = 'none';
+ this.rangeSliders[f.name].disabled(true);
+ }
+ }, this);
+ this.__change.call(this);
+};
+HeatmapControl.prototype.resize = function() {
+ this.setting.fields.forEach( (f) => {
+ // statements
+ this.rangeSliders[f.name].onResize();
+ }, this);
- this.setting.opacities.forEach( f => {
- // statements
- this.opacitySliders[f.name].onResize();
- },this);
-}
-HeatmapControl.prototype.__change = function(){
- if(this.setting.onChange && typeof this.setting.onChange === 'function'){
+ this.setting.opacities.forEach( (f) => {
+ // statements
+ this.opacitySliders[f.name].onResize();
+ }, this);
+};
+HeatmapControl.prototype.__change = function() {
+ if (this.setting.onChange && typeof this.setting.onChange === 'function') {
+ const mode = this.elt.querySelector(`.mode-panel input[type=checkbox]`).checked;
+ const color = this.elt.querySelector('#heatMapColor').value;
+ const colorLegendPanel = this.elt.querySelector('.colors-legend-panel');
+ const colors = getColors(colorLegendPanel.querySelector('.legends'));
+ const fields = [];
+ const field = {};
+ const data = {
+ mode: mode?'gradient':'binal',
+ color: color,
+ colors: colors,
+ };
- const mode = this.elt.querySelector(`.mode-panel input[type=checkbox]`).checked;
- const color = this.elt.querySelector("#heatMapColor").value
- const colorLegendPanel = this.elt.querySelector('.colors-legend-panel');
- const colors = getColors(colorLegendPanel.querySelector('.legends'));
- const fields = [];
- const field = {};
- const data = {
- mode:mode?'gradient':'binal',
- color:color,
- colors:colors
- }
+ if (!mode) {
+ this.setting.fields.forEach( (f)=> {
+ fields.push({name: f.name, range: this.rangeSliders[f.name].getValue()});
+ });
+ data.fields = fields;
+ } else {
+ const selectedField = this.elt.querySelector('.sel-field-panel select').value;
+ field.name = selectedField;
+ field.range = this.rangeSliders[selectedField].getValue();
+ data.field = field;
+ }
+ this.setting.onChange(data);
+ }
+};
- if(!mode){
- this.setting.fields.forEach( f=> {
- fields.push({name:f.name,range:this.rangeSliders[f.name].getValue()});
- });
- data.fields = fields;
- }else {
- const selectedField = this.elt.querySelector('.sel-field-panel select').value;
- field.name = selectedField;
- field.range = this.rangeSliders[selectedField].getValue();
- data.field = field;
- }
- this.setting.onChange(data);
- }
-}
-
-HeatmapControl.prototype.getThreshold = function(){
- elt.querySelectorAll('.fields-panel > div').filter(elt=>{});
-}
+HeatmapControl.prototype.getThreshold = function() {
+ elt.querySelectorAll('.fields-panel > div').filter((elt)=>{});
+};
-HeatmapControl.prototype.__opacityChange = function(){
- if(this.setting.onChange && typeof this.setting.onChange === 'function'){
- const data = {};
- this.setting.opacities.forEach( f => {
- data[f.name] = this.opacitySliders[f.name].getValue()/100;
- });
- this.setting.onOpacityChange(data);
- }
-}
-
-function createSelect(sel, fields, currentField = null){
+HeatmapControl.prototype.__opacityChange = function() {
+ if (this.setting.onChange && typeof this.setting.onChange === 'function') {
+ const data = {};
+ this.setting.opacities.forEach( (f) => {
+ data[f.name] = this.opacitySliders[f.name].getValue()/100;
+ });
+ this.setting.onOpacityChange(data);
+ }
+};
- fields.forEach(field => {
- var option = document.createElement('option');
+function createSelect(sel, fields, currentField = null) {
+ fields.forEach((field) => {
+ const option = document.createElement('option');
- option.text = field.name;
- option.value = field.name;
+ option.text = field.name;
+ option.value = field.name;
- sel.add(option);
- if(currentField) sel.value = currentField;
- });
+ sel.add(option);
+ if (currentField) sel.value = currentField;
+ });
}
-function createField(container, field, changeFunc){
- const div = document.createElement('div');
- const label = document.createElement('label');
- label.textContent = field.name;
- const slider = document.createElement('input');
- slider.type = 'text';
- slider.name = field.name;
- //rangeSlider.
- div.appendChild(label);
- div.appendChild(slider);
- // field value catch
- field.value = field.value || field.range || [0.05,0,1]
- const rs = new rangeSlider({
- target: slider,
- values: {min:field.range[0]*100 >> 0,max:field.range[1]*100 >> 0},
- step:1,
- range: true,
- tooltip: false,
- scale: false,
- labels: false,
- set: [field.value[0]*100 >> 0, field.value[1]*100 >> 0],
- onChange:changeFunc
- });
- container.appendChild(div);
- return rs;
+function createField(container, field, changeFunc) {
+ const div = document.createElement('div');
+ const label = document.createElement('label');
+ label.textContent = field.name;
+ const slider = document.createElement('input');
+ slider.type = 'text';
+ slider.name = field.name;
+ // rangeSlider.
+ div.appendChild(label);
+ div.appendChild(slider);
+ // field value catch
+ field.value = field.value || field.range || [0.05, 0, 1];
+ const rs = new rangeSlider({
+ target: slider,
+ values: {min: field.range[0]*100 >> 0, max: field.range[1]*100 >> 0},
+ step: 1,
+ range: true,
+ tooltip: false,
+ scale: false,
+ labels: false,
+ set: [field.value[0]*100 >> 0, field.value[1]*100 >> 0],
+ onChange: changeFunc,
+ });
+ container.appendChild(div);
+ return rs;
}
-function createOpacities(container, field, changeFunc){
- const div = document.createElement('div');
- const label = document.createElement('label');
- label.textContent = field.name;
- const slider = document.createElement('input');
- slider.type = 'text';
- slider.name = field.name;
- //rangeSlider.
- div.appendChild(label);
- div.appendChild(slider);
- const rs = new rangeSlider({
- target: slider,
- values: {min:0,max:100},
- step:1,
- range: false,
- tooltip: false,
- scale: false,
- labels: false,
- set: [field.value*100],
- onChange:changeFunc
- });
- container.appendChild(div);
- return rs;
+function createOpacities(container, field, changeFunc) {
+ const div = document.createElement('div');
+ const label = document.createElement('label');
+ label.textContent = field.name;
+ const slider = document.createElement('input');
+ slider.type = 'text';
+ slider.name = field.name;
+ // rangeSlider.
+ div.appendChild(label);
+ div.appendChild(slider);
+ const rs = new rangeSlider({
+ target: slider,
+ values: {min: 0, max: 100},
+ step: 1,
+ range: false,
+ tooltip: false,
+ scale: false,
+ labels: false,
+ set: [field.value*100],
+ onChange: changeFunc,
+ });
+ container.appendChild(div);
+ return rs;
}
-//Create HTML Color inputs for given noOfIntervals
-function createIntervalInputs(container, noOfIntervals, changeFunc){
- //Empty the container
- while ( container.firstChild ) container.removeChild( container.firstChild );
- for (let i = 1; i <= noOfIntervals; i++) {
-
- const div = document.createElement('div');
- div.className = 'color-input-container';
- const label = document.createElement('label');
- label.textContent = `Interval ${i} `;
- label.className = 'color-input'
- const color = document.createElement('input');
- color.type = 'color';
- color.value = defaultColorList[getGradientColorIndex(i, noOfIntervals)];
- color.oninput = changeFunc
- //Input for color legends.
- div.appendChild(label);
- div.appendChild(color);
-
- container.appendChild(div);
- }
+// Create HTML Color inputs for given noOfIntervals
+function createIntervalInputs(container, noOfIntervals, changeFunc) {
+ // Empty the container
+ while ( container.firstChild ) container.removeChild( container.firstChild );
+ for (let i = 1; i <= noOfIntervals; i++) {
+ const div = document.createElement('div');
+ div.className = 'color-input-container';
+ const label = document.createElement('label');
+ label.textContent = `Interval ${i} `;
+ label.className = 'color-input';
+ const color = document.createElement('input');
+ color.type = 'color';
+ color.value = defaultColorList[getGradientColorIndex(i, noOfIntervals)];
+ color.oninput = changeFunc;
+ // Input for color legends.
+ div.appendChild(label);
+ div.appendChild(color);
+
+ container.appendChild(div);
+ }
}
// returns selected colors for intervals
-function getColors(container){
- const rs = [];
- $(container).children().each(function (index,colorDiv) {
- rs.push(colorDiv.querySelector('input').value)
- });
- return rs;
+function getColors(container) {
+ const rs = [];
+ $(container).children().each(function(index, colorDiv) {
+ rs.push(colorDiv.querySelector('input').value);
+ });
+ return rs;
}
-// returns index of color in defaultColorList for given position and no of intervals
-function getGradientColorIndex(position, noOfIntervals){
- return parseInt((position * (10 / noOfIntervals)) - 1)
+// returns index of color in defaultColorList for given position and no of intervals
+function getGradientColorIndex(position, noOfIntervals) {
+ return parseInt((position * (10 / noOfIntervals)) - 1);
}
diff --git a/components/heatmapediteddatapanel/heatmapediteddatapanel.js b/components/heatmapediteddatapanel/heatmapediteddatapanel.js
index b461ab8d3..acd435d82 100644
--- a/components/heatmapediteddatapanel/heatmapediteddatapanel.js
+++ b/components/heatmapediteddatapanel/heatmapediteddatapanel.js
@@ -1,113 +1,110 @@
// heatmapediteddatapanel.js
-function HeatmapEditedDataPanel(options){
- this.name = 'HeatmapEditedDataPanel';
- /*
- list:[
- {
- id: ,
- title: ,
- icon: ,
- content:string
- isExpand:,
-
- }
- ]
- */
- this.setting = {
- data:null,
- onDBClick:null,
- onDelete:null
- }
+function HeatmapEditedDataPanel(options) {
+ this.name = 'HeatmapEditedDataPanel';
+ /*
+ list:[
+ {
+ id: ,
+ title: ,
+ icon: ,
+ content:string
+ isExpand:,
- extend(this.setting, options);
+ }
+ ]
+ */
+ this.setting = {
+ data: null,
+ onDBClick: null,
+ onDelete: null,
+ };
- // attach container element
- this.elt = document.getElementById(this.setting.id);
- if(!this.elt && this.setting.element){
- this.elt = this.setting.element;
- }
+ extend(this.setting, options);
- if(!this.elt){
- // create main
- this.elt = document.createElement('div');
- }
+ // attach container element
+ this.elt = document.getElementById(this.setting.id);
+ if (!this.elt && this.setting.element) {
+ this.elt = this.setting.element;
+ }
- //create UI
- this.__refresh();
+ if (!this.elt) {
+ // create main
+ this.elt = document.createElement('div');
+ }
+ // create UI
+ this.__refresh();
}
/**
* @private
* __refresh refresh UI part according to this.setting
*/
-HeatmapEditedDataPanel.prototype.__refresh = function(){
- empty(this.elt);
- this.elt.classList.add('hmed-container');
- this._clusters = [];
- this.setting.data.clusters.forEach(cluster => {
- const name = cluster.name;
- const index = cluster.index;
- const value = +cluster.value;
- const color = cluster.color;
- const cate_value = value?'Positive':'Negative';
- const title = createEditedDataTitle(name,cate_value);
- this.elt.appendChild(title);
- // add toggle event
- title.querySelector('.icon').addEventListener('click', function(e){
- const list = title.nextElementSibling;
- if(title.querySelector('.icon').textContent=='keyboard_arrow_up'){
- title.querySelector('.icon').textContent = 'keyboard_arrow_down';
- list.style.display = 'none';
- }else{
- title.querySelector('.icon').textContent = 'keyboard_arrow_up';
- list.style.display = '';
- }
- });
+HeatmapEditedDataPanel.prototype.__refresh = function() {
+ empty(this.elt);
+ this.elt.classList.add('hmed-container');
+ this._clusters = [];
+ this.setting.data.clusters.forEach((cluster) => {
+ const name = cluster.name;
+ const index = cluster.index;
+ const value = +cluster.value;
+ const color = cluster.color;
+ const cate_value = value?'Positive':'Negative';
+ const title = createEditedDataTitle(name, cate_value);
+ this.elt.appendChild(title);
+ // add toggle event
+ title.querySelector('.icon').addEventListener('click', function(e) {
+ const list = title.nextElementSibling;
+ if (title.querySelector('.icon').textContent=='keyboard_arrow_up') {
+ title.querySelector('.icon').textContent = 'keyboard_arrow_down';
+ list.style.display = 'none';
+ } else {
+ title.querySelector('.icon').textContent = 'keyboard_arrow_up';
+ list.style.display = '';
+ }
+ });
+ const listDiv = document.createElement('div');
+ listDiv.classList.add('list');
+ this.elt.appendChild(listDiv);
+ cluster.editDataArray.forEach((line, idx) => {
+ const lineDiv = createEditedDataItem(idx, color);
+ listDiv.appendChild(lineDiv);
-
- const listDiv = document.createElement('div');
- listDiv.classList.add('list');
- this.elt.appendChild(listDiv);
- cluster.editDataArray.forEach((line,idx) => {
- const lineDiv = createEditedDataItem(idx,color);
- listDiv.appendChild(lineDiv);
+ lineDiv.addEventListener('dblclick', function(e) {
+ if (isFunction(this.setting.onDBClick)) {
+ this.setting.onDBClick.call(lineDiv, {
+ cluster: cluster,
+ index: idx,
+ });
+ }
+ }.bind(this));
- lineDiv.addEventListener('dblclick', function(e){
- if(isFunction(this.setting.onDBClick))
- this.setting.onDBClick.call(lineDiv, {
- cluster:cluster,
- index:idx
- });
- }.bind(this));
-
- lineDiv.querySelector('.icon').addEventListener('click', function(e){
- if(isFunction(this.setting.onDelete))
- this.setting.onDelete.call(lineDiv, {
- cluster:cluster,
- index:idx
- });
- }.bind(this));
-
- });
-
- });
-}
-function createEditedDataTitle(name, cate){
- const div = document.createElement('div');
- div.classList.add('title');
- const clusterTemplate = `keyboard_arrow_up
${name} - ${cate}
`;
- div.innerHTML = clusterTemplate;
- return div;
+ lineDiv.querySelector('.icon').addEventListener('click', function(e) {
+ if (isFunction(this.setting.onDelete)) {
+ this.setting.onDelete.call(lineDiv, {
+ cluster: cluster,
+ index: idx,
+ });
+ }
+ }.bind(this));
+ });
+ });
+};
+function createEditedDataTitle(name, cate) {
+ const div = document.createElement('div');
+ div.classList.add('title');
+ const clusterTemplate = `keyboard_arrow_up
${name} - ${cate}
`;
+ div.innerHTML = clusterTemplate;
+ return div;
}
-function createEditedDataItem(idx, color){
- const div = document.createElement('div');
- div.innerHTML = `
${idx}
clear
`;
- return div;
+function createEditedDataItem(idx, color) {
+ const div = document.createElement('div');
+ div.innerHTML = `
${idx}
clear
`;
+ return div;
}
-HeatmapEditedDataPanel.prototype.__dbclick = function(){
+HeatmapEditedDataPanel.prototype.__dbclick = function() {
-}
\ No newline at end of file
+};
diff --git a/components/heatmapeditorpanel/heatmapeditorpanel.js b/components/heatmapeditorpanel/heatmapeditorpanel.js
index 4c6284c6b..1dd9a8f6d 100644
--- a/components/heatmapeditorpanel/heatmapeditorpanel.js
+++ b/components/heatmapeditorpanel/heatmapeditorpanel.js
@@ -1,113 +1,112 @@
// heatmapeditorpanel.js
-function HeatmapEditorPanel(options){
- this.name = 'HeatmapEditorPanel';
-
- this.setting = {
- data:null,
- fields:null, // required
- editedDate:null, //required
- onFieldChange:null,
- onClick:null,
- onRemove:null,
- onReset:null,
- onSave:null,
- }
+function HeatmapEditorPanel(options) {
+ this.name = 'HeatmapEditorPanel';
- extend(this.setting, options);
+ this.setting = {
+ data: null,
+ fields: null, // required
+ editedDate: null, // required
+ onFieldChange: null,
+ onClick: null,
+ onRemove: null,
+ onReset: null,
+ onSave: null,
+ };
- // attach container element
- this.elt = document.getElementById(this.setting.id);
- if(!this.elt && this.setting.element){
- this.elt = this.setting.element;
- }
+ extend(this.setting, options);
- if(!this.elt){
- // create main
- this.elt = document.createElement('div');
- }
+ // attach container element
+ this.elt = document.getElementById(this.setting.id);
+ if (!this.elt && this.setting.element) {
+ this.elt = this.setting.element;
+ }
- //create UI
- this.__refresh();
+ if (!this.elt) {
+ // create main
+ this.elt = document.createElement('div');
+ }
+ // create UI
+ this.__refresh();
}
-const fieldsColors = ['#576971','#0A1316','#DFB9C1','#2F1218','#C0A7A3','#271A18','#D07DBE', '#2F0526'];
-function createRadios(fields,name){
-
- let radiosTemplate ='';
- fields.forEach((field,idx)=>{
- radiosTemplate+= `
-
-
- ${field.name} - positive
- `;
- radiosTemplate+= `
-
-
- ${field.name} - negative
- `;
- })
- return radiosTemplate;
-}
-HeatmapEditorPanel.prototype.getAllOperations = function(){
- const radios = this.elt.querySelectorAll('.fields-panel input[type=radio]');
- const rs = [];
- radios.forEach(r=>{
- //const [index,name,value,color] = r.value.split('|')
- rs.push(r.value.split('|'))
- })
- return rs;
+const fieldsColors = ['#576971', '#0A1316', '#DFB9C1', '#2F1218', '#C0A7A3', '#271A18', '#D07DBE', '#2F0526'];
+function createRadios(fields, name) {
+ let radiosTemplate ='';
+ fields.forEach((field, idx)=>{
+ radiosTemplate+= `
+
+
+ ${field.name} - positive
+ `;
+ radiosTemplate+= `
+
+
+ ${field.name} - negative
+ `;
+ });
+ return radiosTemplate;
}
+HeatmapEditorPanel.prototype.getAllOperations = function() {
+ const radios = this.elt.querySelectorAll('.fields-panel input[type=radio]');
+ const rs = [];
+ radios.forEach((r)=>{
+ // const [index,name,value,color] = r.value.split('|')
+ rs.push(r.value.split('|'));
+ });
+ return rs;
+};
-HeatmapEditorPanel.prototype.getCurrentOperation = function(){
- const radio = this.elt.querySelector('.fields-panel input[type=radio]:checked');
- return radio?radio.value.split('|'):null;
-}
+HeatmapEditorPanel.prototype.getCurrentOperation = function() {
+ const radio = this.elt.querySelector('.fields-panel input[type=radio]:checked');
+ return radio?radio.value.split('|'):null;
+};
/**
* @private
* __refresh refresh UI part according to this.setting
*/
-HeatmapEditorPanel.prototype.__refresh = function(){
- empty(this.elt);
- this.elt.classList.add('hmep-container');
- // create radio options
- const name = randomId();
- const radiosTempalte = createRadios(this.setting.fields, name);
-
-
- const template = `
-
- Operation:
- ${radiosTempalte}
-
-
- Clear
- Save
-
-
+HeatmapEditorPanel.prototype.__refresh = function() {
+ empty(this.elt);
+ this.elt.classList.add('hmep-container');
+ // create radio options
+ const name = randomId();
+ const radiosTempalte = createRadios(this.setting.fields, name);
+
+
+ const template = `
+
+ Operation:
+ ${radiosTempalte}
+
+
+ Clear
+ Save
+
+
-
- `;
- this.elt.innerHTML = template;
+
+ `;
+ this.elt.innerHTML = template;
- // set change event
- const radios = this.elt.querySelectorAll(`.fields-panel input[type=radio][name=${name}]`);
- radios[0].checked = true;
- radios.forEach(radio =>{
- radio.addEventListener('change',function(e){
- const target = e.srcElement || e.target;
- if(isFunction(this.setting.onFieldChange))
- this.setting.onFieldChange.call(null,target.value.split('|'));
- }.bind(this));
- });
+ // set change event
+ const radios = this.elt.querySelectorAll(`.fields-panel input[type=radio][name=${name}]`);
+ radios[0].checked = true;
+ radios.forEach((radio) =>{
+ radio.addEventListener('change', function(e) {
+ const target = e.srcElement || e.target;
+ if (isFunction(this.setting.onFieldChange)) {
+ this.setting.onFieldChange.call(null, target.value.split('|'));
+ }
+ }.bind(this));
+ });
- // set save event
- this.__save_btns = this.elt.querySelectorAll(`.btn-panel button`);
- this.__save_btns[0].addEventListener('click',function(e){
- if(isFunction(this.setting.onReset))this.setting.onReset.call(this);
- }.bind(this));
- this.__save_btns[1].addEventListener('click',function(e){
- if(isFunction(this.setting.onSave))this.setting.onSave.call(this);
- }.bind(this));
-}
\ No newline at end of file
+ // set save event
+ this.__save_btns = this.elt.querySelectorAll(`.btn-panel button`);
+ this.__save_btns[0].addEventListener('click', function(e) {
+ if (isFunction(this.setting.onReset)) this.setting.onReset.call(this);
+ }.bind(this));
+ this.__save_btns[1].addEventListener('click', function(e) {
+ if (isFunction(this.setting.onSave)) this.setting.onSave.call(this);
+ }.bind(this));
+};
diff --git a/components/layersviewer/layersviewer.js b/components/layersviewer/layersviewer.js
index d9488a3ed..63ab53c95 100644
--- a/components/layersviewer/layersviewer.js
+++ b/components/layersviewer/layersviewer.js
@@ -27,13 +27,13 @@
*
*/
function LayersViewer(options) {
- this.className = "LayersViewer";
+ this.className = 'LayersViewer';
this.setting = {
// id: doc element
// data: layers dataset
// categoricalData
- isSortableView: false
+ isSortableView: false,
};
/**
@@ -51,8 +51,8 @@ function LayersViewer(options) {
this.searchBar; // input and btn
this.categoricalView;
- //this.sortableView;
- //this.sortable;
+ // this.sortableView;
+ // this.sortable;
// setting dataset
extend(this.setting, options);
@@ -61,10 +61,10 @@ function LayersViewer(options) {
console.error(`${this.className}: No Main Elements...`);
return;
}
- this.elt.classList.add("layer_viewer");
+ this.elt.classList.add('layer_viewer');
// sort data
- //this.setting.data.sort(LayersViewer.compare);
+ // this.setting.data.sort(LayersViewer.compare);
// give index
// convert og data to categorical data
this.__covertData();
@@ -72,24 +72,24 @@ function LayersViewer(options) {
}
LayersViewer.prototype.toggleAllItems = function(isShow = false, fresh = true) {
- this.setting.data.forEach(d => (d.isShow = isShow));
+ this.setting.data.forEach((d) => (d.isShow = isShow));
if (fresh) this.update();
};
LayersViewer.prototype.addItem = function(item, isShow = true, fresh = true) {
- this.setting.data.push({ item: item, isShow: isShow });
+ this.setting.data.push({item: item, isShow: isShow});
if (fresh) this.update();
};
LayersViewer.prototype.removeItemById = function(id, fresh = true) {
- const index = this.setting.data.findIndex(d => d.item.id == id);
+ const index = this.setting.data.findIndex((d) => d.item.id == id);
if (index == -1) return;
this.setting.data.splice(index, 1);
if (fresh) this.update();
};
LayersViewer.prototype.getDataItemById = function(id) {
- return this.setting.data.find(d => d.item.id == id);
+ return this.setting.data.find((d) => d.item.id == id);
};
LayersViewer.prototype.onEnd = function(e) {
@@ -99,27 +99,27 @@ LayersViewer.prototype.onEnd = function(e) {
// move data from old index position to new index position
LayersViewer.moveArray(data, e.oldIndex, e.newIndex);
// refresh UI
- const sort = data.map(item => item.id);
+ const sort = data.map((item) => item.id);
this.sortable.sort(sort);
// callback functions
if (this.setting.sortChange) this.setting.sortChange.call(null, sort);
};
-LayersViewer.prototype.moveLayer = function(id, direction = "up") {
+LayersViewer.prototype.moveLayer = function(id, direction = 'up') {
const data = this.setting.data;
// find layer index
- const oldIndex = data.findIndex(item => item.id === id);
+ const oldIndex = data.findIndex((item) => item.id === id);
- const newIndex = direction === "up" ? oldIndex - 1 : oldIndex + 1;
+ const newIndex = direction === 'up' ? oldIndex - 1 : oldIndex + 1;
if (newIndex < 0 || newIndex >= data.length) {
- console.warn("move: Out Of Index");
+ console.warn('move: Out Of Index');
return;
}
// move data from old index position to new index position
LayersViewer.moveArray(data, oldIndex, newIndex);
// refresh UI
- const sort = data.map(item => item.id);
+ const sort = data.map((item) => item.id);
this.sortable.sort(sort);
// callback function
if (this.setting.sortChange) this.setting.sortChange.call(null, sort);
@@ -128,7 +128,7 @@ LayersViewer.prototype.moveLayer = function(id, direction = "up") {
// move
LayersViewer.moveArray = function(array, oldIndex, newIndex) {
if (newIndex >= array.length) {
- var dist = newIndex - array.length + 1;
+ let dist = newIndex - array.length + 1;
while (dist--) {
array.push(undefined);
}
@@ -159,7 +159,7 @@ LayersViewer.prototype.__clearUI = function() {
};
/*
- refresh UI
+ refresh UI
*/
LayersViewer.prototype.__refreshUI = function() {
empty(this.elt); // clear all elements
@@ -173,20 +173,20 @@ LayersViewer.prototype.__refreshUI = function() {
// add switch view event
// this.viewRadios.list.forEach(
- // radio => radio.elt.addEventListener('click',this.__radioClick.bind(this))
+ // radio => radio.elt.addEventListener('click',this.__radioClick.bind(this))
// );
/* create search bar area END */
/* categorical view START*/
// create categorical view div
- let cate_view_div = document.createElement("div");
- cate_view_div.classList.add("layers_list");
+ const cate_view_div = document.createElement('div');
+ cate_view_div.classList.add('layers_list');
// create categorical view content
const objCategories = LayersViewer.createCategoricalView.call(
- this,
- this.setting.categoricalData
+ this,
+ this.setting.categoricalData,
);
cate_view_div.appendChild(objCategories.view);
@@ -209,57 +209,59 @@ LayersViewer.prototype.__refreshUI = function() {
// sort_view_div.appendChild(objSortable.view);
// this.elt.appendChild(sort_view_div);
// this.sortableView = sort_view_div;
- /*sortable view END */
+ /* sortable view END */
// add search event
- this.searchBar.btn.addEventListener("click", this.__search.bind(this));
+ this.searchBar.btn.addEventListener('click', this.__search.bind(this));
//
- this.searchBar.text.addEventListener("change", this.__search.bind(this));
- this.searchBar.text.addEventListener("keyup", this.__search.bind(this));
+ this.searchBar.text.addEventListener('change', this.__search.bind(this));
+ this.searchBar.text.addEventListener('keyup', this.__search.bind(this));
// add event for all checkbox
- const checkboxes = this.elt.querySelectorAll("input[type=checkbox]");
- checkboxes.forEach(chk =>
- chk.addEventListener("change", this.__change.bind(this))
+ const checkboxes = this.elt.querySelectorAll('input[type=checkbox]');
+ checkboxes.forEach((chk) =>
+ chk.addEventListener('change', this.__change.bind(this)),
);
// expand and collapse control for categorical view
const cateItems = this.setting.categoricalData;
- for (let key in cateItems) {
- cateItems[key].elt.firstChild.addEventListener(
- "click",
- this.__switch.bind(this)
- );
+ for (const key in cateItems) {
+ if (cateItems.hasOwnProperty(key)) {
+ cateItems[key].elt.firstChild.addEventListener(
+ 'click',
+ this.__switch.bind(this),
+ );
+ }
}
// moveup
// const ups = this.sortableView.querySelectorAll('.moveup');
// ups.forEach( up => up.addEventListener('click',function(e){
- // const _id = e.target.parentNode.dataset.id;
- // this.moveLayer(_id,'up');
+ // const _id = e.target.parentNode.dataset.id;
+ // this.moveLayer(_id,'up');
// }.bind(this)));
// movedown
// const downs = this.sortableView.querySelectorAll('.movedown');
// downs.forEach( downs => downs.addEventListener('click',function(e){
- // const _id = e.target.parentNode.dataset.id;
- // this.moveLayer(_id,'down');
+ // const _id = e.target.parentNode.dataset.id;
+ // this.moveLayer(_id,'down');
// }.bind(this)));
// initialize checkbox
// if(this.setting.isSortableView){
- // this.viewModeSwitch('sort');
+ // this.viewModeSwitch('sort');
// }else{
- // this.viewModeSwitch('category');
+ // this.viewModeSwitch('category');
// }
};
-//click on view radio btn which changes the view mode
+// click on view radio btn which changes the view mode
LayersViewer.prototype.__radioClick = function() {
const mode = this.elt.querySelector(
- `input[type=radio][name=${this.viewRadios.name}]:checked`
+ `input[type=radio][name=${this.viewRadios.name}]:checked`,
).value;
this.viewModeSwitch(mode);
- if (mode === "sort") {
+ if (mode === 'sort') {
this.setting.isSortableView = true;
} else {
this.setting.isSortableView = false;
@@ -268,22 +270,22 @@ LayersViewer.prototype.__radioClick = function() {
// switch layers view mode - sortable or categorical
LayersViewer.prototype.viewModeSwitch = function(
- mode = "category" /*category/sort */
+ mode = 'category', /* category/sort */
) {
// display two views
- this.sortableView.style.display = "none";
- this.categoricalView.style.display = "none";
+ this.sortableView.style.display = 'none';
+ this.categoricalView.style.display = 'none';
switch (mode) {
- case "category":
+ case 'category':
// open category view and checked cate radio btn
this.viewRadios.list[0].elt.checked = true;
- this.categoricalView.style.display = "block";
+ this.categoricalView.style.display = 'block';
break;
- case "sort":
+ case 'sort':
// open sortable view and checked sort radio btn
this.viewRadios.list[1].elt.checked = true;
- this.sortableView.style.display = "block";
+ this.sortableView.style.display = 'block';
break;
default:
// statements_def
@@ -293,90 +295,92 @@ LayersViewer.prototype.viewModeSwitch = function(
/* For Categorical View functions START */
LayersViewer.createCategoricalView = function(data) {
- const ul = document.createElement("ul");
- for (let typeId in data) {
- // create root li
- const type_data = data[typeId]; // type_data = {id:typeId,name:typeName,items:[{item:,isShow:}]}
- type_data.elt = LayersViewer.createCategoricalItem.call(
- this,
- type_data,
- "root"
- );
- ul.appendChild(type_data.elt); // create li root
-
- const children = document.createElement("ul");
- // add leaf
- type_data.items.forEach(
- function(item) {
- item.elt = LayersViewer.createCategoricalItem.call(this, item);
- children.appendChild(item.elt); // create li leaf
- }.bind(this)
- );
- //
- ul.appendChild(children);
+ const ul = document.createElement('ul');
+ for (const typeId in data) {
+ if (data.hasOwnProperty(typeId)) {
+ // create root li
+ const type_data = data[typeId]; // type_data = {id:typeId,name:typeName,items:[{item:,isShow:}]}
+ type_data.elt = LayersViewer.createCategoricalItem.call(
+ this,
+ type_data,
+ 'root',
+ );
+ ul.appendChild(type_data.elt); // create li root
+
+ const children = document.createElement('ul');
+ // add leaf
+ type_data.items.forEach(
+ function(item) {
+ item.elt = LayersViewer.createCategoricalItem.call(this, item);
+ children.appendChild(item.elt); // create li leaf
+ }.bind(this),
+ );
+ //
+ ul.appendChild(children);
+ }
}
- return { view: ul };
+ return {view: ul};
};
LayersViewer.createCategoricalItem = function(data, type) {
const item = data.item;
const id = `cate.${item.id}`;
// create li
- const li = document.createElement("li");
+ const li = document.createElement('li');
li.dataset.id = item.id;
// data?
// label
- const label = document.createElement("label");
+ const label = document.createElement('label');
label.htmlFor = id;
// div
- const text = document.createElement("div");
- text.textContent = type == "root" ? titleCase(item.name) : item.name;
+ const text = document.createElement('div');
+ text.textContent = type == 'root' ? titleCase(item.name) : item.name;
label.appendChild(text);
// checkbox
- let chk = document.createElement("input");
- chk.type = "checkbox";
+ const chk = document.createElement('input');
+ chk.type = 'checkbox';
chk.dataset.id = item.id;
- if (type === "root") {
- let ic = document.createElement("div");
- ic.classList.add("material-icons");
- ic.textContent = "keyboard_arrow_down";
- label.style.fontWeight = "bold";
- chk.dataset.type = "root";
- chk.style.display = "none";
+ if (type === 'root') {
+ const ic = document.createElement('div');
+ ic.classList.add('material-icons');
+ ic.textContent = 'keyboard_arrow_down';
+ label.style.fontWeight = 'bold';
+ chk.dataset.type = 'root';
+ chk.style.display = 'none';
li.appendChild(ic);
} else {
chk.id = id;
- chk.dataset.type = "leaf";
+ chk.dataset.type = 'leaf';
chk.checked = data.isShow;
li.title = item.name;
}
- if (item.typeName && item.typeName == "human") {
+ if (item.typeName && item.typeName == 'human') {
// remove and relocation
- const remove_div = document.createElement("div");
- remove_div.classList.add("material-icons");
- remove_div.classList.add("md-24");
- remove_div.textContent = "clear";
- remove_div.title = "Remove";
- const location_div = document.createElement("div");
- location_div.style.display = data.isShow?"block":"none";
+ const remove_div = document.createElement('div');
+ remove_div.classList.add('material-icons');
+ remove_div.classList.add('md-24');
+ remove_div.textContent = 'clear';
+ remove_div.title = 'Remove';
+ const location_div = document.createElement('div');
+ location_div.style.display = data.isShow?'block':'none';
// bind event location_searching
- location_div.classList.add("material-icons");
- location_div.classList.add("md-24");
- location_div.textContent = "room";
- location_div.title = "Location";
+ location_div.classList.add('material-icons');
+ location_div.classList.add('md-24');
+ location_div.textContent = 'room';
+ location_div.title = 'Location';
//
- remove_div.addEventListener("click", () => {
+ remove_div.addEventListener('click', () => {
this.setting.removeCallback.call(this, data);
});
- location_div.addEventListener("click", () => {
+ location_div.addEventListener('click', () => {
this.setting.locationCallback.call(this, data);
});
@@ -388,7 +392,7 @@ LayersViewer.createCategoricalItem = function(data, type) {
li.appendChild(label);
}
- //chk.dataset.name = item.name;
+ // chk.dataset.name = item.name;
li.appendChild(chk);
return li;
@@ -397,8 +401,8 @@ LayersViewer.createCategoricalItem = function(data, type) {
/* For Sortable View functions START */
LayersViewer.createSortableView = function(list) {
- const sortableList = document.createElement("ul");
- for (var i = 0; i < list.length; i++) {
+ const sortableList = document.createElement('ul');
+ for (let i = 0; i < list.length; i++) {
const item = list[i];
const elt = LayersViewer.createSortableItem(item);
item.sortItem = elt;
@@ -406,15 +410,15 @@ LayersViewer.createSortableView = function(list) {
}
// sortable options
- var options = {
- group: "share",
+ const options = {
+ group: 'share',
animation: 100,
- dataIdAttr: "data-id"
+ dataIdAttr: 'data-id',
};
//
const sortable = Sortable.create(sortableList, options);
- return { sortable: sortable, view: sortableList };
+ return {sortable: sortable, view: sortableList};
};
// create sortable item for sortable view
@@ -422,38 +426,38 @@ LayersViewer.createSortableItem = function(item) {
const id = `sort.${item.id}`;
// create li
- const li = document.createElement("li");
+ const li = document.createElement('li');
li.dataset.id = item.id;
// data?
// label
- const label = document.createElement("label");
+ const label = document.createElement('label');
label.htmlFor = id;
// div
- const text = document.createElement("div");
+ const text = document.createElement('div');
text.textContent = item.name;
label.appendChild(text);
// div moveup
- const up_icon = document.createElement("div");
- up_icon.classList.add("material-icons");
- up_icon.classList.add("moveup");
- up_icon.textContent = "arrow_drop_up";
+ const up_icon = document.createElement('div');
+ up_icon.classList.add('material-icons');
+ up_icon.classList.add('moveup');
+ up_icon.textContent = 'arrow_drop_up';
// div movedown
- const down_icon = document.createElement("div");
- down_icon.classList.add("material-icons");
- down_icon.classList.add("movedown");
- down_icon.textContent = "arrow_drop_down";
+ const down_icon = document.createElement('div');
+ down_icon.classList.add('material-icons');
+ down_icon.classList.add('movedown');
+ down_icon.textContent = 'arrow_drop_down';
// checkbox
- let chk = document.createElement("input");
- chk.type = "checkbox";
+ const chk = document.createElement('input');
+ chk.type = 'checkbox';
chk.id = id;
chk.checked = item.isShow;
chk.dataset.id = item.id;
- chk.dataset.type = "leaf";
+ chk.dataset.type = 'leaf';
li.appendChild(label);
li.appendChild(up_icon);
li.appendChild(down_icon);
@@ -464,50 +468,50 @@ LayersViewer.createSortableItem = function(item) {
/* For control area functions START */
LayersViewer.createControlBar = function() {
- const view = document.createElement("div");
- view.classList.add("searchbar");
+ const view = document.createElement('div');
+ view.classList.add('searchbar');
// create view radios name
const _name = randomId();
/* create cate btn START */
const cate_id = randomId();
- const cate_btn = document.createElement("div");
- cate_btn.style.display = "none";
+ const cate_btn = document.createElement('div');
+ cate_btn.style.display = 'none';
// cate radio
- const cate_radio = document.createElement("input");
+ const cate_radio = document.createElement('input');
cate_radio.id = cate_id;
- cate_radio.type = "radio";
+ cate_radio.type = 'radio';
cate_radio.name = _name;
- cate_radio.value = "category";
+ cate_radio.value = 'category';
// cate label
- const cate_label = document.createElement("label");
+ const cate_label = document.createElement('label');
cate_label.htmlFor = cate_id;
- cate_label.classList.add("material-icons");
- cate_label.textContent = "category";
+ cate_label.classList.add('material-icons');
+ cate_label.textContent = 'category';
cate_btn.appendChild(cate_radio);
cate_btn.appendChild(cate_label);
- //add into view
+ // add into view
view.appendChild(cate_btn);
/* create cate btn END */
/* create cate btn START */
const sort_id = randomId();
- const sort_btn = document.createElement("div");
- sort_btn.style.display = "none";
- const sort_radio = document.createElement("input");
+ const sort_btn = document.createElement('div');
+ sort_btn.style.display = 'none';
+ const sort_radio = document.createElement('input');
sort_radio.id = sort_id;
- sort_radio.type = "radio";
+ sort_radio.type = 'radio';
sort_radio.name = _name;
- sort_radio.value = "sort";
+ sort_radio.value = 'sort';
- const sort_label = document.createElement("label");
+ const sort_label = document.createElement('label');
sort_label.htmlFor = sort_id;
- sort_label.classList.add("material-icons");
- sort_label.textContent = "sort";
+ sort_label.classList.add('material-icons');
+ sort_label.textContent = 'sort';
sort_btn.appendChild(sort_radio);
sort_btn.appendChild(sort_label);
@@ -518,26 +522,26 @@ LayersViewer.createControlBar = function() {
/* create search bar START */
// text input
- const search_input = document.createElement("input");
- search_input.type = "text";
- search_input.placeholder = "Search By Name/ID";
+ const search_input = document.createElement('input');
+ search_input.type = 'text';
+ search_input.placeholder = 'Search By Name/ID';
// search btn
- const search_btn = document.createElement("div");
- search_btn.classList.add("material-icons");
- search_btn.textContent = "find_in_page";
+ const search_btn = document.createElement('div');
+ search_btn.classList.add('material-icons');
+ search_btn.textContent = 'find_in_page';
- //add input and btn into ciew
+ // add input and btn into ciew
view.appendChild(search_input);
view.appendChild(search_btn);
/* create search bar END */
/* create check all START */
- const chk_all = document.createElement("input");
- chk_all.style.display = "none";
- chk_all.type = "checkbox";
- chk_all.id = "all";
- chk_all.dataset.type = "all";
+ const chk_all = document.createElement('input');
+ chk_all.style.display = 'none';
+ chk_all.type = 'checkbox';
+ chk_all.id = 'all';
+ chk_all.dataset.type = 'all';
view.appendChild(chk_all);
/* create check all END */
@@ -547,12 +551,12 @@ LayersViewer.createControlBar = function() {
viewRadios.list = [
{
id: cate_id,
- elt: cate_radio // categorical view radio btn
+ elt: cate_radio, // categorical view radio btn
},
{
id: sort_id,
- elt: sort_radio // sortable view radio btn
- }
+ elt: sort_radio, // sortable view radio btn
+ },
];
// return obj for search bar
@@ -566,7 +570,7 @@ LayersViewer.createControlBar = function() {
view: view,
viewRadios: viewRadios, // view switch
searchBar: searchBar, // searchbar
- checkAll: chk_all // check all
+ checkAll: chk_all, // check all
};
};
@@ -594,7 +598,7 @@ LayersViewer.prototype.setData = function(data) {
* update the UI according to the data model
*/
LayersViewer.prototype.update = function() {
- //this.setting.data = data;
+ // this.setting.data = data;
this.__covertData();
this.__refreshUI();
};
@@ -606,37 +610,37 @@ LayersViewer.prototype.update = function() {
*/
LayersViewer.prototype.__search = function(e) {
// show all li with leaf class
- let list = this.setting.data;
- list.forEach(data => {
- data.elt.style.display = "flex";
+ const list = this.setting.data;
+ list.forEach((data) => {
+ data.elt.style.display = 'flex';
// item.sortItem.style.display='flex';
});
const pattern = e.target.value;
const items = this.setting.data;
- const regex = new RegExp(pattern, "gi");
+ const regex = new RegExp(pattern, 'gi');
- list.forEach(data => {
+ list.forEach((data) => {
if (!data.item.name.match(regex)) {
- data.elt.style.display = "none";
+ data.elt.style.display = 'none';
// item.sortItem.style.display = 'none';
}
});
};
/*
- convert og/raw data to categorical model/data
+ convert og/raw data to categorical model/data
*/
LayersViewer.prototype.__covertData = function() {
if (!this.setting.data) {
console.warn(`${this.className}: No Raw Data`);
- //return;
+ // return;
}
this.setting.categoricalData = this.setting.data.reduce(function(model, d) {
const item = d.item;
if (!model[item.typeId]) {
model[item.typeId] = {
- item: { id: item.typeId, name: item.typeName },
- items: []
+ item: {id: item.typeId, name: item.typeName},
+ items: [],
};
}
model[item.typeId].items.push(d);
@@ -647,12 +651,12 @@ LayersViewer.prototype.__covertData = function() {
// expand or collapse layer list
LayersViewer.prototype.__switch = function(e) {
const nextElt = e.target.parentNode.nextElementSibling;
- if (nextElt.style.display == "none") {
+ if (nextElt.style.display == 'none') {
nextElt.style.display = null;
- e.target.innerHTML = "keyboard_arrow_down";
+ e.target.innerHTML = 'keyboard_arrow_down';
} else {
- nextElt.style.display = "none";
- e.target.innerHTML = "keyboard_arrow_right";
+ nextElt.style.display = 'none';
+ e.target.innerHTML = 'keyboard_arrow_right';
}
};
@@ -665,37 +669,39 @@ LayersViewer.prototype.__change = function(e) {
const checked = e.target.checked;
const list = this.setting.data;
switch (type) {
- case "all":
- this.setting.data.forEach(d => {
+ case 'all':
+ this.setting.data.forEach((d) => {
d.isShow = checked;
d.elt.lastChild.checked = checked;
// item.sortItem.lastChild.checked = checked;
});
- for (let key in this.setting.categoricalData) {
- this.setting.categoricalData[key].elt.lastChild.checked = checked;
+ for (const key in this.setting.categoricalData) {
+ if (this.setting.categoricalData.hasOwnProperty(key)) {
+ this.setting.categoricalData[key].elt.lastChild.checked = checked;
+ }
}
this.setting.callback.call(null, this.setting.data);
break;
- case "root":
- this.setting.categoricalData[id].items.forEach(d => {
+ case 'root':
+ this.setting.categoricalData[id].items.forEach((d) => {
d.isShow = checked;
d.elt.lastChild.checked = checked;
// item.sortItem.lastChild.checked = checked;
});
this.setting.callback.call(null, this.setting.categoricalData[id].items);
break;
- case "leaf":
- const data = this.setting.data.find(d => d.item.id == id);
+ case 'leaf':
+ const data = this.setting.data.find((d) => d.item.id == id);
if (!data) return;
data.isShow = checked;
data.elt.lastChild.checked = checked;
- const location = e.target.parentElement.querySelector("div");
+ const location = e.target.parentElement.querySelector('div');
if (checked) {
- location.style.display = "block";
+ location.style.display = 'block';
} else {
- location.style.display = "none";
+ location.style.display = 'none';
}
this.setting.callback.call(null, [data]);
diff --git a/components/loading/loading.js b/components/loading/loading.js
index d18d6d757..ed42a159d 100644
--- a/components/loading/loading.js
+++ b/components/loading/loading.js
@@ -1,13 +1,13 @@
/**
* [Loading description]
- * @constructor
+ * @constructor
*/
-function Loading(){
+function Loading() {
}
/**
* @property {Element} the only instance of the loading page
- *
+ *
*/
Loading.instance = null;
@@ -15,46 +15,43 @@ Loading.instance = null;
* @property {Element} the text element of Loading page.
*/
Loading.text = null;
-Loading.open = function(parentNode ,text = 'Loading...',zIndex=999){
- if(!Loading.instance) Loading.instance = Loading.createInstance();
- if(parentNode !== Loading.instance.parentNode) Loading.close();
+Loading.open = function(parentNode, text = 'Loading...', zIndex=999) {
+ if (!Loading.instance) Loading.instance = Loading.createInstance();
+ if (parentNode !== Loading.instance.parentNode) Loading.close();
Loading.instance.style.zIndex = zIndex;
Loading.text.textContent = text;
Loading.pp = parentNode.style.position;
parentNode.style.position = 'absolute';
parentNode.appendChild(Loading.instance);
-}
+};
/**
* factory method to create a instance of Loading class/page
* @return {Element} the container of Loading page/element
*/
-Loading.createInstance = function(){
-
- const cover = document.createElement('div');
+Loading.createInstance = function() {
+ const cover = document.createElement('div');
cover.classList.add('cover');
-
+
const block = document.createElement('div');
block.classList.add('block');
const text = document.createElement('span');
-
+
Loading.text = text;
const bar = document.createElement('div');
bar.classList.add('bar');
-
+
block.appendChild(text);
block.appendChild(bar);
cover.appendChild(block);
-
+
return cover;
-
-}
+};
/**
* Close the loading hint page
*/
-Loading.close = function(){
- if(!Loading.instance || !Loading.instance.parentNode)return;
- Loading.instance.parentNode.style.position = Loading.pp;
- Loading.instance.parentNode.removeChild(Loading.instance);
-
-}
\ No newline at end of file
+Loading.close = function() {
+ if (!Loading.instance || !Loading.instance.parentNode) return;
+ Loading.instance.parentNode.style.position = Loading.pp;
+ Loading.instance.parentNode.removeChild(Loading.instance);
+};
diff --git a/components/messagequeue/messagequeue.js b/components/messagequeue/messagequeue.js
index 4f5d7ac0e..2246bcd11 100644
--- a/components/messagequeue/messagequeue.js
+++ b/components/messagequeue/messagequeue.js
@@ -11,143 +11,142 @@
* @constructor
* @param {Object} options
* All required and optional settings for instantiating a new instance of a MessageQueue.
- *
+ *
* @param {String} [options.position=top-left]
* The position of MessageQueue instance shows up. 'top-left', 'top-right', 'bottom-left', 'bottom-right'.
*/
-class MessageQueue{
- constructor(options){
- this.className = 'MessageQueue';
+class MessageQueue {
+ constructor(options) {
+ this.className = 'MessageQueue';
- this.setting = {
- position:'top-left' // top-left top-right bottom-left bottom-right
- }
- // user setting
- if(options&&options.position) this.setting.position = options.position;
+ this.setting = {
+ position: 'top-left', // top-left top-right bottom-left bottom-right
+ };
+ // user setting
+ if (options&&options.position) this.setting.position = options.position;
- this.elt = document.getElementById(this.setting.id);
- if(!this.elt && this.setting.element){
- this.elt = this.setting.element;
- }
+ this.elt = document.getElementById(this.setting.id);
+ if (!this.elt && this.setting.element) {
+ this.elt = this.setting.element;
+ }
- //
- if(!this.elt){
- // create main
- this.elt = document.createElement('div');
- document.body.appendChild(this.elt);
- }
- this.elt.classList.add('bullet-container');
- switch (this.setting.position) {
- case 'top-left':
- // top-left
- this.elt.style.top = 0;
- this.elt.style.left = 0;
+ //
+ if (!this.elt) {
+ // create main
+ this.elt = document.createElement('div');
+ document.body.appendChild(this.elt);
+ }
+ this.elt.classList.add('bullet-container');
+ switch (this.setting.position) {
+ case 'top-left':
+ // top-left
+ this.elt.style.top = 0;
+ this.elt.style.left = 0;
- break;
- case 'top-right':
- // top-right
-
- this.elt.style.top = 0;
- this.elt.style.right = 0;
- break;
- case 'bottom-left':
- // bottom-left
-
- this.elt.style.bottom = 0;
- this.elt.style.left = 0;
- break;
- case 'bottom-right':
- // bottom-right
-
- this.elt.style.bottom = 0;
- this.elt.style.right = 0;
- break;
- default:
- // statements_def
- break;
- }
+ break;
+ case 'top-right':
+ // top-right
- }
+ this.elt.style.top = 0;
+ this.elt.style.right = 0;
+ break;
+ case 'bottom-left':
+ // bottom-left
- /**
- * add a error message into the queue.
- * @param {String} text
- * the content of the message
- * @param {Number} [time=5000]
- * the time, in milliseconds (thousandths of a second), the timer should delay to destroy this message.
- */
- addError(text, time = 3000){
- this.__add(text,'error',time);
- }
- /**
- * add a warning message into the queue.
- * @param {String} text
- * the content of the message
- * @param {Number} [time=3000]
- * the time, in milliseconds (thousandths of a second), the timer should delay to destroy this message.
- */
- addWarning(text, time = 1000){
- this.__add(text,'warning',time);
- }
+ this.elt.style.bottom = 0;
+ this.elt.style.left = 0;
+ break;
+ case 'bottom-right':
+ // bottom-right
- /**
- * add a plain message into the queue.
- * @param {String} text
- * the content of the message
- * @param {Number} [time=1000]
- * the time, in milliseconds (thousandths of a second), the timer should delay to destroy this message.
- */
- add(text, time = 200){
- this.__add(text,'info',time);
- }
- /**
- * @private
- * add the different type of message to the message queue.
- * @param {String} text
- * the content of the message
- * @param {String} [type=info]
- * the type of the message. 'info' - information, 'warning' - warning message, 'error' - error message.
- * @param {Number} [time=1000]
- * the time, in milliseconds (thousandths of a second), the timer should delay to destroy this message.
- */
- __add(text, type='info', time = 1000){
- const div = MessageQueue.createBullet(text, type);
- this.setting.position.includes('bottom')?this.elt.appendChild(div):this.elt.insertBefore(div, this.elt.firstChild);
- if(this.setting.position.includes('right')) div.classList.add('right');
-
- div.addEventListener('webkitTransitionEnd', this.__destroy.bind(div));
- div.addEventListener('transitionend', this.__destroy.bind(div));
+ this.elt.style.bottom = 0;
+ this.elt.style.right = 0;
+ break;
+ default:
+ // statements_def
+ break;
+ }
+ }
- setTimeout(function(){
- div.classList.add('hide');
- },time);
- }
- /**
- * @private
- * remove the message from the queue
- * @param {Event} e
- * Event
- */
- __destroy(e){
- if (e.propertyName == 'opacity') {
- this.parentNode.removeChild(this);
- }
- }
+ /**
+ * add a error message into the queue.
+ * @param {String} text
+ * the content of the message
+ * @param {Number} [time=5000]
+ * the time, in milliseconds (thousandths of a second), the timer should delay to destroy this message.
+ */
+ addError(text, time = 3000) {
+ this.__add(text, 'error', time);
+ }
+ /**
+ * add a warning message into the queue.
+ * @param {String} text
+ * the content of the message
+ * @param {Number} [time=3000]
+ * the time, in milliseconds (thousandths of a second), the timer should delay to destroy this message.
+ */
+ addWarning(text, time = 1000) {
+ this.__add(text, 'warning', time);
+ }
- /**
- * a static helper that create the message bullet
- * @param {String} text
- * the content of the message
- * @param {Strinf} type
- * the type of the message. 'info' - information, 'warning' - warning message, 'error' - error message.
- * @return {HTMLElement} the div element that represents a message
- */
- static createBullet(text, type){
- const div = document.createElement('div');
- div.classList.add('bullet');
- div.classList.add(type);
- div.textContent = text;
- return div;
- }
+ /**
+ * add a plain message into the queue.
+ * @param {String} text
+ * the content of the message
+ * @param {Number} [time=1000]
+ * the time, in milliseconds (thousandths of a second), the timer should delay to destroy this message.
+ */
+ add(text, time = 200) {
+ this.__add(text, 'info', time);
+ }
+ /**
+ * @private
+ * add the different type of message to the message queue.
+ * @param {String} text
+ * the content of the message
+ * @param {String} [type=info]
+ * the type of the message. 'info' - information, 'warning' - warning message, 'error' - error message.
+ * @param {Number} [time=1000]
+ * the time, in milliseconds (thousandths of a second), the timer should delay to destroy this message.
+ */
+ __add(text, type='info', time = 1000) {
+ const div = MessageQueue.createBullet(text, type);
+ this.setting.position.includes('bottom')?
+ this.elt.appendChild(div):this.elt.insertBefore(div, this.elt.firstChild);
+ if (this.setting.position.includes('right')) div.classList.add('right');
-}
\ No newline at end of file
+ div.addEventListener('webkitTransitionEnd', this.__destroy.bind(div));
+ div.addEventListener('transitionend', this.__destroy.bind(div));
+
+ setTimeout(function() {
+ div.classList.add('hide');
+ }, time);
+ }
+ /**
+ * @private
+ * remove the message from the queue
+ * @param {Event} e
+ * Event
+ */
+ __destroy(e) {
+ if (e.propertyName == 'opacity') {
+ this.parentNode.removeChild(this);
+ }
+ }
+
+ /**
+ * a static helper that create the message bullet
+ * @param {String} text
+ * the content of the message
+ * @param {Strinf} type
+ * the type of the message. 'info' - information, 'warning' - warning message, 'error' - error message.
+ * @return {HTMLElement} the div element that represents a message
+ */
+ static createBullet(text, type) {
+ const div = document.createElement('div');
+ div.classList.add('bullet');
+ div.classList.add(type);
+ div.textContent = text;
+ return div;
+ }
+}
diff --git a/components/modalbox/modalbox.js b/components/modalbox/modalbox.js
index ef6d997ec..9d7448fdd 100644
--- a/components/modalbox/modalbox.js
+++ b/components/modalbox/modalbox.js
@@ -16,87 +16,87 @@
//
//
-function ModalBox(options){
- this.name = 'ModalBox';
- // DOM elts
- /**
+function ModalBox(options) {
+ this.name = 'ModalBox';
+ // DOM elts
+ /**
* @property {Element} elt The element to append the toolbar's container element to.
*/
- this.elt;
+ this.elt;
- //
- this.setting = {
- hasHeader:true,
- hasFooder:true,
+ //
+ this.setting = {
+ hasHeader: true,
+ hasFooder: true,
- };
- extend(this.setting, options);
+ };
+ extend(this.setting, options);
- this.elt = document.getElementById(this.setting.id);
- if(!this.elt){
- console.error(`${this.name}:No Main Container...`);
- return;
- }
+ this.elt = document.getElementById(this.setting.id);
+ if (!this.elt) {
+ console.error(`${this.name}:No Main Container...`);
+ return;
+ }
- this.__create();
- this.__close.addEventListener('click',this.close.bind(this));
- window.onclick = function(event) {
- if (event.target == this.elt)this.close();
- }.bind(this);
+ this.__create();
+ this.__close.addEventListener('click', this.close.bind(this));
+ window.onclick = function(event) {
+ if (event.target == this.elt) this.close();
+ }.bind(this);
}
-ModalBox.prototype.__create = function(){
- function createHeater(text){
- const header = document.createElement('div');
- header.classList.add('modalbox-header');
- const title = document.createElement('div');
- title.textContent = text;
- const close = document.createElement('span');
- close.textContent = 'x';
- close.classList.add('close');
- header.appendChild(close);
- header.appendChild(title);
+ModalBox.prototype.__create = function() {
+ function createHeater(text) {
+ const header = document.createElement('div');
+ header.classList.add('modalbox-header');
+ const title = document.createElement('div');
+ title.textContent = text;
+ const close = document.createElement('span');
+ close.textContent = 'x';
+ close.classList.add('close');
+ header.appendChild(close);
+ header.appendChild(title);
- return header;
+ return header;
+ }
+ function createFooter(text) {
+ const footer = document.createElement('div');
+ footer.classList.add('modalbox-footer');
+ const title = document.createElement('h4');
+ title.textContent = text;
+ footer.appendChild(title);
+ return footer;
+ }
+ empty(this.elt);
+ this.elt.classList.add('modalbox');
+ const content = document.createElement('div');
+ content.classList.add('modalbox-content');
+ if (this.setting.hasHeader) content.appendChild(createHeater(this.setting.headerText));
+ this.body = document.createElement('div');
+ this.body.classList.add('modalbox-body');
+ if (this.setting.provideContent) {
+ this.body.innerHTML = this.setting.content;
+ }
+ content.appendChild(this.body);
+ if (this.setting.hasFooter) content.appendChild(createFooter(this.setting.footerText));
- }
- function createFooter(text){
- const footer = document.createElement('div');
- footer.classList.add('modalbox-footer');
- const title = document.createElement('h4');
- title.textContent = text;
- footer.appendChild(title);
- return footer;
- }
- empty(this.elt);
- this.elt.classList.add('modalbox');
- const content = document.createElement('div');
- content.classList.add('modalbox-content');
- if(this.setting.hasHeader) content.appendChild(createHeater(this.setting.headerText));
- this.body = document.createElement('div');
- this.body.classList.add('modalbox-body');
- if (this.setting.provideContent) {this.body.innerHTML = this.setting.content}
- content.appendChild(this.body);
- if(this.setting.hasFooter) content.appendChild(createFooter(this.setting.footerText));
+ this.elt.appendChild(content);
+ this.__close = this.elt.querySelector('.modalbox-header .close');
+};
+ModalBox.prototype.open = function() {
+ this.elt.style.display = 'block';
+};
+ModalBox.prototype.close = function() {
+ this.elt.style.display = 'none';
+};
+ModalBox.prototype.setBody=function() {
- this.elt.appendChild(content);
- this.__close = this.elt.querySelector('.modalbox-header .close');
+};
+ModalBox.prototype.appendBody=function() {
-}
-ModalBox.prototype.open = function(){
- this.elt.style.display = 'block';
-}
-ModalBox.prototype.close = function(){
- this.elt.style.display = 'none';
-}
-ModalBox.prototype.setBody=function(){
-
-}
-ModalBox.prototype.appendBody=function(){
-
-}
-ModalBox.prototype.setHeaderText = function(text){
- this.elt.querySelector('.modal-footer');
-}
-ModalBox.prototype.setFooterText = function(text){
+};
+ModalBox.prototype.setHeaderText = function(text) {
+ this.elt.querySelector('.modal-footer');
+};
+ModalBox.prototype.setFooterText = function(text) {
-}
\ No newline at end of file
+};
diff --git a/components/multselector/multselector.js b/components/multselector/multselector.js
index edfbf42d9..bdaff9b6b 100644
--- a/components/multselector/multselector.js
+++ b/components/multselector/multselector.js
@@ -24,7 +24,8 @@
* @param {Element} [options.element]
* The container as a html element.
* @param {Array} [options.data]
- * The data of selector's options. The form of each option should be an array -> [key - identity,value - text on option].
+ * The data of selector's options.
+ * The form of each option should be an array -> [key - identity,value - text on option].
* @param {String} [options.title]
* The title of mult-selector
* @param {Boolean} [options.hasControl='true']
@@ -35,45 +36,45 @@
* The text of action btns
*
*/
-function MultSelector(options){
- this.className = 'MultSelector';
- this.elt;
- this.selectors;
- this.btns;
- this.setting = {
- //title:'a head title',
- hasControl:true,
- cancelText:'Cancel',
- actionText:'Action'
- }
-
- extend(this.setting, options);
-
- this.elt = document.getElementById(this.setting.id);
- if(!this.elt && options.element){
- this.elt = options.element;
- }
-
- if(!this.elt){
- // create main
- this.elt = document.createElement('div');
- }
-
- // create ui element
- this.__create();
- // prepare data
- if(this.setting.data) this.setData(this.setting.data);
-
- // add Event
- this.btns[0].addEventListener('click',this.__selectAll.bind(this));
- this.btns[1].addEventListener('click',this.__select.bind(this));
- this.btns[2].addEventListener('click',this.__remove.bind(this));
- this.btns[3].addEventListener('click',this.__removeAll.bind(this));
-
- if(this.setting.hasControl && this.cancel && this.action) {
- this.cancel.addEventListener('click', this.__cancel.bind(this))
- this.action.addEventListener('click', this.__action.bind(this))
- }
+function MultSelector(options) {
+ this.className = 'MultSelector';
+ this.elt;
+ this.selectors;
+ this.btns;
+ this.setting = {
+ // title:'a head title',
+ hasControl: true,
+ cancelText: 'Cancel',
+ actionText: 'Action',
+ };
+
+ extend(this.setting, options);
+
+ this.elt = document.getElementById(this.setting.id);
+ if (!this.elt && options.element) {
+ this.elt = options.element;
+ }
+
+ if (!this.elt) {
+ // create main
+ this.elt = document.createElement('div');
+ }
+
+ // create ui element
+ this.__create();
+ // prepare data
+ if (this.setting.data) this.setData(this.setting.data);
+
+ // add Event
+ this.btns[0].addEventListener('click', this.__selectAll.bind(this));
+ this.btns[1].addEventListener('click', this.__select.bind(this));
+ this.btns[2].addEventListener('click', this.__remove.bind(this));
+ this.btns[3].addEventListener('click', this.__removeAll.bind(this));
+
+ if (this.setting.hasControl && this.cancel && this.action) {
+ this.cancel.addEventListener('click', this.__cancel.bind(this));
+ this.action.addEventListener('click', this.__action.bind(this));
+ }
}
@@ -81,127 +82,126 @@ function MultSelector(options){
* @private
* __create all HTML Elements based on setting/options.
*/
-MultSelector.prototype.__create = function(){
- const elt = this.elt;
- elt.classList.add('multi-select-wrapper');
- // create title
-
- if(this.setting.title){
- this.head = document.createElement('div');
- this.head.classList.add('header');
- this.head.textContent = this.setting.title;
- elt.appendChild(this.head);
- }
-
- // create container
- const container = document.createElement('div');
- container.classList.add('multi-select-container');
- elt.appendChild(container);
-
- // create main select area
- const main = document.createElement('div');
- main.classList.add('main');
- container.appendChild(main);
-
- // create main selector
- const selMain = document.createElement('select');
- selMain.multiple = true;
- main.appendChild(selMain);
-
- // create control
- const ctrl = document.createElement('div');
- ctrl.classList.add('ctrl');
- container.appendChild(ctrl);
-
- // create control btns
- const selectAll = document.createElement('button');
- selectAll.classList.add('material-icons');
- selectAll.textContent = 'last_page';
- ctrl.appendChild(selectAll);
-
- const select = document.createElement('button');
- select.classList.add('material-icons');
- select.textContent = 'chevron_right';
- ctrl.appendChild(select);
-
- const remove = document.createElement('button');
- remove.classList.add('material-icons');
- remove.textContent = 'chevron_left';
- ctrl.appendChild(remove);
-
- const removeAll = document.createElement('button');
- removeAll.classList.add('material-icons');
- removeAll.textContent = 'first_page';
- ctrl.appendChild(removeAll);
-
- // create selected area
- const selected = document.createElement('div');
- selected.classList.add('selected');
- container.appendChild(selected);
-
- // create selected selector
- const selSelected = document.createElement('select');
- selSelected.multiple = true;
- selected.appendChild(selSelected);
-
- this.selectors = [selMain,selSelected];
- this.btns = [selectAll,select,remove,removeAll];
-
- // create ctrl btns
- if(this.setting.hasControl){
- this.footer = document.createElement('div');
- this.footer.classList.add('footer');
- this.cancel = document.createElement('button');
- this.cancel.textContent = this.setting.cancelText;
- this.action = document.createElement('button');
- this.action.textContent = this.setting.actionText ;
- this.footer.appendChild(this.cancel);
- this.footer.appendChild(this.action);
- elt.appendChild(this.footer)
- }
- // there are two btns [cancel] and [save]
-
-}
-
+MultSelector.prototype.__create = function() {
+ const elt = this.elt;
+ elt.classList.add('multi-select-wrapper');
+ // create title
+
+ if (this.setting.title) {
+ this.head = document.createElement('div');
+ this.head.classList.add('header');
+ this.head.textContent = this.setting.title;
+ elt.appendChild(this.head);
+ }
+
+ // create container
+ const container = document.createElement('div');
+ container.classList.add('multi-select-container');
+ elt.appendChild(container);
+
+ // create main select area
+ const main = document.createElement('div');
+ main.classList.add('main');
+ container.appendChild(main);
+
+ // create main selector
+ const selMain = document.createElement('select');
+ selMain.multiple = true;
+ main.appendChild(selMain);
+
+ // create control
+ const ctrl = document.createElement('div');
+ ctrl.classList.add('ctrl');
+ container.appendChild(ctrl);
+
+ // create control btns
+ const selectAll = document.createElement('button');
+ selectAll.classList.add('material-icons');
+ selectAll.textContent = 'last_page';
+ ctrl.appendChild(selectAll);
+
+ const select = document.createElement('button');
+ select.classList.add('material-icons');
+ select.textContent = 'chevron_right';
+ ctrl.appendChild(select);
+
+ const remove = document.createElement('button');
+ remove.classList.add('material-icons');
+ remove.textContent = 'chevron_left';
+ ctrl.appendChild(remove);
+
+ const removeAll = document.createElement('button');
+ removeAll.classList.add('material-icons');
+ removeAll.textContent = 'first_page';
+ ctrl.appendChild(removeAll);
+
+ // create selected area
+ const selected = document.createElement('div');
+ selected.classList.add('selected');
+ container.appendChild(selected);
+
+ // create selected selector
+ const selSelected = document.createElement('select');
+ selSelected.multiple = true;
+ selected.appendChild(selSelected);
+
+ this.selectors = [selMain, selSelected];
+ this.btns = [selectAll, select, remove, removeAll];
+
+ // create ctrl btns
+ if (this.setting.hasControl) {
+ this.footer = document.createElement('div');
+ this.footer.classList.add('footer');
+ this.cancel = document.createElement('button');
+ this.cancel.textContent = this.setting.cancelText;
+ this.action = document.createElement('button');
+ this.action.textContent = this.setting.actionText;
+ this.footer.appendChild(this.cancel);
+ this.footer.appendChild(this.action);
+ elt.appendChild(this.footer);
+ }
+ // there are two btns [cancel] and [save]
+};
/**
* setData
* @param {Array} data
- * The data of selector's options. The form of each option should be an array -> [key - identity,value - text on option].
+ * The data of selector's options.
+ * The form of each option should be an array -> [key - identity,value - text on option].
*/
-MultSelector.prototype.setData = function(data){
-
- if(!Array.isArray(data)){
- console.error(`${this.className}:setData - data is not an array`);
- return;
- }
- data = data.map(item =>{
- if(Array.isArray(item)) return item;
- return [item,item];
- });
- this.setting.data = data;
- // clear all options
- this.selectors[0].innerHTML = '';
- this.selectors[1].innerHTML = '';
- //
- MultSelector.__addOptions(this.selectors[0],this.setting.data);
+MultSelector.prototype.setData = function(data) {
+ if (!Array.isArray(data)) {
+ console.error(`${this.className}:setData - data is not an array`);
+ return;
+ }
+ data = data.map((item) =>{
+ if (Array.isArray(item)) return item;
+ return [item, item];
+ });
+ this.setting.data = data;
+ // clear all options
+ this.selectors[0].innerHTML = '';
+ this.selectors[1].innerHTML = '';
+ //
+ MultSelector.__addOptions(this.selectors[0], this.setting.data);
};
/**
* __addOptions add options to target selector
* @param {Select} target
* a selector that is a html select element
* @param {Array} data
- * The data of selector's options. The form of each option should be an array -> [key - identity,value - text on option].
+ * The data of selector's options.
+ * The form of each option should be an array -> [key - identity,value - text on option].
*/
-MultSelector.__addOptions = function(target, data){
- data.forEach(item => {
- var opt = document.createElement('option');
- opt.value = item[0];
- opt.textContent = item[1];
- target.appendChild(opt);
- });
-}
+MultSelector.__addOptions = function(target, data) {
+ data.forEach((item) => {
+ const opt = document.createElement('option');
+ opt.value = item[0];
+ opt.textContent = item[1];
+ target.appendChild(opt);
+ });
+};
/**
* @private
@@ -209,12 +209,12 @@ MultSelector.__addOptions = function(target, data){
* @param {Event} e
* Event
*/
-MultSelector.prototype.__selectAll = function(e){
- this.selectors[1].innerHTML = '';
- this.selectors[1].innerHTML = this.selectors[0].innerHTML;
+MultSelector.prototype.__selectAll = function(e) {
+ this.selectors[1].innerHTML = '';
+ this.selectors[1].innerHTML = this.selectors[0].innerHTML;
- // event fired
- this.raiseEvent('select-all', {});
+ // event fired
+ this.raiseEvent('select-all', {});
};
/**
* @private
@@ -222,9 +222,9 @@ MultSelector.prototype.__selectAll = function(e){
* @param {Event} e
* Event
*/
-MultSelector.prototype.__cancel = function(e){
- // event fired
- this.raiseEvent('cancel', {});
+MultSelector.prototype.__cancel = function(e) {
+ // event fired
+ this.raiseEvent('cancel', {});
};
/**
* @private
@@ -232,9 +232,9 @@ MultSelector.prototype.__cancel = function(e){
* @param {Event} e
* Event
*/
-MultSelector.prototype.__action = function(e){
- // event fired
- this.raiseEvent('action', {data:this.getSelected()});
+MultSelector.prototype.__action = function(e) {
+ // event fired
+ this.raiseEvent('action', {data: this.getSelected()});
};
/**
* @private
@@ -242,22 +242,22 @@ MultSelector.prototype.__action = function(e){
* @param {Event} e
* Event
*/
-MultSelector.prototype.__select = function(e){
- const selected = this.selectors[0].querySelectorAll('option:checked');
- const data = [];
- [...selected].forEach( function(opt) {
- const num = this.selectors[1].querySelectorAll(`option[value='${opt.value}']`).length;
- if(num === 0) {
- const new_opt = opt.cloneNode(true);
- new_opt.textContent = opt.textContent;
- this.selectors[1].appendChild(new_opt);
- data.push([opt.value,opt.textContent]);
- }
- },this);
-
- // event fired
- this.raiseEvent('select', {data:data});
-}
+MultSelector.prototype.__select = function(e) {
+ const selected = this.selectors[0].querySelectorAll('option:checked');
+ const data = [];
+ [...selected].forEach( function(opt) {
+ const num = this.selectors[1].querySelectorAll(`option[value='${opt.value}']`).length;
+ if (num === 0) {
+ const new_opt = opt.cloneNode(true);
+ new_opt.textContent = opt.textContent;
+ this.selectors[1].appendChild(new_opt);
+ data.push([opt.value, opt.textContent]);
+ }
+ }, this);
+
+ // event fired
+ this.raiseEvent('select', {data: data});
+};
/**
* @private
@@ -265,12 +265,12 @@ MultSelector.prototype.__select = function(e){
* @param {Event} e
* Event
*/
-MultSelector.prototype.__removeAll = function(e){
- this.selectors[1].innerHTML = '';
+MultSelector.prototype.__removeAll = function(e) {
+ this.selectors[1].innerHTML = '';
- // event fired
- this.raiseEvent('remove-all', {});
-}
+ // event fired
+ this.raiseEvent('remove-all', {});
+};
/**
* @private
@@ -278,26 +278,26 @@ MultSelector.prototype.__removeAll = function(e){
* @param {Event} e
* Event
*/
-MultSelector.prototype.__remove = function(e){
- const selected = this.selectors[1].querySelectorAll('option:checked');
- const data = [];
- [...selected].forEach( function(opt) {
- opt.parentNode.removeChild(opt);
- data.push([opt.value,opt.textContent]);
- });
-
- // event fired
- this.raiseEvent('remove', {data:data});
-}
+MultSelector.prototype.__remove = function(e) {
+ const selected = this.selectors[1].querySelectorAll('option:checked');
+ const data = [];
+ [...selected].forEach( function(opt) {
+ opt.parentNode.removeChild(opt);
+ data.push([opt.value, opt.textContent]);
+ });
+
+ // event fired
+ this.raiseEvent('remove', {data: data});
+};
/**
* getSelected get all selected data
* @return {Array} the data form same as [[key,value]...]
*/
-MultSelector.prototype.getSelected = function(){
- const selected = this.selectors[1].querySelectorAll('option');
- return Array.from(selected).map(opt=>[opt.value,opt.textContent]);
-}
+MultSelector.prototype.getSelected = function() {
+ const selected = this.selectors[1].querySelectorAll('option');
+ return Array.from(selected).map((opt)=>[opt.value, opt.textContent]);
+};
// MultSelector inherit from EventHandle in which the MultSelector is able to add Events based on Behaviors.
diff --git a/components/operationpanel/operationpanel.js b/components/operationpanel/operationpanel.js
index 6c86ad4d4..f3f427ab2 100644
--- a/components/operationpanel/operationpanel.js
+++ b/components/operationpanel/operationpanel.js
@@ -11,8 +11,8 @@
* A operation panel that reads the single or multiple JSON schema and generates the data form and form control.
*
* Dependency:
- * lib/pureform/pure-form.js
- * lib/pureform/pure-form.css
+ * lib/pureform/pure-form.js
+ * lib/pureform/pure-form.css
*
* @param {Object} options
* All required and optional settings for instantiating a new instance of a operation panel.
@@ -33,211 +33,212 @@
* @param {Function} [options.action.callback]
* The callback function of the action btn.
*/
-function OperationPanel(options){
- this.name = 'OperationPanel';
- // DOM elts
- /**
+function OperationPanel(options) {
+ this.name = 'OperationPanel';
+ // DOM elts
+ /**
* @property {Element} elt The element to append the toolbar's container element to.
*/
- this.elt;
- // default setting
- this.setting = {
- zIndex:600,
- title:'',
- //formSchemas
- // list pairs
- // btn -> event
- // may be it can be extension in future...
- // formSchemas
- action:{
- text:'Submit',
- title:'submit form'
-
- }
- }
-
- /**
- * @property {Element} _form_ The instance of pure-form, the core of Operation Panel, generates the data form on UI
- */
- this._form_;
-
- /**
- * @property {Element} _head_ The Head part of UI, includes head title and options for multiple data form.
- */
- this._head_;
-
- /**
- * @property {Element} _select_ The select controls to switch the multiple data form.
- */
- this._select_;
-
- /**
- * @property {Element} _ctrl_ the UI part that controls the form actions - reset/clean data form or submit data form.
- */
- this._ctrl_;
-
- /**
- * @property {Element} _reset_ The reset btn for data form.
- */
- this._reset_;
- /**
- * @property {Element} _action_ The action btn for data form.
- */
- this._action_;
-
-
- // setting options
- extend(this.setting, options);
-
-
-
-
- this.elt = document.getElementById(this.setting.id);
- if(!this.elt && this.setting.element){
- this.elt = this.setting.element;
- }
-
- if(!this.elt){
- // create main
- this.elt = document.createElement('div');
-
- }
-
- // check form schema
- if(!this.setting.formSchemas || this.setting.formSchemas.length == 0){
- //console.error(`${this.name}:No Form Schema ...`);
- this.elt.textContent = `${this.name}:No Form Schema ...`;
- return;
- }
- if(!this.setting.action || !this.setting.action.callback){
- //console.error(`${this.name}:No Action ...`);
- this.elt.textContent = `${this.name}:No Action ...`;
- return;
- }
- this.elt.style.zIndex = this.setting.zIndex;
-
-
- this.__refresh();
+ this.elt;
+ // default setting
+ this.setting = {
+ zIndex: 600,
+ title: '',
+ // formSchemas
+ // list pairs
+ // btn -> event
+ // may be it can be extension in future...
+ // formSchemas
+ action: {
+ text: 'Submit',
+ title: 'submit form',
+
+ },
+ };
+
+ /**
+ * @property {Element} _form_ The instance of pure-form, the core of Operation Panel, generates the data form on UI
+ */
+ this._form_;
+
+ /**
+ * @property {Element} _head_ The Head part of UI, includes head title and options for multiple data form.
+ */
+ this._head_;
+
+ /**
+ * @property {Element} _select_ The select controls to switch the multiple data form.
+ */
+ this._select_;
+
+ /**
+ * @property {Element} _ctrl_ the UI part that controls the form actions
+ * reset/clean data form or submit data form.
+ */
+ this._ctrl_;
+
+ /**
+ * @property {Element} _reset_ The reset btn for data form.
+ */
+ this._reset_;
+ /**
+ * @property {Element} _action_ The action btn for data form.
+ */
+ this._action_;
+
+
+ // setting options
+ extend(this.setting, options);
+
+
+ this.elt = document.getElementById(this.setting.id);
+ if (!this.elt && this.setting.element) {
+ this.elt = this.setting.element;
+ }
+
+ if (!this.elt) {
+ // create main
+ this.elt = document.createElement('div');
+ }
+
+ // check form schema
+ if (!this.setting.formSchemas || this.setting.formSchemas.length == 0) {
+ // console.error(`${this.name}:No Form Schema ...`);
+ this.elt.textContent = `${this.name}:No Form Schema ...`;
+ return;
+ }
+ if (!this.setting.action || !this.setting.action.callback) {
+ // console.error(`${this.name}:No Action ...`);
+ this.elt.textContent = `${this.name}:No Action ...`;
+ return;
+ }
+ this.elt.style.zIndex = this.setting.zIndex;
+
+
+ this.__refresh();
}
/**
* @private
* __refresh refresh UI part according to this.setting
*/
-OperationPanel.prototype.__refresh = function(){
- empty(this.elt);
- this.elt.classList.add('operations');
-
- const schemas = this.setting.formSchemas;
-
-
- //
- this._head_ = document.createElement('div');
- this._head_.classList.add('head');
- let lab = document.createElement('label');
- lab.textContent = this.setting.title;
- this._head_.appendChild(lab);
-
-
-
- // create select if multiple schema
- this._select_ = document.createElement('select');
- this._select_.classList.add('pure-form-item');
- schemas.forEach((schema, idx) => {
- const opt = document.createElement('option');
- opt.text = schema.name || schema.id;
- opt.value = idx;
- this._select_.add(opt);
- });
-
- if(schemas.length < 2) this._select_.style.display = 'none';
-
- this._head_.appendChild(this._select_);
- this.elt.appendChild(this._head_);
- // add event
- this._select_.addEventListener('change', this.__formChange.bind(this));
-
- // create form area
- this._form_ = document.createElement('pure-form');
- this._form_.validateOnBlur = true;
- this._form_.schema = this.setting.formSchemas[0];
-
- if(this._form_.schema.autofocusError)
- this._form_.autofocusError = this._form_.schema.autofocusError;
- if(this._form_.schema.autofocusId)
- this._form_.autofocusId = this._form_.schema.autofocusId;
-
- this.elt.appendChild(this._form_);
-
-
- // create control
- this._ctrl_ = document.createElement('div');
- this._ctrl_.classList.add('foot');
- this._reset_ = document.createElement('button');
- this._reset_.classList.add('reset');
- this._reset_.textContent = 'Reset';
- this._reset_.style.float = 'left';
- this._ctrl_.appendChild(this._reset_);
-
- this._action_ = document.createElement('button');
- this._action_.classList.add('action');
- this._action_.textContent = this.setting.action.title||'Submit';
- this._action_.style.float = 'right';
- //this._action_.disabled = true;
- this._ctrl_.appendChild(this._action_);
- this.elt.appendChild(this._ctrl_);
-
- this._reset_.addEventListener('click', ()=>{
- this.clear();
- if(this.setting.resetCallback&&typeof this.setting.resetCallback == 'function') this.setting.resetCallback.call(null,{});
-
- });
- // event action
- this._action_.addEventListener('click', function(){
- if(!this._form_.isValid()){
- console.log('error');
- return;
- }
-
- this.setting.action.callback.call(null, {
- id:this.setting.formSchemas[this._select_.value].id,
- data:this._form_.value
- });
- }.bind(this));
-
- // this._form_.addEventListener('pure-form-validation-failed', function(e) {
- // console.log('failded') // form value
- // console.log(e);
- // //this._action_.disabled = true;
- // }.bind(this));
-
- // this._form_.addEventListener('pure-form-validation-passed', function(e) {
- // console.log('passed'); // pure form element
- // console.log(e);
- // //this._action_.disabled = false;
- // }.bind(this));
-
-}
+OperationPanel.prototype.__refresh = function() {
+ empty(this.elt);
+ this.elt.classList.add('operations');
+
+ const schemas = this.setting.formSchemas;
+
+
+ //
+ this._head_ = document.createElement('div');
+ this._head_.classList.add('head');
+ const lab = document.createElement('label');
+ lab.textContent = this.setting.title;
+ this._head_.appendChild(lab);
+
+
+ // create select if multiple schema
+ this._select_ = document.createElement('select');
+ this._select_.classList.add('pure-form-item');
+ schemas.forEach((schema, idx) => {
+ const opt = document.createElement('option');
+ opt.text = schema.name || schema.id;
+ opt.value = idx;
+ this._select_.add(opt);
+ });
+
+ if (schemas.length < 2) this._select_.style.display = 'none';
+
+ this._head_.appendChild(this._select_);
+ this.elt.appendChild(this._head_);
+ // add event
+ this._select_.addEventListener('change', this.__formChange.bind(this));
+
+ // create form area
+ this._form_ = document.createElement('pure-form');
+ this._form_.validateOnBlur = true;
+ this._form_.schema = this.setting.formSchemas[0];
+
+ if (this._form_.schema.autofocusError) {
+ this._form_.autofocusError = this._form_.schema.autofocusError;
+ }
+ if (this._form_.schema.autofocusId) {
+ this._form_.autofocusId = this._form_.schema.autofocusId;
+ }
+
+ this.elt.appendChild(this._form_);
+
+
+ // create control
+ this._ctrl_ = document.createElement('div');
+ this._ctrl_.classList.add('foot');
+ this._reset_ = document.createElement('button');
+ this._reset_.classList.add('reset');
+ this._reset_.textContent = 'Reset';
+ this._reset_.style.float = 'left';
+ this._ctrl_.appendChild(this._reset_);
+
+ this._action_ = document.createElement('button');
+ this._action_.classList.add('action');
+ this._action_.textContent = this.setting.action.title||'Submit';
+ this._action_.style.float = 'right';
+ // this._action_.disabled = true;
+ this._ctrl_.appendChild(this._action_);
+ this.elt.appendChild(this._ctrl_);
+
+ this._reset_.addEventListener('click', ()=>{
+ this.clear();
+ if (this.setting.resetCallback && typeof this.setting.resetCallback == 'function') {
+ this.setting.resetCallback.call(null, {});
+ }
+ });
+ // event action
+ this._action_.addEventListener('click', function() {
+ if (!this._form_.isValid()) {
+ console.log('error');
+ return;
+ }
+
+ this.setting.action.callback.call(null, {
+ id: this.setting.formSchemas[this._select_.value].id,
+ data: this._form_.value,
+ });
+ }.bind(this));
+
+ // this._form_.addEventListener('pure-form-validation-failed', function(e) {
+ // console.log('failded') // form value
+ // console.log(e);
+ // //this._action_.disabled = true;
+ // }.bind(this));
+
+ // this._form_.addEventListener('pure-form-validation-passed', function(e) {
+ // console.log('passed'); // pure form element
+ // console.log(e);
+ // //this._action_.disabled = false;
+ // }.bind(this));
+};
/**
* @private
* __formChange the action that will change the data form if there are multiple forms.
*/
-OperationPanel.prototype.__formChange = function(e){
- this._form_.schema = this.setting.formSchemas[this._select_.value];
- if(this._form_.schema.autofocusError)
- this._form_.autofocusError = this._form_.schema.autofocusError;
- if(this._form_.schema.autofocusId)
- this._form_.autofocusId = this._form_.schema.autofocusId;
-
- //this._action_.disabled = true;
-}
+OperationPanel.prototype.__formChange = function(e) {
+ this._form_.schema = this.setting.formSchemas[this._select_.value];
+ if (this._form_.schema.autofocusError) {
+ this._form_.autofocusError = this._form_.schema.autofocusError;
+ }
+ if (this._form_.schema.autofocusId) {
+ this._form_.autofocusId = this._form_.schema.autofocusId;
+ }
+
+ // this._action_.disabled = true;
+};
/**
* clear and reset current data form
*/
-OperationPanel.prototype.clear = function(){
- this._form_.clearErrors();
- this._form_.reset();
- //this._action_.disabled = true;
-}
+OperationPanel.prototype.clear = function() {
+ this._form_.clearErrors();
+ this._form_.reset();
+ // this._action_.disabled = true;
+};
diff --git a/components/popuppanel/popuppanel.js b/components/popuppanel/popuppanel.js
index 3d4c56fff..912fa3c70 100644
--- a/components/popuppanel/popuppanel.js
+++ b/components/popuppanel/popuppanel.js
@@ -17,9 +17,9 @@
* @param {Array} [options.footer]
* An array of footers. each footer should represent of a action btn
* @param {String} [options.footer.title]
- * The text of hint on the action btn.
+ * The text of hint on the action btn.
* @param {String} [options.footer.class]
- * The css class on the action btn
+ * The css class on the action btn
* @param {String} [options.footer.text]
* The text of action btn
* @param {Function} [options.footer.callback]
@@ -31,209 +31,205 @@
* @param {String} options.bodyHTML
* the stringified HTML elements.
*/
-function PopupPanel(options){
- this.className = 'PopupPanel';
-
-
- /**
- * @property {Element} elt The elements that represent the container of the component.
- */
- this.elt = null;
-
- /**
- * @property {Element} the element of the title. change the textContent will change the title of PopupPanel.
- */
- this.title;
-
- /**
- * @property {Element} the element of the body. The detail/extra info shows on popup panel.
- */
- this.body;
-
- /**
- * @property {Array} [footerBtns] the extend for popup if needs some actions. etc, delete/add/modify.
- */
- this.footerBtns = [];
+function PopupPanel(options) {
+ this.className = 'PopupPanel';
- /**
- * @property {Object} setting
- *
- */
- this.setting = {
- title:'',
- bodyHTML:'',
- zIndex:650,
- footer:[
- // {
- // type:'btn',
- // title:'Annotation',
- // class:'material-icons',
- // text:'description',
- // callback:saveAnnotation
- // },{
- // }
- ],
- }
- extend(this.setting, options);
+ /**
+ * @property {Element} elt The elements that represent the container of the component.
+ */
+ this.elt = null;
- this.elt = document.getElementById(this.setting.id);
- if(!this.elt && this.setting.element){
- this.elt = this.setting.element;
- }
+ /**
+ * @property {Element} the element of the title. change the textContent will change the title of PopupPanel.
+ */
+ this.title;
- if(!this.elt){
- // create main
- this.elt = document.createElement('div');
- document.body.appendChild(this.elt);
+ /**
+ * @property {Element} the element of the body. The detail/extra info shows on popup panel.
+ */
+ this.body;
- }
- //this.elt.style.width = `${this.setting.width}px`;
- this.elt.style.zIndex = this.setting.zIndex;
- this.elt.style.display = 'none';
- this.elt.classList.add('pop-panel');
- // create UI
- this.__refresh();
+ /**
+ * @property {Array} [footerBtns] the extend for popup if needs some actions. etc, delete/add/modify.
+ */
+ this.footerBtns = [];
+
+ /**
+ * @property {Object} setting
+ *
+ */
+ this.setting = {
+ title: '',
+ bodyHTML: '',
+ zIndex: 650,
+ footer: [
+ // {
+ // type:'btn',
+ // title:'Annotation',
+ // class:'material-icons',
+ // text:'description',
+ // callback:saveAnnotation
+ // },{
+
+ // }
+ ],
+ };
+ extend(this.setting, options);
+
+ this.elt = document.getElementById(this.setting.id);
+ if (!this.elt && this.setting.element) {
+ this.elt = this.setting.element;
+ }
+
+ if (!this.elt) {
+ // create main
+ this.elt = document.createElement('div');
+ document.body.appendChild(this.elt);
+ }
+ // this.elt.style.width = `${this.setting.width}px`;
+ this.elt.style.zIndex = this.setting.zIndex;
+ this.elt.style.display = 'none';
+ this.elt.classList.add('pop-panel');
+ // create UI
+ this.__refresh();
}
/**
- * @private
+ * @private
* refresh component bases on the setting.
*/
-PopupPanel.prototype.__refresh = function(){
- empty(this.elt);
-
- this.footerBtns = [];
+PopupPanel.prototype.__refresh = function() {
+ empty(this.elt);
- /* create header */
- const header = document.createElement('div');
- header.classList.add('pop-panel-header');
+ this.footerBtns = [];
- // head title
- const headTitle = document.createElement('div');
- headTitle.classList.add('pop-panel-header-title');
- headTitle.textContent = this.setting.title;
- header.appendChild(headTitle);
- this.title = headTitle;
- // close btn
- const closeDiv = document.createElement('div');
- closeDiv.classList.add('material-icons');
- closeDiv.textContent = 'close';
- header.appendChild(closeDiv);
- // close event
- closeDiv.addEventListener('click', this.close.bind(this))
+ /* create header */
+ const header = document.createElement('div');
+ header.classList.add('pop-panel-header');
- this.elt.appendChild(header);
+ // head title
+ const headTitle = document.createElement('div');
+ headTitle.classList.add('pop-panel-header-title');
+ headTitle.textContent = this.setting.title;
+ header.appendChild(headTitle);
+ this.title = headTitle;
+ // close btn
+ const closeDiv = document.createElement('div');
+ closeDiv.classList.add('material-icons');
+ closeDiv.textContent = 'close';
+ header.appendChild(closeDiv);
+ // close event
+ closeDiv.addEventListener('click', this.close.bind(this));
+ this.elt.appendChild(header);
- /* create body */
- const body = document.createElement('div');
- this.data = null;
- body.classList.add('pop-panel-body');
-
- if(this.setting.body) {
- body.appendChild(PopupPanel.createBodyContent(this.setting.body))
- }else{
- body.innerHTML = this.setting.bodyHTML;
- }
- this.body = body;
- this.elt.appendChild(body);
- /* create footer */
- const footer = document.createElement('div');
- footer.classList.add('pop-panel-footer');
- // create all foot btns
- const btns = this.setting.footer;
- for (var i = 0; i < btns.length; i++) {
- this.footerBtns.push(PopupPanel.createBtn(footer,btns[i],this));
- }
- this.elt.appendChild(footer);
+ /* create body */
+ const body = document.createElement('div');
+ this.data = null;
+ body.classList.add('pop-panel-body');
-}
+ if (this.setting.body) {
+ body.appendChild(PopupPanel.createBodyContent(this.setting.body));
+ } else {
+ body.innerHTML = this.setting.bodyHTML;
+ }
+ this.body = body;
+ this.elt.appendChild(body);
+ /* create footer */
+ const footer = document.createElement('div');
+ footer.classList.add('pop-panel-footer');
+
+ // create all foot btns
+ const btns = this.setting.footer;
+ for (let i = 0; i < btns.length; i++) {
+ this.footerBtns.push(PopupPanel.createBtn(footer, btns[i], this));
+ }
+ this.elt.appendChild(footer);
+};
/**
* open - popup the panel.
* @param {Object} point
* the point represents the position where the panel is
*/
-PopupPanel.prototype.open = function(point){
- if(!point || !point.x || !point.y){
- console.error('invalid point');
- return;
- }
- this.elt.style.display = 'block';
- if( window.innerWidth > point.x + this.elt.offsetWidth){
- this.elt.style.left = point.x+'px';
- }else{
- this.elt.style.left = (point.x - this.elt.offsetWidth)+'px';
- }
-
- if(window.innerHeight > point.y + this.elt.offsetHeight){
- this.elt.style.top = point.y+'px';
- }else{
- this.elt.style.top = (point.y - this.elt.offsetHeight)+'px';
- }
+PopupPanel.prototype.open = function(point) {
+ if (!point || !point.x || !point.y) {
+ console.error('invalid point');
+ return;
+ }
+ this.elt.style.display = 'block';
+ if ( window.innerWidth > point.x + this.elt.offsetWidth) {
+ this.elt.style.left = point.x+'px';
+ } else {
+ this.elt.style.left = (point.x - this.elt.offsetWidth)+'px';
+ }
-}
+ if (window.innerHeight > point.y + this.elt.offsetHeight) {
+ this.elt.style.top = point.y+'px';
+ } else {
+ this.elt.style.top = (point.y - this.elt.offsetHeight)+'px';
+ }
+};
/**
* setTitle set the title of the panel
* @param {String} text title's text
*/
-PopupPanel.prototype.setTitle = function(text){
- // clear body
- empty(this.title);
- // create body
- this.title.textContent = text;
-}
-PopupPanel.prototype.hideFooter = function(){
- const footer = this.elt.querySelector('.pop-panel-footer');
- if(footer) footer.style.display = 'none';
-
-}
-PopupPanel.prototype.showFooter = function(){
- const footer = this.elt.querySelector('.pop-panel-footer');
- if(footer) footer.style.display = '';
-}
+PopupPanel.prototype.setTitle = function(text) {
+ // clear body
+ empty(this.title);
+ // create body
+ this.title.textContent = text;
+};
+PopupPanel.prototype.hideFooter = function() {
+ const footer = this.elt.querySelector('.pop-panel-footer');
+ if (footer) footer.style.display = 'none';
+};
+PopupPanel.prototype.showFooter = function() {
+ const footer = this.elt.querySelector('.pop-panel-footer');
+ if (footer) footer.style.display = '';
+};
/**
* setBody set the display body part.
* @param {Object} body
* the object of body includes the type of body and the data of body.
- *
+ *
* @param {string} body.type
* 'map' - key,value pair.
* 'table' - multiple columns and rows.
- *
+ *
* @param {data} body.data
- * there are two types of body.
+ * there are two types of body.
* 'map' - key,value pair.
- * [{
- * key,
- * value,
- * },...]
+ * [{
+ * key,
+ * value,
+ * },...]
* 'table' - multiple columns and rows.
- * [{
- * col1,
- * col2,
- * ...
- * },...]
+ * [{
+ * col1,
+ * col2,
+ * ...
+ * },...]
*/
-PopupPanel.prototype.setBody = function(body){
- // clear body
- empty(this.body);
+PopupPanel.prototype.setBody = function(body) {
+ // clear body
+ empty(this.body);
- // create body
- this.body.appendChild(PopupPanel.createBodyContent(body));
-}
+ // create body
+ this.body.appendChild(PopupPanel.createBodyContent(body));
+};
/**
* close close the panel.
*/
-PopupPanel.prototype.close = function(){
- this.elt.style.display = 'none';
- this.elt.style.top = '-1000px';
- this.elt.style.left = '-1000px';
-}
+PopupPanel.prototype.close = function() {
+ this.elt.style.display = 'none';
+ this.elt.style.top = '-1000px';
+ this.elt.style.left = '-1000px';
+};
/**
* @static
@@ -241,135 +237,135 @@ PopupPanel.prototype.close = function(){
* @param {string} body.type
* 'map' - key,value pair.
* 'table' - multiple columns and rows.
- *
+ *
* @param {data} body.data
- * there are two types of body.
+ * there are two types of body.
* 'map' - key,value pair.
- * [{
- * key,
- * value,
- * },...]
+ * [{
+ * key,
+ * value,
+ * },...]
* 'table' - multiple columns and rows.
- * [{
- * col1,
- * col2,
- * ...
- * },...]
+ * [{
+ * col1,
+ * col2,
+ * ...
+ * },...]
* @return {HTML Element} A table style element
*/
-PopupPanel.createBodyContent = function(opt){
- let content;
+PopupPanel.createBodyContent = function(opt) {
+ let content;
- switch (opt.type) {
- case 'table':
- // create table-like content
- content = PopupPanel.createTable(opt.data);
- break;
- case 'map':
- // create key-value content
- content = PopupPanel.createMap(opt.data);
- break;
- default:
- // statements_def
- break;
- }
- return content;
-}
+ switch (opt.type) {
+ case 'table':
+ // create table-like content
+ content = PopupPanel.createTable(opt.data);
+ break;
+ case 'map':
+ // create key-value content
+ content = PopupPanel.createMap(opt.data);
+ break;
+ default:
+ // statements_def
+ break;
+ }
+ return content;
+};
/**
* @static
* createTable - a static method to handle the table type of data and generate the format data for the body.
* @param {data} table data
* 'table' - multiple columns and rows.
- * [{
- * col1,
- * col2,
- * ...
- * },...]
+ * [{
+ * col1,
+ * col2,
+ * ...
+ * },...]
* @return {HTML Element} A table style element
*/
-PopupPanel.createTable = function(data){
- const table = document.createElement('div');
- table.classList.add('table');
- for (var i = 0; i < data.length; i++) {
- const row = data[i];
- // create row div and add into table div
- const tr = document.createElement('div');
- tr.classList.add('row');
- table.appendChild(tr);
- for (var i = 0; i < row.length; i++) {
- const cell = row[i];
- // create cell div and add into row div
- const td = document.createElement('div');
- td.classList.add('value');
- td.textContent = cell;
- tr.appendChild(td);
- }
- }
- return table;
-}
+PopupPanel.createTable = function(data) {
+ const table = document.createElement('div');
+ table.classList.add('table');
+ for (var i = 0; i < data.length; i++) {
+ const row = data[i];
+ // create row div and add into table div
+ const tr = document.createElement('div');
+ tr.classList.add('row');
+ table.appendChild(tr);
+ for (var i = 0; i < row.length; i++) {
+ const cell = row[i];
+ // create cell div and add into row div
+ const td = document.createElement('div');
+ td.classList.add('value');
+ td.textContent = cell;
+ tr.appendChild(td);
+ }
+ }
+ return table;
+};
/**
* @static
* createMap - a static method to handle the map type of data and generate the format data for the body.
* @param {data} map data
* 'map' - key,value pair.
- * [{
- * key,
- * value,
- * },...]
+ * [{
+ * key,
+ * value,
+ * },...]
* @return {HTML Element} A map style element
*/
-PopupPanel.createMap = function(data){
- const table = document.createElement('div');
- table.classList.add('table');
- for (var i = 0; i < data.length; i++) {
- const row = data[i];
- // create row div and add into table div
- const tr = document.createElement('div');
- tr.classList.add('row');
- table.appendChild(tr);
+PopupPanel.createMap = function(data) {
+ const table = document.createElement('div');
+ table.classList.add('table');
+ for (let i = 0; i < data.length; i++) {
+ const row = data[i];
+ // create row div and add into table div
+ const tr = document.createElement('div');
+ tr.classList.add('row');
+ table.appendChild(tr);
- // create key cell
- const key = document.createElement('div');
- key.classList.add('field');
- key.textContent = row.key || row.name;
- // create value cell
- const value = document.createElement('div');
- value.classList.add('value');
- value.textContent = row.value;
-
- tr.appendChild(key);
- tr.appendChild(value);
- }
- return table;
-}
+ // create key cell
+ const key = document.createElement('div');
+ key.classList.add('field');
+ key.textContent = row.key || row.name;
+ // create value cell
+ const value = document.createElement('div');
+ value.classList.add('value');
+ value.textContent = row.value;
+
+ tr.appendChild(key);
+ tr.appendChild(value);
+ }
+ return table;
+};
/**
* @static
* createBtn a factory method to create an action btn based on config operation
* @param {HTML Element} parent
* The parent will be attached on
* @param {Object} opt
- * the options of the btn
+ * the options of the btn
* @param {String} opt.title
- * the Title of the btn
+ * the Title of the btn
* @param {String} [opt.class]
* the css class of the btn
* @param {String} opt.text
* the display text of the btn
* @param {Function} opt.callback
- * the callback function of the btn
+ * the callback function of the btn
* @param {} [thisArg=null]
* @return {HTML Element} A btn element
*/
-PopupPanel.createBtn = function(parent, opt, thisArg = null){
- const btn = document.createElement('button');
- btn.title = opt.title;
- btn.classList.add(opt.class);
- btn.textContent = opt.text;
- btn.addEventListener('click', function(e){
- opt.callback.call(null,thisArg.data);
- });
- parent.appendChild(btn);
- return btn;
-}
\ No newline at end of file
+PopupPanel.createBtn = function(parent, opt, thisArg = null) {
+ const btn = document.createElement('button');
+ btn.title = opt.title;
+ btn.classList.add(opt.class);
+ btn.textContent = opt.text;
+ btn.addEventListener('click', function(e) {
+ opt.callback.call(null, thisArg.data);
+ });
+ parent.appendChild(btn);
+ return btn;
+};
diff --git a/components/sidemenu/sidemenu.js b/components/sidemenu/sidemenu.js
index b17b599ce..db4ef3965 100644
--- a/components/sidemenu/sidemenu.js
+++ b/components/sidemenu/sidemenu.js
@@ -5,17 +5,17 @@
// test:
// constructor:
// width, isOpen,
-//
+//
// method:
// open()
// close()
// addContent(string/elt);
-//
+//
/**
* CaMicroscope Side Menu. description
* @constructor
- * @param {Object} options
+ * @param {Object} options
* All required and optional settings for instantiating a new instance of a Side Menu.
* @param {String} options.id
* Id of the element to append the Side Menu's container element to.
@@ -25,138 +25,142 @@
* initialized status for menu. is open or not.
* @param {Function({opt.target,opt.isOpen})} [options.callback]
* toggle if the side menu is open or close. opt.target - current menu. opt.isOpen - true:open, false:close.
- *
+ *
*/
-function SideMenu(options){
- this.name ='SideMenu';
-
- /**
+function SideMenu(options) {
+ this.name ='SideMenu';
+
+ /**
* @property {Element} elt The element to append the side menu's container element to.
*/
- this.elt = null;
-
- /**
+ this.elt = null;
+
+ /**
* @property {Element} _close_handler The elements that represent the close handler.
*/
- this._close_handler = null; // click to close panel
-
- /**
+ this._close_handler = null; // click to close panel
+
+ /**
* @property {Element} _close_handler The elements that represent the content of the menu.
*/
- this._content = null;
-
- // default setting
- this.setting = {
- //id: container id
- // menu heigh defalut is flex
- // menu width
- width:300,
- // menu initial status
- isOpen:false
- }
-
- // user setting
- extend(this.setting, options);
- this.elt = document.getElementById(this.setting.id);
- if(!this.elt){
- console.error(`${this.name}:No Main Container...`);
- return;
- }
-
- // create UI
- this.__refresh();
-
- // add close event
- this._close_handler.addEventListener('click',this.close.bind(this));
-
-
- if(this.setting.isOpen) this.open();
- //initialInnerMenu
- //if(this.setting.id=='side_apps')this.initialInnerMenu();
+ this._content = null;
+
+ // default setting
+ this.setting = {
+ // id: container id
+ // menu heigh defalut is flex
+ // menu width
+ width: 300,
+ // menu initial status
+ isOpen: false,
+ };
+
+ // user setting
+ extend(this.setting, options);
+ this.elt = document.getElementById(this.setting.id);
+ if (!this.elt) {
+ console.error(`${this.name}:No Main Container...`);
+ return;
+ }
+
+ // create UI
+ this.__refresh();
+
+ // add close event
+ this._close_handler.addEventListener('click', this.close.bind(this));
+
+
+ if (this.setting.isOpen) this.open();
+ // initialInnerMenu
+ // if(this.setting.id=='side_apps')this.initialInnerMenu();
}
/**
* Render UI based on the options.
- *
+ *
*/
-SideMenu.prototype.__refresh = function(){
- // remove all children
- empty(this.elt);
-
- this.elt.style.width = 0;
- this.elt.style.left = `-10px`;
- this.elt.classList.add('side_menu');
- this.elt.classList.add('flex-container');
-
- // create 'close' hand
- this._close_handler = document.createElement('div');
- this._close_handler.classList.add('close');
-
- const icon1 = document.createElement('i');
- icon1.classList.add('material-icons');
- icon1.classList.add('md-24');
- icon1.textContent = 'chevron_left';
-
- const icon2 = icon1.cloneNode(true);
- icon2.classList.add('sec');
-
- this._close_handler.appendChild(icon1);
- this._close_handler.appendChild(icon2);
- this.elt.appendChild(this._close_handler);
-
- // create side panel content panel
- this._content = document.createElement('div');
- this._content.classList.add('side_content');
- this._content.classList.add('flex-container');
- this.elt.appendChild(this._content);
+SideMenu.prototype.__refresh = function() {
+ // remove all children
+ empty(this.elt);
+
+ this.elt.style.width = 0;
+ this.elt.style.left = `-10px`;
+ this.elt.classList.add('side_menu');
+ this.elt.classList.add('flex-container');
+
+ // create 'close' hand
+ this._close_handler = document.createElement('div');
+ this._close_handler.classList.add('close');
+
+ const icon1 = document.createElement('i');
+ icon1.classList.add('material-icons');
+ icon1.classList.add('md-24');
+ icon1.textContent = 'chevron_left';
+ const icon2 = icon1.cloneNode(true);
+ icon2.classList.add('sec');
+
+ this._close_handler.appendChild(icon1);
+ this._close_handler.appendChild(icon2);
+ this.elt.appendChild(this._close_handler);
+
+ // create side panel content panel
+ this._content = document.createElement('div');
+ this._content.classList.add('side_content');
+ this._content.classList.add('flex-container');
+ this.elt.appendChild(this._content);
};
/**
* open the side menu
*/
SideMenu.prototype.open = function() {
- this.elt.style.left = 0;
- this.elt.style.width = this.setting.width+'px';
+ this.elt.style.left = 0;
+ this.elt.style.width = this.setting.width+'px';
- if(this.setting.callback) this.setting.callback.call(this,{
- target:this.elt,
- isOpen:true
- });
+ if (this.setting.callback) {
+ this.setting.callback.call(this, {
+ target: this.elt,
+ isOpen: true,
+ });
+ }
};
/**
* close the side menu
*/
SideMenu.prototype.close = function() {
- this.elt.style.left = `-10px`;
- this.elt.style.width = 0;
- if(this.setting.callback) this.setting.callback.call(this,{
- target:this.elt,
- isOpen:false
- });
+ this.elt.style.left = `-10px`;
+ this.elt.style.width = 0;
+ if (this.setting.callback) {
+ this.setting.callback.call(this, {
+ target: this.elt,
+ isOpen: false,
+ });
+ }
};
/**
* add a content on the side menu.
* @param {String|Element} element the element, text content, or HTML template that be added.
*/
-SideMenu.prototype.addContent = function(elt){
- const content = this._content;
- if(elt instanceof Element)
- content.appendChild(elt);
- // if(typeof element ==='string')
- // this._content.textcontent = element;
- if(typeof elt === 'string') {
- const div = document.createElement('div');
- div.innerHTML = elt;
- const childern = [...div.children];
- childern.forEach(child =>{
- content.appendChild(child);
- })
- };
+SideMenu.prototype.addContent = function(elt) {
+ const content = this._content;
+ if (elt instanceof Element) {
+ content.appendChild(elt);
+ }
+ // if(typeof element ==='string')
+ // this._content.textcontent = element;
+ if (typeof elt === 'string') {
+ const div = document.createElement('div');
+ div.innerHTML = elt;
+ const childern = [...div.children];
+ childern.forEach((child) =>{
+ content.appendChild(child);
+ });
+ };
};
/**
* clear all content on the side menu.
*/
-SideMenu.prototype.clearContent = function(){
- empty(this._content);
-}
+SideMenu.prototype.clearContent = function() {
+ empty(this._content);
+};
diff --git a/components/simplecontextmenu/simplecontextmenu.js b/components/simplecontextmenu/simplecontextmenu.js
index e15109244..8d0e4c445 100644
--- a/components/simplecontextmenu/simplecontextmenu.js
+++ b/components/simplecontextmenu/simplecontextmenu.js
@@ -1,335 +1,327 @@
// menu.js
//
// let __ = {};
-(function($){
- $.SimpleContextMenu = function(target,options){
- this.elt = createElement();
- this.target = target;
- if(!this.target){
- console.error(`${this.className}:No TARGET to operation`);
- return;
- }
-
- this.target.appendChild(this.elt);
-
- this.events = {
- eventClose:eventClose.bind(this),
- eventOpen:eventOpen.bind(this)
- }
-
- this.elt.style.zIndex = options.zIndex || 650;
-
- // style event
- const list = this.elt.querySelectorAll('.style a');
- list.forEach(a=> a.addEventListener('click', selectStyle.bind(this)));
-
- // color event
- const input = this.elt.querySelector('.color input');
- const box = this.elt.querySelector('.color div.icons');
-
- box.style.backgroundColor = input.value;
- box.setAttribute('data-color', input.value);
- input.parentNode.insertBefore(box, input);
- input.type = 'hidden';
- this.picker = new CP(box);
- this.picker.on("change", function(color) {
- input.value = '#' + color;
- box.style.backgroundColor = '#' + color;
- this.raiseEvent('style-changed',this.getStyle());
- }.bind(this));
-
- // clear event
- const clear = this.elt.querySelector('.clear');
- clear.addEventListener('click', function(){
- this.raiseEvent('clear',{});
- }.bind(this));
-
- if(options.isOn) this.on();
-
-
- }
- $.SimpleContextMenu.prototype.on = function(){
- this.close(true);
- this.target.addEventListener('contextmenu',this.events.eventOpen);
- this.target.addEventListener('click', this.events.eventClose);
- };
-
- $.SimpleContextMenu.prototype.off = function(){
- this.close(true);
- this.target.removeEventListener('contextmenu',this.events.eventOpen);
- this.target.removeEventListener('click', this.events.eventClose);
- };
-
- $.SimpleContextMenu.prototype.open = function({x = 0, y = 0, target = null}){
- //
- const items = this.elt.querySelectorAll('.item');
- items.forEach(item => item.classList.remove('list'));
- if(target){
- // get pos on screen
- const height = target.offsetHeight;
- //const width = target.offsetWidth;
- for (var left=0, top=0;target != null;left += target.offsetLeft, top += target.offsetTop, target = target.offsetParent);
- top += height;
- left += 2;//width;
- items.forEach(item => item.classList.add('list'));
- this.elt.style.display = '';
- this.elt.style.left = `${left}px`;
- this.elt.style.top = `${top}px`;
- this.elt.style.visibility = `visible`;
- this.elt.querySelector('.flag').checked = true;
- }else{
- this.elt.style.display = '';
- this.elt.style.left = `${x}px`;
- this.elt.style.top = `${y}px`;
- setTimeout(function(){
- this.elt.style.visibility = `visible`;
- this.elt.querySelector('.flag').checked = true;
- }.bind(this), 100);
- }
-
- };
-$.SimpleContextMenu.prototype.getStyle = function(){
- const color = this.elt.querySelector('.color input[type=hidden]').value;
-
- const model = this.elt.querySelector('.style .active').dataset.model;
- return {
- style:{
- color:color,
- lineJoin:'round', // "bevel" || "round" || "miter"
- lineCap:'round' // "butt" || "round" || "square"
- },
- model:model
+(function($) {
+ $.SimpleContextMenu = function(target, options) {
+ this.elt = createElement();
+ this.target = target;
+ if (!this.target) {
+ console.error(`${this.className}:No TARGET to operation`);
+ return;
}
-}
- $.SimpleContextMenu.prototype.close = function(immediate = false){
- this.picker.exit();
- this.elt.querySelector('.flag').checked = false;
- if(immediate){
- this.elt.style.visibility = ``;
- this.elt.style.display = 'none';
- return;
- }
- setTimeout(function(){
- this.elt.style.visibility = ``;
- this.elt.style.display = 'none';
- }.bind(this), 100);
- };
- function eventOpen(e){
- this.open({x:e.clientX,y:e.clientY});
- e.preventDefault();
-
- }
- function eventClose(e){
- if(!e){
- this.close();
- return;
- }
- const isClickOnMenu = clickInsideElement( e, 'draw-menu-wrap' );
- if ( isClickOnMenu ) return;
-
- this.close();
- }
-/**
+
+ this.target.appendChild(this.elt);
+
+ this.events = {
+ eventClose: eventClose.bind(this),
+ eventOpen: eventOpen.bind(this),
+ };
+
+ this.elt.style.zIndex = options.zIndex || 650;
+
+ // style event
+ const list = this.elt.querySelectorAll('.style a');
+ list.forEach((a)=> a.addEventListener('click', selectStyle.bind(this)));
+
+ // color event
+ const input = this.elt.querySelector('.color input');
+ const box = this.elt.querySelector('.color div.icons');
+
+ box.style.backgroundColor = input.value;
+ box.setAttribute('data-color', input.value);
+ input.parentNode.insertBefore(box, input);
+ input.type = 'hidden';
+ this.picker = new CP(box);
+ this.picker.on('change', function(color) {
+ input.value = '#' + color;
+ box.style.backgroundColor = '#' + color;
+ this.raiseEvent('style-changed', this.getStyle());
+ }.bind(this));
+
+ // clear event
+ const clear = this.elt.querySelector('.clear');
+ clear.addEventListener('click', function() {
+ this.raiseEvent('clear', {});
+ }.bind(this));
+
+ if (options.isOn) this.on();
+ };
+ $.SimpleContextMenu.prototype.on = function() {
+ this.close(true);
+ this.target.addEventListener('contextmenu', this.events.eventOpen);
+ this.target.addEventListener('click', this.events.eventClose);
+ };
+
+ $.SimpleContextMenu.prototype.off = function() {
+ this.close(true);
+ this.target.removeEventListener('contextmenu', this.events.eventOpen);
+ this.target.removeEventListener('click', this.events.eventClose);
+ };
+
+ $.SimpleContextMenu.prototype.open = function({x = 0, y = 0, target = null}) {
+ //
+ const items = this.elt.querySelectorAll('.item');
+ items.forEach((item) => item.classList.remove('list'));
+ if (target) {
+ // get pos on screen
+ const height = target.offsetHeight;
+ // const width = target.offsetWidth;
+ for (var left=0, top=0; target != null;
+ left += target.offsetLeft, top += target.offsetTop, target = target.offsetParent);
+ top += height;
+ left += 2;// width;
+ items.forEach((item) => item.classList.add('list'));
+ this.elt.style.display = '';
+ this.elt.style.left = `${left}px`;
+ this.elt.style.top = `${top}px`;
+ this.elt.style.visibility = `visible`;
+ this.elt.querySelector('.flag').checked = true;
+ } else {
+ this.elt.style.display = '';
+ this.elt.style.left = `${x}px`;
+ this.elt.style.top = `${y}px`;
+ setTimeout(function() {
+ this.elt.style.visibility = `visible`;
+ this.elt.querySelector('.flag').checked = true;
+ }.bind(this), 100);
+ }
+ };
+ $.SimpleContextMenu.prototype.getStyle = function() {
+ const color = this.elt.querySelector('.color input[type=hidden]').value;
+
+ const model = this.elt.querySelector('.style .active').dataset.model;
+ return {
+ style: {
+ color: color,
+ lineJoin: 'round', // "bevel" || "round" || "miter"
+ lineCap: 'round', // "butt" || "round" || "square"
+ },
+ model: model,
+ };
+ };
+ $.SimpleContextMenu.prototype.close = function(immediate = false) {
+ this.picker.exit();
+ this.elt.querySelector('.flag').checked = false;
+ if (immediate) {
+ this.elt.style.visibility = ``;
+ this.elt.style.display = 'none';
+ return;
+ }
+ setTimeout(function() {
+ this.elt.style.visibility = ``;
+ this.elt.style.display = 'none';
+ }.bind(this), 100);
+ };
+ function eventOpen(e) {
+ this.open({x: e.clientX, y: e.clientY});
+ e.preventDefault();
+ }
+ function eventClose(e) {
+ if (!e) {
+ this.close();
+ return;
+ }
+ const isClickOnMenu = clickInsideElement( e, 'draw-menu-wrap' );
+ if ( isClickOnMenu ) return;
+
+ this.close();
+ }
+ /**
* Add an event handler for a given event.
* @function
* @param {String} eventName - Name of event to register.
* @param {OpenSeadragon.EventHandler} handler - Function to call when event is triggered.
* @param {Object} [userData=null] - Arbitrary object to be passed unchanged to the handler.
*/
-$.SimpleContextMenu.prototype.addHandler = function ( eventName, handler, userData ) {
- var events = this.events[ eventName ];
+ $.SimpleContextMenu.prototype.addHandler = function( eventName, handler, userData ) {
+ let events = this.events[eventName];
if ( !events ) {
- this.events[ eventName ] = events = [];
+ this.events[eventName] = events = [];
}
if ( handler && typeof handler === 'function' ) {
- events[ events.length ] = { handler: handler, userData: userData || null };
+ events[events.length] = {handler: handler, userData: userData || null};
}
-}
+ };
-/**
+ /**
* Remove a specific event handler for a given event.
* @function
* @param {String} eventName - Name of event for which the handler is to be removed.
* @param {OpenSeadragon.EventHandler} handler - Function to be removed.
*/
-$.SimpleContextMenu.prototype.removeHandler = function ( eventName, handler ) {
- var events = this.events[ eventName ],
- handlers = [],
- i;
+ $.SimpleContextMenu.prototype.removeHandler = function( eventName, handler ) {
+ const events = this.events[eventName];
+ const handlers = [];
+ let i;
if ( !events ) {
- return;
+ return;
}
if ( $.isArray( events ) ) {
- for ( i = 0; i < events.length; i++ ) {
- if ( events[i].handler !== handler ) {
- handlers.push( events[ i ] );
- }
+ for ( i = 0; i < events.length; i++ ) {
+ if ( events[i].handler !== handler ) {
+ handlers.push( events[i] );
}
- this.events[ eventName ] = handlers;
+ }
+ this.events[eventName] = handlers;
}
-}
+ };
-/**
+ /**
* Remove all event handlers for a given event type. If no type is given all
* event handlers for every event type are removed.
* @function
* @param {String} eventName - Name of event for which all handlers are to be removed.
*/
-$.SimpleContextMenu.prototype.removeAllHandlers = function( eventName ) {
- if ( eventName ){
- this.events[ eventName ] = [];
- } else{
- for ( var eventType in this.events ) {
- this.events[ eventType ] = [];
+ $.SimpleContextMenu.prototype.removeAllHandlers = function( eventName ) {
+ if ( eventName ) {
+ this.events[eventName] = [];
+ } else {
+ for ( const eventType in this.events ) {
+ if (this.events.hasOwnProperty(eventType)) {
+ this.events[eventType] = [];
}
+ }
}
-},
+ },
-/**
+ /**
* Get a function which iterates the list of all handlers registered for a given event, calling the handler for each.
* @function
* @param {String} eventName - Name of event to get handlers for.
*/
-$.SimpleContextMenu.prototype.getHandler = function ( eventName ) {
- var events = this.events[ eventName ];
+ $.SimpleContextMenu.prototype.getHandler = function( eventName ) {
+ let events = this.events[eventName];
if ( !events || !events.length ) {
- return null;
+ return null;
}
events = events.length === 1 ?
- [ events[ 0 ] ] :
- Array.apply( null, events );
- return function ( source, args ) {
- var i,
- length = events.length;
- for ( i = 0; i < length; i++ ) {
- if ( events[ i ] ) {
- args.eventSource = source;
- args.userData = events[ i ].userData;
- events[ i ].handler( args );
- }
+ [events[0]] :
+ Array( ...events );
+ return function( source, args ) {
+ let i;
+ const length = events.length;
+ for ( i = 0; i < length; i++ ) {
+ if ( events[i] ) {
+ args.eventSource = source;
+ args.userData = events[i].userData;
+ events[i].handler( args );
}
+ }
};
-},
+ },
-/**
+ /**
* Trigger an event, optionally passing additional information.
* @function
* @param {String} eventName - Name of event to register.
* @param {Object} eventArgs - Event-specific data.
*/
- $.SimpleContextMenu.prototype.raiseEvent = function( eventName, eventArgs ) {
- //uncomment if you want to get a log of all events
- //$.console.log( eventName );
- var handler = this.getHandler( eventName );
+ $.SimpleContextMenu.prototype.raiseEvent = function( eventName, eventArgs ) {
+ // uncomment if you want to get a log of all events
+ // $.console.log( eventName );
+ const handler = this.getHandler( eventName );
if ( handler ) {
- if ( !eventArgs ) {
- eventArgs = {};
- }
+ if ( !eventArgs ) {
+ eventArgs = {};
+ }
- handler( this, eventArgs );
+ handler( this, eventArgs );
}
-}
- function selectStyle(e){
- //var e = event;
- var theTool = e.target.parentNode;
- var toolbarItems = this.elt.querySelectorAll('ul.style li');
- for (var i = 0; i < toolbarItems.length; ++i) {
- toolbarItems[i].className = '';
- // do something with items[i], which is a