MCPcopy Create free account
hub / github.com/Noumena-Network/code / truncatePath

Function truncatePath

src/utils/logoV2Utils.ts:109–181  ·  view source on GitHub ↗
(path: string, maxLength: number)

Source from the content-addressed store, hash-verified

107 * Width-aware: uses stringWidth() for correct CJK/emoji measurement.
108 */
109export function truncatePath(path: string, maxLength: number): string {
110 if (stringWidth(path) <= maxLength) return path
111
112 const separator = '/'
113 const ellipsis = '…'
114 const ellipsisWidth = 1 // '…' is always 1 column
115 const separatorWidth = 1
116
117 const parts = path.split(separator)
118 const first = parts[0] || ''
119 const last = parts[parts.length - 1] || ''
120 const firstWidth = stringWidth(first)
121 const lastWidth = stringWidth(last)
122
123 // Only one part, so show as much of it as we can
124 if (parts.length === 1) {
125 return truncateToWidth(path, maxLength)
126 }
127
128 // We don't have enough space to show the last part, so truncate it
129 // But since firstPart is empty (unix) we don't want the extra ellipsis
130 if (first === '' && ellipsisWidth + separatorWidth + lastWidth >= maxLength) {
131 return `${separator}${truncateToWidth(last, Math.max(1, maxLength - separatorWidth))}`
132 }
133
134 // We have a first part so let's show the ellipsis and truncate last part
135 if (
136 first !== '' &&
137 ellipsisWidth * 2 + separatorWidth + lastWidth >= maxLength
138 ) {
139 return `${ellipsis}${separator}${truncateToWidth(last, Math.max(1, maxLength - ellipsisWidth - separatorWidth))}`
140 }
141
142 // Truncate first and leave last
143 if (parts.length === 2) {
144 const availableForFirst =
145 maxLength - ellipsisWidth - separatorWidth - lastWidth
146 return `${truncateToWidthNoEllipsis(first, availableForFirst)}${ellipsis}${separator}${last}`
147 }
148
149 // Now we start removing middle parts
150
151 let available =
152 maxLength - firstWidth - lastWidth - ellipsisWidth - 2 * separatorWidth
153
154 // Just the first and last are too long, so truncate first
155 if (available <= 0) {
156 const availableForFirst = Math.max(
157 0,
158 maxLength - lastWidth - ellipsisWidth - 2 * separatorWidth,
159 )
160 const truncatedFirst = truncateToWidthNoEllipsis(first, availableForFirst)
161 return `${truncatedFirst}${separator}${ellipsis}${separator}${last}`
162 }
163
164 // Try to keep as many middle parts as possible
165 const middleParts = []
166 for (let i = parts.length - 2; i > 0; i--) {

Callers 2

LogoV2Function · 0.85
CondensedLogoFunction · 0.85

Calls 3

truncateToWidthFunction · 0.85
maxMethod · 0.80

Tested by

no test coverage detected