JsonFormatter.jsx 10.7 KB
Newer Older
fisherdaddy's avatar
fisherdaddy committed
1
import React, { useState, useEffect } from 'react';
2
import { useTranslation } from '../js/i18n';
fisherdaddy's avatar
fisherdaddy committed
3
import SEO from '../components/SEO';
4
import styled from 'styled-components';
fisherdaddy's avatar
fisherdaddy committed
5 6
import { usePageLoading } from '../hooks/usePageLoading';
import LoadingOverlay from './LoadingOverlay';
fisherdaddy's avatar
fisherdaddy committed
7

8 9 10
const Container = styled.div`
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7ff 0%, #ffffff 100%);
fisherdaddy's avatar
fisherdaddy committed
11
  padding: 6rem 2rem 2rem;
fisherdaddy's avatar
fisherdaddy committed
12 13
  position: relative;
  
14 15 16 17 18 19 20 21 22 23 24 25
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: 
      linear-gradient(90deg, rgba(99, 102, 241, 0.05) 1px, transparent 1px),
      linear-gradient(rgba(99, 102, 241, 0.05) 1px, transparent 1px);
    background-size: 20px 20px;
    pointer-events: none;
26
  }
fisherdaddy's avatar
fisherdaddy committed
27
`;
28

29 30 31 32 33
const ContentWrapper = styled.div`
  max-width: 1400px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
34 35
`;

36 37 38 39 40 41 42 43 44
const Title = styled.h2`
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
  background: linear-gradient(135deg, #6366F1 0%, #4F46E5 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: 700;
  letter-spacing: -0.02em;
  text-align: center;
45 46
`;

fisherdaddy's avatar
fisherdaddy committed
47
function JsonFormatter() {
48
  const { t } = useTranslation();
fisherdaddy's avatar
fisherdaddy committed
49 50
  const [input, setInput] = useState('');
  const [parsedJson, setParsedJson] = useState(null);
51
  const [isCopied, setIsCopied] = useState(false);
fisherdaddy's avatar
fisherdaddy committed
52
  const [isCompressed, setIsCompressed] = useState(false);
fisherdaddy's avatar
fisherdaddy committed
53
  const isLoading = usePageLoading();
fisherdaddy's avatar
fisherdaddy committed
54 55 56

  useEffect(() => {
    try {
57 58 59 60 61 62
      if (input.trim()) {
        const parsed = JSON.parse(input);
        setParsedJson(parsed);
      } else {
        setParsedJson(null);
      }
fisherdaddy's avatar
fisherdaddy committed
63 64 65 66 67
    } catch (error) {
      setParsedJson(null);
    }
  }, [input]);

68 69
  const handleCopy = () => {
    if (parsedJson) {
fisherdaddy's avatar
fisherdaddy committed
70 71 72
      const formattedJson = isCompressed 
        ? JSON.stringify(parsedJson)
        : JSON.stringify(parsedJson, null, 2);
73 74 75 76 77 78 79
      navigator.clipboard.writeText(formattedJson).then(() => {
        setIsCopied(true);
        setTimeout(() => setIsCopied(false), 2000);
      });
    }
  };

fisherdaddy's avatar
fisherdaddy committed
80 81 82 83
  const toggleCompression = () => {
    setIsCompressed(!isCompressed);
  };

fisherdaddy's avatar
fisherdaddy committed
84
  return (
fisherdaddy's avatar
fisherdaddy committed
85
    <>
fisherdaddy's avatar
fisherdaddy committed
86
      {isLoading && <LoadingOverlay />}
fisherdaddy's avatar
fisherdaddy committed
87
      <SEO
fisherdaddy's avatar
fisherdaddy committed
88 89 90
        title={t('tools.jsonFormatter.title')}
        description={t('tools.jsonFormatter.description')}
      />
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
      <Container>
        <ContentWrapper>
          <Title>{t('tools.jsonFormatter.title')}</Title>
          
          <div className="flex flex-col lg:flex-row gap-4 lg:gap-6 h-[calc(100vh-220px)]">
            <textarea
              className="w-full lg:w-5/12 p-4 text-sm font-mono border border-indigo-100 rounded-xl bg-white/80 backdrop-blur-sm focus:border-indigo-300 focus:ring-4 focus:ring-indigo-100 outline-none resize-none transition duration-300"
              placeholder={t('tools.jsonFormatter.inputPlaceholder')}
              value={input}
              onChange={(e) => setInput(e.target.value)}
            />
            
            <div className="w-full lg:w-7/12 relative border border-indigo-100 rounded-xl bg-white/80 backdrop-blur-sm p-4">
              {parsedJson ? (
                <>
                  <div className="font-mono text-sm leading-relaxed overflow-auto">
fisherdaddy's avatar
fisherdaddy committed
107
                    {isCompressed ? (
108 109 110
                      <pre className="m-0 whitespace-nowrap">
                        {JSON.stringify(parsedJson)}
                      </pre>
fisherdaddy's avatar
fisherdaddy committed
111
                    ) : (
112
                      <JsonView data={parsedJson} />
fisherdaddy's avatar
fisherdaddy committed
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
                  </div>
                  <div className="absolute top-4 right-4 flex gap-2">
                    <button
                      onClick={toggleCompression}
                      className={`
                        flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-lg transition-all duration-200 
                        ${isCompressed
                          ? 'bg-indigo-100 text-indigo-700'
                          : 'bg-white/50 hover:bg-indigo-50 text-gray-600 hover:text-indigo-600'
                        }
                      `}
                    >
                      {isCompressed ? (
                        <>
                          <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M4 9h16v2H4V9zm0 4h16v2H4v-2z"/>
                          </svg>
                          {t('tools.jsonFormatter.expand')}
                        </>
                      ) : (
                        <>
                          <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M19 13H5v-2h14v2z"/>
                          </svg>
                          {t('tools.jsonFormatter.compress')}
                        </>
                      )}
                    </button>
                    <button
                      onClick={handleCopy}
                      className={`
                        flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-lg transition-all duration-200 
                        ${isCopied
                          ? 'bg-green-100 text-green-700'
                          : 'bg-white/50 hover:bg-indigo-50 text-gray-600 hover:text-indigo-600'
                        }
                      `}
                    >
                      {isCopied ? (
                        <>
                          <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
                          </svg>
                          {t('tools.jsonFormatter.copied')}
                        </>
                      ) : (
                        <>
                          <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
                          </svg>
                          {t('tools.jsonFormatter.copy')}
                        </>
                      )}
                    </button>
                  </div>
                </>
              ) : (
                <div className="p-4 text-gray-500">
                  {input.trim() ? t('tools.jsonFormatter.invalidJson') : t('tools.jsonFormatter.emptyInput')}
                </div>
              )}
            </div>
          </div>
        </ContentWrapper>
      </Container>
fisherdaddy's avatar
fisherdaddy committed
179
    </>
fisherdaddy's avatar
fisherdaddy committed
180 181 182 183
  );
}

function JsonView({ data }) {
184 185 186
  if (data === null || data === undefined) return null;

  const [collapsedKeys, setCollapsedKeys] = useState(new Set());
fisherdaddy's avatar
fisherdaddy committed
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
  const toggleCollapse = (key) => {
    const newCollapsedKeys = new Set(collapsedKeys);
    if (newCollapsedKeys.has(key)) {
      newCollapsedKeys.delete(key);
    } else {
      newCollapsedKeys.add(key);
    }
    setCollapsedKeys(newCollapsedKeys);
  };

  const renderCollapsibleValue = (value, path = '') => {
    if (value === null) return <span className="text-indigo-400">null</span>;
    if (typeof value === 'boolean') return <span className="text-indigo-400">{value.toString()}</span>;
    if (typeof value === 'number') return <span className="text-emerald-500">{value}</span>;
    if (typeof value === 'string') return <span className="text-amber-500">"{value}"</span>;

    const isCollapsed = collapsedKeys.has(path);
    const hasChildren = Array.isArray(value) || (typeof value === 'object' && value !== null);

    if (Array.isArray(value)) {
      if (isCollapsed) {
        return (
          <div className="inline-flex items-center gap-1">
            <button 
              onClick={() => toggleCollapse(path)}
              className="w-4 h-4 inline-flex items-center justify-center text-gray-500 hover:text-gray-700"
            >
              <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
            </button>
            <span className="text-gray-500">[...]</span>
            <span className="text-gray-400 text-sm ml-1">({value.length} items)</span>
          </div>
        );
      }
      return (
        <div className="ml-5">
          <div className="inline-flex items-center gap-1">
            <button 
              onClick={() => toggleCollapse(path)}
              className="w-4 h-4 inline-flex items-center justify-center text-gray-500 hover:text-gray-700"
            >
              <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
              </svg>
            </button>
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
          </div>
          {value.map((item, index) => (
            <div key={index} className="ml-5">
              {renderCollapsibleValue(item, `${path}[${index}]`)}
              {index < value.length - 1 ? ',' : ''}
            </div>
          ))}
          <div>]</div>
        </div>
      );
    }

    if (typeof value === 'object') {
      const entries = Object.entries(value);
      if (isCollapsed) {
        return (
          <div className="inline-flex items-center gap-1">
            <button 
              onClick={() => toggleCollapse(path)}
              className="w-4 h-4 inline-flex items-center justify-center text-gray-500 hover:text-gray-700"
            >
              <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
            </button>
            <span className="text-gray-500">{'{...}'}</span>
            <span className="text-gray-400 text-sm ml-1">({entries.length} properties)</span>
          </div>
        );
      }
      return (
        <div className="ml-5">
          <div className="inline-flex items-center gap-1">
            <button 
              onClick={() => toggleCollapse(path)}
              className="w-4 h-4 inline-flex items-center justify-center text-gray-500 hover:text-gray-700"
            >
              <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
              </svg>
            </button>
277
            {'{'}
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
          </div>
          {entries.map(([key, val], index) => (
            <div key={key} className="ml-5">
              <span className="text-pink-500">"{key}"</span>: {renderCollapsibleValue(val, `${path}.${key}`)}
              {index < entries.length - 1 ? ',' : ''}
            </div>
          ))}
          <div>{'}'}</div>
        </div>
      );
    }
    return value;
  };

  return renderCollapsibleValue(data, 'root');
fisherdaddy's avatar
fisherdaddy committed
293 294 295
}

export default JsonFormatter;