Git Product home page Git Product logo

column-resizer's Introduction

ColumnResizer

ColumnResizer is a fork of the jQuery plugin colResizable. The plugin is rewritten as vanilla ES6 javascript.

Features

  • Supports mouse and touch events
  • Persistent layout on refresh
  • No external resources
  • Lightweight and small footprint
  • Customizable column anchors
  • Server side rendering

Usage

Column-resizer can be used directly as a script in a page:

<head>
  <script src="js/column-resizer.js"></script>
  <script type="text/javascript">
     window.onload = function() {
        let resizable = ColumnResizer.default;
        
          new resizable(document.querySelector("#somethingUnique"),{
              liveDrag:true,
              draggingClass:"rangeDrag",
              gripInnerHtml:"<div class='rangeGrip'></div>",
              minWidth:8
          });
     };
  </script>
</head>
<body>	 
  <table id="somethingUnique" width="100%" >
    <tr> <th> header </th> <th> header </th> </tr>
    <tr> <td> cell </td> <td> cell </td> </tr>							
    <tr> <td> cell </td> <td> cell </td> </tr>							
  </table>	
</body>

It can also be used as an ES6 module as in this React example:

import ColumnResizer from 'column-resizer';
import React, { Component } from 'react';

class MyTable extends Component {
    
    /**  Other implementation ignored ... **/
    
    componentDidMount() {
        if (this.props.resizable) {
            this.enableResize();
        }
    }

    componentWillUnmount() {
        if (this.props.resizable) {
            this.disableResize();
        }
    }

    componentDidUpdate() {
        if (this.props.resizable) {
            this.enableResize();
        }
    }

    componentWillUpdate() {
        if (this.props.resizable) {
            this.disableResize();
        }
    }

    /*
     * In this example, one table controls the resizing of the
     * another table so both tables' columns resize synchronously.
     */
    enableResize() {
        const remoteTable = ReactDOM.findDOMNode(this)
            .querySelector(`#${this.remoteTableId}`);
        const options = this.props.resizerOptions;
        options.remoteTable = remoteTable;
        if (!this.resizer) {
            this.resizer = new ColumnResizer(
                ReactDOM.findDOMNode(this)
                    .querySelector(`#${this.tableId}`), options);
        } else {
            this.resizer.reset(options);
        }
    }

    disableResize() {
        if (this.resizer) {
            /* This will return the current options object.
             *
             * The options, which include the column widths,
             * can be used to re-create the table with the 
             * same column widths as last used.
             */
            this.resizer.reset({ disable: true });
        }
    }
}

Options

  • resizeMode: [type: string] [default: 'fit'] [values: 'fit', 'flex', 'overflow']

    It is used to set how the resize method works. Those are the possible values:

    • 'fit': this is default resizing model, in which resizing a column does not alter table width, which means that when a column is expanded the next one shrinks.
    • 'flex': table can change its width and each column can shrink or expand independently if there is enough space in the parent container. If there is not enough space, columns will share its width as they are resized. Table will never get bigger than its parent.
    • 'overflow': allows resize of columns with overflow of parent container.

  • disable: [type: boolean] [default: false]

When set to true it aims to remove all previously added enhancements such as events and additional DOM elements assigned by this plugin to a single or collection of tables. It is required to disable a previously resized table prior its removal from the document object tree using JavaScript, and also before any DOM manipulations to an already resized table such as adding columns, rows, etc.


  • disabledColumns: [type: array of int] [default: []]

An array of column indexes to be excluded, so it will not be possible to drag them manually.


  • liveDrag: [type: boolean] [default: false]

When set to true the table layout is updated while dragging column anchors. liveDrag enabled is more CPU consuming so it is not recommended for slow computers, specially when dealing with huge or extremely complicated tables.


  • partialRefresh: [type: boolean] [default: false]

This attribute should be set to true if the table is inside of an updatePanel or any other kind of partial page refresh using ajax. Table's ID should be same before and after the partial partial refresh.


  • innerGripHtml: [type: string] [default: empty string]

Its purpose is to allow column anchor customization by defining the HTML to be used in the column grips to provide some visual feedback. It can be used in a wide range of ways to obtain very different outputs, and its flexibility can be increased by combining it with the draggingClass attribute.


  • draggingClass: [type: string] [default: internal css class]

This attribute is used as the css class assigned to column anchors while being dragged. It can be used for visual feedback purposes.


  • minWidth: [type: number] [default: 15]

This value specifies the minimum width (measured in pixels) that is allowed for the columns.


  • headerOnly: [type: boolean] [default: false]

This attribute can be used to prevent vertical expansion of the column anchors to fit the table height. If it is set to true, column handler's size will be bounded to the first row's vertical size.


  • hoverCursor: [type: string] [default: "e-resize"]

This attribute can be used to customize the cursor that will be displayed when the user is positioned on the column anchors.


  • dragCursor: [type: string] [default: "e-resize"]

Defines the cursor that will be used while the user is resizing a column.


  • flush: [type: boolean] [default: false]

Flush is to remove all previously stored data related to the current table layout from session storage.


  • marginLeft: [type: string / null] [default: null]

If the target table contains an explicit margin-left CSS rule, the same value must be used in this attribute (for example: "auto", "20%", "10px"). The reason why it is needed it is because most browsers (all except of legacy IE) don’t allow direct access to the current CSS rule applied to an element in its original units (such as "%", "em" or "auto" values).


  • marginRight: [type: string / null] [default: null]

It behaves in exactly the same way than the previous attribute but applied to the right margin.


  • remoteTable: [type: Node / null] [default: null]

Table element whose column widths will be set by the current table. Remote table must have the same number of columns.


  • widths: [type: array of int] [default: []]

An array of column widths to set the initial width.


  • serialize: [type:Boolean] [default: true]

Flag to determine if column width data will be saved to session storage.


Events

  • onResize: [type: function] [default: null]

If a callback function is supplied it will be fired when the user has ended dragging a column anchor altering the previous table layout. The callback function can obtain a reference to the updated table through the currentTarget attribute of the event retrieved by parameters


  • onDrag: [type: function] [default: null]

This event is fired while dragging a column anchor if liveDrag is enabled. It can be useful if the table is being used as a multiple range slider. The callback function can obtain a reference to the updated table through the currentTarget attribute of the event retrieved by parameters

column-resizer's People

Contributors

dependabot[bot] avatar jglynn43 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

column-resizer's Issues

Add an option to reset columns to their initial widths

Is your feature request related to a problem? Please describe.
Hi, I use your package and would like to understand how to reset the columns to their initial size (which means, erase the localStorage property and init table columns)

Describe the solution you'd like
I would expect that this.resizer.reset() will change the columns to their original widths.

Describe alternatives you've considered
The way I tried to do it is by calling this.resizer.reset() but that didn't work,
So what I'm doing now and is kind of horrible, is to save the initial widths in my react state, and when a user clicks a button, I call reset() with these widths. It causes problems in case the window size was changed etc.

Thank you

Incorrect loading of column widths from session storage for two tables

Describe the bug
Incorrect loading of column widths from session storage, if there are two tables on the page: values for second table are equal to values for first table.
(In session storage values is valid).

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://jsfiddle.net/s0nLca7x/4/
  2. Set different widths for two tables
  3. Rerun script (for load values from session storage)
  4. See incorrect values for second table

Expected behavior
Correct loading column widths from session storage for each table.

td Drag for Vertical table

Need to add support for td Vertical table.
Need to increase the height of the td if we have Vertical table.

HTML

<table width="100%" border="1" height="100%" id="somethingUnique">
  <tr>
    <th>This th should be dragable by height </th>
    <td>Bill Gates</td>
    <td>Bill Gates</td>
  </tr>
  <tr>
    <th>This th should be dragable by height</th>
    <td>555 77 854</td>
    <td>555 77 854</td>
  </tr>
  <tr>
    <th>This th should be dragable by height</th>
    <td>555 77 855</td>
    <td>555 77 855</td>
  </tr>
</table>
This th should be dragable by height Bill Gates Bill Gates
This th should be dragable by height 555 77 854 555 77 854
This th should be dragable by height 555 77 855 555 77 855

Should last column grip show on hover when resizeMode is "fit" ?

Describe the bug
This is more of a question. If one uses resizeMode: fit, should the last column grip in the table show? It seems that if full width is the size of the table, then the user should not be able to grab the right side of the last columns (far right). Maybe I'm missing the use case. I understand that in an resizeMode: overflow context that grip should be present.

Expected behavior
Grip would not show on hover

Screenshots
Screen Shot 2021-08-17 at 4 48 28 PM

ResizeMode 'overflow' table width issue

I have exactly the same issue described here
When resizeMode is of type fit the table width is right
qNIgkhl

While when resizeMode is of type flex or overflow this is the result (note the white space on the right of the table).
ED4JGzul9j

When you resize (small column resize) the table takes up the white space.

I have tried with and without widths and flush.

new ColumnResizer(targetEl, {
  liveDrag: true,
  resizeMode: 'overflow', // or 'flex'
  widths: [int, int, int], // with or without this param
  flush: true // with or without this param
});

Thanks

ResizeMode 'overflow' and width property issue

There seems to be an issue when setting the widths property and using the resizeMode overflow.

When both are set you would expect the width of each cell to math the exact value specified in the widths property. However this is not the case. The width is set on the cell with the correct value initially, but the actual with differs.

This is how I initialise the library:

new colResizable(normal, {
  liveDrag: true,
  gripInnerHtml: "<div class='grip'></div>",
  draggingClass: "dragging",
  resizeMode: 'overflow',
  widths: [275, 350, 500]
});

PS when you reload/resize (small resize) the browser it sets the proper values in the DOM.

thanks!

looking for a way to use same columns widths on many tables sharing same kind of data

Is your feature request related to a problem? Please describe.
I am working on an rails app that shows versioning history of a Model, so I am dealing with many many Model instances. Right now I can present each Model instance versioning history in a table with ColumnResizer that allows to resize columns, for each instance table is presented in a initial state (of columns) and ColumnResizer keeps state of column widths in a separate object in session storage (grip-resizable0, grip-resizable3 etc.).

Describe the solution you'd like
Is there a way to tell ColumnResizer to use same grip-resizable object from session storage for every table, eg. by using a CSS class on each table and/or initialising ColumnResizer in a special way?

Best rgds, Adam

Row resizing

Hi,
it would be awesome if you add to your packager ability to not only resize columns but also resize rows! <3

ES5 Version

Hello,

i was trying to use this in an angular 9 project, but i can't make it work in IE11 since this is written in ES6 and IE11 don't support the arrow functions.

Can this could be written in ES5?

IE11 compatibility. Element.matches()

Describe the bug

Column resize init throws an exception on IE11 without matches() polyfill.

SCRIPT438: Object doesn't support property or method 'matches'

Desktop (please complete the following information):

  • OS: Windows 7/8/10
  • Browser: Internet Explorer
  • Version: 11

This issue would be easily fixed by adding this 3 line polyfill:

if (!Element.prototype.matches) {
    Element.prototype.matches = Element.prototype.msMatchesSelector;
}

Is this fix considered to be in the scope of the project or is it left to the dev to load/include the polyfill?

Thanks

Hooks support needed.

Can you add support for hooks for the column resizer functionality.Also example would be good..

need help getting columns width information

import React, { Component } from 'react';
import ReactDOM from "react-dom";
import PropTypes from 'prop-types';
import ColumnResizer from "./column.resize";
import styles from '../css/datasheet.css';
import HeaderRenderer from './headerrenderer';

class DataSheetMainRenderer extends Component {
constructor(props) {
super(props);
this.state = {};
}

componentDidMount() {
const resizer = new ColumnResizer(document.getElementById("mytable"), {
liveDrag: true,
resizeMode: 'overflow',
minWidth: 150,
headerOnly: true,
flush: true,
disabledColumns: [0, this.props.viewForm ? 1 : null]
});
if (this.props.resizable) {
this.enableResize();
}
}
componentWillUpdate() {
console.log('resizersdsdsds');
if (this.props.resizable) {
this.disableResize();
}
}
componentDidUpdate() {
console.log('resizersdsdsd2112s');
if (this.props.resizable) {
this.enableResize();
}
}
componentWillUnmount() {
if (this.props.resizable) {
this.disableResize();
}
}

enableResize() {
const normalRemote = ReactDOM.findDOMNode(this).querySelector(
#${this.bodyId}
);
const options = this.props.resizerOptions;
options.remoteTable = normalRemote;
if (!this.resizer) {
this.resizer = new ColumnResizer(
ReactDOM.findDOMNode(this).querySelector(#${this.headerId}),
options
);
console.log('this.resizer', this.resizer);
} else {
this.resizer.reset(options);
console.log('this.resizer', this.resizer);
}
}

disableResize() {
if (this.resizer) {
console.log('this.resizer', this.resizer);
// This will return the current state of the
// options including column widths.
// These widths can be saved so the table
// can be initialized with them.
this.resizer.reset({ disable: true });
}
}

render() {
const { className, columns, viewForm, checkboxIndex } = this.props;
return(


{/*
<col width= {'40px'}/>
{viewForm && <col width= {'40px'}/>}
{
columns.map((col, index) => (
<col key={col.Id} width= {(col.Width || 150) + 'px'}/>
))
}
*/}
<thead className={${styles.dataHeader}}>
<HeaderRenderer {...this.props}/>

<tbody className={${styles.dataBody}}>
{this.props.children}


);
}
}

DataSheetMainRenderer.propTypes = {
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.array
]),
className: PropTypes.PropTypes.string,
selected: PropTypes.array,
onSelectAllChanged: PropTypes.func,
columns: PropTypes.array.isRequired,
selections: PropTypes.array,
onColumnDrop: PropTypes.func,
sort: PropTypes.array,
checkboxIndex: PropTypes.bool,
viewForm: PropTypes.bool,
handleSort: PropTypes.func,
rowsCount: PropTypes.number,
resizable: PropTypes.bool,
resizerOptions: PropTypes.object
};

export default DataSheetMainRenderer;
Where i will recive width information

What is HeaderID?

In the readme, it mentions we should use headerId, but we never specify that anywhere. Which tag do we give the headerId attribute to?

Erorr while using webpack

Hi,
I am using webpack, when I try to compile this file:

import ColumnResizer from "column-resizer/src/ColumnResizer";

let resizable = ColumnResizer.default;

new resizable(document.querySelector("#AdsTable"),{
    liveDrag:true,
    draggingClass:"rangeDrag",
    gripInnerHtml:"<div class='rangeGrip'></div>",
    minWidth:8
});

I am getting error:

ERROR in ./node_modules/column-resizer/src/ColumnResizer.js 14:7
Module parse failed: Unexpected token (14:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
| export default class ColumnResizer {
>     ID = 'id';
|     PX = 'px';
|     RESIZABLE = 'grip-resizable';
 @ ./index.js 5:0-61 11:16-37

webpack 5.10.0 compiled with 1 error in 4207 ms

My webpack conf looks like:

const webpack = require('webpack');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const publicDir = path.normalize(`${__dirname}/../public`);

module.exports = {
    entry: "./index.js",
    output:{
        filename: "main.js",
        path: path.resolve(publicDir, "utils"),
        publicPath: ''
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader', ],
            },
            {
                test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'file-loader'
            }
        ]
    },
    plugins: [new MiniCssExtractPlugin()],
};

Not SSR compatible

Describe the bug
This is not SSR compatible.

To Reproduce
Steps to reproduce the behavior:

  1. Load module in gatsby and watch the gatsby build fail

Expected behavior
It should be SSR compatible

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: macOS Mojave
  • Browser: N/A
  • Version N/A

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
A typical error can be seen here:

  2 | //# sourceMappingURL=column-resizer.js.map


  WebpackError: ReferenceError: window is not defined
  
  - column-resizer.js:1 
    [lib]/[column-resizer]/dist/column-resizer.js:1:208
  
  
  
  
  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1

Add typescript definitions

Right now we have to use it like this:

const ColumnResizer = require('column-resizer');
const resizer = new ColumnResizer.default(document.getElementById('mytable'), {});

Which isn't ideal. It would be great if there were TS definitions so we could import it like normal. Thanks!

Overflowing table header is not hidden

The overflowing table header is not hidden

To Reproduce
Initialize a table and resize the header smaller then the header text
Options:
liveDrag: true,
gripInnerHtml: '<div class="rangeGrip"></div>',
minWidth: 25,
headerOnly: true,
serialize: true,
resizeMode: 'fit'

Expected behavior
Oveflowing header text should be hidden

Screenshots
screenshot-localhost_8080-2019 11 30-22_38_30

Desktop (please complete the following information):

  • OS: MacOS
  • Chrome
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • 78.0.3904.108 (Official Build) (64-bit)

Additional context
In the init method should be changed the style part from
.grip-resizable > tbody > tr > th{overflow:hidden}
to
.grip-resizable > thead > tr > th{overflow:hidden}

onResize target issues

The documentation says:

If a callback function is supplied it will be fired when the user has ended dragging a column anchor
altering the previous table layout. The callback function can obtain a reference to the updated table
through the currentTarget attribute of the event retrieved by parameters

The currentTarget however points to the HTML document. The target is the grip itself.

What I'm looking for is a way to track what widths were used for the columns so I can store it, so that when the table is shown again it's shown with the same widths.

Centering the table

How to center the table?
If I do this:
My html table looks like:

<div class="table-responsive">
  <table id="AdsTable" class="table" style="width: 100%">
    ...
  </table>
</div>

I use class table-responsive from bootstrap
My js looks like:

import ColumnResizer from "column-resizer";

let resizable = ColumnResizer;
new resizable(document.querySelector("#AdsTable"),{
    resizeMode: 'overflow',
    liveDrag:true,
    draggingClass:"rangeDrag",
    gripInnerHtml:"<div class='rangeGerip'></div>",
    minWidth:8
});

Css:

table {
margin: auto;
}

I get this(the cursor to resize the column is outside of the table
image

How to center the table and do not lose the ability to resize the columns?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.