draggable.js 17.9 KB
Newer Older
邓晓峰's avatar
邓晓峰 committed
1 2 3
import React from 'react';

import ReactDraggable from 'react-draggable';
邓晓峰's avatar
邓晓峰 committed
4
/* eslint-disable */
邓晓峰's avatar
邓晓峰 committed
5
import Resize from './resize';
邓晓峰's avatar
邓晓峰 committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
class Draggable extends React.Component {
  constructor(props) {
    super(props);
    this.resizing = false;
    this.resizingPosition = {
      x: 0,
      y: 0,
    };
    this.offsetFromParent = {
      left: 0,
      top: 0,
    };
    this.resizableElement = {
      current: null,
    };

    this.refDraggable = ref => {
      ref && (this.draggable = ref);
    };
    this.refResizable = resize => {
      resize &&
        ((this.resizable = resize),
        (this.resizableElement.current = resize.resizable));
    };
    this.state = {
      original: {
        x: 0,
        y: 0,
      },
      bounds: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0,
      },
      maxWidth: props.maxWidth,
      maxHeight: props.maxHeight,
    };
邓晓峰's avatar
邓晓峰 committed
44 45 46 47 48 49 50
    this.onResizeStart = this.onResizeStart.bind(this);
    this.onResize = this.onResize.bind(this);
    this.onResizeStop = this.onResizeStop.bind(this);
    this.onDragStart = this.onDragStart.bind(this);
    this.onDrag = this.onDrag.bind(this);
    this.onDragStop = this.onDragStop.bind(this);
    this.getMaxSizesFromProps = this.getMaxSizesFromProps.bind(this);
邓晓峰's avatar
邓晓峰 committed
51 52 53
  }

  componentDidMount() {
邓晓峰's avatar
邓晓峰 committed
54 55 56 57 58 59 60 61
    this.updateOffsetFromParent();
    const { left, top } = this.offsetFromParent;
    const { x, y } = this.getDraggablePosition();
    this.draggable.setState({
      x: x - left,
      y: y - top,
    });
    this.forceUpdate();
邓晓峰's avatar
邓晓峰 committed
62 63 64
  }

  getDraggablePosition() {
邓晓峰's avatar
邓晓峰 committed
65 66 67 68 69
    const { state } = this.draggable;
    return {
      x: state.x,
      y: state.y,
    };
邓晓峰's avatar
邓晓峰 committed
70 71 72
  }

  getParent() {
邓晓峰's avatar
邓晓峰 committed
73
    return this.resizable && this.resizable.parentNode;
邓晓峰's avatar
邓晓峰 committed
74 75 76
  }

  getParentSize() {
邓晓峰's avatar
邓晓峰 committed
77
    return this.resizable.getParentSize();
邓晓峰's avatar
邓晓峰 committed
78 79 80
  }

  getMaxSizesFromProps() {
邓晓峰's avatar
邓晓峰 committed
81 82 83 84 85 86 87 88 89 90
    return {
      maxWidth:
        void 0 === this.props.maxWidth
          ? Number.MAX_SAFE_INTEGER
          : this.props.maxWidth,
      maxHeight:
        void 0 === this.props.maxHeight
          ? Number.MAX_SAFE_INTEGER
          : this.props.maxHeight,
    };
邓晓峰's avatar
邓晓峰 committed
91 92 93
  }

  getSelfElement() {
邓晓峰's avatar
邓晓峰 committed
94
    return this.resizable && this.resizable.resizable;
邓晓峰's avatar
邓晓峰 committed
95 96 97
  }

  getOffsetHeight(event) {
邓晓峰's avatar
邓晓峰 committed
98 99 100 101 102 103 104 105 106
    const { scale } = this.props;
    switch (this.props.bounds) {
      case 'window':
        return window.innerHeight / scale;
      case 'body':
        return document.body.offsetHeight / scale;
      default:
        return event.offsetHeight;
    }
邓晓峰's avatar
邓晓峰 committed
107 108 109
  }

  getOffsetWidth(event) {
邓晓峰's avatar
邓晓峰 committed
110 111 112 113 114 115 116 117 118
    const { scale } = this.props;
    switch (this.props.bounds) {
      case 'window':
        return window.innerWidth / scale;
      case 'body':
        return document.body.offsetWidth / scale;
      default:
        return event.offsetWidth;
    }
邓晓峰's avatar
邓晓峰 committed
119 120 121
  }

  onDragStart(event, position) {
邓晓峰's avatar
邓晓峰 committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    if (
      (this.props.onDragStart && this.props.onDragStart(event, position),
      this.props.bounds)
    ) {
      const parent = this.getParent();
      const { scale } = this.props;
      // eslint-disable-next-line no-underscore-dangle
      let _parent;
      if (this.props.bounds === 'parent') {
        _parent = parent;
      } else {
        if (this.props.bounds === 'body') {
          const rect = parent.getBoundingClientRect();
          const { left, top } = rect;
          const domRect = document.body.getBoundingClientRect();
          const deltLeft =
            -(left - parent.offsetLeft * scale - domRect.left) / scale;
          const deltTop =
            -(top - parent.offsetTop * scale - domRect.top) / scale;
          const deltRight =
            (document.body.offsetWidth - this.resizable.size.width * scale) /
              scale +
            deltLeft;
          const deltBottom =
            (document.body.offsetHeight - this.resizable.size.height * scale) /
              scale +
            deltTop;
          return this.setState({
            bounds: {
              top: deltTop,
              right: deltRight,
              left: deltLeft,
              bottom: deltBottom,
            },
          });
        }
邓晓峰's avatar
邓晓峰 committed
158

邓晓峰's avatar
邓晓峰 committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        if (this.props.bounds === 'window') {
          if (!this.resizable) return;
          const rect = parent.getBoundingClientRect();
          const deltLeft = -(rect.left - parent.offsetLeft * scale) / scale;
          const deltTop = -(rect.top - parent.offsetTop * scale) / scale;
          const deltRight =
            (window.innerWidth - this.resizable.size.width * scale) / scale +
            deltLeft;
          const deltBottom =
            (window.innerHeight - this.resizable.size.height * scale) / scale +
            deltTop;
          return this.setState({
            bounds: {
              top: deltTop,
              right: deltRight,
              left: deltLeft,
              bottom: deltBottom,
            },
          });
邓晓峰's avatar
邓晓峰 committed
178
        }
邓晓峰's avatar
邓晓峰 committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        _parent = document.querySelector(this.props.bounds);
      }
      if (_parent instanceof HTMLElement && parent instanceof HTMLElement) {
        const rect = _parent.getBoundingClientRect();
        const { left, top } = rect;
        const parentRect = parent.getBoundingClientRect();
        let deltLeft = (left - parentRect.left) / scale;
        const deltTop = top - deltLeft.top;
        if (this.resizable) {
          this.updateOffsetFromParent();
          const fromParent = this.offsetFromParent;
          this.setState({
            bounds: {
              top: deltTop - fromParent.top,
              right:
                deltLeft +
                (_parent.offsetWidth - this.resizable.size.width) -
                fromParent.left / scale,
              bottom:
                deltTop +
                (_parent.offsetHeight - this.resizable.size.height) -
                fromParent.top,
              // eslint-disable-next-line no-const-assign
              left: (deltLeft = fromParent.left / scale),
            },
          });
邓晓峰's avatar
邓晓峰 committed
205
        }
邓晓峰's avatar
邓晓峰 committed
206 207
      }
    }
邓晓峰's avatar
邓晓峰 committed
208 209 210
  }

  onDrag(event, position) {
邓晓峰's avatar
邓晓峰 committed
211 212 213 214 215 216 217 218 219 220
    if (this.props.onDrag) {
      const fromParent = this.offsetFromParent;
      return this.props.onDrag(
        event,
        Object.assign(Object.assign({}, position), {
          x: position.x - fromParent.left,
          y: position.y - fromParent.top,
        }),
      );
    }
邓晓峰's avatar
邓晓峰 committed
221 222 223
  }

  onDragStop(event, position) {
邓晓峰's avatar
邓晓峰 committed
224 225 226 227 228 229 230 231 232 233
    if (this.props.onDragStop) {
      const fromParent = this.offsetFromParent;
      return this.props.onDragStop(
        event,
        Object.assign(Object.assign({}, position), {
          x: position.y + fromParent.left,
          y: position.y + fromParent.top,
        }),
      );
    }
邓晓峰's avatar
邓晓峰 committed
234 235 236 237 238
  }

  onResizeStart(event, placment, callback) {
    event.stopPropagation();
    this.resizing = !0;
邓晓峰's avatar
邓晓峰 committed
239
    const { scale } = this.props;
邓晓峰's avatar
邓晓峰 committed
240 241
    const fromParent = this.offsetFromParent;
    const dragPosition = this.getDraggablePosition();
邓晓峰's avatar
邓晓峰 committed
242 243
    if (
      ((this.resizingPosition = {
邓晓峰's avatar
邓晓峰 committed
244
        x: dragPosition.x + fromParent.left,
邓晓峰's avatar
邓晓峰 committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
        y: dragPosition.y + fromParent.top,
      }),
      this.setState({
        original: dragPosition,
      }),
      this.props.bounds)
    ) {
      const parent = this.getParent();
      let element = void 0;
      element =
        this.props.bounds === 'parent'
          ? parent
          : this.props.bounds === 'body'
          ? document.body
          : this.props.bounds === 'window'
          ? window
          : document.querySelector(this.props.bounds);
      const selfElement = this.getSelfElement();
      if (
        selfElement instanceof Element &&
        (element instanceof HTMLElement || element === window) &&
        parent instanceof HTMLElement
      ) {
        const maxSizeProps = this.getMaxSizesFromProps();
        const parentSize = this.getParentSize();
        let { maxWidth, maxHeight } = maxSizeProps;
        if (maxWidth && typeof maxWidth === 'string') {
          if (maxWidth.endsWith('%')) {
            const delt = Number(maxWidth.replace('%', '')) / 100;
            maxWidth = parentSize.width * delt;
          } else {
            maxWidth.endsWith('px') &&
              (maxWidth = Number(maxWidth.replace('px', '')));
          }
        }
邓晓峰's avatar
邓晓峰 committed
280

邓晓峰's avatar
邓晓峰 committed
281 282 283 284 285 286 287 288 289 290 291
        if (maxHeight && typeof maxHeight === 'string') {
          if (maxHeight.endsWith('%')) {
            const delt = Number(maxHeight.replace('%', '')) / 100;
            maxHeight = parentSize.width * delt;
          } else {
            maxHeight.endsWith('px') &&
              (maxHeight = Number(maxHeight.replace('px', '')));
            maxHeight.endsWith('px') &&
              (maxHeight = Number(maxHeight.replace('px', '')));
          }
        }
邓晓峰's avatar
邓晓峰 committed
292

邓晓峰's avatar
邓晓峰 committed
293
        const rect = selfElement.getBoundingClientRect();
邓晓峰's avatar
邓晓峰 committed
294

邓晓峰's avatar
邓晓峰 committed
295 296 297 298 299 300
        // eslint-disable-next-line no-underscore-dangle
        const _rect_ =
          this.props.bounds === 'window'
            ? {
              left: 0,
              top: 0,
邓晓峰's avatar
邓晓峰 committed
301
            }
邓晓峰's avatar
邓晓峰 committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315
            : element.getBoundingClientRect();

        const offsetWidth = this.getOffsetWidth();
        const offsetHeight = this.getOffsetHeight();
        const convertLeft = placment.toLowerCase().endsWith('left');
        const convertRight = placment.toLowerCase().endsWith('right');

        if (convertLeft && this.resizable) {
          const deltWidth =
            (rect.left - _rect_.left) / scale + this.resizable.size.width;
          this.setState({
            maxWidth: deltWidth > Number(maxWidth) ? maxWidth : deltWidth,
          });
        }
邓晓峰's avatar
邓晓峰 committed
316

邓晓峰's avatar
邓晓峰 committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
        if (convertRight || (this.props.lockAspectRatio && !convertLeft)) {
          const deltWidth = offsetWidth + (_rect_.left - rect.left) / scale;
          this.setState({
            maxWidth: deltWidth > Number(maxWidth) ? maxWidth : deltWidth,
          });
        }

        if (placment.startsWith('top') && this.resizable) {
          const deltHeight = rect.top - _rect_.top + this.resizable.size.height;
          this.setState({
            maxHeight: deltHeight > Number(maxHeight) ? maxHeight : deltHeight,
          });
        }

        if (
          placment.startsWith('bottom') ||
          (this.props.lockAspectRatio && !placment.startsWith('top'))
        ) {
          const deltHeight = offsetHeight + (_rect_.top - rect.top) / scale;
          this.setState({
            maxHeight: deltHeight > Number(maxHeight) ? maxHeight : deltHeight,
          });
邓晓峰's avatar
邓晓峰 committed
339
        }
邓晓峰's avatar
邓晓峰 committed
340
      }
邓晓峰's avatar
邓晓峰 committed
341
    } else {
邓晓峰's avatar
邓晓峰 committed
342 343 344 345
      this.setState({
        maxWidth: this.props.maxWidth,
        maxHeight: this.props.maxHeight,
      });
邓晓峰's avatar
邓晓峰 committed
346
    }
邓晓峰's avatar
邓晓峰 committed
347 348
    this.props.onResizeStart &&
      this.props.onResizeStart(event, placment, callback);
邓晓峰's avatar
邓晓峰 committed
349 350 351
  }

  onResize(event, placment, position, target) {
邓晓峰's avatar
邓晓峰 committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    const original = {
      x: this.state.original.x,
      y: this.state.original.y,
    };
    const width = -target.width;
    const height = -target.height;
    ['top', 'left', 'topLeft', 'bottomLeft', 'topRight'].indexOf(placment) !==
      -1 &&
      (placment === 'bottomLeft'
        ? (original.x += width)
        : (placment === 'topRight' || (original.x += width),
          (original.y += height)));
    (original.x === this.draggable.state.x &&
      original.y === this.draggable.state.y) ||
      this.draggable.setState(original);
    this.updateOffsetFromParent();
    const fromParent = this.offsetFromParent;
    const x = this.getDraggablePosition().x + fromParent.left;
    const y = this.getDraggablePosition().y + fromParent.top;
    this.resizingPosition = {
      x,
      y,
    };
    this.props.onResize &&
      this.props.onResize(event, placment, position, target, {
        x,
        y,
      });
邓晓峰's avatar
邓晓峰 committed
380 381 382 383 384 385
  }

  onResizeStop(event, placment, position, target) {
    this.resizing = !1;
    const { maxWidth, maxHeight } = this.getMaxSizesFromProps();
    this.setState({
邓晓峰's avatar
邓晓峰 committed
386 387
      maxHeight,
      maxWidth,
邓晓峰's avatar
邓晓峰 committed
388
    });
邓晓峰's avatar
邓晓峰 committed
389 390 391 392 393 394 395 396
    this.props.onResizeStop &&
      this.props.onResizeStop(
        event,
        placment,
        position,
        target,
        this.resizingPosition,
      );
邓晓峰's avatar
邓晓峰 committed
397 398 399
  }

  updateSize(target) {
邓晓峰's avatar
邓晓峰 committed
400 401 402 403 404
    this.resizable &&
      this.resizable.updateSize({
        width: target.width,
        height: target.height,
      });
邓晓峰's avatar
邓晓峰 committed
405 406 407
  }

  updatePosition(position) {
邓晓峰's avatar
邓晓峰 committed
408
    this.draggable.setState(position);
邓晓峰's avatar
邓晓峰 committed
409 410 411
  }

  updateOffsetFromParent() {
邓晓峰's avatar
邓晓峰 committed
412 413 414 415 416 417 418
    const { scale } = this.props;
    const parent = this.getParent();
    const selfElement = this.getSelfElement();
    if (!parent || selfElement === null) {
      return {
        top: 0,
        left: 0,
邓晓峰's avatar
邓晓峰 committed
419
      };
邓晓峰's avatar
邓晓峰 committed
420 421 422 423 424 425 426 427
    }
    const rect = parent.getBoundingClientRect();
    const selfRect = selfElement.getBoundingClientRect();
    const dragPosition = this.getDraggablePosition();
    this.offsetFromParent = {
      left: selfRect.left - rect.left - dragPosition.x * scale,
      top: selfRect.top - rect.top - dragPosition.y * scale,
    };
邓晓峰's avatar
邓晓峰 committed
428 429 430
  }

  render() {
邓晓峰's avatar
邓晓峰 committed
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    const { props } = this;

    const {
      disableDragging,
      style,
      dragHandleClassName,
      position,
      onMouseDown,
      onMouseUp,
      dragAxis,
      dragGrid,
      bounds,
      enableUserSelectHack,
      cancel,
      children,
      resizeHandleClasses,
      resizeHandleComponent,
      enableResizing,
      resizeGrid,
      resizeHandleWrapperClass,
      resizeHandleWrapperStyle,
      scale = 1,
      allowAnyClick,
    } = props;
    const event = (props.onResize,
    props.onResizeStop,
    props.onDragStart,
    props.onDrag,
    props.onDragStop,
    props.resizeHandleStyles);
    const _ = (function(e, t) {
      const n = {};
      // eslint-disable-next-line guard-for-in
      for (var r in e)
        Object.prototype.hasOwnProperty.call(e, r) &&
          t.indexOf(r) < 0 &&
          (n[r] = e[r]);
      if (e != null && typeof Object.getOwnPropertySymbols === 'function') {
        let o = 0;
        // eslint-disable-next-line block-scoped-var,no-plusplus
        for (r = Object.getOwnPropertySymbols(e); o < r.length; o++)
          t.indexOf(r[o]) < 0 &&
          // eslint-disable-next-line block-scoped-var
            Object.prototype.propertyIsEnumerable.call(e, r[o]) &&
          // eslint-disable-next-line block-scoped-var
            (n[r[o]] = e[r[o]]);
      }
      return n;
    })(props, [
      'disableDragging',
      'style',
      'dragHandleClassName',
      'position',
      'onMouseDown',
      'onMouseUp',
      'dragAxis',
      'dragGrid',
      'bounds',
      'enableUserSelectHack',
      'cancel',
      'children',
      'onResizeStart',
      'onResize',
      'onResizeStop',
      'onDragStart',
      'onDrag',
      'onDragStop',
      'resizeHandleStyles',
      'resizeHandleClasses',
      'resizeHandleComponent',
      'enableResizing',
      'resizeGrid',
      'resizeHandleWrapperClass',
      'resizeHandleWrapperStyle',
      'scale',
      'allowAnyClick',
    ]);
    const defaultPosition = this.props.default
      ? Object.assign({}, this.props.default)
      : void 0;
    delete _.default;
    let calcPostion;

    position &&
      (calcPostion = {
        x: position.x - this.offsetFromParent.left,
        y: position.y - this.offsetFromParent.top,
      });
    let _enableResizing;
    const _position_ = this.resizing ? void 0 : calcPostion;
    const styles = Object.assign(
      Object.assign(
        Object.assign(
          {},
          {
            width: this.props.default.width,
            height: this.props.default.height,
            display: 'inline-block',
            position: 'absolute',
            top: 0,
            left: 0,
            zIndex: 5000,
            boxShadow: 'rgba(0, 0, 0, 0.21) 0px 4px 16px 0px',
            backgroundColor: 'rgb(255, 255, 255)',
            overflow: 'hidden',
          },
        ),
        disableDragging || dragHandleClassName
          ? { cursor: 'auto' }
          : { cursor: 'move' },
      ),
      this.props.style,
    );

    return (
      <ReactDraggable
        ref={e => this.refDraggable(e)}
        handle={dragHandleClassName ? `.${dragHandleClassName}` : void 0}
        defaultPosition={defaultPosition}
        onMouseDown={onMouseDown}
        onMouseUp={onMouseUp}
        onStart={this.onDragStart}
        onDrag={this.onDrag}
        onStop={this.onDragStop}
        axis={dragAxis || 'both'}
        grid={dragGrid}
        position={_position_}
        bounds={bounds ? this.state.bounds : void 0}
        enableUserSelectHack={enableUserSelectHack}
        cancel={cancel}
        scale={scale}
        allowAnyClick={allowAnyClick}
        nodeRef={this.resizableElement}
      >
        <Resize
          ref={e => this.refResizable(e)}
          defaultSize={defaultPosition}
          size={this.props.size}
          enable={
            typeof enableResizing === 'boolean'
              ? ((_enableResizing = enableResizing),
                {
                  bottom: _enableResizing,
                  bottomLeft: _enableResizing,
                  bottomRight: _enableResizing,
                  left: _enableResizing,
                  right: _enableResizing,
                  top: _enableResizing,
                topLeft: _enableResizing,
                  topRight: _enableResizing,
              })
              : enableResizing
          }
          onResizeStart={this.onResizeStart}
          onResize={this.onResize}
          onResizeStop={this.onResizeStop}
          style={styles}
          minWidth={this.props.minWidth}
          minHeight={this.props.minHeight}
          maxWidth={this.resizing ? this.state.maxWidth : this.props.maxWidth}
          maxHeight={
            this.resizing ? this.state.maxHeight : this.props.maxHeight
          }
          grid={dragGrid}
          handleWrapperClass={resizeHandleWrapperClass}
          handleWrapperStyle={resizeHandleWrapperStyle}
          lockAspectRatio={this.props.lockAspectRatio}
          lockAspectRatioExtraWidth={this.props.lockAspectRatioExtraWidth}
          lockAspectRatioExtraHeight={this.props.lockAspectRatioExtraHeight}
          handleStyles={event}
          handleClasses={resizeHandleClasses}
          handleComponent={resizeHandleComponent}
          scale={this.props.scale}
        >
          {props.children}
        </Resize>
      </ReactDraggable>
    );
邓晓峰's avatar
邓晓峰 committed
609 610 611 612 613 614 615
  }
}

Draggable.defaultProps = {
  maxWidth: Number.MAX_SAFE_INTEGER,
  maxHeight: Number.MAX_SAFE_INTEGER,
  scale: 1,
邓晓峰's avatar
邓晓峰 committed
616 617 618 619 620 621
  onResizeStart() {},
  onResize() {},
  onResizeStop() {},
  onDragStart() {},
  onDrag() {},
  onDragStop() {},
邓晓峰's avatar
邓晓峰 committed
622 623
};
export default Draggable;