浏览代码

adding layout

Z F 7 年之前
父节点
当前提交
d4387097e0
共有 9 个文件被更改,包括 131 次插入117 次删除
  1. 81 71
      src/AddRemove/index.tsx
  2. 2 2
      src/index.tsx
  3. 32 32
      src/lib/dragact.tsx
  4. 1 1
      src/lib/gridItem.tsx
  5. 1 1
      src/lib/util/collison.ts
  6. 2 1
      src/lib/util/compact.ts
  7. 1 1
      src/lib/util/correction.ts
  8. 1 1
      src/lib/util/initiate.ts
  9. 10 7
      src/lib/util/sort.ts

+ 81 - 71
src/AddRemove/index.tsx

@@ -1,78 +1,88 @@
-// import *as React from 'react';
-// import { Dragact } from '../lib/dragact';
+import *as React from 'react';
+import { Dragact } from '../lib/dragact';
 
-// 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' }
-// ]
+const Words = [
+    { content: 'You can do anything, but not everything.' },
+    { content: 'Those who dare to fail miserably can achieve greatly.' },
+    { content: 'You miss 100 percent of the shots you never take.' },
+    { content: 'Those who believe in telekinetics, raise my hand.' },
+    { content: 'I’d rather live with a good question than a bad answer.' }
+]
 
 
-// const Card = (props: any) => {
-//     const item: any = props.item;
-//     const dataSet: any = props['data-set'];
-//     return (
-//         <div className='layout-Item' >
-//             <img src={item.img} style={{ width: '100%', height: '60%' }} draggable={false} alt='card'></img>
-//             <div style={{ padding: 5, textAlign: 'center', color: '#595959' }}>{dataSet.handle ? <div className='card-handle' id="dragact-handle">点我拖动</div> : item.content}</div>
-//         </div>
-//     )
-// }
+const Card = ({ item, provided }: any) => {
+    // console.log(provided);
+    return (
+        <div
+            className='layout-Item'
+            {...provided.props}
+            {...provided.dragHandle}
+        >
+            <div style={{ padding: 5, textAlign: 'center', color: '#595959' }}>{item.content}</div>
+        </div>
+    )
+}
 
+const fakeData = () => {
+    var Y = 0;
+    return Words.map((item, index) => {
+        if (index % 4 === 0) Y++;
 
-// export class AddRemove extends React.Component<{}, {}> {
-//     layoutWrap: HTMLDivElement | null
-//     dragactNode: Dragact;
-//     state = {
-//         layout: [1]
-//     }
+        return { ...item, GridX: index % 4 * 4, GridY: Y * 4, w: 4, h: 3, key: index }
+    })
+}
 
-//     componentDidMount() {
-//         this.setState({
-//             layout: this.dragactNode.getLayout()
-//         })
-//     }
-//     handleClick = () => {
-//         this.setState({
-//             layout: [...this.state.layout, 1]
-//         })
-//         console.log(this.state.layout)
-//     }
-//     handleDeleteClick = () => {
-//         this.state.layout.shift()
-//         this.setState({
-//             layout: [...this.state.layout]
-//         })
-//     }
+const makeOne = () => {
+    return { content: 'added', GridX: 0, GridY: 0, w: 4, h: 3, key: Date.now() }
+}
 
-//     render() {
-//         const margin: [number, number] = [5, 5];
-//         const dragactInit = {
-//             width: 800,
-//             col: 12,
-//             rowHeight: 800 / 12,
-//             margin: margin,
-//             className: 'normal-layout'
-//         }
-//         return (
-//             <div>
-//                 <div style={{ display: 'flex', justifyContent: 'center' }} >
-//                     <div>
-//                         <h1 style={{ textAlign: 'center' }}>AddRemove Demo</h1>
-//                         <Dragact {...dragactInit} ref={node => node ? this.dragactNode = node : null} >
-//                             {this.state.layout.map((el, i) => {
-//                                 return (
-//                                     <Card item={Words[0]} key={i} data-set={{ GridX: i * 3, GridY: 0, w: 3, h: 3 }} />
-//                                 )
-//                             })}
-//                         </Dragact>
-//                         <button onClick={this.handleClick}>新增</button>
-//                         <button onClick={this.handleDeleteClick}>删除</button>
-//                     </div>
-//                 </div>
-//             </div>
-//         )
-//     }
-// }
+
+export class AddRemove extends React.Component<{}, {}> {
+    state = {
+        layout: fakeData()
+    }
+
+    componentDidMount() {
+
+    }
+    handleClick = () => {
+        this.setState({
+            layout: [...this.state.layout, makeOne()]
+        })
+        console.log(this.state.layout)
+    }
+    handleDeleteClick = () => {
+        this.state.layout.shift()
+        this.setState({
+            layout: [...this.state.layout]
+        })
+    }
+
+    render() {
+        const margin: [number, number] = [5, 5];
+        const dragactInit = {
+            width: 800,
+            col: 12,
+            rowHeight: 800 / 12,
+            margin: margin,
+            className: 'normal-layout',
+            layout: this.state.layout
+        }
+        return (
+            <div>
+                <div style={{ display: 'flex', justifyContent: 'center' }} >
+                    <div>
+                        <h1 style={{ textAlign: 'center' }}>AddRemove Demo</h1>
+                        <Dragact {...dragactInit} >
+                            {(item, provided) => {
+                                return <Card item={item} provided={provided} />
+                            }}
+                        </Dragact>
+                        <button onClick={this.handleClick}>新增</button>
+                        <button onClick={this.handleDeleteClick}>删除</button>
+                    </div>
+                </div>
+            </div>
+        )
+    }
+}

+ 2 - 2
src/index.tsx

@@ -4,7 +4,7 @@ import { LayoutDemo } from './NormalLayout/index';
 import { SortedTableWithStatic } from "./StaticWidget/index";
 import { LayoutRestore } from "./LayoutRestore/index";
 import { HandleLayout } from "./HandleLayout/index";
-// import { AddRemove } from "./AddRemove/index";
+import { AddRemove } from "./AddRemove/index";
 import { Mobile } from "./mobileLayout/index";
 import './index.css'
 // import { Dragact } from "./lib/dragact";
@@ -114,7 +114,7 @@ class DemoDispatcher extends React.Component<{}, {}> {
 
 
 ReactDOM.render(
-    <DemoDispatcher />,
+    <AddRemove />,
     document.getElementById('root')
 );
 

+ 32 - 32
src/lib/dragact.tsx

@@ -155,7 +155,7 @@ export class Dragact extends React.Component<DragactProps, DragactState> {
 
     onResizing = (layoutItem: GridItemEvent) => {
 
-        const newLayout = layoutCheck(this.state.layout, layoutItem, layoutItem.UniqueKey, layoutItem.UniqueKey, 0);
+        const newLayout = layoutCheck(this.state.layout, layoutItem, layoutItem.UniqueKey + '', layoutItem.UniqueKey + '', 0);
 
         const { compacted, mapLayout } = compactLayout(newLayout, layoutItem, this.state.mapLayout)
 
@@ -203,9 +203,8 @@ export class Dragact extends React.Component<DragactProps, DragactState> {
         const { GridY, UniqueKey } = layoutItem;
         const moving = GridY - this.state.GridYMoving;
 
-        const newLayout = layoutCheck(this.state.layout, layoutItem, UniqueKey, UniqueKey/*用户移动方块的key */, moving);
+        const newLayout = layoutCheck(this.state.layout, layoutItem, UniqueKey + '', UniqueKey + ''/*用户移动方块的key */, moving);
         const { compacted, mapLayout } = compactLayout(newLayout, layoutItem, this.state.mapLayout);
-
         this.setState({
             GridXMoving: layoutItem.GridX,
             GridYMoving: layoutItem.GridY,
@@ -259,46 +258,47 @@ export class Dragact extends React.Component<DragactProps, DragactState> {
     }
 
     componentWillReceiveProps(nextProps: any) {
-        if (this.props.children.length > nextProps.children.length) { //remove
-            const mapLayoutCopy = { ...this.state.mapLayout };
-            nextProps.children.forEach((child: any) => {
-                if ((mapLayoutCopy as any)[child.key] !== void 666) delete (mapLayoutCopy as any)[child.key];
-            })
-            for (const key in mapLayoutCopy) {
-                const newLayout = this.state.layout.filter((child) => {
-                    if (child.key !== key) return child
-                })
-                const { compacted, mapLayout } = compactLayout(newLayout, undefined, this.state.mapLayout);
-                this.setState({
-                    containerHeight: getMaxContainerHeight(compacted, this.props.rowHeight, this.props.margin[1], this.state.containerHeight),
-                    layout: compacted,
-                    mapLayout
-                })
-            }
-        }
-
-        if (this.props.children.length < nextProps.children.length) { //add
+        // if (this.props.children.length > nextProps.children.length) { //remove
+        //     const mapLayoutCopy = { ...this.state.mapLayout };
+        //     nextProps.children.forEach((child: any) => {
+        //         if ((mapLayoutCopy as any)[child.key] !== void 666) delete (mapLayoutCopy as any)[child.key];
+        //     })
+        //     for (const key in mapLayoutCopy) {
+        //         const newLayout = this.state.layout.filter((child) => {
+        //             if (child.key !== key) return child
+        //         })
+        //         const { compacted, mapLayout } = compactLayout(newLayout, undefined, this.state.mapLayout);
+        //         this.setState({
+        //             containerHeight: getMaxContainerHeight(compacted, this.props.rowHeight, this.props.margin[1], this.state.containerHeight),
+        //             layout: compacted,
+        //             mapLayout
+        //         })
+        //     }
+        // }
+        if (this.props.layout.length < nextProps.layout.length) {//add
             var item;
-            for (const idx in nextProps.children) {
-                const i = nextProps.children[idx];
-                if (this.state.mapLayout && !this.state.mapLayout[i.key]) {
+            for (const idx in nextProps.layout) {
+                const i = nextProps.layout[idx];
+                if (this.state.mapLayout && !this.state.mapLayout[i.key + '']) {
                     item = i;
                     break;
                 }
             }
             if (item !== void 666) {
-                const dataSet = { ...item.props['data-set'], isUserMove: false, key: item.key };
+                const dataSet = { ...item, isUserMove: false, key: item.key + '' };
                 var newLayout = [...this.state.layout, dataSet]
-                newLayout = correctLayout(newLayout, this.props.col)
                 const { compacted, mapLayout } = compactLayout(newLayout, undefined, this.state.mapLayout);
                 this.setState({
-                    containerHeight: getMaxContainerHeight(compacted, this.props.rowHeight, this.props.margin[1], this.state.containerHeight),
+                    containerHeight: getMaxContainerHeight(compacted,
+                        this.props.rowHeight,
+                        this.props.margin[1],
+                        this.state.containerHeight,
+                        false),
                     layout: compacted,
                     mapLayout
                 })
             }
         }
-
     }
 
     componentDidMount() {
@@ -308,7 +308,7 @@ export class Dragact extends React.Component<DragactProps, DragactState> {
             this.setState({
                 layout: compacted,
                 mapLayout: mapLayout,
-                containerHeight: getMaxContainerHeight(compacted, this.props.rowHeight, this.props.margin[1], this.state.containerHeight)
+                containerHeight: getMaxContainerHeight(compacted, this.props.rowHeight, this.props.margin[1], this.state.containerHeight, false)
             })
         }, 1);
     }
@@ -317,7 +317,7 @@ export class Dragact extends React.Component<DragactProps, DragactState> {
         const { dragType, mapLayout } = this.state;
         var { col, width, padding, rowHeight, margin } = this.props;
         if (mapLayout) {
-            const renderItem = layoutItemForkey(mapLayout, child.key);
+            const renderItem = layoutItemForkey(mapLayout, child.key + '');
             if (!padding) padding = 0;
             return (
                 <GridItem
@@ -331,7 +331,7 @@ export class Dragact extends React.Component<DragactProps, DragactState> {
                     onDragStart={this.onDragStart}
                     onDragEnd={this.onDragEnd}
                     isUserMove={renderItem.isUserMove !== void 666 ? renderItem.isUserMove : false}
-                    UniqueKey={child.key}
+                    UniqueKey={child.key + ''}
                     onResizing={this.onResizing}
                     onResizeStart={this.onResizeStart}
                     onResizeEnd={this.onResizeEnd}

+ 1 - 1
src/lib/gridItem.tsx

@@ -31,7 +31,7 @@ export interface GridItemProps {
 
     isUserMove: Boolean
 
-    UniqueKey?: string | number
+    UniqueKey?: string 
 
     static?: Boolean
 

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

@@ -34,7 +34,7 @@ export const layoutCheck = function () {
     var caches: any = {};
 
     const _layoutCheck = function (layout: DragactLayoutItem[], layoutItem: GridItemEvent,
-        key: string | number, fristItemkey: string | number, moving: number) {
+        key: string, fristItemkey: string, moving: number) {
 
 
         if (layoutItem.GridX === caches.GridX

+ 2 - 1
src/lib/util/compact.ts

@@ -10,7 +10,7 @@ import { GridItemEvent } from "../GridItem";
  */
 export const compactItem = (finishedLayout: DragactLayoutItem[], item: DragactLayoutItem) => {
     if (item.static) return item;
-    const newItem = { ...item }
+    const newItem = { ...item, key: item.key + '' }
     if (finishedLayout.length === 0) {
         return { ...newItem, GridY: 0 }
     }
@@ -59,6 +59,7 @@ export const compactLayout = function () {
         const compareList = []
         const mapLayout: mapLayout = {};
 
+
         for (let i = 0, length = sorted.length; i < length; i++) {
             let finished = compactItem(compareList, sorted[i])
             if (movingItem) {

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

@@ -28,7 +28,7 @@ export const correctLayout = (layout: DragactLayoutItem[], col: number) => {
         correctItem(copy[i + 1], col);
 
         if (collision(copy[i], copy[i + 1])) {
-            copy = layoutCheck(copy, <GridItemEvent>copy[i], (<GridItemEvent>copy[i]).UniqueKey, (<GridItemEvent>copy[i]).UniqueKey, 0)
+            copy = layoutCheck(copy, <GridItemEvent>copy[i], (<GridItemEvent>copy[i]).UniqueKey + '', (<GridItemEvent>copy[i]).UniqueKey + '', 0)
         }
     }
 

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

@@ -48,7 +48,7 @@ export const MapLayoutTostate = (layout: DragactLayoutItem[], children: any[]) =
  * @param {*} layout 输入进来的布局
  * @param {*} key 
  */
-export const layoutItemForkey = (layout: mapLayout, key: number) => {
+export const layoutItemForkey = (layout: mapLayout, key: string) => {
     return layout[key]
 }
 

+ 10 - 7
src/lib/util/sort.ts

@@ -22,19 +22,22 @@ export const sortLayout = (layout: any) => {
  * 这个函数带有记忆功能
  */
 export const getMaxContainerHeight = function () {
-    var lastOneGridY = 0;
-    return function (layout: DragactLayoutItem[], elementHeight = 30, elementMarginBottom = 10, currentHeight: number) {
-        const length = layout.length;
-        const currentLastOne = layout[length - 1];
-        if (currentLastOne.GridY === lastOneGridY) {
-            return currentHeight
+    var lastOneYNH = 0;
+    return function (layout: DragactLayoutItem[], elementHeight = 30, elementMarginBottom = 10, currentHeight: number, useCache?: Boolean) {
+        if (useCache !== false) {
+            const length = layout.length;
+            const currentLastOne = layout[length - 1];
+            if (currentLastOne.GridY + currentLastOne.h === lastOneYNH) {
+                return currentHeight
+            }
+            lastOneYNH = currentLastOne.GridY + currentLastOne.h;
         }
-        lastOneGridY = currentLastOne.GridY;
         const ar = layout.map((item) => {
             return item.GridY + item.h
         })
         const h = quickSort(ar)[ar.length - 1];
         const height = h * (elementHeight + elementMarginBottom) + elementMarginBottom
+
         return height
     }
 }();