Compare commits

...

42 commits

Author SHA1 Message Date
meld-cp
60b609a904
Update LICENSE 2024-06-06 19:39:19 +12:00
meld-cp
26e6163047 update gitignore 2024-04-07 13:45:13 +12:00
meld-cp
e75c9c7454
Merge pull request #3 from meld-cp/meld-cp/issue2
Add cell formatting for markdown table creation
2023-03-31 13:44:29 +13:00
meld-cp
f161094121 Add cell formatting for markdown table creation
Fixes #2
2023-03-31 00:40:08 +00:00
meld-cp
f40da8d781
Update user-guide.md 2023-03-30 07:16:13 +13:00
meld-cp
0bbb5f0d44
Update api.md 2023-03-27 04:02:12 +13:00
Cleon
12f591841c ver bump 2023-03-26 10:33:39 +13:00
Cleon
26181f02dc use cachedRead instead of read 2023-03-26 10:32:04 +13:00
Cleon
214df0d6fb remove use of innerHTML for messages 2023-03-26 10:12:45 +13:00
meld-cp
71c45bdf07 fix marker fetching
remove console logging
version bump
2023-02-10 02:19:52 +00:00
meld-cp
9cf988da38 remove logging 2023-02-10 01:29:58 +00:00
meld-cp
11958fadcb add array test to prevent runtime error 2023-02-10 01:29:42 +00:00
meld-cp
fb09699c1b add markdown helper, fix spelling 2023-02-09 03:54:29 +00:00
meld-cp
26d267aca5 remove console.debugs 2023-02-08 20:33:15 +00:00
meld-cp
e03f2b90d6 fix marker regex 2023-02-08 20:22:59 +00:00
meld-cp
260e08bc1f
update marker value regex 2023-02-09 08:50:02 +13:00
Cleon
6e2a255d6b spelling 2023-02-04 18:35:28 +13:00
Cleon
4a713ab8ed update marker api docs 2023-02-04 18:19:54 +13:00
Cleon
bd8f6c2f09 ver bump 2023-02-04 18:12:08 +13:00
Cleon
79bc5215e8 add load and get to markers 2023-02-04 18:11:02 +13:00
Cleon
474d4eb4a2 ver bump 2023-02-04 17:16:17 +13:00
Cleon
21cd0b1ac0 ver bumb 2023-02-04 17:14:30 +13:00
Cleon
04535c2f50 ver bumb 2023-02-04 17:14:21 +13:00
Cleon
d2e0d4f7ea - don't use global app instance
- remove unneeded code
- better await for modal closes
2023-02-04 17:08:33 +13:00
Cleon
24a3de716a release prep 2023-01-08 14:06:26 +13:00
Cleon
328982dbe5 remove await $.render from docs 2023-01-08 13:56:10 +13:00
Cleon
b1d641077d correct min version 2023-01-08 13:55:04 +13:00
Cleon
97d05c4ddf fix spelling 2023-01-07 22:07:09 +13:00
Cleon
f812dcef2a add jpeg to mimetypes, move mimetypes to constants, update docs 2023-01-07 21:51:20 +13:00
Cleon
2731c96c83 docs 2023-01-07 21:31:29 +13:00
Cleon
110c18dc5d docs 2023-01-07 21:30:43 +13:00
Cleon
b6ae6a2783 docs 2023-01-07 21:07:08 +13:00
Cleon
805a16b2db docs 2023-01-07 20:51:50 +13:00
Cleon
5d5a401982 docs 2023-01-07 20:37:09 +13:00
Cleon
ff0ef12c21 docs 2023-01-07 20:35:36 +13:00
Cleon
320c6a21f7 docs 2023-01-07 20:33:23 +13:00
Cleon
f3daa76531 docs 2023-01-07 20:30:40 +13:00
Cleon
ee45e07a17 docs 2023-01-07 20:28:59 +13:00
Cleon
bf9d1fc259 update docs 2023-01-07 20:26:49 +13:00
Cleon
c937346571 better skip detection 2023-01-07 20:26:21 +13:00
Cleon
ee9b18c40d remove logging 2023-01-07 19:42:21 +13:00
Cleon
88f500371a version bump 2023-01-07 19:35:17 +13:00
29 changed files with 485 additions and 286 deletions

5
.gitignore vendored
View file

@ -22,4 +22,7 @@ data.json
.DS_Store
# Test vault
test-vault
test-vault
# Other
desktop.ini

View file

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2021 Michael Brenan
Copyright (c) 2023 Cleon Pinto
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View file

@ -4,6 +4,8 @@ Write and execute (sandboxed) JavaScript to render templates, query DataView and
Basically, turn a note into a small, simple, runnable thing.
<a href="https://www.buymeacoffee.com/cleon"><img src="https://img.buymeacoffee.com/button-api/?text=&emoji=&slug=meld-build&button_colour=FFDD00&font_colour=000000&font_family=Arial&outline_colour=000000&coffee_colour=ffffff"></a>
## Quick Start
- Install and enable the plugin
- Paste the Markdown below into a new note.
@ -30,9 +32,6 @@ await $.ui.message( `From this day forth you shall be known as ${ans}` );
- [Guess The Number Game (Using Markers)](/docs/examples/guess-the-number-marker.md)
- [Simple Invoice Builder](/docs/examples/invoice-builder.md)
## Known Issues
- If you quickly try to run a note just after some changes, there's a chance that the Obsidian cache hasn't been updated yet. The workaround for now is to wait a second or two before running a changed note.
## Manually installing the plugin
- Copy over `main.js`, `styles.css`, `manifest.json` to your vault `VaultFolder/.obsidian/plugins/meld-build/`.

6
dist/manifest.json vendored
View file

@ -1,10 +1,10 @@
{
"id": "meld-build",
"name": "Meld Build",
"version": "0.1.3",
"minAppVersion": "1.1.9",
"version": "0.1.9",
"minAppVersion": "1.0.1",
"description": "Write and execute (sandboxed) JavaScript to render templates, query DataView and create dynamic notes.",
"author": "meld-cp",
"authorUrl": "https://github.com/meld-cp/",
"isDesktopOnly": false
}
}

View file

@ -1,11 +1,11 @@
# Meld-Build API
## The Context Object (`$`)
- `$.data[<name>]`
- `$.data.<name>`
- Used to access imported Markdown table data.
- The `<name>` will be the previous header to the table in the note.
- e.g. if you had a header `# My Customers` before a markdown table, `$.data.my_customers` would return the data of that table.
- Use `await $.log($.data);` to discover the data object.
- e.g. if you had a header `# My Customers` before a markdown table, `$.data.my_customers` would return an array of that table.
- `$.blocks[]`
- An array of non-`meld-build` codeblocks
- Can be used as templates
@ -75,8 +75,8 @@ const ans4 = await $.ui.ask( 'Title', 'question 4', ['1', '2', '3'] );
// show a message
await $.ui.message( `Your answers were:\n\n${ans1}, ${ans2}, ${ans3}, ${ans4}` );
// show a message with title
await $.ui.message( 'A Title', 'A titled <b>message</b>' );
// show a 2 line message with title
await $.ui.message( 'A Title', 'A titled message\nLine 2' );
await $.ui.message( 'Math', 13 * 67 );
// rebuild the current view, may be needed if you have an embedded note which was modified
@ -96,8 +96,8 @@ Read and write vault files.
- The loaded data is also returned
- `const dataurl = await $.io.load_data_url( path, mimetype? )`
- Encode the contents of a file into a dataurl for use in a template
- Optionaly specify the mime type.
- Auto mime type mappings are available for the following file extensions: `.jpg`, `.png`, `.gif`, `.svg`, `.css`
- Optionally specify the mime type.
- Auto mime type mappings are available for the following common file extensions: `.jpeg`, `.jpg`, `.png`, `.gif`, `.svg`, `.css`
- `await $.io.output( file, content, open? )`
- (Over)Writes the `file` with given `content`
- Tries to open the `file` if `open` is true (false by default)
@ -146,6 +146,10 @@ Markers can be used to replace sections of a note with dynamic values. Sections
- `$.markers.target_file( file? )`
- Sets the target file to `file`
- `file` is optional and defaults to the current note
- `await $.markers.load()`
- Loads target file markers into memory
- `$.markers.get( name )`
- Gets the marker value named `name` from memory
- `$.markers.set( name, value )`
- Sets the marker value named `name` in memory
- `$.markers.clear()`
@ -153,7 +157,7 @@ Markers can be used to replace sections of a note with dynamic values. Sections
- `markers = await $.markers.fetch()`
- Returns the markers found in the target file
- `changes = await $.markers.apply( clearUnknownMarkerValues? )`
- Applys set marker values to the target file
- Applies set marker values to the target file
- `clearUnknownMarkerValues` is optional, set it to `false` if you want to prevent unset markers being blanked out.
### Examples
@ -172,12 +176,18 @@ Markers can be used to replace sections of a note with dynamic values. Sections
//$.markers.target_file( 'Marker Target.md' );
// returns list of markers found in the target file
const markers = await $.markers.fetch();
//const markers = await $.markers.fetch();
//console.log({markers});
// loads maker values into memory from target file
await $.markers.load();
// removes marker values from memory
//$.markers.clear();
// gets a marker value from memory
const value = $.markers.get( 'marker1' );
// sets a marker value in memory
$.markers.set( 'marker1', Math.random() );
@ -187,6 +197,15 @@ const result = await $.markers.apply();
```
````
## Markdown Helper (`$.md`)
- `$.md.table( headers:[], rows:[[]])`
- Build a markdown table
- e.g. `$.md.table( ['header 1', 'header2'], rows:[ ['row 1 col 1', 'row 1 col 2'], ['row 2 col 1', 'row 2 col 2'], ])`
- `$.md.table( data )`
- Build a markdown table from imported data
- e.g. `$.md.table( $.data.customers )`
## Assert (`$.assert`)
You can use `$.assert` to stop the run and show a message if a test fails.

View file

@ -10,8 +10,8 @@ run = Let The Games Begin
help =
```
Guess Number: %%round=%%7%%=round%%
Your last guess was: %%last=%%47%%=last%%, **%%msg=%%🥳 YUS! You win!%%=msg%%**
Guess Number: %%round=%%%%=round%%
Your last guess was: %%last=%%%%=last%%, **%%msg=%%%%=msg%%**
```js meld-build
const min = 1;
@ -52,7 +52,6 @@ while ( !done ){
}
$.markers.set('last', guessNum );
//console.log($.markers.newValues);
if( guessNum < number ){
// guess was too low

View file

@ -26,13 +26,13 @@ const customers = [
{ id: 101, name: 'Some Other Co', address: ['123 Some Other Rd', 'Some City'] },
]
// Define the invoices their lines
// Define the invoices and their lines
const invoices = [
{
id: '22001', customer:100, date: '2022-12-01', status: 'open',
work: [
{ inv: '22001', date: '2022-11-13', start: 7.00, end: 16.50, rate: 25.45, desc: 'I did the thing' },
{ inv: '22001', date: '2022-11-16', start: 10.75, end: 12.00, rate: 25.45, desc: 'I did the other thing' },
{ date: '2022-11-13', start: 7.00, end: 16.50, rate: 25.45, desc: 'I did the thing' },
{ date: '2022-11-16', start: 10.75, end: 12.00, rate: 25.45, desc: 'I did the other thing' },
]
},
]
@ -109,7 +109,7 @@ const customer = customers.filter( e => e.id==inv.customer ).at(0);
const template = $.blocks.at(0);
// render the template passing in the customer and invoice
const html = await $.render( template, { customer, inv } );
const html = $.render( template, { customer, inv } );
// create an html invoice file and open it in the default browser, from there it can be saved as a PDF
await $.io.output( `inv ${inv.id}.html`, html, true );

View file

@ -25,6 +25,27 @@ Within the current note:
---
## Tagging and Grouping `meld-build` codeblocks
It is possible to tag codeblocks for targeted runs using the `meld-build-toolbar`.
For instance, the following codeblock is tagged with `init`
````md
```js meld-build init
await $.ui.message('This is the init codeblock');
```
````
Multiple codeblocks with the same tag will be concatenated together before running.
To skip a codeblock all together, use the `skip` tag like this:
````md
```js meld-build skip
await $.ui.message("This won't run");
```
````
---
## Toolbar
To make running `meld-build` codeblocks easier you can add the following codeblock to show a toolbar.
@ -34,7 +55,25 @@ To make running `meld-build` codeblocks easier you can add the following codeblo
```
````
_TODO: add screenshot_
By default you will see a `Run` and a `Help` button.
You can configure the labels of buttons like this:
````md
```meld-build-toolbar
run = Run Me!
help = SOS
```
````
To define run buttons which target codeblock tags you can do something like:
````md
```meld-build-toolbar
run|init = Run the Init Code
run|main = Run Code tagged with main
run = Run the Non-tagged Code
```
````
---
@ -48,7 +87,7 @@ Here's an example:
const mytemplate = 'Hello {{name}}';
const mydata = { name:'World' };
const result = await $.render( mytemplate, mydata );
const result = $.render( mytemplate, mydata );
await $.ui.message( result );
```
@ -58,11 +97,11 @@ There are other ways to load templates too, for example, using the content of co
Say your note looks like this:
````md
# My Runable Note
# My Runnable Note
The template codeblock:
```html
<p>Greetings <strong>{{name}}</strong>, {{message}}</p>
```
Greetings {{name}}, {{message}}
```
The meld-build block to run:
@ -70,14 +109,14 @@ The meld-build block to run:
const template = $.blocks.at(0); // gets the first non-meld-build block in the note
const data = { name:'John', message:'How are you?' };
const result = await $.render( template, data );
const result = $.render( template, data );
await $.ui.message( result );
```
````
Running this note will show a message with the following text: 'Greetings **John**, How are you?'
Running this note will show a message with the following text: 'Greetings John, How are you?'
See the `$.io.import` and `$.io.load` [API](api.md) functions for other ways to load templates.
@ -90,10 +129,10 @@ It is possible to mark sections of a note with start and end markers. These sec
For example, when the following note is run, the `replace me` will be replaced with a random number.
````md
%%my marker=%%replace me%%=my marker%%
%%my marker=%%replace me%%=my marker%%
```js meld-build
$.markers.set('my marker', Math.random() );
$.markers.set( 'my marker', Math.random() );
await $.markers.apply();
```
````
@ -104,14 +143,13 @@ See the [API](api.md) or another [example](examples/guess-the-number-marker.md)
## Accessing the DataView plugin API
If you are fimilar with the [DataView](https://github.com/blacksmithgu/obsidian-dataview) plugin and have it installed, you can access it's [js api](https://blacksmithgu.github.io/obsidian-dataview/api/code-reference/) via the `$.dv.` interface.
If you are familiar with the [DataView](https://github.com/blacksmithgu/obsidian-dataview) plugin and have it installed, you can access it's [js api](https://blacksmithgu.github.io/obsidian-dataview/api/code-reference/) via the `$.dv.` interface.
For example:
````md
```js meld-build
// use DataView to fetch all notes within the vault
const pages = await $.dv.pages();
...
```
````
@ -129,35 +167,9 @@ await $.io.output( 'My List.md', md );
---
## Skipping `meld-build` blocks
If you have multiple `meld-build` codeblocks in a note, you can choose to ignore some by adding `skip` after `meld-build`.
For example, running the following will display the number 0.
````md
# My Runable Note
## code block 1
```js meld-build
let x = 0;
```
## code block 2, skipped
```js meld-build skip
x = 2;
```
## code block 3
```js meld-build
await $.ui.message(x);
```
````
---
## Other
- It's recommended to turn `on` the `Files & Links > Detect all file extensions` option in Obsidian. This will make working with files for templating easier.
- Hint: add `//@hide_when_reading` to a `JavaScript` codeblock to hide it in Reading mode.
---
## More Information

View file

@ -1,10 +1,10 @@
{
"id": "meld-build",
"name": "Meld Build",
"version": "0.1.2",
"minAppVersion": "1.1.9",
"version": "0.1.9",
"minAppVersion": "1.0.1",
"description": "Write and execute (sandboxed) JavaScript to render templates, query DataView and create dynamic notes.",
"author": "meld-cp",
"authorUrl": "https://github.com/meld-cp/",
"isDesktopOnly": false
}
}

10
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "meld-build-obsidian-plugin",
"version": "1.0.0",
"version": "0.1.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "meld-build-obsidian-plugin",
"version": "1.0.0",
"version": "0.1.9",
"license": "MIT",
"devDependencies": {
"@types/handlebars": "^4.1.0",
@ -1845,9 +1845,9 @@
"dev": true
},
"node_modules/obsidian-dataview": {
"version": "0.5.52",
"resolved": "https://registry.npmjs.org/obsidian-dataview/-/obsidian-dataview-0.5.52.tgz",
"integrity": "sha512-0i5urpMRBjTtBhZuTUFvy35sQoCsM1rZg2jfDSbYu0dRnKtJcMzKSItBCNnCvPLabGtf5AG+wTaLjRszHkchkQ==",
"version": "0.5.53",
"resolved": "https://registry.npmjs.org/obsidian-dataview/-/obsidian-dataview-0.5.53.tgz",
"integrity": "sha512-t9sivTBVUZ2JA5qv3DWzzMx7/fSJKyYxGnTMEgmmlbp7AeY5apfytUbAKb9CJeIBBGkNgdkgjDzy12VniABhRQ==",
"dev": true,
"dependencies": {
"@codemirror/language": "git+https://github.com/lishid/cm-language.git",

View file

@ -1,6 +1,6 @@
{
"name": "meld-build-obsidian-plugin",
"version": "1.0.0",
"version": "0.1.9",
"description": "This is a sample plugin for Obsidian (https://obsidian.md)",
"main": "main.js",
"scripts": {

26
src/ToolbarButton.ts Normal file
View file

@ -0,0 +1,26 @@
export class ToolbarButton {
id: string;
label?: string;
params: string[];
constructor(id: string, label?: string, params?: string[]) {
this.id = id;
this.label = label;
this.params = params ?? [];
}
public static parse(line: string): ToolbarButton | null {
const pair = line.split('=');
if (pair.length == 2) {
const buttonParts = pair[0].split('|').map(e => e.trim());
const id = buttonParts.shift() ?? '';
const params = buttonParts;
const label = pair[1].trim();
return new ToolbarButton(id, label, params);
}
return null;
}
}

View file

@ -15,10 +15,10 @@ export class CodeBlockInfo{
export class CodeBlockInfoHelper {
public static isRunable( info: CodeBlockInfo ):boolean{
public static isRunnable( info: CodeBlockInfo ):boolean{
return ['js', 'javascript'].contains( info.language )
&& info.params.at(0) === 'meld-build'
&& info.params.at(1) !== 'skip'
&& !info.params.contains( 'skip' )
;
}

View file

@ -6,10 +6,11 @@ import { RunLogger } from 'src/run-logger';
import { TRunContext } from "src/run-context";
import { NamedCodeBlock } from "./named-code-block";
import { CodeBlockInfoHelper } from "./code-block-info";
import { AssertRunContextImplemention } from "./rci-assert";
import { UiRunContextImplemention } from "./rci-ui";
import { IoRunContextImplemention } from "./rci-io";
import { MarkerRunContextImplemention } from "./rci-markers";
import { AssertRunContextImplementation } from "./rci-assert";
import { UiRunContextImplementation } from "./rci-ui";
import { IoRunContextImplementation } from "./rci-io";
import { MarkerRunContextImplementation } from "./rci-markers";
import { MarkdownHelperRunContextImplementation } from "./rci-markdown";
export class Compiler{
@ -104,17 +105,17 @@ export class Compiler{
// code blocks
const allCodeBlocks = await pzr.fetchCodeBlocks( view );
// runable code blocks
const runableCodeBlocks = allCodeBlocks
.filter( cb => CodeBlockInfoHelper.isRunable( cb.info ) )
// runnable code blocks
const runnableCodeBlocks = allCodeBlocks
.filter( cb => CodeBlockInfoHelper.isRunnable( cb.info ) )
.filter( cb => runGroupTag == undefined || cb.info.params.contains( runGroupTag ) )
;
if ( runableCodeBlocks.length == 0 ){
if ( runnableCodeBlocks.length == 0 ){
return null;
}
// source code
const sourceCode = runableCodeBlocks.map( e => e.content ).join('\n');
const sourceCode = runnableCodeBlocks.map( e => e.content ).join('\n');
// consumable blocks
const consumableBlocks = allCodeBlocks
@ -142,15 +143,27 @@ export class Compiler{
return '';
},
assert: new AssertRunContextImplemention(),
assert: new AssertRunContextImplementation(),
ui: new UiRunContextImplemention(),
ui: new UiRunContextImplementation(),
io: new IoRunContextImplemention( log, data, consumableBlocks ),
io: new IoRunContextImplementation(
view.app.vault,
view.app.workspace,
log,
data,
consumableBlocks
),
markers: new MarkerRunContextImplemention(log, view.file.path ),
markers: new MarkerRunContextImplementation(
view.app.vault,
log,
view.file.path
),
dv: dvGetAPI(),
md: new MarkdownHelperRunContextImplementation( log )
}
}

View file

@ -1,2 +1,12 @@
export const CODE_BLOCK_LANG_TOOLBAR = 'meld-build-toolbar';
export const URL_HELP = 'https://github.com/meld-cp/obsidian-build/blob/master/docs/user-guide.md';
export const URL_HELP = 'https://github.com/meld-cp/obsidian-build/blob/master/docs/user-guide.md';
export const EXTENSION_MIMETYPE_MAP = new Map<string,string>([
['jpeg', 'image/jpeg'],
['jpg', 'image/jpeg'],
['png', 'image/png'],
['gif', 'image/gif'],
['svg', 'image/svg+xml'],
['css', 'text/css'],
]);

View file

@ -1,5 +1,26 @@
export class DataSet extends Array<DataSetRow> {
public columns:string[] = [];
constructor( columnNames:string[] ){
super();
//console.debug( "DataSet:", {columnNames} );
if ( Array.isArray( columnNames ) && columnNames.length > 0 ){
this.columns = columnNames.map( cn => cn.trim() );
}
}
private extractAsColumnName( str:string ) : string {
return str.trim().replaceAll(/\W/ig, '_').toLowerCase().trim();
}
public getPropertyName ( colName:string ) : string | undefined {
return this.extractAsColumnName( colName );
}
}
export interface IDataSetCollection {
@ -14,12 +35,13 @@ export class DataSetRow implements IRowDataValueCollection{
[column: string]: unknown;
constructor(columnNames:string[], data: unknown[]){
for (let colIdx = 0; colIdx < columnNames.length; colIdx++) {
const value = data.at(colIdx);
const colName = columnNames[colIdx].trim();
if ( colName != '' ){
this[colName] = value;
constructor( dataSet:DataSet, values: unknown[] ){
const columns = dataSet.columns;
for ( let colIdx = 0; colIdx < columns.length; colIdx++ ) {
const rawColName = columns[colIdx];
const propColName = dataSet.getPropertyName(rawColName);
if ( propColName !== undefined ){
this[propColName] = values.at(colIdx);
}
}
}

View file

@ -3,18 +3,9 @@ import * as HB from 'handlebars';
import { RunLogger } from 'src/run-logger';
import { Compiler } from 'src/compiler';
import { CODE_BLOCK_LANG_TOOLBAR, URL_HELP } from 'src/constants';
interface MeldBuildPluginSettings {
mySetting: string;
}
const DEFAULT_SETTINGS: MeldBuildPluginSettings = {
mySetting: 'default'
}
import { ToolbarButton } from './ToolbarButton';
export default class MeldBuildPlugin extends Plugin {
settings: MeldBuildPluginSettings;
private async codeblockProcessor(el: HTMLElement, ctx: MarkdownPostProcessorContext): Promise<void> {
const els = el.querySelector('.language-js');
@ -24,15 +15,13 @@ export default class MeldBuildPlugin extends Plugin {
}
if ( els.getText().contains( '//@hide_when_reading' ) ){
console.debug('Hiding element',{el});
//console.debug('Hiding element',{el});
el.hide();
}
}
async onload() {
await this.loadSettings();
await this.reloadActiveViewsWithToolbars();
this.registerHandlebarHelpers();
@ -107,7 +96,7 @@ export default class MeldBuildPlugin extends Plugin {
}
private async reloadActiveViewsWithToolbars(){
app.workspace.iterateAllLeaves( leaf =>{
this.app.workspace.iterateAllLeaves( leaf =>{
const view = leaf.view;
if ( view instanceof MarkdownView ){
@ -115,7 +104,7 @@ export default class MeldBuildPlugin extends Plugin {
return;
}
console.debug( `Meld-Build::Rebuilding view for file '${view.file.path}'` );
//console.debug( `Meld-Build::Rebuilding view for file '${view.file.path}'` );
(view.leaf as any).rebuildView();
}
@ -123,7 +112,7 @@ export default class MeldBuildPlugin extends Plugin {
}
private async buildAndRunActiveView( runGroupTag?:string ){
const view = app.workspace.getActiveViewOfType( MarkdownView );
const view = this.app.workspace.getActiveViewOfType( MarkdownView );
if (!view){
new Notice( 'Unable to run, no active Markdown View found' );
return;
@ -135,14 +124,13 @@ export default class MeldBuildPlugin extends Plugin {
if ( !( view instanceof MarkdownView ) ){
return;
}
const logger = new RunLogger();
const logger = new RunLogger( view.app.vault );
try{
//await view.save();
const compiler = new Compiler();
const runner = await compiler.compile( logger, view, runGroupTag );
runner?.();
}catch(e){
console.debug('here');
await logger.error(e);
new Notice(e);
}
@ -174,39 +162,6 @@ export default class MeldBuildPlugin extends Plugin {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class ToolbarButton{
id:string;
label?: string;
params: string[];
constructor( id:string, label?:string, params?:string[] ){
this.id = id;
this.label = label;
this.params = params ?? [];
}
public static parse( line:string ) : ToolbarButton|null{
const pair = line.split( '=' );
if( pair.length == 2 ){
const buttonParts = pair[0].split( '|' ).map( e => e.trim() );
const id = buttonParts.shift() ?? '';
const params = buttonParts;
const label = pair[1].trim();
return new ToolbarButton( id, label, params );
}
return null;
}
}

View file

@ -1,5 +1,4 @@
import { App, Modal, Setting } from "obsidian";
import { Utils } from "src/utils";
export class AskModal extends Modal {
@ -7,8 +6,6 @@ export class AskModal extends Modal {
private options:string[] = [];
private answerInput:Setting;
public answer:string|undefined;
private completed = true;
//private cancelled = false;
constructor(app: App) {
super(app);
@ -26,14 +23,16 @@ export class AskModal extends Modal {
this.answer = undefined;
this.options = options ?? [];
this.completed = false;
this.open();
while(!this.completed){
await Utils.delay(250);
}
await new Promise<void>((resolve) => {
this.open();
this.onClose = () => {
this.contentEl.empty();
resolve();
}
});
return this.answer;
}
@ -60,7 +59,7 @@ export class AskModal extends Modal {
if (ev.key == 'Enter'){
ev.stopPropagation();
ev.preventDefault();
this.answer = answer;
this.answer = answer ?? '';
this.close();
}
})
@ -74,17 +73,12 @@ export class AskModal extends Modal {
cb
.setButtonText('OK')
.onClick( ev => {
this.answer = answer;
this.answer = answer ?? '';
this.close();
})
;
})
;
}
override onClose() {
const { contentEl } = this;
this.completed = true;
contentEl.empty();
}
}

View file

@ -1,13 +1,11 @@
import { App, Modal } from "obsidian";
import { Utils } from "src/utils";
export class MessageModal extends Modal {
private message:string;
private closed = true;
constructor(app: App) {
super(app);
constructor( app: App ) {
super( app );
}
public async execute(
@ -17,26 +15,29 @@ export class MessageModal extends Modal {
this.titleEl.setText( title );
this.message = message;
this.closed = false;
this.open();
while(!this.closed){
await Utils.delay(250);
}
this.contentEl.append( ...MessageModal.buildContent( message ) );
await new Promise<void>((resolve) => {
this.open();
this.onClose = () => {
this.contentEl.empty();
resolve();
}
});
}
onOpen() {
const { contentEl } = this;
const formattedLines = this.message.split('\n').join('<br/>');
contentEl.innerHTML = formattedLines;
}
onClose() {
const { contentEl } = this;
contentEl.empty();
this.closed = true;
private static buildContent( message: string ) : Node[] {
const result = Array<Node>();
const lines = message.split( '\n' );
lines.forEach( line => {
result.push( createDiv( { text: line } ) );
} );
return result;
}
}

View file

@ -12,16 +12,16 @@ export class Parser {
const result: NamedCodeBlock[] = [];
const file = view.file;
const fileContent = await app.vault.read(file);
const fileCache = app.metadataCache.getFileCache( file );
const fileContent = await view.app.vault.cachedRead(file);
const fileCache = view.app.metadataCache.getFileCache( file );
if ( fileCache == null ){
console.debug('Parser::fetchCodeBlocks, fileCache is null');
//console.debug('Parser::fetchCodeBlocks, fileCache is null');
return result;
}
if ( fileCache.sections == undefined ){
console.debug('Parser::fetchCodeBlocks, fileCache.sections is undefined');
//console.debug('Parser::fetchCodeBlocks, fileCache.sections is undefined');
return result;
}
@ -48,10 +48,9 @@ export class Parser {
}
// filter languages
console.debug('Parser::fetchCodeBlocks',{lines});
const codeBlockInfo = this.extractCodeBlockInfo(lines[0]);
if ( codeBlockInfo == null ){
console.debug('Parser::fetchCodeBlocks, codeBlockInfo is null', {content});
//console.debug('Parser::fetchCodeBlocks, codeBlockInfo is null', {content});
return;
}
@ -67,7 +66,7 @@ export class Parser {
result.push( codeBlock );
});
console.debug('Parser::fetchCodeBlocks', {result});
return result;
}
@ -84,7 +83,7 @@ export class Parser {
//const matches = line.match(/````*/i);
if ( codeBlockMatch == null || codeBlockMatch.length < 1 ){
console.debug('Parser::extractCodeBlockInfo, codeBlockMatch is null or length < 1', {codeBlockMatch, line});
//console.debug('Parser::extractCodeBlockInfo, codeBlockMatch is null or length < 1', {codeBlockMatch, line});
return null;
}
@ -105,20 +104,20 @@ export class Parser {
public loadCsv( csvContent:string ) : DataSet {
const lines = csvContent.split('\n').map( e=>e.trim() );
if (lines.length == 0){
return new DataSet();
return new DataSet( [] );
}
const columns = lines.first()?.split(',').map( e => this.extractAsColumnName(e) ) ?? [];
const columns = lines.first()?.split(',') ?? [];
const rows = new Array<DataSetRow>();
const ds = new DataSet( columns );
//const rows = new Array<DataSetRow>();
for (let i = 1; i < lines.length; i++) {
const rowData = lines[i].split(',').map( d => this.extractValueFromString(d));
rows.push( new DataSetRow(columns, rowData));
ds.push( new DataSetRow(ds, rowData));
}
const ds = new DataSet( ...rows );
return ds;
}
@ -182,19 +181,15 @@ export class Parser {
}
private parseMdTable( tableLines:string[] ): DataSet {
const data: DataSet = new DataSet();
const tlines = tableLines
.map( e=>e.trim().slice(1,-1).trim());
const tlines = tableLines.map( e=>e.trim().slice(1,-1).trim());
const columns = tlines.first()?.split('|') ?? [];
const data: DataSet = new DataSet( columns );
const columns = tlines
.first()?.split('|')
.map( e=> this.extractAsColumnName(e) )
.filter( e=>e.length > 0)
?? []
;
for (let i = 1; i < tlines.length; i++) {
for (let i = 2; i < tlines.length; i++) {
const rowLine = tlines[i];
if (rowLine.startsWith('---') ){
continue;
@ -203,7 +198,7 @@ export class Parser {
continue;
}
const rowValues : unknown[] = rowLine.split('|').map( e => this.extractValueFromString(e) );
data.push( new DataSetRow( columns, rowValues ) );
data.push( new DataSetRow( data, rowValues ) );
}
return data;
@ -215,8 +210,8 @@ export class Parser {
} = {};
const file = view.file;
const fileContent = await app.vault.read(file);
const fileCache = app.metadataCache.getFileCache( file );
const fileContent = await view.app.vault.cachedRead(file);
const fileCache = view.app.metadataCache.getFileCache( file );
if ( fileCache == null ){
return result;
@ -237,9 +232,6 @@ export class Parser {
}
if ( section.type == 'table' ){
// const from = editor.offsetToPos(section.position.start.offset);
// const to = editor.offsetToPos(section.position.end.offset);
// const table = editor.getRange( from, to );
const table = fileContent.slice(
section.position.start.offset,
section.position.end.offset
@ -288,10 +280,6 @@ export class Parser {
return str.trim().replaceAll(/\W/ig, '_').toLowerCase();
}
private extractAsColumnName( str:string ) : string {
return str.trim().replaceAll(/\W/ig, '_').toLowerCase();
}
private extractValueFromString( str:string ) : string | number | Date {
const trimmed = str.trim();

View file

@ -1,7 +1,7 @@
import { MessageModal } from "./modal-message";
import { TAssertRunContext } from "./run-context";
export class AssertRunContextImplemention implements TAssertRunContext {
export class AssertRunContextImplementation implements TAssertRunContext {
private async showFailMessage( label:string, msg:string ) : Promise<void>{
const title = '❗ Assert Failed' + ( label.length > 0 ? ` - ${label}` : '' );

View file

@ -1,4 +1,5 @@
import { normalizePath, TFile } from "obsidian";
import { normalizePath, TFile, Vault, Workspace } from "obsidian";
import { EXTENSION_MIMETYPE_MAP } from "./constants";
import { DataSet, IDataSetCollection } from "./data-set";
import { NamedCodeBlock } from "./named-code-block";
import { Parser } from "./parser";
@ -6,20 +7,24 @@ import { TIoRunContext } from "./run-context";
import { RunLogger } from "./run-logger";
import { Utils } from "./utils";
export class IoRunContextImplemention implements TIoRunContext {
export class IoRunContextImplementation implements TIoRunContext {
private vault: Vault;
private workspace: Workspace;
private log: RunLogger;
private data:IDataSetCollection;
private consumableBlocks:NamedCodeBlock[]
constructor( log: RunLogger, data:IDataSetCollection, consumableBlocks:NamedCodeBlock[] ){
constructor( vault:Vault, workspace:Workspace, log: RunLogger, data:IDataSetCollection, consumableBlocks:NamedCodeBlock[] ){
this.vault = vault;
this.workspace = workspace;
this.log = log;
this.data = data;
this.consumableBlocks = consumableBlocks;
}
private getAbsoluteFilepathFromActiveFile( path:string ) : string | undefined {
const activeFile = app.workspace.getActiveFile();
const activeFile = this.workspace.getActiveFile();
if (activeFile == null){
return;
}
@ -27,25 +32,27 @@ export class IoRunContextImplemention implements TIoRunContext {
}
private async data_loader(filepath:string, name?:string) : Promise<DataSet>{
let resultDataSet = new DataSet();
const absFilepath = this.getAbsoluteFilepathFromActiveFile(filepath);
if (!absFilepath){
return resultDataSet;
return new DataSet([]);
}
const file = app.vault.getAbstractFileByPath(absFilepath);
const file = this.vault.getAbstractFileByPath(absFilepath);
const pzr = new Parser();
if (file instanceof TFile){
if (file.extension == 'csv'){
const csvdata = await app.vault.read( file );
resultDataSet = pzr.loadCsv(csvdata);
this.data[name??file.basename] = resultDataSet;
if ( file.extension == 'csv'){
const csvData = await this.vault.cachedRead( file );
const dataSet = pzr.loadCsv(csvData);
this.data[name??file.basename] = dataSet;
return dataSet;
}
}
return resultDataSet;
return new DataSet([]);
}
async import(path: string): Promise<boolean> {
@ -55,7 +62,7 @@ export class IoRunContextImplemention implements TIoRunContext {
return false;
}
const file = app.vault.getAbstractFileByPath(absFilepath);
const file = this.vault.getAbstractFileByPath(absFilepath);
if (!(file instanceof TFile)){
await this.log.error(`import::File not found: "${path}"`);
@ -63,7 +70,7 @@ export class IoRunContextImplemention implements TIoRunContext {
}
if ( file.extension == 'md' ){
const content = await app.vault.read( file );
const content = await this.vault.cachedRead( file );
const pzr = new Parser();
pzr.applyMarkdownContent(
file.basename,
@ -81,13 +88,13 @@ export class IoRunContextImplemention implements TIoRunContext {
async load(path: string): Promise<string | undefined> {
const filepath = Utils.getSameFolderFilepath(path);
const af = app.vault.getAbstractFileByPath(filepath);
const af = this.vault.getAbstractFileByPath(filepath);
if (!(af instanceof TFile)){
return undefined;
}
return await app.vault.read(af)
return await this.vault.cachedRead(af)
}
async load_data(path: string, name?: string | undefined): Promise<DataSet> {
@ -97,21 +104,18 @@ export class IoRunContextImplemention implements TIoRunContext {
async load_data_url(path: string, mimetype?: string | undefined): Promise<string | undefined> {
const filepath = Utils.getSameFolderFilepath(path);
const af = app.vault.getAbstractFileByPath(filepath);
const af = this.vault.getAbstractFileByPath(filepath);
if (!(af instanceof TFile)){
return Promise.resolve(undefined);
}
const finalMimeType = mimetype ?? {
'jpg':'image/jpeg',
'png':'image/png',
'gif':'image/gif',
'svg':'image/svg+xml',
'css':'text/css'
}[af.extension] ?? '';
const finalMimeType = mimetype
?? EXTENSION_MIMETYPE_MAP.get(af.extension)
?? ''
;
const base64Data = Utils.toBase64( await app.vault.readBinary(af) );
const base64Data = Utils.toBase64( await this.vault.readBinary(af) );
return `data:${finalMimeType};base64,${base64Data}`;
}
@ -119,28 +123,28 @@ export class IoRunContextImplemention implements TIoRunContext {
async output(file: string, content: string, open?: boolean | undefined): Promise<void> {
const newFilepath = Utils.getSameFolderFilepath(file);
const af = app.vault.getAbstractFileByPath(newFilepath);
const af = this.vault.getAbstractFileByPath(newFilepath);
if (af instanceof TFile){
await app.vault.trash(af, false);
await this.vault.trash(af, false);
}
await app.vault.create( newFilepath, content );
await this.vault.create( newFilepath, content );
//new Notice(`${newFilepath} created`);
if (open == true){
await app.workspace.openLinkText( newFilepath, '' );
await this.workspace.openLinkText( newFilepath, '' );
}
}
async open(linktext: string): Promise<void> {
await app.workspace.openLinkText( linktext, '' );
await this.workspace.openLinkText( linktext, '' );
}
async delete(path: string): Promise<void> {
const filepath = Utils.getSameFolderFilepath(path);
const af = app.vault.getAbstractFileByPath(filepath);
const af = this.vault.getAbstractFileByPath(filepath);
if (af instanceof TFile){
await app.vault.trash(af, false);
await this.vault.trash(af, false);
}
}

120
src/rci-markdown.ts Normal file
View file

@ -0,0 +1,120 @@
import { DataSet } from "./data-set";
import { TMarkdownHelperRunContext, TMarkdownHelperTableCellFormatter } from "./run-context";
import { RunLogger } from "./run-logger";
export class MarkdownHelperRunContextImplementation implements TMarkdownHelperRunContext{
private log: RunLogger;
constructor( log: RunLogger ){
this.log = log;
}
private buildTable(headings: string[], rows: any[][]): string{
return MarkdownTableHelper.buildTable( headings, rows );
}
buildTableFromDataSet(data: DataSet, cellFormatter?:TMarkdownHelperTableCellFormatter): string {
const headings = data.columns;
const rowValues : any[][] = [];
for (const row of data) {
const values : any[] = [];
for (const heading of headings) {
const prop = data.getPropertyName(heading);
let value = prop == undefined ? undefined : row[prop];
if (prop != undefined && cellFormatter != null){
const formattedValue = cellFormatter(prop, value);
if (formattedValue != undefined){
value = formattedValue;
}
}
values.push(value);
}
rowValues.push( values );
}
return MarkdownTableHelper.buildTable( headings, rowValues );
}
public table(arg1: unknown, arg2?: unknown): string {
if (arg1 instanceof DataSet){
return this.buildTableFromDataSet(arg1, arg2 as TMarkdownHelperTableCellFormatter);
}
if ( Array.isArray(arg1) && Array.isArray(arg2) ){
return this.buildTable(arg1, arg2);
}
throw new Error('Invalid args for markdown table');
}
}
class MarkdownTableHelper {
public static buildTable(headings: string[], rowValues: any[][]): string{
const headers = MarkdownTableHelper.buildHeaderRows( headings );
const rows = MarkdownTableHelper.buildValueRows( rowValues );
const lines = [
'',
...headers,
...rows,
'',
]
//console.debug({lines});
return lines.join('\n');
}
private static removeHeaderFormat( header: string ) : string {
if ( header.startsWith('<') || header.startsWith('>') ){
return header.slice(1);
}
return header;
}
private static buildFormatRowCell( header: string ): string {
let leftMarker = ' ';
let rightMarker = ' ';
if ( header.startsWith('<') ){
leftMarker = ':';
header = header.slice(1);
} else if ( header.startsWith('>') ){
rightMarker = ':';
header = header.slice(1);
}else{
leftMarker = ':';
rightMarker = ':';
header = header;
}
return leftMarker + '-'.repeat( header.length ) + rightMarker;
}
private static buildHeaderRows( formattedHeadings: string[] ) : string[] {
var result : string[] = [];
result.push( '|' + formattedHeadings.map( header => ` ${MarkdownTableHelper.removeHeaderFormat(header)} ` ).join('|') + '|' );
result.push( '|' + formattedHeadings.map( header => MarkdownTableHelper.buildFormatRowCell(header) ).join('|') + '|' );
return result;
}
private static buildValueRow( rowValues: any[] ) : string {
return '|' + rowValues.map( c => ` ${c} ` ).join('|') + '|';
}
private static buildValueRows( valueRows: any[][] ) : string[] {
return valueRows.map( rowValues => MarkdownTableHelper.buildValueRow(rowValues) );
}
}

View file

@ -1,8 +1,8 @@
import { TFile } from "obsidian";
import { TFile, Vault } from "obsidian";
import { MarkerChange, MarkerValue, TMarkerRunContext } from "./run-context";
import { RunLogger } from "./run-logger";
export class MarkerRunContextImplemention implements TMarkerRunContext {
export class MarkerRunContextImplementation implements TMarkerRunContext {
private markerStartPrefix = '%%';
private markerStartSuffix = '=%%';
@ -10,7 +10,9 @@ export class MarkerRunContextImplemention implements TMarkerRunContext {
private markerEndPrefix = '%%=';
private markerEndSuffix = '%%'
private markerValueRegEx = '((?:.|\\n|\\r)*?)';
private vault: Vault;
private log: RunLogger;
private currentPath: string;
@ -18,7 +20,8 @@ export class MarkerRunContextImplemention implements TMarkerRunContext {
private newValues = new Map<string,string|null>();
constructor( log: RunLogger, currentPath:string ){
constructor( vault:Vault, log: RunLogger, currentPath:string ){
this.vault = vault;
this.log = log;
this.currentPath = currentPath;
this.targetPath = currentPath;
@ -42,12 +45,23 @@ export class MarkerRunContextImplemention implements TMarkerRunContext {
this.newValues.clear();
}
async load() : Promise<void>{
const markers = await this.fetch();
markers.forEach(mk => {
this.set(mk.name, mk.value);
});
}
get( name: string ) : string|null|undefined {
return this.newValues.get( name );
}
set( name: string, value: string|null ): void {
this.newValues.set( name, value );
}
private getTargetFileOrThrow(): TFile{
const targetFile = app.vault.getAbstractFileByPath( this.targetPath );
const targetFile = this.vault.getAbstractFileByPath( this.targetPath );
if (!(targetFile instanceof TFile)){
throw new Error(`Target file path was not found. '${this.targetPath}'`);
@ -57,7 +71,7 @@ export class MarkerRunContextImplemention implements TMarkerRunContext {
private async getTargetContents() : Promise<string>{
const targetFile = this.getTargetFileOrThrow();
return await app.vault.read( targetFile );
return await this.vault.cachedRead( targetFile );
}
async fetch(): Promise<MarkerValue[]> {
@ -70,20 +84,24 @@ export class MarkerRunContextImplemention implements TMarkerRunContext {
const exp = this.escapeRegex(this.markerStartPrefix)
+ '(.*?)' // marker name start
+ this.escapeRegex(this.markerStartSuffix)
+ '(\n?.*?\n?)' // marker value
+ this.markerValueRegEx // marker value
+ this.escapeRegex(this.markerEndPrefix)
+ '(.*?)' // marker name end
+ this.escapeRegex(this.markerEndSuffix)
;
//console.debug({exp});
const rgexp = new RegExp(exp, 'g');
//console.debug('MarkerRunContextImplementation::findMarkers', {exp});
const rgexp = new RegExp(exp, 'gm');
const matches = text.matchAll( rgexp );
const result:MarkerValue[] = [];
for (const match of matches) {
//console.debug({match});
if( match.index == undefined ){
continue;
}
@ -119,7 +137,7 @@ export class MarkerRunContextImplemention implements TMarkerRunContext {
if ( this.newValues.has( marker.name ) ){
continue;
}
console.log('apply::clearing marker value', {marker});
//console.log('apply::clearing marker value', {marker});
this.newValues.set( marker.name, '' );
}
}
@ -129,23 +147,22 @@ export class MarkerRunContextImplemention implements TMarkerRunContext {
for ( const key of this.newValues.keys() ) {
const currentMarkers = markers.filter( e => e.name == key );
if ( currentMarkers.length == 0 ){
console.debug('apply::marker isn\'t in file',{key, markers, targetFileContent});
//console.debug('apply::marker isn\'t in file',{key, markers, targetFileContent});
continue; // marker isn't in file
}
const newValue = this.newValues.get(key) ?? '';
// build replacement regex
const findExp = this.escapeRegex(this.markerStartPrefix + key + this.markerStartSuffix)
+ '(\n?.*?\n?)' // any old marker value
+ this.escapeRegex(this.markerEndPrefix + key +this.markerEndSuffix)
+ this.markerValueRegEx // any old marker value
+ this.escapeRegex(this.markerEndPrefix + key +this.markerEndSuffix)
;
const replacement = `${this.markerStartPrefix}${key}${this.markerStartSuffix}${newValue}${this.markerEndPrefix}${key}${this.markerEndSuffix}`;
//console.log({findExp, replacement, currentMarkers});
const findRegex = new RegExp(findExp, 'g');
const findRegex = new RegExp(findExp, 'gm');
targetFileContent = targetFileContent.replaceAll( findRegex, replacement );
@ -160,10 +177,10 @@ export class MarkerRunContextImplemention implements TMarkerRunContext {
//console.debug({targetFileContent});
const targetFile = this.getTargetFileOrThrow();
await app.vault.modify( targetFile, targetFileContent );
await this.vault.modify( targetFile, targetFileContent );
return result;
}
}
}

View file

@ -3,7 +3,7 @@ import { AskModal } from "./modal-ask";
import { MessageModal } from "./modal-message";
import { TUiRunContext } from "./run-context";
export class UiRunContextImplemention implements TUiRunContext {
export class UiRunContextImplementation implements TUiRunContext {
notice(
message: string | DocumentFragment,

View file

@ -24,6 +24,8 @@ export type TRunContext = {
dv: DataviewApi | undefined;
md: TMarkdownHelperRunContext;
}
export type TUiRunContext = {
@ -73,8 +75,10 @@ export type TMarkerRunContext = {
clear() : void;
get( name:string ): string|null|undefined;
set( name:string, value:string|null ): void;
load() : Promise<void>;
fetch() : Promise<MarkerValue[]>;
apply( clearUnknownMarkerValues?:boolean ) : Promise<MarkerChange[]>;
@ -114,3 +118,9 @@ export class MarkerChange{
}
}
export type TMarkdownHelperTableCellFormatter = (propName:string, value:any) => string|undefined;
export type TMarkdownHelperRunContext = {
table( headings:Array<string>, rows:Array<Array<any>> ) : string;
table( data:DataSet, cellFormatter?:TMarkdownHelperTableCellFormatter ) : string;
}

View file

@ -1,10 +1,15 @@
import { TFile } from "obsidian";
import { TFile, Vault } from "obsidian";
import { Utils } from "src/utils";
export class RunLogger {
private vault:Vault;
private file: TFile|undefined;
constructor( vault:Vault ){
this.vault = vault;
}
private console_info( ...params: any[] ){
window.console.info( 'meld-build', ...params );
}
@ -53,7 +58,7 @@ export class RunLogger {
logLine += '\n';
await app.vault.append( this.file, logLine );
await this.vault.append( this.file, logLine );
}
@ -65,14 +70,14 @@ export class RunLogger {
const filepath = Utils.getSameFolderFilepath(filename);
const af = app.vault.getAbstractFileByPath(filepath);
const af = this.vault.getAbstractFileByPath(filepath);
if ( af instanceof TFile ){
this.file = af;
if ( clear == true ){
app.vault.modify( this.file, '' );
this.vault.modify( this.file, '' );
}
}else{
this.file = await app.vault.create( filepath, '' );
this.file = await this.vault.create( filepath, '' );
}
}

View file

@ -20,10 +20,6 @@ export class Utils{
return normalizePath( parentPath + finalFilename );
}
public static delay(ms: number) : Promise<()=>void> {
return new Promise( resolve => setTimeout(resolve, ms) );
}
public static toBase64( buf: ArrayBuffer ) : string {
return arrayBufferToBase64( buf );
}

View file

@ -1,5 +1,11 @@
{
"0.1.3": "1.1.9",
"0.1.2": "1.1.9",
"0.1.1": "1.1.9"
}
"0.1.1": "1.0.1",
"0.1.2": "1.0.1",
"0.1.3": "1.0.1",
"0.1.4": "1.0.1",
"0.1.5": "1.0.1",
"0.1.6": "1.0.1",
"0.1.7": "1.0.1",
"0.1.8": "1.0.1",
"0.1.9": "1.0.1"
}