Since no one has done it already, I did a simple Angular directive for the awesome Trunk8 by Rick Viscomi. Note: It’s not thoroughly tested, and requires jQuery. I added a zero-timeout to allow the template to render before trunk8 is applied.
Usage:
1 |
<span trunk8="{lines: 2}">Text </span> |
Settings (Default value):
1 2 3 4 5 6 7 8 |
fill: '…', //The string to insert in place of the omitted text. This value may include HTML. lines: 1, //The number of lines of text-wrap to tolerate before truncating. This value must be an integer greater than or equal to 1. side: 'right', //The side of the text from which to truncate. Valid values include 'center', 'left', and 'right'. tooltip: true, //When true, the title attribute of the targeted HTML element will be set to the original, untruncated string. Valid values include true and false. width: 'auto', // The width, in characters, of the desired text. When set to 'auto', trunk8 will maximize the amount of text without spilling over. parseHTML: false, //When true, parse and save html structure and restore structure in the truncated text. responsive: false, //Truncate on window resize onTruncate: function(){} //Called after truncation is completed. |
Source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
(function(){ function trunk8() { var _directive = this, defaultSettings = { fill: '…', lines: 1, side: 'right', tooltip: true, width: 'auto', parseHTML: false, responsive: false, onTruncate: function(){} }, methods, utils, SIDES = { /* cen...ter */ center: 'center', /* ...left */ left: 'left', /* right... */ right: 'right' }, WIDTH = { auto: 'auto' }; function _trunk8(element) { this.$element = $(element); this.original_text = $.trim(this.$element.html()); this.settings = $.extend({}, defaultSettings); } _trunk8.prototype.updateSettings = function (options) { this.settings = $.extend(this.settings, options); }; function stripHTML(html) { var tmp = document.createElement("DIV"); tmp.innerHTML = html; if (typeof tmp.textContent != 'undefined') { return tmp.textContent; } return tmp.innerText; } function getHtmlArr(str) { /* Builds an array of strings and designated */ /* HTML tags around them. */ if (stripHTML(str) === str) { return str.split(/\s/g); } var allResults = [], reg = /<([a-z]+)([^<]*)(?:>(.*?(?!<\1>))<\/\1>|\s+\/>)(['.?!,]*)|((?:[^<>\s])+['.?!,]*\w?|<br\s?\/?>)/ig, outArr = reg.exec(str), lastI, ind; while (outArr && lastI !== reg.lastIndex) { lastI = reg.lastIndex; if (outArr[5]) { allResults.push(outArr[5]); } else if (outArr[1]) { allResults.push({ tag: outArr[1], attribs: outArr[2], content: outArr[3], after: outArr[4] }); } outArr = reg.exec(str); } for (ind = 0; ind < allResults.length; ind++) { if (typeof allResults[ind] !== 'string' && allResults[ind].content) { allResults[ind].content = getHtmlArr(allResults[ind].content); } } return allResults; } function rebuildHtmlFromBite(bite, htmlObject, fill) { // Take the processed bite after binary-search // truncated and re-build the original HTML // tags around the processed string. bite = bite.replace(fill, ''); var biteHelper = function(contentArr, tagInfo) { var retStr = '', content, biteContent, biteLength, nextWord, i; for (i = 0; i < contentArr.length; i++) { content = contentArr[i]; biteLength = $.trim(bite).split(' ').length; if ($.trim(bite).length) { if (typeof content === 'string') { if (!/<br\s*\/?>/i.test(content)) { if (biteLength === 1 && $.trim(bite).length <= content.length) { content = bite; // We want the fill to go inside of the last HTML // element if the element is a container. if (tagInfo === 'p' || tagInfo === 'div') { content += fill; } bite = ''; } else { bite = bite.replace(content, ''); } } retStr += $.trim(content) + ((i === contentArr.length-1 || biteLength <= 1) ? '' : ' '); } else { biteContent = biteHelper(content.content, content.tag); if (content.after) bite = bite.replace(content.after, ''); if (biteContent) { if (!content.after) content.after = ' '; retStr += '<'+content.tag+content.attribs+'>'+biteContent+'</'+content.tag+'>' + content.after; } } } } return retStr; }, htmlResults = biteHelper(htmlObject); // Add fill if doesn't exist. This will place it outside the HTML elements. if (htmlResults.slice(htmlResults.length - fill.length) === fill) { htmlResults += fill; } return htmlResults; } function truncate() { var data = this.data('trunk8'), settings = data.settings, width = settings.width, side = settings.side, fill = settings.fill, parseHTML = settings.parseHTML, line_height = utils.getLineHeight(this) * settings.lines, str = data.original_text, length = str.length, max_bite = '', lower, upper, bite_size, bite, text, htmlObject; /* Reset the field to the original string. */ this.html(str); text = this.text(); /* If string has HTML and parse HTML is set, build */ /* the data struct to house the tags */ if (parseHTML && stripHTML(str) !== str) { htmlObject = getHtmlArr(str); str = stripHTML(str); length = str.length; } if (width === WIDTH.auto) { /* Assuming there is no "overflow: hidden". */ if (this.height() <= line_height) { /* Text is already at the optimal trunkage. */ return; } /* Binary search technique for finding the optimal trunkage. */ /* Find the maximum bite without overflowing. */ lower = 0; upper = length - 1; while (lower <= upper) { bite_size = lower + ((upper - lower) >> 1); bite = utils.eatStr(str, side, length - bite_size, fill); if (parseHTML && htmlObject) { bite = rebuildHtmlFromBite(bite, htmlObject, fill); } this.html(bite); /* Check for overflow. */ if (this.height() > line_height) { upper = bite_size - 1; } else { lower = bite_size + 1; /* Save the bigger bite. */ max_bite = (max_bite.length > bite.length) ? max_bite : bite; } } /* Reset the content to eliminate possible existing scroll bars. */ this.html(''); /* Display the biggest bite. */ this.html(max_bite); if (settings.tooltip) { this.attr('title', text); } } else if (!isNaN(width)) { bite_size = length - width; bite = utils.eatStr(str, side, bite_size, fill); this.html(bite); if (settings.tooltip) { this.attr('title', str); } } else { $.error('Invalid width "' + width + '".'); return; } settings.onTruncate(); } methods = { init: function (options) { console.log(options); if( options.responsive ) { //Remove old listener if exists if( this.resizeFunction ) { window.removeEventListener('resize', this.resizeFunction); } this.resizeFunction = debounce(function() { this.each(function () { truncate.call($(this)); }); }, 250).bind(this); //Add new listener to window window.addEventListener('resize', this.resizeFunction); } var loop = this.each(function () { var $this = $(this), data = $this.data('trunk8'); if (!data) { $this.data('trunk8', (data = new _trunk8(this))); } data.updateSettings(options); //Make sure angular has finnished loading the content setTimeout(function(){ truncate.call($this); }); console.log($this); }); return loop; }, /** Updates the text value of the elements while maintaining truncation. */ update: function (new_string) { return this.each(function () { var $this = $(this); /* Update text. */ if (new_string) { $this.data('trunk8').original_text = new_string; } /* Truncate accordingly. */ truncate.call($this); }); }, revert: function () { return this.each(function () { /* Get original text. */ var text = $(this).data('trunk8').original_text; /* Revert element to original text. */ $(this).html(text); }); }, /** Returns this instance's settings object. NOT CHAINABLE. */ getSettings: function () { return $(this.get(0)).data('trunk8').settings; } }; utils = { /** Replaces [bite_size] [side]-most chars in [str] with [fill]. */ eatStr: function (str, side, bite_size, fill) { var length = str.length, key = utils.eatStr.generateKey.apply(null, arguments), half_length, half_bite_size; /* If the result is already in the cache, return it. */ if (utils.eatStr.cache[key]) { return utils.eatStr.cache[key]; } /* Common error handling. */ if ((typeof str !== 'string') || (length === 0)) { $.error('Invalid source string "' + str + '".'); } if ((bite_size < 0) || (bite_size > length)) { $.error('Invalid bite size "' + bite_size + '".'); } else if (bite_size === 0) { /* No bite should show no truncation. */ return str; } if (typeof (fill + '') !== 'string') { $.error('Fill unable to be converted to a string.'); } /* Compute the result, store it in the cache, and return it. */ switch (side) { case SIDES.right: /* str... */ return utils.eatStr.cache[key] = $.trim(str.substr(0, length - bite_size)) + fill; case SIDES.left: /* ...str */ return utils.eatStr.cache[key] = fill + $.trim(str.substr(bite_size)); case SIDES.center: /* Bit-shift to the right by one === Math.floor(x / 2) */ half_length = length >> 1; // halve the length half_bite_size = bite_size >> 1; // halve the bite_size /* st...r */ return utils.eatStr.cache[key] = $.trim(utils.eatStr(str.substr(0, length - half_length), SIDES.right, bite_size - half_bite_size, '')) + fill + $.trim(utils.eatStr(str.substr(length - half_length), SIDES.left, half_bite_size, '')); default: $.error('Invalid side "' + side + '".'); } }, getLineHeight: function (elem) { var floats = $(elem).css('float'); if (floats !== 'none') { $(elem).css('float', 'none'); } var pos = $(elem).css('position'); if (pos === 'absolute') { $(elem).css('position', 'static'); } var html = $(elem).html(), wrapper_id = 'line-height-test', line_height; /* Set the content to a small single character and wrap. */ $(elem).html('i').wrap('<div id="' + wrapper_id + '" />'); /* Calculate the line height by measuring the wrapper.*/ line_height = $('#' + wrapper_id).innerHeight(); /* Remove the wrapper and reset the content. */ $(elem).html(html).css({ 'float': floats, 'position': pos }).unwrap(); return line_height; } }; utils.eatStr.cache = {}; utils.eatStr.generateKey = function () { return Array.prototype.join.call(arguments, ''); }; $.fn._trunk8 = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.trunk8'); } }; //David Walsh | http://davidwalsh.name/javascript-debounce-function // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; return { restrict: 'A', link: function(scope, element, attrs){ var settings = $.extend(defaultSettings,scope.$eval( attrs.trunk8)); $(element)._trunk8(settings); } }; } angular.module('myApp') .directive('trunk8', trunk8); })(); |