✨ Innovative and open-source visualization application that transforms various data formats, such as JSON, YAML, XML and CSV into interactive graphs.
feat: implement color format validation and refactor text rendering logic
AykutSarac9c60d721705f
diff --git a/packages/jsoncrack-react/src/components/TextRenderer.tsx b/packages/jsoncrack-react/src/components/TextRenderer.tsxindex 943172ba..3f3686ab 100644--- a/packages/jsoncrack-react/src/components/TextRenderer.tsx+++ b/packages/jsoncrack-react/src/components/TextRenderer.tsx@@ -1,24 +1,14 @@import React from "react";+import { isColorFormat } from "../utils/colorFormat";import styles from "./TextRenderer.module.css";const URL_PATTERN =/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([-.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i;-const HEX_CODE_PATTERN = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;-const RGB_PATTERN = /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/;-const RGBA_PATTERN = /^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(0|1|0\.\d+)\s*\)$/;const isURL = (word: string) => {return URL_PATTERN.test(word);};-const isColorFormat = (colorString: string) => {- return (- HEX_CODE_PATTERN.test(colorString) ||- RGB_PATTERN.test(colorString) ||- RGBA_PATTERN.test(colorString)- );-};-const LinkifiedText = ({ text }: { text: string }) => {if (!isURL(text)) return <>{text}</>;diff --git a/packages/jsoncrack-react/src/parser.ts b/packages/jsoncrack-react/src/parser.tsindex 04bfb427..ca6ad0a4 100644--- a/packages/jsoncrack-react/src/parser.ts+++ b/packages/jsoncrack-react/src/parser.ts@@ -1,6 +1,6 @@import { getNodePath, parseTree, type Node, type ParseError } from "jsonc-parser";import type { EdgeData, GraphData, NodeData, NodeRow } from "./types";-import { calculateNodeSize } from "./utils/calculateNodeSize";+import { calculateNodeSize, type NodeTextRow } from "./utils/calculateNodeSize";export interface ParseGraphResult extends GraphData {errors: ParseError[];@@ -179,14 +179,21 @@ export const parseGraph = (json: string): ParseGraphResult => {...appendParentKey(),});} else {- let displayText: string | [string, string][];+ let displayText: string | NodeTextRow[];if (text.some(row => row.key !== null)) {- displayText = text.map(row => {+ displayText = text.map<NodeTextRow>(row => {const keyStr = row.key === null ? "" : row.key;-- if (row.type === "object") return [keyStr, `{${row.childrenCount ?? 0} keys}`];- if (row.type === "array") return [keyStr, `[${row.childrenCount ?? 0} items]`];+ // Same condition as the collapse button rendered by ObjectNode's Row+ const hasCollapseButton =+ row.key != null &&+ (row.type === "object" || row.type === "array") &&+ (row.childrenCount ?? 0) > 0;++ if (row.type === "object")+ return [keyStr, `{${row.childrenCount ?? 0} keys}`, hasCollapseButton];+ if (row.type === "array")+ return [keyStr, `[${row.childrenCount ?? 0} items]`, hasCollapseButton];if (row.value === null) return [keyStr, "null"];return [keyStr, `${row.value}`];diff --git a/packages/jsoncrack-react/src/utils/calculateNodeSize.ts b/packages/jsoncrack-react/src/utils/calculateNodeSize.tsindex 969825ae..d750d426 100644--- a/packages/jsoncrack-react/src/utils/calculateNodeSize.ts+++ b/packages/jsoncrack-react/src/utils/calculateNodeSize.ts@@ -1,58 +1,88 @@+import { isColorFormat } from "./colorFormat";+const NODE_DIMENSIONS = {ROW_HEIGHT: 30,PARENT_HEIGHT: 36,} as const;-type Text = number | string | [string, string][];+// .collapseButton in Node.module.css: 14px width + 2x1px border + 6px right margin+const COLLAPSE_BUTTON_WIDTH = 22;++// .colorPreview in TextRenderer.module.css: 12px width + 2x1px border + 4px flex gap+const COLOR_PREVIEW_WIDTH = 18;++// Must match .foreignObject in Node.module.css+const NODE_FONT_FAMILY =+ 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';++export type NodeTextRow = [string, string, boolean?];+type Text = number | string | NodeTextRow[];type Size = { width: number; height: number };+type Line = { text: string; extraWidth: number };const CACHE_TTL_MS = 120_000;const sizeCache = new Map<string, Size>();let lastCacheClearAt = Date.now();-const calculateLines = (text: Text): string => {+const calculateLines = (text: Text): Line[] => {if (Array.isArray(text)) {- return text.map(([k, v]) => `${k}: ${JSON.stringify(v).slice(0, 80)}`).join("\n");+ return text.map(([k, v, hasCollapseButton]) => {+ let extraWidth = hasCollapseButton ? COLLAPSE_BUTTON_WIDTH : 0;+ if (isColorFormat(v)) extraWidth += COLOR_PREVIEW_WIDTH;++ return {+ text: `${k}: ${v.slice(0, 80)}`,+ extraWidth,+ };+ });}- return `${text}`;+ return `${text}`.split("\n").map(line => ({ text: line, extraWidth: 0 }));};-const fallbackSize = (str: string, single: boolean): Size => {- const lines = str.split("\n");- const longestLine = lines.reduce((max, line) => Math.max(max, line.length), 0);+const fallbackSize = (lines: Line[], single: boolean): Size => {+ const longestLine = lines.reduce(+ (max, line) => Math.max(max, line.text.length * 8 + line.extraWidth),+ 0+ );return {- width: Math.min(700, Math.max(45, longestLine * 8 + 24)),+ width: Math.min(700, Math.max(45, longestLine + 24)),height: single ? NODE_DIMENSIONS.PARENT_HEIGHT : lines.length * NODE_DIMENSIONS.ROW_HEIGHT,};};-const calculateWidthAndHeight = (str: string, single = false): Size => {- if (!str) return { width: 45, height: 45 };+const calculateWidthAndHeight = (lines: Line[], single = false): Size => {+ if (lines.every(line => !line.text)) return { width: 45, height: 45 };if (typeof document === "undefined") {- return fallbackSize(str, single);+ return fallbackSize(lines, single);}const dummyElement = document.createElement("div");dummyElement.style.position = "absolute";dummyElement.style.visibility = "hidden";dummyElement.style.pointerEvents = "none";- dummyElement.style.whiteSpace = single ? "nowrap" : "pre-wrap";- dummyElement.innerText = str;dummyElement.style.fontSize = "12px";dummyElement.style.width = "fit-content";dummyElement.style.padding = "0 10px";dummyElement.style.fontWeight = "500";- dummyElement.style.fontFamily = "monospace";- document.body.appendChild(dummyElement);+ dummyElement.style.fontFamily = NODE_FONT_FAMILY;++ for (const line of lines) {+ const lineElement = document.createElement("div");+ lineElement.style.whiteSpace = "nowrap";+ lineElement.style.width = "fit-content";+ if (line.extraWidth > 0) lineElement.style.paddingRight = `${line.extraWidth}px`;+ lineElement.textContent = line.text;+ dummyElement.appendChild(lineElement);+ }+ document.body.appendChild(dummyElement);const clientRect = dummyElement.getBoundingClientRect();- const lines = str.split("\n").length;const width = clientRect.width + 4;- const height = single ? NODE_DIMENSIONS.PARENT_HEIGHT : lines * NODE_DIMENSIONS.ROW_HEIGHT;+ const height = single ? NODE_DIMENSIONS.PARENT_HEIGHT : lines.length * NODE_DIMENSIONS.ROW_HEIGHT;document.body.removeChild(dummyElement);return { width, height };diff --git a/packages/jsoncrack-react/src/utils/colorFormat.ts b/packages/jsoncrack-react/src/utils/colorFormat.tsnew file mode 100644index 00000000..6626d383--- /dev/null+++ b/packages/jsoncrack-react/src/utils/colorFormat.ts@@ -0,0 +1,11 @@+const HEX_CODE_PATTERN = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;+const RGB_PATTERN = /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/;+const RGBA_PATTERN = /^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(0|1|0\.\d+)\s*\)$/;++export const isColorFormat = (colorString: string) => {+ return (+ HEX_CODE_PATTERN.test(colorString) ||+ RGB_PATTERN.test(colorString) ||+ RGBA_PATTERN.test(colorString)+ );+};