Related article: How to build building blocks to develop H5 pages quickly? Address: H5-Dooring page production platform note: ⚠️ This article is the nuggets community first contract article, unauthorized reproduction is prohibited

I have been working on projects related to LowCode and visualization, and I have produced a series of technical articles on visualization technology. Today I will continue to talk about the topic of visualization platform – the component store. This requirement has been raised by some netizens since I opened h5-Dooring, as follows:

Recently I have done a series of refactoring and optimization, so I think it is time to start the component store, so I would like to take this opportunity to talk about how to design the component store for the visual building platform.

In keeping with my usual writing style, I will outline the articles below so that you can read and learn them efficiently and selectively:

  • What is a component store and why is it designed
  • Component store workflow design
  • Component shop workflow concrete scheme implementation
    • Implement an online code editor
    • Component submission scheme design
    • Component approval scheme design
    • Update solution for components in the cabinet
  • Visualized building platform component store summary and later planning

The view of the article is as follows. You can also organize your thoughts through mind mapping at work.

What is a component store and why is it designed

“Store” may not be unfamiliar to everyone, to the user, its basic purpose is to meet the normal consumption demand; For suppliers, stores provide a marketing channel to sell their products; For the store itself, on the one hand, it can obtain the customer flow and profit, on the other hand, it can provide the extension of its own value in the space.

From the illustration above, it is easy to think of one word — ecology. Because each link is promoting each other, mutual influence. So with the physical store in mind, let’s look at the “component store” in technology.

One of the core components of a visual building platform is component assets. Users will consume a variety of components in the design and construction of the page, but for different users, the requirements of the components are often different, most lowcode or Nocode platform can not well solve the user’s customized component needs, so to solve this problem, the component store is born.

We need to provide a mechanism in the platform to support producers to produce components, to define components, and to allow managers to categorize and manage components produced by producers (e.g., shelf/remove/sort, etc.). Friends who have done the e-commerce system may find that it is a logical process with the launch of goods on the e-commerce platform:

So next I will take you to design such a process, for your reference.

Component store workflow design

Based on the introduction and analysis above, we need the following to implement a complete component store workflow:

  • Component online editing (uploading) module
  • Component audit module
  • Component update/release modules
  • Component Management (shelf/Shelf/Delete/Download)

With the above four pieces of support, the basic component store is ready to work. The specific process is as follows:

Component shop workflow concrete scheme implementation

After having a specific planning and design, we can step by step to achieve.

1. Implement online code editor

There are several mature solutions for online code editors on the market, such as:

  • react-monaco-editor
  • react-codemirror2
  • Ace | performance and function can be comparable to native code editor

You can choose any of the above solutions, here the author uses React-Codemirror2 to implement. The results are as follows:

As you can see from the figure above, you can write React, Css, and Js code online and configure component information. First let’s install the plugin:

yarn add react-codemirror2 codemirror2
Copy the code

Codemirror gives us a lot of language support and different styles of code themes, so we can easily create different language edit panels. Let’s implement a React code editor:

import {UnControlled as CodeMirror} from 'react-codemirror2';
require('codemirror/mode/jsx/jsx');

const react_code = `import styles from './index.less'; import React, { memo, useState } from 'react'; import ReactDOM from 'react-dom'; const MenuCp = memo((props) => { const { visible, list, bgColor, top } = props; return ReactDOM.createPortal( 
      
H5-Dooring
, (document as any).querySelector('.react-grid-layout').parentNode, ) })`
const ReactEditPanel = () = > { const codeEditorChange = ( _editor: CodeMirror.Editor, _data: CodeMirror.EditorChange, value: string.type: string ) = > { console.log(_data, value, type)}return <CodeMirror value={react_code} className={styles.codeWrap} options={{ mode: 'jsx', theme: 'material', lineNumbers: true }} onChange={(editor, data.value) = > codeEditorChange(editor, data, value, 'react')} /> } Copy the code

This implements a simple React code editor. For the CSS and JS code editor, we need to define the mode of the CodeMirror property to CSS and javascript. We can also set theme to switch to our favorite code theme, which I used here as a material style.

It’s not enough to simply implement an online code editor. We also need to process the code, save it, and define the components. Let’s take a look at how the components are committed.

2. Component submission scheme design

After the “producer” has written the component code, the component itself needs to be defined. Because the visual platform component materials depend on the platform’s component development protocol, we need to upload the standard custom components according to the platform’s specifications, so that the platform can better understand the application components and maintain the consistency of users’ cognition.

The author designs the following fields for component description information:

  • Component Name (Chinese)
  • Component name (English, easy to store)
  • Component categories (Basic, Visual, Marketing, media, etc.)
  • Component default size (width and height)
  • Component icon (easy for users to recognize and find)

You can also define and spec it according to your platform characteristics so that you can submit a complete set of component data.

At the moment, I, it is the user submits a complete component data exist in the library, in order to review the components into a visual platform can consumption, of course you can also use a more intelligent way, automatic extraction and conversion of component code information of its weakness is error rate control, and can’t to accurate description of the component. Here’s what I submitted:

The component commit logic is also simple:

form.validateFields().then(values= > {
  codeRef.current['form'] = {
    ...values,
    icon: values.icon[0].url
  };
  req.post('/visible/cp/save', codeRef.current).then(res= > {
    setIsModalVisible(false);
  })
}).catch(errorInfo= > {
  console.log(errorInfo)
  setCurTab("4")})Copy the code

We only need to use ANTD Form to collect the data filled in by the user and submit it to the background interface. Because my background uses nodeJS implementation, the upload interface is nothing more than to save the component data, the implementation is relatively simple, here is not a introduction. Anyone interested in NodeJS can refer to my previous open source project to build a full stack CMS from zero.

3. Component approval scheme design

Component approval is mainly operated by the website administrator. When the user component is submitted successfully, the client notifies the administrator through message signaling, and the administrator will approve the component after receiving the message. Then the whole process is very simple, we can use WebSocket to achieve two-way message communication, the complete process is as follows:

We first to achieve socket communication, here I use the market more mature socket. IO, to simply get through a client, server two-way communication process.

First of all, let’s follow the dependency:

# the service side
yarn add socket.io

# client
yarn add socket.io-client
Copy the code

For the server, we need to rewrite it as follows:

import koa from 'koa';
import http from 'http';

const app = new koa();
const server = http.createServer(app.callback());
const io = require('socket.io')(server);

// Some business logic...

/ / socket communication
io.on('connection'.(socket) = > {
    console.log('a user connected');
    socket.on('component upload success'.(msg) = > {
      // Notice approval
      io.emit('component review', msg)
    })
  });

server.listen(config.serverPort, () = > {
    console.log('Server address :xxx.xxx.xxx')});Copy the code

For the client, the logic is as follows:

import io from 'socket.io-client'
import { serverUrl } from '@/utils/tool'

const socket = io(serverUrl);

/ /... Some logic
useEffect(() = > {
   socket.on('connect'.function(){
     console.log('connect')}); socket.on('htmlWorked'.function(data){
     const { result, message } = data
     if(result ! = ='error') {
       // ...
     }else {
       // ...}}); socket.on('disconnect'.function(e){
     console.log('disconnect', e)
   });
 }, [])
Copy the code

Through the above implementation of the client and server can communicate at any time. Let’s look at the effect of the approval:

Components submitted by users on the H5-Dooring platform flow into the management back end, where administrators can review the components and download the source code. Approval also uses the codemirror library, which is used to echo string code stored in the database. Of course, you can also achieve online preview components online after the effect, this you are interested in can try their own implementation, the principle is also very simple. Let’s take a look at the approval demo:

4. Update the components in the cabinet

There are a lot of options for putting components on the shelf, such as manually putting components on the shelf for update, or automate the process. So here I introduce my online automated listing solution, here still need to use the above introduced socket. IO and nodejs. The principle is as follows:

Complete process is platform administrator on component after approved, will automatically use the socket send for examination and approval by the signal to the server, the server will be carried out on the component data parsing, written under the corresponding categories of component library (that is, the component into the Treasury), yuan write to the editor and the component information base, at this time to update the effect of the base to get the latest, Nodejs is required to parse the build directive line to package the base. When the base is updated, it sends a message to H5-Dooring using socket, notifying the user that the component library has been updated, and prompting the user to refresh the component list. At this point, a complete component shelf update process is complete. Here we implement how to package the editor dock online.

First we need to know something about nodeJS’s parent and child processes, such as child_process. I will use child_process’s exec implementation to parse and execute command line instructions. If you are not familiar with nodeJS parent-child processes, you can also see my previous article about building an online automated packaging workflow from zero based on NodeJS.

Because the whole process needs to be automated, we cannot manually execute the NPM run build or YARN build as we did before when we packaged the project. We need the program to automatically execute this command line command for us, as follows:

import { exec } from 'child_process'
const outWorkDir = resolve(__dirname, '.. /h5_base_frame')
const fid = uuid(8.16)
const cmdStr = `cd ${outWorkDir} && yarn build ${fid}`

router.post(api.generalConfig,
    auth,
    ctx= > {
      // ...
      exec(cmdStr, function(err, stdout, stderr){
       if(err) {
         console.log('api error:'+stderr);
         io.emit('htmlWorked', { result: 'error'.message: stderr })
       } else {
         io.emit('component update success', { result: 'success'.message: 'xxxx'})}})// ...});Copy the code

Online packaging through the above way, we can update our project base, and implanted into any parameters, dynamic written to the file if you need, we only need to use fs module processing, through such online workflow, we can realize more complex logic, even a small front CI workflow. If you have more elegant and better ideas, feel free to share them in the comments section.

Visualized building platform component store summary and later planning

All the design scheme of implementation is to design based on the actual demand, of course, there are many details need to be processed and optimization, as and demand, the complexity of the business, later will do component, the component data analysis, component and monitoring ability, you can also refer to the above design, design your own component store.

If you’re interested in visualizations or low/zero code, check out my previous posts or share your thoughts in the comments section.

The articles

  • Design the visualized large screen building engine from zero
  • Build the desktop visual editor Dooring from zero using electron
  • (low code) Visual build platform data source design analysis
  • Build PC page editor PC-Dooring from scratch
  • How to build building blocks to develop H5 pages quickly?