Skip to content

Commit

Permalink
v0.3.0
Browse files Browse the repository at this point in the history
Fixed #5 Duplicate code entries at Auto refresh
  • Loading branch information
eoureo committed Jun 28, 2023
1 parent 1f386d6 commit 7929344
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 41 deletions.
33 changes: 22 additions & 11 deletions README.ko-KR.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,7 @@

RunJS는 [옵시디언](https://obsidian.md/)에서 JavaScript 코드를 실행하기 위한 플러그인입니다. 별도의 플러그인을 생성할 필요 없이 사소한(?) 코드들을 바로 실행할 수 있습니다. 그러나 다른 플러그인과 마찬가지로 Obsidian 및 노트들을 다루는 코드를 실행할 수 있습니다. 실행 코드는 옵시디언 노트들의 코드블록(.md) 또는 별도의 파일(.js, .mjs)로 작성됩니다. 또한 코드를 실행 가능한 코드와 모듈로 나누어 코드 관리를 할 수 있도록 합니다.

![Obsidian-RunJS FrontMatter test](images/Obsidian_RunJS_FrontMatter_test_1600.gif)<p ><small>간단한 사용 방법을 보여 줍니다. Codelist View에서 명령어(Toggle cssclass width-100)를 클릭합니다. 그러면 frontmatter의 cssclass에 "width-100" 값을 추가합니다. CSS Snippets에 저장된 스타일이 적용되어 노트 너비가 넓어집니다. 다시 클릭하면 "width-100" 값이 제거되고 노트의 너비가 원래 너비로 돌아갑니다. "코드 파일 열기" 명령을 실행하면 그 코드를 볼 수 있습니다. 그런 다음 필요하면 고칠 수도 있습니다.</small></p>

[Discussions - Codes](https://github.com/eoureo/obsidian-runjs/discussions)에서 쓸모있는 코드들을 볼 수 있습니다. 여기에 계속 코드들을 올리도록 하겠습니다. 또한 [Discussions - Codes Share](https://github.com/eoureo/obsidian-runjs/discussions/categories/codes-share)에 당신이 만든 코드를 공유하고 소개하여 주세요.

**주의 사항**:
*코드들은 다른 플러그인들과 동일한 작업을 수행할 수 있습니다. 따라서 잘못된 코드는 옵시디언이나 노트들을 망가뜨릴 수 있습니다. 코드를 실행하기 전에 안전한 코드인지 확인해야 합니다.*
![Obsidian-RunJS FrontMatter test](images/Obsidian_RunJS_FrontMatter_test_1600.gif)<p ><small>간단한 [사용 방법](https://github.com/eoureo/obsidian-runjs/discussions/10)을 보여 줍니다. Codelist View에서 명령어(Toggle cssclass width-100)를 클릭합니다. 그러면 frontmatter의 cssclass에 "width-100" 값을 추가합니다. CSS Snippets에 저장된 스타일이 적용되어 노트 너비가 넓어집니다. 다시 클릭하면 "width-100" 값이 제거되고 노트의 너비가 원래 너비로 돌아갑니다. "코드 파일 열기" 명령을 실행하면 그 코드를 볼 수 있습니다. 그런 다음 필요하면 고칠 수도 있습니다.</small></p>


## 특징
Expand All @@ -22,12 +17,28 @@ RunJS는 [옵시디언](https://obsidian.md/)에서 JavaScript 코드를 실행
- **리본 아이콘 추가**: 코드를 바로 실행할 수 있도록 리본에 아이콘을 추가합니다.

- **코드 종류**: 자바스크립트 모듈 시스템이 가능합니다.
- **스크립트**: t:"s"(기본값)로 설정된 코드 (노트의 코드블럭 안에 위치) 또는 .js 파일 (RunJS 스크립트 폴더 안에 위치)
- **모듈**: t:"m"로 설정된 코드 (노트의 코드블럭 안에 위치) 또는 .mjs 파일 (RunJS 스크립트 폴더 안에 위치)
- **스크립트**:
- 노트의 코드블럭 안에 t:"s"(기본값)로 설정된 코드
- .js 파일 (RunJS 스크립트 폴더 안에 위치)
- **모듈**:
- 노트의 코드블럭 안에 t:"m"로 설정된 코드
- .mjs 파일 (RunJS 스크립트 폴더 안에 위치)

- **코드 작성**: 다른 플러그인을 개발할 때 코드를 수정없이 바로 사용할 수 있습니다.


## 코드를 얻는 방법

자신 환경에 맞게 코드를 수정하세요. 일반적으로 바꿀 필요가 있는 설정은 코드 맨 위에 있습니다.

- **Codes of RunJS**: [Discussions - Codes](https://github.com/eoureo/obsidian-runjs/discussions)에서 쓸모있는 코드들을 볼 수 있습니다. 여기에 계속 코드들을 올리도록 하겠습니다.
- **Codes Share**: [Discussions - Codes Share](https://github.com/eoureo/obsidian-runjs/discussions/categories/codes-share)에 당신이 만든 코드를 공유하고 소개하여 주세요.


**⚠️ 주의 사항**:
*코드들은 다른 플러그인들과 동일한 작업을 수행할 수 있습니다. 따라서 잘못된 코드는 옵시디언이나 노트들을 망가뜨릴 수 있습니다. 코드를 실행하기 전에 안전한 코드인지 확인해야 합니다.*


## 시작 - Hello, World!

````markdown
Expand All @@ -45,7 +56,7 @@ new Notice("Hello, World!");
아래 링크에서 더 볼 수 있습니다.

Hello, World! : Discussions - Codes
https://github.com/eoureo/obsidian-runjs/discussions/2
[https://github.com/eoureo/obsidian-runjs/discussions/2](https://github.com/eoureo/obsidian-runjs/discussions/2)


## 쓸모있는 코드들
Expand Down Expand Up @@ -95,8 +106,8 @@ runJS.openIconModal();

아래 링크에서 더 보실 수 있습니다.

Open icon modal : Discussions - Codes
https://github.com/eoureo/obsidian-runjs/discussions/3
Open icon modal : Discussions - Codes
[https://github.com/eoureo/obsidian-runjs/discussions/3](https://github.com/eoureo/obsidian-runjs/discussions/3)


### 스크립트와 모듈
Expand Down
33 changes: 22 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,7 @@

RunJS is a plugin for running JavaScript code in [Obsidian](https://obsidian.md/). You can directly run trivial(?) code snippets without having to create a separate plugin. But, like any other plugin, you can run code that manages Obsidian and notes. Codes is written as codeblocks (.md) in Obsidian Notes or as separate files (.js, .mjs). You also have the option to break down your code into executable code and modules to give you better organization.

![Obsidian-RunJS FrontMatter test](images/Obsidian_RunJS_FrontMatter_test_1600.gif)<p ><small>This is a simple usage example. Click on a command(Toggle cssclass width-100) in the Codelist View. Then add "width-100" value to cssclass in frontmatter. The style saved in CSS Snippets is applied, making note wider. Clicking on it again removes the "width-100" value and the width of the note returns to its original width. Run "Open code file" command and you can see the code. Then you can modify it.</small></p>

You can see some useful code in [Discussions - Codes](https://github.com/eoureo/obsidian-runjs/discussions). I'll keep posting the codes here. Also, please share and introduce your code to [Discussions - Codes Share](https://github.com/eoureo/obsidian-runjs/discussions/categories/codes-share).

**Caution**:
*Codes can do the same thing as other plugins. So bad code can potentially disrupt Obsidian or corrupt notes. It is important to ensure that the code is safe before executing it.*
![Obsidian-RunJS FrontMatter test](images/Obsidian_RunJS_FrontMatter_test_1600.gif)<p ><small>This is a simple usage [example](https://github.com/eoureo/obsidian-runjs/discussions/10). Click on a command(Toggle cssclass width-100) in the Codelist View. Then add "width-100" value to cssclass in frontmatter. The style saved in CSS Snippets is applied, making note wider. Clicking on it again removes the "width-100" value and the width of the note returns to its original width. Run "Open code file" command and you can see the code. Then you can modify it.</small></p>


## Features
Expand All @@ -22,12 +17,28 @@ You can see some useful code in [Discussions - Codes](https://github.com/eoureo/
- **Add Ribbon icon**: Add an icon to Ribbon to run code right away.

- **Code types**: JavaScript module system is available.
- **script**: code set to t:"s" (default) (in codeblock of note) or .js file (in RunJS Scripts folder)
- **module**: code set to t:"m" (in codeblock of note) or .mjs file (in RunJS Scripts folder)
- **script**:
- code set to t:"s" (default) in codeblock of note
- js file in RunJS Scripts folder
- **module**:
- code set to t:"m" in codeblock of note
- .mjs file in RunJS Scripts folder

- **Coding**: When developing other plugins, the code can be used directly without modification.


## How to get code

Modify the code to suit your environment. Settings that usually need to be changed are at the top of the code.

- **Codes of RunJS**: You can see some useful code in [Discussions - Codes of RunJS](https://github.com/eoureo/obsidian-runjs/discussions/categories/codes-of-runjs). I'll keep posting the codes here.
- **Codes Share**: Please share and introduce your code to [Discussions - Codes Share](https://github.com/eoureo/obsidian-runjs/discussions/categories/codes-share).


**⚠️ Caution**:
*Codes can do the same thing as other plugins. So bad code can potentially disrupt Obsidian or corrupt notes. It is important to ensure that the code is safe before executing it.*


## Start - Hello, World!

````markdown
Expand All @@ -45,7 +56,7 @@ new Notice("Hello, World!");
You can see more at the link below.

Hello, World! : Discussions - Codes
https://github.com/eoureo/obsidian-runjs/discussions/2
[https://github.com/eoureo/obsidian-runjs/discussions/2](https://github.com/eoureo/obsidian-runjs/discussions/2)


## Useful starter codes
Expand Down Expand Up @@ -95,8 +106,8 @@ runJS.openIconModal();

You can see more at the link below.

Open icon modal : Discussions - Codes
https://github.com/eoureo/obsidian-runjs/discussions/3
Open icon modal : Discussions - Codes
[https://github.com/eoureo/obsidian-runjs/discussions/3](https://github.com/eoureo/obsidian-runjs/discussions/3)


### Scripts & Modules
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "runjs",
"name": "RunJS",
"version": "0.2.0",
"version": "0.3.0",
"minAppVersion": "0.15.0",
"description": "RunJS is a plugin for running JavaScript code in Obsidian (https://obsidian.md).",
"author": "eoureo",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "runjs",
"version": "0.2.0",
"version": "0.3.0",
"description": "RunJS is a plugin for running JavaScript code in Obsidian (https://obsidian.md).",
"main": "main.js",
"scripts": {
Expand Down
102 changes: 88 additions & 14 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,14 @@ interface ModulesLoaded {
[name: string]: { codeText: string; module: Module | null };
}

interface RefreshJob {
time?: number; timeoutId?: NodeJS.Timeout;
}

interface RefreshJobs {
[file_path: string]: RefreshJob;
}

export default class RunJSPlugin extends Plugin {
settings: RunJSPluginSettings;
codes: Code[];
Expand All @@ -131,6 +139,9 @@ export default class RunJSPlugin extends Plugin {
private _iconsObsidian: string[];
state: string;
runJSSymbol: symbol;
refreshId: number;
refreshJobs: RefreshJobs;
refreshLimitTime: number;

regexpCodeblockIndicator: RegExp = /^`{3,}(?:javascript|js) RunJS:(.*)/;
eventRenameFile: EventRef;
Expand All @@ -149,6 +160,9 @@ export default class RunJSPlugin extends Plugin {
this.modulesLoaded = {};
this.state = "initial";
this.runJSSymbol = Symbol(this.manifest.id);
this.refreshJobs = {};
this.refreshLimitTime = 3000;
this.refreshId = Date.now();

let oldSymbols = Object.getOwnPropertySymbols(window).filter(elem => elem.toString() == this.runJSSymbol.toString());
for(let oldSymbol of oldSymbols) {
Expand Down Expand Up @@ -292,7 +306,12 @@ export default class RunJSPlugin extends Plugin {
}

handleRenameFile(file: TAbstractFile, oldPath: string) {
if(!(file instanceof TFile)) return;
if (!(file instanceof TFile)) return;

this.applyRenameFile(file, oldPath);
}

applyRenameFile(file: TAbstractFile, oldPath: string) {

let checkChanged = false;

Expand All @@ -310,15 +329,35 @@ export default class RunJSPlugin extends Plugin {
}

async handleModifyFile(file: TAbstractFile) {
if(!(file instanceof TFile)) return;
if (!(file instanceof TFile)) return;

let job: RefreshJob;
const time = Date.now();
const jobName = "[modify]" + file.path;

if (jobName in this.refreshJobs) {
job = this.refreshJobs[jobName];
clearTimeout(job.timeoutId);
} else {
job = {};
this.refreshJobs[jobName] = job;
}

job.time = time;
job.timeoutId = setTimeout(() => {
delete this.refreshJobs[jobName];
this.applyModifyFile(file);
}, this.refreshLimitTime);
}

async applyModifyFile(file: TAbstractFile) {
await this.handleDeleteFile(file, false);
await sleep(500);
await this.handleCreateFile(file);
}

async handleCreateFile(file: TAbstractFile) {
if(!(file instanceof TFile)) return;
if (!(file instanceof TFile)) return;

let checkChanged = false;

Expand Down Expand Up @@ -360,7 +399,7 @@ export default class RunJSPlugin extends Plugin {
}

handleDeleteFile(file: TAbstractFile, doUpdate: boolean = true) {
if(!(file instanceof TFile)) return;
if (!(file instanceof TFile)) return;

const codesTarget = [];

Expand Down Expand Up @@ -483,12 +522,47 @@ export default class RunJSPlugin extends Plugin {
}

async refresh() {
await this.refreshCodes();
new Notice(this.manifest.name + ": codes updated");
this.listview.update();
const changed = await this.refreshCodes();

if (changed) {
new Notice(this.manifest.name + ": codes updated");
this.listview.update();
}
}

async refreshCodes() {
async refreshCodes(): Promise<boolean> {
let changed: boolean = true;

for ( let jobName in this.refreshJobs) {
clearTimeout(this.refreshJobs[jobName].timeoutId);
}
Object.keys(this.refreshJobs).forEach(
(jobName) => delete this.refreshJobs[jobName]
);

const refreshId = Date.now();
this.refreshId = refreshId;

const codesDataNew = {
codes: [],
codesScript: [],
codesModule: {}
}

if (refreshId < this.refreshId) return false;

await this.iterateCodeblocks(this.appendCode.bind(codesDataNew));

const tFolder: TFolder = <TFolder>(
this.app.vault.getAbstractFileByPath(this.settings.scriptsFolder)
);

if (refreshId < this.refreshId) return false;

await this.iterateScriptsFolder(tFolder, this.appendCode.bind(codesDataNew));

if (refreshId < this.refreshId) return false;

// initialize data
this.codes.splice(0, this.codes.length);
this.codesScript.splice(0, this.codesScript.length);
Expand All @@ -497,13 +571,11 @@ export default class RunJSPlugin extends Plugin {
(key) => delete this.codesModule[key]
);

await this.iterateCodeblocks(this.appendCode.bind(this));
this.codes.push(...codesDataNew.codes);
this.codesScript.push(...codesDataNew.codesScript);
Object.assign(this.codesModule, codesDataNew.codesModule);

const tFolder: TFolder = <TFolder>(
this.app.vault.getAbstractFileByPath(this.settings.scriptsFolder)
);

await this.iterateScriptsFolder(tFolder, this.appendCode.bind(this));
return changed;
}

appendCode(code: Code) {
Expand Down Expand Up @@ -737,6 +809,8 @@ export default class RunJSPlugin extends Plugin {
async import(codeName: string) {
if (codeName === "obsidian") {
return obsidian;
} else if (codeName.startsWith("https://")) {
return await import(codeName);
}

const code = this.codesModule[codeName];
Expand Down
4 changes: 3 additions & 1 deletion versions.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
"0.0.1": "0.15.0",
"0.1.0": "0.15.0",
"0.1.1": "0.15.0",
"0.1.2": "0.15.0"
"0.1.2": "0.15.0",
"0.2.0": "0.15.0",
"0.3.0": "0.15.0"
}

0 comments on commit 7929344

Please sign in to comment.