-
-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathformat-helpers.ts
More file actions
517 lines (416 loc) · 13.5 KB
/
format-helpers.ts
File metadata and controls
517 lines (416 loc) · 13.5 KB
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
import { isNode, isERBNode, getTagName, isAnyOf, isERBControlFlowNode, hasERBOutput } from "@herb-tools/core"
import { Node, HTMLDoctypeNode, HTMLTextNode, HTMLElementNode, HTMLCommentNode, HTMLOpenTagNode, HTMLCloseTagNode, ERBIfNode, ERBContentNode, WhitespaceNode } from "@herb-tools/core"
// --- Types ---
/**
* Analysis result for HTMLElementNode formatting decisions
*/
export interface ElementFormattingAnalysis {
openTagInline: boolean
elementContentInline: boolean
closeTagInline: boolean
}
/**
* Content unit represents a piece of content in text flow
* Can be atomic (inline elements, ERB) or splittable (text)
*/
export interface ContentUnit {
content: string
type: 'text' | 'inline' | 'erb' | 'block'
isAtomic: boolean
breaksFlow: boolean
isHerbDisable?: boolean
}
/**
* Content unit paired with its source AST node
*/
export interface ContentUnitWithNode {
unit: ContentUnit
node: Node | null
}
// --- Constants ---
// TODO: we can probably expand this list with more tags/attributes
export const FORMATTABLE_ATTRIBUTES: Record<string, string[]> = {
'*': ['class'],
'img': ['srcset', 'sizes']
}
export const INLINE_ELEMENTS = new Set([
'a', 'abbr', 'acronym', 'b', 'bdo', 'big', 'br', 'cite', 'code',
'dfn', 'em', 'i', 'img', 'kbd', 'label', 'map', 'object', 'q',
'samp', 'small', 'span', 'strong', 'sub', 'sup',
'tt', 'var', 'del', 'ins', 'mark', 's', 'u', 'time', 'wbr'
])
export const CONTENT_PRESERVING_ELEMENTS = new Set([
'script', 'style', 'pre', 'textarea'
])
export const SPACEABLE_CONTAINERS = new Set([
'div', 'section', 'article', 'main', 'header', 'footer', 'aside',
'figure', 'details', 'summary', 'dialog', 'fieldset'
])
export const TIGHT_GROUP_PARENTS = new Set([
'ul', 'ol', 'nav', 'select', 'datalist', 'optgroup', 'tr', 'thead',
'tbody', 'tfoot'
])
export const TIGHT_GROUP_CHILDREN = new Set([
'li', 'option', 'td', 'th', 'dt', 'dd'
])
export const SPACING_THRESHOLD = 3
/**
* Token list attributes that contain space-separated values and benefit from
* spacing around ERB content for readability
*/
export const TOKEN_LIST_ATTRIBUTES = new Set([
'class', 'data-controller', 'data-action'
])
// --- Node Utility Functions ---
/**
* Check if a node is pure whitespace (empty text node with only whitespace)
*/
export function isPureWhitespaceNode(node: Node): boolean {
return isNode(node, HTMLTextNode) && node.content.trim() === ""
}
/**
* Check if a node is non-whitespace (has meaningful content)
*/
export function isNonWhitespaceNode(node: Node): boolean {
if (isNode(node, WhitespaceNode)) return false
if (isNode(node, HTMLTextNode)) return node.content.trim() !== ""
return true
}
/**
* Find the previous meaningful (non-whitespace) sibling
* Returns -1 if no meaningful sibling is found
*/
export function findPreviousMeaningfulSibling(siblings: Node[], currentIndex: number): number {
for (let i = currentIndex - 1; i >= 0; i--) {
if (isNonWhitespaceNode(siblings[i])) {
return i
}
}
return -1
}
/**
* Check if there's whitespace between two indices in children array
*/
export function hasWhitespaceBetween(children: Node[], startIndex: number, endIndex: number): boolean {
for (let j = startIndex + 1; j < endIndex; j++) {
if (isNode(children[j], WhitespaceNode) || isPureWhitespaceNode(children[j])) {
return true
}
}
return false
}
/**
* Filter children to remove insignificant whitespace
*/
export function filterSignificantChildren(body: Node[]): Node[] {
return body.filter(child => {
if (isNode(child, WhitespaceNode)) return false
if (isNode(child, HTMLTextNode)) {
if (child.content === " ") return true
return child.content.trim() !== ""
}
return true
})
}
/**
* Filter out empty text nodes and whitespace nodes
*/
export function filterEmptyNodes(nodes: Node[]): Node[] {
return nodes.filter(child =>
!isNode(child, WhitespaceNode) && !(isNode(child, HTMLTextNode) && child.content.trim() === "")
)
}
/**
* Smart filter that preserves exactly ONE whitespace before herb:disable comments
*/
export function filterEmptyNodesForHerbDisable(nodes: Node[]): Node[] {
const result: Node[] = []
let pendingWhitespace: Node | null = null
for (const node of nodes) {
const isWhitespace = isNode(node, WhitespaceNode) || (isNode(node, HTMLTextNode) && node.content.trim() === "")
const isHerbDisable = isNode(node, ERBContentNode) && isHerbDisableComment(node)
if (isWhitespace) {
if (!pendingWhitespace) {
pendingWhitespace = node
}
} else {
if (isHerbDisable && pendingWhitespace) {
result.push(pendingWhitespace)
}
pendingWhitespace = null
result.push(node)
}
}
return result
}
// --- Punctuation and Word Spacing Functions ---
/**
* Check if a word is standalone closing punctuation
*/
export function isClosingPunctuation(word: string): boolean {
return /^[.,;:!?)\]]+$/.test(word)
}
/**
* Check if a line ends with opening punctuation
*/
export function lineEndsWithOpeningPunctuation(line: string): boolean {
return /[(\[]$/.test(line)
}
/**
* Check if a string is an ERB tag
*/
export function isERBTag(text: string): boolean {
return /^<%.*?%>$/.test(text.trim())
}
/**
* Check if a string ends with an ERB tag
*/
export function endsWithERBTag(text: string): boolean {
return /%>$/.test(text.trim())
}
/**
* Check if a string starts with an ERB tag
*/
export function startsWithERBTag(text: string): boolean {
return /^<%/.test(text.trim())
}
/**
* Determine if space is needed between the current line and the next word
*/
export function needsSpaceBetween(currentLine: string, word: string): boolean {
if (isClosingPunctuation(word)) return false
if (lineEndsWithOpeningPunctuation(currentLine)) return false
if (currentLine.endsWith(' ')) return false
if (endsWithERBTag(currentLine) && startsWithERBTag(word)) return false
return true
}
/**
* Build a line by adding a word with appropriate spacing
*/
export function buildLineWithWord(currentLine: string, word: string): string {
if (!currentLine) return word
if (word === ' ') {
return currentLine.endsWith(' ') ? currentLine : `${currentLine} `
}
return needsSpaceBetween(currentLine, word) ? `${currentLine} ${word}` : `${currentLine}${word}`
}
/**
* Check if a node is an inline element or ERB node
*/
export function isInlineOrERBNode(node: Node): boolean {
return isERBNode(node) || (isNode(node, HTMLElementNode) && isInlineElement(getTagName(node)))
}
/**
* Check if an element should be treated as inline based on its tag name
*/
export function isInlineElement(tagName: string): boolean {
return INLINE_ELEMENTS.has(tagName.toLowerCase())
}
/**
* Check if the current inline element is adjacent to a previous inline element (no whitespace between)
*/
export function isAdjacentToPreviousInline(siblings: Node[], index: number): boolean {
const previousNode = siblings[index - 1]
if (isInlineOrERBNode(previousNode)) {
return true
}
if (index > 1 && isNode(previousNode, HTMLTextNode) && !/^\s/.test(previousNode.content)) {
const twoBack = siblings[index - 2]
return isInlineOrERBNode(twoBack)
}
return false
}
/**
* Check if a node should be appended to the last line (for adjacent inline elements and punctuation)
*/
export function shouldAppendToLastLine(child: Node, siblings: Node[], index: number): boolean {
if (index === 0) return false
if (isNode(child, HTMLTextNode) && !/^\s/.test(child.content)) {
const previousNode = siblings[index - 1]
return isInlineOrERBNode(previousNode)
}
if (isNode(child, HTMLElementNode) && isInlineElement(getTagName(child))) {
return isAdjacentToPreviousInline(siblings, index)
}
if (isNode(child, ERBContentNode)) {
for (let i = index - 1; i >= 0; i--) {
const previousSibling = siblings[i]
if (isPureWhitespaceNode(previousSibling) || isNode(previousSibling, WhitespaceNode)) {
continue
}
if (previousSibling.location && child.location) {
return previousSibling.location.end.line === child.location.start.line
}
break
}
}
return false
}
/**
* Check if user-intentional spacing should be preserved (double newlines between elements)
*/
export function shouldPreserveUserSpacing(child: Node, siblings: Node[], index: number): boolean {
if (!isPureWhitespaceNode(child)) return false
const hasPreviousNonWhitespace = index > 0 && isNonWhitespaceNode(siblings[index - 1])
const hasNextNonWhitespace = index < siblings.length - 1 && isNonWhitespaceNode(siblings[index + 1])
const hasMultipleNewlines = isNode(child, HTMLTextNode) && child.content.includes('\n\n')
return hasPreviousNonWhitespace && hasNextNonWhitespace && hasMultipleNewlines
}
/**
* Check if children contain any text content with newlines
*/
export function hasMultilineTextContent(children: Node[]): boolean {
for (const child of children) {
if (isNode(child, HTMLTextNode)) {
return child.content.includes('\n')
}
if (isNode(child, HTMLElementNode)) {
const nestedChildren = filterEmptyNodes(child.body)
if (hasMultilineTextContent(nestedChildren)) {
return true
}
}
}
return false
}
/**
* Check if all nested elements in the children are inline elements
*/
export function areAllNestedElementsInline(children: Node[]): boolean {
for (const child of children) {
if (isNode(child, HTMLElementNode)) {
if (!isInlineElement(getTagName(child))) {
return false
}
const nestedChildren = filterEmptyNodes(child.body)
if (!areAllNestedElementsInline(nestedChildren)) {
return false
}
} else if (isAnyOf(child, HTMLDoctypeNode, HTMLCommentNode, isERBControlFlowNode)) {
return false
}
}
return true
}
/**
* Check if element has complex ERB control flow
*/
export function hasComplexERBControlFlow(inlineNodes: Node[]): boolean {
return inlineNodes.some(node => {
if (isNode(node, ERBIfNode)) {
if (node.statements.length > 0 && node.location) {
const startLine = node.location.start.line
const endLine = node.location.end.line
return startLine !== endLine
}
return false
}
return false
})
}
/**
* Check if children contain mixed text and inline elements (like "text<em>inline</em>text")
* or mixed ERB output and text (like "<%= value %> text")
* This indicates content that should be formatted inline even with structural newlines
*/
export function hasMixedTextAndInlineContent(children: Node[]): boolean {
let hasText = false
let hasInlineElements = false
for (const child of children) {
if (isNode(child, HTMLTextNode)) {
if (child.content.trim() !== "") {
hasText = true
}
} else if (isNode(child, HTMLElementNode)) {
if (isInlineElement(getTagName(child))) {
hasInlineElements = true
}
}
}
return (hasText && hasInlineElements) || (hasERBOutput(children) && hasText)
}
export function isContentPreserving(element: HTMLElementNode | HTMLOpenTagNode | HTMLCloseTagNode): boolean {
const tagName = getTagName(element)
return CONTENT_PRESERVING_ELEMENTS.has(tagName)
}
/**
* Count consecutive inline elements/ERB at the start of children (with no whitespace between)
*/
export function countAdjacentInlineElements(children: Node[]): number {
let count = 0
let lastSignificantIndex = -1
for (let i = 0; i < children.length; i++) {
const child = children[i]
if (isPureWhitespaceNode(child) || isNode(child, WhitespaceNode)) {
continue
}
const isInlineOrERB = (isNode(child, HTMLElementNode) && isInlineElement(getTagName(child))) || isNode(child, ERBContentNode)
if (!isInlineOrERB) {
break
}
if (lastSignificantIndex >= 0 && hasWhitespaceBetween(children, lastSignificantIndex, i)) {
break
}
count++
lastSignificantIndex = i
}
return count
}
/**
* Determine if we should wrap to the next line
*/
export function shouldWrapToNextLine(testLine: string, currentLine: string, word: string, wrapWidth: number): boolean {
if (!currentLine) return false
if (isClosingPunctuation(word)) return false
return testLine.length >= wrapWidth
}
/**
* Check if a node represents a block-level element
*/
export function isBlockLevelNode(node: Node): boolean {
if (!isNode(node, HTMLElementNode)) {
return false
}
const tagName = getTagName(node)
if (INLINE_ELEMENTS.has(tagName)) {
return false
}
return true
}
/**
* Normalize text by replacing multiple spaces with single space and trim
* Then split into words
*/
export function normalizeAndSplitWords(text: string): string[] {
const normalized = text.replace(/\s+/g, ' ')
return normalized.trim().split(' ')
}
/**
* Check if text starts with an alphanumeric character (not punctuation)
*/
export function startsWithAlphanumeric(text: string): boolean {
const trimmed = text.trim()
return /^[a-zA-Z0-9]/.test(trimmed)
}
/**
* Check if text ends with an alphanumeric character (not punctuation)
*/
export function endsWithAlphanumeric(text: string): boolean {
return /[a-zA-Z0-9]$/.test(text)
}
/**
* Check if text ends with whitespace
*/
export function endsWithWhitespace(text: string): boolean {
return /\s$/.test(text)
}
/**
* Check if an ERB content node is a herb:disable comment
*/
export function isHerbDisableComment(node: Node): boolean {
if (!isNode(node, ERBContentNode)) return false
if (node.tag_opening?.value !== "<%#") return false
const content = node?.content?.value || ""
const trimmed = content.trim()
return trimmed.startsWith("herb:disable")
}