Basis of rails driven photo website with a Flash uploader
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

972 lines
30 KiB

15 years ago
  1. // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
  2. // (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
  3. //
  4. // script.aculo.us is freely distributable under the terms of an MIT-style license.
  5. // For details, see the script.aculo.us web site: http://script.aculo.us/
  6. if(Object.isUndefined(Effect))
  7. throw("dragdrop.js requires including script.aculo.us' effects.js library");
  8. var Droppables = {
  9. drops: [],
  10. remove: function(element) {
  11. this.drops = this.drops.reject(function(d) { return d.element==$(element) });
  12. },
  13. add: function(element) {
  14. element = $(element);
  15. var options = Object.extend({
  16. greedy: true,
  17. hoverclass: null,
  18. tree: false
  19. }, arguments[1] || { });
  20. // cache containers
  21. if(options.containment) {
  22. options._containers = [];
  23. var containment = options.containment;
  24. if(Object.isArray(containment)) {
  25. containment.each( function(c) { options._containers.push($(c)) });
  26. } else {
  27. options._containers.push($(containment));
  28. }
  29. }
  30. if(options.accept) options.accept = [options.accept].flatten();
  31. Element.makePositioned(element); // fix IE
  32. options.element = element;
  33. this.drops.push(options);
  34. },
  35. findDeepestChild: function(drops) {
  36. deepest = drops[0];
  37. for (i = 1; i < drops.length; ++i)
  38. if (Element.isParent(drops[i].element, deepest.element))
  39. deepest = drops[i];
  40. return deepest;
  41. },
  42. isContained: function(element, drop) {
  43. var containmentNode;
  44. if(drop.tree) {
  45. containmentNode = element.treeNode;
  46. } else {
  47. containmentNode = element.parentNode;
  48. }
  49. return drop._containers.detect(function(c) { return containmentNode == c });
  50. },
  51. isAffected: function(point, element, drop) {
  52. return (
  53. (drop.element!=element) &&
  54. ((!drop._containers) ||
  55. this.isContained(element, drop)) &&
  56. ((!drop.accept) ||
  57. (Element.classNames(element).detect(
  58. function(v) { return drop.accept.include(v) } ) )) &&
  59. Position.within(drop.element, point[0], point[1]) );
  60. },
  61. deactivate: function(drop) {
  62. if(drop.hoverclass)
  63. Element.removeClassName(drop.element, drop.hoverclass);
  64. this.last_active = null;
  65. },
  66. activate: function(drop) {
  67. if(drop.hoverclass)
  68. Element.addClassName(drop.element, drop.hoverclass);
  69. this.last_active = drop;
  70. },
  71. show: function(point, element) {
  72. if(!this.drops.length) return;
  73. var drop, affected = [];
  74. this.drops.each( function(drop) {
  75. if(Droppables.isAffected(point, element, drop))
  76. affected.push(drop);
  77. });
  78. if(affected.length>0)
  79. drop = Droppables.findDeepestChild(affected);
  80. if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
  81. if (drop) {
  82. Position.within(drop.element, point[0], point[1]);
  83. if(drop.onHover)
  84. drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
  85. if (drop != this.last_active) Droppables.activate(drop);
  86. }
  87. },
  88. fire: function(event, element) {
  89. if(!this.last_active) return;
  90. Position.prepare();
  91. if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
  92. if (this.last_active.onDrop) {
  93. this.last_active.onDrop(element, this.last_active.element, event);
  94. return true;
  95. }
  96. },
  97. reset: function() {
  98. if(this.last_active)
  99. this.deactivate(this.last_active);
  100. }
  101. };
  102. var Draggables = {
  103. drags: [],
  104. observers: [],
  105. register: function(draggable) {
  106. if(this.drags.length == 0) {
  107. this.eventMouseUp = this.endDrag.bindAsEventListener(this);
  108. this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
  109. this.eventKeypress = this.keyPress.bindAsEventListener(this);
  110. Event.observe(document, "mouseup", this.eventMouseUp);
  111. Event.observe(document, "mousemove", this.eventMouseMove);
  112. Event.observe(document, "keypress", this.eventKeypress);
  113. }
  114. this.drags.push(draggable);
  115. },
  116. unregister: function(draggable) {
  117. this.drags = this.drags.reject(function(d) { return d==draggable });
  118. if(this.drags.length == 0) {
  119. Event.stopObserving(document, "mouseup", this.eventMouseUp);
  120. Event.stopObserving(document, "mousemove", this.eventMouseMove);
  121. Event.stopObserving(document, "keypress", this.eventKeypress);
  122. }
  123. },
  124. activate: function(draggable) {
  125. if(draggable.options.delay) {
  126. this._timeout = setTimeout(function() {
  127. Draggables._timeout = null;
  128. window.focus();
  129. Draggables.activeDraggable = draggable;
  130. }.bind(this), draggable.options.delay);
  131. } else {
  132. window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
  133. this.activeDraggable = draggable;
  134. }
  135. },
  136. deactivate: function() {
  137. this.activeDraggable = null;
  138. },
  139. updateDrag: function(event) {
  140. if(!this.activeDraggable) return;
  141. var pointer = [Event.pointerX(event), Event.pointerY(event)];
  142. // Mozilla-based browsers fire successive mousemove events with
  143. // the same coordinates, prevent needless redrawing (moz bug?)
  144. if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
  145. this._lastPointer = pointer;
  146. this.activeDraggable.updateDrag(event, pointer);
  147. },
  148. endDrag: function(event) {
  149. if(this._timeout) {
  150. clearTimeout(this._timeout);
  151. this._timeout = null;
  152. }
  153. if(!this.activeDraggable) return;
  154. this._lastPointer = null;
  155. this.activeDraggable.endDrag(event);
  156. this.activeDraggable = null;
  157. },
  158. keyPress: function(event) {
  159. if(this.activeDraggable)
  160. this.activeDraggable.keyPress(event);
  161. },
  162. addObserver: function(observer) {
  163. this.observers.push(observer);
  164. this._cacheObserverCallbacks();
  165. },
  166. removeObserver: function(element) { // element instead of observer fixes mem leaks
  167. this.observers = this.observers.reject( function(o) { return o.element==element });
  168. this._cacheObserverCallbacks();
  169. },
  170. notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
  171. if(this[eventName+'Count'] > 0)
  172. this.observers.each( function(o) {
  173. if(o[eventName]) o[eventName](eventName, draggable, event);
  174. });
  175. if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
  176. },
  177. _cacheObserverCallbacks: function() {
  178. ['onStart','onEnd','onDrag'].each( function(eventName) {
  179. Draggables[eventName+'Count'] = Draggables.observers.select(
  180. function(o) { return o[eventName]; }
  181. ).length;
  182. });
  183. }
  184. };
  185. /*--------------------------------------------------------------------------*/
  186. var Draggable = Class.create({
  187. initialize: function(element) {
  188. var defaults = {
  189. handle: false,
  190. reverteffect: function(element, top_offset, left_offset) {
  191. var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
  192. new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
  193. queue: {scope:'_draggable', position:'end'}
  194. });
  195. },
  196. endeffect: function(element) {
  197. var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
  198. new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
  199. queue: {scope:'_draggable', position:'end'},
  200. afterFinish: function(){
  201. Draggable._dragging[element] = false
  202. }
  203. });
  204. },
  205. zindex: 1000,
  206. revert: false,
  207. quiet: false,
  208. scroll: false,
  209. scrollSensitivity: 20,
  210. scrollSpeed: 15,
  211. snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
  212. delay: 0
  213. };
  214. if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
  215. Object.extend(defaults, {
  216. starteffect: function(element) {
  217. element._opacity = Element.getOpacity(element);
  218. Draggable._dragging[element] = true;
  219. new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
  220. }
  221. });
  222. var options = Object.extend(defaults, arguments[1] || { });
  223. this.element = $(element);
  224. if(options.handle && Object.isString(options.handle))
  225. this.handle = this.element.down('.'+options.handle, 0);
  226. if(!this.handle) this.handle = $(options.handle);
  227. if(!this.handle) this.handle = this.element;
  228. if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
  229. options.scroll = $(options.scroll);
  230. this._isScrollChild = Element.childOf(this.element, options.scroll);
  231. }
  232. Element.makePositioned(this.element); // fix IE
  233. this.options = options;
  234. this.dragging = false;
  235. this.eventMouseDown = this.initDrag.bindAsEventListener(this);
  236. Event.observe(this.handle, "mousedown", this.eventMouseDown);
  237. Draggables.register(this);
  238. },
  239. destroy: function() {
  240. Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
  241. Draggables.unregister(this);
  242. },
  243. currentDelta: function() {
  244. return([
  245. parseInt(Element.getStyle(this.element,'left') || '0'),
  246. parseInt(Element.getStyle(this.element,'top') || '0')]);
  247. },
  248. initDrag: function(event) {
  249. if(!Object.isUndefined(Draggable._dragging[this.element]) &&
  250. Draggable._dragging[this.element]) return;
  251. if(Event.isLeftClick(event)) {
  252. // abort on form elements, fixes a Firefox issue
  253. var src = Event.element(event);
  254. if((tag_name = src.tagName.toUpperCase()) && (
  255. tag_name=='INPUT' ||
  256. tag_name=='SELECT' ||
  257. tag_name=='OPTION' ||
  258. tag_name=='BUTTON' ||
  259. tag_name=='TEXTAREA')) return;
  260. var pointer = [Event.pointerX(event), Event.pointerY(event)];
  261. var pos = Position.cumulativeOffset(this.element);
  262. this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
  263. Draggables.activate(this);
  264. Event.stop(event);
  265. }
  266. },
  267. startDrag: function(event) {
  268. this.dragging = true;
  269. if(!this.delta)
  270. this.delta = this.currentDelta();
  271. if(this.options.zindex) {
  272. this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
  273. this.element.style.zIndex = this.options.zindex;
  274. }
  275. if(this.options.ghosting) {
  276. this._clone = this.element.cloneNode(true);
  277. this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
  278. if (!this._originallyAbsolute)
  279. Position.absolutize(this.element);
  280. this.element.parentNode.insertBefore(this._clone, this.element);
  281. }
  282. if(this.options.scroll) {
  283. if (this.options.scroll == window) {
  284. var where = this._getWindowScroll(this.options.scroll);
  285. this.originalScrollLeft = where.left;
  286. this.originalScrollTop = where.top;
  287. } else {
  288. this.originalScrollLeft = this.options.scroll.scrollLeft;
  289. this.originalScrollTop = this.options.scroll.scrollTop;
  290. }
  291. }
  292. Draggables.notify('onStart', this, event);
  293. if(this.options.starteffect) this.options.starteffect(this.element);
  294. },
  295. updateDrag: function(event, pointer) {
  296. if(!this.dragging) this.startDrag(event);
  297. if(!this.options.quiet){
  298. Position.prepare();
  299. Droppables.show(pointer, this.element);
  300. }
  301. Draggables.notify('onDrag', this, event);
  302. this.draw(pointer);
  303. if(this.options.change) this.options.change(this);
  304. if(this.options.scroll) {
  305. this.stopScrolling();
  306. var p;
  307. if (this.options.scroll == window) {
  308. with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
  309. } else {
  310. p = Position.page(this.options.scroll);
  311. p[0] += this.options.scroll.scrollLeft + Position.deltaX;
  312. p[1] += this.options.scroll.scrollTop + Position.deltaY;
  313. p.push(p[0]+this.options.scroll.offsetWidth);
  314. p.push(p[1]+this.options.scroll.offsetHeight);
  315. }
  316. var speed = [0,0];
  317. if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
  318. if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
  319. if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
  320. if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
  321. this.startScrolling(speed);
  322. }
  323. // fix AppleWebKit rendering
  324. if(Prototype.Browser.WebKit) window.scrollBy(0,0);
  325. Event.stop(event);
  326. },
  327. finishDrag: function(event, success) {
  328. this.dragging = false;
  329. if(this.options.quiet){
  330. Position.prepare();
  331. var pointer = [Event.pointerX(event), Event.pointerY(event)];
  332. Droppables.show(pointer, this.element);
  333. }
  334. if(this.options.ghosting) {
  335. if (!this._originallyAbsolute)
  336. Position.relativize(this.element);
  337. delete this._originallyAbsolute;
  338. Element.remove(this._clone);
  339. this._clone = null;
  340. }
  341. var dropped = false;
  342. if(success) {
  343. dropped = Droppables.fire(event, this.element);
  344. if (!dropped) dropped = false;
  345. }
  346. if(dropped && this.options.onDropped) this.options.onDropped(this.element);
  347. Draggables.notify('onEnd', this, event);
  348. var revert = this.options.revert;
  349. if(revert && Object.isFunction(revert)) revert = revert(this.element);
  350. var d = this.currentDelta();
  351. if(revert && this.options.reverteffect) {
  352. if (dropped == 0 || revert != 'failure')
  353. this.options.reverteffect(this.element,
  354. d[1]-this.delta[1], d[0]-this.delta[0]);
  355. } else {
  356. this.delta = d;
  357. }
  358. if(this.options.zindex)
  359. this.element.style.zIndex = this.originalZ;
  360. if(this.options.endeffect)
  361. this.options.endeffect(this.element);
  362. Draggables.deactivate(this);
  363. Droppables.reset();
  364. },
  365. keyPress: function(event) {
  366. if(event.keyCode!=Event.KEY_ESC) return;
  367. this.finishDrag(event, false);
  368. Event.stop(event);
  369. },
  370. endDrag: function(event) {
  371. if(!this.dragging) return;
  372. this.stopScrolling();
  373. this.finishDrag(event, true);
  374. Event.stop(event);
  375. },
  376. draw: function(point) {
  377. var pos = Position.cumulativeOffset(this.element);
  378. if(this.options.ghosting) {
  379. var r = Position.realOffset(this.element);
  380. pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
  381. }
  382. var d = this.currentDelta();
  383. pos[0] -= d[0]; pos[1] -= d[1];
  384. if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
  385. pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
  386. pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
  387. }
  388. var p = [0,1].map(function(i){
  389. return (point[i]-pos[i]-this.offset[i])
  390. }.bind(this));
  391. if(this.options.snap) {
  392. if(Object.isFunction(this.options.snap)) {
  393. p = this.options.snap(p[0],p[1],this);
  394. } else {
  395. if(Object.isArray(this.options.snap)) {
  396. p = p.map( function(v, i) {
  397. return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
  398. } else {
  399. p = p.map( function(v) {
  400. return (v/this.options.snap).round()*this.options.snap }.bind(this));
  401. }
  402. }}
  403. var style = this.element.style;
  404. if((!this.options.constraint) || (this.options.constraint=='horizontal'))
  405. style.left = p[0] + "px";
  406. if((!this.options.constraint) || (this.options.constraint=='vertical'))
  407. style.top = p[1] + "px";
  408. if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
  409. },
  410. stopScrolling: function() {
  411. if(this.scrollInterval) {
  412. clearInterval(this.scrollInterval);
  413. this.scrollInterval = null;
  414. Draggables._lastScrollPointer = null;
  415. }
  416. },
  417. startScrolling: function(speed) {
  418. if(!(speed[0] || speed[1])) return;
  419. this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
  420. this.lastScrolled = new Date();
  421. this.scrollInterval = setInterval(this.scroll.bind(this), 10);
  422. },
  423. scroll: function() {
  424. var current = new Date();
  425. var delta = current - this.lastScrolled;
  426. this.lastScrolled = current;
  427. if(this.options.scroll == window) {
  428. with (this._getWindowScroll(this.options.scroll)) {
  429. if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
  430. var d = delta / 1000;
  431. this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
  432. }
  433. }
  434. } else {
  435. this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
  436. this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
  437. }
  438. Position.prepare();
  439. Droppables.show(Draggables._lastPointer, this.element);
  440. Draggables.notify('onDrag', this);
  441. if (this._isScrollChild) {
  442. Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
  443. Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
  444. Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
  445. if (Draggables._lastScrollPointer[0] < 0)
  446. Draggables._lastScrollPointer[0] = 0;
  447. if (Draggables._lastScrollPointer[1] < 0)
  448. Draggables._lastScrollPointer[1] = 0;
  449. this.draw(Draggables._lastScrollPointer);
  450. }
  451. if(this.options.change) this.options.change(this);
  452. },
  453. _getWindowScroll: function(w) {
  454. var T, L, W, H;
  455. with (w.document) {
  456. if (w.document.documentElement && documentElement.scrollTop) {
  457. T = documentElement.scrollTop;
  458. L = documentElement.scrollLeft;
  459. } else if (w.document.body) {
  460. T = body.scrollTop;
  461. L = body.scrollLeft;
  462. }
  463. if (w.innerWidth) {
  464. W = w.innerWidth;
  465. H = w.innerHeight;
  466. } else if (w.document.documentElement && documentElement.clientWidth) {
  467. W = documentElement.clientWidth;
  468. H = documentElement.clientHeight;
  469. } else {
  470. W = body.offsetWidth;
  471. H = body.offsetHeight;
  472. }
  473. }
  474. return { top: T, left: L, width: W, height: H };
  475. }
  476. });
  477. Draggable._dragging = { };
  478. /*--------------------------------------------------------------------------*/
  479. var SortableObserver = Class.create({
  480. initialize: function(element, observer) {
  481. this.element = $(element);
  482. this.observer = observer;
  483. this.lastValue = Sortable.serialize(this.element);
  484. },
  485. onStart: function() {
  486. this.lastValue = Sortable.serialize(this.element);
  487. },
  488. onEnd: function() {
  489. Sortable.unmark();
  490. if(this.lastValue != Sortable.serialize(this.element))
  491. this.observer(this.element)
  492. }
  493. });
  494. var Sortable = {
  495. SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
  496. sortables: { },
  497. _findRootElement: function(element) {
  498. while (element.tagName.toUpperCase() != "BODY") {
  499. if(element.id && Sortable.sortables[element.id]) return element;
  500. element = element.parentNode;
  501. }
  502. },
  503. options: function(element) {
  504. element = Sortable._findRootElement($(element));
  505. if(!element) return;
  506. return Sortable.sortables[element.id];
  507. },
  508. destroy: function(element){
  509. element = $(element);
  510. var s = Sortable.sortables[element.id];
  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. };