|
| 1 | +// Truncate text component module |
| 2 | + |
| 3 | +'use strict'; |
| 4 | + |
| 5 | +var $ = require('jquery'); |
| 6 | +var debounce = require('../services/debounce'); |
| 7 | + |
| 8 | +module.exports = function Truncate() { |
| 9 | + var truncate = {}; |
| 10 | + |
| 11 | + /** |
| 12 | + * @example |
| 13 | + * <div id="truncate" style="overflow: hidden; line-height: 20px; max-height: 60px;"> |
| 14 | + * Lorem ipsum ... |
| 15 | + * </div> |
| 16 | + * |
| 17 | + * import truncate from 'massive-web/src/components/truncate'; |
| 18 | + * truncate.initialize($('#truncate'), {}); |
| 19 | + * |
| 20 | + * @param {jQuery} $el |
| 21 | + * @param {object} options |
| 22 | + */ |
| 23 | + truncate.initialize = function initialize($el, options) { |
| 24 | + truncate.$el = $el; |
| 25 | + |
| 26 | + // Set default options if no custom options are defined |
| 27 | + truncate.separator = options.separator || ' ...'; |
| 28 | + truncate.debounceDelay = options.debounceDelay || 250; |
| 29 | + |
| 30 | + truncate.text = truncate.$el.text().trim(); |
| 31 | + truncate.$inner = $('<span></span>').text(truncate.text).css('display', 'block'); |
| 32 | + truncate.$el.html(truncate.$inner).css('display', 'block'); |
| 33 | + |
| 34 | + truncate.calculateRegex(); |
| 35 | + truncate.calculateText(); |
| 36 | + |
| 37 | + $(window).on('resize', debounce(truncate.calculateText, truncate.debounceDelay)); |
| 38 | + }; |
| 39 | + |
| 40 | + /** |
| 41 | + * Calculate regex based on the separator. |
| 42 | + */ |
| 43 | + truncate.calculateRegex = function calculateRegex() { |
| 44 | + var separatorRegex = truncate.separator.split('').map(c => '\\' + c).join(''); |
| 45 | + truncate.regex = new RegExp('\\W*\\s?(?:\\S*|\\S*' + separatorRegex + ')$'); |
| 46 | + }; |
| 47 | + |
| 48 | + /** |
| 49 | + * Calculate output text based on the element's height. |
| 50 | + */ |
| 51 | + truncate.calculateText = function calculateText() { |
| 52 | + var height; |
| 53 | + |
| 54 | + truncate.$inner.text(truncate.text); |
| 55 | + height = truncate.$el.height(); |
| 56 | + |
| 57 | + while (truncate.$inner.outerHeight() > height) { |
| 58 | + truncate.$inner.text(function(index, text) { |
| 59 | + if (text === truncate.separator) { |
| 60 | + return ''; |
| 61 | + } |
| 62 | + |
| 63 | + return text.replace(truncate.regex, truncate.separator); |
| 64 | + }); |
| 65 | + } |
| 66 | + }; |
| 67 | + |
| 68 | + return { |
| 69 | + initialize: truncate.initialize |
| 70 | + }; |
| 71 | +}; |
0 commit comments