dragdrop.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. // script.aculo.us dragdrop.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
  2. // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
  3. // (c) 2005-2008 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._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
  279. if (!this._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._originallyAbsolute)
  337. Position.relativize(this.element);
  338. delete this._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. element = $(element);
  511. var s = Sortable.sortables[element.id];
  512. if(s) {
  513. Draggables.removeObserver(s.element);
  514. s.droppables.each(function(d){ Droppables.remove(d) });
  515. s.draggables.invoke('destroy');
  516. delete Sortable.sortables[s.element.id];
  517. }
  518. },
  519. create: function(element) {
  520. element = $(element);
  521. var options = Object.extend({
  522. element: element,
  523. tag: 'li', // assumes li children, override with tag: 'tagname'
  524. dropOnEmpty: false,
  525. tree: false,
  526. treeTag: 'ul',
  527. overlap: 'vertical', // one of 'vertical', 'horizontal'
  528. constraint: 'vertical', // one of 'vertical', 'horizontal', false
  529. containment: element, // also takes array of elements (or id's); or false
  530. handle: false, // or a CSS class
  531. only: false,
  532. delay: 0,
  533. hoverclass: null,
  534. ghosting: false,
  535. quiet: false,
  536. scroll: false,
  537. scrollSensitivity: 20,
  538. scrollSpeed: 15,
  539. format: this.SERIALIZE_RULE,
  540. // these take arrays of elements or ids and can be
  541. // used for better initialization performance
  542. elements: false,
  543. handles: false,
  544. onChange: Prototype.emptyFunction,
  545. onUpdate: Prototype.emptyFunction
  546. }, arguments[1] || { });
  547. // clear any old sortable with same element
  548. this.destroy(element);
  549. // build options for the draggables
  550. var options_for_draggable = {
  551. revert: true,
  552. quiet: options.quiet,
  553. scroll: options.scroll,
  554. scrollSpeed: options.scrollSpeed,
  555. scrollSensitivity: options.scrollSensitivity,
  556. delay: options.delay,
  557. ghosting: options.ghosting,
  558. constraint: options.constraint,
  559. handle: options.handle };
  560. if(options.starteffect)
  561. options_for_draggable.starteffect = options.starteffect;
  562. if(options.reverteffect)
  563. options_for_draggable.reverteffect = options.reverteffect;
  564. else
  565. if(options.ghosting) options_for_draggable.reverteffect = function(element) {
  566. element.style.top = 0;
  567. element.style.left = 0;
  568. };
  569. if(options.endeffect)
  570. options_for_draggable.endeffect = options.endeffect;
  571. if(options.zindex)
  572. options_for_draggable.zindex = options.zindex;
  573. // build options for the droppables
  574. var options_for_droppable = {
  575. overlap: options.overlap,
  576. containment: options.containment,
  577. tree: options.tree,
  578. hoverclass: options.hoverclass,
  579. onHover: Sortable.onHover
  580. };
  581. var options_for_tree = {
  582. onHover: Sortable.onEmptyHover,
  583. overlap: options.overlap,
  584. containment: options.containment,
  585. hoverclass: options.hoverclass
  586. };
  587. // fix for gecko engine
  588. Element.cleanWhitespace(element);
  589. options.draggables = [];
  590. options.droppables = [];
  591. // drop on empty handling
  592. if(options.dropOnEmpty || options.tree) {
  593. Droppables.add(element, options_for_tree);
  594. options.droppables.push(element);
  595. }
  596. (options.elements || this.findElements(element, options) || []).each( function(e,i) {
  597. var handle = options.handles ? $(options.handles[i]) :
  598. (options.handle ? $(e).select('.' + options.handle)[0] : e);
  599. options.draggables.push(
  600. new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
  601. Droppables.add(e, options_for_droppable);
  602. if(options.tree) e.treeNode = element;
  603. options.droppables.push(e);
  604. });
  605. if(options.tree) {
  606. (Sortable.findTreeElements(element, options) || []).each( function(e) {
  607. Droppables.add(e, options_for_tree);
  608. e.treeNode = element;
  609. options.droppables.push(e);
  610. });
  611. }
  612. // keep reference
  613. this.sortables[element.id] = options;
  614. // for onupdate
  615. Draggables.addObserver(new SortableObserver(element, options.onUpdate));
  616. },
  617. // return all suitable-for-sortable elements in a guaranteed order
  618. findElements: function(element, options) {
  619. return Element.findChildren(
  620. element, options.only, options.tree ? true : false, options.tag);
  621. },
  622. findTreeElements: function(element, options) {
  623. return Element.findChildren(
  624. element, options.only, options.tree ? true : false, options.treeTag);
  625. },
  626. onHover: function(element, dropon, overlap) {
  627. if(Element.isParent(dropon, element)) return;
  628. if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
  629. return;
  630. } else if(overlap>0.5) {
  631. Sortable.mark(dropon, 'before');
  632. if(dropon.previousSibling != element) {
  633. var oldParentNode = element.parentNode;
  634. element.style.visibility = "hidden"; // fix gecko rendering
  635. dropon.parentNode.insertBefore(element, dropon);
  636. if(dropon.parentNode!=oldParentNode)
  637. Sortable.options(oldParentNode).onChange(element);
  638. Sortable.options(dropon.parentNode).onChange(element);
  639. }
  640. } else {
  641. Sortable.mark(dropon, 'after');
  642. var nextElement = dropon.nextSibling || null;
  643. if(nextElement != element) {
  644. var oldParentNode = element.parentNode;
  645. element.style.visibility = "hidden"; // fix gecko rendering
  646. dropon.parentNode.insertBefore(element, nextElement);
  647. if(dropon.parentNode!=oldParentNode)
  648. Sortable.options(oldParentNode).onChange(element);
  649. Sortable.options(dropon.parentNode).onChange(element);
  650. }
  651. }
  652. },
  653. onEmptyHover: function(element, dropon, overlap) {
  654. var oldParentNode = element.parentNode;
  655. var droponOptions = Sortable.options(dropon);
  656. if(!Element.isParent(dropon, element)) {
  657. var index;
  658. var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
  659. var child = null;
  660. if(children) {
  661. var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
  662. for (index = 0; index < children.length; index += 1) {
  663. if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
  664. offset -= Element.offsetSize (children[index], droponOptions.overlap);
  665. } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
  666. child = index + 1 < children.length ? children[index + 1] : null;
  667. break;
  668. } else {
  669. child = children[index];
  670. break;
  671. }
  672. }
  673. }
  674. dropon.insertBefore(element, child);
  675. Sortable.options(oldParentNode).onChange(element);
  676. droponOptions.onChange(element);
  677. }
  678. },
  679. unmark: function() {
  680. if(Sortable._marker) Sortable._marker.hide();
  681. },
  682. mark: function(dropon, position) {
  683. // mark on ghosting only
  684. var sortable = Sortable.options(dropon.parentNode);
  685. if(sortable && !sortable.ghosting) return;
  686. if(!Sortable._marker) {
  687. Sortable._marker =
  688. ($('dropmarker') || Element.extend(document.createElement('DIV'))).
  689. hide().addClassName('dropmarker').setStyle({position:'absolute'});
  690. document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
  691. }
  692. var offsets = Position.cumulativeOffset(dropon);
  693. Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
  694. if(position=='after')
  695. if(sortable.overlap == 'horizontal')
  696. Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
  697. else
  698. Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
  699. Sortable._marker.show();
  700. },
  701. _tree: function(element, options, parent) {
  702. var children = Sortable.findElements(element, options) || [];
  703. for (var i = 0; i < children.length; ++i) {
  704. var match = children[i].id.match(options.format);
  705. if (!match) continue;
  706. var child = {
  707. id: encodeURIComponent(match ? match[1] : null),
  708. element: element,
  709. parent: parent,
  710. children: [],
  711. position: parent.children.length,
  712. container: $(children[i]).down(options.treeTag)
  713. };
  714. /* Get the element containing the children and recurse over it */
  715. if (child.container)
  716. this._tree(child.container, options, child);
  717. parent.children.push (child);
  718. }
  719. return parent;
  720. },
  721. tree: function(element) {
  722. element = $(element);
  723. var sortableOptions = this.options(element);
  724. var options = Object.extend({
  725. tag: sortableOptions.tag,
  726. treeTag: sortableOptions.treeTag,
  727. only: sortableOptions.only,
  728. name: element.id,
  729. format: sortableOptions.format
  730. }, arguments[1] || { });
  731. var root = {
  732. id: null,
  733. parent: null,
  734. children: [],
  735. container: element,
  736. position: 0
  737. };
  738. return Sortable._tree(element, options, root);
  739. },
  740. /* Construct a [i] index for a particular node */
  741. _constructIndex: function(node) {
  742. var index = '';
  743. do {
  744. if (node.id) index = '[' + node.position + ']' + index;
  745. } while ((node = node.parent) != null);
  746. return index;
  747. },
  748. sequence: function(element) {
  749. element = $(element);
  750. var options = Object.extend(this.options(element), arguments[1] || { });
  751. return $(this.findElements(element, options) || []).map( function(item) {
  752. return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
  753. });
  754. },
  755. setSequence: function(element, new_sequence) {
  756. element = $(element);
  757. var options = Object.extend(this.options(element), arguments[2] || { });
  758. var nodeMap = { };
  759. this.findElements(element, options).each( function(n) {
  760. if (n.id.match(options.format))
  761. nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
  762. n.parentNode.removeChild(n);
  763. });
  764. new_sequence.each(function(ident) {
  765. var n = nodeMap[ident];
  766. if (n) {
  767. n[1].appendChild(n[0]);
  768. delete nodeMap[ident];
  769. }
  770. });
  771. },
  772. serialize: function(element) {
  773. element = $(element);
  774. var options = Object.extend(Sortable.options(element), arguments[1] || { });
  775. var name = encodeURIComponent(
  776. (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
  777. if (options.tree) {
  778. return Sortable.tree(element, arguments[1]).children.map( function (item) {
  779. return [name + Sortable._constructIndex(item) + "[id]=" +
  780. encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
  781. }).flatten().join('&');
  782. } else {
  783. return Sortable.sequence(element, arguments[1]).map( function(item) {
  784. return name + "[]=" + encodeURIComponent(item);
  785. }).join('&');
  786. }
  787. }
  788. };
  789. // Returns true if child is contained within element
  790. Element.isParent = function(child, element) {
  791. if (!child.parentNode || child == element) return false;
  792. if (child.parentNode == element) return true;
  793. return Element.isParent(child.parentNode, element);
  794. };
  795. Element.findChildren = function(element, only, recursive, tagName) {
  796. if(!element.hasChildNodes()) return null;
  797. tagName = tagName.toUpperCase();
  798. if(only) only = [only].flatten();
  799. var elements = [];
  800. $A(element.childNodes).each( function(e) {
  801. if(e.tagName && e.tagName.toUpperCase()==tagName &&
  802. (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
  803. elements.push(e);
  804. if(recursive) {
  805. var grandchildren = Element.findChildren(e, only, recursive, tagName);
  806. if(grandchildren) elements.push(grandchildren);
  807. }
  808. });
  809. return (elements.length>0 ? elements.flatten() : []);
  810. };
  811. Element.offsetSize = function (element, type) {
  812. return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
  813. };