Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changes

## unreleased

- FEATURE: Added truncate component. #32

## 1.4.1

- FEATURE: Added return of instance in startComponent. #30
Expand Down
1 change: 0 additions & 1 deletion scss/tools/_media.scss
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,3 @@ $media-breakpoints: $breakpoints !default;
}
}
}

87 changes: 87 additions & 0 deletions src/components/truncate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Truncate text component module

'use strict';

var $ = require('jquery');

// Extracted from UnderscoreJS
/**
* @ignore
*/
function debounce(func, wait, immediate) {
var timeout;

return function() {
var context = this;
var args = arguments;

clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;

if (!immediate) {
func.apply(context, args);
}
}, wait);

if (immediate && !timeout) {
func.apply(context, args);
}
};
}

module.exports = function Truncate() {
var truncate = {};

truncate.separator = ' ...';
truncate.debounceDelay = 250;

truncate.initialize = function initialize($el, options) {
truncate.$el = $el;

if (options) {
if (options.separator) {
truncate.separator = options.separator;
}

if (options.debounceDelay) {
truncate.debounceDelay = options.debounceDelay;
}
}

truncate.text = truncate.$el.text().trim();
truncate.$inner = $('<span></span>').text(truncate.text).css('display', 'block');
truncate.$el.html(truncate.$inner).css('display', 'block');

truncate.calculateRegex();
truncate.calculateText();

$(window).on('resize', debounce(truncate.calculateText, truncate.debounceDelay));
};

truncate.calculateRegex = function calculateRegex() {
var separatorRegex = truncate.separator.split('').map(c => '\\' + c).join('');
truncate.regex = new RegExp('\\W*\\s?(?:\\S*|\\S*' + separatorRegex + ')$');
};

truncate.calculateText = function calculateText() {
var height;

truncate.$inner.text(truncate.text);
height = truncate.$el.height();

while (truncate.$inner.outerHeight() > height) {
truncate.$inner.text(function(index, text) {
if (text === truncate.separator) {
return '';
}

return text.replace(truncate.regex, truncate.separator);
});
}
};

return {
initialize: truncate.initialize
};
};