All files / utils text.ts

98.79% Statements 82/83
93.54% Branches 58/62
100% Functions 16/16
98.66% Lines 74/75

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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        94x 94x                                           94x 620x   620x 5x     615x                         94x 24x                                                         94x           1881x 437x     1444x   1444x 2883x   1444x 2554x 2554x 2554x 2291x 2291x   263x 263x 263x     2554x 1115x     1439x 1439x     1444x 1444x                   94x                 94x                     94x 207012x 514024x   207012x 207012x 514024x   207012x                                           94x 283x 1132x   1132x         1132x     283x 283x                     283x             94x 5079x       94x 5102x       9048x   5102x 9058x       23x   9035x       94x 11x         661x   661x 583x   583x         78x   6x 6x           72x 12x       30x           60x 5x             55x 3x         52x     661x    
/**
 * @module Utils
 */
 
import * as MC from "@lisn/globals/minification-constants";
import * as MH from "@lisn/globals/minification-helpers";
 
import { Size, StrRecord } from "@lisn/globals/types";
 
/**
 * Formats an object as a string. It supports more meaningful formatting as
 * string for certain types rather than using the default string
 * representation.
 *
 * **NOTE:** This is not intended for serialization of data that needs to be
 * de-serialized. Only for debugging output.
 *
 * @param value    The value to format as string.
 * @param [maxLen] Maximum length of the returned string. If not given or
 *                 is <= 0, the string is not truncated. Otherwise, if the
 *                 result is longer than maxLen, it is truncated to
 *                 `maxLen - 3` and added a suffix of "...".
 *                 Note that if `maxLen` is > 0 but <= 3, the result is
 *                 always "..."
 *
 * @category Text
 */
export const formatAsString = (value: unknown, maxLen?: number) => {
  const result = maybeConvertToString(value, false);
 
  if (!MH.isNullish(maxLen) && maxLen > 0 && MH.lengthOf(result) > maxLen) {
    return result.slice(0, MH.max(0, maxLen - 3)) + "...";
  }
 
  return result;
};
 
/**
 * Join an array of values as string using separator. It uses
 * {@link formatAsString} rather than the default string representation as
 * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join | Array:join} would.
 *
 * @param separator The separator to use to delimit each argument.
 * @param args      Objects or values to convert to string and join.
 *
 * @category Text
 */
export const joinAsString = (separator: string, ...args: unknown[]) =>
  args.map((a) => formatAsString(a)).join(separator);
 
/**
 * Similar to
 * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split | String.prototype.split}
 * except that
 * 1. `limit` is interpreted as the maximum number of splits, and the
 *   returned array contains `limit + 1` entries. Also if `limit` is given and
 *   the number of substrings is greater than the limit, all the remaining
 *   substrings are present in the final substring.
 * 2. If input is an empty string (or containing only whitespace), returns an
 *    empty array.
 *
 * @example
 * ```javascript
 * splitOn('foo, bar, baz', RegExp(',\\s*'), 0); // -> ['foo, bar, baz']
 * splitOn('foo, bar, baz', RegExp(',\\s*'), 1); // -> ['foo', 'bar, baz']
 * splitOn('foo, bar, baz', RegExp(',\\s*'), 2); // -> ['foo', 'bar', 'baz']
 * splitOn('foo, bar, baz', RegExp(',\\s*'), 3); // -> ['foo', 'bar', 'baz']
 * ```
 *
 * @param trim  If true, entries will be trimmed for whitespace after splitting.
 *
 * @param limit If not given or < 0, the string will be split on every
 *              occurrence of `separator`. Otherwise, it will be split on
 *              the first `limit` number of occurrences of `separator`.
 *
 * @category Text
 */
export const splitOn = (
  input: string,
  separator: string | RegExp,
  trim?: boolean,
  limit?: number,
) => {
  if (!input.trim()) {
    return [];
  }
 
  limit ??= -1;
 
  const output: string[] = [];
  const addEntry = (s: string) => output.push(trim ? s.trim() : s);
 
  while (limit--) {
    let matchIndex = -1,
      matchLength = 0;
    if (MH.isLiteralString(separator)) {
      matchIndex = input.indexOf(separator);
      matchLength = MH.lengthOf(separator);
    } else {
      const match = separator.exec(input);
      matchIndex = match?.index ?? -1;
      matchLength = match ? MH.lengthOf(match[0]) : 0;
    }
 
    if (matchIndex < 0) {
      break;
    }
 
    addEntry(input.slice(0, matchIndex));
    input = input.slice(matchIndex + matchLength);
  }
 
  addEntry(input);
  return output;
};
 
/**
 * Converts a kebab-cased-string to camelCase.
 * The result is undefined if the input string is not formatted in
 * kebab-case.
 *
 * @category Text
 */
export const kebabToCamelCase = MH.kebabToCamelCase;
 
/**
 * Converts a camelCasedString to kebab-case.
 * The result is undefined if the input string is not formatted in
 * camelCase.
 *
 * @category Text
 */
export const camelToKebabCase = MH.camelToKebabCase;
 
/**
 * Generates a random string of a fixed length.
 *
 * **IMPORTANT:** This is _not_ suitable for cryptographic applications.
 *
 * @param nChars The length of the returned stirng.
 *
 * @category Text
 */
export const randId = (nChars = 8) => {
  const segment = () =>
    MH.floor(100000 + MC.MATH.random() * 900000).toString(36);
 
  let s = "";
  while (MH.lengthOf(s) < nChars) {
    s += segment();
  }
  return s.slice(0, nChars);
};
 
/**
 * Returns an array of numeric margins in pixels from the given margin string.
 * The string should contain margins in either pixels or percentage; other
 * units are not supported.
 *
 * Percentage values are converted to pixels relative to the given
 * `absoluteSize`: left/right margins relative to the width, and top/bottom
 * margins relative to the height.
 *
 * Note that for the margin property, percentages are always relative to the
 * WIDTH of the parent, so you should pass the parent width as both the width
 * and the height keys in `absoluteSize`. But for IntersectionObserver's
 * `rootMargin`, top/bottom margin is relative to the height of the root, so
 * pass the actual root size.
 *
 * @returns [topMarginInPx, rightMarginInPx, bottomMarginInPx, leftMarginInPx]
 *
 * @category Text
 */
export const toMargins = (value: string, absoluteSize: Size) => {
  const toPxValue = (strValue: string | undefined, index: number) => {
    let margin = MH.parseFloat(strValue ?? "") || 0;
 
    Iif (strValue === margin + "%") {
      margin *=
        index % 2 ? absoluteSize[MC.S_HEIGHT] : absoluteSize[MC.S_WIDTH];
    }
 
    return margin;
  };
 
  const parts = splitOn(value, " ", true);
  const margins: [number, number, number, number] = [
    // top
    toPxValue(parts[0], 0),
    // right
    toPxValue(parts[1] ?? parts[0], 1),
    // bottom
    toPxValue(parts[2] ?? parts[0], 2),
    // left
    toPxValue(parts[3] ?? parts[1] ?? parts[0], 3),
  ];
 
  return margins;
};
 
/**
 * @ignore
 * @internal
 */
export const objToStrKey = (obj: StrRecord): string =>
  MH.stringify(flattenForSorting(obj));
 
// --------------------
 
const flattenForSorting = (obj: StrRecord): unknown[] => {
  const array = MH.isArray(obj)
    ? obj
    : MH.keysOf(obj)
        .sort()
        .map((k) => obj[k]);
 
  return array.map((value) => {
    if (
      MH.isArray(value) ||
      (MH.isNonPrimitive(value) && MH.constructorOf(value) === MC.OBJECT)
    ) {
      return flattenForSorting(value);
    }
    return value;
  });
};
 
const stringifyReplacer = (key: string, value: unknown) =>
  key ? maybeConvertToString(value, true) : value;
 
function maybeConvertToString<V>(value: V, nested: true): string | V;
function maybeConvertToString(value: unknown, nested: false): string;
function maybeConvertToString<V>(value: V, nested: boolean) {
  let result: string | V = "";
 
  if (MH.isElement(value)) {
    const classStr = MH.classList(value).toString().trim();
 
    result = value.id
      ? "#" + value.id
      : `<${MH.tagName(value)}${classStr ? ' class="' + classStr + '"' : ""}>`;
 
    //
  } else if (MH.isInstanceOf(value, Error)) {
    /* istanbul ignore else */
    if ("stack" in value && MH.isString(value.stack)) {
      result = value.stack;
    } else {
      result = `Error: ${value.message}`;
    }
 
    //
  } else if (MH.isArray(value)) {
    result =
      "[" +
      value
        .map((v) =>
          MH.isString(v) ? MH.stringify(v) : maybeConvertToString(v, false),
        )
        .join(",") +
      "]";
 
    //
  } else if (MH.isIterableObject(value)) {
    result =
      MH.typeOrClassOf(value) +
      "(" +
      maybeConvertToString(MH.arrayFrom(value), false) +
      ")";
 
    //
  } else if (MH.isNonPrimitive(value)) {
    result = nested ? value : MH.stringify(value, stringifyReplacer);
 
    //
  } else {
    // primitive
    result = nested ? value : MC.STRING(value);
  }
 
  return result;
}