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} 21 22function replaceLeadingTrailingSpacesWithNbsp(text: string) { 23 return text.replace(/^\s+|\s+$/g, function (match) { 24 return '\u00A0'.repeat(match.length); 25 }); 26} 27 28/** 29 * Puts ellipsis in the middle of a long string, rather than putting them at 30 * either end, for occasions where the start and end of the text are more 31 * important than the middle. 32 */ 33export class MiddleEllipsis implements m.ClassComponent<MiddleEllipsisAttrs> { 34 view({attrs, children}: m.Vnode<MiddleEllipsisAttrs>): m.Children { 35 const {text, endChars = text.length > 16 ? 10 : 0} = attrs; 36 const trimmed = text.trim(); 37 const index = trimmed.length - endChars; 38 const left = trimmed.substring(0, index); 39 const right = trimmed.substring(index); 40 return m( 41 '.pf-middle-ellipsis', 42 m( 43 'span.pf-middle-ellipsis-left', 44 replaceLeadingTrailingSpacesWithNbsp(left), 45 ), 46 m( 47 'span.pf-middle-ellipsis-right', 48 replaceLeadingTrailingSpacesWithNbsp(right), 49 ), 50 children, 51 ); 52 } 53} 54