GithubHelp home page GithubHelp logo

stoplightio / json-schema-viewer Goto Github PK

View Code? Open in Web Editor NEW
154.0 17.0 29.0 4.77 MB

A JSON Schema viewer React component

License: Apache License 2.0

JavaScript 1.92% TypeScript 97.78% HTML 0.30%
json-schema-viewer storybook stoplightio json-schema react

json-schema-viewer's Introduction

@stoplight/json-schema-viewer

A JSON Schema viewer React component

Features

  • Full JSON Schema Draft 4 support, including oneOf and anyOf combiner properties
  • Renders complicated nested objects to any depth
  • Renders validation properties and markdown descriptions
  • Capable of linking resolved $refs
  • Theme-able
  • Collapsible

Installation

Supported in modern browsers and node.

# latest stable
yarn add @stoplight/json-schema-viewer

Usage

// index.jsx
import { JsonSchemaViewer } from "@stoplight/json-schema-viewer";

<JsonSchemaViewer
  name="Todos Model"
  schema={schema}
  expanded={true}
  hideTopBar={false}
  emptyText="No schema defined"
  defaultExpandedDepth={0}
/>;

More examples can be find in the Storybook stories.

Contributing

  1. Clone repo.
  2. Create / checkout feature/{name}, chore/{name}, or fix/{name} branch.
  3. Install deps: yarn.
  4. Make your changes.
  5. Run tests: yarn test.prod.
  6. Stage relevant files to git.
  7. Commit: yarn commit. NOTE: Commits that don't follow the conventional format will be rejected. yarn commit creates this format for you, or you can put it together manually and then do a regular git commit.
  8. Push: git push.
  9. Open PR targeting the develop branch.

json-schema-viewer's People

Contributors

belfordz avatar billiegoose avatar brendarearden avatar casserni avatar cjlanzo avatar daniel-white avatar dependabot[bot] avatar dotslashderek avatar edvinyard avatar jgreen44 avatar kaylachun avatar lottamus avatar mallachari avatar marbemac avatar mmiask avatar mpodlasin avatar nezteb avatar p0lip avatar paulatulis avatar ssspear avatar weyert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json-schema-viewer's Issues

Error: l.on is not a function

Describe the bug

Just rendering the component with one of the example json files (https://github.com/stoplightio/json-schema-viewer/blob/beta/src/__fixtures__/todo-allof.schema.json) gives the above error.

To Reproduce

# index.jsx:
const React = require('react')
import schema from './schema.json'
import { JsonSchemaViewer } from '@stoplight/json-schema-viewer'

export default function () {
  return (
    <JsonSchemaViewer
      name='Otomi Values'
      schema={schema}
      expanded={true}
      hideTopBar={false}
      emptyText='No schema defined'
      defaultExpandedDepth={0}
    />
  )
}

Expected behavior

The component to render

Additional context

Environment (remove any that are not applicable):

  • Library version: 2.12.0
  • OS: OSX
  • Browser: Chrome

Dependancy @stoplight/mosaic breaks our Docusaurus build

Context

In one of our Docusaurus websites, we would like to integrate a JSON schema viewer.
When integrating this lib, we discovered that :

  1. process.env statements are present in the production build
  2. buffer isn't polyfilled ( @stoplightio/yaml-ast-parser )

Current Behavior

image

Expected Behavior

I should be able to use it inside Docusaurus.

Possible Workaround/Solution

For point n°2, we might consider that : https://gist.github.com/sibelius/24f63eef7f43b15dc73c4a0be11bbef8
But ofc, it didn't work for point n°1

Steps to Reproduce

npx create-docusaurus@latest my-website classic --typescript
cd my-website
npm install @stoplight/json-schema-viewer

Create a schema.json into static folder such as :

{
  "$id": "https://example.com/person.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Person",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string",
      "description": "The person's first name."
    },
    "lastName": {
      "type": "string",
      "description": "The person's last name."
    },
    "age": {
      "description": "Age in years which must be equal to or greater than zero.",
      "type": "integer",
      "minimum": 0
    }
  }
}

Create inside src/pages the file json_schema.tsx with :

import React, { useState, useEffect } from 'react';
import Layout from '@theme/Layout';
import useBaseUrl from '@docusaurus/useBaseUrl';
import {useColorMode} from '@docusaurus/theme-common';
import { JsonSchemaViewer } from "@stoplight/json-schema-viewer";

// docusaurus.config.js
// https://gist.github.com/sibelius/24f63eef7f43b15dc73c4a0be11bbef8

function fetchSchema(URL : string, callback : (any) => void) {
    fetch(URL, {
        method: "GET",
        headers: {
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(json => callback(json))
    .catch(err => callback(undefined));
}

export default function JSONSchema(): JSX.Element {
    const [schema, setSchema] = useState(undefined);
    const {colorMode} = useColorMode();
    const JSON_SCHEMA_URL = useBaseUrl("/schema.json");

    useEffect(() => fetchSchema(JSON_SCHEMA_URL, setSchema), []);

    return (
        <Layout
            title={`JSON Schema Viewer`}
            description={`JSON Schema for xxx`}
        >
            {
                (schema !== undefined) &&
                    <JsonSchemaViewer
                        schema={schema}
                        emptyText="No schema found"
                        defaultExpandedDepth={1}
                    />
            }
            {
                (schema === undefined ) && <div>Loading ...</div>
            }
        </Layout>
    )
}

npm start , open a browser and go to http://localhost:3000/json_schema

Environment

  • Version used: latest
  • Environment name and version (e.g. Chrome 39, node.js 5.4): Chrome 108.0.5359.125 , Node 18.5
  • Operating System and version (desktop or mobile): Windows 10 Desktop

Limit scope of global styles / reset

Moving #115 (comment) over here.

Global css reset might cause issues in consuming applications - what are our options?

--

Separate the reset css out to separate file / functions that end user would be expected to include themselves if they are not using their own reset.

Downsides are:

  1. more work/complexity for consumers that don't already have their own reset and
  2. what if consumer's reset doesn't do all the things mosaic is expecting?

Option to customize reset scope somehow. This is tricky because:

  1. at least for the JSV use case the scope would probably have to be very specific (targeting just JSV containers).
  2. what to do about portals / other things that are mounted outside of the regular tree (for example dialogs, popovers, etc)

Uncaught error causes endless spinner

Describe the bug

As expected, adding an allOf with different types logs the following error to the console:

Uncaught Error: Could not resolve values for path:"type". They are probably incompatible. Values: "string" "number"

The UI displays an endless spinner with no information about the error.

To Reproduce

  1. Go to https://stoplightio.github.io/json-schema-viewer/?path=/story/jsonschemaviewer--custom-schema
  2. Add the following schema:
{
   "title": "All Of",
   "allOf": [
      {
         "type": "string"
      },
      {
         "type": "number"
      }
   ]
}

Expected behavior

An error boundary is shown displaying the error.

Screenshots

image

boolean enum cannot be shown properly

image

Schema:

{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://example.com/root.json",
  "type": "object",
  "title": "The Root Schema",
  "required": [
    "checked"
  ],
  "properties": {
    "checked": {
      "type": "boolean",
      "description": "The Checked Schema `code`",
      "enum": [false],
      "examples": [
        false
      ]
    }
  }
}

Tested in master branch, in 1.x version (specially 1.0.3) this behavior is OK.

use import instead of require

is it possible to change the require annotation into import annotation?

Context

I am using using Vite for my react application and vite doesn't really support require("your file") annotations resulting in an error in production :
ReferenceError: require is not defined
const eT=require("@stoplight/json-schema-merge-allof")

Current Behavior

right now the path @stoplight/json-schema-merge-allof is included using require statement and all if it's content is using require statement as well (not sure if there are other files affected)

Expected Behavior

use import instead of require

Possible Workaround/Solution

example : import "@stoplight/json-schema-merge-allof"

Steps to Reproduce

Environment

React Vite

question: render `$ref` for (local) `definitions`?

Hi there, stumbled across this repo while looking for an alternative to docson.

Wondering what your plans are for rendering references to local #definitions?

Unless I'm missing something it seems that currently they only show as a styled path string, without being able to view the actual definition rendered.

thx!

Select looks weird

Describe the bug

Select for choosing type options is weirdly placed and in general doesn't look right - probably some kind of regression.

To Reproduce

Visible on default story in storybook

Expected behavior

Looks closer to what is present in the designs

Screenshots
Screenshot from 2021-04-19 15-54-29

React Failed to compile

Describe the bug

After creating a fresh react app with create-react-app I added json-schema-viewer with yarn, imported it per the README, and dropped in the example block updating schema to be an import of a json schema. When I start the react app I get this error:

Failed to compile.

./node_modules/@stoplight/json/index.es.js
Attempted import error: 'ORDER_KEY_ID' is not exported from '@stoplight/ordered-object-literal' (imported as 'h').

To Reproduce

  1. Create a fresh create-react-app with npx create-react-app schema-viewer
  2. Install json-schema-viewer yarn add @stoplight/json-schema-viewer
  3. Update App.js to this:
import './App.css';
import { JsonSchemaViewer } from "@stoplight/json-schema-viewer";
import * as schema from './schemas/battery.json';

function App() {
  return (
    <div className="App">
      <JsonSchemaViewer
        name="Battery Model"
        schema={schema}
        expanded={true}
        hideTopBar={false}
        emptyText="No schema defined"
        defaultExpandedDepth={0}
      />
    </div>
  );
}

export default App;

Battery Schema

{
	"type": "struct",
	"fields": [{
		"name": "battery_status",
		"type": "integer",
		"nullable": true,
		"metadata": {}
	}]
}

Expected behavior

The module to compile and render in React.

Additional context

Add any other context about the problem here.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment (remove any that are not applicable):

  • Library version: 3.0.1
  • OS: OSX Big Surr
  • Browser: Chrome 89.0.4389.90
  • Platform: web

Support JSON Schema draft-7, 2019-09, and 2020-12

User story.
As a developer, I can visualise new JSON Schema, so that I can work with OAS 3.2 (maybe).

Describe the solution you'd like
Suport changes from daft-7 and 2019-09

Additional context
JSON Schema core team - Thank you for your donation.
I want to try make this happen =D

title field do not render

title field do not render.

Example

"definitions": {
"MessageType": {
"description": "message type, such as ....",
"title": "Message Type",
"type": "string"
},
}

Environment

  • Version used:
    Google Chrome: 109.0.5414.119
    @stoplight/json-schema-viewer: 4.5.0

Option to configure resizing behavior

As a user, I'd like to see the webpage content resize to fit the length of the schema.

It would be great if we could pass in a prop to modify the AutoSizer behavior. In the dev tools, I get the desired behavior Iif I set the disableHeight prop for the AutoSizer.

I'd do this myself, but the AutoSizer component is part of the @stoplight/tree-list module which is a private repo. Can that repo be made public?

Make top level rows non-collapsible

Summary

This looks weird:
image

We understand the incentive behind not allocating another level of nesting (left-padding) for the top level rows. The conclusion was to further align JSV with the product designs, and make top level rows non-collapsible.

This way we could have the label of the top-level rows start at exactly at the top left of the component, adding the notion of nesting visually, yet keeping the position of the children unchanged.

Example values in Dark mode are hard/impossible to read

Describe the bug

When using the dark theme, the example values are hard to read. It feels like these color values are not taken from the theme, but are hard coded.

To Reproduce

  1. Go to the storybook deployment for the dark mode: https://stoplightio.github.io/json-schema-viewer/?path=/story/jsonschemaviewer--dark
  2. Replace the background with a dark color, as it isn't set correctly
  3. Observe the example values.

Expected behavior

Example values should be styled base on the current theme.

Additional context

I'm trying to embed the json-schema-viewer into Backstage, but would like to support both light and dark mode. It's a bit difficult right now as mosaic is not public yet, but I could get it to work and understand how theming is configured 😉. I'm also aware that this is in an early state, but I'm already quite satisfied with it, nice work!

Screenshots

image

Environment (remove any that are not applicable):

  • Library version: [e.g. 3.0.0]
  • OS: [e.g. Windows 7]
  • Browser: [e.g. Chrome 61]
  • Platform: [desktop or web]

Mega Batch of JSV UI/UX fixes

Another few items from the UI/UX list, items 16 and 17 are labelled 16 and 17 in the image below.

  1. Border color is swapped - operation title bottom border (for request, response, etc) should be default border color and JSV divider color should be sl-border-light (the more prominent UI element on the page should have a higher contrast border)

  2. JSV: expand/collapse caret is slightly mis-aligned with the text in it's row

image.png

These bits are not labelled in the image:

  • On schema pages, do not render the root level schema description in the JSV, since we're already rendering it above the schema
  • On schema page, remove the border around the JSV. We can remove the ability to show examples.
  • Property descriptions should be at base font size (same as property title)

Property name is not displayed for mixed types

Describe the bug

We do not display property name despite it being present.

To Reproduce

  1. Given this JSON Schema document
{
  "type": [
    "string",
    "object"
  ],
  "properties": {
    "foo": {
      "type": "array",
      "items": {
        "type": "integer"
      }
    }
  }
}
  1. 'foo' is not displayed.

Expected behavior
Foo is displayed

Screenshots
Broken:

image

Expected:
image

Additional context
Already fixed in 1a18f25 but adding the ticket for transparency, so qa-team can include the case in their own test cases.

Need help in getting tree state(expanded or collapsed) of JSON schema

Hi Team,

I'm new to @stoplight/json-schema-viewer. I'm using @stoplight/json-schema-viewer: 3.1.1 version

<JsonSchemaViewer name="Todos Model" schema={schema} expanded={true} hideTopBar={false} emptyText="No schema defined" defaultExpandedDepth={0} />
I'm implementing expand all and collapse all feature. I want to get tree state of json schema(if any node is expanded or not), that I could use it for further coding.
could you please help me, how can i get the tree state.

Thanks,
Sreevidya

"ReferenceError: Node is not defined" when the package is used

Describe the bug

When building my Next.js Application with @stoplight/json-schema-viewer and the necessary peer dependencies the build fails.

$ yarn build
yarn run v1.22.17
$ next build
warn  - SWC minify beta enabled. https://nextjs.org/docs/messages/swc-minify-enabled
info  - Checking validity of types  
info  - Creating an optimized production build  
info  - Compiled successfully
info  - Collecting page data .[zustand persist middleware] The given storage for item 'mosaic-theme' does not contain a 'removeItem' method, which will be required in v4.
info  - Collecting page data
[    ] info  - Generating static pages (0/3)[zustand persist middleware] The given storage for item 'mosaic-theme' does not contain a 'removeItem' method, which will be required in v4.
[=   ] info  - Generating static pages (2/3)
Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
ReferenceError: Node is not defined
    at useOverlayPosition (C:\Programming\Work\nextjs-template\node_modules\@stoplight\mosaic\core.umd.js:6957:53)
    at Object.render (C:\Programming\Work\nextjs-template\node_modules\@stoplight\mosaic\core.umd.js:11680:9)
    at a.b.render (C:\Programming\Work\nextjs-template\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:43:194)
    at a.b.read (C:\Programming\Work\nextjs-template\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:41:83)
    at Object.exports.renderToString (C:\Programming\Work\nextjs-template\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:52:138)
    at renderDocument (C:\Programming\Work\nextjs-template\node_modules\next\dist\server\render.js:752:37)
    at renderToHTML (C:\Programming\Work\nextjs-template\node_modules\next\dist\server\render.js:774:34)
    at async C:\Programming\Work\nextjs-template\node_modules\next\dist\export\worker.js:273:36
    at async Span.traceAsyncFn (C:\Programming\Work\nextjs-template\node_modules\next\dist\trace\trace.js:74:20)
info  - Generating static pages (3/3)

> Build error occurred
Error: Export encountered errors on following paths:
        /
    at C:\Programming\Work\nextjs-template\node_modules\next\dist\export\index.js:500:19
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Span.traceAsyncFn (C:\Programming\Work\nextjs-template\node_modules\next\dist\trace\trace.js:74:20)
    at async C:\Programming\Work\nextjs-template\node_modules\next\dist\build\index.js:987:17
    at async Span.traceAsyncFn (C:\Programming\Work\nextjs-template\node_modules\next\dist\trace\trace.js:74:20)
    at async C:\Programming\Work\nextjs-template\node_modules\next\dist\build\index.js:861:13
    at async Span.traceAsyncFn (C:\Programming\Work\nextjs-template\node_modules\next\dist\trace\trace.js:74:20)
    at async Object.build [as default] (C:\Programming\Work\nextjs-template\node_modules\next\dist\build\index.js:82:25)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

To Reproduce

  1. Here is a Next.js repo with the issue.
  2. Run yarn build

Expected behavior

The Next.js application should build successfully. The build only fails when @stoplight/json-schema-viewer is used.

Additional context

N/A

Screenshots

N/A

Environment (remove any that are not applicable):

  • Library version: 4.5.0
  • OS: Windows 10

Render `allOf`, `oneOf`, `anyOf` constraints for Array items

Currently, when rendering an array, constraints on the item spec are not rendered. Also, I noticed that non-object types are not rendered either, e.g.

image

{
    "definitions": {
        "RateLimitAction": {
            "type": "object",
            "properties": {
                "source_cluster": {
                    "type": "string",
                    "description": "Rate limit on source cluster."
                },
                "destination_cluster": {
                    "type": "string",
                    "description": "Rate limit on destination cluster."
                },
                "request_headers": {
                    "type": "string",
                    "description": "Rate limit on request headers."
                },
                "remote_address": {
                    "type": "string",
                    "description": "Rate limit on remote address."
                },
                "generic_key": {
                    "type": "string",
                    "description": "Rate limit on a generic key."
                },
                "header_value_match": {
                    "type": "string",
                    "description": "Rate limit on the existence of request headers."
                }
            },
            "oneOf": [{
                    "required": ["source_cluster"]
                },
                {
                    "required": ["destination_cluster"]
                },
                {
                    "required": ["request_headers"]
                },
                {
                    "required": ["remote_address"]
                },
                {
                    "required": ["generic_key"]
                },
                {
                    "required": ["header_value_match"]
                }
            ]
        }
    },
    "type": "object",
    "properties": {
        "paths": {
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "actions": {
            "type": "array",
            "description": "A list of actions that are to be applied for this rate limit configuration. Order matters as the actions are processed sequentially and the descriptor is composed by appending descriptor entries in that sequence. If an action cannot append a descriptor entry, no descriptor is generated for the configuration. See composing actions for additional documentation.",
            "items": {
                "$ref": "#/definitions/RateLimitAction"
            }
        }
    }
}

As an aside, I cannot find any public source for @stoplight/tree-list. Is that published from a private repo?

Empty contents of TreeList

Describe the bug
I just created a new project using Create React App, installed latest stable [email protected], and there is no contents in DOM when I tried to show an json schema.

Screenshots
Снимок экрана 2020-04-13 в 11 46 15

To Reproduce
This is a project with example: JsonViewerReactTest

Seems like an issue with service worker, but I really don't understand what am I doing wrong :/

@stoplight/lifecycle

Describe the bug

To get this working I had to add a yarn resolution so @stoplight/tree-list used "@stoplight/lifecycle": "2.2.1"

seems to be because of this breaking change in "2.3.1"

stoplightio/lifecycle@fbf004a#diff-9cb2536ac56d6c39910e37455e7a5be1e0595a10f8470ff4f54f8ff3b59c58a7L107

I was getting createEventEmitter is not a function.

To Reproduce

These are my dependencies:

	"dependencies": {
		"@stoplight/json-schema-viewer": "^2.12.0",
		"@stoplight/lifecycle": "^2.0.1",
		"@stoplight/markdown-viewer": "^3.5.5",
		"@stoplight/tree-list": "^4.8.0",
		"@stoplight/ui-kit": "^2.10.0",
		"mobx": "^5.13.0",
		"react": "^16.8.0",
		"react-dom": "^16.8.0"
	},
  "resolutions": {
    "@stoplight/lifecycle": "2.2.1"
  }

Is there anything i'm doing wrong in my dependencies?

Expected behavior

Should not have not use the resolution.

Environment (remove any that are not applicable):

  • OS: IOS
  • Browser:Chrome

Render without any style,And there is a warning

environment:
"react": "^17.0.2",
"react-dom": "^17.0.2",

"@stoplight/json-schema-viewer": "4.5.0",
"@stoplight/markdown-viewer": "^5",
"@stoplight/mosaic": "^1.24.4",
"@stoplight/mosaic-code-viewer": "^1.24.4",

warning
[DEPRECATED]: use useSetAtom from jotai instead.

Batch of JSV UI/UX Fixes

Describe the bug

1. Border for parameters runs too far to the left

Right now if I embed JSV in Elements, I get an ugly left padding, see Screenshot. In stoplightio/elements#979 I am forced to use some negative margin to work around.

The component should be exactly as large as the space it actually uses, just like any well-behaving element.

Currently looks like this:

image

Should look like this:

image

2. There should not be more space between title and description than there is padding at top and bottom of a row

Currently:

image

Spacing could be closer to the Figma:

image

3. Background color for examples / allowed values should be #EDF2F7

Currently

image

Should be

image

Falsy default values are not displayed

Describe the bug

Falsy default values aren't currently displayed and are entirely ignored.

To Reproduce

  1. Given any schema model with a falsy default value
{
  "type": "number",
  "default": 0
}
  1. It's not rendered

Expected behavior

They are displayed in the same as any other value.

Additional context

Caused by https://github.com/stoplightio/json-schema-viewer/blob/master/src/components/shared/Validations.tsx#L229
This correct code should look more or less as follows

     ...('default' in schemaNode.annotations ? { default: JSON.stringify(schemaNode.annotations.default) } : null),

Screenshots

image

image

Support schemas inside of `additionalProperties`

Describe the bug

When I have a JSON schema that defines further schema constraints inside of additionalProperties...JSV does not render them properly in the UI.

To Reproduce

Sample JSON Schema

{
	"$id": "https://example.com/sample.schema.json",
	"$schema": "http://json-schema.org/draft-07/schema#",
	"type": "object",
	"title": "Sample schema",
	"description": "To reproduce a JSV issue",
	"required": [
		"foo",
		"bar",
		"baz"
	],
	"additionalProperties": false,
	"properties": {
		"foo": {
			"type": "string",
			"description": "Some foo property",
			"const": "foo_value"
		},
		"bar": {
			"type": "object",
			"description": "An object where keys can be anything...but I want to restrict the values of each key",
			"required": [
				"bing",
				"bang"
			],
			"additionalProperties": {
				"type": "object",
				"description": "Constraints for each value",
				"additionalProperties": false,
				"properties": {
					"bar_prop_one": {
						"type": "string"
					},
					"bar_prop_two": {
						"type": "string"
					}
				}
			}
		},
		"baz": {
			"type": "object",
			"description": "An object where keys can be anything...but I want to restrict the values of each key by a shared definition",
			"required": [
				"boom"
			],
			"additionalProperties": {
				"$ref": "#/definitions/defined_entity"
			}
		}
	},
	"definitions": {
		"defined_entity": {
			"$id": "#/definitions/defined_entity",
			"type": "string",
			"description": "Definition for an Entity.",
			"enum": [
				"entity_one",
				"entity_two"
			]
		}
	}
}

Sample JSON object that would work with schema above

{
	"foo": "foo_value",
	"bar": {
		"bing": {
			"bar_prop_one": "a",
			"bar_prop_two": "b",
		},
		"bang": {
			"bar_prop_one": "a",
			"bar_prop_two": "b",
		},
		"tang": {
			"bar_prop_one": "tango",
			"bar_prop_two": "tangotango",
		},
	},
	"baz": {
		"boom": "entity_one",
		"one": "entity_one",
		"two": "entity_one",
		"three": "entity_two",
		"four": "entity_two",
		"eleven": "entity_two"
	}
}

JSV Configuration

import sampleSchema = "../../../schemas/sample.schema.json";

<JsonSchemaViewer
	schema={sampleSchema}
	viewMode="standalone"
/>

Expected behavior

A clear and concise description of what you expected to happen.

My expectation is that the schema I provide inside additionalProperties is rendered in some way.

Additional context

Add any other context about the problem here.

Screenshots

image

Environment

{
	"@stoplight/json-schema-viewer": "3.0.0",
	"@stoplight/markdown-viewer": "3.8.1",
	"@stoplight/ui-kit": "3.0.0-beta.39",
	"mobx": "5.15.7"
}

Add support for rendering vendor extensions

I would like to purpose the ability to render or visualise vendor extensions within the JSON Schema Viewer.

Context

I have vendor extensions which I want to visualise or show up in the schema definition

Current Behavior

No ability to display vendor extensions

Expected Behavior

I want to have function similar to renderRowAddon to allow render vendor extensions

Possible Solution(s)

I have been working on implementing a function named renderExtensionAddon with the signature:

({ schemaNode: SchemaNode; nestingLevel: number; vendorExtensions: Record<string, unknown>}) => React.ReactNode

As you can see the function will return a React node back which can be rendered by the component, and the responsibility for returning the component is off loaded to the consumer of JsonSchemaViewer.

This would be used by the TopLevelSchemaRow and SchemaRow components, in a way, such as:

// Add around line 40-41
{hasVendorProperties && renderExtensionAddon
          ? renderExtensionAddon({ schemaNode, nestingLevel, vendorExtensions })
          : null}

Note: Currently, there is no way to easily extract vendor extensions from a schema node, only way is to grab it from fragment-property and then get all properties prefixed with x-.

In the SchemaRow-component a similar code can be added as above:

// Add around line 180-181
{hasVendorProperties && renderExtensionAddon ? (
              <Box>{renderExtensionAddon({ schemaNode, nestingLevel, vendorExtensions })}</Box>
            ) : null}

A potential implementation of the renderExtensionAddon could be:

/**
 * @private
 * A helper function to render vendor extensions of an OpenaPI schema definition
 */
export function renderExtensions({ schemaNode, nestingLevel, vendorExtensions }: ExtensionRowProps) {
  // Avoid rendering vendor extensions for the zero nesting level or root of a schema
  if (nestingLevel === 0) {
    return null;
  }
  return <VendorExtensions node={schemaNode} vendorExtensions={vendorExtensions} />;
}

I am happy to raise a pull request for these changes. I have been using it in a fork of the component and so far it works as expected.

Annotations should not be considered as validations

Describe the bug

Since we mix validations & annotations, they undergo pretty much the same process.
While avoiding true or false makes perfect sense in the case of validation keywords, it ruins the experience in the case of annotations.

To Reproduce

  1. Given a schema containing some annotation with booleanish value
{
  "type": "boolean",
  "examples": [true]
}
  1. The values are not displayed

Expected behavior

The values are displayed

Additional context

This is caused by https://github.com/stoplightio/json-schema-viewer/blob/master/src/components/shared/Validations.tsx#L112

We should filter out annotations
The correct code could look so

    pickBy(validations, (v, k) => !['examples', 'default'].includes(k) && ['true', 'false'].includes(String(v))),

Screenshots
image

image

Suggestion: ability to change the way validations are displayed

In versions before 1.1, and also the version currently used on next.stoplight.com, validations will be expanded in the field definition after clicking the row:

image

In 2.X however, validations are displayed in a tooltip when hovering on the rightmost hint, moving away the mouse will let it disappear, and clicking the hint cannot make it display permanently.

image

Obviously this is a major design change in 2.X, the philosophy of this change I suppose, is to avoid changing the height of the field row, so that the look and feeling is more solid than before.

This is OK as a new feature, for many cases where the schema is simple, this makes the viewer looks cleaner. But when the schema contains a lot of validations, such as the images above, reader needs a constant view of multiple fields expanded with their validations. Compare the two images above, it's obvious to find the first one is much more informative than the second one. Imagining the reader split the screen in left and right, left is the json schema viewer document, right is the editor for coding, if the validations cannot be permanently expanded, he has to move mouse a lot to open the tooltip of different fields, which could be very interruptive for the work.

In general, I suggest to make how validations are displayed to be a configuration, for example, it could be called validationsDisplayMethod, and has two enum values: TOOLTIP and INLINE, let the user to choose the one that suit best for the situation.

Handle if `null` in a combiner like `allOf`, `anyOf`, `oneOf`

Describe the bug

If there is somehow a null or otherwise non object value in the combiner array, json schema viewer will completely fail.

To Reproduce

Screen Shot 2020-03-25 at 4 50 21 PM

Screen Shot 2020-03-25 at 4 47 39 PM

Expected behavior

Render as normal, skipping the invalid values (I bet it fails for true, null, etc - anything that's not an object) - we'll catch this issue in spectral etc to report to the user.

Cannot import

Hi,

I try to integrate the newest version into a new react app created with create-react-app,

but I get the following error:

./node_modules/@stoplight/json/index.es.js
Attempted import error: 'ORDER_KEY_ID' is not exported from '@stoplight/ordered-object-literal' (imported as 'h').

Rendering array of allOf only works when in a schema with another allOf property

Describe the bug

We have the capability of rendering an array of allOf. You can see this via the "working schema" below because I'm including another allOf property. However it fails to render whenever that extra allOf property is removed as you can see via the "broken schema".

To Reproduce

Working schema:

{
  "title": "Test",
  "type": "object",
  "properties": {
    "array-all-objects": {
      "type": "array",
      "items": {
        "allOf": [
          {
            "properties": {
              "foo": {
                "type": "string"
              }
            }
          },
          {
            "properties": {
              "bar": {
                "type": "string"
              }
            }
          }
        ],
        "type": "object"
      }
    },
    "all-objects": {
      "allOf": []
    }
  }
}

image

Broken schema:

{
  "title": "Test",
  "type": "object",
  "properties": {
    "array-all-objects": {
      "type": "array",
      "items": {
        "allOf": [
          {
            "properties": {
              "foo": {
                "type": "string"
              }
            }
          },
          {
            "properties": {
              "bar": {
                "type": "string"
              }
            }
          }
        ],
        "type": "object"
      }
    }
  }
}

image

Expected behavior

The allOf is resolved and nested inside the array as seen in the working schema example.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

using oneOf `object` or `boolean` doesn't render the boolean

Trying to use this component for the MetaMask docs with OpenRPC and running into this bug with oneOf object or string.

Heres an example schema and a gif of the results in storybook.

Seems like it only works if the sub schemas of the oneOf are the same type.

{
  "title": "Syncing status",
  "oneOf": [
    {
      "title": "Syncing progress",
      "type": "object",
      "properties": {
        "startingBlock": {
          "title": "Starting block",
          "type": "string"
        },
        "currentBlock": {
          "title": "Current block",
          "type": "string"
        },
        "highestBlock": {
          "title": "Highest block",
          "type": "string"
        }
      }
    },
    {
      "title": "Not syncing",
      "description": "Should always return false if not syncing.",
      "type": "boolean"
    }
  ]
}

Screen grab:

oneOf_issie

Expected Behaviour

When Not Syncing is clicked, it should show you type boolean

Switch ui-kit to mosaic

Summary

Switch from ui-kit to equivalent mosaic components.

Tasks

  • Make sure all unprefixed Tailwind class names are gone
  • Remove all trace of Blueprint CSS
  • Delete any dependencies relating to ui-kit

Simplest means of using the viewer

Question: Is this viewer hosted in a publicly available instance? I'd just like to be able to visualise a schema I am developing, to help with the review process. I don't see it as a feature within stoplight studio. Alas I don't have any knowledge of React so the documented Usage isn't much for me to go on! Apologies for what I'm sure is a dumb question.

Handle local references better

Describe the bug

When there are local references, they're not all expandable (not sure if this is array property type problem or not though).

To Reproduce

  1. Try rendering the schema below with JSV
title: Email Message
type: object
x-tags:
  - Email
properties:
  fromAddress:
    $ref: '#/properties/another'
  toAddresses:
    type: array
    items:
      $ref: '#/properties/another'
  ccAddresses:
    type: array
    items:
      $ref: '#/properties/another'
  bccAddresses:
    type: array
    items:
      $ref: '#/properties/another'
  another:
    title: Email
    type: object
    x-tags:
      - Email
    description: An email object
    properties:
      category:
        type: string
      address:
        type: string

Expected behavior

  • toAddresses, ccAddresses, and bccAddresses should be expandable similar to how the another property is.
  • I don't know that we need to show local $refs (as seen in screenshot below in fromAddress property)? @P0lip what do you think?
  • Any particular reason for the extra nested object in the fromAddress property below? The another property is much nicer. cc @P0lip because I think you might have done the original implementation here.
  • The array properties toAddresses, ccAddresses, and bccAddresses should have type array[object], or array[#/propertiesanother] if we're keeping the local refs showing. One other thought is that we could drop the array word there, and go with syntax like [object], [number], etc.

Screenshots

Screen Shot 2020-03-25 at 9 19 52 PM

Clean up HTML output & improve accessibility

Summary

With #109 merged, we now have the option to output much nicer HTML than we do right now.

This would help with both the new product initiative of promoting accessibility across the product, and with getting the tests in shape. (My prior attempts like #112 turned out too difficult because the structure was really not testing-friendly. It could be now.)

Tasks

  • Use proper nested lists instead of divs everywhere.
  • Apply proper roles and aria-attributes for the tree. Example here.

Class extends value undefined is not a constructor or null

Describe the bug
When trying to rendering any schema, I've got an Uncaught TypeError: Class extends value undefined is not a constructor or null. I see warnings like this:

"export 'Tree' (imported as 'r') was not found in '@stoplight/tree-list'
"export 'TreeState' (imported as 'a') was not found in '@stoplight/tree-list'
"export 'isParentNode' (imported as 't') was not found in '@stoplight/tree-list'

Is it a problem with webpack config?

v3.0.0-beta.11

Screenshots
Снимок экрана 2020-04-07 в 13 32 40

Improve overall perfomance

When profiling Studio, I found JSV is quite slow under certain circumstances and therefore makes Studio feel sluggish

image

The biggest bottleneck is allOf merging.
Luckily, we can easily improve it. We just use incorrectly - json-all-of-merge does a deep flattening, so there we can call it once rather than n times.
https://github.com/stoplightio/json-schema-viewer/blob/master/src/utils/renderSchema.ts#L57

The other improvement is to run that heavy rendering in a worker.
To provide a pleasant UX, we can do a simple pre-rendering.

Show title instead of any for combiners

Context

Consider the schema:

{
  "title": "a",
  "oneOf": [
    {
      "title": "b",
      "type": "object",
      "properties": {
        "c": {
          "title": "d",
          "type": "string"
        },
        "e": {
          "title": "e",
          "type": "string"
        }
      }
    },
    {
      "title": "f",
      "type": "boolean"
    },
    {
      "title": "g",
      "oneOf": [
        {
          "title": "h",
          "type": "string"
        },
        {
          "title": "l",
          "type": "object",
          "properties": {
            "foo": {
              "title": "k",
              "oneOf": [
                {
                  "title": "m",
                  "type": "string"
                },
                {
                  "title": "o",
                  "type": "object",
                  "properties": {
                    "foo": { "type": "string" }
                  }
                }
              ]
            }
          }
        }
      ]
    }
  ]
}

Current Behavior

Displays any inplace of g
in the choices dropdown:
image

in the schema row
image

Expected Behavior

Displays g inplace of any
in the choices dropdown:
image

in the schema row
image

Possible Workaround/Solution

Steps to Reproduce

  1. copy the schema at the top into a fixture

Environment

Generate titles based on $ref names for oneOf/anyOf dropdown

** User Story**

As a docs viewer I like to see descriptive names for switching between oneOf/anyOf, even if the author has not used the title property in every schema.

Details

Currently when we do oneOf/anyOf dropdowns we only look for the title property, and if there is no title we will show "1. object" and "2. object". This issue provides some logic for generating titles from a $ref if its provided, by looking at the last segment.

The last segment of the $ref should usually be ok to use as a "display name", which will show up in that dropdown.

  • $ref: #/components/schemas/Something = Something
  • $ref: #/components/schemas/SomethingElse = SomethingElse
  • $ref: #/components/schemas/SomethingElse/properties/something_else = something_else
  • $ref: shared/turtle.json = turtle
  • $ref: #/components/headers/Sunset = Sunset

So assuming none of those refs have a title property inside, if a schema contains this:

oneOf: 
- $ref: "shared/turtle.json"
- $ref: "#/components/headers/Sunset"
- type: number

Then the dropdown should show:

  • turtle
  • Sunset
  • number

Titles should still be taken from the schema object when set:

// openapi.yaml

components: 
  schema:
    Tag:
      title: Tag Model
      type: object
      properties:
        id:
          # ...

These titles can exist in "shared schemas" too:

// turtle.json

{
  "title": "Custom Turtle Model Name",
  "type": "object"
}

So look for title, if there's no title then take the last $ref segment and display it unmodified in whatever case with hyphens or whatever else.

Also currently we have "1. Foo" and "2. Bar" but it should not be a numbered list, just a select box. We only add numbers if there are unknown types like "object #1" and "object #2".

Additional Context

#110

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.