Skip to content

Commit

Permalink
introduce new block attribute to control sorting direction (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
stklcode committed Aug 16, 2024
1 parent f4f210f commit c7076a3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
25 changes: 25 additions & 0 deletions scripts/block.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@
type: 'boolean',
default: false,
},
sort: {
type: 'string',
default: 'desc',
},
},
edit: withSelect( function( select ) {
return {
Expand Down Expand Up @@ -166,6 +170,26 @@
},
}
),
el(
wp.components.SelectControl,
{
label: __( 'Output direction', 'stklcode-liveticker' ),
value: props.attributes.sort,
options: [
{
value: 'desc',
label: __( 'oldest first', 'stklcode-liveticker' ),
},
{
value: 'asc',
label: __( 'newest first', 'stklcode-liveticker' ),
},
],
onChange: function( val ) {
props.setAttributes( { sort: val } );
},
}
),
];
}

Expand All @@ -183,6 +207,7 @@
'data-sclt-ticker': props.attributes.ticker,
'data-sclt-limit': props.attributes.unlimited ? 0 : props.attributes.limit,
'data-sclt-last': 0,
'data-sclt-sort': props.attributes.sort,
}
);
},
Expand Down
20 changes: 17 additions & 3 deletions scripts/liveticker.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Contructor of the scLiveticker object.
* Constructor of the scLiveticker object.
*
* @class
*/
Expand Down Expand Up @@ -73,6 +73,7 @@
var parseElement = function( elem, widget, n ) {
var list = elem.querySelector( 'ul' );
var last = elem.getAttribute( 'data-sclt-last' );
var sort = elem.getAttribute( 'data-sclt-sort' );

elem.id = 'sclt-' + n;

Expand All @@ -92,11 +93,16 @@
);
}

if ( 'asc' !== sort && 'desc' !== 'sort' ) {
sort = 'desc';
}

return {
id: n,
ticker: elem.getAttribute( 'data-sclt-ticker' ),
limit: elem.getAttribute( 'data-sclt-limit' ),
lastPoll: last,
sort: sort,
ticks: list,
isWidget: widget,
updating: false,
Expand Down Expand Up @@ -210,8 +216,11 @@
if ( old ) {
// Replace entry, if it already exists (i.e. has been updated).
t.ticks.replaceChild( li, old );
} else if ( 'asc' === t.sort ) {
// Append new tick as last element to container.
t.ticks.appendChild( li );
} else {
// Prepend new tick to container.
// Prepend new tick as fist element to container.
t.ticks.insertBefore( li, t.ticks.firstChild );
}

Expand All @@ -221,7 +230,12 @@

// Remove tail, if limit is set.
if ( 0 < t.limit ) {
[].slice.call( t.ticks.getElementsByTagName( 'li' ), t.limit ).forEach(
if ( 'asc' === t.sort ) {
old = [].slice.call( t.ticks.getElementsByTagName( 'li' ), 0, t.limit );
} else {
old = [].slice.call( t.ticks.getElementsByTagName( 'li' ), t.limit );
}
old.forEach(
function( l ) {
l.remove();
}
Expand Down

0 comments on commit c7076a3

Please sign in to comment.