Skip to content

Commit

Permalink
add JsFile patch (#462)
Browse files Browse the repository at this point in the history
  • Loading branch information
shalldie committed Oct 11, 2024
1 parent 8608567 commit 271c0a3
Show file tree
Hide file tree
Showing 11 changed files with 371 additions and 39 deletions.
2 changes: 1 addition & 1 deletion .prettierrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = {
arrowParens: 'avoid',
overrides: [
{
files: ['*.md', '*.json', '*.ya?ml'],
files: ['*.md', 'package(-lock)?.json', '*.ya?ml'],
options: {
singleQuote: false,
tabWidth: 2
Expand Down
1 change: 1 addition & 0 deletions docs/WELCOME.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# vscode-background
5 changes: 5 additions & 0 deletions docs/WELCOME.zh-CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# vscode-background

欢迎使用 `background v2` !

![](../images/logo.png)
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@
"category": "Background",
"title": "%extension.background.command.install.title%"
},
{
"command": "extension.background.disable",
"category": "Background",
"title": "%extension.background.command.disable.title%"
},
{
"command": "extension.background.uninstall",
"category": "Background",
Expand Down
3 changes: 2 additions & 1 deletion package.nls.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"extension.background.command.info.title": "View plugin info",
"extension.background.command.install.title": "Installs and enables the background.",
"extension.background.command.install.title": "Install and enable the background.",
"extension.background.command.disable.title": "Disable the background.",
"extension.background.command.uninstall.title": "Uninstall plugin",

"extension.background.enabled.description": "Plugin background enabled.",
Expand Down
1 change: 1 addition & 0 deletions package.nls.zh.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"extension.background.command.info.title": "查看插件信息",
"extension.background.command.install.title": "安装/激活插件",
"extension.background.command.disable.title": "禁用插件",
"extension.background.command.uninstall.title": "卸载插件",

"extension.background.enabled.description": "background 插件是否启用",
Expand Down
127 changes: 112 additions & 15 deletions src/background/Background.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import fs from 'fs';
import { tmpdir } from 'os';
import path from 'path';

import vscode, { Disposable } from 'vscode';
import vscode, { Disposable, Uri } from 'vscode';

import { ENCODING, TOUCH_FILE_PATH } from '../constants';
import { ENCODING, EXTENSION_NAME, TOUCH_FILE_PATH } from '../constants';
import { utils } from '../utils';
import { vscodePath } from '../utils/vscodePath';
import { vsHelp } from '../utils/vsHelp';
import { CssFile, ECSSEditType } from './CssFile';
import { CssGenerator, TCssGeneratorOptions } from './CssGenerator';
import { JsFile } from './JsFile';

/**
* 配置类型
Expand All @@ -30,14 +33,18 @@ export class Background implements Disposable {
*/
public cssFile = new CssFile(vscodePath.cssPath); // 没必要继承,组合就行

public jsFile = new JsFile(vscodePath.jsPath);

/**
* 当前用户配置
*
* @private
* @type {TConfigType}
* @memberof Background
*/
private config: TConfigType = vscode.workspace.getConfiguration('background') as TConfigType;
public get config() {
return vscode.workspace.getConfiguration('background') as TConfigType;
}

/**
* 需要释放的资源
Expand All @@ -64,17 +71,95 @@ export class Background implements Disposable {

if (firstLoad) {
// 提示
// vscode.env.language
vscode.commands.executeCommand('extension.background.info');
this.showWelcome();
// 标识插件已启动过
await fs.promises.writeFile(TOUCH_FILE_PATH, vscodePath.cssPath, ENCODING);

return true;
}

return false;
}

public async showWelcome() {
// 欢迎页
const docDir = path.join(__dirname, '../../docs');
const docName = /^zh/.test(vscode.env.language) ? 'WELCOME.zh-CN.md' : 'WELCOME.md';

let content = await fs.promises.readFile(path.join(docDir, docName), ENCODING);
content = content.replace(/\.\.\/images[^\)]+/g, (relativePath: string) => {
const imgPath = path.join(vscodePath.extensionRoot, 'images', relativePath);

return (
`data:image/${path.extname(imgPath).slice(1) || 'png'};base64,` +
Buffer.from(fs.readFileSync(imgPath)).toString('base64')
);
});

const targetPath = path.join(tmpdir(), 'welcome-to-background.md');
await fs.promises.writeFile(targetPath, content, ENCODING);
vscode.commands.executeCommand('markdown.showPreviewToSide', Uri.file(targetPath));
}

/**
* 移除旧版本css文件中的patch
*
* @private
* @return {*}
* @memberof Background
*/
private async removeLegacyCssPatch() {
const hasInstalled = await this.cssFile.hasInstalled();
if (!hasInstalled) {
return;
}
await this.cssFile.uninstall();
}

private async onConfigChange() {
const hasInstalled = await this.jsFile.hasInstalled();
const enabled = this.config.enabled;

// 禁用
if (!enabled) {
if (hasInstalled) {
await this.jsFile.uninstall();
vsHelp.showInfoRestart('Background has been disabled! Please restart.');
}
return;
}

// 更新,需要二次确认
const confirm = await vscode.window.showInformationMessage('Configuration has been changed, click to update.', {
title: 'Update and restart'
});

if (!confirm) {
return;
}

await this.applyPatch();
vscode.commands.executeCommand('workbench.action.reloadWindow');
}

public async applyPatch() {
// 禁用时候,不处理
if (!this.config.enabled) {
return;
}

const cssTxt = await CssGenerator.create(this.config);

const scriptContent = `
(function(){
var style = document.createElement('style');
style.textContent = ${JSON.stringify(cssTxt)};
document.body.appendChild(style);
})();
`;

this.jsFile.applyPatch(scriptContent);
}

// #endregion

// #region public methods
Expand Down Expand Up @@ -105,7 +190,7 @@ export class Background implements Disposable {
}

// 3.保存当前配置
this.config = config; // 更新配置
// this.config = config; // 更新配置

// 4.如果关闭插件
if (!config.enabled) {
Expand Down Expand Up @@ -145,22 +230,33 @@ export class Background implements Disposable {
* @memberof Background
*/
public async setup(): Promise<void> {
await this.removeLegacyCssPatch();
const firstload = await this.checkFirstload(); // 是否初次加载插件

const editType = await this.cssFile.getEditType(); // css 文件目前状态

// 如果是第一次加载插件,或者旧版本
if (firstload || editType === ECSSEditType.IsOld || editType === ECSSEditType.NoModified) {
await this.install(true);
}
// if (firstload || editType === ECSSEditType.IsOld || editType === ECSSEditType.NoModified) {
// await this.install(true);
// }

// 监听文件改变
this.disposables.push(
vscode.workspace.onDidChangeConfiguration(async () => {
vscode.workspace.onDidChangeConfiguration(async ex => {
const hasChanged = ex.affectsConfiguration(EXTENSION_NAME);
if (!hasChanged) {
return;
}

this.onConfigChange();

// await this.applyPatch();
// vsHelp.showInfoRestart('Background has been changed! Please restart.');

// 0~500ms 的延时,对于可能的多实例,错开对于文件的操作
// 虽然有锁了,但这样更安心 =。=
await utils.sleep(~~(Math.random() * 500));
this.install();
// await utils.sleep(~~(Math.random() * 500));
// this.install();
})
);
}
Expand All @@ -172,7 +268,7 @@ export class Background implements Disposable {
* @memberof Background
*/
public hasInstalled(): Promise<boolean> {
return this.cssFile.hasInstalled();
return this.jsFile.hasInstalled();
}

/**
Expand All @@ -182,7 +278,8 @@ export class Background implements Disposable {
* @memberof Background
*/
public uninstall(): Promise<boolean> {
return this.cssFile.uninstall();
// return this.cssFile.uninstall();
return this.jsFile.uninstall();
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/background/CssGenerator/CssGenerator.base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export abstract class AbsCssGenerator<T = any> {
const styles = this.compileCSS(source);

if (process.env.NODE_ENV === 'development') {
console.log(styles);
// console.log(styles);
}

return `
Expand Down
Loading

0 comments on commit 271c0a3

Please sign in to comment.