mirror of
https://github.com/ritz078/transform.git
synced 2026-11-21 00:32:56 +03:00
fixed firefox issue
This commit is contained in:
1 parent
d4f91dd2b9
commit
6d2d298102
18 files changed
+286
-243
No files matched your search
@@ -77,7 +77,7 @@ export default class ConversionPanel extends PureComponent {
|
||||
prettifyRightPanel: true,
|
||||
splitLeft: false,
|
||||
showFetchButton: true,
|
||||
fetchButtonText: 'Fetch JSON from URL'
|
||||
fetchButtonText: "Fetch JSON from URL"
|
||||
};
|
||||
|
||||
state = {
|
||||
@@ -91,23 +91,23 @@ export default class ConversionPanel extends PureComponent {
|
||||
componentDidMount() {
|
||||
const { defaultText, splitValue } = this.props;
|
||||
|
||||
this.onChange(defaultText, splitValue)
|
||||
this.onChange(defaultText, splitValue);
|
||||
}
|
||||
|
||||
fetchJSON = async () => {
|
||||
const url = window.prompt('Enter URL to fetch JSON from a remote server.')
|
||||
if (!url) return
|
||||
const url = window.prompt("Enter URL to fetch JSON from a remote server.");
|
||||
if (!url) return;
|
||||
try {
|
||||
const res = await unfetch(url)
|
||||
const json = await res.json()
|
||||
this.onChange(JSON.stringify(json, null, 2))
|
||||
const res = await unfetch(url);
|
||||
const json = await res.json();
|
||||
this.onChange(JSON.stringify(json, null, 2));
|
||||
} catch (e) {
|
||||
this.setState({
|
||||
info: e.message,
|
||||
infoType: "error"
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
onChange = async (newValue, leftSplitValue) => {
|
||||
const nValue = newValue || this.state.value;
|
||||
@@ -140,7 +140,7 @@ export default class ConversionPanel extends PureComponent {
|
||||
const checked = e.currentTarget.checked;
|
||||
if (this.props.onCheckboxChange) {
|
||||
this.props.onCheckboxChange(checked, () => {
|
||||
this.onChange()
|
||||
this.onChange();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -238,13 +238,14 @@ export default class ConversionPanel extends PureComponent {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.section {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.right {
|
||||
@@ -314,7 +315,7 @@ export default class ConversionPanel extends PureComponent {
|
||||
}
|
||||
|
||||
.react-codemirror2 {
|
||||
overflow: scroll
|
||||
overflow: scroll;
|
||||
}
|
||||
|
||||
.react-codemirror2,
|
||||
@@ -338,7 +339,7 @@ export default class ConversionPanel extends PureComponent {
|
||||
.split .CodeMirror {
|
||||
}
|
||||
.right .react-codemirror2 {
|
||||
background-color: #fafafa;
|
||||
background-color: #fafafa;
|
||||
}
|
||||
|
||||
.right .CodeMirror {
|
||||
@@ -371,7 +372,12 @@ export default class ConversionPanel extends PureComponent {
|
||||
<div className="panel">
|
||||
<div className="header">
|
||||
<h4 className="title">{leftTitle}</h4>
|
||||
{leftMode === 'json' && showFetchButton && <button className="btn" onClick={this.fetchJSON}>{fetchButtonText}</button>}
|
||||
{leftMode === "json" &&
|
||||
showFetchButton && (
|
||||
<button className="btn" onClick={this.fetchJSON}>
|
||||
{fetchButtonText}
|
||||
</button>
|
||||
)}
|
||||
<button className="btn" onClick={this.prettifyCode}>
|
||||
Prettify
|
||||
</button>
|
||||
@@ -407,41 +413,41 @@ export default class ConversionPanel extends PureComponent {
|
||||
</div>
|
||||
<div className="section right">
|
||||
<div className="panel">
|
||||
<div className="header">
|
||||
<h4 className="title">{rightTitle}</h4>
|
||||
{onCheckboxChange && (
|
||||
<label htmlFor="#text">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="#text"
|
||||
defaultChecked={initialCheckboxValue}
|
||||
onChange={this.toggleCheckbox}
|
||||
/>{" "}
|
||||
{checkboxText}
|
||||
</label>
|
||||
<div className="header">
|
||||
<h4 className="title">{rightTitle}</h4>
|
||||
{onCheckboxChange && (
|
||||
<label htmlFor="#text">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="#text"
|
||||
defaultChecked={initialCheckboxValue}
|
||||
onChange={this.toggleCheckbox}
|
||||
/>{" "}
|
||||
{checkboxText}
|
||||
</label>
|
||||
)}
|
||||
<button className="btn" onClick={this.copyCode}>
|
||||
Copy
|
||||
</button>
|
||||
</div>
|
||||
{isBrowser && (
|
||||
<CodeMirror
|
||||
value={
|
||||
prettifyRightPanel ? (
|
||||
js_beautify(resultValue, { e4x: true })
|
||||
) : (
|
||||
resultValue
|
||||
)
|
||||
}
|
||||
options={{
|
||||
readOnly: true,
|
||||
mode: modeMapping[rightMode] || rightMode,
|
||||
...codeMirrorOptions,
|
||||
lineNumbers: false
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<button className="btn" onClick={this.copyCode}>
|
||||
Copy
|
||||
</button>
|
||||
</div>
|
||||
{isBrowser && (
|
||||
<CodeMirror
|
||||
value={
|
||||
prettifyRightPanel ? (
|
||||
js_beautify(resultValue, { e4x: true })
|
||||
) : (
|
||||
resultValue
|
||||
)
|
||||
}
|
||||
options={{
|
||||
readOnly: true,
|
||||
mode: modeMapping[rightMode] || rightMode,
|
||||
...codeMirrorOptions,
|
||||
lineNumbers: false
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={`footer${infoType ? " has-" + infoType : ""}`}>
|
||||
|
||||
+20
-15
@@ -88,8 +88,8 @@ export default class Layout extends PureComponent {
|
||||
this.setKey(this.props.pathname);
|
||||
}
|
||||
|
||||
componentDidMount () {
|
||||
routes.forEach(({path}) => Router.prefetch(path))
|
||||
componentDidMount() {
|
||||
routes.forEach(({ path }) => Router.prefetch(path));
|
||||
}
|
||||
|
||||
componentWillReceiveProps({ pathname }) {
|
||||
@@ -131,19 +131,24 @@ export default class Layout extends PureComponent {
|
||||
href="https://cdnjs.cloudflare.com/ajax/libs/font-mfizz/2.4.1/font-mfizz.min.css"
|
||||
/>
|
||||
<link rel="stylesheet" href="/static/styles.css" />
|
||||
<link rel="manifest" href="/static/manifest.json"/>
|
||||
<meta name="theme-color" content="#2196f3"/>
|
||||
<meta name="mobile-web-app-capable" content="yes"/>
|
||||
<meta name="apple-mobile-web-app-capable" content="yes"/>
|
||||
<meta name="application-name" content="Transform"/>
|
||||
<meta name="apple-mobile-web-app-title" content="Transform"/>
|
||||
<meta name="theme-color" content="#2196f3"/>
|
||||
<meta name="msapplication-navbutton-color" content="#2196f3"/>
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/>
|
||||
<meta name="msapplication-starturl" content="./"/>
|
||||
<meta name="msapplication-TileColor" content="#2196f3"/>
|
||||
<meta name="msapplication-TileImage" content="/static/images/icons/icon-144x144.png"/>
|
||||
|
||||
<link rel="manifest" href="/static/manifest.json" />
|
||||
<meta name="theme-color" content="#2196f3" />
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="application-name" content="Transform" />
|
||||
<meta name="apple-mobile-web-app-title" content="Transform" />
|
||||
<meta name="theme-color" content="#2196f3" />
|
||||
<meta name="msapplication-navbutton-color" content="#2196f3" />
|
||||
<meta
|
||||
name="apple-mobile-web-app-status-bar-style"
|
||||
content="black-translucent"
|
||||
/>
|
||||
<meta name="msapplication-starturl" content="./" />
|
||||
<meta name="msapplication-TileColor" content="#2196f3" />
|
||||
<meta
|
||||
name="msapplication-TileImage"
|
||||
content="/static/images/icons/icon-144x144.png"
|
||||
/>
|
||||
</Head>
|
||||
<style jsx>{`
|
||||
.sidebar {
|
||||
|
||||
+2
-2
@@ -30,8 +30,8 @@ export default class Css2Js extends PureComponent {
|
||||
isRn: false
|
||||
};
|
||||
|
||||
getTransformedValue = (newValue) => {
|
||||
return cssToJS(newValue, this.state.isRn)
|
||||
getTransformedValue = newValue => {
|
||||
return cssToJS(newValue, this.state.isRn);
|
||||
};
|
||||
|
||||
render() {
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { PureComponent } from "react";
|
||||
import Layout from "../components/Layout";
|
||||
import ConversionPanel from "../components/ConversionPanel";
|
||||
import { dummySchema, dummyQuery } from "../utils/graphql-schema";
|
||||
import transform from "transform-graphql-type-annotations"
|
||||
import transform from "transform-graphql-type-annotations";
|
||||
|
||||
export default class Json2Ts extends PureComponent {
|
||||
getTransformedValue = (newValue, splitValue) => {
|
||||
|
||||
@@ -6,7 +6,7 @@ import { dummySchema, dummyQuery } from "../utils/graphql-schema";
|
||||
|
||||
export default class Json2Ts extends PureComponent {
|
||||
getTransformedValue = (newValue, splitValue) => {
|
||||
return transform(newValue, splitValue, 'typescript');
|
||||
return transform(newValue, splitValue, "typescript");
|
||||
};
|
||||
|
||||
render() {
|
||||
|
||||
+10
-4
@@ -1,9 +1,9 @@
|
||||
import React, { PureComponent } from "react";
|
||||
import HTMLtoJSX from "@tsuyoshiwada/htmltojsx";
|
||||
import convertSvgString from "transform-svg-to-native"
|
||||
import convertSvgString from "transform-svg-to-native";
|
||||
import Layout from "../components/Layout";
|
||||
import ConversionPanel from "../components/ConversionPanel";
|
||||
import isSvg from "is-svg"
|
||||
import isSvg from "is-svg";
|
||||
|
||||
const converter = new HTMLtoJSX({
|
||||
createClass: false
|
||||
@@ -20,10 +20,16 @@ export default class Css2Js extends PureComponent {
|
||||
|
||||
getTransformedValue = async (newValue: string) => {
|
||||
if (this.state.native && !isSvg(newValue)) {
|
||||
throw new Error('You can only convert an SVG in this mode. Try turning off the react-native-svg checkbox.')
|
||||
throw new Error(
|
||||
"You can only convert an SVG in this mode. Try turning off the react-native-svg checkbox."
|
||||
);
|
||||
}
|
||||
|
||||
return this.state.native ? new Promise(resolve => convertSvgString(newValue, (code) => resolve(code))) : converter.convert(newValue)
|
||||
return this.state.native
|
||||
? new Promise(resolve =>
|
||||
convertSvgString(newValue, code => resolve(code))
|
||||
)
|
||||
: converter.convert(newValue);
|
||||
};
|
||||
|
||||
render() {
|
||||
|
||||
+6
-5
@@ -4,7 +4,7 @@ import immutablePropsPlugin from "../utils/babel-plugin-js-to-immutable-prop-typ
|
||||
import Layout from "../components/Layout";
|
||||
import { transform } from "babel-standalone";
|
||||
import defaultText from "../utils/dummy-json";
|
||||
import merge from "lodash/merge"
|
||||
import merge from "lodash/merge";
|
||||
|
||||
import ConversionPanel from "../components/ConversionPanel";
|
||||
|
||||
@@ -14,17 +14,18 @@ export default class Main extends PureComponent {
|
||||
};
|
||||
|
||||
getTransformedValue = newValue => {
|
||||
let x = JSON.parse(newValue)
|
||||
let x = JSON.parse(newValue);
|
||||
if (typeof x !== "object" || Array.isArray(x)) {
|
||||
x = merge({}, ...x)
|
||||
x = merge({}, ...x);
|
||||
}
|
||||
x = "const propTypes = " + JSON.stringify(x);
|
||||
const plugin = this.state.isImmutable ? immutablePropsPlugin : jsonToProptypes;
|
||||
const plugin = this.state.isImmutable
|
||||
? immutablePropsPlugin
|
||||
: jsonToProptypes;
|
||||
const { code } = transform(x, {
|
||||
plugins: [plugin]
|
||||
});
|
||||
|
||||
|
||||
return `import PropTypes from "prop-types";
|
||||
|
||||
${code}`;
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import React, { PureComponent } from "react";
|
||||
import Layout from "../components/Layout";
|
||||
import stringify from "stringify-object"
|
||||
import stringify from "stringify-object";
|
||||
import ConversionPanel from "../components/ConversionPanel";
|
||||
import text from "../utils/dummy-object-json"
|
||||
import text from "../utils/dummy-object-json";
|
||||
|
||||
const defaultText = stringify(eval(`(${text})`))
|
||||
const defaultText = stringify(eval(`(${text})`));
|
||||
|
||||
export default class Main extends PureComponent {
|
||||
|
||||
getTransformedValue = newValue => {
|
||||
return JSON.stringify(eval('(' + newValue + ')'), null ,2)
|
||||
return JSON.stringify(eval("(" + newValue + ")"), null, 2);
|
||||
};
|
||||
|
||||
render() {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { PureComponent } from "react";
|
||||
import Layout from "../components/Layout";
|
||||
import ConversionPanel from "../components/ConversionPanel";
|
||||
import { compile } from "json-schema-to-typescript"
|
||||
import { compile } from "json-schema-to-typescript";
|
||||
|
||||
const json = `{
|
||||
title: 'Example Schema',
|
||||
@@ -29,10 +29,10 @@ const json = `{
|
||||
}
|
||||
},
|
||||
required: ['firstName', 'lastName']
|
||||
}`
|
||||
}`;
|
||||
|
||||
export default class Json2Ts extends PureComponent {
|
||||
getTransformedValue = code => compile(eval('(' + code + ')'))
|
||||
getTransformedValue = code => compile(eval("(" + code + ")"));
|
||||
|
||||
render() {
|
||||
return (
|
||||
@@ -51,4 +51,4 @@ export default class Json2Ts extends PureComponent {
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,10 @@ import dynamic from "next/dynamic";
|
||||
import Layout from "../components/Layout";
|
||||
import ConversionPanel from "../components/ConversionPanel";
|
||||
import defaultText from "../utils/dummy-json";
|
||||
import transform from "transform-json-types"
|
||||
import transform from "transform-json-types";
|
||||
|
||||
export default class Json2Ts extends PureComponent {
|
||||
getTransformedValue = code => transform(code)
|
||||
getTransformedValue = code => transform(code);
|
||||
|
||||
render() {
|
||||
return (
|
||||
|
||||
+4
-4
@@ -3,11 +3,11 @@ import dynamic from "next/dynamic";
|
||||
import Layout from "../components/Layout";
|
||||
import ConversionPanel from "../components/ConversionPanel";
|
||||
import defaultText from "../utils/dummy-json";
|
||||
import json2go from "../utils/json-to-go"
|
||||
import gofmt from "gofmt.js"
|
||||
import json2go from "../utils/json-to-go";
|
||||
import gofmt from "gofmt.js";
|
||||
|
||||
export default class extends PureComponent {
|
||||
getTransformedValue = code => gofmt(json2go(code).go)
|
||||
getTransformedValue = code => gofmt(json2go(code).go);
|
||||
|
||||
render() {
|
||||
return (
|
||||
@@ -26,4 +26,4 @@ export default class extends PureComponent {
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,12 @@ import React, { PureComponent } from "react";
|
||||
import Layout from "../components/Layout";
|
||||
import ConversionPanel from "../components/ConversionPanel";
|
||||
import defaultText from "../utils/dummy-json";
|
||||
import transform from "transform-json-types"
|
||||
import transform from "transform-json-types";
|
||||
export default class Json2Ts extends PureComponent {
|
||||
getTransformedValue = code => transform(code, {
|
||||
lang: 'rust-serde'
|
||||
})
|
||||
getTransformedValue = code =>
|
||||
transform(code, {
|
||||
lang: "rust-serde"
|
||||
});
|
||||
|
||||
render() {
|
||||
return (
|
||||
|
||||
@@ -2,11 +2,12 @@ import React, { PureComponent } from "react";
|
||||
import Layout from "../components/Layout";
|
||||
import ConversionPanel from "../components/ConversionPanel";
|
||||
import defaultText from "../utils/dummy-json";
|
||||
import transform from "transform-json-types"
|
||||
import transform from "transform-json-types";
|
||||
export default class Json2Ts extends PureComponent {
|
||||
getTransformedValue = code => transform(code, {
|
||||
lang: "scala"
|
||||
})
|
||||
getTransformedValue = code =>
|
||||
transform(code, {
|
||||
lang: "scala"
|
||||
});
|
||||
|
||||
render() {
|
||||
return (
|
||||
|
||||
@@ -3,12 +3,13 @@ import dynamic from "next/dynamic";
|
||||
import Layout from "../components/Layout";
|
||||
import ConversionPanel from "../components/ConversionPanel";
|
||||
import defaultText from "../utils/dummy-json";
|
||||
import transform from "transform-json-types"
|
||||
import transform from "transform-json-types";
|
||||
|
||||
export default class Json2Ts extends PureComponent {
|
||||
getTransformedValue = code => transform(code, {
|
||||
lang: "typescript"
|
||||
})
|
||||
getTransformedValue = code =>
|
||||
transform(code, {
|
||||
lang: "typescript"
|
||||
});
|
||||
|
||||
render() {
|
||||
return (
|
||||
|
||||
@@ -70,7 +70,9 @@ export default function({ types: t }) {
|
||||
|
||||
VariableDeclaration(path) {
|
||||
path.insertBefore(
|
||||
t.identifier(`import ImmutablePropTypes from 'react-immutable-proptypes'`)
|
||||
t.identifier(
|
||||
`import ImmutablePropTypes from 'react-immutable-proptypes'`
|
||||
)
|
||||
);
|
||||
},
|
||||
|
||||
|
||||
@@ -2184,4 +2184,4 @@ fragment heroFriends on Character {
|
||||
friends {
|
||||
name
|
||||
}
|
||||
}`;
|
||||
}`;
|
||||
+150
-132
@@ -7,209 +7,227 @@
|
||||
A simple utility to translate JSON into a Go type definition.
|
||||
*/
|
||||
|
||||
function jsonToGo (json, typename) {
|
||||
let data
|
||||
let scope
|
||||
let go = ''
|
||||
let tabs = 0
|
||||
function jsonToGo(json, typename) {
|
||||
let data;
|
||||
let scope;
|
||||
let go = "";
|
||||
let tabs = 0;
|
||||
|
||||
try {
|
||||
data = JSON.parse(json.replace(/\.0/g, '.1')) // hack that forces floats to stay as floats
|
||||
scope = data
|
||||
}
|
||||
catch (e) {
|
||||
data = JSON.parse(json.replace(/\.0/g, ".1")); // hack that forces floats to stay as floats
|
||||
scope = data;
|
||||
} catch (e) {
|
||||
return {
|
||||
go: '',
|
||||
go: "",
|
||||
error: e.message
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
typename = format(typename || 'AutoGenerated')
|
||||
append('type ' + typename + ' ')
|
||||
typename = format(typename || "AutoGenerated");
|
||||
append("type " + typename + " ");
|
||||
|
||||
parseScope(scope)
|
||||
parseScope(scope);
|
||||
|
||||
return {go: go}
|
||||
return { go: go };
|
||||
|
||||
function parseScope (scope) {
|
||||
let keyname
|
||||
if (typeof scope === 'object' && scope !== null) {
|
||||
function parseScope(scope) {
|
||||
let keyname;
|
||||
if (typeof scope === "object" && scope !== null) {
|
||||
if (Array.isArray(scope)) {
|
||||
let i
|
||||
let sliceType, scopeLength = scope.length
|
||||
let i;
|
||||
let sliceType,
|
||||
scopeLength = scope.length;
|
||||
|
||||
for (i = 0; i < scopeLength; i++) {
|
||||
const thisType = goType(scope[i])
|
||||
if (!sliceType)
|
||||
sliceType = thisType
|
||||
const thisType = goType(scope[i]);
|
||||
if (!sliceType) sliceType = thisType;
|
||||
else if (sliceType !== thisType) {
|
||||
sliceType = mostSpecificPossibleGoType(thisType, sliceType)
|
||||
if (sliceType === 'interface{}')
|
||||
break
|
||||
sliceType = mostSpecificPossibleGoType(thisType, sliceType);
|
||||
if (sliceType === "interface{}") break;
|
||||
}
|
||||
}
|
||||
|
||||
append('[]')
|
||||
if (sliceType === 'struct') {
|
||||
let k
|
||||
let keys
|
||||
const allFields = {}
|
||||
append("[]");
|
||||
if (sliceType === "struct") {
|
||||
let k;
|
||||
let keys;
|
||||
const allFields = {};
|
||||
|
||||
// for each field counts how many times appears
|
||||
for (i = 0; i < scopeLength; i++) {
|
||||
keys = Object.keys(scope[i])
|
||||
keys = Object.keys(scope[i]);
|
||||
for (k in keys) {
|
||||
keyname = keys[k]
|
||||
keyname = keys[k];
|
||||
if (!(keyname in allFields)) {
|
||||
allFields[keyname] = {
|
||||
value: scope[i][keyname],
|
||||
count: 0
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
allFields[keyname].count++
|
||||
allFields[keyname].count++;
|
||||
}
|
||||
}
|
||||
|
||||
// create a common struct with all fields found in the current array
|
||||
// omitempty dict indicates if a field is optional
|
||||
keys = Object.keys(allFields)
|
||||
let struct = {}, omitempty = {}
|
||||
keys = Object.keys(allFields);
|
||||
let struct = {},
|
||||
omitempty = {};
|
||||
for (k in keys) {
|
||||
keyname = keys[k]
|
||||
let elem = allFields[keyname]
|
||||
keyname = keys[k];
|
||||
let elem = allFields[keyname];
|
||||
|
||||
struct[keyname] = elem.value
|
||||
omitempty[keyname] = elem.count !== scopeLength
|
||||
struct[keyname] = elem.value;
|
||||
omitempty[keyname] = elem.count !== scopeLength;
|
||||
}
|
||||
|
||||
parseStruct(struct, omitempty) // finally parse the struct !!
|
||||
}
|
||||
else if (sliceType === 'slice') {
|
||||
parseScope(scope[0])
|
||||
}
|
||||
else
|
||||
append(sliceType || 'interface{}')
|
||||
parseStruct(struct, omitempty); // finally parse the struct !!
|
||||
} else if (sliceType === "slice") {
|
||||
parseScope(scope[0]);
|
||||
} else append(sliceType || "interface{}");
|
||||
} else {
|
||||
parseStruct(scope);
|
||||
}
|
||||
else {
|
||||
parseStruct(scope)
|
||||
}
|
||||
}
|
||||
else
|
||||
append(goType(scope))
|
||||
} else append(goType(scope));
|
||||
}
|
||||
|
||||
function parseStruct (scope, omitempty) {
|
||||
append('struct {\n')
|
||||
++tabs
|
||||
const keys = Object.keys(scope)
|
||||
function parseStruct(scope, omitempty) {
|
||||
append("struct {\n");
|
||||
++tabs;
|
||||
const keys = Object.keys(scope);
|
||||
for (const i in keys) {
|
||||
const keyname = keys[i]
|
||||
indent(tabs)
|
||||
append(format(keyname) + ' ')
|
||||
parseScope(scope[keyname])
|
||||
const keyname = keys[i];
|
||||
indent(tabs);
|
||||
append(format(keyname) + " ");
|
||||
parseScope(scope[keyname]);
|
||||
|
||||
append(' `json:"' + keyname)
|
||||
append(' `json:"' + keyname);
|
||||
if (omitempty && omitempty[keyname] === true) {
|
||||
append(',omitempty')
|
||||
append(",omitempty");
|
||||
}
|
||||
append('"`\n')
|
||||
append('"`\n');
|
||||
}
|
||||
indent(--tabs)
|
||||
append('}')
|
||||
indent(--tabs);
|
||||
append("}");
|
||||
}
|
||||
|
||||
function indent (tabs) {
|
||||
for (let i = 0; i < tabs; i++)
|
||||
go += '\t';
|
||||
function indent(tabs) {
|
||||
for (let i = 0; i < tabs; i++) go += "\t";
|
||||
}
|
||||
|
||||
function append (str) {
|
||||
go += str
|
||||
function append(str) {
|
||||
go += str;
|
||||
}
|
||||
|
||||
// Sanitizes and formats a string to make an appropriate identifier in Go
|
||||
function format (str) {
|
||||
if (!str)
|
||||
return ''
|
||||
else if (str.match(/^\d+$/))
|
||||
str = 'Num' + str
|
||||
function format(str) {
|
||||
if (!str) return "";
|
||||
else if (str.match(/^\d+$/)) str = "Num" + str;
|
||||
else if (str.charAt(0).match(/\d/)) {
|
||||
const numbers = {
|
||||
'0': 'Zero_', '1': 'One_', '2': 'Two_', '3': 'Three_',
|
||||
'4': 'Four_', '5': 'Five_', '6': 'Six_', '7': 'Seven_',
|
||||
'8': 'Eight_', '9': 'Nine_'
|
||||
}
|
||||
str = numbers[str.charAt(0)] + str.substr(1)
|
||||
"0": "Zero_",
|
||||
"1": "One_",
|
||||
"2": "Two_",
|
||||
"3": "Three_",
|
||||
"4": "Four_",
|
||||
"5": "Five_",
|
||||
"6": "Six_",
|
||||
"7": "Seven_",
|
||||
"8": "Eight_",
|
||||
"9": "Nine_"
|
||||
};
|
||||
str = numbers[str.charAt(0)] + str.substr(1);
|
||||
}
|
||||
return toProperCase(str).replace(/[^a-z0-9]/ig, '') || 'NAMING_FAILED'
|
||||
return toProperCase(str).replace(/[^a-z0-9]/gi, "") || "NAMING_FAILED";
|
||||
}
|
||||
|
||||
// Determines the most appropriate Go type
|
||||
function goType (val) {
|
||||
if (val === null)
|
||||
return 'interface{}'
|
||||
function goType(val) {
|
||||
if (val === null) return "interface{}";
|
||||
|
||||
switch (typeof val) {
|
||||
case 'string':
|
||||
case "string":
|
||||
if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val))
|
||||
return 'time.Time'
|
||||
else
|
||||
return 'string'
|
||||
case 'number':
|
||||
return "time.Time";
|
||||
else return "string";
|
||||
case "number":
|
||||
if (val % 1 === 0) {
|
||||
if (val > -2147483648 && val < 2147483647)
|
||||
return 'int'
|
||||
else
|
||||
return 'int64'
|
||||
}
|
||||
else
|
||||
return 'float64'
|
||||
case 'boolean':
|
||||
return 'bool'
|
||||
case 'object':
|
||||
if (Array.isArray(val))
|
||||
return 'slice'
|
||||
return 'struct'
|
||||
if (val > -2147483648 && val < 2147483647) return "int";
|
||||
else return "int64";
|
||||
} else return "float64";
|
||||
case "boolean":
|
||||
return "bool";
|
||||
case "object":
|
||||
if (Array.isArray(val)) return "slice";
|
||||
return "struct";
|
||||
default:
|
||||
return 'interface{}'
|
||||
return "interface{}";
|
||||
}
|
||||
}
|
||||
|
||||
// Given two types, returns the more specific of the two
|
||||
function mostSpecificPossibleGoType (typ1, typ2) {
|
||||
if (typ1.substr(0, 5) === 'float'
|
||||
&& typ2.substr(0, 3) === 'int')
|
||||
return typ1
|
||||
else if (typ1.substr(0, 3) === 'int'
|
||||
&& typ2.substr(0, 5) === 'float')
|
||||
return typ1
|
||||
else
|
||||
return 'interface{}'
|
||||
function mostSpecificPossibleGoType(typ1, typ2) {
|
||||
if (typ1.substr(0, 5) === "float" && typ2.substr(0, 3) === "int")
|
||||
return typ1;
|
||||
else if (typ1.substr(0, 3) === "int" && typ2.substr(0, 5) === "float")
|
||||
return typ1;
|
||||
else return "interface{}";
|
||||
}
|
||||
|
||||
// Proper cases a string according to Go conventions
|
||||
function toProperCase (str) {
|
||||
function toProperCase(str) {
|
||||
// https://github.com/golang/lint/blob/39d15d55e9777df34cdffde4f406ab27fd2e60c0/lint.go#L695-L731
|
||||
const commonInitialisms = [
|
||||
'API', 'ASCII', 'CPU', 'CSS', 'DNS', 'EOF', 'GUID', 'HTML', 'HTTP',
|
||||
'HTTPS', 'ID', 'IP', 'JSON', 'LHS', 'QPS', 'RAM', 'RHS', 'RPC', 'SLA',
|
||||
'SMTP', 'SSH', 'TCP', 'TLS', 'TTL', 'UDP', 'UI', 'UID', 'UUID', 'URI',
|
||||
'URL', 'UTF8', 'VM', 'XML', 'XSRF', 'XSS'
|
||||
]
|
||||
"API",
|
||||
"ASCII",
|
||||
"CPU",
|
||||
"CSS",
|
||||
"DNS",
|
||||
"EOF",
|
||||
"GUID",
|
||||
"HTML",
|
||||
"HTTP",
|
||||
"HTTPS",
|
||||
"ID",
|
||||
"IP",
|
||||
"JSON",
|
||||
"LHS",
|
||||
"QPS",
|
||||
"RAM",
|
||||
"RHS",
|
||||
"RPC",
|
||||
"SLA",
|
||||
"SMTP",
|
||||
"SSH",
|
||||
"TCP",
|
||||
"TLS",
|
||||
"TTL",
|
||||
"UDP",
|
||||
"UI",
|
||||
"UID",
|
||||
"UUID",
|
||||
"URI",
|
||||
"URL",
|
||||
"UTF8",
|
||||
"VM",
|
||||
"XML",
|
||||
"XSRF",
|
||||
"XSS"
|
||||
];
|
||||
|
||||
return str.replace(/(^|[^a-zA-Z])([a-z]+)/g, function (unused, sep, frag) {
|
||||
if (commonInitialisms.indexOf(frag.toUpperCase()) >= 0)
|
||||
return sep + frag.toUpperCase()
|
||||
else
|
||||
return sep + frag[0].toUpperCase() + frag.substr(1).toLowerCase()
|
||||
}).replace(/([A-Z])([a-z]+)/g, function (unused, sep, frag) {
|
||||
if (commonInitialisms.indexOf(sep + frag.toUpperCase()) >= 0)
|
||||
return (sep + frag).toUpperCase()
|
||||
else
|
||||
return sep + frag
|
||||
})
|
||||
return str
|
||||
.replace(/(^|[^a-zA-Z])([a-z]+)/g, function(unused, sep, frag) {
|
||||
if (commonInitialisms.indexOf(frag.toUpperCase()) >= 0)
|
||||
return sep + frag.toUpperCase();
|
||||
else return sep + frag[0].toUpperCase() + frag.substr(1).toLowerCase();
|
||||
})
|
||||
.replace(/([A-Z])([a-z]+)/g, function(unused, sep, frag) {
|
||||
if (commonInitialisms.indexOf(sep + frag.toUpperCase()) >= 0)
|
||||
return (sep + frag).toUpperCase();
|
||||
else return sep + frag;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = jsonToGo
|
||||
module.exports = jsonToGo;
|
||||
+10
-7
@@ -41,7 +41,7 @@ export const categorizedRoutes = [
|
||||
{
|
||||
label: "JSON to React PropTypes",
|
||||
path: "/",
|
||||
title: 'Transform | All important transforms at one place.',
|
||||
title: "Transform | All important transforms at one place.",
|
||||
desc:
|
||||
"An online utility to convert a JSON object to prop-types, Typescript Interface, Rust serde or flow types. It also converts your CSS into JS and HTML into JSX."
|
||||
},
|
||||
@@ -87,7 +87,8 @@ export const categorizedRoutes = [
|
||||
{
|
||||
label: "JSON Schema to TypeScript",
|
||||
path: "/json-schema-to-ts",
|
||||
desc: "An online REPL for converting JSON Schema to TypeScript Interface."
|
||||
desc:
|
||||
"An online REPL for converting JSON Schema to TypeScript Interface."
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -156,11 +157,13 @@ export const categorizedRoutes = [
|
||||
{
|
||||
category: "Go",
|
||||
iconName: "icon-go",
|
||||
content: [{
|
||||
label: "JSON to Go Struct",
|
||||
path: "/json-to-go",
|
||||
desc: "An online REPL to generate Go Struct from JSON."
|
||||
}]
|
||||
content: [
|
||||
{
|
||||
label: "JSON to Go Struct",
|
||||
path: "/json-to-go",
|
||||
desc: "An online REPL to generate Go Struct from JSON."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
category: "XML",
|
||||
|
||||
Reference in new issue
Block a user