• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2024 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import m from 'mithril';
16
17export interface MiddleEllipsisAttrs {
18  text: string;
19  endChars?: number;
20  className?: string;
21}
22
23function replaceLeadingTrailingSpacesWithNbsp(text: string) {
24  return text.replace(/^\s+|\s+$/g, function (match) {
25    return '\u00A0'.repeat(match.length);
26  });
27}
28
29/**
30 * Puts ellipsis in the middle of a long string, rather than putting them at
31 * either end, for occasions where the start and end of the text are more
32 * important than the middle.
33 */
34export class MiddleEllipsis implements m.ClassComponent<MiddleEllipsisAttrs> {
35  view({attrs, children}: m.Vnode<MiddleEllipsisAttrs>): m.Children {
36    const {text, endChars = text.length > 16 ? 10 : 0} = attrs;
37    const trimmed = text.trim();
38    const index = trimmed.length - endChars;
39    const left = trimmed.substring(0, index);
40    const right = trimmed.substring(index);
41    return m(
42      '.pf-middle-ellipsis',
43      {
44        className: attrs.className,
45      },
46      m(
47        'span.pf-middle-ellipsis-left',
48        replaceLeadingTrailingSpacesWithNbsp(left),
49      ),
50      m(
51        'span.pf-middle-ellipsis-right',
52        replaceLeadingTrailingSpacesWithNbsp(right),
53      ),
54      children,
55    );
56  }
57}
58