-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
398 lines (356 loc) · 12.9 KB
/
Copy pathmain.js
File metadata and controls
398 lines (356 loc) · 12.9 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
/**
* Converts JSON data to semantic HTML with configurable headers and styling
* @param {object|array|string|number|boolean|null} json - The JSON data to convert
* @param {object} options - Configuration options
* @param {Object<string, number>} [options.headers={}] - Mapping of JSON paths to heading levels (h1-h6)
* @param {string} [options.initialPath=""] - Initial path for the root object
* @param {"default"|"none"|object} [options.useStyles="default"] - Styling configuration
* @param {boolean|string[]} [options.listObjects=false] - Keys that should be rendered as lists
* @param {boolean} [options.formatKeys=false] - Whether to format keys from camelCase/snake_case to normal text
* @param {"inline"|"top"} [options.styleLocation="inline"] - Where to place styles: inline or in a top-level style tag
* @returns {string} The generated HTML string
*/
const jsonToHtml = (json, options = {}) => {
const {
headers = {},
initialPath = "",
useStyles = "default",
listObjects = false,
formatKeys = false,
styleLocation = "inline",
} = options;
const defaultStyles = {
container:
"font-family: system-ui, sans-serif; line-height: 1.5; padding: 5px;",
key: "font-weight: bold; color: #000;",
value: "margin-left: 8px; color: #3b3b3b;",
number: "margin-left: 8px; color: #0F766E;",
boolean: "margin-left: 8px; color: #9333EA;",
null: "margin-left: 8px; color: #888; font-style: italic;",
heading: "margin: 16px 0 8px 0;",
list: "margin: 0; padding: 0 0 0 20px; line-height: 1.5;", // Fully reset list styles
"top-list": "margin: 0; padding: 0 0 0 20px; list-style: '↘';", // Avoid newline for top list markers
"top-list-item": "display: inline-flex; align-items: center;", // Prevent newline and align
"top-list-marker": "margin-right: 8px; color: #000;", // Style marker manually
circular: "margin-left: 8px; color: #FF0000;",
};
const styles =
useStyles === "none"
? {}
: useStyles === "default"
? defaultStyles
: { ...defaultStyles, ...useStyles };
// Function to apply inline or class-based styles dynamically
const applyStyle = (key) => {
if (!styles[key]) return "";
if (styleLocation === "inline") {
// Handle special cases for characters needing Unicode escape sequences
if (key === "top-list") {
return ` style="${styles[key].replace("'↘'", "'\\2198'")}"`; // Unicode for ↘
}
return ` style="${styles[key]}"`; // General inline styles
}
return ` class="json-${key}"`; // Class-based styles
};
const generateStyleTag = () => {
if (styleLocation !== "top" || useStyles === "none") return "";
const styleRules = Object.entries(styles)
.map(([key, value]) => {
if (key === "top-list") {
return `.json-${key} { ${value} }
.json-${key} > li { color: inherit; }
.json-${key} > li::marker { color: #9CA3AF; }`;
}
return `.json-${key} { ${value} }`;
})
.join("\n");
return `<style>\n${styleRules}\n</style>\n\n`;
};
const visited = new WeakSet();
const getIndent = (level) => " ".repeat(level * 2);
const escapeHtml = (str) => {
return String(str)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
};
const formatPrimitive = (value) => {
if (value === null) {
return `<span${applyStyle("null")}>null</span>`;
}
switch (typeof value) {
case "number":
return `<span${applyStyle("number")}>${value}</span>`;
case "boolean":
return `<span${applyStyle("boolean")}>${value}</span>`;
case "string":
return `<span${applyStyle("value")}>${escapeHtml(value)}</span>`;
default:
return `<span${applyStyle("value")}>${escapeHtml(
String(value)
)}</span>`;
}
};
const shouldRenderAsList = (path) => {
if (Array.isArray(listObjects)) {
const lastKey = path.split(".").pop();
return listObjects.includes(lastKey);
}
return listObjects;
};
const shouldBeHeader = (path) => {
// For paths containing array indices (e.g., "path[0].property")
if (path.match(/\[\d+\]/)) {
// Convert numeric indices to [] (e.g., "path[].property")
const arrayPattern = path.replace(/\[\d+\]/g, "[]");
return headers[arrayPattern] || null;
}
// For regular paths, only exact matches
return headers[path] || null;
};
const convertValue = (value, path = "", level = 0) => {
if (value === null) {
return formatPrimitive(null);
}
if (typeof value === "object" && value !== null) {
if (visited.has(value)) {
return `<span${applyStyle("circular")}>[Circular Reference]</span>`;
}
visited.add(value);
}
switch (typeof value) {
case "object":
if (Array.isArray(value)) {
return convertArray(value, path, level);
}
return convertObject(value, path, level);
default:
return formatPrimitive(value);
}
};
const convertArray = (arr, path, level) => {
if (arr.length === 0) return "<div>(empty array)</div>";
const indent = getIndent(level);
// Check if this array contains nested objects that should become lists
const hasNestedLists = arr.some((item) => {
if (typeof item !== "object" || item === null) return false;
// If listObjects is true, any object should become a list
if (listObjects === true) return true;
// For array of listObjects keys, check if any nested keys match
if (Array.isArray(listObjects)) {
return Object.keys(item).some((key) => listObjects.includes(key));
}
return false;
});
// First, analyze the array to see if we need to split it due to headers
const segments = arr.reduce((acc, item, index) => {
if (typeof item === "object" && item !== null) {
// Find any header properties in this item
const headerEntries = Object.entries(item).filter(([key]) => {
const fullPath = `${path}.${key}`; // Try direct path
const normalizedPath = fullPath
.replace(/\[\d+\]/g, "")
.replace(/\.\./g, "."); // Try normalized
return shouldBeHeader(fullPath) || shouldBeHeader(normalizedPath);
});
if (headerEntries.length > 0) {
// Create a header segment
acc.push({
type: "header",
content: headerEntries,
remainingEntries: Object.entries(item).filter(
([key]) =>
!shouldBeHeader(`${path}.${key}`) &&
!shouldBeHeader(
`${path}.${key}`.replace(/\[\d+\]/g, "").replace(/\.\./g, ".")
)
),
itemPath: `${path}[${index}]`,
});
// Start a new list segment
acc.push({
type: "list",
items: [],
});
} else {
// Add to current list segment
if (acc.length === 0 || acc[acc.length - 1].type === "header") {
acc.push({ type: "list", items: [] });
}
acc[acc.length - 1].items.push({ item, index });
}
} else {
// Handle primitive values
if (acc.length === 0 || acc[acc.length - 1].type === "header") {
acc.push({ type: "list", items: [] });
}
acc[acc.length - 1].items.push({ item, index });
}
return acc;
}, []);
// Render all segments
return segments
.map((segment) => {
if (segment.type === "header") {
// Render headers and their remaining properties
return `${segment.content
.map(([key, value]) => {
const headerLevel = shouldBeHeader(`${path}.${key}`);
const valueHtml = convertValue(
value,
`${segment.itemPath}.${key}`,
level + 1
);
return `${indent}<h${headerLevel}${applyStyle(
"heading"
)}>${escapeHtml(formatKey(key))}: ${
typeof value === "object" && value !== null
? `<span${applyStyle("value")}>${
Array.isArray(value) ? `[${value.length} items]` : "{...}"
}</span>`
: valueHtml
}</h${headerLevel}>${
typeof value === "object" && value !== null
? `\n${valueHtml}`
: ""
}`;
})
.join("\n")}
${segment.remainingEntries
.map(
([key, value]) =>
`${indent}<div><span${applyStyle("key")}>${escapeHtml(
formatKey(key)
)}:</span> ${convertValue(
value,
`${segment.itemPath}.${key}`,
level + 1
)}</div>`
)
.join("\n")}`;
} else {
// Render list segments
if (segment.items.length === 0) return "";
// Use top-list style for outer lists under headers that contain nested lists
const listStyle = listObjects && hasNestedLists ? "top-list" : "list";
return `${indent}<ul${applyStyle(listStyle)}>
${segment.items
.map(
({ item, index }) =>
`${getIndent(level + 1)}<li>${convertValue(
item,
`${path}[${index}]`,
level + 1
)}</li>`
)
.join("\n")}
${indent}</ul>`;
}
})
.join("\n");
};
const toNormalText = (str) => {
return (
str
// Handle snake_case first
.split("_")
.map(
(word) =>
// Capitalize first letter of each word
word.charAt(0).toUpperCase() +
// Handle camelCase within each word
word.slice(1).replace(/([A-Z])/g, " $1")
)
.join(" ")
// Clean up any extra spaces
.replace(/\s+/g, " ")
.trim()
);
};
const formatKey = (key) => (formatKeys ? toNormalText(key) : key);
const convertObject = (obj, path, level) => {
const keys = Object.keys(obj);
if (keys.length === 0) return "<div>(empty object)</div>";
const indent = getIndent(level);
// Add this block to handle list rendering
if (shouldRenderAsList(path)) {
const items = keys
.map((key) => {
const value = obj[key];
const newPath = path ? `${path}.${key}` : key;
const headerLevel = shouldBeHeader(newPath);
if (headerLevel) {
// If it's a header, break it out of the list structure
return `</ul>
<h${headerLevel}${applyStyle("heading")}>${escapeHtml(
formatKey(key)
)}</h${headerLevel}>
${convertValue(value, newPath, 1)}
<ul${applyStyle("list")}>`;
}
// Regular list item
return `${indent} <li><span${applyStyle("key")}>${escapeHtml(
formatKey(key)
)}:</span> ${convertValue(value, newPath, level + 1)}</li>`;
})
.join("\n");
// Use top-list style for top-level lists when listObjects is true
const listStyle = level === 0 ? "top-list" : "list";
return `${indent}<ul${applyStyle(listStyle)}>${items}${indent}</ul>`;
}
// Add the regular object rendering logic here
return keys
.map((key) => {
const value = obj[key];
const newPath = path ? `${path}.${key}` : key;
const headerLevel = shouldBeHeader(newPath);
if (headerLevel) {
// Show full value for primitives only, no preview for objects/arrays
const headerContent =
typeof value === "object" && value !== null
? "" // No preview text for objects/arrays
: convertValue(value, newPath, level + 1);
return `${indent}<h${headerLevel}${applyStyle(
"heading"
)}>${escapeHtml(formatKey(key))}${
headerContent ? `: ${headerContent}` : ""
}</h${headerLevel}>${
typeof value === "object" && value !== null
? `\n${convertValue(value, newPath, level + 1)}`
: ""
}`;
}
return `${indent}<div><span${applyStyle("key")}>${escapeHtml(
formatKey(key)
)}:</span> ${convertValue(value, newPath, level + 1)}</div>`;
})
.join("\n");
};
// Add post-processing function
const postProcessHtml = (html) => {
// Only apply top-list styling when we have a key followed by a list containing another list
let processed = html.replace(
/(<li><span[^>]*json-key[^>]*>[^<]*<\/span>\s*<ul[^>]*json-list[^>]*>(?=\s*<li>\s*<ul))/g,
(match) => {
return match.replace("json-list", "json-top-list");
}
);
// Remove empty ul tags
let previousHtml;
do {
previousHtml = processed;
processed = processed.replace(/<ul[^>]*>\s*<\/ul>/g, "");
} while (processed !== previousHtml);
return processed;
};
return postProcessHtml(`${generateStyleTag()}<div${applyStyle("container")}>
${convertValue(json, initialPath)}
</div>`)
.replace(/>\s+</g, "><")
.replace(/\s{2,}/g, " ")
.replace(/[\n\r]/g, "")
.trim();
};
export { jsonToHtml };