【vscode】vscode插件学习(三)

前言

  • 今天继续学习制作vscode插件

本地读取文件

  • 本次制作本地看小说插件。
  • 就是本地txt文件在vscode里看小说。

贡献点

  • 我们要在左侧出现个图标,这里我直接整了个reactapp的logo弄来。
  • 当点击图标后激活命令,在左侧获取文件列表,点击后查看文件。
"activationEvents": [
		"onView:myread-list"
	],
	"main": "./dist/extension.js",
	"contributes": {
		"commands": [
			{
				"command": "storyvs.helloWorld",
				"title": "Hello World"
			}
		],
		"viewsContainers": {
			"activitybar": [
				{
					"id": "myread",
					"title": "myread",
					"icon": "images/logo192.png"
				}
			]
		},
		"views": {
			"myread": [
				{
					"name": "本地列表栏",
					"id": "myread-list"
				}
			]
		}
	},

代码

  • 老样子,在里面注册下命令
const op = vscode.commands.registerCommand("openSelectedNovel", (args) => {
		vscode.commands.executeCommand(
			"vscode.open",
			vscode.Uri.file(args.path)
		);
	});

	const provider = new Provider();
	const dis = vscode.window.registerTreeDataProvider("myread-list", provider);
	context.subscriptions.push(dis);
	context.subscriptions.push(op);
  • 这个open的命令是点击左侧后打开文件的命令。
  • myread-list则是点击左侧后激活的。
  • 其中要传个provider,它是对TreeDataProvider的实现。这个类比较关键,它可以控制左侧显示成啥样。provider需要实现2个方法,他们返回值就是下面说的novelitem实例
function getLocalBooks(): Promise<NovelItem[]> {
	const files = Fs.readdirSync(localNovelsPath);
	const localnovellist: NovelItem[] = [];
	files.forEach((file: string) => {
		const extname = Path.extname(file).substr(1);
		if (extname === "txt") {
			const name = Path.basename(file, ".txt");
			const path = Path.join(localNovelsPath, file);
			localnovellist.push({
				path,
				name,
			});
		}
	});
	return Promise.resolve(localnovellist);
}

class Provider implements vscode.TreeDataProvider<NovelItem> {
	// 提供单行的UI展示
	getTreeItem(info: NovelItem): NovelTreeItem {
		return new NovelTreeItem(info);
	}
	// 提供每一行的数据
	getChildren(): Promise<NovelItem[]> {
		return getLocalBooks();
	}
}
  • noveltreeitem是每一行的实例,一般是继承它默认的,然后拿我们数据对其改造
const localNovelsPath = `D:\\frontpro\\vscodego\\storyvs`;

interface NovelItem {
	name: string;
	path: string;
}

class NovelTreeItem extends TreeItem {
	constructor(info: NovelItem) {
		super(`${info.name}`);

		const tips = [`名称: ${info.name}`];
		// tooltip是悬浮的条提示
		this.tooltip = tips.join("\r\n");
		// 我们设置一下点击该行的命令,并且传参进去
		this.command = {
			command: "openSelectedNovel",
			title: "打开该小说",
			arguments: [{ name: info.name, path: info.path }],
		};
	}
}
  • 当点击每个item实例,则触发前面已注册的command命令,这样就形成了闭环。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

业火之理

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值