Browse Source

Setup dragger for canvas and refactor zoom

pull/1800/head
Artur Arseniev 8 years ago
parent
commit
ca8a50faeb
  1. 2
      dist/css/grapes.min.css
  2. 8
      src/canvas/index.js
  3. 16
      src/canvas/model/Canvas.js
  4. 20
      src/canvas/view/CanvasView.js
  5. 79
      src/commands/view/CanvasMove.js
  6. 3
      src/editor/model/Editor.js
  7. 7
      src/styles/scss/_gjs_canvas.scss
  8. 18
      src/styles/scss/_gjs_status.scss
  9. 2
      src/styles/scss/main.scss
  10. 407
      src/utils/Dragger.js

2
dist/css/grapes.min.css

File diff suppressed because one or more lines are too long

8
src/canvas/index.js

@ -516,6 +516,14 @@ module.exports = () => {
if (hasDnd(c.em)) this.droppable = new Droppable(c.em);
},
getZoom() {
return parseFloat(canvas.get('zoom'));
},
getZoomDecimal() {
return this.getZoom() / 100;
},
/**
* Returns wrapper element
* @return {HTMLElement}

16
src/canvas/model/Canvas.js

@ -5,11 +5,19 @@ module.exports = Backbone.Model.extend({
defaults: {
frame: '',
wrapper: '',
rulers: false
rulers: false,
zoom: 100,
x: 0,
y: 0
},
initialize(config) {
var conf = this.conf || {};
this.set('frame', new Frame(conf.frame));
initialize() {
this.set('frame', new Frame());
this.listenTo(this, 'change:zoom', this.onZoomChange);
},
onZoomChange() {
const zoom = this.get('zoom');
zoom < 1 && this.set('zoom', 1);
}
});

20
src/canvas/view/CanvasView.js

@ -11,7 +11,7 @@ module.exports = Backbone.View.extend({
template() {
const { pfx } = this;
return `<div class="${pfx}canvas__area">
return `<div class="${pfx}canvas__area" data-canvas-area>
<div class="${pfx}canvas__frames" data-frames></div>
<div id="${pfx}tools" class="${pfx}canvas__tools" data-tools></div>
</div>`;
@ -20,13 +20,15 @@ module.exports = Backbone.View.extend({
initialize(o) {
_.bindAll(this, 'renderBody', 'onFrameScroll', 'clearOff', 'onKeyPress');
on(window, 'scroll resize', this.clearOff);
const { model } = this;
this.config = o.config || {};
this.em = this.config.em || {};
this.pfx = this.config.stylePrefix || '';
this.ppfx = this.config.pStylePrefix || '';
this.className = this.config.stylePrefix + 'canvas';
this.listenTo(this.em, 'change:canvasOffset', this.clearOff);
this.listenTo(this.em, 'change:zoom', this.onZoomChange);
this.listenTo(model, 'change:zoom', this.onZoomChange);
this.listenTo(model, 'change:x change:y', this.onPosChange);
this.toggleListeners(1);
this.frame = new FrameView({
model: this.model.get('frame'),
@ -65,10 +67,10 @@ module.exports = Backbone.View.extend({
onWheel(ev) {
if (ev.ctrlKey || ev.metaKey) {
this.preventDefault(ev);
const { em } = this;
const { model } = this;
const delta = Math.max(-1, Math.min(1, ev.wheelDelta || -ev.detail));
const zoom = em.get('zoom');
em.set('zoom', zoom + delta * 2);
const zoom = model.get('zoom');
model.set('zoom', zoom + delta * 2);
}
},
@ -83,8 +85,13 @@ module.exports = Backbone.View.extend({
timerZoom = setTimeout(() => em.runDefault(defOpts));
},
onPosChange() {
const { x, y } = this.model.attributes;
this.canvasAreaEl.style.transform = `translate(${x}px, ${y}px)`;
},
getZoom() {
return this.em.get('zoom') / 100;
return this.em.getZoomDecimal();
},
/**
@ -477,6 +484,7 @@ module.exports = Backbone.View.extend({
this.resizerEl = el.querySelector(`.${ppfx}resizer`);
this.offsetEl = el.querySelector(`.${ppfx}offset-v`);
this.fixedOffsetEl = el.querySelector(`.${ppfx}offset-fixed-v`);
this.canvasAreaEl = $el.find('[data-canvas-area]').get(0);
this.toolsEl = toolsEl;
this.el.className = this.className;
return this;

79
src/commands/view/CanvasMove.js

@ -1,7 +1,80 @@
import { bindAll } from 'underscore';
import { on, off, getKeyChar } from 'utils/mixins';
import Dragger from 'utils/Dragger';
module.exports = {
run(ed) {
console.log('run CANVAS MOVE command');
// add move cursor on canvas grab grabbing
bindAll(this, 'onKeyUp', 'enableDragger', 'disableDragger');
this.editor = ed;
this.canvasModel = this.canvas.getCanvasView().model;
this.toggleMove(1);
},
stop(ed) {}
stop(ed) {
this.toggleMove();
this.disableDragger();
},
onKeyUp(ev) {
if (getKeyChar(ev) === ' ') {
this.editor.stopCommand(this.id);
}
},
enableDragger(ev) {
this.toggleDragger(1, ev);
},
disableDragger(ev) {
this.toggleDragger(0, ev);
},
toggleDragger(enable, ev) {
const { canvasModel } = this;
let { dragger } = this;
const methodCls = enable ? 'add' : 'remove';
this.getCanvas().classList[methodCls](`${this.ppfx}is__grabbing`);
if (!dragger) {
dragger = Dragger.init({
getPosition() {
return {
x: canvasModel.get('x'),
y: canvasModel.get('y')
};
},
setPosition({ x, y }) {
canvasModel.set({ x, y });
}
// onStart(ev, dragger) {
// console.log('START');
// console.log('pointer start', dragger.startPointer, 'position start', dragger.startPosition);
// },
// onDrag(ev, dragger) {
// console.log('DRAG');
// console.log('pointer', dragger.currentPointer, 'position', dragger.position, 'delta', dragger.delta);
// },
// onEnd(ev, dragger) {
// console.log('END');
// console.log('pointer', dragger.currentPointer, 'position', dragger.position, 'delta', dragger.delta);
// },
});
this.dragger = dragger;
}
enable ? dragger.start(ev) : dragger.stop();
},
toggleMove(enable) {
const { ppfx } = this;
const methodCls = enable ? 'add' : 'remove';
const methodEv = enable ? 'on' : 'off';
const methodsEv = { on, off };
const canvas = this.getCanvas();
const classes = [`${ppfx}is__grab`];
!enable && classes.push(`${ppfx}is__grabbing`);
classes.forEach(cls => canvas.classList[methodCls](cls));
methodsEv[methodEv](document, 'keyup', this.onKeyUp);
methodsEv[methodEv](canvas, 'mousedown', this.enableDragger);
methodsEv[methodEv](document, 'mouseup', this.disableDragger);
}
};

3
src/editor/model/Editor.js

@ -51,7 +51,6 @@ const logs = {
module.exports = Backbone.Model.extend({
defaults() {
return {
zoom: 100,
editing: 0,
selected: new Collection(),
clipboard: null,
@ -610,7 +609,7 @@ module.exports = Backbone.Model.extend({
},
getZoomDecimal() {
return this.get('zoom') / 100;
return this.get('Canvas').getZoomDecimal();
},
/**

7
src/styles/scss/_gjs_canvas.scss

@ -13,6 +13,13 @@ $canvasTop: 40px;
left: 0;
top: 40px;
&#{gjs-is(grab)},
&#{gjs-is(grabbing)} {
.#{$cv-prefix}canvas__area {
pointer-events: none;
}
}
&__area,
&__frames {
position: absolute;

18
src/styles/scss/_gjs_status.scss

@ -0,0 +1,18 @@
$gjs-is-prefix: '.#{$app-prefix}is__';
@function gjs-is($name) {
@return '#{$gjs-is-prefix}#{$name}';
}
#{$gjs-is-prefix} {
&grab,
&grab * {
cursor: grab !important;
}
&grabbing,
&grabbing * {
@include user-select(none);
cursor: grabbing !important;
}
}

2
src/styles/scss/main.scss

@ -50,6 +50,8 @@
$prefix: $app-prefix;
@import "gjs_status";
.#{$prefix} {
@each $cnum, $ccol in (one, $primaryColor), (two, $secondaryColor), (three, $tertiaryColor), (four, $quaternaryColor) {
&#{$cnum} {

407
src/utils/Dragger.js

@ -1,48 +1,53 @@
import Backbone from 'backbone';
const $ = Backbone.$;
var getBoundingRect = (el, win) => {
var w = win || window;
var rect = el.getBoundingClientRect();
return {
left: rect.left + w.pageXOffset,
top: rect.top + w.pageYOffset,
width: rect.width,
height: rect.height
};
};
module.exports = {
// TODO move to opts
setKey(keys, command) {
//key(keys, command);
},
import { bindAll, isFunction } from 'underscore';
import { on, off } from 'utils/mixins';
const options = {
/**
* Return element position
* @param {HTMLElement} el
* @return {Object}
* Callback on start
* onStart(ev, dragger) {
* console.log('pointer start', dragger.startPointer, 'position start', dragger.startPosition);
* },
*/
getElementRect(el) {
var posFetcher = this.opts.posFetcher || '';
return posFetcher
? posFetcher(el, {
avoidFrameOffset: 1
})
: getBoundingRect(el);
},
onStart: null,
/**
* Callback on drag
* onDrag(ev, dragger) {
* console.log('pointer', dragger.currentPointer, 'position', dragger.position, 'delta', dragger.delta);
* },
*/
onDrag: null,
/**
* Callback on drag
* onEnd(ev, dragger) {
* console.log('pointer', dragger.currentPointer, 'position', dragger.position, 'delta', dragger.delta);
* },
*/
onEnd: null,
/**
* Indicate a callback where to pass an object with new coordinates
*/
setPosition: null,
/**
* Indicate a callback where to get initial coordinates.
* getPosition: () => {
* ...
* return { x: 10, y: 100 }
* }
*/
getPosition: null
};
module.exports = {
/**
* Init the resizer
* @param {Object} opts
*/
init(opts) {
bindAll(this, 'drag', 'stop');
this.opts = options;
this.setOptions(opts);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.drag = this.drag.bind(this);
this.move = this.move.bind(this);
this.stop = this.stop.bind(this);
this.setKey('up, right, down, left', this.handleKey);
this.delta = { x: 0, y: 0 };
this.startPosition = this.getStartPosition();
return this;
},
@ -50,135 +55,105 @@ module.exports = {
* Update options
* @param {Object} options
*/
setOptions(opts) {
this.opts = opts || {};
setOptions(opts = {}) {
this.opts = {
...this.opts,
...opts
};
},
/**
* Focus dragger on the element
* @param {HTMLElement} el
*/
focus(el) {
// Avoid focusing on already focused element
if (el && el === this.el) {
return;
}
this.getDocumentEl(el);
this.blur();
this.el = el;
this.handlers = this.opts.dragHandlers || [el];
var elRect = this.getElementRect(el); //<-- TODO have wrong top:left
this.elRect = elRect;
this.startTop = elRect.top;
this.startLeft = elRect.left;
// TODO init snapper
this.getDocumentEl().on('mousedown', this.handleMouseDown);
toggleDrag(enable) {
const docs = this.getDocumentEl();
const method = enable ? 'on' : 'off';
const methods = { on, off };
methods[method](docs, 'mousemove', this.drag);
methods[method](docs, 'mouseup', this.stop);
},
/**
* Blur from the focused element
* Start dragging
* @param {Event} e
*/
blur() {
this.getDocumentEl().off('mousedown', this.handleMouseDown);
this.el = null;
start(ev) {
const { onStart } = this.opts;
this.toggleDrag(1);
this.startPointer = this.getPointerPos(ev);
this.startPosition = this.getStartPosition();
isFunction(onStart) && onStart(ev, this);
this.drag(ev);
},
/**
* Start dragging
* @param {Event} e
* Drag event
* @param {Event} event
*/
start(e) {
this.startPos = this.getMousePos(e);
var docs = this.getDocumentEl();
docs.on('mousemove', this.drag);
docs.on('mouseup', this.stop);
drag(ev) {
const { startPointer } = this;
const currentPos = this.getPointerPos(ev);
const delta = {
x: currentPos.x - startPointer.x,
y: currentPos.y - startPointer.y
};
let { lockedAxis } = this;
// Start callback
var onStart = this.opts.onStart;
if (typeof onStart === 'function') {
onStart(e, {
docs,
el: this.el,
start: this.startPos,
elRect: this.elRect
});
// Lock one axis
if (ev.shiftKey) {
lockedAxis = !lockedAxis && this.detectAxisLock(delta.x, delta.y);
} else {
lockedAxis = null;
}
this.drag(e);
},
if (lockedAxis === 'x') {
delta.x = startPointer.x;
} else if (lockedAxis === 'y') {
delta.y = startPointer.y;
}
/**
* Stop dragging
*/
stop(e) {
var docs = this.getDocumentEl();
docs.off('mousemove', this.drag);
docs.off('mouseup', this.stop);
this.lockedAxis = null;
this.lockedAxis = lockedAxis;
this.delta = delta;
this.move(delta.x, delta.y);
this.currentPointer = currentPos;
const { onDrag } = this.opts;
isFunction(onDrag) && onDrag(ev, this);
// Stop callback
var onEnd = this.opts.onEnd;
if (typeof onEnd === 'function') {
onEnd(e, {
docs,
delta: this.delta,
end: {
x: this.startLeft + this.delta.x,
y: this.startTop + this.delta.y
}
});
}
// In case the mouse button was released outside of the window
ev.which === 0 && this.stop(ev);
},
/**
* Handle mousedown to check if it's possible to drag
* @param {Event} e
* Stop dragging
*/
handleMouseDown(e) {
var el = e.target;
if (this.isHandler(el)) {
this.start(e);
}
stop(ev) {
const { delta } = this;
this.toggleDrag();
this.lockedAxis = null;
this.move(delta.x, delta.y, 1);
const { onEnd } = this.opts;
isFunction(onEnd) && onEnd(ev, this);
},
/**
* Detects if the clicked element is a valid handler
* @param {HTMLElement} el
* @return {Boolean}
* Move the element
* @param {integer} x
* @param {integer} y
*/
isHandler(el) {
var handlers = this.handlers;
for (var n in handlers) {
if (handlers[n] === el) return true;
}
move: function(x, y, end) {
const { el, opts } = this;
const pos = this.startPosition;
const { setPosition } = opts;
const xPos = pos.x + x;
const yPos = pos.y + y;
this.position = {
x: xPos,
y: yPos,
end
};
return false;
},
isFunction(setPosition) && setPosition(this.position);
/**
* Handle key press
* @param {Event} e
* @param {Object} handler
*/
handleKey(e, handler) {
switch (handler.shortcut) {
case 'up':
this.move(0, -1);
break;
case 'right':
this.move(1, 0);
break;
case 'down':
this.move(0, 1);
break;
case 'left':
this.move(-1, 0);
break;
if (el) {
el.style.left = `${xPos}px`;
el.style.top = `${yPos}px`;
}
},
@ -186,15 +161,15 @@ module.exports = {
* Returns documents
*/
getDocumentEl(el) {
var el = el || this.el;
if (!this.$doc) {
var docs = [document];
if (el) {
docs.push(el.ownerDocument);
}
this.$doc = $(docs);
el = el || this.el;
if (!this.docs) {
const docs = [document];
el && docs.push(el.ownerDocument);
this.docs = docs;
}
return this.$doc;
return this.docs;
},
/**
@ -202,126 +177,44 @@ module.exports = {
* @param {Event} event
* @return {Object}
*/
getMousePos(e) {
var mouseFetch = this.opts.mousePosFetcher;
return mouseFetch
? mouseFetch(e)
getPointerPos(ev) {
const getPos = this.opts.getPointerPosition;
return getPos
? getPos(ev)
: {
x: e.clientX,
y: e.clientY
x: ev.clientX,
y: ev.clientY
};
},
/**
* Drag event
* @param {Event} event
*/
drag(e) {
var lockedAxis = this.lockedAxis;
var currentPos = this.getMousePos(e);
var delta = {
x: currentPos.x - this.startPos.x,
y: currentPos.y - this.startPos.y
};
// Lock one axis
if (e.shiftKey) {
if (!lockedAxis) {
var relX = delta.x;
var relY = delta.y;
var absX = Math.abs(relX);
var absY = Math.abs(relY);
// Vertical or Horizontal lock
if (relY >= absX || relY <= -absX) {
lockedAxis = 'x';
} else if (relX > absY || relX < -absY) {
lockedAxis = 'y';
}
}
} else {
lockedAxis = null;
}
if (lockedAxis === 'x') {
delta.x = this.startPos.x;
}
getStartPosition() {
const { el, opts } = this;
const getPos = opts.getPosition;
let result = { x: 0, y: 0 };
if (lockedAxis === 'y') {
delta.y = this.startPos.y;
if (isFunction(getPos)) {
result = getPos();
} else if (el) {
result = {
x: parseFloat(el.style.left),
y: parseFloat(el.style.top)
};
}
this.lockedAxis = lockedAxis;
this.delta = delta;
this.move(delta.x, delta.y);
// Drag callback
const onDrag = this.opts.onDrag;
if (typeof onDrag === 'function') {
onDrag(e, {
delta,
current: {
x: this.startLeft + delta.x,
y: this.startTop + delta.y
},
lockedAxis
});
}
// In case the mouse button was released outside of the window
if (e.which === 0) {
this.stop(e);
}
return result;
},
/**
* Move the element
* @param {integer} x
* @param {integer} y
*/
move: function(x, y) {
this.moveX(x);
this.moveY(y);
},
detectAxisLock(x, y) {
const relX = x;
const relY = y;
const absX = Math.abs(relX);
const absY = Math.abs(relY);
/**
* Move in x direction
* @param {integer} x
*/
moveX(x) {
var el = this.el;
var opts = this.opts;
var xPos = this.startLeft + x;
const setX = this.opts.setX;
if (typeof setX === 'function') {
setX(xPos, {
el,
start: this.startLeft,
delta: x
});
} else {
el.style.left = xPos + 'px';
}
},
/**
* Move in y direction
* @param {integer} y
*/
moveY(y) {
var el = this.el;
var opts = this.opts;
var yPos = this.startTop + y;
const setY = this.opts.setY;
if (typeof setY === 'function') {
setY(yPos, {
el,
start: this.startTop,
delta: y
});
} else {
el.style.top = yPos + 'px';
// Vertical or Horizontal lock
if (relY >= absX || relY <= -absX) {
return 'x';
} else if (relX > absY || relX < -absY) {
return 'y';
}
}
};

Loading…
Cancel
Save