ItemSet.js 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384
  1. var Hammer = require('../../module/hammer');
  2. var util = require('../../util');
  3. var DataSet = require('../../DataSet');
  4. var DataView = require('../../DataView');
  5. var TimeStep = require('../TimeStep');
  6. var Component = require('./Component');
  7. var Group = require('./Group');
  8. var BackgroundGroup = require('./BackgroundGroup');
  9. var BoxItem = require('./item/BoxItem');
  10. var PointItem = require('./item/PointItem');
  11. var RangeItem = require('./item/RangeItem');
  12. var BackgroundItem = require('./item/BackgroundItem');
  13. var Popup = require('../../shared/Popup').default;
  14. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  15. var BACKGROUND = '__background__'; // reserved group id for background items without group
  16. /**
  17. * An ItemSet holds a set of items and ranges which can be displayed in a
  18. * range. The width is determined by the parent of the ItemSet, and the height
  19. * is determined by the size of the items.
  20. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  21. * @param {Object} [options] See ItemSet.setOptions for the available options.
  22. * @constructor ItemSet
  23. * @extends Component
  24. */
  25. function ItemSet(body, options) {
  26. this.body = body;
  27. this.defaultOptions = {
  28. type: null, // 'box', 'point', 'range', 'background'
  29. orientation: {
  30. item: 'bottom' // item orientation: 'top' or 'bottom'
  31. },
  32. align: 'auto', // alignment of box items
  33. stack: true,
  34. stackSubgroups: true,
  35. groupOrderSwap: function(fromGroup, toGroup, groups) { // eslint-disable-line no-unused-vars
  36. var targetOrder = toGroup.order;
  37. toGroup.order = fromGroup.order;
  38. fromGroup.order = targetOrder;
  39. },
  40. groupOrder: 'order',
  41. selectable: true,
  42. multiselect: false,
  43. itemsAlwaysDraggable: {
  44. item: false,
  45. range: false,
  46. },
  47. editable: {
  48. updateTime: false,
  49. updateGroup: false,
  50. add: false,
  51. remove: false,
  52. overrideItems: false
  53. },
  54. groupEditable: {
  55. order: false,
  56. add: false,
  57. remove: false
  58. },
  59. snap: TimeStep.snap,
  60. // Only called when `objectData.target === 'item'.
  61. onDropObjectOnItem: function(objectData, item, callback) {
  62. callback(item)
  63. },
  64. onAdd: function (item, callback) {
  65. callback(item);
  66. },
  67. onUpdate: function (item, callback) {
  68. callback(item);
  69. },
  70. onMove: function (item, callback) {
  71. callback(item);
  72. },
  73. onRemove: function (item, callback) {
  74. callback(item);
  75. },
  76. onMoving: function (item, callback) {
  77. callback(item);
  78. },
  79. onAddGroup: function (item, callback) {
  80. callback(item);
  81. },
  82. onMoveGroup: function (item, callback) {
  83. callback(item);
  84. },
  85. onRemoveGroup: function (item, callback) {
  86. callback(item);
  87. },
  88. margin: {
  89. item: {
  90. horizontal: 10,
  91. vertical: 10
  92. },
  93. axis: 20
  94. },
  95. showTooltips: true,
  96. tooltip: {
  97. followMouse: false,
  98. overflowMethod: 'flip'
  99. },
  100. tooltipOnItemUpdateTime: false
  101. };
  102. // options is shared by this ItemSet and all its items
  103. this.options = util.extend({}, this.defaultOptions);
  104. this.options.rtl = options.rtl;
  105. // options for getting items from the DataSet with the correct type
  106. this.itemOptions = {
  107. type: {start: 'Date', end: 'Date'}
  108. };
  109. this.conversion = {
  110. toScreen: body.util.toScreen,
  111. toTime: body.util.toTime
  112. };
  113. this.dom = {};
  114. this.props = {};
  115. this.hammer = null;
  116. var me = this;
  117. this.itemsData = null; // DataSet
  118. this.groupsData = null; // DataSet
  119. // listeners for the DataSet of the items
  120. this.itemListeners = {
  121. 'add': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  122. me._onAdd(params.items);
  123. },
  124. 'update': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  125. me._onUpdate(params.items);
  126. },
  127. 'remove': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  128. me._onRemove(params.items);
  129. }
  130. };
  131. // listeners for the DataSet of the groups
  132. this.groupListeners = {
  133. 'add': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  134. me._onAddGroups(params.items);
  135. if (me.groupsData && me.groupsData.length > 0) {
  136. var groupsData = me.groupsData.getDataSet();
  137. groupsData.get().forEach(function (groupData) {
  138. if (groupData.nestedGroups) {
  139. if (groupData.showNested != false) {
  140. groupData.showNested = true;
  141. }
  142. var updatedGroups = [];
  143. groupData.nestedGroups.forEach(function(nestedGroupId) {
  144. var updatedNestedGroup = groupsData.get(nestedGroupId);
  145. if (!updatedNestedGroup) { return; }
  146. updatedNestedGroup.nestedInGroup = groupData.id;
  147. if (groupData.showNested == false) {
  148. updatedNestedGroup.visible = false;
  149. }
  150. updatedGroups = updatedGroups.concat(updatedNestedGroup);
  151. });
  152. groupsData.update(updatedGroups, senderId);
  153. }
  154. });
  155. }
  156. },
  157. 'update': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  158. me._onUpdateGroups(params.items);
  159. },
  160. 'remove': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  161. me._onRemoveGroups(params.items);
  162. }
  163. };
  164. this.items = {}; // object with an Item for every data item
  165. this.groups = {}; // Group object for every group
  166. this.groupIds = [];
  167. this.selection = []; // list with the ids of all selected nodes
  168. this.popup = null;
  169. this.touchParams = {}; // stores properties while dragging
  170. this.groupTouchParams = {};
  171. // create the HTML DOM
  172. this._create();
  173. this.setOptions(options);
  174. }
  175. ItemSet.prototype = new Component();
  176. // available item types will be registered here
  177. ItemSet.types = {
  178. background: BackgroundItem,
  179. box: BoxItem,
  180. range: RangeItem,
  181. point: PointItem
  182. };
  183. /**
  184. * Create the HTML DOM for the ItemSet
  185. */
  186. ItemSet.prototype._create = function(){
  187. var frame = document.createElement('div');
  188. frame.className = 'vis-itemset';
  189. frame['timeline-itemset'] = this;
  190. this.dom.frame = frame;
  191. // create background panel
  192. var background = document.createElement('div');
  193. background.className = 'vis-background';
  194. frame.appendChild(background);
  195. this.dom.background = background;
  196. // create foreground panel
  197. var foreground = document.createElement('div');
  198. foreground.className = 'vis-foreground';
  199. frame.appendChild(foreground);
  200. this.dom.foreground = foreground;
  201. // create axis panel
  202. var axis = document.createElement('div');
  203. axis.className = 'vis-axis';
  204. this.dom.axis = axis;
  205. // create labelset
  206. var labelSet = document.createElement('div');
  207. labelSet.className = 'vis-labelset';
  208. this.dom.labelSet = labelSet;
  209. // create ungrouped Group
  210. this._updateUngrouped();
  211. // create background Group
  212. var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this);
  213. backgroundGroup.show();
  214. this.groups[BACKGROUND] = backgroundGroup;
  215. // attach event listeners
  216. // Note: we bind to the centerContainer for the case where the height
  217. // of the center container is larger than of the ItemSet, so we
  218. // can click in the empty area to create a new item or deselect an item.
  219. this.hammer = new Hammer(this.body.dom.centerContainer);
  220. // drag items when selected
  221. this.hammer.on('hammer.input', function (event) {
  222. if (event.isFirst) {
  223. this._onTouch(event);
  224. }
  225. }.bind(this));
  226. this.hammer.on('panstart', this._onDragStart.bind(this));
  227. this.hammer.on('panmove', this._onDrag.bind(this));
  228. this.hammer.on('panend', this._onDragEnd.bind(this));
  229. this.hammer.get('pan').set({threshold:5, direction: Hammer.DIRECTION_HORIZONTAL});
  230. // single select (or unselect) when tapping an item
  231. this.hammer.on('tap', this._onSelectItem.bind(this));
  232. // multi select when holding mouse/touch, or on ctrl+click
  233. this.hammer.on('press', this._onMultiSelectItem.bind(this));
  234. // add item on doubletap
  235. this.hammer.on('doubletap', this._onAddItem.bind(this));
  236. if (this.options.rtl) {
  237. this.groupHammer = new Hammer(this.body.dom.rightContainer);
  238. } else {
  239. this.groupHammer = new Hammer(this.body.dom.leftContainer);
  240. }
  241. this.groupHammer.on('tap', this._onGroupClick.bind(this));
  242. this.groupHammer.on('panstart', this._onGroupDragStart.bind(this));
  243. this.groupHammer.on('panmove', this._onGroupDrag.bind(this));
  244. this.groupHammer.on('panend', this._onGroupDragEnd.bind(this));
  245. this.groupHammer.get('pan').set({threshold:5, direction: Hammer.DIRECTION_VERTICAL});
  246. this.body.dom.centerContainer.addEventListener('mouseover', this._onMouseOver.bind(this));
  247. this.body.dom.centerContainer.addEventListener('mouseout', this._onMouseOut.bind(this));
  248. this.body.dom.centerContainer.addEventListener('mousemove', this._onMouseMove.bind(this));
  249. // right-click on timeline
  250. this.body.dom.centerContainer.addEventListener('contextmenu', this._onDragEnd.bind(this));
  251. this.body.dom.centerContainer.addEventListener('mousewheel', this._onMouseWheel.bind(this));
  252. // attach to the DOM
  253. this.show();
  254. };
  255. /**
  256. * Set options for the ItemSet. Existing options will be extended/overwritten.
  257. * @param {Object} [options] The following options are available:
  258. * {string} type
  259. * Default type for the items. Choose from 'box'
  260. * (default), 'point', 'range', or 'background'.
  261. * The default style can be overwritten by
  262. * individual items.
  263. * {string} align
  264. * Alignment for the items, only applicable for
  265. * BoxItem. Choose 'center' (default), 'left', or
  266. * 'right'.
  267. * {string} orientation.item
  268. * Orientation of the item set. Choose 'top' or
  269. * 'bottom' (default).
  270. * {Function} groupOrder
  271. * A sorting function for ordering groups
  272. * {boolean} stack
  273. * If true (default), items will be stacked on
  274. * top of each other.
  275. * {number} margin.axis
  276. * Margin between the axis and the items in pixels.
  277. * Default is 20.
  278. * {number} margin.item.horizontal
  279. * Horizontal margin between items in pixels.
  280. * Default is 10.
  281. * {number} margin.item.vertical
  282. * Vertical Margin between items in pixels.
  283. * Default is 10.
  284. * {number} margin.item
  285. * Margin between items in pixels in both horizontal
  286. * and vertical direction. Default is 10.
  287. * {number} margin
  288. * Set margin for both axis and items in pixels.
  289. * {boolean} selectable
  290. * If true (default), items can be selected.
  291. * {boolean} multiselect
  292. * If true, multiple items can be selected.
  293. * False by default.
  294. * {boolean} editable
  295. * Set all editable options to true or false
  296. * {boolean} editable.updateTime
  297. * Allow dragging an item to an other moment in time
  298. * {boolean} editable.updateGroup
  299. * Allow dragging an item to an other group
  300. * {boolean} editable.add
  301. * Allow creating new items on double tap
  302. * {boolean} editable.remove
  303. * Allow removing items by clicking the delete button
  304. * top right of a selected item.
  305. * {Function(item: Item, callback: Function)} onAdd
  306. * Callback function triggered when an item is about to be added:
  307. * when the user double taps an empty space in the Timeline.
  308. * {Function(item: Item, callback: Function)} onUpdate
  309. * Callback function fired when an item is about to be updated.
  310. * This function typically has to show a dialog where the user
  311. * change the item. If not implemented, nothing happens.
  312. * {Function(item: Item, callback: Function)} onMove
  313. * Fired when an item has been moved. If not implemented,
  314. * the move action will be accepted.
  315. * {Function(item: Item, callback: Function)} onRemove
  316. * Fired when an item is about to be deleted.
  317. * If not implemented, the item will be always removed.
  318. */
  319. ItemSet.prototype.setOptions = function(options) {
  320. if (options) {
  321. // copy all options that we know
  322. var fields = [
  323. 'type', 'rtl', 'align', 'order', 'stack', 'stackSubgroups', 'selectable', 'multiselect',
  324. 'multiselectPerGroup', 'groupOrder', 'dataAttributes', 'template', 'groupTemplate', 'visibleFrameTemplate',
  325. 'hide', 'snap', 'groupOrderSwap', 'showTooltips', 'tooltip', 'tooltipOnItemUpdateTime'
  326. ];
  327. util.selectiveExtend(fields, this.options, options);
  328. if ('itemsAlwaysDraggable' in options) {
  329. if (typeof options.itemsAlwaysDraggable === 'boolean') {
  330. this.options.itemsAlwaysDraggable.item = options.itemsAlwaysDraggable;
  331. this.options.itemsAlwaysDraggable.range = false;
  332. }
  333. else if (typeof options.itemsAlwaysDraggable === 'object') {
  334. util.selectiveExtend(['item', 'range'], this.options.itemsAlwaysDraggable, options.itemsAlwaysDraggable);
  335. // only allow range always draggable when item is always draggable as well
  336. if (! this.options.itemsAlwaysDraggable.item) {
  337. this.options.itemsAlwaysDraggable.range = false;
  338. }
  339. }
  340. }
  341. if ('orientation' in options) {
  342. if (typeof options.orientation === 'string') {
  343. this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom';
  344. }
  345. else if (typeof options.orientation === 'object' && 'item' in options.orientation) {
  346. this.options.orientation.item = options.orientation.item;
  347. }
  348. }
  349. if ('margin' in options) {
  350. if (typeof options.margin === 'number') {
  351. this.options.margin.axis = options.margin;
  352. this.options.margin.item.horizontal = options.margin;
  353. this.options.margin.item.vertical = options.margin;
  354. }
  355. else if (typeof options.margin === 'object') {
  356. util.selectiveExtend(['axis'], this.options.margin, options.margin);
  357. if ('item' in options.margin) {
  358. if (typeof options.margin.item === 'number') {
  359. this.options.margin.item.horizontal = options.margin.item;
  360. this.options.margin.item.vertical = options.margin.item;
  361. }
  362. else if (typeof options.margin.item === 'object') {
  363. util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
  364. }
  365. }
  366. }
  367. }
  368. if ('editable' in options) {
  369. if (typeof options.editable === 'boolean') {
  370. this.options.editable.updateTime = options.editable;
  371. this.options.editable.updateGroup = options.editable;
  372. this.options.editable.add = options.editable;
  373. this.options.editable.remove = options.editable;
  374. this.options.editable.overrideItems = false;
  375. }
  376. else if (typeof options.editable === 'object') {
  377. util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove', 'overrideItems'], this.options.editable, options.editable);
  378. }
  379. }
  380. if ('groupEditable' in options) {
  381. if (typeof options.groupEditable === 'boolean') {
  382. this.options.groupEditable.order = options.groupEditable;
  383. this.options.groupEditable.add = options.groupEditable;
  384. this.options.groupEditable.remove = options.groupEditable;
  385. }
  386. else if (typeof options.groupEditable === 'object') {
  387. util.selectiveExtend(['order', 'add', 'remove'], this.options.groupEditable, options.groupEditable);
  388. }
  389. }
  390. // callback functions
  391. var addCallback = (function (name) {
  392. var fn = options[name];
  393. if (fn) {
  394. if (!(fn instanceof Function)) {
  395. throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
  396. }
  397. this.options[name] = fn;
  398. }
  399. }).bind(this);
  400. ['onDropObjectOnItem', 'onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving', 'onAddGroup', 'onMoveGroup', 'onRemoveGroup'].forEach(addCallback);
  401. // force the itemSet to refresh: options like orientation and margins may be changed
  402. this.markDirty();
  403. }
  404. };
  405. /**
  406. * Mark the ItemSet dirty so it will refresh everything with next redraw.
  407. * Optionally, all items can be marked as dirty and be refreshed.
  408. * @param {{refreshItems: boolean}} [options]
  409. */
  410. ItemSet.prototype.markDirty = function(options) {
  411. this.groupIds = [];
  412. if (options && options.refreshItems) {
  413. util.forEach(this.items, function (item) {
  414. item.dirty = true;
  415. if (item.displayed) item.redraw();
  416. });
  417. }
  418. };
  419. /**
  420. * Destroy the ItemSet
  421. */
  422. ItemSet.prototype.destroy = function() {
  423. this.hide();
  424. this.setItems(null);
  425. this.setGroups(null);
  426. this.hammer = null;
  427. this.body = null;
  428. this.conversion = null;
  429. };
  430. /**
  431. * Hide the component from the DOM
  432. */
  433. ItemSet.prototype.hide = function() {
  434. // remove the frame containing the items
  435. if (this.dom.frame.parentNode) {
  436. this.dom.frame.parentNode.removeChild(this.dom.frame);
  437. }
  438. // remove the axis with dots
  439. if (this.dom.axis.parentNode) {
  440. this.dom.axis.parentNode.removeChild(this.dom.axis);
  441. }
  442. // remove the labelset containing all group labels
  443. if (this.dom.labelSet.parentNode) {
  444. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  445. }
  446. };
  447. /**
  448. * Show the component in the DOM (when not already visible).
  449. */
  450. ItemSet.prototype.show = function() {
  451. // show frame containing the items
  452. if (!this.dom.frame.parentNode) {
  453. this.body.dom.center.appendChild(this.dom.frame);
  454. }
  455. // show axis with dots
  456. if (!this.dom.axis.parentNode) {
  457. this.body.dom.backgroundVertical.appendChild(this.dom.axis);
  458. }
  459. // show labelset containing labels
  460. if (!this.dom.labelSet.parentNode) {
  461. if (this.options.rtl) {
  462. this.body.dom.right.appendChild(this.dom.labelSet);
  463. } else {
  464. this.body.dom.left.appendChild(this.dom.labelSet);
  465. }
  466. }
  467. };
  468. /**
  469. * Set selected items by their id. Replaces the current selection
  470. * Unknown id's are silently ignored.
  471. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  472. * selected, or a single item id. If ids is undefined
  473. * or an empty array, all items will be unselected.
  474. */
  475. ItemSet.prototype.setSelection = function(ids) {
  476. var i, ii, id, item;
  477. if (ids == undefined) ids = [];
  478. if (!Array.isArray(ids)) ids = [ids];
  479. // unselect currently selected items
  480. for (i = 0, ii = this.selection.length; i < ii; i++) {
  481. id = this.selection[i];
  482. item = this.items[id];
  483. if (item) item.unselect();
  484. }
  485. // select items
  486. this.selection = [];
  487. for (i = 0, ii = ids.length; i < ii; i++) {
  488. id = ids[i];
  489. item = this.items[id];
  490. if (item) {
  491. this.selection.push(id);
  492. item.select();
  493. }
  494. }
  495. };
  496. /**
  497. * Get the selected items by their id
  498. * @return {Array} ids The ids of the selected items
  499. */
  500. ItemSet.prototype.getSelection = function() {
  501. return this.selection.concat([]);
  502. };
  503. /**
  504. * Get the id's of the currently visible items.
  505. * @returns {Array} The ids of the visible items
  506. */
  507. ItemSet.prototype.getVisibleItems = function() {
  508. var range = this.body.range.getRange();
  509. var right, left;
  510. if (this.options.rtl) {
  511. right = this.body.util.toScreen(range.start);
  512. left = this.body.util.toScreen(range.end);
  513. } else {
  514. left = this.body.util.toScreen(range.start);
  515. right = this.body.util.toScreen(range.end);
  516. }
  517. var ids = [];
  518. for (var groupId in this.groups) {
  519. if (this.groups.hasOwnProperty(groupId)) {
  520. var group = this.groups[groupId];
  521. var rawVisibleItems = group.isVisible ? group.visibleItems : [];
  522. // filter the "raw" set with visibleItems into a set which is really
  523. // visible by pixels
  524. for (var i = 0; i < rawVisibleItems.length; i++) {
  525. var item = rawVisibleItems[i];
  526. // TODO: also check whether visible vertically
  527. if (this.options.rtl) {
  528. if ((item.right < left) && (item.right + item.width > right)) {
  529. ids.push(item.id);
  530. }
  531. } else {
  532. if ((item.left < right) && (item.left + item.width > left)) {
  533. ids.push(item.id);
  534. }
  535. }
  536. }
  537. }
  538. }
  539. return ids;
  540. };
  541. /**
  542. * Deselect a selected item
  543. * @param {string | number} id
  544. * @private
  545. */
  546. ItemSet.prototype._deselect = function(id) {
  547. var selection = this.selection;
  548. for (var i = 0, ii = selection.length; i < ii; i++) {
  549. if (selection[i] == id) { // non-strict comparison!
  550. selection.splice(i, 1);
  551. break;
  552. }
  553. }
  554. };
  555. /**
  556. * Repaint the component
  557. * @return {boolean} Returns true if the component is resized
  558. */
  559. ItemSet.prototype.redraw = function() {
  560. var margin = this.options.margin,
  561. range = this.body.range,
  562. asSize = util.option.asSize,
  563. options = this.options,
  564. orientation = options.orientation.item,
  565. resized = false,
  566. frame = this.dom.frame;
  567. // recalculate absolute position (before redrawing groups)
  568. this.props.top = this.body.domProps.top.height + this.body.domProps.border.top;
  569. if (this.options.rtl) {
  570. this.props.right = this.body.domProps.right.width + this.body.domProps.border.right;
  571. } else {
  572. this.props.left = this.body.domProps.left.width + this.body.domProps.border.left;
  573. }
  574. // update class name
  575. frame.className = 'vis-itemset';
  576. // reorder the groups (if needed)
  577. resized = this._orderGroups() || resized;
  578. // check whether zoomed (in that case we need to re-stack everything)
  579. // TODO: would be nicer to get this as a trigger from Range
  580. var visibleInterval = range.end - range.start;
  581. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth);
  582. var scrolled = range.start != this.lastRangeStart;
  583. var changedStackOption = options.stack != this.lastStack;
  584. var changedStackSubgroupsOption = options.stackSubgroups != this.lastStackSubgroups;
  585. var forceRestack = (zoomed || scrolled || changedStackOption || changedStackSubgroupsOption);
  586. this.lastVisibleInterval = visibleInterval;
  587. this.lastRangeStart = range.start;
  588. this.lastStack = options.stack;
  589. this.lastStackSubgroups = options.stackSubgroups;
  590. this.props.lastWidth = this.props.width;
  591. var firstGroup = this._firstGroup();
  592. var firstMargin = {
  593. item: margin.item,
  594. axis: margin.axis
  595. };
  596. var nonFirstMargin = {
  597. item: margin.item,
  598. axis: margin.item.vertical / 2
  599. };
  600. var height = 0;
  601. var minHeight = margin.axis + margin.item.vertical;
  602. // redraw the background group
  603. this.groups[BACKGROUND].redraw(range, nonFirstMargin, forceRestack);
  604. var redrawQueue = {};
  605. var redrawQueueLength = 0;
  606. // collect redraw functions
  607. util.forEach(this.groups, function (group, key) {
  608. if (key === BACKGROUND) return;
  609. var groupMargin = group == firstGroup ? firstMargin : nonFirstMargin;
  610. var returnQueue = true;
  611. redrawQueue[key] = group.redraw(range, groupMargin, forceRestack, returnQueue);
  612. redrawQueueLength = redrawQueue[key].length;
  613. });
  614. var needRedraw = redrawQueueLength > 0;
  615. if (needRedraw) {
  616. var redrawResults = {};
  617. for (var i = 0; i < redrawQueueLength; i++) {
  618. util.forEach(redrawQueue, function (fns, key) {
  619. redrawResults[key] = fns[i]();
  620. });
  621. }
  622. // redraw all regular groups
  623. util.forEach(this.groups, function (group, key) {
  624. if (key === BACKGROUND) return;
  625. var groupResized = redrawResults[key];
  626. resized = groupResized || resized;
  627. height += group.height;
  628. });
  629. height = Math.max(height, minHeight);
  630. }
  631. height = Math.max(height, minHeight);
  632. // update frame height
  633. frame.style.height = asSize(height);
  634. // calculate actual size
  635. this.props.width = frame.offsetWidth;
  636. this.props.height = height;
  637. // reposition axis
  638. this.dom.axis.style.top = asSize((orientation == 'top') ?
  639. (this.body.domProps.top.height + this.body.domProps.border.top) :
  640. (this.body.domProps.top.height + this.body.domProps.centerContainer.height));
  641. if (this.options.rtl) {
  642. this.dom.axis.style.right = '0';
  643. } else {
  644. this.dom.axis.style.left = '0';
  645. }
  646. this.initialItemSetDrawn = true;
  647. // check if this component is resized
  648. resized = this._isResized() || resized;
  649. return resized;
  650. };
  651. /**
  652. * Get the first group, aligned with the axis
  653. * @return {Group | null} firstGroup
  654. * @private
  655. */
  656. ItemSet.prototype._firstGroup = function() {
  657. var firstGroupIndex = (this.options.orientation.item == 'top') ? 0 : (this.groupIds.length - 1);
  658. var firstGroupId = this.groupIds[firstGroupIndex];
  659. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  660. return firstGroup || null;
  661. };
  662. /**
  663. * Create or delete the group holding all ungrouped items. This group is used when
  664. * there are no groups specified.
  665. * @protected
  666. */
  667. ItemSet.prototype._updateUngrouped = function() {
  668. var ungrouped = this.groups[UNGROUPED];
  669. var item, itemId;
  670. if (this.groupsData) {
  671. // remove the group holding all ungrouped items
  672. if (ungrouped) {
  673. ungrouped.hide();
  674. delete this.groups[UNGROUPED];
  675. for (itemId in this.items) {
  676. if (this.items.hasOwnProperty(itemId)) {
  677. item = this.items[itemId];
  678. item.parent && item.parent.remove(item);
  679. var groupId = this._getGroupId(item.data);
  680. var group = this.groups[groupId];
  681. group && group.add(item) || item.hide();
  682. }
  683. }
  684. }
  685. }
  686. else {
  687. // create a group holding all (unfiltered) items
  688. if (!ungrouped) {
  689. var id = null;
  690. var data = null;
  691. ungrouped = new Group(id, data, this);
  692. this.groups[UNGROUPED] = ungrouped;
  693. for (itemId in this.items) {
  694. if (this.items.hasOwnProperty(itemId)) {
  695. item = this.items[itemId];
  696. ungrouped.add(item);
  697. }
  698. }
  699. ungrouped.show();
  700. }
  701. }
  702. };
  703. /**
  704. * Get the element for the labelset
  705. * @return {HTMLElement} labelSet
  706. */
  707. ItemSet.prototype.getLabelSet = function() {
  708. return this.dom.labelSet;
  709. };
  710. /**
  711. * Set items
  712. * @param {vis.DataSet | null} items
  713. */
  714. ItemSet.prototype.setItems = function(items) {
  715. var me = this,
  716. ids,
  717. oldItemsData = this.itemsData;
  718. // replace the dataset
  719. if (!items) {
  720. this.itemsData = null;
  721. }
  722. else if (items instanceof DataSet || items instanceof DataView) {
  723. this.itemsData = items;
  724. }
  725. else {
  726. throw new TypeError('Data must be an instance of DataSet or DataView');
  727. }
  728. if (oldItemsData) {
  729. // unsubscribe from old dataset
  730. util.forEach(this.itemListeners, function (callback, event) {
  731. oldItemsData.off(event, callback);
  732. });
  733. // remove all drawn items
  734. ids = oldItemsData.getIds();
  735. this._onRemove(ids);
  736. }
  737. if (this.itemsData) {
  738. // subscribe to new dataset
  739. var id = this.id;
  740. util.forEach(this.itemListeners, function (callback, event) {
  741. me.itemsData.on(event, callback, id);
  742. });
  743. // add all new items
  744. ids = this.itemsData.getIds();
  745. this._onAdd(ids);
  746. // update the group holding all ungrouped items
  747. this._updateUngrouped();
  748. }
  749. this.body.emitter.emit('_change', {queue: true});
  750. };
  751. /**
  752. * Get the current items
  753. * @returns {vis.DataSet | null}
  754. */
  755. ItemSet.prototype.getItems = function() {
  756. return this.itemsData;
  757. };
  758. /**
  759. * Set groups
  760. * @param {vis.DataSet} groups
  761. */
  762. ItemSet.prototype.setGroups = function(groups) {
  763. var me = this,
  764. ids;
  765. // unsubscribe from current dataset
  766. if (this.groupsData) {
  767. util.forEach(this.groupListeners, function (callback, event) {
  768. me.groupsData.off(event, callback);
  769. });
  770. // remove all drawn groups
  771. ids = this.groupsData.getIds();
  772. this.groupsData = null;
  773. this._onRemoveGroups(ids); // note: this will cause a redraw
  774. }
  775. // replace the dataset
  776. if (!groups) {
  777. this.groupsData = null;
  778. }
  779. else if (groups instanceof DataSet || groups instanceof DataView) {
  780. this.groupsData = groups;
  781. }
  782. else {
  783. throw new TypeError('Data must be an instance of DataSet or DataView');
  784. }
  785. if (this.groupsData) {
  786. // go over all groups nesting
  787. var groupsData = this.groupsData;
  788. if (this.groupsData instanceof DataView) {
  789. groupsData = this.groupsData.getDataSet()
  790. }
  791. groupsData.get().forEach(function(group){
  792. if (group.nestedGroups) {
  793. group.nestedGroups.forEach(function(nestedGroupId) {
  794. var updatedNestedGroup = groupsData.get(nestedGroupId);
  795. updatedNestedGroup.nestedInGroup = group.id;
  796. if (group.showNested == false) {
  797. updatedNestedGroup.visible = false;
  798. }
  799. groupsData.update(updatedNestedGroup);
  800. })
  801. }
  802. });
  803. // subscribe to new dataset
  804. var id = this.id;
  805. util.forEach(this.groupListeners, function (callback, event) {
  806. me.groupsData.on(event, callback, id);
  807. });
  808. // draw all ms
  809. ids = this.groupsData.getIds();
  810. this._onAddGroups(ids);
  811. }
  812. // update the group holding all ungrouped items
  813. this._updateUngrouped();
  814. // update the order of all items in each group
  815. this._order();
  816. this.body.emitter.emit('_change', {queue: true});
  817. };
  818. /**
  819. * Get the current groups
  820. * @returns {vis.DataSet | null} groups
  821. */
  822. ItemSet.prototype.getGroups = function() {
  823. return this.groupsData;
  824. };
  825. /**
  826. * Remove an item by its id
  827. * @param {string | number} id
  828. */
  829. ItemSet.prototype.removeItem = function(id) {
  830. var item = this.itemsData.get(id),
  831. dataset = this.itemsData.getDataSet();
  832. if (item) {
  833. // confirm deletion
  834. this.options.onRemove(item, function (item) {
  835. if (item) {
  836. // remove by id here, it is possible that an item has no id defined
  837. // itself, so better not delete by the item itself
  838. dataset.remove(id);
  839. }
  840. });
  841. }
  842. };
  843. /**
  844. * Get the time of an item based on it's data and options.type
  845. * @param {Object} itemData
  846. * @returns {string} Returns the type
  847. * @private
  848. */
  849. ItemSet.prototype._getType = function (itemData) {
  850. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  851. };
  852. /**
  853. * Get the group id for an item
  854. * @param {Object} itemData
  855. * @returns {string} Returns the groupId
  856. * @private
  857. */
  858. ItemSet.prototype._getGroupId = function (itemData) {
  859. var type = this._getType(itemData);
  860. if (type == 'background' && itemData.group == undefined) {
  861. return BACKGROUND;
  862. }
  863. else {
  864. return this.groupsData ? itemData.group : UNGROUPED;
  865. }
  866. };
  867. /**
  868. * Handle updated items
  869. * @param {number[]} ids
  870. * @protected
  871. */
  872. ItemSet.prototype._onUpdate = function(ids) {
  873. var me = this;
  874. ids.forEach(function (id) {
  875. var itemData = me.itemsData.get(id, me.itemOptions);
  876. var item = me.items[id];
  877. var type = itemData ? me._getType(itemData) : null;
  878. var constructor = ItemSet.types[type];
  879. var selected;
  880. if (item) {
  881. // update item
  882. if (!constructor || !(item instanceof constructor)) {
  883. // item type has changed, delete the item and recreate it
  884. selected = item.selected; // preserve selection of this item
  885. me._removeItem(item);
  886. item = null;
  887. }
  888. else {
  889. me._updateItem(item, itemData);
  890. }
  891. }
  892. if (!item && itemData) {
  893. // create item
  894. if (constructor) {
  895. item = new constructor(itemData, me.conversion, me.options);
  896. item.id = id; // TODO: not so nice setting id afterwards
  897. me._addItem(item);
  898. if (selected) {
  899. this.selection.push(id);
  900. item.select();
  901. }
  902. }
  903. else if (type == 'rangeoverflow') {
  904. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  905. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
  906. '.vis-item.vis-range .vis-item-content {overflow: visible;}');
  907. }
  908. else {
  909. throw new TypeError('Unknown item type "' + type + '"');
  910. }
  911. }
  912. }.bind(this));
  913. this._order();
  914. this.body.emitter.emit('_change', {queue: true});
  915. };
  916. /**
  917. * Handle added items
  918. * @param {number[]} ids
  919. * @protected
  920. */
  921. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  922. /**
  923. * Handle removed items
  924. * @param {number[]} ids
  925. * @protected
  926. */
  927. ItemSet.prototype._onRemove = function(ids) {
  928. var count = 0;
  929. var me = this;
  930. ids.forEach(function (id) {
  931. var item = me.items[id];
  932. if (item) {
  933. count++;
  934. me._removeItem(item);
  935. }
  936. });
  937. if (count) {
  938. // update order
  939. this._order();
  940. this.body.emitter.emit('_change', {queue: true});
  941. }
  942. };
  943. /**
  944. * Update the order of item in all groups
  945. * @private
  946. */
  947. ItemSet.prototype._order = function() {
  948. // reorder the items in all groups
  949. // TODO: optimization: only reorder groups affected by the changed items
  950. util.forEach(this.groups, function (group) {
  951. group.order();
  952. });
  953. };
  954. /**
  955. * Handle updated groups
  956. * @param {number[]} ids
  957. * @private
  958. */
  959. ItemSet.prototype._onUpdateGroups = function(ids) {
  960. this._onAddGroups(ids);
  961. };
  962. /**
  963. * Handle changed groups (added or updated)
  964. * @param {number[]} ids
  965. * @private
  966. */
  967. ItemSet.prototype._onAddGroups = function(ids) {
  968. var me = this;
  969. ids.forEach(function (id) {
  970. var groupData = me.groupsData.get(id);
  971. var group = me.groups[id];
  972. if (!group) {
  973. // check for reserved ids
  974. if (id == UNGROUPED || id == BACKGROUND) {
  975. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  976. }
  977. var groupOptions = Object.create(me.options);
  978. util.extend(groupOptions, {
  979. height: null
  980. });
  981. group = new Group(id, groupData, me);
  982. me.groups[id] = group;
  983. // add items with this groupId to the new group
  984. for (var itemId in me.items) {
  985. if (me.items.hasOwnProperty(itemId)) {
  986. var item = me.items[itemId];
  987. if (item.data.group == id) {
  988. group.add(item);
  989. }
  990. }
  991. }
  992. group.order();
  993. group.show();
  994. }
  995. else {
  996. // update group
  997. group.setData(groupData);
  998. }
  999. });
  1000. this.body.emitter.emit('_change', {queue: true});
  1001. };
  1002. /**
  1003. * Handle removed groups
  1004. * @param {number[]} ids
  1005. * @private
  1006. */
  1007. ItemSet.prototype._onRemoveGroups = function(ids) {
  1008. var groups = this.groups;
  1009. ids.forEach(function (id) {
  1010. var group = groups[id];
  1011. if (group) {
  1012. group.hide();
  1013. delete groups[id];
  1014. }
  1015. });
  1016. this.markDirty();
  1017. this.body.emitter.emit('_change', {queue: true});
  1018. };
  1019. /**
  1020. * Reorder the groups if needed
  1021. * @return {boolean} changed
  1022. * @private
  1023. */
  1024. ItemSet.prototype._orderGroups = function () {
  1025. if (this.groupsData) {
  1026. // reorder the groups
  1027. var groupIds = this.groupsData.getIds({
  1028. order: this.options.groupOrder
  1029. });
  1030. groupIds = this._orderNestedGroups(groupIds);
  1031. var changed = !util.equalArray(groupIds, this.groupIds);
  1032. if (changed) {
  1033. // hide all groups, removes them from the DOM
  1034. var groups = this.groups;
  1035. groupIds.forEach(function (groupId) {
  1036. groups[groupId].hide();
  1037. });
  1038. // show the groups again, attach them to the DOM in correct order
  1039. groupIds.forEach(function (groupId) {
  1040. groups[groupId].show();
  1041. });
  1042. this.groupIds = groupIds;
  1043. }
  1044. return changed;
  1045. }
  1046. else {
  1047. return false;
  1048. }
  1049. };
  1050. /**
  1051. * Reorder the nested groups
  1052. *
  1053. * @param {Array.<number>} groupIds
  1054. * @returns {Array.<number>}
  1055. * @private
  1056. */
  1057. ItemSet.prototype._orderNestedGroups = function(groupIds) {
  1058. var newGroupIdsOrder = [];
  1059. groupIds.forEach(function(groupId){
  1060. var groupData = this.groupsData.get(groupId);
  1061. if (!groupData.nestedInGroup) {
  1062. newGroupIdsOrder.push(groupId)
  1063. }
  1064. if (groupData.nestedGroups) {
  1065. var nestedGroups = this.groupsData.get({
  1066. filter: function(nestedGroup) {
  1067. return nestedGroup.nestedInGroup == groupId;
  1068. },
  1069. order: this.options.groupOrder
  1070. });
  1071. var nestedGroupIds = nestedGroups.map(function(nestedGroup) { return nestedGroup.id });
  1072. newGroupIdsOrder = newGroupIdsOrder.concat(nestedGroupIds);
  1073. }
  1074. }, this);
  1075. return newGroupIdsOrder;
  1076. };
  1077. /**
  1078. * Add a new item
  1079. * @param {Item} item
  1080. * @private
  1081. */
  1082. ItemSet.prototype._addItem = function(item) {
  1083. this.items[item.id] = item;
  1084. // add to group
  1085. var groupId = this._getGroupId(item.data);
  1086. var group = this.groups[groupId];
  1087. if (!group) {
  1088. item.groupShowing = false;
  1089. } else if (group && group.data && group.data.showNested) {
  1090. item.groupShowing = true;
  1091. }
  1092. if (group) group.add(item);
  1093. };
  1094. /**
  1095. * Update an existing item
  1096. * @param {Item} item
  1097. * @param {Object} itemData
  1098. * @private
  1099. */
  1100. ItemSet.prototype._updateItem = function(item, itemData) {
  1101. // update the items data (will redraw the item when displayed)
  1102. item.setData(itemData);
  1103. var groupId = this._getGroupId(item.data);
  1104. var group = this.groups[groupId];
  1105. if (!group) {
  1106. item.groupShowing = false;
  1107. } else if (group && group.data && group.data.showNested) {
  1108. item.groupShowing = true;
  1109. }
  1110. };
  1111. /**
  1112. * Delete an item from the ItemSet: remove it from the DOM, from the map
  1113. * with items, and from the map with visible items, and from the selection
  1114. * @param {Item} item
  1115. * @private
  1116. */
  1117. ItemSet.prototype._removeItem = function(item) {
  1118. // remove from DOM
  1119. item.hide();
  1120. // remove from items
  1121. delete this.items[item.id];
  1122. // remove from selection
  1123. var index = this.selection.indexOf(item.id);
  1124. if (index != -1) this.selection.splice(index, 1);
  1125. // remove from group
  1126. item.parent && item.parent.remove(item);
  1127. };
  1128. /**
  1129. * Create an array containing all items being a range (having an end date)
  1130. * @param {Array.<Object>} array
  1131. * @returns {Array}
  1132. * @private
  1133. */
  1134. ItemSet.prototype._constructByEndArray = function(array) {
  1135. var endArray = [];
  1136. for (var i = 0; i < array.length; i++) {
  1137. if (array[i] instanceof RangeItem) {
  1138. endArray.push(array[i]);
  1139. }
  1140. }
  1141. return endArray;
  1142. };
  1143. /**
  1144. * Register the clicked item on touch, before dragStart is initiated.
  1145. *
  1146. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  1147. * already moving. Therefore, the mouse/touch can sometimes be above an other
  1148. * DOM element than the item itself.
  1149. *
  1150. * @param {Event} event
  1151. * @private
  1152. */
  1153. ItemSet.prototype._onTouch = function (event) {
  1154. // store the touched item, used in _onDragStart
  1155. this.touchParams.item = this.itemFromTarget(event);
  1156. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  1157. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  1158. this.touchParams.itemProps = null;
  1159. };
  1160. /**
  1161. * Given an group id, returns the index it has.
  1162. *
  1163. * @param {number} groupId
  1164. * @returns {number} index / groupId
  1165. * @private
  1166. */
  1167. ItemSet.prototype._getGroupIndex = function(groupId) {
  1168. for (var i = 0; i < this.groupIds.length; i++) {
  1169. if (groupId == this.groupIds[i])
  1170. return i;
  1171. }
  1172. };
  1173. /**
  1174. * Start dragging the selected events
  1175. * @param {Event} event
  1176. * @private
  1177. */
  1178. ItemSet.prototype._onDragStart = function (event) {
  1179. if (this.touchParams.itemIsDragging) { return; }
  1180. var item = this.touchParams.item || null;
  1181. var me = this;
  1182. var props;
  1183. if (item && (item.selected || this.options.itemsAlwaysDraggable.item)) {
  1184. if (this.options.editable.overrideItems &&
  1185. !this.options.editable.updateTime &&
  1186. !this.options.editable.updateGroup) {
  1187. return;
  1188. }
  1189. // override options.editable
  1190. if ((item.editable != null && !item.editable.updateTime && !item.editable.updateGroup)
  1191. && !this.options.editable.overrideItems) {
  1192. return;
  1193. }
  1194. var dragLeftItem = this.touchParams.dragLeftItem;
  1195. var dragRightItem = this.touchParams.dragRightItem;
  1196. this.touchParams.itemIsDragging = true;
  1197. this.touchParams.selectedItem = item;
  1198. if (dragLeftItem) {
  1199. props = {
  1200. item: dragLeftItem,
  1201. initialX: event.center.x,
  1202. dragLeft: true,
  1203. data: this._cloneItemData(item.data)
  1204. };
  1205. this.touchParams.itemProps = [props];
  1206. } else if (dragRightItem) {
  1207. props = {
  1208. item: dragRightItem,
  1209. initialX: event.center.x,
  1210. dragRight: true,
  1211. data: this._cloneItemData(item.data)
  1212. };
  1213. this.touchParams.itemProps = [props];
  1214. } else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1215. // create a new range item when dragging with ctrl key down
  1216. this._onDragStartAddItem(event);
  1217. } else {
  1218. if(this.groupIds.length < 1) {
  1219. // Mitigates a race condition if _onDragStart() is
  1220. // called after markDirty() without redraw() being called between.
  1221. this.redraw();
  1222. }
  1223. var baseGroupIndex = this._getGroupIndex(item.data.group);
  1224. var itemsToDrag = (this.options.itemsAlwaysDraggable.item && !item.selected) ? [item.id] : this.getSelection();
  1225. this.touchParams.itemProps = itemsToDrag.map(function (id) {
  1226. var item = me.items[id];
  1227. var groupIndex = me._getGroupIndex(item.data.group);
  1228. return {
  1229. item: item,
  1230. initialX: event.center.x,
  1231. groupOffset: baseGroupIndex-groupIndex,
  1232. data: this._cloneItemData(item.data)
  1233. };
  1234. }.bind(this));
  1235. }
  1236. event.stopPropagation();
  1237. } else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  1238. // create a new range item when dragging with ctrl key down
  1239. this._onDragStartAddItem(event);
  1240. }
  1241. };
  1242. /**
  1243. * Start creating a new range item by dragging.
  1244. * @param {Event} event
  1245. * @private
  1246. */
  1247. ItemSet.prototype._onDragStartAddItem = function (event) {
  1248. var xAbs;
  1249. var x;
  1250. var snap = this.options.snap || null;
  1251. if (this.options.rtl) {
  1252. xAbs = util.getAbsoluteRight(this.dom.frame);
  1253. x = xAbs - event.center.x + 10; // plus 10 to compensate for the drag starting as soon as you've moved 10px
  1254. } else {
  1255. xAbs = util.getAbsoluteLeft(this.dom.frame);
  1256. x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  1257. }
  1258. var time = this.body.util.toTime(x);
  1259. var scale = this.body.util.getScale();
  1260. var step = this.body.util.getStep();
  1261. var start = snap ? snap(time, scale, step) : time;
  1262. var end = start;
  1263. var itemData = {
  1264. type: 'range',
  1265. start: start,
  1266. end: end,
  1267. content: 'new item'
  1268. };
  1269. var id = util.randomUUID();
  1270. itemData[this.itemsData._fieldId] = id;
  1271. var group = this.groupFromTarget(event);
  1272. if (group) {
  1273. itemData.group = group.groupId;
  1274. }
  1275. var newItem = new RangeItem(itemData, this.conversion, this.options);
  1276. newItem.id = id; // TODO: not so nice setting id afterwards
  1277. newItem.data = this._cloneItemData(itemData);
  1278. this._addItem(newItem);
  1279. this.touchParams.selectedItem = newItem;
  1280. var props = {
  1281. item: newItem,
  1282. initialX: event.center.x,
  1283. data: newItem.data
  1284. };
  1285. if (this.options.rtl) {
  1286. props.dragLeft = true;
  1287. } else {
  1288. props.dragRight = true;
  1289. }
  1290. this.touchParams.itemProps = [props];
  1291. event.stopPropagation();
  1292. };
  1293. /**
  1294. * Drag selected items
  1295. * @param {Event} event
  1296. * @private
  1297. */
  1298. ItemSet.prototype._onDrag = function (event) {
  1299. if (this.touchParams.itemProps) {
  1300. event.stopPropagation();
  1301. var me = this;
  1302. var snap = this.options.snap || null;
  1303. var xOffset;
  1304. if (this.options.rtl) {
  1305. xOffset = this.body.dom.root.offsetLeft + this.body.domProps.right.width;
  1306. } else {
  1307. xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  1308. }
  1309. var scale = this.body.util.getScale();
  1310. var step = this.body.util.getStep();
  1311. //only calculate the new group for the item that's actually dragged
  1312. var selectedItem = this.touchParams.selectedItem;
  1313. var updateGroupAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateGroup) ||
  1314. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateGroup);
  1315. var newGroupBase = null;
  1316. if (updateGroupAllowed && selectedItem) {
  1317. if (selectedItem.data.group != undefined) {
  1318. // drag from one group to another
  1319. var group = me.groupFromTarget(event);
  1320. if (group) {
  1321. //we know the offset for all items, so the new group for all items
  1322. //will be relative to this one.
  1323. newGroupBase = this._getGroupIndex(group.groupId);
  1324. }
  1325. }
  1326. }
  1327. // move
  1328. this.touchParams.itemProps.forEach(function (props) {
  1329. var current = me.body.util.toTime(event.center.x - xOffset);
  1330. var initial = me.body.util.toTime(props.initialX - xOffset);
  1331. var offset;
  1332. var initialStart;
  1333. var initialEnd;
  1334. var start;
  1335. var end;
  1336. if (this.options.rtl) {
  1337. offset = -(current - initial); // ms
  1338. } else {
  1339. offset = (current - initial); // ms
  1340. }
  1341. var itemData = this._cloneItemData(props.item.data); // clone the data
  1342. if (props.item.editable != null
  1343. && !props.item.editable.updateTime
  1344. && !props.item.editable.updateGroup
  1345. && !me.options.editable.overrideItems) {
  1346. return;
  1347. }
  1348. var updateTimeAllowed = ((this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateTime) ||
  1349. (!this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateTime);
  1350. if (updateTimeAllowed) {
  1351. if (props.dragLeft) {
  1352. // drag left side of a range item
  1353. if (this.options.rtl) {
  1354. if (itemData.end != undefined) {
  1355. initialEnd = util.convert(props.data.end, 'Date');
  1356. end = new Date(initialEnd.valueOf() + offset);
  1357. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1358. itemData.end = snap ? snap(end, scale, step) : end;
  1359. }
  1360. } else {
  1361. if (itemData.start != undefined) {
  1362. initialStart = util.convert(props.data.start, 'Date');
  1363. start = new Date(initialStart.valueOf() + offset);
  1364. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1365. itemData.start = snap ? snap(start, scale, step) : start;
  1366. }
  1367. }
  1368. }
  1369. else if (props.dragRight) {
  1370. // drag right side of a range item
  1371. if (this.options.rtl) {
  1372. if (itemData.start != undefined) {
  1373. initialStart = util.convert(props.data.start, 'Date');
  1374. start = new Date(initialStart.valueOf() + offset);
  1375. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1376. itemData.start = snap ? snap(start, scale, step) : start;
  1377. }
  1378. } else {
  1379. if (itemData.end != undefined) {
  1380. initialEnd = util.convert(props.data.end, 'Date');
  1381. end = new Date(initialEnd.valueOf() + offset);
  1382. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1383. itemData.end = snap ? snap(end, scale, step) : end;
  1384. }
  1385. }
  1386. }
  1387. else {
  1388. // drag both start and end
  1389. if (itemData.start != undefined) {
  1390. initialStart = util.convert(props.data.start, 'Date').valueOf();
  1391. start = new Date(initialStart + offset);
  1392. if (itemData.end != undefined) {
  1393. initialEnd = util.convert(props.data.end, 'Date');
  1394. var duration = initialEnd.valueOf() - initialStart.valueOf();
  1395. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1396. itemData.start = snap ? snap(start, scale, step) : start;
  1397. itemData.end = new Date(itemData.start.valueOf() + duration);
  1398. }
  1399. else {
  1400. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  1401. itemData.start = snap ? snap(start, scale, step) : start;
  1402. }
  1403. }
  1404. }
  1405. }
  1406. if (updateGroupAllowed && (!props.dragLeft && !props.dragRight) && newGroupBase!=null) {
  1407. if (itemData.group != undefined) {
  1408. var newOffset = newGroupBase - props.groupOffset;
  1409. //make sure we stay in bounds
  1410. newOffset = Math.max(0, newOffset);
  1411. newOffset = Math.min(me.groupIds.length-1, newOffset);
  1412. itemData.group = me.groupIds[newOffset];
  1413. }
  1414. }
  1415. // confirm moving the item
  1416. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  1417. me.options.onMoving(itemData, function (itemData) {
  1418. if (itemData) {
  1419. props.item.setData(this._cloneItemData(itemData, 'Date'));
  1420. }
  1421. }.bind(this));
  1422. }.bind(this));
  1423. this.body.emitter.emit('_change');
  1424. }
  1425. };
  1426. /**
  1427. * Move an item to another group
  1428. * @param {Item} item
  1429. * @param {string | number} groupId
  1430. * @private
  1431. */
  1432. ItemSet.prototype._moveToGroup = function(item, groupId) {
  1433. var group = this.groups[groupId];
  1434. if (group && group.groupId != item.data.group) {
  1435. var oldGroup = item.parent;
  1436. oldGroup.remove(item);
  1437. oldGroup.order();
  1438. item.data.group = group.groupId;
  1439. group.add(item);
  1440. group.order();
  1441. }
  1442. };
  1443. /**
  1444. * End of dragging selected items
  1445. * @param {Event} event
  1446. * @private
  1447. */
  1448. ItemSet.prototype._onDragEnd = function (event) {
  1449. this.touchParams.itemIsDragging = false;
  1450. if (this.touchParams.itemProps) {
  1451. event.stopPropagation();
  1452. var me = this;
  1453. var dataset = this.itemsData.getDataSet();
  1454. var itemProps = this.touchParams.itemProps ;
  1455. this.touchParams.itemProps = null;
  1456. itemProps.forEach(function (props) {
  1457. var id = props.item.id;
  1458. var exists = me.itemsData.get(id, me.itemOptions) != null;
  1459. if (!exists) {
  1460. // add a new item
  1461. me.options.onAdd(props.item.data, function (itemData) {
  1462. me._removeItem(props.item); // remove temporary item
  1463. if (itemData) {
  1464. me.itemsData.getDataSet().add(itemData);
  1465. }
  1466. // force re-stacking of all items next redraw
  1467. me.body.emitter.emit('_change');
  1468. });
  1469. }
  1470. else {
  1471. // update existing item
  1472. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  1473. me.options.onMove(itemData, function (itemData) {
  1474. if (itemData) {
  1475. // apply changes
  1476. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  1477. dataset.update(itemData);
  1478. }
  1479. else {
  1480. // restore original values
  1481. props.item.setData(props.data);
  1482. me.body.emitter.emit('_change');
  1483. }
  1484. });
  1485. }
  1486. }.bind(this));
  1487. }
  1488. };
  1489. ItemSet.prototype._onGroupClick = function (event) {
  1490. var group = this.groupFromTarget(event);
  1491. if (!group || !group.nestedGroups) return;
  1492. var groupsData = this.groupsData.getDataSet();
  1493. var nestingGroup = groupsData.get(group.groupId)
  1494. if (nestingGroup.showNested == undefined) { nestingGroup.showNested = true; }
  1495. nestingGroup.showNested = !nestingGroup.showNested;
  1496. var nestedGroups = groupsData.get(group.nestedGroups).map(function(nestedGroup) {
  1497. nestedGroup.visible = nestingGroup.showNested;
  1498. return nestedGroup;
  1499. });
  1500. groupsData.update(nestedGroups.concat(nestingGroup));
  1501. if (nestingGroup.showNested) {
  1502. util.removeClassName(group.dom.label, 'collapsed');
  1503. util.addClassName(group.dom.label, 'expanded');
  1504. } else {
  1505. util.removeClassName(group.dom.label, 'expanded');
  1506. var collapsedDirClassName = this.options.rtl ? 'collapsed-rtl' : 'collapsed';
  1507. util.addClassName(group.dom.label, collapsedDirClassName);
  1508. }
  1509. };
  1510. ItemSet.prototype._onGroupDragStart = function (event) {
  1511. if (this.options.groupEditable.order) {
  1512. this.groupTouchParams.group = this.groupFromTarget(event);
  1513. if (this.groupTouchParams.group) {
  1514. event.stopPropagation();
  1515. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  1516. order: this.options.groupOrder
  1517. });
  1518. }
  1519. }
  1520. };
  1521. ItemSet.prototype._onGroupDrag = function (event) {
  1522. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1523. event.stopPropagation();
  1524. var groupsData = this.groupsData;
  1525. if (this.groupsData instanceof DataView) {
  1526. groupsData = this.groupsData.getDataSet()
  1527. }
  1528. // drag from one group to another
  1529. var group = this.groupFromTarget(event);
  1530. // try to avoid toggling when groups differ in height
  1531. if (group && group.height != this.groupTouchParams.group.height) {
  1532. var movingUp = (group.top < this.groupTouchParams.group.top);
  1533. var clientY = event.center ? event.center.y : event.clientY;
  1534. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  1535. var draggedGroupHeight = this.groupTouchParams.group.height;
  1536. if (movingUp) {
  1537. // skip swapping the groups when the dragged group is not below clientY afterwards
  1538. if (targetGroupTop + draggedGroupHeight < clientY) {
  1539. return;
  1540. }
  1541. } else {
  1542. var targetGroupHeight = group.height;
  1543. // skip swapping the groups when the dragged group is not below clientY afterwards
  1544. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  1545. return;
  1546. }
  1547. }
  1548. }
  1549. if (group && group != this.groupTouchParams.group) {
  1550. var targetGroup = groupsData.get(group.groupId);
  1551. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  1552. // switch groups
  1553. if (draggedGroup && targetGroup) {
  1554. this.options.groupOrderSwap(draggedGroup, targetGroup, groupsData);
  1555. groupsData.update(draggedGroup);
  1556. groupsData.update(targetGroup);
  1557. }
  1558. // fetch current order of groups
  1559. var newOrder = groupsData.getIds({
  1560. order: this.options.groupOrder
  1561. });
  1562. // in case of changes since _onGroupDragStart
  1563. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  1564. var origOrder = this.groupTouchParams.originalOrder;
  1565. var draggedId = this.groupTouchParams.group.groupId;
  1566. var numGroups = Math.min(origOrder.length, newOrder.length);
  1567. var curPos = 0;
  1568. var newOffset = 0;
  1569. var orgOffset = 0;
  1570. while (curPos < numGroups) {
  1571. // as long as the groups are where they should be step down along the groups order
  1572. while ((curPos+newOffset) < numGroups
  1573. && (curPos+orgOffset) < numGroups
  1574. && newOrder[curPos+newOffset] == origOrder[curPos+orgOffset]) {
  1575. curPos++;
  1576. }
  1577. // all ok
  1578. if (curPos+newOffset >= numGroups) {
  1579. break;
  1580. }
  1581. // not all ok
  1582. // if dragged group was move upwards everything below should have an offset
  1583. if (newOrder[curPos+newOffset] == draggedId) {
  1584. newOffset = 1;
  1585. }
  1586. // if dragged group was move downwards everything above should have an offset
  1587. else if (origOrder[curPos+orgOffset] == draggedId) {
  1588. orgOffset = 1;
  1589. }
  1590. // found a group (apart from dragged group) that has the wrong position -> switch with the
  1591. // group at the position where other one should be, fix index arrays and continue
  1592. else {
  1593. var slippedPosition = newOrder.indexOf(origOrder[curPos+orgOffset]);
  1594. var switchGroup = groupsData.get(newOrder[curPos+newOffset]);
  1595. var shouldBeGroup = groupsData.get(origOrder[curPos+orgOffset]);
  1596. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  1597. groupsData.update(switchGroup);
  1598. groupsData.update(shouldBeGroup);
  1599. var switchGroupId = newOrder[curPos+newOffset];
  1600. newOrder[curPos+newOffset] = origOrder[curPos+orgOffset];
  1601. newOrder[slippedPosition] = switchGroupId;
  1602. curPos++;
  1603. }
  1604. }
  1605. }
  1606. }
  1607. }
  1608. };
  1609. ItemSet.prototype._onGroupDragEnd = function (event) {
  1610. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  1611. event.stopPropagation();
  1612. // update existing group
  1613. var me = this;
  1614. var id = me.groupTouchParams.group.groupId;
  1615. var dataset = me.groupsData.getDataSet();
  1616. var groupData = util.extend({}, dataset.get(id)); // clone the data
  1617. me.options.onMoveGroup(groupData, function (groupData) {
  1618. if (groupData) {
  1619. // apply changes
  1620. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  1621. dataset.update(groupData);
  1622. }
  1623. else {
  1624. // fetch current order of groups
  1625. var newOrder = dataset.getIds({
  1626. order: me.options.groupOrder
  1627. });
  1628. // restore original order
  1629. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  1630. var origOrder = me.groupTouchParams.originalOrder;
  1631. var numGroups = Math.min(origOrder.length, newOrder.length);
  1632. var curPos = 0;
  1633. while (curPos < numGroups) {
  1634. // as long as the groups are where they should be step down along the groups order
  1635. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  1636. curPos++;
  1637. }
  1638. // all ok
  1639. if (curPos >= numGroups) {
  1640. break;
  1641. }
  1642. // found a group that has the wrong position -> switch with the
  1643. // group at the position where other one should be, fix index arrays and continue
  1644. var slippedPosition = newOrder.indexOf(origOrder[curPos]);
  1645. var switchGroup = dataset.get(newOrder[curPos]);
  1646. var shouldBeGroup = dataset.get(origOrder[curPos]);
  1647. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  1648. dataset.update(switchGroup);
  1649. dataset.update(shouldBeGroup);
  1650. var switchGroupId = newOrder[curPos];
  1651. newOrder[curPos] = origOrder[curPos];
  1652. newOrder[slippedPosition] = switchGroupId;
  1653. curPos++;
  1654. }
  1655. }
  1656. }
  1657. });
  1658. me.body.emitter.emit('groupDragged', { groupId: id });
  1659. }
  1660. };
  1661. /**
  1662. * Handle selecting/deselecting an item when tapping it
  1663. * @param {Event} event
  1664. * @private
  1665. */
  1666. ItemSet.prototype._onSelectItem = function (event) {
  1667. if (!this.options.selectable) return;
  1668. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  1669. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  1670. if (ctrlKey || shiftKey) {
  1671. this._onMultiSelectItem(event);
  1672. return;
  1673. }
  1674. var oldSelection = this.getSelection();
  1675. var item = this.itemFromTarget(event);
  1676. var selection = item ? [item.id] : [];
  1677. this.setSelection(selection);
  1678. var newSelection = this.getSelection();
  1679. // emit a select event,
  1680. // except when old selection is empty and new selection is still empty
  1681. if (newSelection.length > 0 || oldSelection.length > 0) {
  1682. this.body.emitter.emit('select', {
  1683. items: newSelection,
  1684. event: event
  1685. });
  1686. }
  1687. };
  1688. /**
  1689. * Handle hovering an item
  1690. * @param {Event} event
  1691. * @private
  1692. */
  1693. ItemSet.prototype._onMouseOver = function (event) {
  1694. var item = this.itemFromTarget(event);
  1695. if (!item) return;
  1696. // Item we just left
  1697. var related = this.itemFromRelatedTarget(event);
  1698. if (item === related) {
  1699. // We haven't changed item, just element in the item
  1700. return;
  1701. }
  1702. var title = item.getTitle();
  1703. if (this.options.showTooltips && title) {
  1704. if (this.popup == null) {
  1705. this.popup = new Popup(this.body.dom.root,
  1706. this.options.tooltip.overflowMethod || 'flip');
  1707. }
  1708. this.popup.setText(title);
  1709. var container = this.body.dom.centerContainer;
  1710. this.popup.setPosition(
  1711. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1712. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1713. );
  1714. this.popup.show();
  1715. } else {
  1716. // Hovering over item without a title, hide popup
  1717. // Needed instead of _just_ in _onMouseOut due to #2572
  1718. if (this.popup != null) {
  1719. this.popup.hide();
  1720. }
  1721. }
  1722. this.body.emitter.emit('itemover', {
  1723. item: item.id,
  1724. event: event
  1725. });
  1726. };
  1727. ItemSet.prototype._onMouseOut = function (event) {
  1728. var item = this.itemFromTarget(event);
  1729. if (!item) return;
  1730. // Item we are going to
  1731. var related = this.itemFromRelatedTarget(event);
  1732. if (item === related) {
  1733. // We aren't changing item, just element in the item
  1734. return;
  1735. }
  1736. if (this.popup != null) {
  1737. this.popup.hide();
  1738. }
  1739. this.body.emitter.emit('itemout', {
  1740. item: item.id,
  1741. event: event
  1742. });
  1743. };
  1744. ItemSet.prototype._onMouseMove = function (event) {
  1745. var item = this.itemFromTarget(event);
  1746. if (!item) return;
  1747. if (this.options.showTooltips && this.options.tooltip.followMouse) {
  1748. if (this.popup) {
  1749. if (!this.popup.hidden) {
  1750. var container = this.body.dom.centerContainer;
  1751. this.popup.setPosition(
  1752. event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft,
  1753. event.clientY - util.getAbsoluteTop(container) + container.offsetTop
  1754. );
  1755. this.popup.show(); // Redraw
  1756. }
  1757. }
  1758. }
  1759. };
  1760. /**
  1761. * Handle mousewheel
  1762. * @param {Event} event The event
  1763. * @private
  1764. */
  1765. ItemSet.prototype._onMouseWheel = function(event) {
  1766. if (this.touchParams.itemIsDragging) {
  1767. this._onDragEnd(event);
  1768. }
  1769. };
  1770. /**
  1771. * Handle updates of an item on double tap
  1772. * @param {vis.Item} item The item
  1773. * @private
  1774. */
  1775. ItemSet.prototype._onUpdateItem = function (item) {
  1776. if (!this.options.selectable) return;
  1777. if (!this.options.editable.add) return;
  1778. var me = this;
  1779. if (item) {
  1780. // execute async handler to update the item (or cancel it)
  1781. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  1782. this.options.onUpdate(itemData, function (itemData) {
  1783. if (itemData) {
  1784. me.itemsData.getDataSet().update(itemData);
  1785. }
  1786. });
  1787. }
  1788. };
  1789. /**
  1790. * Handle drop event of data on item
  1791. * Only called when `objectData.target === 'item'.
  1792. * @param {Event} event The event
  1793. * @private
  1794. */
  1795. ItemSet.prototype._onDropObjectOnItem = function(event) {
  1796. var item = this.itemFromTarget(event);
  1797. var objectData = JSON.parse(event.dataTransfer.getData("text"));
  1798. this.options.onDropObjectOnItem(objectData, item)
  1799. }
  1800. /**
  1801. * Handle creation of an item on double tap or drop of a drag event
  1802. * @param {Event} event The event
  1803. * @private
  1804. */
  1805. ItemSet.prototype._onAddItem = function (event) {
  1806. if (!this.options.selectable) return;
  1807. if (!this.options.editable.add) return;
  1808. var me = this;
  1809. var snap = this.options.snap || null;
  1810. var xAbs;
  1811. var x;
  1812. // add item
  1813. if (this.options.rtl) {
  1814. xAbs = util.getAbsoluteRight(this.dom.frame);
  1815. x = xAbs - event.center.x;
  1816. } else {
  1817. xAbs = util.getAbsoluteLeft(this.dom.frame);
  1818. x = event.center.x - xAbs;
  1819. }
  1820. // var xAbs = util.getAbsoluteLeft(this.dom.frame);
  1821. // var x = event.center.x - xAbs;
  1822. var start = this.body.util.toTime(x);
  1823. var scale = this.body.util.getScale();
  1824. var step = this.body.util.getStep();
  1825. var end;
  1826. var newItemData;
  1827. if (event.type == 'drop') {
  1828. newItemData = JSON.parse(event.dataTransfer.getData("text"));
  1829. newItemData.content = newItemData.content ? newItemData.content : 'new item';
  1830. newItemData.start = newItemData.start ? newItemData.start : (snap ? snap(start, scale, step) : start);
  1831. newItemData.type = newItemData.type || 'box';
  1832. newItemData[this.itemsData._fieldId] = newItemData.id || util.randomUUID();
  1833. if (newItemData.type == 'range' && !newItemData.end) {
  1834. end = this.body.util.toTime(x + this.props.width / 5);
  1835. newItemData.end = snap ? snap(end, scale, step) : end;
  1836. }
  1837. } else {
  1838. newItemData = {
  1839. start: snap ? snap(start, scale, step) : start,
  1840. content: 'new item'
  1841. };
  1842. newItemData[this.itemsData._fieldId] = util.randomUUID();
  1843. // when default type is a range, add a default end date to the new item
  1844. if (this.options.type === 'range') {
  1845. end = this.body.util.toTime(x + this.props.width / 5);
  1846. newItemData.end = snap ? snap(end, scale, step) : end;
  1847. }
  1848. }
  1849. var group = this.groupFromTarget(event);
  1850. if (group) {
  1851. newItemData.group = group.groupId;
  1852. }
  1853. // execute async handler to customize (or cancel) adding an item
  1854. newItemData = this._cloneItemData(newItemData); // convert start and end to the correct type
  1855. this.options.onAdd(newItemData, function (item) {
  1856. if (item) {
  1857. me.itemsData.getDataSet().add(item);
  1858. if (event.type == 'drop') {
  1859. me.setSelection([item.id]);
  1860. }
  1861. // TODO: need to trigger a redraw?
  1862. }
  1863. });
  1864. };
  1865. /**
  1866. * Handle selecting/deselecting multiple items when holding an item
  1867. * @param {Event} event
  1868. * @private
  1869. */
  1870. ItemSet.prototype._onMultiSelectItem = function (event) {
  1871. if (!this.options.selectable) return;
  1872. var item = this.itemFromTarget(event);
  1873. if (item) {
  1874. // multi select items (if allowed)
  1875. var selection = this.options.multiselect
  1876. ? this.getSelection() // take current selection
  1877. : []; // deselect current selection
  1878. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  1879. if (shiftKey && this.options.multiselect) {
  1880. // select all items between the old selection and the tapped item
  1881. var itemGroup = this.itemsData.get(item.id).group;
  1882. // when filtering get the group of the last selected item
  1883. var lastSelectedGroup = undefined;
  1884. if (this.options.multiselectPerGroup) {
  1885. if (selection.length > 0) {
  1886. lastSelectedGroup = this.itemsData.get(selection[0]).group;
  1887. }
  1888. }
  1889. // determine the selection range
  1890. if (!this.options.multiselectPerGroup || lastSelectedGroup == undefined || lastSelectedGroup == itemGroup) {
  1891. selection.push(item.id);
  1892. }
  1893. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  1894. if (!this.options.multiselectPerGroup || lastSelectedGroup == itemGroup) {
  1895. // select all items within the selection range
  1896. selection = [];
  1897. for (var id in this.items) {
  1898. if (this.items.hasOwnProperty(id)) {
  1899. var _item = this.items[id];
  1900. var start = _item.data.start;
  1901. var end = (_item.data.end !== undefined) ? _item.data.end : start;
  1902. if (start >= range.min &&
  1903. end <= range.max &&
  1904. (!this.options.multiselectPerGroup || lastSelectedGroup == this.itemsData.get(_item.id).group) &&
  1905. !(_item instanceof BackgroundItem)) {
  1906. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  1907. }
  1908. }
  1909. }
  1910. }
  1911. }
  1912. else {
  1913. // add/remove this item from the current selection
  1914. var index = selection.indexOf(item.id);
  1915. if (index == -1) {
  1916. // item is not yet selected -> select it
  1917. selection.push(item.id);
  1918. }
  1919. else {
  1920. // item is already selected -> deselect it
  1921. selection.splice(index, 1);
  1922. }
  1923. }
  1924. this.setSelection(selection);
  1925. this.body.emitter.emit('select', {
  1926. items: this.getSelection(),
  1927. event: event
  1928. });
  1929. }
  1930. };
  1931. /**
  1932. * Calculate the time range of a list of items
  1933. * @param {Array.<Object>} itemsData
  1934. * @return {{min: Date, max: Date}} Returns the range of the provided items
  1935. * @private
  1936. */
  1937. ItemSet._getItemRange = function(itemsData) {
  1938. var max = null;
  1939. var min = null;
  1940. itemsData.forEach(function (data) {
  1941. if (min == null || data.start < min) {
  1942. min = data.start;
  1943. }
  1944. if (data.end != undefined) {
  1945. if (max == null || data.end > max) {
  1946. max = data.end;
  1947. }
  1948. }
  1949. else {
  1950. if (max == null || data.start > max) {
  1951. max = data.start;
  1952. }
  1953. }
  1954. });
  1955. return {
  1956. min: min,
  1957. max: max
  1958. }
  1959. };
  1960. /**
  1961. * Find an item from an element:
  1962. * searches for the attribute 'timeline-item' in the element's tree
  1963. * @param {HTMLElement} element
  1964. * @return {Item | null} item
  1965. */
  1966. ItemSet.prototype.itemFromElement = function(element) {
  1967. var cur = element;
  1968. while (cur) {
  1969. if (cur.hasOwnProperty('timeline-item')) {
  1970. return cur['timeline-item'];
  1971. }
  1972. cur = cur.parentNode;
  1973. }
  1974. return null;
  1975. };
  1976. /**
  1977. * Find an item from an event target:
  1978. * searches for the attribute 'timeline-item' in the event target's element tree
  1979. * @param {Event} event
  1980. * @return {Item | null} item
  1981. */
  1982. ItemSet.prototype.itemFromTarget = function(event) {
  1983. return this.itemFromElement(event.target);
  1984. };
  1985. /**
  1986. * Find an item from an event's related target:
  1987. * searches for the attribute 'timeline-item' in the related target's element tree
  1988. * @param {Event} event
  1989. * @return {Item | null} item
  1990. */
  1991. ItemSet.prototype.itemFromRelatedTarget = function(event) {
  1992. return this.itemFromElement(event.relatedTarget);
  1993. };
  1994. /**
  1995. * Find the Group from an event target:
  1996. * searches for the attribute 'timeline-group' in the event target's element tree
  1997. * @param {Event} event
  1998. * @return {Group | null} group
  1999. */
  2000. ItemSet.prototype.groupFromTarget = function(event) {
  2001. var clientY = event.center ? event.center.y : event.clientY;
  2002. var groupIds = this.groupIds;
  2003. if (groupIds.length <= 0 && this.groupsData) {
  2004. groupIds = this.groupsData.getIds({
  2005. order: this.options.groupOrder
  2006. });
  2007. }
  2008. for (var i = 0; i < groupIds.length; i++) {
  2009. var groupId = groupIds[i];
  2010. var group = this.groups[groupId];
  2011. var foreground = group.dom.foreground;
  2012. var top = util.getAbsoluteTop(foreground);
  2013. if (clientY > top && clientY < top + foreground.offsetHeight) {
  2014. return group;
  2015. }
  2016. if (this.options.orientation.item === 'top') {
  2017. if (i === this.groupIds.length - 1 && clientY > top) {
  2018. return group;
  2019. }
  2020. }
  2021. else {
  2022. if (i === 0 && clientY < top + foreground.offset) {
  2023. return group;
  2024. }
  2025. }
  2026. }
  2027. return null;
  2028. };
  2029. /**
  2030. * Find the ItemSet from an event target:
  2031. * searches for the attribute 'timeline-itemset' in the event target's element tree
  2032. * @param {Event} event
  2033. * @return {ItemSet | null} item
  2034. */
  2035. ItemSet.itemSetFromTarget = function(event) {
  2036. var target = event.target;
  2037. while (target) {
  2038. if (target.hasOwnProperty('timeline-itemset')) {
  2039. return target['timeline-itemset'];
  2040. }
  2041. target = target.parentNode;
  2042. }
  2043. return null;
  2044. };
  2045. /**
  2046. * Clone the data of an item, and "normalize" it: convert the start and end date
  2047. * to the type (Date, Moment, ...) configured in the DataSet. If not configured,
  2048. * start and end are converted to Date.
  2049. * @param {Object} itemData, typically `item.data`
  2050. * @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
  2051. * @return {Object} The cloned object
  2052. * @private
  2053. */
  2054. ItemSet.prototype._cloneItemData = function (itemData, type) {
  2055. var clone = util.extend({}, itemData);
  2056. if (!type) {
  2057. // convert start and end date to the type (Date, Moment, ...) configured in the DataSet
  2058. type = this.itemsData.getDataSet()._options.type;
  2059. }
  2060. if (clone.start != undefined) {
  2061. clone.start = util.convert(clone.start, type && type.start || 'Date');
  2062. }
  2063. if (clone.end != undefined) {
  2064. clone.end = util.convert(clone.end , type && type.end || 'Date');
  2065. }
  2066. return clone;
  2067. };
  2068. module.exports = ItemSet;