Reac16+Monaco打造代码编辑器(前端部分)

效果图

Reac16+Monaco打造代码编辑器(前端部分)_第1张图片
Reac16+Monaco打造代码编辑器(前端部分)_第2张图片

实现

这里小编只讲编辑器的主体部分,及两个选择框以及编辑器部分。
首先是选择器,毕竟主体的编辑器需要通过选择器来改变样式以及提供语言高亮等支持

SelectBox.js
import React from 'react';
import {
    Select } from 'element-react';
import {
    Layout } from 'element-react';
import 'element-theme-default';
import valueData from '../../../jsondata/editor-data.json'

class SelectBox extends React.Component{
   
    constructor(props) {
   
        super(props);
        this.state = {
   
            //支持的语言
            options: [
                {
   
                    value: '选项1',
                    label: 'apex',
                },
                {
   
                    value: '选项2',
                    label: 'azcli',
                },
                {
   
                    value: '选项3',
                    label: 'bat',
                },
                {
   
                    value: '选项4',
                    label: 'c'
                },
                {
   
                    value: '选项5',
                    label: 'clojure',
                },
                {
   
                    value: '选项6',
                    label: 'coffeescript',
                },
                {
   
                    value: '选项7',
                    label: 'cpp',
                },
                {
   
                    value: '选项8',
                    label: 'csharp',
                },
                {
   
                    value: '选项9',
                    label: 'csp',
                },
                {
   
                    value: '选项10',
                    label: 'css',
                },
                {
   
                    value: '选项11',
                    label: 'dockerfile',
                },
                {
   
                    value: '选项12',
                    label: 'fsharp',
                },
                {
   
                    value: '选项13',
                    label: 'go',
                },
                {
   
                    value: '选项14',
                    label: 'handlebars',
                },
                {
   
                    value: '选项15',
                    label: 'html',
                },
                {
   
                    value: '选项16',
                    label: 'ini',
                },
                {
   
                    value: '选项17',
                    label: 'java',
                },
                {
   
                    value: '选项18',
                    label: 'javascript',
                },
                {
   
                    value: '选项19',
                    label: 'json',
                },
                {
   
                    value: '选项20',
                    label: 'less',
                },
                {
   
                    value: '选项21',
                    label: 'lua',
                },
                {
   
                    value: '选项22',
                    label: 'markdown',
                },
                {
   
                    value: '选项23',
                    label: 'msdax',
                },
                {
   
                    value: '选项24',
                    label: 'mysql',
                },
                {
   
                    value: '选项25',
                    label: 'objective',
                },
                {
   
                    value: '选项26',
                    label: 'pascal',
                },
                {
   
                    value: '选项27',
                    label: 'perl',
                },
                {
   
                    value: '选项28',
                    label: 'pgsql',
                },
                {
   
                    value: '选项29',
                    label: 'php',
                },
                {
   
                    value: '选项30',
                    label: 'postiats',
                },
                {
   
                    value: '选项31',
                    label: 'powerquery',
                },
                {
   
                    value: '选项32',
                    label: 'powershell',
                },
                {
   
                    value: '选项33',
                    label: 'pug',
                },
                {
   
                    value: '选项34',
                    label: 'python',
                },
                {
   
                    value: '选项35',
                    label: 'r',
                },
                {
   
                    value: '选项36',
                    label: 'razor',
                },
                {
   
                    value: '选项37',
                    label: 'redis',
                },
                {
   
                    value: '选项38',
                    label: 'redshift',
                },
                {
   
                    value: '选项39',
                    label: 'ruby',
                },
                {
   
                    value: '选项40',
                    label: 'rust',
                },
                {
   
                    value: '选项41',
                    label: 'sb',
                },
                {
   
                    value: '选项42',
                    label: 'scheme',
                },
                {
   
                    value: '选项43',
                    label: 'scss',
                },
                {
   
                    value: '选项44',
                    label: 'shell',
                },
                {
   
                    value: '选项45',
                    label: 'sol',
                },
                {
   
                    value: '选项46',
                    label: 'sql',
                },
                {
   
                    value: '选项47',
                    label: 'st',
                },
                {
   
                    value: '选项48',
                    label: 'swift',
                },
                {
   
                    value: '选项49',
                    label: 'typescript',
                },
                {
   
                    value: '选项50',
                    label: 'vb',
                },
                {
   
                    value: '选项51',
                    label: 'xml',
                },
                {
   
                    value: '选项52',
                    label: 'yaml'
                }
            ],
            //支持的主题
            theme: [
                {
   
                    value: '选项1',
                    label: 'Visual Studio',
                },
                {
   
                    value: '选项2',
                    label: 'Visual Studio Dark',
                },
                {
   
                    value: '选项3',
                    label: 'Hight Contrast Dark',
                },
            ],
            value: ''
        };
    }

    //改变主题,通过Select的onChnage触发
    handleSelectTheme(event){
   
        //根据选择设置对主题的值
        let selectval = '';
        if (event === '选项1') {
   
            selectval = 'vs';
        } else if (event === '选项2') {
   
            selectval = 'vs-dark';
        } else if (event === '选项3') {
   
            selectval = 'hc-black';
        }
        //通过调用父组件的方法,修改父组件中的state
        this.props.ChangeTheme(selectval);
    }

    //改变语言,通过Select的onChnage触发
    handleSelectLanguage(event){
   
        //通过调用父组件的方法,修改父组件中的state,修改的是语言
        this.props.ChangeLanguage(event);
        for(let i = 0;i < valueData.values.length;i++)
        {
   
            if (valueData.values[i].language === event)
            {
   
                //通过调用父组件的方法,修改父组件中的state
                //修改的是编辑框中显示的内容
                //这里是用的是json数据
                this.props.ChangeValue(valueData.values[i].value);
            }
        }
    }

    render() {
   
        return (
            <div>
                <Layout.Row>
                    <Layout.Col span="12">
                        <div className="grid-content bg-purple-light">
                            <span>主题:</span>
                            <Select value={
   this.state.value} placeholder="请选择" onChange={
   this.handleSelectTheme.bind(this)}>
                                {
   
                                    this.state.theme.map(el => {
   
                                        return <Select.Option  key={
   el.value} label={
   el.label} value={
   el.value}/>
                                    })
                                }
                            </Select>
                        </div>
                    </Layout.Col>
                    <Layout.Col span="12">
                        <div className="grid-content bg-purple-light">
                            <span>语言:</span>
                            <Select value={
   this.state.value} placeholder="请选择" onChange={
   this.handleSelectLanguage.bind(this)}>
                                {
   
                                    this.state.options.map(el => {
   
                                        return <Select.Option  key={
   el.value} label={
   el.label} value={
   el.label}/>
                                    })
                                }
                            </Select>
                        </div>
                    </Layout.Col>
                </Layout.Row>
            </div>
        );
    }
}

export default SelectBox;

json数据
{
   
  "values": [
    {
   
      "language": "apex",
      "value": "/* Using a single database query, find all the leads in\n    the database that have the same email address as any\n    of the leads being inserted or updated. */\nfor (Lead lead : [SELECT Email FROM Lead WHERE Email IN :leadMap.KeySet()]) {\n    Lead newLead = leadMap.get(lead.Email);\n    newLead.Email.addError('A lead with this email address already exists.');\n}\n"


    },
    {
   
      "language": "azcli",
      "value": "# Create a resource group.\naz group create --name myResourceGroup --location westeurope\n\n# Create a new virtual machine, this creates SSH keys if not present.\naz vm create --resource-group myResourceGroup --name myVM --image UbuntuLTS --generate-ssh-keys"
    },
    {
   
      "language": "bat",
      "value": "rem *******Begin Comment**************\nrem This program starts the superapp batch program on the network,\nrem directs the output to a file, and displays the file\nrem in Notepad.\nrem *******End Comment**************\n@echo off\nif exist C:\\output.txt goto EMPTYEXISTS\nsetlocal\n\tpath=g:\\programs\\superapp;%path%\n\tcall superapp>C:\\output.txt\nendlocal\n:EMPTYEXISTS\nstart notepad c:\\output.txt"
    },
    {
   
      "language": "clojure",
      "value": "(ns game-of-life\n  \"Conway's Game of Life, based on the work of\n  Christophe Grand (http://clj-me.cgrand.net/2011/08/19/conways-game-of-life)\n  and Laurent Petit (https://gist.github.com/1200343).\")\n\n;;; Core game of life's algorithm functions\n\n(defn neighbors\n  \"Given a cell's coordinates `[x y]`, returns the coordinates of its\n  neighbors.\"\n  [[x y]]\n  (for [dx [-1 0 1]\n        dy (if (zero? dx)\n             [-1 1]\n             [-1 0 1])]\n    [(+ dx x) (+ dy y)]))\n\n(defn step\n  \"Given a set of living `cells`, computes the new set of living cells.\"\n  [cells]\n  (set (for [[cell n] (frequencies (mapcat neighbors cells))\n             :when (or (= n 3)\n                       (and (= n 2)\n                            (cells cell)))]\n         cell)))\n\n;;; Utility methods for displaying game on a text terminal\n\n(defn print-grid\n  \"Prints a `grid` of `w` columns and `h` rows, on *out*, representing a\n  step in the game.\"\n  [grid w h]\n  (doseq [x (range (inc w))\n          y (range (inc h))]\n    (when (= y 0) (println))\n    (print (if (grid [x y])\n             \"[X]\"\n             \" . \"))))\n\n(defn print-grids\n  \"Prints a sequence of `grids` of `w` columns and `h` rows on *out*,\n  representing several steps.\"\n  [grids w h]\n  (doseq [grid grids]\n    (print-grid grid w h)\n    (println)))\n\n;;; Launches an example grid\n\n(def grid\n  \"`grid` represents the initial set of living cells\"\n  #{[2 1] [2 2] [2 3]})\n\n(print-grids (take 3 (iterate step grid)) 5 5)"
    },
    {
   
      "language": "coffeescript",
      "value": "\"\"\"\nA CoffeeScript sample.\n\"\"\"\n\nclass Vehicle\n  constructor: (@name) =>\n  \n  drive: () =>\n    alert \"Conducting #{@name}\"\n\nclass Car extends Vehicle\n  drive: () =>\n    alert \"Driving #{@name}\"\n\nc = new Car \"Brandie\"\n\nwhile notAtDestination()\n  c.drive()\n\nraceVehicles = (new Car for i in [1..100])\n\nstartRace = (vehicles) -> [vehicle.drive() for vehicle in vehicles]\n\nfancyRegExp = ///\n\t(\\d+)\t# numbers\n\t(\\w*)\t# letters\n\t$\t\t# the end\n///\n"
    },
    {
   
      "language": "cpp",
      "value": "#include \"pch.h\"\n#include \"Direct3DBase.h\"\n\nusing namespace Microsoft::WRL;\nusing namespace Windows::UI::Core;\nusing namespace Windows::Foundation;\n\n// Constructor.\nDirect3DBase::Direct3DBase()\n{\n}\n\n// Initialize the Direct3D resources required to run.\nvoid Direct3DBase::Initialize(CoreWindow^ window)\n{\n    m_window = window;\n    \n    CreateDeviceResources();\n    CreateWindowSizeDependentResources();\n}\n\n// These are the resources that depend on the device.\nvoid Direct3DBase::CreateDeviceResources()\n{\n    // This flag adds support for surfaces with a different color channel ordering than the API default.\n    // It is recommended usage, and is required for compatibility with Direct2D.\n    UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;\n\n#if defined(_DEBUG)\n    // If the project is in a debug build, enable debugging via SDK Layers with this flag.\n    creationFlags |= D3D11_CREATE_DEVICE_DEBUG;\n#endif\n\n    // This array defines the set of DirectX hardware feature levels this app will support.\n    // Note the ordering should be preserved.\n    // Don't forget to declare your application's minimum required feature level in its\n    // description.  All applications are assumed to support 9.1 unless otherwise stated.\n    D3D_FEATURE_LEVEL featureLevels[] = \n    {\n        D3D_FEATURE_LEVEL_11_1,\n        D3D_FEATURE_LEVEL_11_0,\n        D3D_FEATURE_LEVEL_10_1,\n        D3D_FEATURE_LEVEL_10_0,\n        D3D_FEATURE_LEVEL_9_3,\n        D3D_FEATURE_LEVEL_9_2,\n        D3D_FEATURE_LEVEL_9_1\n    };\n\n    // Create the DX11 API device object, and get a corresponding context.\n    ComPtr device;\n    ComPtr context;\n    DX::ThrowIfFailed(\n        D3D11CreateDevice(\n            nullptr,                    // specify null to use the default adapter\n            D3D_DRIVER_TYPE_HARDWARE,\n            nullptr,                    // leave as nullptr unless software device\n            creationFlags,              // optionally set debug and Direct2D compatibility flags\n            featureLevels,              // list of feature levels this app can support\n            ARRAYSIZE(featureLevels),   // number of entries in above list\n            D3D11_SDK_VERSION,          // always set this to D3D11_SDK_VERSION\n            &device,                    // returns the Direct3D device created\n            &m_featureLeve

你可能感兴趣的:(React,Monaco)