Эх сурвалжийг харах

1.新增测试
2.release 0.1.0

方正 7 жил өмнө
parent
commit
349dba365c

+ 25 - 8
.babelrc

@@ -1,20 +1,37 @@
 // 新建.babelrc
 {
   "presets": [
-    ["es2015", {"modules": false}],
-       // webpack现在已经支持原生的import语句了, 并且将其运用在tree-shaking特性上
+    [
+      "es2015",
+      {
+        "modules": false
+      }
+    ],
+    // webpack现在已经支持原生的import语句了, 并且将其运用在tree-shaking特性上
     "stage-2",
-      // 规定JS运用的语言规范层级
-      // Stage 2 是 "草案", 4 是 "已完成", 0 is "稻草人(strawman)"。
-      // 详情查看 https://tc39.github.io/process-document/
+    // 规定JS运用的语言规范层级
+    // Stage 2 是 "草案", 4 是 "已完成", 0 is "稻草人(strawman)"。
+    // 详情查看 https://tc39.github.io/process-document/
     "react"
-      // 转译React组件为JS代码
+    // 转译React组件为JS代码
   ],
   "plugins": [
     "transform-runtime",
     "react-hot-loader/babel",
     "transform-object-rest-spread",
     "transform-react-jsx"
-      // 开启react代码的模块热替换(HMR)
-  ]
+    // 开启react代码的模块热替换(HMR)
+  ],
+  "env": {
+    "development": {
+      "plugins": [
+        "transform-es2015-modules-commonjs"
+      ]
+    },
+    "test": {
+      "plugins": [
+        "transform-es2015-modules-commonjs"
+      ]
+    }
+  }
 }

+ 132 - 0
README.EN.md

@@ -0,0 +1,132 @@
+# Whath is Dragact?
+
+Dragact is a react component, which allows you to build your own **dragable grid layout** easily.
+
+![](https://github.com/215566435/React-dragger-layout/blob/master/example/image/NormalLayoutDemo.gif)
+
+### 快速安装
+```
+npm install --save dragact
+```
+
+### 写一个例子🌰
+```javascript
+import * as React from "react";
+import * as ReactDOM from "react-dom";
+
+import { Dragact } from 'dragact';
+import './index.css'
+
+ReactDOM.render(
+    <Dragact
+        col={8}
+        width={800}
+        margin={[5, 5]}
+        rowHeight={40}
+        className='plant-layout'
+    >
+        <div key={0} data-set={{ GridX: 0, GridY: 0, w: 4, h: 2 }} className='layout-child'>0</div>
+        <div key={1} data-set={{ GridX: 0, GridY: 0, w: 1, h: 2 }} className='layout-child'>1</div>
+        <div key={2} data-set={{ GridX: 0, GridY: 0, w: 3, h: 2 }} className='layout-child'>2</div>
+    </Dragact>,
+    document.getElementById('root')
+);
+```
+
+# Demo
+[Live Demo](http://htmlpreview.github.io/?https://github.com/215566435/React-dragger-layout/blob/master/build/index.html)
+
+
+# Feature
+- [x] auto sorted layout
+- [x] mobile device supported
+- [x] auto height fixed
+- [x] static component
+- [x] Draggable component
+
+
+# Dragact 提供的属性
+```ts
+interface DragactProps {
+    layout?: DragactLayout[] //暂时不推荐使用
+    /** 
+     * 宽度切分比 
+     * 这个参数会把容器的宽度平均分为col等份
+     * 于是容器内元素的最小宽度就等于 containerWidth/col
+    */
+    col: number,
+
+    /** 
+     * 容器的宽度
+    */
+    width: number,
+
+    /**容器内每个元素的最小高度 */
+    rowHeight: number,
+
+    /**
+     * 容器内部的padding
+     */
+    padding?: number,
+
+    children: any[] | any
+
+
+    // 
+    // interface GridItemEvent {
+    //     event: any //浏览器拖动事件
+    //     GridX: number //在布局中的x格子  
+    //     GridY: number //在布局中的y格子  
+    //     w: number //元素的宽度
+    //     h: number //元素的高度
+    //     UniqueKey: string | number //元素的唯一key
+    // }
+
+    /**
+     * 拖动开始的回调
+     */
+    onDragStart?: (event: GridItemEvent) => void
+
+    /**
+     * 拖动中的回调
+     */
+    onDrag?: (event: GridItemEvent) => void
+
+    /**
+     * 拖动结束的回调
+     */
+    onDragEnd?: (key: number | string) => void
+
+    /**
+     * 每个元素的margin,第一个参数是左右,第二个参数是上下
+     */
+    margin: [number, number]
+
+    /** 
+     * layout的名字
+    */
+    className: number | string
+}
+
+```
+
+
+
+# Contribute
+
+### Want a new feature?
+1. If you have a feature request, please add it as an issue or make a pull request.
+2. After adding some awesome feature, please run the test and make sure it will pass all tests before you make a PR.
+
+### A bug?
+If you have a bug to report, please reproduce the bug in Github issue with a sample code to help us easily isolate it.
+
+
+
+
+# TODO-LIST
+- [ ] horizontal swaping
+- [ ] resizing
+- [ ] touch handle
+- [ ] responsive layout
+- [ ] SSR/server rendering 

+ 9 - 0
README.md

@@ -127,6 +127,15 @@ interface DragactProps {
 
 
 
+# 测试
+```
+git clone https://github.com/215566435/Dragact.git
+cd Dragact
+npm install 
+npm run test
+```
+
+
 # 贡献
 
 ### 想要一个新的特色、功能?

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 0 - 0
build/react-dragger-layout.js


+ 8 - 10
dist/NormalLayout/index.js

@@ -1,26 +1,24 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-var React = require("react");
-var dragact_1 = require("../lib/dragact");
-require("./index.css");
-var Words = [
+import * as React from 'react';
+import { Dragact } from '../lib/dragact';
+import './index.css';
+const Words = [
     { content: 'You can do anything, but not everything.', img: 'http://pic.sc.chinaz.com/files/pic/pic9/201303/xpic10472.jpg' },
     { content: 'Those who dare to fail miserably can achieve greatly.', img: 'https://img00.deviantart.net/1163/i/2013/059/d/7/irish_views_by_ssquared_photography-d5wjnsk.jpg' },
     { content: 'You miss 100 percent of the shots you never take.', img: 'http://www.landsendhotel.co.uk/uploads/gallery/gallery/coastal_scenery_seascapes_6.jpg' },
     { content: 'Those who believe in telekinetics, raise my hand.', img: 'https://tctechcrunch2011.files.wordpress.com/2017/10/26099344353_18cd6fabb8_k.jpg?w=738' },
     { content: 'I’d rather live with a good question than a bad answer.', img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQVa26cLzh6PYUwY4LMpwbHyDHFmWi_w2JuqDzeOdm1IIEbBZO0Vg' }
 ];
-var Card = function (props) {
-    var item = props.item;
+const Card = (props) => {
+    const item = props.item;
     return (React.createElement("div", { className: 'layout-Item' },
         React.createElement("img", { src: item.img, style: { width: '100%', height: '60%' }, draggable: false, alt: 'card' }),
         React.createElement("div", { style: { padding: 5, textAlign: 'center', color: '#595959' } }, item.content)));
 };
-exports.LayoutDemo = function () {
+export const LayoutDemo = () => {
     return (React.createElement("div", { style: { display: 'flex', justifyContent: 'center' } },
         React.createElement("div", null,
             React.createElement("h1", { style: { textAlign: 'center' } }, "Normal Layout Demo"),
-            React.createElement(dragact_1.Dragact, { width: 800, col: 12, rowHeight: 800 / 12, margin: [5, 5], className: 'normal-layout' }, Words.map(function (el, index) {
+            React.createElement(Dragact, { width: 800, col: 12, rowHeight: 800 / 12, margin: [5, 5], className: 'normal-layout' }, Words.map((el, index) => {
                 return React.createElement(Card, { item: el, key: index, "data-set": { GridX: (index * 3) % 12, GridY: index * 2, w: 3, h: 3 } });
             })))));
 };

+ 8 - 10
dist/SortedTable/index.js

@@ -1,26 +1,24 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-var React = require("react");
-var dragact_1 = require("../lib/dragact");
-require("./index.css");
-var Words = [
+import * as React from 'react';
+import { Dragact } from '../lib/dragact';
+import './index.css';
+const Words = [
     { content: 'You can do anything, but not everything.', img: 'http://pic.sc.chinaz.com/files/pic/pic9/201303/xpic10472.jpg' },
     { content: 'Those who dare to fail miserably can achieve greatly.', img: 'https://img00.deviantart.net/1163/i/2013/059/d/7/irish_views_by_ssquared_photography-d5wjnsk.jpg' },
     { content: 'You miss 100 percent of the shots you never take.', img: 'http://www.landsendhotel.co.uk/uploads/gallery/gallery/coastal_scenery_seascapes_6.jpg' },
     { content: 'Those who believe in telekinetics, raise my hand.', img: 'https://tctechcrunch2011.files.wordpress.com/2017/10/26099344353_18cd6fabb8_k.jpg?w=738' },
     { content: 'I’d rather live with a good question than a bad answer.', img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQVa26cLzh6PYUwY4LMpwbHyDHFmWi_w2JuqDzeOdm1IIEbBZO0Vg' }
 ];
-var Cell = function (props) {
-    var item = props.item;
+const Cell = (props) => {
+    const item = props.item;
     return (React.createElement("div", { className: 'layout-Cell' },
         React.createElement("img", { src: item.img, style: { width: 45, height: 45 }, draggable: false, alt: 'card' }),
         React.createElement("div", { style: { paddingLeft: 12, color: '#595959' } }, item.content)));
 };
-exports.SortedTable = function () {
+export const SortedTable = () => {
     return (React.createElement("div", { style: { display: 'flex', justifyContent: 'center' } },
         React.createElement("div", null,
             React.createElement("h1", { style: { textAlign: 'center' } }, "Sorted Table Demo"),
-            React.createElement(dragact_1.Dragact, { width: 800, col: 1, rowHeight: 60, margin: [2, 2], className: 'normal-layout' }, Words.map(function (el, index) {
+            React.createElement(Dragact, { width: 800, col: 1, rowHeight: 60, margin: [2, 2], className: 'normal-layout' }, Words.map((el, index) => {
                 return React.createElement(Cell, { item: el, key: index, "data-set": { GridX: 0, GridY: 0, w: 1, h: 1 } });
             })))));
 };

+ 9 - 11
dist/StaticHeader/index.js

@@ -1,26 +1,24 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-var React = require("react");
-var dragact_1 = require("../lib/dragact");
-require("./index.css");
-var Words = [
+import * as React from 'react';
+import { Dragact } from '../lib/dragact';
+import './index.css';
+const Words = [
     { content: 'Sorry I just can not move in any circumstances', img: 'http://pic.sc.chinaz.com/files/pic/pic9/201303/xpic10472.jpg', static: true },
     { content: 'Those who dare to fail miserably can achieve greatly.', img: 'https://img00.deviantart.net/1163/i/2013/059/d/7/irish_views_by_ssquared_photography-d5wjnsk.jpg' },
     { content: 'You miss 100 percent of the shots you never take.', img: 'http://www.landsendhotel.co.uk/uploads/gallery/gallery/coastal_scenery_seascapes_6.jpg' },
     { content: 'Those who believe in telekinetics, raise my hand.', img: 'https://tctechcrunch2011.files.wordpress.com/2017/10/26099344353_18cd6fabb8_k.jpg?w=738' },
     { content: 'I’d rather live with a good question than a bad answer.', img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQVa26cLzh6PYUwY4LMpwbHyDHFmWi_w2JuqDzeOdm1IIEbBZO0Vg' }
 ];
-var Cell = function (props) {
-    var item = props.item;
-    return (React.createElement("div", { className: "layout-Cell " + (item.static ? "static" : ""), style: { background: item.static ? "#e8e8e8" : "" } },
+const Cell = (props) => {
+    const { item } = props;
+    return (React.createElement("div", { className: `layout-Cell ${item.static ? "static" : ""}`, style: { background: item.static ? "#e8e8e8" : "" } },
         React.createElement("img", { src: item.img, style: { width: 45, height: 45 }, draggable: false, alt: 'card' }),
         React.createElement("div", { style: { paddingLeft: 12, color: '#595959' } }, item.content)));
 };
-exports.SortedTableWithStatic = function () {
+export const SortedTableWithStatic = () => {
     return (React.createElement("div", { style: { display: 'flex', justifyContent: 'center' } },
         React.createElement("div", null,
             React.createElement("h1", { style: { textAlign: 'center' } }, "Static Header Table Demo"),
-            React.createElement(dragact_1.Dragact, { width: 800, col: 1, rowHeight: 60, margin: [2, 2], className: 'normal-layout' }, Words.map(function (el, index) {
+            React.createElement(Dragact, { width: 800, col: 1, rowHeight: 60, margin: [2, 2], className: 'normal-layout' }, Words.map((el, index) => {
                 return React.createElement(Cell, { item: el, key: index, "data-set": { GridX: 0, GridY: index, w: 1, h: 1, static: el.static } });
             })))));
 };

+ 23 - 39
dist/index.js

@@ -1,50 +1,34 @@
-"use strict";
-var __extends = (this && this.__extends) || (function () {
-    var extendStatics = Object.setPrototypeOf ||
-        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
-        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
-    return function (d, b) {
-        extendStatics(d, b);
-        function __() { this.constructor = d; }
-        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-    };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-var React = require("react");
-var ReactDOM = require("react-dom");
-var index_1 = require("./NormalLayout/index");
-var SortedTable_1 = require("./SortedTable");
-var StaticHeader_1 = require("./StaticHeader");
-require("./index.css");
-var DemoMap = {
-    normalLayout: React.createElement(index_1.LayoutDemo, null),
-    SortedTable: React.createElement(SortedTable_1.SortedTable, null),
-    StaticHeader: React.createElement(StaticHeader_1.SortedTableWithStatic, null)
+import * as React from "react";
+import * as ReactDOM from "react-dom";
+import { LayoutDemo } from './NormalLayout/index';
+import { SortedTable } from "./SortedTable/index";
+import { SortedTableWithStatic } from "./StaticHeader/index";
+import './index.css';
+const DemoMap = {
+    normalLayout: React.createElement(LayoutDemo, null),
+    SortedTable: React.createElement(SortedTable, null),
+    StaticHeader: React.createElement(SortedTableWithStatic, null)
 };
-var DemoDispatcher = /** @class */ (function (_super) {
-    __extends(DemoDispatcher, _super);
-    function DemoDispatcher() {
-        var _this = _super !== null && _super.apply(this, arguments) || this;
-        _this.state = {
-            demo: React.createElement(index_1.LayoutDemo, null)
+class DemoDispatcher extends React.Component {
+    constructor() {
+        super(...arguments);
+        this.state = {
+            demo: React.createElement(LayoutDemo, null)
         };
-        _this.handleLayoutChange = function (demoName) {
-            _this.setState({
+        this.handleLayoutChange = (demoName) => {
+            this.setState({
                 demo: DemoMap[demoName]
             });
         };
-        return _this;
     }
-    DemoDispatcher.prototype.render = function () {
-        var _this = this;
+    render() {
         return (React.createElement("div", null,
             React.createElement("div", { className: 'demo-button-layout' },
                 React.createElement("div", null, "Switch Demos"),
-                React.createElement("button", { onClick: function () { return _this.handleLayoutChange('normalLayout'); } }, "normalLayout"),
-                React.createElement("button", { onClick: function () { return _this.handleLayoutChange('SortedTable'); } }, "SortedTable"),
-                React.createElement("button", { onClick: function () { return _this.handleLayoutChange('StaticHeader'); } }, "StaticHeader")),
+                React.createElement("button", { onClick: () => this.handleLayoutChange('normalLayout') }, "normalLayout"),
+                React.createElement("button", { onClick: () => this.handleLayoutChange('SortedTable') }, "SortedTable"),
+                React.createElement("button", { onClick: () => this.handleLayoutChange('StaticHeader') }, "StaticHeader")),
             this.state.demo));
-    };
-    return DemoDispatcher;
-}(React.Component));
+    }
+}
 ReactDOM.render(React.createElement(DemoDispatcher, null), document.getElementById('root'));

+ 62 - 86
dist/lib/GridItem.js

@@ -1,118 +1,94 @@
-"use strict";
-var __extends = (this && this.__extends) || (function () {
-    var extendStatics = Object.setPrototypeOf ||
-        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
-        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
-    return function (d, b) {
-        extendStatics(d, b);
-        function __() { this.constructor = d; }
-        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-    };
-})();
-var __assign = (this && this.__assign) || Object.assign || function(t) {
-    for (var s, i = 1, n = arguments.length; i < n; i++) {
-        s = arguments[i];
-        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
-            t[p] = s[p];
-    }
-    return t;
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-var React = require("react");
-var index_1 = require("./dragger/index");
-var correction_1 = require("./util/correction");
-var GridItem = /** @class */ (function (_super) {
-    __extends(GridItem, _super);
-    function GridItem(props) {
-        var _this = _super.call(this, props) || this;
-        _this.onDrag = _this.onDrag.bind(_this);
-        _this.onDragStart = _this.onDragStart.bind(_this);
-        _this.onDragEnd = _this.onDragEnd.bind(_this);
-        _this.calGridXY = _this.calGridXY.bind(_this);
-        _this.calColWidth = _this.calColWidth.bind(_this);
-        return _this;
+import * as React from "react";
+import { Dragger } from './dragger/index';
+import { checkInContainer } from './util/correction';
+export default class GridItem extends React.Component {
+    constructor(props) {
+        super(props);
+        this.onDrag = this.onDrag.bind(this);
+        this.onDragStart = this.onDragStart.bind(this);
+        this.onDragEnd = this.onDragEnd.bind(this);
+        this.calGridXY = this.calGridXY.bind(this);
+        this.calColWidth = this.calColWidth.bind(this);
     }
     /** 计算容器的每一个格子多大 */
-    GridItem.prototype.calColWidth = function () {
-        var _a = this.props, containerWidth = _a.containerWidth, col = _a.col, containerPadding = _a.containerPadding, margin = _a.margin;
+    calColWidth() {
+        const { containerWidth, col, containerPadding, margin } = this.props;
         if (margin) {
             return (containerWidth - containerPadding[0] * 2 - margin[0] * (col + 1)) / col;
         }
         return (containerWidth - containerPadding[0] * 2 - 0 * (col + 1)) / col;
-    };
+    }
     /**转化,计算网格的GridX,GridY值 */
-    GridItem.prototype.calGridXY = function (x, y) {
-        var _a = this.props, margin = _a.margin, containerWidth = _a.containerWidth, col = _a.col, w = _a.w, rowHeight = _a.rowHeight;
+    calGridXY(x, y) {
+        const { margin, containerWidth, col, w, rowHeight } = this.props;
         /**坐标转换成格子的时候,无须计算margin */
-        var GridX = Math.round(x / containerWidth * col);
-        var GridY = Math.round(y / (rowHeight + (margin ? margin[1] : 0)));
+        let GridX = Math.round(x / containerWidth * col);
+        let GridY = Math.round(y / (rowHeight + (margin ? margin[1] : 0)));
         // /**防止元素出container */
-        return correction_1.checkInContainer(GridX, GridY, col, w);
-    };
+        return checkInContainer(GridX, GridY, col, w);
+    }
     /**给予一个grid的位置,算出元素具体的在容器中位置在哪里,单位是px */
-    GridItem.prototype.calGridItemPosition = function (GridX, GridY) {
-        var _a = this.props, margin = _a.margin, rowHeight = _a.rowHeight;
+    calGridItemPosition(GridX, GridY) {
+        var { margin, rowHeight } = this.props;
         if (!margin)
             margin = [0, 0];
-        var x = Math.round(GridX * this.calColWidth() + (GridX + 1) * margin[0]);
-        var y = Math.round(GridY * rowHeight + margin[1] * (GridY + 1));
+        let x = Math.round(GridX * this.calColWidth() + (GridX + 1) * margin[0]);
+        let y = Math.round(GridY * rowHeight + margin[1] * (GridY + 1));
         return {
             x: x,
             y: y
         };
-    };
-    GridItem.prototype.shouldComponentUpdate = function (props, state) {
+    }
+    shouldComponentUpdate(props, state) {
         return this.props.GridX !== props.GridX ||
             this.props.GridY !== props.GridY ||
             this.props.isUserMove !== props.isUserMove;
-    };
+    }
     /**宽和高计算成为px */
-    GridItem.prototype.calWHtoPx = function (w, h) {
-        var margin = this.props.margin;
+    calWHtoPx(w, h) {
+        var { margin } = this.props;
         if (!margin)
             margin = [0, 0];
-        var wPx = Math.round(w * this.calColWidth() + (w - 1) * margin[0]);
-        var hPx = Math.round(h * this.props.rowHeight + (h - 1) * margin[1]);
-        return { wPx: wPx, hPx: hPx };
-    };
-    GridItem.prototype.onDragStart = function (x, y) {
-        var _a = this.props, w = _a.w, h = _a.h, UniqueKey = _a.UniqueKey;
+        const wPx = Math.round(w * this.calColWidth() + (w - 1) * margin[0]);
+        const hPx = Math.round(h * this.props.rowHeight + (h - 1) * margin[1]);
+        return { wPx, hPx };
+    }
+    onDragStart(x, y) {
+        const { w, h, UniqueKey } = this.props;
         if (this.props.static)
             return;
-        var _b = this.calGridXY(x, y), GridX = _b.GridX, GridY = _b.GridY;
+        const { GridX, GridY } = this.calGridXY(x, y);
         this.props.onDragStart && this.props.onDragStart({
-            event: event, GridX: GridX, GridY: GridY, w: w, h: h, UniqueKey: UniqueKey + ''
+            event, GridX, GridY, w, h, UniqueKey: UniqueKey + ''
         });
-    };
-    GridItem.prototype.onDrag = function (event, x, y) {
+    }
+    onDrag(event, x, y) {
         if (this.props.static)
             return;
-        var _a = this.calGridXY(x, y), GridX = _a.GridX, GridY = _a.GridY;
-        var _b = this.props, w = _b.w, h = _b.h, UniqueKey = _b.UniqueKey;
-        this.props.onDrag && this.props.onDrag({ GridX: GridX, GridY: GridY, w: w, h: h, UniqueKey: UniqueKey + '', event: event });
-    };
-    GridItem.prototype.onDragEnd = function () {
+        const { GridX, GridY } = this.calGridXY(x, y);
+        const { w, h, UniqueKey } = this.props;
+        this.props.onDrag && this.props.onDrag({ GridX, GridY, w, h, UniqueKey: UniqueKey + '', event });
+    }
+    onDragEnd() {
         if (this.props.static)
             return;
         if (this.props.onDragEnd)
             this.props.onDragEnd(this.props.UniqueKey + '');
-    };
-    GridItem.prototype.render = function () {
-        var _a = this.props, w = _a.w, h = _a.h, style = _a.style, bounds = _a.bounds, GridX = _a.GridX, GridY = _a.GridY;
-        var _b = this.calGridItemPosition(GridX, GridY), x = _b.x, y = _b.y;
-        var _c = this.calWHtoPx(w, h), wPx = _c.wPx, hPx = _c.hPx;
-        return (React.createElement(index_1.Dragger, { style: __assign({}, style, { width: wPx, height: hPx, position: 'absolute', transition: this.props.isUserMove ? '' : 'all .2s' }), onDragStart: this.onDragStart, onMove: this.onDrag, onDragEnd: this.onDragEnd, x: x, y: y, isUserMove: this.props.isUserMove, bounds: bounds },
-            React.createElement("div", { style: { width: wPx, height: hPx } }, React.Children.map(this.props.children, function (child) { return child; }))));
-    };
-    GridItem.defaultProps = {
-        col: 12,
-        containerWidth: 500,
-        containerPadding: [0, 0],
-        margin: [10, 10],
-        rowHeight: 30,
-        w: 1,
-        h: 1
-    };
-    return GridItem;
-}(React.Component));
-exports.default = GridItem;
+    }
+    render() {
+        const { w, h, style, bounds, GridX, GridY } = this.props;
+        const { x, y } = this.calGridItemPosition(GridX, GridY);
+        const { wPx, hPx } = this.calWHtoPx(w, h);
+        return (React.createElement(Dragger, { style: Object.assign({}, style, { width: wPx, height: hPx, position: 'absolute', transition: this.props.isUserMove ? '' : 'all .2s' }), onDragStart: this.onDragStart, onMove: this.onDrag, onDragEnd: this.onDragEnd, x: x, y: y, isUserMove: this.props.isUserMove, bounds: bounds },
+            React.createElement("div", { style: { width: wPx, height: hPx } }, React.Children.map(this.props.children, (child) => child))));
+    }
+}
+GridItem.defaultProps = {
+    col: 12,
+    containerWidth: 500,
+    containerPadding: [0, 0],
+    margin: [10, 10],
+    rowHeight: 30,
+    w: 1,
+    h: 1
+};

+ 61 - 79
dist/lib/dragact.js

@@ -1,36 +1,23 @@
-"use strict";
-var __extends = (this && this.__extends) || (function () {
-    var extendStatics = Object.setPrototypeOf ||
-        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
-        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
-    return function (d, b) {
-        extendStatics(d, b);
-        function __() { this.constructor = d; }
-        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-    };
-})();
-Object.defineProperty(exports, "__esModule", { value: true });
-var React = require("react");
-var GridItem_1 = require("./GridItem");
-var compact_1 = require("./util/compact");
-var sort_1 = require("./util/sort");
-var collison_1 = require("./util/collison");
-var correction_1 = require("./util/correction");
-var utils_1 = require("./utils");
-var initiate_1 = require("./util/initiate");
-require("./style.css");
-var Dragact = /** @class */ (function (_super) {
-    __extends(Dragact, _super);
-    function Dragact(props) {
-        var _this = _super.call(this, props) || this;
-        _this.onDrag = _this.onDrag.bind(_this);
-        _this.onDragStart = _this.onDragStart.bind(_this);
-        _this.onDragEnd = _this.onDragEnd.bind(_this);
-        var layout = props.layout ?
-            initiate_1.MapLayoutTostate(props.layout, props.children)
+import * as React from "react";
+import GridItem from './GridItem';
+import { compactLayout } from './util/compact';
+import { getMaxContainerHeight } from './util/sort';
+import { layoutCheck } from './util/collison';
+import { correctLayout } from './util/correction';
+import { getDataSet, stringJoin } from './utils';
+import { layoutItemForkey, syncLayout, MapLayoutTostate } from './util/initiate';
+import './style.css';
+export class Dragact extends React.Component {
+    constructor(props) {
+        super(props);
+        this.onDrag = this.onDrag.bind(this);
+        this.onDragStart = this.onDragStart.bind(this);
+        this.onDragEnd = this.onDragEnd.bind(this);
+        const layout = props.layout ?
+            MapLayoutTostate(props.layout, props.children)
             :
-                utils_1.getDataSet(props.children);
-        _this.state = {
+                getDataSet(props.children);
+        this.state = {
             GridXMoving: 0,
             GridYMoving: 0,
             wMoving: 0,
@@ -40,11 +27,10 @@ var Dragact = /** @class */ (function (_super) {
             layout: layout,
             containerHeight: 500
         };
-        return _this;
     }
-    Dragact.prototype.onDragStart = function (bundles) {
-        var GridX = bundles.GridX, GridY = bundles.GridY, w = bundles.w, h = bundles.h, UniqueKey = bundles.UniqueKey;
-        var newlayout = initiate_1.syncLayout(this.state.layout, UniqueKey, GridX, GridY, true);
+    onDragStart(bundles) {
+        const { GridX, GridY, w, h, UniqueKey } = bundles;
+        const newlayout = syncLayout(this.state.layout, UniqueKey, GridX, GridY, true);
         this.setState({
             GridXMoving: GridX,
             GridYMoving: GridY,
@@ -55,14 +41,14 @@ var Dragact = /** @class */ (function (_super) {
             layout: newlayout,
         });
         this.props.onDragStart && this.props.onDragStart(bundles);
-    };
-    Dragact.prototype.onDrag = function (layoutItem) {
-        var GridY = layoutItem.GridY, UniqueKey = layoutItem.UniqueKey;
-        var moving = GridY - this.state.GridYMoving;
-        var newLayout = collison_1.layoutCheck(this.state.layout, layoutItem, UniqueKey, UniqueKey /*用户移动方块的key */, moving);
-        var compactedLayout = compact_1.compactLayout(newLayout);
-        for (var i = 0; i < compactedLayout.length; i++) {
-            var compactedItem = compactedLayout[i];
+    }
+    onDrag(layoutItem) {
+        const { GridY, UniqueKey } = layoutItem;
+        const moving = GridY - this.state.GridYMoving;
+        const newLayout = layoutCheck(this.state.layout, layoutItem, UniqueKey, UniqueKey /*用户移动方块的key */, moving);
+        const compactedLayout = compactLayout(newLayout);
+        for (let i = 0; i < compactedLayout.length; i++) {
+            const compactedItem = compactedLayout[i];
             if (UniqueKey === compactedItem.key) {
                 /**
                  * 特殊点:当我们移动元素的时候,元素在layout中的位置不断改变
@@ -80,57 +66,53 @@ var Dragact = /** @class */ (function (_super) {
             GridXMoving: layoutItem.GridX,
             GridYMoving: layoutItem.GridY,
             layout: compactedLayout,
-            containerHeight: sort_1.getMaxContainerHeight(compactedLayout, this.props.rowHeight, this.props.margin[1])
+            containerHeight: getMaxContainerHeight(compactedLayout, this.props.rowHeight, this.props.margin[1])
         });
         this.props.onDrag && this.props.onDrag(layoutItem);
-    };
-    Dragact.prototype.onDragEnd = function (key) {
-        var compactedLayout = compact_1.compactLayout(this.state.layout);
+    }
+    onDragEnd(key) {
+        const compactedLayout = compactLayout(this.state.layout);
         this.setState({
             placeholderShow: false,
             layout: compactedLayout,
-            containerHeight: sort_1.getMaxContainerHeight(compactedLayout, this.props.rowHeight, this.props.margin[1])
+            containerHeight: getMaxContainerHeight(compactedLayout, this.props.rowHeight, this.props.margin[1])
         });
         this.props.onDragEnd && this.props.onDragEnd(key);
-    };
-    Dragact.prototype.renderPlaceholder = function () {
+    }
+    renderPlaceholder() {
         if (!this.state.placeholderShow)
             return null;
-        var _a = this.props, col = _a.col, width = _a.width, padding = _a.padding, rowHeight = _a.rowHeight, margin = _a.margin;
-        var _b = this.state, GridXMoving = _b.GridXMoving, GridYMoving = _b.GridYMoving, wMoving = _b.wMoving, hMoving = _b.hMoving, placeholderMoving = _b.placeholderMoving;
+        var { col, width, padding, rowHeight, margin } = this.props;
+        const { GridXMoving, GridYMoving, wMoving, hMoving, placeholderMoving } = this.state;
         if (!padding)
             padding = 0;
-        return (React.createElement(GridItem_1.default, { margin: margin, col: col, containerWidth: width, containerPadding: [padding, padding], rowHeight: rowHeight, GridX: GridXMoving, GridY: GridYMoving, w: wMoving, h: hMoving, style: { background: '#d6e4ff', zIndex: 1, transition: ' all .15s' }, isUserMove: !placeholderMoving }));
-    };
-    Dragact.prototype.componentDidMount = function () {
-        var _this = this;
-        setTimeout(function () {
-            var layout = correction_1.correctLayout(_this.state.layout, _this.props.col);
-            var compacted = compact_1.compactLayout(layout);
-            _this.setState({
+        return (React.createElement(GridItem, { margin: margin, col: col, containerWidth: width, containerPadding: [padding, padding], rowHeight: rowHeight, GridX: GridXMoving, GridY: GridYMoving, w: wMoving, h: hMoving, style: { background: '#d6e4ff', zIndex: 1, transition: ' all .15s' }, isUserMove: !placeholderMoving }));
+    }
+    componentDidMount() {
+        setTimeout(() => {
+            let layout = correctLayout(this.state.layout, this.props.col);
+            const compacted = compactLayout(layout);
+            this.setState({
                 layout: compacted,
-                containerHeight: sort_1.getMaxContainerHeight(compacted, _this.props.rowHeight, _this.props.margin[1])
+                containerHeight: getMaxContainerHeight(compacted, this.props.rowHeight, this.props.margin[1])
             });
         }, 1);
-    };
-    Dragact.prototype.getGridItem = function (child, index) {
-        var layout = this.state.layout;
-        var _a = this.props, col = _a.col, width = _a.width, padding = _a.padding, rowHeight = _a.rowHeight, margin = _a.margin;
-        var renderItem = initiate_1.layoutItemForkey(layout, child.key); //TODO:可以优化速度,这一步不是必须;
+    }
+    getGridItem(child, index) {
+        const { layout } = this.state;
+        var { col, width, padding, rowHeight, margin } = this.props;
+        const renderItem = layoutItemForkey(layout, child.key); //TODO:可以优化速度,这一步不是必须;
         if (renderItem) {
             if (!padding)
                 padding = 0;
-            return (React.createElement(GridItem_1.default, { margin: margin, col: col, containerWidth: width, containerPadding: [padding, padding], rowHeight: rowHeight, GridX: renderItem.GridX, GridY: renderItem.GridY, w: renderItem.w, h: renderItem.h, onDrag: this.onDrag, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd, isUserMove: renderItem.isUserMove !== void 666 ? renderItem.isUserMove : false, UniqueKey: child.key, style: { zIndex: 2 }, static: renderItem.static }, child));
+            return (React.createElement(GridItem, { margin: margin, col: col, containerWidth: width, containerPadding: [padding, padding], rowHeight: rowHeight, GridX: renderItem.GridX, GridY: renderItem.GridY, w: renderItem.w, h: renderItem.h, onDrag: this.onDrag, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd, isUserMove: renderItem.isUserMove !== void 666 ? renderItem.isUserMove : false, UniqueKey: child.key, style: { zIndex: 2 }, static: renderItem.static }, child));
         }
-    };
-    Dragact.prototype.render = function () {
-        var _this = this;
-        var _a = this.props, width = _a.width, className = _a.className;
-        var containerHeight = this.state.containerHeight;
-        return (React.createElement("div", { className: utils_1.stringJoin('DraggerLayout', className + ''), style: { left: 100, width: width, height: containerHeight, zIndex: 1 } },
-            React.Children.map(this.props.children, function (child, index) { return _this.getGridItem(child, index); }),
+    }
+    render() {
+        const { width, className } = this.props;
+        const { containerHeight } = this.state;
+        return (React.createElement("div", { className: stringJoin('DraggerLayout', className + ''), style: { left: 100, width: width, height: containerHeight, zIndex: 1 } },
+            React.Children.map(this.props.children, (child, index) => this.getGridItem(child, index)),
             this.renderPlaceholder()));
-    };
-    return Dragact;
-}(React.Component));
-exports.Dragact = Dragact;
+    }
+}

+ 49 - 73
dist/lib/dragger/index.js

@@ -1,32 +1,11 @@
-"use strict";
-var __extends = (this && this.__extends) || (function () {
-    var extendStatics = Object.setPrototypeOf ||
-        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
-        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
-    return function (d, b) {
-        extendStatics(d, b);
-        function __() { this.constructor = d; }
-        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-    };
-})();
-var __assign = (this && this.__assign) || Object.assign || function(t) {
-    for (var s, i = 1, n = arguments.length; i < n; i++) {
-        s = arguments[i];
-        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
-            t[p] = s[p];
-    }
-    return t;
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-var React = require("react");
-var utils_1 = require("../utils");
+import * as React from "react";
+import { int, innerHeight, innerWidth, outerHeight, outerWidth, parseBounds } from '../utils';
 /// <reference path="react.d.ts" />
-var doc = document;
-var Dragger = /** @class */ (function (_super) {
-    __extends(Dragger, _super);
-    function Dragger(props) {
-        var _this = _super.call(this, props) || this;
-        _this.state = {
+const doc = document;
+export class Dragger extends React.Component {
+    constructor(props) {
+        super(props);
+        this.state = {
             /** x轴位移,单位是px */
             x: 0,
             /** y轴位移,单位是px */
@@ -41,18 +20,17 @@ var Dragger = /** @class */ (function (_super) {
             /**堆叠的层级 */
             zIndex: 1
         };
-        _this.move = _this.move.bind(_this);
-        _this.onDragEnd = _this.onDragEnd.bind(_this);
-        _this.parent = null;
-        _this.self = null;
-        return _this;
+        this.move = this.move.bind(this);
+        this.onDragEnd = this.onDragEnd.bind(this);
+        this.parent = null;
+        this.self = null;
     }
-    Dragger.prototype.move = function (event) {
-        var _a = this.state, lastX = _a.lastX, lastY = _a.lastY;
+    move(event) {
+        let { lastX, lastY } = this.state;
         /*  event.client - this.state.origin 表示的是移动的距离,
         *   elX表示的是原来已经有的位移
         */
-        var deltaX, deltaY;
+        let deltaX, deltaY;
         if (event.type.indexOf('mouse') >= 0) {
             deltaX = event.clientX - this.state.originX + lastX;
             deltaY = event.clientY - this.state.originY + lastY;
@@ -61,29 +39,29 @@ var Dragger = /** @class */ (function (_super) {
             deltaX = event.touches[0].clientX - this.state.originX + lastX;
             deltaY = event.touches[0].clientY - this.state.originY + lastY;
         }
-        var bounds = this.props.bounds;
+        const { bounds } = this.props;
         if (bounds) {
             /**
             * 如果用户指定一个边界,那么在这里处理
             */
-            var NewBounds = typeof bounds !== 'string' ? utils_1.parseBounds(bounds) : bounds;
+            let NewBounds = typeof bounds !== 'string' ? parseBounds(bounds) : bounds;
             /**
              * 网格式移动范围设定,永远移动 n 的倍数
              * 注意:设定移动范围的时候,一定要在判断bounds之前,否则会造成bounds不对齐
              */
-            var grid = this.props.grid;
+            const { grid } = this.props;
             if (Array.isArray(grid) && grid.length === 2) {
                 deltaX = Math.round(deltaX / grid[0]) * grid[0];
                 deltaY = Math.round(deltaY / grid[1]) * grid[1];
             }
             if (this.props.bounds === 'parent') {
                 NewBounds = {
-                    left: utils_1.int(this.parent.style.paddingLeft) + utils_1.int(this.self.style.marginLeft) - this.self.offsetLeft,
-                    top: utils_1.int(this.parent.style.paddingTop) + utils_1.int(this.self.style.marginTop) - this.self.offsetTop,
-                    right: utils_1.innerWidth(this.parent) - utils_1.outerWidth(this.self) - this.self.offsetLeft +
-                        utils_1.int(this.parent.style.paddingRight) - utils_1.int(this.self.style.marginRight),
-                    bottom: utils_1.innerHeight(this.parent) - utils_1.outerHeight(this.self) - this.self.offsetTop +
-                        utils_1.int(this.parent.style.paddingBottom) - utils_1.int(this.self.style.marginBottom)
+                    left: int(this.parent.style.paddingLeft) + int(this.self.style.marginLeft) - this.self.offsetLeft,
+                    top: int(this.parent.style.paddingTop) + int(this.self.style.marginTop) - this.self.offsetTop,
+                    right: innerWidth(this.parent) - outerWidth(this.self) - this.self.offsetLeft +
+                        int(this.parent.style.paddingRight) - int(this.self.style.marginRight),
+                    bottom: innerHeight(this.parent) - outerHeight(this.self) - this.self.offsetTop +
+                        int(this.parent.style.paddingBottom) - int(this.self.style.marginBottom)
                 };
             }
             /**
@@ -113,8 +91,8 @@ var Dragger = /** @class */ (function (_super) {
             x: deltaX,
             y: deltaY
         });
-    };
-    Dragger.prototype.onDragStart = function (event) {
+    }
+    onDragStart(event) {
         /** 保证用户在移动元素的时候不会选择到元素内部的东西 */
         doc.body.style.userSelect = 'none';
         // if (this.props.hasDraggerHandle) {
@@ -150,7 +128,7 @@ var Dragger = /** @class */ (function (_super) {
             this.self = event.currentTarget;
         }
         this.props.onDragStart && this.props.onDragStart(this.state.x, this.state.y);
-        var originX, originY;
+        let originX, originY;
         if (event.type.indexOf('mouse') >= 0) {
             originX = event.clientX;
             originY = event.clientY;
@@ -166,8 +144,8 @@ var Dragger = /** @class */ (function (_super) {
             lastY: this.state.y,
             zIndex: 10
         });
-    };
-    Dragger.prototype.onDragEnd = function (event) {
+    }
+    onDragEnd(event) {
         /** 取消用户选择限制,用户可以重新选择 */
         doc.body.style.userSelect = '';
         this.parent = null;
@@ -184,8 +162,8 @@ var Dragger = /** @class */ (function (_super) {
             zIndex: 1
         });
         this.props.onDragEnd && this.props.onDragEnd(event);
-    };
-    Dragger.prototype.componentDidMount = function () {
+    }
+    componentDidMount() {
         /**
          * 这个函数只会调用一次
          * 这个只是一个临时的解决方案,因为这样会使得元素进行两次刷新
@@ -197,14 +175,14 @@ var Dragger = /** @class */ (function (_super) {
                 y: this.props.y
             });
         }
-    };
-    Dragger.prototype.componentWillReceiveProps = function (nextProps) {
+    }
+    componentWillReceiveProps(nextProps) {
         /**
          * 外部props 改变的时候更新元素的内部位置
          * 这个api设计其实很不好
          * 以后可能会修改掉
          */
-        var isUserMove = nextProps.isUserMove;
+        const { isUserMove } = nextProps;
         if (!isUserMove) {
             if (typeof nextProps.x === 'number' &&
                 typeof nextProps.y === 'number') {
@@ -216,27 +194,25 @@ var Dragger = /** @class */ (function (_super) {
                 });
             }
         }
-    };
-    Dragger.prototype.render = function () {
-        var _a = this.state, x = _a.x, y = _a.y, zIndex = _a.zIndex;
-        var _b = this.props, style = _b.style, className = _b.className;
+    }
+    render() {
+        let { x, y, zIndex } = this.state;
+        const { style, className } = this.props;
         if (!this.props.isUserMove) {
             /**当外部设置其props的x,y初始属性的时候,我们在这里设置元素的初始位移 */
             x = this.props.x ? this.props.x : 0;
             y = this.props.y ? this.props.y : 0;
         }
         /**主要是为了让用户定义自己的className去修改css */
-        var fixedClassName = typeof className === 'undefined' ? '' : className + ' ';
-        return (React.createElement("div", { className: fixedClassName + "WrapDragger", style: __assign({}, style, { zIndex: zIndex, touchAction: 'none!important', transform: "translate(" + x + "px," + y + "px)" }), onMouseDown: this.onDragStart.bind(this), onTouchStart: this.onDragStart.bind(this), onTouchEnd: this.onDragEnd.bind(this), onMouseUp: this.onDragEnd.bind(this) }, React.Children.only(this.props.children)));
-    };
-    /**
-     * 初始变量设置
-     */
-    Dragger.defaultProps = {
-        allowX: true,
-        allowY: true,
-        isUserMove: true
-    };
-    return Dragger;
-}(React.Component));
-exports.Dragger = Dragger;
+        const fixedClassName = typeof className === 'undefined' ? '' : className + ' ';
+        return (React.createElement("div", { className: `${fixedClassName}WrapDragger`, style: Object.assign({}, style, { zIndex: zIndex, touchAction: 'none!important', transform: `translate(${x}px,${y}px)` }), onMouseDown: this.onDragStart.bind(this), onTouchStart: this.onDragStart.bind(this), onTouchEnd: this.onDragEnd.bind(this), onMouseUp: this.onDragEnd.bind(this) }, React.Children.only(this.props.children)));
+    }
+}
+/**
+ * 初始变量设置
+ */
+Dragger.defaultProps = {
+    allowX: true,
+    allowY: true,
+    isUserMove: true
+};

+ 24 - 34
dist/lib/util/collison.js

@@ -1,14 +1,4 @@
-"use strict";
-var __assign = (this && this.__assign) || Object.assign || function(t) {
-    for (var s, i = 1, n = arguments.length; i < n; i++) {
-        s = arguments[i];
-        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
-            t[p] = s[p];
-    }
-    return t;
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.collision = function (a, b) {
+export const collision = (a, b) => {
     if (a.GridX === b.GridX && a.GridY === b.GridY &&
         a.w === b.w && a.h === b.h) {
         return true;
@@ -24,28 +14,28 @@ exports.collision = function (a, b) {
     return true;
 };
 /**获取layout中,item第一个碰撞到的物体 */
-exports.getFirstCollison = function (layout, item) {
-    for (var i = 0, length_1 = layout.length; i < length_1; i++) {
-        if (exports.collision(layout[i], item)) {
+export const getFirstCollison = (layout, item) => {
+    for (let i = 0, length = layout.length; i < length; i++) {
+        if (collision(layout[i], item)) {
             return layout[i];
         }
     }
     return null;
 };
-exports.layoutCheck = function (layout, layoutItem, key, fristItemkey, moving) {
-    var i = [], movedItem = []; /**收集所有移动过的物体 */
-    var newlayout = layout.map(function (item, idx) {
+export const layoutCheck = (layout, layoutItem, key, fristItemkey, moving) => {
+    let i = [], movedItem = []; /**收集所有移动过的物体 */
+    let newlayout = layout.map((item, idx) => {
         if (item.key !== key) {
             if (item.static) {
                 return item;
             }
-            if (exports.collision(item, layoutItem)) {
+            if (collision(item, layoutItem)) {
                 i.push(item.key);
                 /**
                  * 这里就是奇迹发生的地方,如果向上移动,那么必须注意的是
                  * 一格一格的移动,而不是一次性移动
                  */
-                var offsetY = item.GridY + 1;
+                let offsetY = item.GridY + 1;
                 /**这一行也非常关键,当向上移动的时候,碰撞的元素必须固定 */
                 // if (moving < 0 && layoutItem.GridY > 0) offsetY = item.GridY
                 if (layoutItem.GridY > item.GridY && layoutItem.GridY < item.GridY + item.h) {
@@ -60,43 +50,43 @@ exports.layoutCheck = function (layout, layoutItem, key, fristItemkey, moving) {
                  */
                 if (moving > 0) {
                     if (layoutItem.GridY + layoutItem.h < item.GridY) {
-                        var collision_1;
-                        var copy_1 = __assign({}, item);
+                        let collision;
+                        let copy = Object.assign({}, item);
                         while (true) {
-                            var newLayout = layout.filter(function (item) {
-                                if (item.key !== key && (item.key !== copy_1.key)) {
+                            let newLayout = layout.filter((item) => {
+                                if (item.key !== key && (item.key !== copy.key)) {
                                     return item;
                                 }
                             });
-                            collision_1 = exports.getFirstCollison(newLayout, copy_1);
-                            if (collision_1) {
-                                offsetY = collision_1.GridY + collision_1.h;
+                            collision = getFirstCollison(newLayout, copy);
+                            if (collision) {
+                                offsetY = collision.GridY + collision.h;
                                 break;
                             }
                             else {
-                                copy_1.GridY--;
+                                copy.GridY--;
                             }
-                            if (copy_1.GridY < 0) {
+                            if (copy.GridY < 0) {
                                 offsetY = 0;
                                 break;
                             }
                         }
                     }
                 }
-                movedItem.push(__assign({}, item, { GridY: offsetY, isUserMove: false }));
-                return __assign({}, item, { GridY: offsetY, isUserMove: false });
+                movedItem.push(Object.assign({}, item, { GridY: offsetY, isUserMove: false }));
+                return Object.assign({}, item, { GridY: offsetY, isUserMove: false });
             }
         }
         else if (fristItemkey === key) {
             /**永远保持用户移动的块是 isUserMove === true */
-            return __assign({}, item, { GridX: layoutItem.GridX, GridY: layoutItem.GridY, isUserMove: true });
+            return Object.assign({}, item, { GridX: layoutItem.GridX, GridY: layoutItem.GridY, isUserMove: true });
         }
         return item;
     });
     /** 递归调用,将layout中的所有重叠元素全部移动 */
-    var length = movedItem.length;
-    for (var c = 0; c < length; c++) {
-        newlayout = exports.layoutCheck(newlayout, movedItem[c], i[c], fristItemkey, 0);
+    const length = movedItem.length;
+    for (let c = 0; c < length; c++) {
+        newlayout = layoutCheck(newlayout, movedItem[c], i[c], fristItemkey, 0);
     }
     return newlayout;
 };

+ 13 - 23
dist/lib/util/compact.js

@@ -1,32 +1,22 @@
-"use strict";
-var __assign = (this && this.__assign) || Object.assign || function(t) {
-    for (var s, i = 1, n = arguments.length; i < n; i++) {
-        s = arguments[i];
-        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
-            t[p] = s[p];
-    }
-    return t;
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-var sort_1 = require("./sort");
-var collison_1 = require("./collison");
+import { sortLayout } from "./sort";
+import { getFirstCollison } from "./collison";
 /**
  * 压缩单个元素,使得每一个元素都会紧挨着边界或者相邻的元素
  * @param {*} finishedLayout 压缩完的元素会放进这里来,用来对比之后的每一个元素是否需要压缩
  * @param {*} item
  */
-exports.compactItem = function (finishedLayout, item) {
+export const compactItem = (finishedLayout, item) => {
     if (item.static)
         return item;
-    var newItem = __assign({}, item);
+    const newItem = Object.assign({}, item);
     if (finishedLayout.length === 0) {
-        return __assign({}, newItem, { GridY: 0 });
+        return Object.assign({}, newItem, { GridY: 0 });
     }
     /**
      * 类似一个递归调用
      */
     while (true) {
-        var FirstCollison = collison_1.getFirstCollison(finishedLayout, newItem);
+        let FirstCollison = getFirstCollison(finishedLayout, newItem);
         if (FirstCollison) {
             /**第一次发生碰撞时,就可以返回了 */
             newItem.GridY = FirstCollison.GridY + FirstCollison.h;
@@ -34,19 +24,19 @@ exports.compactItem = function (finishedLayout, item) {
         }
         newItem.GridY--;
         if (newItem.GridY < 0)
-            return __assign({}, newItem, { GridY: 0 }); /**碰到边界的时候,返回 */
+            return Object.assign({}, newItem, { GridY: 0 }); /**碰到边界的时候,返回 */
     }
 };
 /**
  * 压缩layout,使得每一个元素都会紧挨着边界或者相邻的元素
  * @param {*} layout
  */
-exports.compactLayout = function (layout) {
-    var sorted = sort_1.sortLayout(layout);
-    var needCompact = Array(layout.length);
-    var compareList = [];
-    for (var i = 0, length_1 = sorted.length; i < length_1; i++) {
-        var finished = exports.compactItem(compareList, sorted[i]);
+export const compactLayout = (layout) => {
+    let sorted = sortLayout(layout);
+    const needCompact = Array(layout.length);
+    const compareList = [];
+    for (let i = 0, length = sorted.length; i < length; i++) {
+        let finished = compactItem(compareList, sorted[i]);
         finished.isUserMove = false;
         compareList.push(finished);
         needCompact[i] = finished;

+ 12 - 14
dist/lib/util/correction.js

@@ -1,7 +1,5 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-var collison_1 = require("./collison");
-exports.checkInContainer = function (GridX, GridY, col, w) {
+import { collision, layoutCheck } from "./collison";
+export const checkInContainer = (GridX, GridY, col, w) => {
     /**防止元素出container */
     if (GridX + w > col - 1)
         GridX = col - w; //右边界
@@ -9,24 +7,24 @@ exports.checkInContainer = function (GridX, GridY, col, w) {
         GridX = 0; //左边界
     if (GridY < 0)
         GridY = 0; //上边界
-    return { GridX: GridX, GridY: GridY };
+    return { GridX, GridY };
 };
 /**
  * 这个函数会有副作用,不是纯函数,会改变item的Gridx和GridY
  * @param {*} item
  */
-exports.correctItem = function (item, col) {
-    var _a = exports.checkInContainer(item.GridX, item.GridY, col, item.w), GridX = _a.GridX, GridY = _a.GridY;
+export const correctItem = (item, col) => {
+    const { GridX, GridY } = checkInContainer(item.GridX, item.GridY, col, item.w);
     item.GridX = GridX;
     item.GridY = GridY;
 };
-exports.correctLayout = function (layout, col) {
-    var copy = layout.slice();
-    for (var i = 0; i < layout.length - 1; i++) {
-        exports.correctItem(copy[i], col);
-        exports.correctItem(copy[i + 1], col);
-        if (collison_1.collision(copy[i], copy[i + 1])) {
-            copy = collison_1.layoutCheck(copy, copy[i], copy[i].UniqueKey, copy[i].UniqueKey, 0);
+export const correctLayout = (layout, col) => {
+    var copy = [...layout];
+    for (let i = 0; i < layout.length - 1; i++) {
+        correctItem(copy[i], col);
+        correctItem(copy[i + 1], col);
+        if (collision(copy[i], copy[i + 1])) {
+            copy = layoutCheck(copy, copy[i], copy[i].UniqueKey, copy[i].UniqueKey, 0);
         }
     }
     return copy;

+ 7 - 17
dist/lib/util/initiate.js

@@ -1,13 +1,3 @@
-"use strict";
-var __assign = (this && this.__assign) || Object.assign || function(t) {
-    for (var s, i = 1, n = arguments.length; i < n; i++) {
-        s = arguments[i];
-        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
-            t[p] = s[p];
-    }
-    return t;
-};
-Object.defineProperty(exports, "__esModule", { value: true });
 /**
  * 把用户移动的块,标记为true
  * @param {*} layout
@@ -16,8 +6,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
  * @param {*} GridY
  * @param {*} isUserMove
  */
-exports.syncLayout = function (layout, key, GridX, GridY, isUserMove) {
-    var newlayout = layout.map(function (item) {
+export const syncLayout = (layout, key, GridX, GridY, isUserMove) => {
+    const newlayout = layout.map((item) => {
         if (item.key === key) {
             item.GridX = GridX;
             item.GridY = GridY;
@@ -35,9 +25,9 @@ exports.syncLayout = function (layout, key, GridX, GridY, isUserMove) {
  * @param {*} layout
  * @param {*} children
  */
-exports.MapLayoutTostate = function (layout, children) {
-    return layout.map(function (child, index) {
-        var newChild = __assign({}, child, { isUserMove: true, key: children[index].key, static: children[index].static });
+export const MapLayoutTostate = (layout, children) => {
+    return layout.map((child, index) => {
+        let newChild = Object.assign({}, child, { isUserMove: true, key: children[index].key, static: children[index].static });
         return newChild;
     });
 };
@@ -46,8 +36,8 @@ exports.MapLayoutTostate = function (layout, children) {
  * @param {*} layout 输入进来的布局
  * @param {*} key
  */
-exports.layoutItemForkey = function (layout, key) {
-    for (var i = 0, length_1 = layout.length; i < length_1; i++) {
+export const layoutItemForkey = (layout, key) => {
+    for (let i = 0, length = layout.length; i < length; i++) {
         if (key === layout[i].key) {
             return layout[i];
         }

+ 8 - 13
dist/lib/util/sort.js

@@ -1,11 +1,8 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-function quickSort(a) {
-    return a.length <= 1 ? a : quickSort(a.slice(1).filter(function (item) { return item <= a[0]; })).concat(a[0], quickSort(a.slice(1).filter(function (item) { return item > a[0]; })));
+export function quickSort(a) {
+    return a.length <= 1 ? a : quickSort(a.slice(1).filter(item => item <= a[0])).concat(a[0], quickSort(a.slice(1).filter(item => item > a[0])));
 }
-exports.quickSort = quickSort;
-exports.sortLayout = function (layout) {
-    return [].concat(layout).sort(function (a, b) {
+export const sortLayout = (layout) => {
+    return [].concat(layout).sort((a, b) => {
         if (a.GridY > b.GridY || (a.GridY === b.GridY && a.GridX > b.GridX)) {
             if (a.static)
                 return 0; //为了静态,排序的时候尽量把静态的放在前面
@@ -17,13 +14,11 @@ exports.sortLayout = function (layout) {
         return -1;
     });
 };
-exports.getMaxContainerHeight = function (layout, elementHeight, elementMarginBottom) {
-    if (elementHeight === void 0) { elementHeight = 30; }
-    if (elementMarginBottom === void 0) { elementMarginBottom = 10; }
-    var ar = layout.map(function (item) {
+export const getMaxContainerHeight = (layout, elementHeight = 30, elementMarginBottom = 10) => {
+    const ar = layout.map((item) => {
         return item.GridY + item.h;
     });
-    var h = quickSort(ar)[ar.length - 1];
-    var height = h * (elementHeight + elementMarginBottom) + elementMarginBottom;
+    const h = quickSort(ar)[ar.length - 1];
+    const height = h * (elementHeight + elementMarginBottom) + elementMarginBottom;
     return height;
 };

+ 28 - 38
dist/lib/utils.js

@@ -1,48 +1,38 @@
-"use strict";
-var __assign = (this && this.__assign) || Object.assign || function(t) {
-    for (var s, i = 1, n = arguments.length; i < n; i++) {
-        s = arguments[i];
-        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
-            t[p] = s[p];
-    }
-    return t;
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.int = function (number) {
+export const int = (number) => {
     if (number === '' || number === null) {
         return 0;
     }
     return parseInt(number, 10);
 };
-exports.innerWidth = function (node) {
-    var width = node.clientWidth;
-    var computedStyle = node.style;
-    width -= exports.int(computedStyle.paddingLeft);
-    width -= exports.int(computedStyle.paddingRight);
+export const innerWidth = (node) => {
+    let width = node.clientWidth;
+    const computedStyle = node.style;
+    width -= int(computedStyle.paddingLeft);
+    width -= int(computedStyle.paddingRight);
     return width;
 };
-exports.outerWidth = function (node) {
-    var width = node.clientWidth;
-    var computedStyle = node.style;
-    width += exports.int(computedStyle.borderLeftWidth);
-    width += exports.int(computedStyle.borderRightWidth);
+export const outerWidth = (node) => {
+    let width = node.clientWidth;
+    const computedStyle = node.style;
+    width += int(computedStyle.borderLeftWidth);
+    width += int(computedStyle.borderRightWidth);
     return width;
 };
-exports.innerHeight = function (node) {
-    var height = node.clientHeight;
-    var computedStyle = node.style;
-    height -= exports.int(computedStyle.paddingTop);
-    height -= exports.int(computedStyle.paddingBottom);
+export const innerHeight = (node) => {
+    let height = node.clientHeight;
+    const computedStyle = node.style;
+    height -= int(computedStyle.paddingTop);
+    height -= int(computedStyle.paddingBottom);
     return height;
 };
-exports.outerHeight = function (node) {
-    var height = node.clientHeight;
-    var computedStyle = node.style;
-    height += exports.int(computedStyle.borderTopWidth);
-    height += exports.int(computedStyle.borderBottomWidth);
+export const outerHeight = (node) => {
+    let height = node.clientHeight;
+    const computedStyle = node.style;
+    height += int(computedStyle.borderTopWidth);
+    height += int(computedStyle.borderBottomWidth);
     return height;
 };
-exports.parseBounds = function (bounds) {
+export const parseBounds = (bounds) => {
     return {
         left: bounds.left,
         top: bounds.top,
@@ -50,14 +40,14 @@ exports.parseBounds = function (bounds) {
         bottom: bounds.bottom
     };
 };
-exports.isNumber = function (things) {
+export const isNumber = (things) => {
     return typeof things === 'number' ? true : false;
 };
-exports.getDataSet = function (children) {
-    return children.map(function (child) {
-        return __assign({}, child.props['data-set'], { isUserMove: true, key: child.key });
+export const getDataSet = (children) => {
+    return children.map((child) => {
+        return Object.assign({}, child.props['data-set'], { isUserMove: true, key: child.key });
     });
 };
-exports.stringJoin = function (source, join) {
-    return source + (join ? " " + join : '');
+export const stringJoin = (source, join) => {
+    return source + (join ? ` ${join}` : '');
 };

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 456 - 68
package-lock.json


+ 29 - 4
package.json

@@ -1,12 +1,12 @@
 {
   "name": "dragact",
-  "version": "0.1.1",
+  "version": "0.1.2",
   "description": "",
   "main": "index.js",
   "scripts": {
     "temp": "NODE_ENV=production webpack -p --config webpack.pro.config.js ",
-    "test": "webpack-dev-server --devtool eval-source-map --progress --host 127.0.0.1 --colors --hot --content-base ./build --history-api-fallback",
-    "build": "./node_modules/.bin/babel --out-dir ./build ./app/src/",
+    "test": "jest --watch --no-cache",
+    "build": "tsc ./src/lib",
     "dev": "webpack-dev-server --devtool eval-source-map --progress --host 127.0.0.1 --colors --content-base ./build --history-api-fallback --open"
   },
   "author": "Fangzheng",
@@ -27,14 +27,39 @@
     "webpack": "^3.0.0",
     "webpack-dev-server": "^2.4.5"
   },
+  "jest": {
+    "verbose": true,
+    "transform": {
+      "^.+\\.js$": "babel-jest",
+      "^.+\\.(ts|tsx)$": "typescript-babel-jest"
+    },
+    "globals": {
+      "NODE_ENV": "test"
+    },
+    "moduleFileExtensions": [
+      "js",
+      "jsx",
+      "ts",
+      "tsx"
+    ],
+    "moduleDirectories": [
+      "node_modules",
+      "src/frontend",
+      "src/shared"
+    ]
+  },
   "dependencies": {
     "@types/react": "^16.0.38",
     "@types/react-dom": "^16.0.4",
+    "babel-jest": "^22.2.2",
     "babel-plugin-transform-object-rest-spread": "^6.26.0",
     "babel-plugin-transform-react-jsx": "^6.24.1",
     "babel-plugin-transform-runtime": "^6.23.0",
+    "jest": "^22.3.0",
+    "power-assert": "^1.4.4",
     "prop-types": "^15.5.10",
     "react": "^16.3.0-alpha.1",
-    "react-dom": "^16.3.0-alpha.1"
+    "react-dom": "^16.3.0-alpha.1",
+    "typescript-babel-jest": "^1.0.5"
   }
 }

+ 2 - 2
src/index.tsx

@@ -1,8 +1,8 @@
 import * as React from "react";
 import * as ReactDOM from "react-dom";
 import { LayoutDemo } from './NormalLayout/index';
-import { SortedTable } from "./SortedTable";
-import { SortedTableWithStatic } from "./StaticHeader";
+import { SortedTable } from "./SortedTable/index";
+import { SortedTableWithStatic } from "./StaticHeader/index";
 
 import './index.css'
 

+ 3 - 3
src/lib/dragact.tsx

@@ -10,7 +10,7 @@ import { layoutItemForkey, syncLayout, MapLayoutTostate } from './util/initiate'
 import './style.css';
 
 
-export interface DragactLayout {
+export interface DragactLayoutItem {
     GridX: number
     GridY: number
     static?: Boolean
@@ -21,7 +21,7 @@ export interface DragactLayout {
 }
 
 export interface DragactProps {
-    layout?: DragactLayout[] //暂时不推荐使用
+    layout?: DragactLayoutItem[] //暂时不推荐使用
     /** 
      * 宽度切分比 
      * 这个参数会把容器的宽度平均分为col等份
@@ -88,7 +88,7 @@ interface DragactState {
     hMoving: number
     placeholderShow: Boolean,
     placeholderMoving: Boolean,
-    layout: DragactLayout[],
+    layout: DragactLayoutItem[],
     containerHeight: number
 }
 

+ 4 - 4
src/lib/util/collison.ts

@@ -1,7 +1,7 @@
-import { DragactLayout } from "../dragact";
+import { DragactLayoutItem } from "../dragact";
 import { GridItemEvent } from "../gridItem";
 
-export const collision = (a: DragactLayout, b: DragactLayout) => {
+export const collision = (a: DragactLayoutItem, b: DragactLayoutItem) => {
     if (a.GridX === b.GridX && a.GridY === b.GridY &&
         a.w === b.w && a.h === b.h) {
         return true
@@ -15,7 +15,7 @@ export const collision = (a: DragactLayout, b: DragactLayout) => {
 
 
 /**获取layout中,item第一个碰撞到的物体 */
-export const getFirstCollison = (layout: DragactLayout[], item: DragactLayout) => {
+export const getFirstCollison = (layout: DragactLayoutItem[], item: DragactLayoutItem) => {
     for (let i = 0, length = layout.length; i < length; i++) {
         if (collision(layout[i], item)) {
             return layout[i]
@@ -24,7 +24,7 @@ export const getFirstCollison = (layout: DragactLayout[], item: DragactLayout) =
     return null
 }
 
-export const layoutCheck = (layout: DragactLayout[], layoutItem: GridItemEvent,
+export const layoutCheck = (layout: DragactLayoutItem[], layoutItem: GridItemEvent,
     key: string | number, fristItemkey: string | number, moving: number) => {
 
     let i: any = [], movedItem: any = []/**收集所有移动过的物体 */

+ 3 - 3
src/lib/util/compact.ts

@@ -1,13 +1,13 @@
 import { sortLayout } from "./sort";
 import { getFirstCollison } from "./collison";
-import { DragactLayout } from "../dragact";
+import { DragactLayoutItem } from "../dragact";
 
 /**
  * 压缩单个元素,使得每一个元素都会紧挨着边界或者相邻的元素
  * @param {*} finishedLayout 压缩完的元素会放进这里来,用来对比之后的每一个元素是否需要压缩
  * @param {*} item 
  */
-export const compactItem = (finishedLayout: DragactLayout[], item: DragactLayout) => {
+export const compactItem = (finishedLayout: DragactLayoutItem[], item: DragactLayoutItem) => {
     if (item.static) return item;
     const newItem = { ...item }
     if (finishedLayout.length === 0) {
@@ -34,7 +34,7 @@ export const compactItem = (finishedLayout: DragactLayout[], item: DragactLayout
  * 压缩layout,使得每一个元素都会紧挨着边界或者相邻的元素
  * @param {*} layout 
  */
-export const compactLayout = (layout: DragactLayout[]) => {
+export const compactLayout = (layout: DragactLayoutItem[]) => {
     let sorted = sortLayout(layout)
     const needCompact = Array(layout.length)
     const compareList = []

+ 3 - 3
src/lib/util/correction.ts

@@ -1,5 +1,5 @@
 import { collision, layoutCheck } from "./collison";
-import { DragactLayout } from "../dragact";
+import { DragactLayoutItem } from "../dragact";
 import { GridItemEvent } from "../gridItem";
 
 
@@ -15,12 +15,12 @@ export const checkInContainer = (GridX: number, GridY: number, col: number, w: n
  * 这个函数会有副作用,不是纯函数,会改变item的Gridx和GridY
  * @param {*} item 
  */
-export const correctItem = (item: DragactLayout, col: number) => {
+export const correctItem = (item: DragactLayoutItem, col: number) => {
     const { GridX, GridY } = checkInContainer(item.GridX, item.GridY, col, item.w)
     item.GridX = GridX;
     item.GridY = GridY;
 }
-export const correctLayout = (layout: DragactLayout[], col: number) => {
+export const correctLayout = (layout: DragactLayoutItem[], col: number) => {
     var copy = [...layout];
     for (let i = 0; i < layout.length - 1; i++) {
         correctItem(copy[i], col)

+ 4 - 4
src/lib/util/initiate.ts

@@ -1,4 +1,4 @@
-import { DragactLayout } from "../dragact";
+import { DragactLayoutItem } from "../dragact";
 
 /**
  * 把用户移动的块,标记为true
@@ -8,7 +8,7 @@ import { DragactLayout } from "../dragact";
  * @param {*} GridY 
  * @param {*} isUserMove 
  */
-export const syncLayout = (layout: DragactLayout[], key: number | string, GridX: number, GridY: number, isUserMove: Boolean) => {
+export const syncLayout = (layout: DragactLayoutItem[], key: number | string, GridX: number, GridY: number, isUserMove: Boolean) => {
     const newlayout = layout.map((item) => {
         if (item.key === key) {
             item.GridX = GridX
@@ -30,7 +30,7 @@ export const syncLayout = (layout: DragactLayout[], key: number | string, GridX:
  * @param {*} children 
  */
 
-export const MapLayoutTostate = (layout: DragactLayout[], children: any[]) => {
+export const MapLayoutTostate = (layout: DragactLayoutItem[], children: any[]) => {
     return layout.map((child, index) => {
         let newChild = { ...child, isUserMove: true, key: children[index].key, static: children[index].static }
         return newChild
@@ -42,7 +42,7 @@ export const MapLayoutTostate = (layout: DragactLayout[], children: any[]) => {
  * @param {*} layout 输入进来的布局
  * @param {*} key 
  */
-export const layoutItemForkey = (layout: DragactLayout[], key: number) => {
+export const layoutItemForkey = (layout: DragactLayoutItem[], key: number) => {
     for (let i = 0, length = layout.length; i < length; i++) {
         if (key === layout[i].key) {
             return layout[i]

+ 2 - 2
src/lib/util/sort.ts

@@ -1,4 +1,4 @@
-import { DragactLayout } from "../dragact";
+import { DragactLayoutItem } from "../dragact";
 
 export function quickSort(a: number[]): any {
     return a.length <= 1 ? a : quickSort(a.slice(1).filter(item => item <= a[0])).concat(a[0], quickSort(a.slice(1).filter(item => item > a[0])));
@@ -16,7 +16,7 @@ export const sortLayout = (layout: any) => {
     })
 }
 
-export const getMaxContainerHeight = (layout: DragactLayout[], elementHeight = 30, elementMarginBottom = 10) => {
+export const getMaxContainerHeight = (layout: DragactLayoutItem[], elementHeight = 30, elementMarginBottom = 10) => {
     const ar = layout.map((item) => {
         return item.GridY + item.h
     })

+ 15 - 0
test/utils.test.js

@@ -0,0 +1,15 @@
+import { stringJoin, int, innerHeight } from '../src/lib/utils';
+import assert from "power-assert";
+
+describe("utils test", () => {
+  it("should join the string", () => {
+    const joined = stringJoin('good', 'bye');
+    assert.equal(joined, 'good bye')
+  });
+
+  it("parseint", () => {
+    const inted = int("1233");
+    assert.equal(inted, 1233);
+  });
+
+});

+ 1 - 1
tsconfig.json

@@ -1,6 +1,6 @@
 {
     "compilerOptions": {
-        "module": "commonjs",
+        "module": "ES6",
         "target": "es5",
         "noImplicitAny": true,
         "sourceMap": false,

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно