dragdrop.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. // script.aculo.us dragdrop.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008
  2. // Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
  3. // (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
  4. //
  5. // script.aculo.us is freely distributable under the terms of an MIT-style license.
  6. // For details, see the script.aculo.us web site: http://script.aculo.us/
  7. if(Object.isUndefined(Effect))
  8. throw("dragdrop.js requires including script.aculo.us' effects.js library");
  9. var Droppables = {
  10. drops: [],
  11. remove: function(element) {
  12. this.drops = this.drops.reject(function(d) { return d.element==$(element) });
  13. },
  14. add: function(element) {
  15. element = $(element);
  16. var options = Object.extend({
  17. greedy: true,
  18. hoverclass: null,
  19. tree: false
  20. }, arguments[1] || { });
  21. // cache containers
  22. if(options.containment) {
  23. options._containers = [];
  24. var containment = options.containment;
  25. if(Object.isArray(containment)) {
  26. containment.each( function(c) { options._containers.push($(c)) });
  27. } else {
  28. options._containers.push($(containment));
  29. }
  30. }
  31. if(options.accept) options.accept = [options.accept].flatten();
  32. Element.makePositioned(element); // fix IE
  33. options.element = element;
  34. this.drops.push(options);
  35. },
  36. findDeepestChild: function(drops) {
  37. deepest = drops[0];
  38. for (i = 1; i < drops.length; ++i)
  39. if (Element.isParent(drops[i].element, deepest.element))
  40. deepest = drops[i];
  41. return deepest;
  42. },
  43. isContained: function(element, drop) {
  44. var containmentNode;
  45. if(drop.tree) {
  46. containmentNode = element.treeNode;
  47. } else {
  48. containmentNode = element.parentNode;
  49. }
  50. return drop._containers.detect(function(c) { return containmentNode == c });
  51. },
  52. isAffected: function(point, element, drop) {
  53. return (
  54. (drop.element!=element) &&
  55. ((!drop._containers) ||
  56. this.isContained(element, drop)) &&
  57. ((!drop.accept) ||
  58. (Element.classNames(element).detect(
  59. function(v) { return drop.accept.include(v) } ) )) &&
  60. Position.within(drop.element, point[0], point[1]) );
  61. },
  62. deactivate: function(drop) {
  63. if(drop.hoverclass)
  64. Element.removeClassName(drop.element, drop.hoverclass);
  65. this.last_active = null;
  66. },
  67. activate: function(drop) {
  68. if(drop.hoverclass)
  69. Element.addClassName(drop.element, drop.hoverclass);
  70. this.last_active = drop;
  71. },
  72. show: function(point, element) {
  73. if(!this.drops.length) return;
  74. var drop, affected = [];
  75. this.drops.each( function(drop) {
  76. if(Droppables.isAffected(point, element, drop))
  77. affected.push(drop);
  78. });
  79. if(affected.length>0)
  80. drop = Droppables.findDeepestChild(affected);
  81. if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
  82. if (drop) {
  83. Position.within(drop.element, point[0], point[1]);
  84. if(drop.onHover)
  85. drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
  86. if (drop != this.last_active) Droppables.activate(drop);
  87. }
  88. },
  89. fire: function(event, element) {
  90. if(!this.last_active) return;
  91. Position.prepare();
  92. if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
  93. if (this.last_active.onDrop) {
  94. this.last_active.onDrop(element, this.last_active.element, event);
  95. return true;
  96. }
  97. },
  98. reset: function() {
  99. if(this.last_active)
  100. this.deactivate(this.last_active);
  101. }
  102. }
  103. var Draggables = {
  104. drags: [],
  105. observers: [],
  106. register: function(draggable) {
  107. if(this.drags.length == 0) {
  108. this.eventMouseUp = this.endDrag.bindAsEventListener(this);
  109. this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
  110. this.eventKeypress = this.keyPress.bindAsEventListener(this);
  111. Event.observe(document, "mouseup", this.eventMouseUp);
  112. Event.observe(document, "mousemove", this.eventMouseMove);
  113. Event.observe(document, "keypress", this.eventKeypress);
  114. }
  115. this.drags.push(draggable);
  116. },
  117. unregister: function(draggable) {
  118. this.drags = this.drags.reject(function(d) { return d==draggable });
  119. if(this.drags.length == 0) {
  120. Event.stopObserving(document, "mouseup", this.eventMouseUp);
  121. Event.stopObserving(document, "mousemove", this.eventMouseMove);
  122. Event.stopObserving(document, "keypress", this.eventKeypress);
  123. }
  124. },
  125. activate: function(draggable) {
  126. if(draggable.options.delay) {
  127. this._timeout = setTimeout(function() {
  128. Draggables._timeout = null;
  129. window.focus();
  130. Draggables.activeDraggable = draggable;
  131. }.bind(this), draggable.options.delay);
  132. } else {
  133. window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
  134. this.activeDraggable = draggable;
  135. }
  136. },
  137. deactivate: function() {
  138. this.activeDraggable = null;
  139. },
  140. updateDrag: function(event) {
  141. if(!this.activeDraggable) return;
  142. var pointer = [Event.pointerX(event), Event.pointerY(event)];
  143. // Mozilla-based browsers fire successive mousemove events with
  144. // the same coordinates, prevent needless redrawing (moz bug?)
  145. if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
  146. this._lastPointer = pointer;
  147. this.activeDraggable.updateDrag(event, pointer);
  148. },
  149. endDrag: function(event) {
  150. if(this._timeout) {
  151. clearTimeout(this._timeout);
  152. this._timeout = null;
  153. }
  154. if(!this.activeDraggable) return;
  155. this._lastPointer = null;
  156. this.activeDraggable.endDrag(event);
  157. this.activeDraggable = null;
  158. },
  159. keyPress: function(event) {
  160. if(this.activeDraggable)
  161. this.activeDraggable.keyPress(event);
  162. },
  163. addObserver: function(observer) {
  164. this.observers.push(observer);
  165. this._cacheObserverCallbacks();
  166. },
  167. removeObserver: function(element) { // element instead of observer fixes mem leaks
  168. this.observers = this.observers.reject( function(o) { return o.element==element });
  169. this._cacheObserverCallbacks();
  170. },
  171. notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
  172. if(this[eventName+'Count'] > 0)
  173. this.observers.each( function(o) {
  174. if(o[eventName]) o[eventName](eventName, draggable, event);
  175. });
  176. if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
  177. },
  178. _cacheObserverCallbacks: function() {
  179. ['onStart','onEnd','onDrag'].each( function(eventName) {
  180. Draggables[eventName+'Count'] = Draggables.observers.select(
  181. function(o) { return o[eventName]; }
  182. ).length;
  183. });
  184. }
  185. }
  186. /*--------------------------------------------------------------------------*/
  187. var Draggable = Class.create({
  188. initialize: function(element) {
  189. var defaults = {
  190. handle: false,
  191. reverteffect: function(element, top_offset, left_offset) {
  192. var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
  193. new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
  194. queue: {scope:'_draggable', position:'end'}
  195. });
  196. },
  197. endeffect: function(element) {
  198. var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
  199. new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
  200. queue: {scope:'_draggable', position:'end'},
  201. afterFinish: function(){
  202. Draggable._dragging[element] = false
  203. }
  204. });
  205. },
  206. zindex: 1000,
  207. revert: false,
  208. quiet: false,
  209. scroll: false,
  210. scrollSensitivity: 20,
  211. scrollSpeed: 15,
  212. snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
  213. delay: 0
  214. };
  215. if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
  216. Object.extend(defaults, {
  217. starteffect: function(element) {
  218. element._opacity = Element.getOpacity(element);
  219. Draggable._dragging[element] = true;
  220. new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
  221. }
  222. });
  223. var options = Object.extend(defaults, arguments[1] || { });
  224. this.element = $(element);
  225. if(options.handle && Object.isString(options.handle))
  226. this.handle = this.element.down('.'+options.handle, 0);
  227. if(!this.handle) this.handle = $(options.handle);
  228. if(!this.handle) this.handle = this.element;
  229. if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
  230. options.scroll = $(options.scroll);
  231. this._isScrollChild = Element.childOf(this.element, options.scroll);
  232. }
  233. Element.makePositioned(this.element); // fix IE
  234. this.options = options;
  235. this.dragging = false;
  236. this.eventMouseDown = this.initDrag.bindAsEventListener(this);
  237. Event.observe(this.handle, "mousedown", this.eventMouseDown);
  238. Draggables.register(this);
  239. },
  240. destroy: function() {
  241. Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
  242. Draggables.unregister(this);
  243. },
  244. currentDelta: function() {
  245. return([
  246. parseInt(Element.getStyle(this.element,'left') || '0'),
  247. parseInt(Element.getStyle(this.element,'top') || '0')]);
  248. },
  249. initDrag: function(event) {
  250. if(!Object.isUndefined(Draggable._dragging[this.element]) &&
  251. Draggable._dragging[this.element]) return;
  252. if(Event.isLeftClick(event)) {
  253. // abort on form elements, fixes a Firefox issue
  254. var src = Event.element(event);
  255. if((tag_name = src.tagName.toUpperCase()) && (
  256. tag_name=='INPUT' ||
  257. tag_name=='SELECT' ||
  258. tag_name=='OPTION' ||
  259. tag_name=='BUTTON' ||
  260. tag_name=='TEXTAREA')) return;
  261. var pointer = [Event.pointerX(event), Event.pointerY(event)];
  262. var pos = Position.cumulativeOffset(this.element);
  263. this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
  264. Draggables.activate(this);
  265. Event.stop(event);
  266. }
  267. },
  268. startDrag: function(event) {
  269. this.dragging = true;
  270. if(!this.delta)
  271. this.delta = this.currentDelta();
  272. if(this.options.zindex) {
  273. this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
  274. this.element.style.zIndex = this.options.zindex;
  275. }
  276. if(this.options.ghosting) {
  277. this._clone = this.element.cloneNode(true);
  278. this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
  279. if (!this.element._originallyAbsolute)
  280. Position.absolutize(this.element);
  281. this.element.parentNode.insertBefore(this._clone, this.element);
  282. }
  283. if(this.options.scroll) {
  284. if (this.options.scroll == window) {
  285. var where = this._getWindowScroll(this.options.scroll);
  286. this.originalScrollLeft = where.left;
  287. this.originalScrollTop = where.top;
  288. } else {
  289. this.originalScrollLeft = this.options.scroll.scrollLeft;
  290. this.originalScrollTop = this.options.scroll.scrollTop;
  291. }
  292. }
  293. Draggables.notify('onStart', this, event);
  294. if(this.options.starteffect) this.options.starteffect(this.element);
  295. },
  296. updateDrag: function(event, pointer) {
  297. if(!this.dragging) this.startDrag(event);
  298. if(!this.options.quiet){
  299. Position.prepare();
  300. Droppables.show(pointer, this.element);
  301. }
  302. Draggables.notify('onDrag', this, event);
  303. this.draw(pointer);
  304. if(this.options.change) this.options.change(this);
  305. if(this.options.scroll) {
  306. this.stopScrolling();
  307. var p;
  308. if (this.options.scroll == window) {
  309. with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
  310. } else {
  311. p = Position.page(this.options.scroll);
  312. p[0] += this.options.scroll.scrollLeft + Position.deltaX;
  313. p[1] += this.options.scroll.scrollTop + Position.deltaY;
  314. p.push(p[0]+this.options.scroll.offsetWidth);
  315. p.push(p[1]+this.options.scroll.offsetHeight);
  316. }
  317. var speed = [0,0];
  318. if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
  319. if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
  320. if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
  321. if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
  322. this.startScrolling(speed);
  323. }
  324. // fix AppleWebKit rendering
  325. if(Prototype.Browser.WebKit) window.scrollBy(0,0);
  326. Event.stop(event);
  327. },
  328. finishDrag: function(event, success) {
  329. this.dragging = false;
  330. if(this.options.quiet){
  331. Position.prepare();
  332. var pointer = [Event.pointerX(event), Event.pointerY(event)];
  333. Droppables.show(pointer, this.element);
  334. }
  335. if(this.options.ghosting) {
  336. if (!this.element._originallyAbsolute)
  337. Position.relativize(this.element);
  338. delete this.element._originallyAbsolute;
  339. Element.remove(this._clone);
  340. this._clone = null;
  341. }
  342. var dropped = false;
  343. if(success) {
  344. dropped = Droppables.fire(event, this.element);
  345. if (!dropped) dropped = false;
  346. }
  347. if(dropped && this.options.onDropped) this.options.onDropped(this.element);
  348. Draggables.notify('onEnd', this, event);
  349. var revert = this.options.revert;
  350. if(revert && Object.isFunction(revert)) revert = revert(this.element);
  351. var d = this.currentDelta();
  352. if(revert && this.options.reverteffect) {
  353. if (dropped == 0 || revert != 'failure')
  354. this.options.reverteffect(this.element,
  355. d[1]-this.delta[1], d[0]-this.delta[0]);
  356. } else {
  357. this.delta = d;
  358. }
  359. if(this.options.zindex)
  360. this.element.style.zIndex = this.originalZ;
  361. if(this.options.endeffect)
  362. this.options.endeffect(this.element);
  363. Draggables.deactivate(this);
  364. Droppables.reset();
  365. },
  366. keyPress: function(event) {
  367. if(event.keyCode!=Event.KEY_ESC) return;
  368. this.finishDrag(event, false);
  369. Event.stop(event);
  370. },
  371. endDrag: function(event) {
  372. if(!this.dragging) return;
  373. this.stopScrolling();
  374. this.finishDrag(event, true);
  375. Event.stop(event);
  376. },
  377. draw: function(point) {
  378. var pos = Position.cumulativeOffset(this.element);
  379. if(this.options.ghosting) {
  380. var r = Position.realOffset(this.element);
  381. pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
  382. }
  383. var d = this.currentDelta();
  384. pos[0] -= d[0]; pos[1] -= d[1];
  385. if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
  386. pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
  387. pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
  388. }
  389. var p = [0,1].map(function(i){
  390. return (point[i]-pos[i]-this.offset[i])
  391. }.bind(this));
  392. if(this.options.snap) {
  393. if(Object.isFunction(this.options.snap)) {
  394. p = this.options.snap(p[0],p[1],this);
  395. } else {
  396. if(Object.isArray(this.options.snap)) {
  397. p = p.map( function(v, i) {
  398. return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this))
  399. } else {
  400. p = p.map( function(v) {
  401. return (v/this.options.snap).round()*this.options.snap }.bind(this))
  402. }
  403. }}
  404. var style = this.element.style;
  405. if((!this.options.constraint) || (this.options.constraint=='horizontal'))
  406. style.left = p[0] + "px";
  407. if((!this.options.constraint) || (this.options.constraint=='vertical'))
  408. style.top = p[1] + "px";
  409. if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
  410. },
  411. stopScrolling: function() {
  412. if(this.scrollInterval) {
  413. clearInterval(this.scrollInterval);
  414. this.scrollInterval = null;
  415. Draggables._lastScrollPointer = null;
  416. }
  417. },
  418. startScrolling: function(speed) {
  419. if(!(speed[0] || speed[1])) return;
  420. this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
  421. this.lastScrolled = new Date();
  422. this.scrollInterval = setInterval(this.scroll.bind(this), 10);
  423. },
  424. scroll: function() {
  425. var current = new Date();
  426. var delta = current - this.lastScrolled;
  427. this.lastScrolled = current;
  428. if(this.options.scroll == window) {
  429. with (this._getWindowScroll(this.options.scroll)) {
  430. if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
  431. var d = delta / 1000;
  432. this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
  433. }
  434. }
  435. } else {
  436. this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
  437. this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
  438. }
  439. Position.prepare();
  440. Droppables.show(Draggables._lastPointer, this.element);
  441. Draggables.notify('onDrag', this);
  442. if (this._isScrollChild) {
  443. Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
  444. Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
  445. Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
  446. if (Draggables._lastScrollPointer[0] < 0)
  447. Draggables._lastScrollPointer[0] = 0;
  448. if (Draggables._lastScrollPointer[1] < 0)
  449. Draggables._lastScrollPointer[1] = 0;
  450. this.draw(Draggables._lastScrollPointer);
  451. }
  452. if(this.options.change) this.options.change(this);
  453. },
  454. _getWindowScroll: function(w) {
  455. var T, L, W, H;
  456. with (w.document) {
  457. if (w.document.documentElement && documentElement.scrollTop) {
  458. T = documentElement.scrollTop;
  459. L = documentElement.scrollLeft;
  460. } else if (w.document.body) {
  461. T = body.scrollTop;
  462. L = body.scrollLeft;
  463. }
  464. if (w.innerWidth) {
  465. W = w.innerWidth;
  466. H = w.innerHeight;
  467. } else if (w.document.documentElement && documentElement.clientWidth) {
  468. W = documentElement.clientWidth;
  469. H = documentElement.clientHeight;
  470. } else {
  471. W = body.offsetWidth;
  472. H = body.offsetHeight
  473. }
  474. }
  475. return { top: T, left: L, width: W, height: H };
  476. }
  477. });
  478. Draggable._dragging = { };
  479. /*--------------------------------------------------------------------------*/
  480. var SortableObserver = Class.create({
  481. initialize: function(element, observer) {
  482. this.element = $(element);
  483. this.observer = observer;
  484. this.lastValue = Sortable.serialize(this.element);
  485. },
  486. onStart: function() {
  487. this.lastValue = Sortable.serialize(this.element);
  488. },
  489. onEnd: function() {
  490. Sortable.unmark();
  491. if(this.lastValue != Sortable.serialize(this.element))
  492. this.observer(this.element)
  493. }
  494. });
  495. var Sortable = {
  496. SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
  497. sortables: { },
  498. _findRootElement: function(element) {
  499. while (element.tagName.toUpperCase() != "BODY") {
  500. if(element.id && Sortable.sortables[element.id]) return element;
  501. element = element.parentNode;
  502. }
  503. },
  504. options: function(element) {
  505. element = Sortable._findRootElement($(element));
  506. if(!element) return;
  507. return Sortable.sortables[element.id];
  508. },
  509. destroy: function(element){
  510. var s = Sortable.options(element);
  511. if(s) {
  512. Draggables.removeObserver(s.element);
  513. s.droppables.each(function(d){ Droppables.remove(d) });
  514. s.draggables.invoke('destroy');
  515. delete Sortable.sortables[s.element.id];
  516. }
  517. },
  518. create: function(element) {
  519. element = $(element);
  520. var options = Object.extend({
  521. element: element,
  522. tag: 'li', // assumes li children, override with tag: 'tagname'
  523. dropOnEmpty: false,
  524. tree: false,
  525. treeTag: 'ul',
  526. overlap: 'vertical', // one of 'vertical', 'horizontal'
  527. constraint: 'vertical', // one of 'vertical', 'horizontal', false
  528. containment: element, // also takes array of elements (or id's); or false
  529. handle: false, // or a CSS class
  530. only: false,
  531. delay: 0,
  532. hoverclass: null,
  533. ghosting: false,
  534. quiet: false,
  535. scroll: false,
  536. scrollSensitivity: 20,
  537. scrollSpeed: 15,
  538. format: this.SERIALIZE_RULE,
  539. // these take arrays of elements or ids and can be
  540. // used for better initialization performance
  541. elements: false,
  542. handles: false,
  543. onChange: Prototype.emptyFunction,
  544. onUpdate: Prototype.emptyFunction
  545. }, arguments[1] || { });
  546. // clear any old sortable with same element
  547. this.destroy(element);
  548. // build options for the draggables
  549. var options_for_draggable = {
  550. revert: true,
  551. quiet: options.quiet,
  552. scroll: options.scroll,
  553. scrollSpeed: options.scrollSpeed,
  554. scrollSensitivity: options.scrollSensitivity,
  555. delay: options.delay,
  556. ghosting: options.ghosting,
  557. constraint: options.constraint,
  558. handle: options.handle };
  559. if(options.starteffect)
  560. options_for_draggable.starteffect = options.starteffect;
  561. if(options.reverteffect)
  562. options_for_draggable.reverteffect = options.reverteffect;
  563. else
  564. if(options.ghosting) options_for_draggable.reverteffect = function(element) {
  565. element.style.top = 0;
  566. element.style.left = 0;
  567. };
  568. if(options.endeffect)
  569. options_for_draggable.endeffect = options.endeffect;
  570. if(options.zindex)
  571. options_for_draggable.zindex = options.zindex;
  572. // build options for the droppables
  573. var options_for_droppable = {
  574. overlap: options.overlap,
  575. containment: options.containment,
  576. tree: options.tree,
  577. hoverclass: options.hoverclass,
  578. onHover: Sortable.onHover
  579. }
  580. var options_for_tree = {
  581. onHover: Sortable.onEmptyHover,
  582. overlap: options.overlap,
  583. containment: options.containment,
  584. hoverclass: options.hoverclass
  585. }
  586. // fix for gecko engine
  587. Element.cleanWhitespace(element);
  588. options.draggables = [];
  589. options.droppables = [];
  590. // drop on empty handling
  591. if(options.dropOnEmpty || options.tree) {
  592. Droppables.add(element, options_for_tree);
  593. options.droppables.push(element);
  594. }
  595. (options.elements || this.findElements(element, options) || []).each( function(e,i) {
  596. var handle = options.handles ? $(options.handles[i]) :
  597. (options.handle ? $(e).select('.' + options.handle)[0] : e);
  598. options.draggables.push(
  599. new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
  600. Droppables.add(e, options_for_droppable);
  601. if(options.tree) e.treeNode = element;
  602. options.droppables.push(e);
  603. });
  604. if(options.tree) {
  605. (Sortable.findTreeElements(element, options) || []).each( function(e) {
  606. Droppables.add(e, options_for_tree);
  607. e.treeNode = element;
  608. options.droppables.push(e);
  609. });
  610. }
  611. // keep reference
  612. this.sortables[element.id] = options;
  613. // for onupdate
  614. Draggables.addObserver(new SortableObserver(element, options.onUpdate));
  615. },
  616. // return all suitable-for-sortable elements in a guaranteed order
  617. findElements: function(element, options) {
  618. return Element.findChildren(
  619. element, options.only, options.tree ? true : false, options.tag);
  620. },
  621. findTreeElements: function(element, options) {
  622. return Element.findChildren(
  623. element, options.only, options.tree ? true : false, options.treeTag);
  624. },
  625. onHover: function(element, dropon, overlap) {
  626. if(Element.isParent(dropon, element)) return;
  627. if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
  628. return;
  629. } else if(overlap>0.5) {
  630. Sortable.mark(dropon, 'before');
  631. if(dropon.previousSibling != element) {
  632. var oldParentNode = element.parentNode;
  633. element.style.visibility = "hidden"; // fix gecko rendering
  634. dropon.parentNode.insertBefore(element, dropon);
  635. if(dropon.parentNode!=oldParentNode)
  636. Sortable.options(oldParentNode).onChange(element);
  637. Sortable.options(dropon.parentNode).onChange(element);
  638. }
  639. } else {
  640. Sortable.mark(dropon, 'after');
  641. var nextElement = dropon.nextSibling || null;
  642. if(nextElement != element) {
  643. var oldParentNode = element.parentNode;
  644. element.style.visibility = "hidden"; // fix gecko rendering
  645. dropon.parentNode.insertBefore(element, nextElement);
  646. if(dropon.parentNode!=oldParentNode)
  647. Sortable.options(oldParentNode).onChange(element);
  648. Sortable.options(dropon.parentNode).onChange(element);
  649. }
  650. }
  651. },
  652. onEmptyHover: function(element, dropon, overlap) {
  653. var oldParentNode = element.parentNode;
  654. var droponOptions = Sortable.options(dropon);
  655. if(!Element.isParent(dropon, element)) {
  656. var index;
  657. var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
  658. var child = null;
  659. if(children) {
  660. var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
  661. for (index = 0; index < children.length; index += 1) {
  662. if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
  663. offset -= Element.offsetSize (children[index], droponOptions.overlap);
  664. } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
  665. child = index + 1 < children.length ? children[index + 1] : null;
  666. break;
  667. } else {
  668. child = children[index];
  669. break;
  670. }
  671. }
  672. }
  673. dropon.insertBefore(element, child);
  674. Sortable.options(oldParentNode).onChange(element);
  675. droponOptions.onChange(element);
  676. }
  677. },
  678. unmark: function() {
  679. if(Sortable._marker) Sortable._marker.hide();
  680. },
  681. mark: function(dropon, position) {
  682. // mark on ghosting only
  683. var sortable = Sortable.options(dropon.parentNode);
  684. if(sortable && !sortable.ghosting) return;
  685. if(!Sortable._marker) {
  686. Sortable._marker =
  687. ($('dropmarker') || Element.extend(document.createElement('DIV'))).
  688. hide().addClassName('dropmarker').setStyle({position:'absolute'});
  689. document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
  690. }
  691. var offsets = Position.cumulativeOffset(dropon);
  692. Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
  693. if(position=='after')
  694. if(sortable.overlap == 'horizontal')
  695. Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
  696. else
  697. Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
  698. Sortable._marker.show();
  699. },
  700. _tree: function(element, options, parent) {
  701. var children = Sortable.findElements(element, options) || [];
  702. for (var i = 0; i < children.length; ++i) {
  703. var match = children[i].id.match(options.format);
  704. if (!match) continue;
  705. var child = {
  706. id: encodeURIComponent(match ? match[1] : null),
  707. element: element,
  708. parent: parent,
  709. children: [],
  710. position: parent.children.length,
  711. container: $(children[i]).down(options.treeTag)
  712. }
  713. /* Get the element containing the children and recurse over it */
  714. if (child.container)
  715. this._tree(child.container, options, child)
  716. parent.children.push (child);
  717. }
  718. return parent;
  719. },
  720. tree: function(element) {
  721. element = $(element);
  722. var sortableOptions = this.options(element);
  723. var options = Object.extend({
  724. tag: sortableOptions.tag,
  725. treeTag: sortableOptions.treeTag,
  726. only: sortableOptions.only,
  727. name: element.id,
  728. format: sortableOptions.format
  729. }, arguments[1] || { });
  730. var root = {
  731. id: null,
  732. parent: null,
  733. children: [],
  734. container: element,
  735. position: 0
  736. }
  737. return Sortable._tree(element, options, root);
  738. },
  739. /* Construct a [i] index for a particular node */
  740. _constructIndex: function(node) {
  741. var index = '';
  742. do {
  743. if (node.id) index = '[' + node.position + ']' + index;
  744. } while ((node = node.parent) != null);
  745. return index;
  746. },
  747. sequence: function(element) {
  748. element = $(element);
  749. var options = Object.extend(this.options(element), arguments[1] || { });
  750. return $(this.findElements(element, options) || []).map( function(item) {
  751. return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
  752. });
  753. },
  754. setSequence: function(element, new_sequence) {
  755. element = $(element);
  756. var options = Object.extend(this.options(element), arguments[2] || { });
  757. var nodeMap = { };
  758. this.findElements(element, options).each( function(n) {
  759. if (n.id.match(options.format))
  760. nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
  761. n.parentNode.removeChild(n);
  762. });
  763. new_sequence.each(function(ident) {
  764. var n = nodeMap[ident];
  765. if (n) {
  766. n[1].appendChild(n[0]);
  767. delete nodeMap[ident];
  768. }
  769. });
  770. },
  771. serialize: function(element) {
  772. element = $(element);
  773. var options = Object.extend(Sortable.options(element), arguments[1] || { });
  774. var name = encodeURIComponent(
  775. (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
  776. if (options.tree) {
  777. return Sortable.tree(element, arguments[1]).children.map( function (item) {
  778. return [name + Sortable._constructIndex(item) + "[id]=" +
  779. encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
  780. }).flatten().join('&');
  781. } else {
  782. return Sortable.sequence(element, arguments[1]).map( function(item) {
  783. return name + "[]=" + encodeURIComponent(item);
  784. }).join('&');
  785. }
  786. }
  787. }
  788. // Returns true if child is contained within element
  789. Element.isParent = function(child, element) {
  790. if (!child.parentNode || child == element) return false;
  791. if (child.parentNode == element) return true;
  792. return Element.isParent(child.parentNode, element);
  793. }
  794. Element.findChildren = function(element, only, recursive, tagName) {
  795. if(!element.hasChildNodes()) return null;
  796. tagName = tagName.toUpperCase();
  797. if(only) only = [only].flatten();
  798. var elements = [];
  799. $A(element.childNodes).each( function(e) {
  800. if(e.tagName && e.tagName.toUpperCase()==tagName &&
  801. (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
  802. elements.push(e);
  803. if(recursive) {
  804. var grandchildren = Element.findChildren(e, only, recursive, tagName);
  805. if(grandchildren) elements.push(grandchildren);
  806. }
  807. });
  808. return (elements.length>0 ? elements.flatten() : []);
  809. }
  810. Element.offsetSize = function (element, type) {
  811. return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
  812. }