Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Sortable UI primitives for Ember.js

License

NotificationsYou must be signed in to change notification settings

adopted-ember-addons/ember-sortable

npm versionBuild StatusDownloads WeeklyEmber Observer ScoreCode Climate

Sortable UI primitives for Ember.

Check out the demo

Requirements

Ember SortableEmberNode
3.0.03.24+12+
4.0.03.24+14+
5.0.03.28+n/a1

Installation

$ ember install ember-sortable

Usage

{{! app/components/my-list/template.hbs }}<ol{{sortable-grouponChange=this.reorderItems}}>{{#eachthis.itemsas |item|}}    <li{{sortable-itemmodel=item}}>{{item}}      <spanclass='handle'{{sortable-handle}}>&varr;</span>    </li>{{/each}}</ol><p>The last dragged item was:{{this.lastDragged}}</p>

TheonChange action is called with two arguments:

  • Your item models in their new order
  • The model you just dragged
// app/components/my-list/component.jsexportdefaultclassMyListextendsComponent{  @trackedlastDragged;  @trackeditems=['Coal Ila','Askaig','Bowmore'];  @actionreorderItems(itemModels,draggedModel){this.items=itemModels;this.lastDragged=draggedModel;}}

The modifier version does not supportgroupModel, use the currying ofaction or thefn helper.

{{! app/components/my-list/template.hbs }}<ol{{sortable-grouponChange=(fnthis.reorderItemsmodel)}}>{{#eachthis.itemsas |item|}}    <li{{sortable-itemmodel=item}}>{{item}}      <spanclass='handle'{{sortable-handle}}>&varr;</span>    </li>{{/each}}</ol>

Changing sort direction

To change sort direction, definedirection onsortable-groupPossible values are:

  • y (default): allowes to move items up/down
  • x: allowes to move items left/right
  • grid: items can be moved in all directions inside a group
<ol{{sortable-groupdirection="x"onChange=this.reorderItems}}>

Changing spacing between currently dragged element and the rest of the group

When user starts to drag element, other elements jump back. Works for all direction option.

Iny case: elements above current one jump up, and elements below current one - jump down.Inx /grid case: elements before current one jump to the left, and elements after current one - jump to the right.

To change this property, definespacing onsortable-item (default is0):

<li{{sortable-itemspacing=15}}>

Changing the drag tolerance

distance attribute changes the tolerance, in pixels, for when sorting should start.If specified, sorting will not start until after mouse is dragged beyond distance.Can be used to allow for clicks on elements within a handle.

<li{{sortable-itemdistance=30}}>

Disabling reordering

Thedisabled attribute allows you to disable sorting for the entire group and its child items.

<li{{sortable-groupdisabled=true}}>

CSS, Animation

Sortable items can be in one of four states: default, dragging, dropping, and activated.The classes look like this:

<!-- Default --><liclass="sortable-item">...</li><!-- Dragging --><liclass="sortable-item is-dragging">...</li><!-- Dropping --><liclass="sortable-item is-dropping">...</li><!-- Keyboard --><liclass="sortable-item is-activated">...</li>

In ourexample app.css we apply atransition of.125s in the default case:

.sortable-item {transition: all0.125s;}

While an item is dragging we want it to move pixel-for-pixel with theuser’s mouse so we bring the transition duration to 0. We also giveit a highlight color and bring it to the top of the stack:

.sortable-item.is-dragging {transition-duration:0s;background: red;z-index:10;}

While dropping, theis-dragging class is removed and the item returns to its default transition duration. If we wanted to apply adifferent duration we could do so with theis-dropping class. Inour example we opt to simply maintain the z-index and apply aslightly different colour:

.sortable-item.is-dropping {background:#f66;z-index:10;}

If the user presses space to activate and move an item via the keyboard,is-activated is added. Once the user drops the item it isremoved. Use this class to add a visual indicator that the item is selected and being manipulated.

Drag Actions

TheonDragStart andonDragStop actions are available for thesortable-items. You can provide an action to listen to these actions tobe notified when an item is being dragged or not.

When the action is called, the item's model will be provided as the onlyargument.

// app/components/my-list/component.jsexportdefaultclassMyRouteextendsRoute{  @actiondragStarted(item){console.log(`Item started dragging:${item}`);},  @actiondragStopped(item){console.log(`Item stopped dragging:${item}`);}}
<li{{sortable-itemonDragStart=this.dragStartedonDragStop=this.dragStoppedmodel=item}}>{{item}}  <spanclass='handle'{{sortable-handle}}>&varr;</span></li>

Multiple Ember-Sortables renders simultaneously

There is a service behind the scenes for communication between the group and the items and to maintain state. It does this seemlessly when the elements are rendered on the screen. However, if there are two sortables rendered at the same time, either in the same component or different components, the state management does not know which items belong to which group.

Both the{{sortable-group}} and{{sortable-item}} take an additional argumentgroupName. Should you encounter this conflict, assign agroupName to the group and items. You only need to do this for one of the sortables in conflict, but you can on both if you wish.

<ol{{sortable-groupgroupName='products'onChange=this.reorderItems}}>{{#eachthis.itemsas |item|}}    <li{{sortable-itemgroupName='products'model=item}}>{{item}}      <spanclass='handle'{{sortable-handle}}>&varr;</span>    </li>{{/each}}</ol>

Ensure that the same name is passed to both the group and the items, this would be best accomplished by creating property on the component and referring to that property. If you are able to use the{{#let}} helper (useful in template only components), using{{#let}} makes the usage clearer.

{{#let'products'as |myGroupName|}}  <ol{{sortable-groupgroupName=myGroupNameonChange=this.reorderItems}}>{{#eachthis.itemsas |item|}}      <li{{sortable-itemgroupName=myGroupNamemodel=item}}>{{item}}        <spanclass='handle'{{sortable-handle}}>&varr;</span>      </li>{{/each}}  </ol>{{/let}}

Disabling Drag (Experimental)

sortable-item exposes an optionaldisabled (previouslyisDraggingDisabled) flag that you can use to disable reordering for that particular item. Disabling and item won't prevent it from changing position in the array. The user can still move other non-disabled items to over it.

This flag is intended as an utility to make your life easier with 3 main benefits:

  1. You can now specify whichsortable-item are not intended to be draggable/sortable.
  2. You do not have to duplicate thesortable-item UI just for the purpose of disabling thesorting behavior.
  3. Allows you to access the entire list ofmodels for youronChange action, which can now be a mix of sortable and non-sortable items.

Data down, actions up

No data is mutated bysortable-group orsortable-item. In the spirit of “data down, actions up”, a fresh array containing the models from each item in their new order is sent via the group’sonChange action.

Each item takes amodel property. This should be fairly self-explanatory but it’s important to note that it doesn’t do anything with this object besides keeping a reference for later use inonChange.

Accessibility

Thesortable-group has support for the following accessibility functionality:

Built-in Functionalities

Keyboard Navigation

There are 4 modes during keyboard navigation:

  • ACTIVATEenables the keyboard navigation.Activate viaENTER/SPACE
  • MOVEenables item(s) to be moved up, down, left, or right based ondirection.Activate viaARROW UP/DOWN/LEFT/RIGHT
  • CONFIRMsubmits the new sort order, invokes theonChange action.Activate viaENTER/SPACE.
  • CANCELcancels the new sort order, reverts back to the old sort order.Activate viaESCAPE or whenfocus is lost.
Focus Management
  • Whenfocus is on aitem orhandle, user can effectively select theitem viaENTER/SPACE. This is theACTIVATE mode.
  • WhileACTIVATE, thefocus is locked onsortable-group container and will not be lost untilCONFIRM,CANCEL, orfocus is lost.

User configurable

Screen Reader

The default language forember-sortable is English. Any language can be supported by passing in the configuration below in the appropriate language.

  • a11yItemNamea name for the item. Defaults toitem.
  • a11yAnnouncementConfiga map ofaction enums tofunctions that takes the followingconfig, which is exposed bysortable-group.
a11yAnnounceConfig={  a11yItemName,// name associated with the name  index,// 0-based  maxLength,// length of the items  direction,// x or y  delta,// +1 means down or right, -1 means up or left};

and returns astring constructed from theconfig.

Default value

{ACTIVATE:function({ a11yItemName, index, maxLength, direction}){letmessage=`${a11yItemName} at position,${index+1} of${maxLength}, is activated to be repositioned.`;if(direction==='y'){message+='Press up and down keys to change position,';}else{message+='Press left and right keys to change position,';}message+=' Space to confirm new position, Escape to cancel.';returnmessage;},MOVE:function({ a11yItemName, index, maxLength, delta}){return`${a11yItemName} is moved to position,${index+1+delta} of${maxLength}. Press Space to confirm new position, Escape to cancel.`;},CONFIRM:function({ a11yItemName}){return`${a11yItemName} is successfully repositioned.`;},CANCEL:function({ a11yItemName}){return`Cancelling${a11yItemName} repositioning`;}}
Visual Indicator
  • handleVisualClassThis class will be added to thesortable-handle duringACTIVATE andMOVE operations. This allows you to add custom styles such asvisual arrows viapseudo classes.

  • itemVisualClassThis class will be added to thesortable-item duringACTIVATE andMOVE operations. The default class added isis-activated. This is needed to creating avisual indicator that mimicsfocus b/c the nativefocus is on the container.

Testing

ember-sortable exposes some acceptance test helpers:

  • drag: Drags elements by an offset specified in pixels.
  • reorder: Reorders elements to the specified state.
  • keyboard: Keycode constants for quick.

To include them in your application, you can import them:

import{drag,reorder,ENTER_KEY_CODE,SPACE_KEY_CODE,ESCAPE_KEY_CODE,ARROW_KEY_CODES,}from'ember-sortable/test-support';

Examples

Reorder

awaitreorder('mouse','[data-test-vertical-demo-handle]', ...order);

Drag

awaitdrag('mouse','[data-test-scrollable-demo-handle] .handle',()=>{return{dy:itemHeight()*2+1,dx:undefined};});

Keyboard

awaittriggerKeyEvent('[data-test-vertical-demo-handle]','keydown',ENTER_KEY_CODE);

Migrating

v3 -> v4

None, just make sure Node v14+ and Ember is v3.24+. Although older versions might work, but are no longer tested against. Specifically ember-modifier dropped support for older versions of Ember.

v2 -> v3

The component versions have been removed and you must use the modifier.The modifier version does not supportgroupModel, use the currying of thefn helper.

v1 -> v2

If you are migrating from1.x.x to2.x.x,For components, please read thismigration guide.For modifiers, please read thismigration guide.

Developing

Requirement

You need to install nodejs andpnpm.The specific versions you need, you can findhere

Setup

$ git clone git@github.com:adopted-ember-addons/ember-sortable$cd ember-sortable$ pnpm install

Dev Server

$cd test-app$ ember serve

Running Tests

$ pnpm runtest

Publishing Demo

$ make demo

Footnotes

  1. Node is not relevant for v2 addons. As of v5.0.0, ember-sortable is a v2 addon. V2 addons don't have to be for browser-only contexts, but ember-sortable is -- so node is not relevant anymore. This is different from v1 addons, which are not browser libraries, but node programs that happen emit browser code to the consuming app at app-build time.

About

Sortable UI primitives for Ember.js

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Sponsor this project

  •  

Packages

No packages published

Contributors89


[8]ページ先頭

©2009-2025 Movatter.jp