Day31 | 提供程序码编辑的editor区域

大家好,我是韦恩,今天是铁人赛的第三十一天,今天我们来练习一下在web里怎麽提供editor区块编辑。之後我们会把编辑功能加到Webview里让使用者编辑。

今天,我会介绍一个javascript的工具prismjs。

Prismjs简介



[图源:prismjs官网截图]

在javascript的世界里,我们有非常多强大的editor可以使用,如知名的VSCode团队打造的Monaco Editor,此外还有ace等受欢迎的js编辑器工具。为什麽这边我们挑选了prismjs呢?

理由很简单:轻巧、快速

对於我们的使用情境,我们不需要太多强大的功能,把整个vscode的功能搬到Webview上,仅需要编辑程序码的区域与编辑器的外观样式。对於Webview而言,占用使用者的资源越少是越好的。

而Prismjs具有几个特性:

  • library体积小,核心gzip後仅有2kb,加了语言与主题样式也不超过4kb。
  • 速度快,如果需要,甚至可启用Webworker的功能。
    (在Webview里我们不会使用到,但还是值得提一下)
  • 容易调整样式,使用css即可客制化。

因为有以上特点,符合使用情境,我们选择了这个工具。

接下来,我们会使用prism-react-renderer这个套件,它会提供封装了prismjs套件的component。

让我们下载prism-react-renderer

yarn add prism-react-renderer //或是npm install prism-react-renderer 

下载完以後,我们可以import相关的component

import Highlight, { defaultProps } from 'prism-react-renderer';

并且可以这样使用

const editedCode = `

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('foo');
  }, 300);
});

promise1.then((value) => {
  console.log(value);
  // expected output: "foo"
});

console.log(promise1);
// expected output: [object Promise]
`;

class App extends Component<AppProps, AppState> {
  constructor(props) {
    super(props);
    this.state = {
      name: 'React'
    };
  }
  render() {
    return (
      <Highlight
        {...defaultProps}
        code={exampleCode}
        language="javascript"
      >
        {({ className, style, tokens, getLineProps, getTokenProps }) => (
          <pre className={className} style={style}>
            {tokens.map((line, i) => (
              <div {...getLineProps({ line, key: i })}>
                {line.map((token, key) => (
                  <span {...getTokenProps({ token, key })} />
                ))}
              </div>
            ))}
          </pre>
        )}
      </Highlight>
    );
  }
}

结语


好的,今天简单介绍将引入的套件。

明天我们继续实作,我们明天见,掰掰!


<<:  Day9 练习java-二维阵列

>>:  31.Module

爬虫怎麽爬 从零开始的爬虫自学 DAY14 python条件运算式

前言 各位早安,书接上回我们练习了条件判断语法 if else elif 的用法,今天我们要来介绍它...

19.MYSQL NOT指令

NOT与!的意思相同,它代表的意思是,运算结果为0时回传1,其他都回传1 WHERE NOT (AG...

DAY3 [从游戏带起兴趣-2]

第三天记录一样让大家从游戏中探索,最基本好理解的游戏,是帮助上手的好方法,但会相较昨天困难点喔。
 ...

Day16 Gin's Routing Structure And Context

Gin's Item Structure |-app |-common 公共方法 |-display...

7 种敏捷估算技术 (Agile Estimation Techniques)

敏捷估算 (Agile Estimation) 技术有助於估算并且猜测如何正确地计划和执行是很重要的...