All files App.tsx

6.77% Statements 4/59
0% Branches 0/56
0% Functions 0/13
6.77% Lines 4/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                1x 1x             1x                           1x                                                                                                                                                                                                                                                                                              
import React, { useCallback, useEffect, useRef} from 'react';
import Split from '@uiw/react-split';
import GitHubCorners from '@uiw/react-github-corners';
import JsonViewer from '@uiw/react-json-view';
import CodeMirror, { ReactCodeMirrorRef } from '@uiw/react-codemirror';
import { json as jsonLang } from '@codemirror/lang-json';
import { createHashHistory } from 'history';
import styles from './App.module.css';
 
type Parameters = {
  json?: string;
  cornerhref?: string;
  hidenheader?: '1' | '0';
  corner?: '1' | '0';
  view?: 'preview'| 'editor';
}
const history = createHashHistory();
const getURLParameters = (url: string): Parameters =>
  ((url.match(/([^?=&]+)(=([^&]*))/g) || []) as any).reduce(
    (a: any, v: string) => (
      ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a)
    ),
    {}
  );
const objectToQueryString = (queryParameters: Parameters) => {
  return queryParameters
    ? Object.entries(queryParameters).reduce(
        (queryString, [key, val], index) => {
          const symbol = queryString.length === 0 ? '?' : '&';
          queryString +=
            typeof val === 'string' ? `${symbol}${key}=${val}` : '';
          return queryString;
        },
        ''
      )
    : '';
};
 
const App = () => {
  const param = getURLParameters(window.location.href);
  const cmRef = useRef<ReactCodeMirrorRef>(null);
  param.json = param.json ? decodeURI(param.json): undefined;
  const [code, setCode] = React.useState(decodeURIComponent(param.json || ''));
  const [json, setJson] = React.useState();
  const [message, setMessage] = React.useState('');
  const [linebar, setLinebar] = React.useState('');
  
  const handleJson = useCallback(() => {
    setMessage('');
    try {
      if (code) {
        const obj = JSON.parse(code);
        setJson(obj);
      }
    } catch (error) {
      if (error instanceof Error) {
        setMessage(error.message);
        setJson(undefined)
      } else {
        throw error;
      }
    }
  }, [code]);
  const formatJson = useCallback((_: any, replacer: number = 2) => {
    setMessage('');
    try {
      if (code) {
        const obj = JSON.parse(code);
        const str = JSON.stringify(obj, null, replacer);
        setCode(str);
      }
    } catch (error) {
      if (error instanceof Error) {
        setMessage(error.message);
        setJson(undefined)
      } else {
        throw error;
      }
    }
  }, [code]);
 
  const shareJson = () => {
    param.json = encodeURI(code);
    history.push(`${objectToQueryString(param)}`, { some: "state" });
  }
 
  useEffect(() => {
    handleJson()
  }, [code, handleJson]);
 
  const editor = (
    <div style={{ minWidth: 230, width: param.view === 'editor' ? '100%' : '45%', position: 'relative', backgroundColor: 'rgb(245, 245, 245)' }}>
      <div style={{overflow: 'auto',height: '100%', boxSizing: 'border-box' }}>
        <CodeMirror
          value={code}
          ref={cmRef}
          height="100%"
          style={{ height: '100%' }}
          extensions={[jsonLang()]}
          onUpdate={(cm) => {
            if (param.hidenheader === '1') {
              return;
            }
            const { selection } = cm.state;
            const line = cm.view.state.doc.lineAt(selection.main.from);
            setLinebar(`Line ${line.number}/${cm.state.doc.lines}, Column ${cm.state.selection.main.head - line.from + 1}`);
            const text = cm.state.sliceDoc(selection.main.from, selection.main.to);
            if (text) {
              if (selection.ranges.length > 1) {
                setLinebar(`${selection.ranges.length} selection regions`);
              } else {
                setLinebar(`${text.split('\n').length} lines, ${text.length} characters selected`);
              }
            }
          }}
          onChange={(value, viewUpdate) => {
            setCode(value)
          }}
        />
      </div>
    </div>
  );
 
  const preview = (
    <div style={{ flex: 1, minWidth: 230, userSelect: 'none', padding: 10, overflow: 'auto' }}>
      {message && (
        <pre style={{ padding: 0, margin: 0, color: 'red' }}>
          {message}
        </pre>
      )}
      {json && typeof json == 'object' && (
        <JsonViewer value={json!} style={{  }} displayDataTypes={false} />
      )}
    </div>
  );
  return (
    <div className={styles.app}>
      {!Number(param.corner) && (
        <GitHubCorners fixed zIndex={999} size={43} target="__blank" href={param.cornerhref ? param.cornerhref : 'https://github.com/uiwjs/json-viewer'} />
      )}
      <Split mode="vertical" visiable={false}>
        {param.hidenheader !== '1' && (
          <div className={styles.header} style={{  }}>
            <h1>JSON Viewer</h1>
            <div className={styles.toolbar}>
              <div>
                {linebar && (
                  <span> {linebar} </span>
                )}
              </div>
              {message && (
                <div className={styles.message}>{message}</div>
              )}
              <div className={styles.btn}>
                <button onClick={formatJson}>
                  Format
                </button>
                <button onClick={() => formatJson(null, 0)}>
                  Compress
                </button>
                {code && (
                  <button onClick={() => shareJson()}>
                    Share
                  </button>
                )}
              </div>
            </div>
          </div>
        )}
        <Split style={{ flex: 1, height: param.hidenheader !== '1' ? 'calc(100% - 32px)' : '100%' }}>
          {!param.view && editor}
          {!param.view && preview}
          {param.view === 'editor' && editor}
          {param.view === 'preview' && preview}
        </Split>
      </Split>
    </div>
  )
};
 
export default App;