-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathparseAlign.ts
More file actions
74 lines (66 loc) · 2.05 KB
/
parseAlign.ts
File metadata and controls
74 lines (66 loc) · 2.05 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
import type { Attribute } from '@tiptap/core'
/**
* Supported table cell alignment values
*/
export enum TableCellAlign {
Left = 'left',
Right = 'right',
Center = 'center',
}
/**
* Normalize unknown input into a supported table alignment
*
* @param value - A potential alignment value
* @returns A valid TableCellAlign value or null
*/
export function normalizeTableCellAlign(value: unknown): TableCellAlign | null {
if (value === TableCellAlign.Left || value === TableCellAlign.Right || value === TableCellAlign.Center) {
return value
}
return null
}
/**
* Parse table cell alignment from an HTML element
*
* Prefers inline style (${"`"}text-align${"`"}) and falls back to the legacy
* ${"`"}align${"`"} attribute.
*
* @param element - The table cell/header DOM element
* @returns A valid TableCellAlign value or null
*/
export function parseAlign(element: HTMLElement): TableCellAlign | null {
const styleAlign = (element.style.textAlign || '').trim().toLowerCase()
const attrAlign = (element.getAttribute('align') || '').trim().toLowerCase()
const align = styleAlign || attrAlign
return normalizeTableCellAlign(align)
}
/**
* Normalize alignment from a generic attrs object that may include an align field
*
* @param attributes - A node attrs-like object with an optional align field
* @returns A valid TableCellAlign value or null.
*/
export function normalizeTableCellAlignFromAttributes(
attributes: { align?: TableCellAlign } | null | undefined,
): TableCellAlign | null {
return normalizeTableCellAlign(attributes?.align)
}
/**
* Create a reusable Tiptap attribute config for table alignment
*
* @returns A Tiptap Attribute definition that parses and renders table alignment
*/
export function createAlignAttribute(): Attribute {
return {
default: null,
parseHTML: (element: HTMLElement) => parseAlign(element),
renderHTML: (attributes: { align?: TableCellAlign | null }) => {
if (!attributes.align) {
return {}
}
return {
style: `text-align: ${attributes.align}`,
}
},
}
}