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