PluginProbe
Tableberg – Simple Gutenberg Table Block / 1.1.5
Tableberg – Simple Gutenberg Table Block v1.1.5
1.1.5 1.1.4 1.1.3 1.1.2 1.1.1 1.1.0 1.0.5 1.0.4 1.0.3 1.0.2 1.0.1 trunk 0.0.2 0.2.1 0.3.2 0.3.3 0.4.1 0.5.0 0.5.1 0.5.2 0.5.3 0.5.4 0.5.5 0.5.6 0.5.7 All 42 releases
tableberg / src / alignment.ts

alignment.ts in Tableberg – Simple Gutenberg Table Block 1.1.5, at src/alignment.ts

102 lines 2.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import { CSSProperties } from "react";
2 import { CellElement } from "./attributes";
3
4 export type ElementAlignment = "left" | "center" | "right";
5
6 export const DEFAULT_ELEMENT_ALIGNMENT: ElementAlignment = "left";
7
8 function isRecord(value: unknown): value is Record<string, unknown> {
9 return typeof value === "object" && value !== null;
10 }
11
12 export function isElementAlignment(value: unknown): value is ElementAlignment {
13 return value === "left" || value === "center" || value === "right";
14 }
15
16 export function elementAlignmentToJustifyContent(
17 alignment: ElementAlignment
18 ): CSSProperties["justifyContent"] {
19 if (alignment === "center") {
20 return "center";
21 }
22
23 if (alignment === "right") {
24 return "flex-end";
25 }
26
27 return "flex-start";
28 }
29
30 export function getElementAlignment(element: CellElement): ElementAlignment {
31 const elementName = element.name as string;
32 const attrs: Record<string, unknown> = isRecord(element.attributes)
33 ? element.attributes
34 : {};
35
36 if (elementName === "icon") {
37 const rawStyles = attrs["styles"];
38 const styles = isRecord(rawStyles) ? rawStyles : {};
39 return isElementAlignment(styles.align)
40 ? styles.align
41 : DEFAULT_ELEMENT_ALIGNMENT;
42 }
43
44 return isElementAlignment(attrs.align)
45 ? attrs.align
46 : DEFAULT_ELEMENT_ALIGNMENT;
47 }
48
49 export function setElementAlignment(
50 element: CellElement,
51 alignment: ElementAlignment
52 ): CellElement {
53 const elementName = element.name as string;
54 const attrs = isRecord(element.attributes)
55 ? { ...element.attributes }
56 : ({} as Record<string, unknown>);
57
58 if (elementName === "icon") {
59 const rawStyles = attrs["styles"];
60 const styles = isRecord(rawStyles)
61 ? { ...rawStyles }
62 : ({} as Record<string, unknown>);
63
64 return {
65 ...element,
66 attributes: {
67 ...attrs,
68 styles: {
69 ...styles,
70 align: alignment,
71 },
72 },
73 } as CellElement;
74 }
75
76 return {
77 ...element,
78 attributes: {
79 ...attrs,
80 align: alignment,
81 },
82 } as CellElement;
83 }
84
85 export function getUniformElementsAlignment(
86 elements: CellElement[]
87 ): ElementAlignment | undefined {
88 if (elements.length === 0) {
89 return DEFAULT_ELEMENT_ALIGNMENT;
90 }
91
92 const first = getElementAlignment(elements[0]);
93
94 for (let i = 1; i < elements.length; i++) {
95 if (getElementAlignment(elements[i]) !== first) {
96 return undefined;
97 }
98 }
99
100 return first;
101 }
102