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

Function truncatePath

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

Source from the content-addressed store, hash-verified

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