Coder Social home page Coder Social logo

asyncapi / generator-react-sdk Goto Github PK

View Code? Open in Web Editor NEW
17.0 4.0 7.0 868 KB

Generator React SDK enabling the AsyncAPI generator to support React as the rendering engine for templates.

License: Apache License 2.0

JavaScript 9.41% TypeScript 90.59%
nodejs react get-global-node-release-workflows get-global-releaserc get-global-docs-autoupdate

generator-react-sdk's Introduction

AsyncAPI React SDK

AsyncAPI React SDK is a set of components/functions to use React as render engine in the Generator.

Installation

Run this command to install the SDK in your project:

npm install --save @asyncapi/generator-react-sdk

How it works

The process of creating content from React components consists of two main process: transpile and rendering.

The Transpile Process

The SDK has a custom transpiler which ensures that any directory are transpiled using Rollup. Rollup helps bundling all dependencies and transpile them into CommonJS modules. This is required because this library will be used through NodeJS which does not understand these new modules natively and we do not want to limit the developer in which syntax they prefer nor how they want to separate code.

The Rendering Process

SDK has its own reconciler for React components. It traverses through each element in the template structure and transforms it into a pure string. Additionally, prop children is also converted to a regular string and stored in the childrenContent prop, which is appended to each component. See example.

Restrictions:

  • React hooks is not allowed.
  • HTML tags at the moment is not supported.
  • React internal components like Fragments, Suspense etc. are skipped.

Requirements

To render the transpiled template SDK requires:

  • Node.js v18 and higher

The debug flag

When rendering you have the option of passing a debug flag which does not remove the transpiled files after the rendering process is done.

Example

import { Text, Indent, IndentationTypes, render } from '@asyncapi/generator-react-sdk';

class ClassComponent extends React.Component {
  constructor(props) { 
    super(props);
  }

  render() {
    // In `childrenContent` prop is stored `text wrapped by custom component\n\n`.
    // The content of the `children` prop is transformed to string and saved to the `childrenContent` prop.
    return this.props.childrenContent;
  }
}

function FunctionComponent() {
  return (
    <Indent size={3} type={IndentationTypes.TABS}>
      indented text
      <ClassComponent>
        <Text newLines={2}>
          text wrapped by custom component
        </Text>
      </ClassComponent>
    </Indent>
  );
}

// content will be `\t\t\tindented text text wrapped by custom component\n\n`
const content = render(<FunctionComponent />);

Resources

  • template-for-generator-templates template showcases features of the AsyncAPI Generator, including the React renderer. It shows how to write templates, reusable parts (components), what are the recommended patterns. It has simple and complex examples of using React.
  • markdown-template is written using React. It generates documentation into a Markdown file.

For more help join our Slack workspace.

Development

  1. Setup project by installing dependencies npm install
  2. Write code and tests.
  3. Make sure all tests pass npm test
  4. Make sure code is well formatted and secure npm run lint

Contributing

Read CONTRIBUTING guide.

generator-react-sdk's People

Contributors

asyncapi-bot avatar codingtenshi avatar derberg avatar jonaslagoni avatar magicmatatjahu avatar mcturco avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar

generator-react-sdk's Issues

Integrate context inside React renderer

As in title: integrate context like in normal React in our React renderer. Idea is described here.

Copied comment from above link:

Context

If we go with React engine as a base solution for model generation, then we should also introduce context for React components. It should works similar to React-DOM context. Let's check the example:

<NamespaceContext>
  <Namespace>
    <ClassContext>
      <Class>
        <PropertyContext>
          <Property />
        </PropertyContext>

        <MethodContext>
          <Method />
        </MethodContext>
      </Class>
    </ClassContext>
  </Namespace>
</NamespaceContext>

Then inside Property and Method components we can use contexts: NamespaceContext, ClassContext, PropertyContext (only Property can use it) and MethodContext (only Method can use it). In Class component we can use contexts: NamespaceContext, ClassContext. By this we lookup for contexts in parent components (not in children - it is not logical).

Using context in component:

import { useContext } from "@asyncapi/generator-react-sdk";

function Property({ ...props }) {
  // we can retrieve some data from ClassContext
  const { className } = useContext(ClassContext);
  // and also from NamespaceContext
  const { namespaceName } = useContext(NamespaceContext);
}

Context can store some data (because context can be written and used as normal JS class) in rendering time and then developer can change output based on stored data.

Similar issue in shape-up repository: asyncapi/shape-up-process#54

markdown-template failing for us since generator-react-sdk:0.1.5 was released

For a few hours our Markdown documentation generation fails. Since it indicates this module as the cause and fetches the version just released I thought this is the cause rather than something with markdown-template. Generation worked fine before that.

Here's the output (project references anonymized - I hope):

$ npm run asyncapi-md

> @[email protected] asyncapi-md /home/martin/project
> ag ./docs/asyncapi.yaml @asyncapi/markdown-template --param outFilename=events.md --output ./docs/ --force-write

npm http fetch GET 304 ...
...

+ @asyncapi/[email protected]
added 162 packages from 85 contributors, removed 168 packages and moved 2 packages in 10.37s

11 packages are looking for funding
  run `npm fund` for details

Something went wrong:
Error: Cannot find module '/home/martin/project/node_modules/@asyncapi/generator/node_modules/@asyncapi/markdown-template/node_modules/@asyncapi/generator-react-sdk/lib/index.js'. Please verify that the package.json has a valid "main" entry
    at tryPackage (internal/modules/cjs/loader.js:295:19)
    at Function.Module._findPath (internal/modules/cjs/loader.js:508:18)
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:802:27)
    at Function.Module._load (internal/modules/cjs/loader.js:667:27)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/martin/project/node_modules/@asyncapi/generator/node_modules/@asyncapi/markdown-template/__transpiled/asyncapi.js:5:25)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at /home/martin/project/node_modules/@asyncapi/generator-react-sdk/src/renderer/template.ts:45:25
    at new Promise (<anonymous>)
    at importComponent (/home/martin/project/node_modules/@asyncapi/generator-react-sdk/src/renderer/template.ts:38:10)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @[email protected] asyncapi-md: `ag ./docs/asyncapi.yaml @asyncapi/markdown-template --param outFilename=events.md --output ./docs/ --force-write`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @[email protected] asyncapi-md script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/martin/.npm/_logs/2021-02-05T14_16_38_557Z-debug.log

I also attached the (also anonymized) 2021-02-05T14_16_38_557Z-debug.log.

Providing a full project would take a bit longer. Just let me know if this doesn't show up for you at all and I'll dig into that.

Thanks for any pointers! Or a fix :)

Simplify `File template` feature

Reason/Context

Some people know or not, the Generator has feature called File template. More info here https://github.com/asyncapi/generator/blob/master/docs/authoring.md#file-templates

Issue is created to start discussion about how to simplify this feature. File template is good for Nunjucks but using React we can make it more powerful and more flexible.

Proposition

My proposition is return as output from template an array of <File> components and then render and save every given File, something like:

export default function({ asyncapi }) {
  if (!asyncapi.components().hasSchemas()) {
    return null;
  }

  return Object.entries(asyncapi.components().schemas()).map(([schemaName, schema]) => {
    return (
      <File name={`${schemaName}.html`}>
        <SchemaFile schemaName={schemaName} schema={schema} />
      </File>
    );
  });
}

function SchemaFile({ schemaName, schema }) {
  // implementation...
}

Any other ideas? :)

react warnings are loud when generating react templates

Describe the bug

When I generate markdown template I get this in the console

Warning: Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information.
    at Server (/Users/wookiee/sources/markdown-template/__transpiled/asyncapi.js:227:26)
Warning: Each child in a list should have a unique "key" prop.

Check the top-level render call using <Text>. See https://reactjs.org/link/warning-keys for more information.
    at Schema (/Users/wookiee/sources/markdown-template/__transpiled/asyncapi.js:320:21)

How to Reproduce

just generate with markdown-template and you'll see it

Expected behavior

these logs should not be visible

Support asynchronous template functions

Reason/Context

It is currently not possible to use a default asynchronous function in the template such as

export default async function schemaRender({ asyncapi }) {
   ...
}

Description

This is required in order to use the new model library.

stack trace when trying to use it

Something went wrong:
ReferenceError: regeneratorRuntime is not defined
    at _schemaRender (/Users/lagoni/Documents/AsyncAPI/ts-nats-template/__transpiled/src/schemas/schema.ts.js:155:51)
    at schemaRender (/Users/lagoni/Documents/AsyncAPI/ts-nats-template/template/src/schemas/schema.ts.js:15:1)
    at /Users/lagoni/Documents/AsyncAPI/ts-nats-template/node_modules/@asyncapi/generator-react-sdk/src/renderer/template.ts:50:52
    at new Promise (<anonymous>)
    at importComponent (/Users/lagoni/Documents/AsyncAPI/ts-nats-template/node_modules/@asyncapi/generator-react-sdk/src/renderer/template.ts:42:10)
    at Object.<anonymous> (/Users/lagoni/Documents/AsyncAPI/ts-nats-template/node_modules/@asyncapi/generator-react-sdk/src/renderer/template.ts:19:18)
    at step (/Users/lagoni/Documents/AsyncAPI/ts-nats-template/node_modules/@asyncapi/generator-react-sdk/lib/renderer/template.js:33:23)
    at Object.next (/Users/lagoni/Documents/AsyncAPI/ts-nats-template/node_modules/@asyncapi/generator-react-sdk/lib/renderer/template.js:14:53)
    at /Users/lagoni/Documents/AsyncAPI/ts-nats-template/node_modules/@asyncapi/generator-react-sdk/lib/renderer/template.js:8:71
    at new Promise (<anonymous>)

Need for urgent changes in GitHub Actions automation

This issue defines a list of tasks that need to be performed in this repo to make sure it's ci/cd automation works long term without any issues.

It is up to maintainers to decide if it must be addressed in one or multiple PRs.

Below are 3 different sections describing 3 different important ci/cd changes.

IMPORTANT-START
For GitHub workflows that contain This workflow is centrally managed in https://github.com/asyncapi/.github/ you do not have to perform any work. These workflows were already updated through the update in .github. The only exception is the workflows related to nodejs release. More details in Upgrade Release pipeline - in case of nodejs projects section
IMPORTANT-END

Deprecation of way data is shared between steps

Every single GitHub Action workflow that has echo "::set-output name={name}::{value}" need to be updated to follow echo "{name}={value}" >> $GITHUB_OUTPUT

We do not yet know when set-output will stop working. Previous disable date was 31.05 but now then say community needs more time.

For more details read official article from GitHub

Deprecation of node12

2nd bullet point is still relevant for you even if your projects in not nodejs project

  • Every single workflow that uses setup-node action needs an update to follow v3 version of this action, and make sure minimum node 14 is used
  • Now this part is more complex. Problem with node12 is that node-based GitHub Actions were using it in majority as a runtime environment. Look for example at this action.yaml file for setup-node action v2. So the job that you have to do is go through all the workflows, and verify every single action that you use, make sure you are using the latest version that is not based on node12. I already did review a lot of actions as part of this PR so maybe you will find some actions there and can copy from me. For example action/checkout needs to be updated to v3.

Node12 end of support in action is probably September 27th.

For more details read official article from GitHub

Upgrade Release pipeline - in case of nodejs projects

ignore this section if your project is not nodejs project

You have 2 options. You can:

A. choose to switch to new release pipeline using instruction from asyncapi/.github#205

B. stay with old release pipeline, and manually update GitHub workflows and actions used in it, you can inspire a lot from this PR asyncapi/.github#226

I definitely recommend going with A

Workflows related to release:

  • .github/workflows/if-nodejs-release.yml
  • .github/workflows/if-nodejs-version-bump.yml
  • .github/workflows/bump.yml

Update README with new logo banner

Reason/Context

This is to replace the old AsyncAPI logo in this repo's README with the banner attached below that represents the new branding.

Here are a few guidelines for this change as well:

  1. Make sure you are using Markdown syntax only
  2. Be sure to remove the old logo as well as the old title of the repo as this image will replace both elements
  3. Make sure you link this image to the website: https://www.asyncapi.com
  4. If there is any description text below the repo title, let's make it left-aligned if it isn't already, so as to match the left-alignment of the content in the new banner image

Download the image file:
github-repobanner-reactsdk.png.zip


Banner preview

Please note that this is only a preview of the image, the contributor should download and use the above zip file

github-repobanner-reactsdk

Update dependencies.

Security issues:

@babel/traverse

@babel/core

There are some very old dependencies used by asyncapi. E.g. babel/core is 3 years old.

Can you please update the dependencies? I know it is used for code generation, but still.

Release as version 1

Reason/Context

Since its creation we have used version 0, however with more than 1 year with no bugs, I think it's fair to say we can release this as being stable version 1 ๐Ÿ™‚

@magicmatatjahu what do you think?

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.