2015-01-30 01:10:49 +00:00
|
|
|
/**
|
2018-09-11 22:27:47 +00:00
|
|
|
* Copyright (c) Facebook, Inc. and its affiliates.
|
2015-03-23 22:07:33 +00:00
|
|
|
*
|
2018-02-17 02:24:55 +00:00
|
|
|
* This source code is licensed under the MIT license found in the
|
|
|
|
* LICENSE file in the root directory of this source tree.
|
2015-01-30 01:10:49 +00:00
|
|
|
*
|
2018-05-11 02:06:46 +00:00
|
|
|
* @format
|
2015-03-24 16:26:16 +00:00
|
|
|
* @flow
|
2015-01-30 01:10:49 +00:00
|
|
|
*/
|
2018-05-11 02:06:46 +00:00
|
|
|
|
2015-01-30 01:10:49 +00:00
|
|
|
'use strict';
|
|
|
|
|
2015-03-24 16:26:16 +00:00
|
|
|
type truncateOptions = {
|
2016-08-09 13:32:41 +00:00
|
|
|
breakOnWords: boolean,
|
|
|
|
minDelta: number,
|
|
|
|
elipsis: string,
|
2018-05-11 02:06:46 +00:00
|
|
|
};
|
2015-03-24 16:26:16 +00:00
|
|
|
|
2016-06-13 17:06:29 +00:00
|
|
|
const defaultOptions = {
|
2015-01-30 01:10:49 +00:00
|
|
|
breakOnWords: true,
|
|
|
|
minDelta: 10, // Prevents truncating a tiny bit off the end
|
|
|
|
elipsis: '...',
|
|
|
|
};
|
|
|
|
|
2015-12-15 17:08:39 +00:00
|
|
|
// maxChars (including ellipsis)
|
2016-06-13 17:06:29 +00:00
|
|
|
const truncate = function(
|
2015-03-24 16:26:16 +00:00
|
|
|
str: ?string,
|
|
|
|
maxChars: number,
|
2018-05-11 02:06:46 +00:00
|
|
|
options?: truncateOptions,
|
2015-03-24 16:26:16 +00:00
|
|
|
): ?string {
|
2016-06-13 17:06:29 +00:00
|
|
|
options = Object.assign({}, defaultOptions, options);
|
2018-05-11 02:06:46 +00:00
|
|
|
if (
|
|
|
|
str &&
|
|
|
|
str.length &&
|
|
|
|
str.length - options.minDelta + options.elipsis.length >= maxChars
|
|
|
|
) {
|
2018-03-12 19:31:45 +00:00
|
|
|
// If the slice is happening in the middle of a wide char, add one more char
|
2018-05-11 02:06:46 +00:00
|
|
|
const extraChar =
|
|
|
|
str.charCodeAt(maxChars - options.elipsis.length) > 255 ? 1 : 0;
|
2018-03-12 19:31:45 +00:00
|
|
|
str = str.slice(0, maxChars - options.elipsis.length + 1 + extraChar);
|
2015-01-30 01:10:49 +00:00
|
|
|
if (options.breakOnWords) {
|
2018-05-10 22:44:52 +00:00
|
|
|
const ii = Math.max(str.lastIndexOf(' '), str.lastIndexOf('\n'));
|
2015-01-30 01:10:49 +00:00
|
|
|
str = str.slice(0, ii);
|
|
|
|
}
|
|
|
|
str = str.trim() + options.elipsis;
|
|
|
|
}
|
|
|
|
return str;
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = truncate;
|