6

开发者的福利 - NutUI-VSCode 智能提示来了

 2 years ago
source link: https://jelly.jd.com/article/6278e71f8acc790195e0c254
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

NutUI-VSCode 智能提示来了

开发者的福利 - NutUI-VSCode 智能提示来了
上传日期:2022.05.10
NutUI v3 版本发布至今已经 1 年了,无论是集团内部还是外部开发者,都在各自不同的业务场景中开发使用,我们感到骄傲的同时也是压力倍增,积极努力修复开发者的各种 Issue,扩展组件功能,尽可能满足开发者诉求。今年以来陆续补充了多技术栈(React)、组件级 UI 定制、国际化及代码智能提示能力。本篇将介绍代码智能提示(VSCode插件)的功能,并就 NutUI-VSCode 的实现给大家做一个详尽的剖析。

什么是代码智能提示?为了让大家有一个直观的认识,让我们先来仔细观察下面两张 gif 图~

组件库没有任何的代码提示

11d36b920f7b79f2.png

组件库有了智能提示之后

11d36b920f7b79f2.png

不知大家在看了上面两张图片之后有什么样的感想?很明显,我们使用了智能提示之后,无论是快速查看文档,还是查看组件属性,都会很方便的进行查阅,当然开发效率上肯定也有了显著的提升。那么,让我们快来亲自体验下吧~

11d36b920f7b79f2.png

Tips: NutUI官网-开发工具支持 ,这里也有简要介绍哦~

  • vscode 中安装 nutui-vscode-extension 插件
11d36b920f7b79f2.png
  • 安装 vetur 插件。不了解这个插件的 这里 有介绍
11d36b920f7b79f2.png

安装完成以上两个插件之后,重新启动我们的 vscode ,就可以愉快的体验 NutUI 的智能提示功能啦,是不是简直不要太简单~

体验也结束了,是不是该跟我一起熟悉熟悉它的原理啦。既然是开发 vscode 插件,那首先我们一定是要先熟悉它的开发以及调试、发布流程。一份文档送给你哦。 看这里

熟悉了基本的 vscode 开发流程之后,下面就跟随我一步步揭开这个智能提示功能的神秘面纱吧~

360全方位解读

11d36b920f7b79f2.png

快速查看组件文档

11d36b920f7b79f2.png

从上图可以看出,当我们在使用 NutUI 进行开发的时候,我们在写完一个组件 nut-button,鼠标 Hover 到组件上时,会出现一个提示,点击提示可以打开 Button 组件的官方文档。我们可快速查看对应的 API 来使用它开发。

首先我们需要在 vscode 生成的项目中,找到对应的钩子函数 activate ,在这里面注册一个 Provider,然后针对定义好的类型文件 files 通过 provideHover 来进行解析。

const files = ['vue', 'typescript', 'javascript', 'react'];

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.languages.registerHoverProvider(files, {
      provideHover
    })
  );
}

下面我们可以具体看看 provideHover 是如何实现的?

const LINK_REG = /(?<=<nut-)([\w-]+)/g;
const BIG_LINK_REG = /(?<=<Nut-)([\w-])+/g;
const provideHover = (document: vscode.TextDocument, position: vscode.Position) => {
  const line = document.lineAt(position); //根据鼠标的位置读取当前所在行
  const componentLink = line.text.match(LINK_REG) ?? [];//对 nut-开头的字符串进行匹配
  const componentBigLink = line.text.match(BIG_LINK_REG) ?? [];
  const components = [...new Set([...componentLink, ...componentBigLink.map(kebabCase)])]; //匹配出当前Hover行所包含的组件

  if (components.length) {
    const text = components
      .filter((item: string) => componentMap[item])
      .map((item: string) => {
        const { site } = componentMap[item];

        return new vscode.MarkdownString(
          `[NutUI -> $(references) 请查看 ${bigCamelize(item)} 组件官方文档](${DOC}${site})\n`,
          true
        );
      });

    return new vscode.Hover(text);
  }
};

通过 vscode 提供的 API 以及 对应的正则匹配,获取当前 Hover 行所包含的组件,然后通过遍历的方式返回不同组件对应的 MarkDownString,最后返回 vscode.Hover 对象。

细心的你们可能发现了,这里面还包含了一个 componentMap ,它是一个对象,里面包含了所有组件的官网链接地址以及 props 信息,它大致的内容是这样的:

export interface ComponentDesc {
  site: string;
  props?: string[];
}

export const componentMap: Record<string, ComponentDesc> = {
    actionsheet: {
        site: '/actionsheet',
        props: ["v-model:visible=''"]
    },
    address: {
        site: '/address',
        props: ["v-model:visible=''"]
    },
    addresslist: {
        site: '/addresslist',
        props: ["data=''"]
    }
    ...
}

为了能够保持每次组件的更新都会及时同步,componentMap 这个对象的生成会通过一个本地脚本执行然后自动注入,每次在更新发布插件的时候都会去执行一次,保证和现阶段的组件以及对应的信息保持一致。这里的组件以及它所包含的信息都需要从项目目录中获取,这里的实现和后面讲的一些内容相似,大家可以先想一下实现方式,具体实现细节在后面会一起详解~

组件自动补全

11d36b920f7b79f2.png

我们使用 NutUI 组件库进行项目开发,当我们输入 nut- 时,编辑器会给出我们目前组件库中包含的所有组件,当我们使用上下键快速选中其中一个组件进行回车,这时编辑器会自动帮我们补全选中的组件,并且能够带出当前所选组件的其中一个 props,方便我们快速定义。

这里的实现,同样我们需要在 vscode 的钩子函数 activate 中注册一个 Provider

vscode.languages.registerCompletionItemProvider(files, {
    provideCompletionItems,
    resolveCompletionItem
})

其中,provideCompletionItems ,需要输出用于自动补全的当前组件库中所包含的组件 completionItems

const provideCompletionItems = () => {
  const completionItems: vscode.CompletionItem[] = [];
  Object.keys(componentMap).forEach((key: string) => {
    completionItems.push(
      new vscode.CompletionItem(`nut-${key}`, vscode.CompletionItemKind.Field),
      new vscode.CompletionItem(bigCamelize(`nut-${key}`), vscode.CompletionItemKind.Field)
    );
  });
  return completionItems;
};

resolveCompletionItem 定义光标选中当前自动补全的组件时触发的动作,这里我们需要重新定义光标的位置。

const resolveCompletionItem = (item: vscode.CompletionItem) => {
  const name = kebabCase(<string>item.label).slice(4);
  const descriptor: ComponentDesc = componentMap[name];

  const propsText = descriptor.props ? descriptor.props : '';
  const tagSuffix = `</${item.label}>`;
  item.insertText = `<${item.label} ${propsText}>${tagSuffix}`;

  item.command = {
    title: 'nutui-move-cursor',
    command: 'nutui-move-cursor',
    arguments: [-tagSuffix.length - 2]
  };
  return item;
};

其中, arguments代表光标的位置参数,一般我们自动补全选中之后光标会在 props 的引号中,便于用来定义,我们结合目前补全的字符串的规律,这里光标的位置是相对确定的。就是闭合标签的字符串长度 -tagSuffix.length,再往前面 2 个字符的位置。即 arguments: [-tagSuffix.length - 2]

最后,nutui-move-cursor 这个命令的执行需要在 activate 钩子函数中进行注册,并在 moveCursor 中执行光标的移动。这样就实现了我们的自动补全功能。

const moveCursor = (characterDelta: number) => {
  const active = vscode.window.activeTextEditor!.selection.active!;
  const position = active.translate({ characterDelta });
  vscode.window.activeTextEditor!.selection = new vscode.Selection(position, position);
};

export function activate(context: vscode.ExtensionContext) {
  vscode.commands.registerCommand('nutui-move-cursor', moveCursor);
}

什么?有了这些还不够?有没有更加智能化的,我不用看组件文档,照样可以轻松开发。emm~~~,当然,请听下文讲解

vetur 智能化提示

提到 vetur,熟悉 Vue 的同学一定不陌生,它是 Vue 官方开发的插件,具有代码高亮提示、识别 Vue 文件等功能。通过借助于它,我们可以做到自己组件库里的组件能够自动识别 props 并进行和官网一样的详细说明。

vetur详细介绍看这里

11d36b920f7b79f2.png

像上面一样,我们在使用组件 Button 时,它会自动提示组件中定义的所有属性。当按上下键快速切换时,右侧会显示当前选中属性的详细说明,这样,我们无需查看文档,这里就可以看到每个属性的详细描述以及默认值,这样的开发简直爽到起飞~

仔细读过文档就可以了解到,vetur 已经提供给了我们配置项,我们只需要简单配置下即可,像这样:

//packag.json
{
    ...
    "vetur": {
        "tags": "dist/smartips/tags.json",
        "attributes": "dist/smartips/attributes.json"
    },
    ...
}

tags.jsonattributes.json 需要包含在我们的打包目录中。当前这两个文件的内容,我们也可以看下:

// tags.json
{
  "nut-actionsheet": {
      "attributes": [
        "v-model:visible",
        "menu-items",
        "option-tag",
        "option-sub-tag",
        "choose-tag-value",
        "color",
        "title",
        "description",
        "cancel-txt",
        "close-abled"
      ]
  },
  ...
}
//attributes.json
{
    "nut-actionsheet/v-model:visible": {
        "type": "boolean",
        "description": "属性说明:遮罩层可见,默认值:false"
    },
    "nut-actionsheet/menu-items": {
        "type": "array",
        "description": "属性说明:列表项,默认值:[ ]"
    },
    "nut-actionsheet/option-tag": {
        "type": "string",
        "description": "属性说明:设置列表项标题展示使用参数,默认值:'name'"
    },
    ...
}

很明显,这两个文件也是需要我们通过脚本生成。和前面提到的一样,这里涉及到组件以及和它们关联的信息,为了能够保持一致并且维护一份,我们这里通过每个组件源码下面的 doc.md 文件来获取。因为,这个文件中包含了组件的 props 以及它们的详细说明和默认值。

组件 props 详细信息

tags, attibutes, componentMap 都需要获取这些信息。 我们首先来看看 doc.md 中都包含什么?

## 介绍
## 基本用法
...
### Prop

| 字段     | 说明                                                             | 类型   | 默认值 |
| -------- | ---------------------------------------------------------------- | ------ | ------ |
| size     | 设置头像的大小,可选值为:large、normal、small,支持直接输入数字   | String | normal |
| shape    | 设置头像的形状,可选值为:square、round            | String | round  |
...

每个组件的 md 文档,我们预览时是通过 vite 提供的插件 vite-plugin-md,来生成对应的 html,而这个插件里面引用到了 markdown-it 这个模块。所以,我们现在想要解析 md 文件,也需要借助于 markdown-it 这个模块提供的 parse API.

// Function getSources
let sources = MarkdownIt.parse(data, {});
// data代表文档内容,sources代表解析出的list列表。这里解析出来的是Token列表。
11d36b920f7b79f2.png

Token 中,我们只关心 type 即可。因为我们要的是 props,这部分对应的 Tokentype 就是 table_opentable_close 中间所包含的部分。考虑到一个文档中有多个 table。这里我们始终取第一个,* 这也是要求我们的开发者在写文档时需要注意的地方 *

拿到了中间的部分之后,我们只要在这个基础上再次进行筛选,选出 tr_opentr_close 中间的部分,然后再筛选中间 type = inline 的部分。最后取 Token 这个对象中的 content 字段即可。然后在根据上面三个文件不同的需求做相应的处理即可。

const getSubSources = (sources) => {
  let sourcesMap = [];
  const startIndex = sources.findIndex((source) => source.type === TYPE_IDENTIFY_OPEN);
  const endIndex = sources.findIndex((source) => source.type === TYPE_IDENTIFY_CLOSE);
  sources = sources.slice(startIndex, endIndex + 1);
  while (sources.filter((source) => source.type === TR_TYPE_IDENTIFY_OPEN).length) {
    let trStartIndex = sources.findIndex((source) => source.type === TR_TYPE_IDENTIFY_OPEN);
    let trEndIndex = sources.findIndex((source) => source.type === TR_TYPE_IDENTIFY_CLOSE);
    sourcesMap.push(sources.slice(trStartIndex, trEndIndex + 1));
    sources.splice(trStartIndex, trEndIndex - trStartIndex + 1);
  }
  return sourcesMap;
};

好了,以上就是解析的全部内容了。总结起来就那么几点:

1、创建一个基于 vscode 的项目,在它提供的钩子中注册不同行为的 commandlanguages,并实现对应的行为

2、结合 vetur,配置 packages.json

3、针对 map json 文件,需要提供相应的生成脚本,确保信息的一致性。这里解析 md 需要使用 markdown-it 给我们提供的 parse 功能。

本文从直观体验到实际使用再到实现原理分析,一步步带着大家感受了 NutUIVSCode 结合,给大家带来的福利,让大家能在开发上有了全新的体验,同时,也让我们的组件库越发充满了魅力。接下来,让我们共同携手,让它发挥出更加强大的价值~

期待您的使用与 反馈 ❤️~


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK