-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtokensTable.js
248 lines (234 loc) · 10.6 KB
/
tokensTable.js
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
import React from 'react';
import { Flex, FlexItem, Grid, GridItem, Title, capitalize } from '@patternfly/react-core';
import {
Table,
Thead,
Th,
Tr,
Tbody,
Td,
ExpandableRowContent,
OuterScrollContainer,
InnerScrollContainer
} from '@patternfly/react-table';
import { TokensToolbar } from './tokensToolbar';
import './tokensTable.css';
// eslint-disable-next-line camelcase
import global_spacer_md from '@patternfly/react-tokens/dist/esm/global_spacer_md';
import LevelUpAltIcon from '@patternfly/react-icons/dist/esm/icons/level-up-alt-icon';
// Used to combine data grouped by theme under each token name
const deepMerge = (target, source) => {
for (const key in source) {
if (source[key] instanceof Object && key in target) {
Object.assign(source[key], deepMerge(target[key], source[key]));
}
}
return Object.assign(target || {}, source);
};
const getTokenChain = (themeTokenData) => {
let tokenChain = [];
let referenceToken = themeTokenData?.references?.[0];
while (referenceToken && referenceToken !== undefined) {
tokenChain = [...tokenChain, referenceToken.name];
if (referenceToken?.references?.[0]) {
referenceToken = referenceToken?.references?.[0];
} else {
tokenChain.push(referenceToken.value);
break;
}
}
return tokenChain;
};
const showTokenChain = (themeTokenData, hasReferences) => {
// Show final value if isColorToken but no references - otherwise color value not displayed in table
const tokenChain = hasReferences ? getTokenChain(themeTokenData) : [themeTokenData.value];
return (
<div>
{tokenChain.map((nextValue, index) => (
<div
key={`${index}`}
style={{
padding: `4px 0 4px calc(${global_spacer_md.value} * ${index})`
}}
>
<LevelUpAltIcon style={{ transform: 'rotate(90deg)' }} />
<span style={{ paddingInlineStart: global_spacer_md.value }}>{nextValue}</span>
</div>
))}
</div>
);
};
const isSearchMatch = (searchValue, tokenName, tokenData) => {
// match all tokens if no search term
if (searchValue === '') {
return true;
}
// match search term to token name, value, and description
searchValue = searchValue.toLowerCase();
return (
tokenName.toLowerCase().includes(searchValue) ||
Object.entries(tokenData).some(
([_themeName, themeData]) =>
themeData?.value?.toString().toLowerCase().includes(searchValue) ||
themeData?.description?.toLowerCase().includes(searchValue)
)
);
};
export const TokensTable = ({ tokenJson, formatThemeText = capitalize }) => {
// parse tokens from json, convert from modules, merge into single allTokens obj
const themesArr = Object.keys(tokenJson);
const themesObj = themesArr.reduce((acc, cur) => {
acc[cur] = JSON.parse(JSON.stringify(tokenJson[cur]));
return acc;
}, {});
const allTokens = deepMerge(...Object.values(themesObj));
// remove default property which is duplicate of other fields
delete allTokens.default;
// state variables
const [searchValue, setSearchValue] = React.useState('');
const [expandedTokens, setExpandedTokens] = React.useState([]);
const [selectedCategories, setSelectedCategories] = React.useState([]);
// helper funcs
const isTokenExpanded = (tokenName) => expandedTokens.includes(tokenName);
const isSelectedCategory = (categoryName) =>
selectedCategories.length === 0 || selectedCategories.includes(categoryName);
const setExpanded = (tokenName, isExpanding = true) =>
setExpandedTokens((prevExpanded) => {
const otherExpandedTokens = prevExpanded.filter((n) => n !== tokenName);
return isExpanding ? [...otherExpandedTokens, tokenName] : otherExpandedTokens;
});
return (
<React.Fragment>
<TokensToolbar
searchValue={searchValue}
setSearchValue={setSearchValue}
selectedCategories={selectedCategories}
setSelectedCategories={setSelectedCategories}
/>
<OuterScrollContainer className="tokens-table-outer-wrapper">
<InnerScrollContainer>
{
// Create new Table for each tokens layer [base, chart, palette, semantic]
Object.entries(allTokens).map(([layerName, layerDataObj], _rowIndex) => {
// save if semantic layer - used for custom styling due to description field
const isSemanticLayer = layerName === 'semantic';
// Create array of all tokens/nested tokens in layer, filtered by selectedCategories
let layerTokens = [];
if (!['base', 'semantic'].includes(layerName) && isSelectedCategory(layerName)) {
layerTokens = Object.entries(layerDataObj);
} else {
// base/semantic combine subcategory tokens into flattened arr
for (var subLayer in layerDataObj) {
isSelectedCategory(subLayer) && layerTokens.push(...Object.entries(layerDataObj[subLayer]));
}
}
// finally filter all tokens based on search term
const filteredTokens = layerTokens.filter(([tokenName, tokenData]) =>
isSearchMatch(searchValue, tokenName, tokenData)
);
return (
<>
<Title headingLevel="h2" id={`${layerName}-table`} className="pf-v6-u-mt-xl">
{formatThemeText(layerName)} tokens
</Title>
<Table variant="compact" style={{ marginBlockEnd: `var(--pf-t--global--spacer--xl)` }}>
<Thead>
<Tr>
{/* Only semantic tokens have description, adjust columns accordingly */}
<Th width={5}></Th>
<Th width={isSemanticLayer ? 60 : 80}>Name</Th>
<Th width={isSemanticLayer ? 10 : 15}>Value</Th>
{isSemanticLayer && <Th width={25}>Description</Th>}
</Tr>
</Thead>
{/* Loop through row for each token in current layer */}
{filteredTokens.map(([tokenName, tokenData], rowIndex) => {
const tokenThemesArr = Object.entries(tokenData);
const hasReferences = tokenThemesArr.some(([_themeName, themeToken]) =>
themeToken.hasOwnProperty('references')
);
const isColorToken = tokenThemesArr[0][1].type === 'color';
const tokenDescription = tokenThemesArr[0][1].description;
return (
<Tbody key={`row-${tokenName}`} isExpanded={isTokenExpanded(tokenName)}>
<Tr>
{/* Expandable row icon */}
<Td
expand={
hasReferences || isColorToken
? {
rowIndex,
isExpanded: isTokenExpanded(tokenName),
onToggle: () => setExpanded(tokenName, !isTokenExpanded(tokenName)),
expandId: `${tokenName}-expandable-toggle`
}
: undefined
}
/>
<Td>
<code>{tokenName}</code>
</Td>
{/* Token values for each theme */}
<Td>
{tokenThemesArr.map(([themeName, themeToken]) => {
const isColor = /^(#|rgb)/.test(themeToken.value);
return (
<Flex
justifyContent={{ default: 'justify-content-space-between' }}
flexWrap={{ default: 'nowrap' }}
key={`${themeName}-${tokenName}`}
>
<FlexItem>{formatThemeText(themeName)}:</FlexItem>
{isColor ? (
<FlexItem
key={`${themeName}_${tokenName}_swatch`}
className="pf-v6-l-flex pf-m-column pf-m-align-self-center"
>
<span
className="ws-token-swatch"
style={{ backgroundColor: themeToken.value }}
/>
</FlexItem>
) : (
<div className="pf-v6-l-flex pf-m-column pf-m-align-self-center">
{themeToken.value}
</div>
)}
</Flex>
);
})}
</Td>
{/* Description - only for semantic tokens */}
{isSemanticLayer && <Td>{tokenDescription}</Td>}
</Tr>
{/* Expandable token chain */}
{(hasReferences || isColorToken) && isTokenExpanded(tokenName) && (
<Tr isExpanded>
<Td />
<Td colSpan={3}>
<ExpandableRowContent>
<Grid hasGutter>
{tokenThemesArr.map(([themeName, themeToken]) => (
<>
<GridItem span={2}>{formatThemeText(themeName)}:</GridItem>
<GridItem span={10}>{showTokenChain(themeToken, hasReferences)}</GridItem>
</>
))}
</Grid>
</ExpandableRowContent>
</Td>
</Tr>
)}
</Tbody>
);
})}
</Table>
</>
);
})
}
</InnerScrollContainer>
</OuterScrollContainer>
</React.Fragment>
);
};