split 0.0.2

  • README.md
  • Installing
  • Versions
  • 69

Split.js

Build Status File Size npm version Dependencies Backers on Open Collective Sponsors on Open Collective

Split.js #

2kb unopinionated utility for resizeable split views.

  • Zero Deps
  • Tiny: Weights 2kb gzipped.
  • Fast: No overhead or attached window event listeners, uses pure CSS for resizing.
  • Unopinionated: Plays nicely with float, flex and other layouts.
  • Compatible: Works great in IE9, and even loads in IE8 with polyfills. Early Firefox/Chrome/Safari/Opera supported too.

Table of Contents #

Installation #

Yarn:

$ yarn add split.js

npm:

$ npm install --save split.js

Include with a module bundler like rollup or webpack:

// using ES6 modules
import Split from 'split.js'

// using CommonJS modules
var Split = require('split.js')

The UMD build is also available on unpkg:

<script src="https://unpkg.com/split.js/dist/split.min.js"></script>

or cdnjs:

<script src="https://cdnjs.cloudflare.com/ajax/libs/split.js/1.5.9/split.min.js"></script>

You can find the library on window.Split.

Documentation #

var split = Split(<HTMLElement|selector[]> elements, <options> options?)
OptionsTypeDefaultDescription
sizesArrayInitial sizes of each element in percents or CSS values.
minSizeNumber or Array100Minimum size of each element.
expandToMinBooleanfalseGrow initial sizes to minSize
gutterSizeNumber10Gutter size in pixels.
gutterAlignString'center'Gutter alignment between elements.
snapOffsetNumber30Snap to minimum size offset in pixels.
dragIntervalNumber1Number of pixels to drag.
directionString'horizontal'Direction to split: horizontal or vertical.
cursorString'col-resize'Cursor to display while dragging.
gutterFunctionCalled to create each gutter element
elementStyleFunctionCalled to set the style of each element.
gutterStyleFunctionCalled to set the style of the gutter.
onDragFunctionCallback on drag.
onDragStartFunctionCallback on drag start.
onDragEndFunctionCallback on drag end.

Important Note #

Split.js does not set CSS beyond the minimum needed to manage the width or height of the elements. This is by design. It makes Split.js flexible and useful in many different situations. If you create a horizontal split, you are responsible for (likely) floating the elements and the gutter, and setting their heights. See the CSS section below. If your gutters are not showing up, check the applied CSS styles.

THIS IS THE #1 QUESTION ABOUT THE LIBRARY.

Options #

sizes #

An array of initial sizes of the elements, specified as percentage values. Example: Setting the initial sizes to 25% and 75%.

Split(['#one', '#two'], {
    sizes: [25, 75],
})

minSize. Default: 100

An array of minimum sizes of the elements, specified as pixel values. Example: Setting the minimum sizes to 100px and 300px, respectively.

Split(['#one', '#two'], {
    minSize: [100, 300],
})

If a number is passed instead of an array, all elements are set to the same minimum size:

Split(['#one', '#two'], {
    minSize: 100,
})

expandToMin. Default: false

When the split is created, if expandToMin is true, the minSize for each element overrides the percentage value from the sizes option. Example: The first element (#one) is set to 25% width of the parent container. However, it's minSize is 300px. Using expandToMin: true means that the first element will always load at at least 300px, even if 25% were smaller.

Split(['#one', '#two'], {
    sizes: [25, 75],
    minSize: [300, 100],
    expanedToMin: true,
})

gutterSize. Default: 10

Gutter size in pixels. Example: Setting the gutter size to 20px.

Split(['#one', '#two'], {
    gutterSize: 20,
})

gutterAlign. Default: 'center'

Possible options are 'start', 'end' and 'center'. Determines how the gutter aligns between the two elements. 'start' shrinks the first element to fit the gutter, 'end' shrinks the second element to fit the gutter and 'center' shrinks both elements by the same amount so the gutter sits between. Added in v1.5.3.

Example: move gutter to the side of the second element:

Split(['#one', '#two'], {
    gutterAlign: 'end',
})

snapOffset. Default: 30

Snap to minimum size at this offset in pixels. Example: Set to 0 to disable to snap effect.

Split(['#one', '#two'], {
    snapOffset: 0,
})

dragInterval. Default: 1

Drag this number of pixels at a time. Defaults to 1 for smooth dragging, but can be set to a pixel value to give more control over the resulting sizes. Works particularly well when the gutterSize is set to the same size. Added in v1.5.3. Example: Drag 20px at a time:

Split(['#one', '#two'], {
    dragInterval: 20,
})

direction. Default: 'horizontal'

Direction to split in. Can be 'vertical' or 'horizontal'. Determines which CSS properties are applied (ie. width/height) to each element and gutter. Example: split vertically:

Split(['#one', '#two'], {
    direction: 'vertical',
})

cursor. Default: 'col-resize'

Cursor to show on the gutter (also applied to the body on dragging to prevent flickering). Defaults to 'col-resize'for direction: 'horizontal' and 'row-resize' for direction: 'vertical':

Split(['#one', '#two'], {
    direction: 'vertical',
    cursor: 'row-resize',
})

gutter #

Optional function called to create each gutter element. The signature looks like this:

;(index, direction, pairElement) => HTMLElement

Defaults to creating a div with class="gutter gutter-horizontal" or class="gutter gutter-vertical", depending on the direction. The default gutter function looks like this:

;(index, direction) => {
    const gutter = document.createElement('div')
    gutter.className = `gutter gutter-${direction}`
    return gutter
}

The returned element is then inserted into the DOM, and it's width or height are set. This option can be used to clone an existing DOM element, or to create a new element with custom styles.

Returning a falsey value like null or false will not insert a gutter. This behavior was added in v1.4.1. An additional argument, pairElement, is passed to the gutter function: this is the DOM element after (to the right or below) the gutter. This argument was added in v1.4.1.

This final argument makes it easy to return the gutter that has already been created, for example, if split.destroy() was called with the option to preserve the gutters.

;(index, direction, pairElement) => pairElement.previousSibling

elementStyle #

Optional function called setting the CSS style of the elements. The signature looks like this:

;(dimension, elementSize, gutterSize, index) => Object

Dimension will be a string, 'width' or 'height', and can be used in the return style. elementSize is the target percentage value of the element, and gutterSize is the target pixel value of the gutter.

It should return an object with CSS properties to apply to the element. For horizontal splits, the return object looks like this:

{
    'width': 'calc(50% - 5px)'
}

A vertical split style would look like this:

{
    'height': 'calc(50% - 5px)'
}

You might use this function if you're using a different layout like flex (see Flex Layout). Flex styles for a horizontal split could return an object like this:

{
    'flex-basis': 'calc(50% - 5px)'
}

gutterStyle #

Optional function called when setting the CSS style of the gutters. The signature looks like this:

;(dimension, gutterSize, index) => Object

Dimension is a string, either 'width' or 'height', and gutterSize is a pixel value representing the width of the gutter.

It should return a similar object as elementStyle, an object with CSS properties to apply to the gutter. Since gutters have fixed widths, it will generally look like this:

{
    'width': '10px'
}

Both elementStyle and gutterStyle are called continously while dragging, so don't do anything besides return the style object in these functions. Both of these functions should be pure, returning the same values for the same inputs and not modifying any external state.

onDrag, onDragStart, onDragEnd #

Callbacks that can be added on drag (fired continously), drag start and drag end. If doing more than basic operations in onDrag, add a debounce function to rate limit the callback.

onDragStart and onDragEnd are passed the initial and final sizes of the split since it's a common pattern to access the sizes this way.

Their function signature looks like this, where sizes is an array of percentage values like returned by getSizes():

sizes => {}

Usage Examples #

Reference HTML for examples. Gutters are inserted automatically:

<div>
    <div id="one">content one</div>
    <div id="two">content two</div>
    <div id="three">content three</div>
</div>

A split with two elements, starting at 25% and 75% wide, with 200px minimum width.

Split(['#one', '#two'], {
    sizes: [25, 75],
    minSize: 200,
})

A split with three elements, starting with even (default) widths and minimum widths set to 100px, 100px and 300px, respectively.

Split(['#one', '#two', '#three'], {
    minSize: [100, 100, 300],
})

A vertical split with two elements.

Split(['#one', '#two'], {
    direction: 'vertical',
})

Saving State #

Use local storage to save the most recent state:

var sizes = localStorage.getItem('split-sizes')

if (sizes) {
    sizes = JSON.parse(sizes)
} else {
    sizes = [50, 50] // default sizes
}

var split = Split(['#one', '#two'], {
    sizes: sizes,
    onDragEnd: function(sizes) {
        localStorage.setItem('split-sizes', JSON.stringify(sizes))
    },
})

Flex Layout #

Flex layout is supported easily by adding a display: flex to the parent element. The width or height CSS values assigned by default by Split.js work well with flex.

<div id="flex">
    <div id="flex-1"></div>
    <div id="flex-2"></div>
</div>

And CSS style like this:

#flex {
    display: flex;
    flex-direction: row;
}

For more complicated flex layouts, the elementStyle and gutterStyle can be used to set flex-basis:

Split(['#flex-1', '#flex-2'], {
    elementStyle: function(dimension, size, gutterSize) {
        return {
            'flex-basis': 'calc(' + size + '% - ' + gutterSize + 'px)',
        }
    },
    gutterStyle: function(dimension, gutterSize) {
        return {
            'flex-basis': gutterSize + 'px',
        }
    },
})

API #

Split.js returns an instance with a couple of functions. The instance is returned on creation:

var instance = Split([], ...)

.setSizes([]) #

setSizes behaves the same as the sizes configuration option, passing an array of percentages. It updates the sizes of the elements in the split. Added in v1.1.0:

instance.setSizes([25, 75])

.getSizes() #

getSizes returns an array of percents, suitable for using with setSizes or creation. Not supported in IE8. Added in v1.1.2:

instance.getSizes() > [25, 75]

.collapse(index) #

collapse changes the size of element at index to it's minSize. Every element except the last is collapsed towards the front (left or top). The last is collapsed towards the back. Not supported in IE8. Added in v1.1.0:

instance.collapse(0)

.destroy(preserveStyles? = false, preserveGutters? = false) #

Destroy the instance. It removes the gutter elements, and the size CSS styles Split.js set. Added in v1.1.1. Passing preserveStyles = true does not remove the CSS styles. Option added in v1.4.0. Passing preserveGutters = true does not remove the gutter elements. Option added in v1.4.1.

instance.destroy()

CSS #

In being non-opionionated, the only CSS Split.js sets is the widths or heights of the elements. Everything else is left up to you. You must set the elements and gutter heights when using horizontal mode. The gutters will not be visible if their height is 0px. Here's some basic CSS to style the gutters with, although it's not required. Both grip images are included in this repo:

.gutter {
    background-color: #eee;

    background-repeat: no-repeat;
    background-position: 50%;
}

.gutter.gutter-horizontal {
    background-image: url('grips/vertical.png');
    cursor: col-resize;
}

.gutter.gutter-vertical {
    background-image: url('grips/horizontal.png');
    cursor: row-resize;
}

The grip images are small files and can be included with base64 instead:

.gutter.gutter-vertical {
    background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAFAQMAAABo7865AAAABlBMVEVHcEzMzMzyAv2sAAAAAXRSTlMAQObYZgAAABBJREFUeF5jOAMEEAIEEFwAn3kMwcB6I2AAAAAASUVORK5CYII=');
}

.gutter.gutter-horizontal {
    background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAIklEQVQoU2M4c+bMfxAGAgYYmwGrIIiDjrELjpo5aiZeMwF+yNnOs5KSvgAAAABJRU5ErkJggg==');
}

Split.js also works best when the elements are sized using border-box. The split class would have to be added manually to apply these styles:

.split {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

And for horizontal splits, make sure the layout allows elements (including gutters) to be displayed side-by-side. Floating the elements is one option:

.split,
.gutter.gutter-horizontal {
    float: left;
}

If you use floats, set the height of the elements including the gutters. The gutters will not be visible otherwise if the height is set to 0px.

.split,
.gutter.gutter-horizontal {
    height: 300px;
}

Overflow can be handled as well, to get scrolling within the elements:

.split {
    overflow-y: auto;
    overflow-x: hidden;
}

Browser Support #

This library uses CSS calc(), CSS box-sizing and JS getBoundingClientRect(). These features are supported in the following browsers:

Chrome logoFirefox logoInternet Explorer logoOpera logoSafari logoSauce Labs
22+ ✔6+ ✔9+ ✔15+ ✔6.2+ ✔Sponsored ✔

Gracefully falls back in IE 8 and below to only setting the initial widths/heights and not allowing dragging. IE 8 requires polyfills for Array.isArray(), Array.forEach, Array.map, Array.filter, Object.keys() and getComputedStyle. This script from Polyfill.io includes all of these, adding 1.91 kb to the gzipped size.

This is ONLY NEEDED if you are supporting IE8:

<script src="///polyfill.io/v2/polyfill.min.js?features=Array.isArray,Array.prototype.forEach,Array.prototype.map,Object.keys,Array.prototype.filter,getComputedStyle"></script>

Cross-browser Testing Platform and Open Source <3 Provided by Sauce Labs.

Credits #

Contributors #

This project exists thanks to all the people who contribute. [Contribute].

Backers #

Thank you to all our backers! 🙏 [Become a backer]

Sponsors #

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

Sauce Labs

License #

Copyright (c) 2018 Nathan Cahill

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  split: ^0.0.2

2. Install it

You can install packages from the command line:

with pub:


$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:split/split.dart';
  
Version Uploaded Documentation Archive
0.0.2 Apr 25, 2019 Go to the documentation of split 0.0.2 Download split 0.0.2 archive
0.0.1 Feb 19, 2019 Go to the documentation of split 0.0.1 Download split 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
57
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
50
Overall:
Weighted score of the above. [more]
69
Learn more about scoring.

We analyzed this package on Jun 17, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.3.2
  • pana: 0.12.18

Platforms

Detected platforms: web

Primary library: package:split/split.dart with components: html, js.

Maintenance issues and suggestions

Provide a file named CHANGELOG.md. (-20 points)

Changelog entries help developers follow the progress of your package. See the example generated by stagehand.

Maintain an example. (-10 points)

Create a short demo in the example/ directory to show how to use this package.

Common filename patterns include main.dart, example.dart, and split.dart. Packages with multiple examples should provide example/README.md.

For more information see the pub package layout conventions.

Update README.md. (-10 points)

5 image links are insecure (e.g. http://i.imgur.com/dJC1GUv.png), use https URLs instead.

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0-dev <3.0.0
js ^0.6.1+1 0.6.1+1