mirror of
https://github.com/meld-cp/obsidian-build.git
synced 2026-07-22 07:30:25 +00:00
Compare commits
No commits in common. "master" and "0.1.5" have entirely different histories.
20 changed files with 100 additions and 294 deletions
5
.gitignore
vendored
5
.gitignore
vendored
|
|
@ -22,7 +22,4 @@ data.json
|
|||
.DS_Store
|
||||
|
||||
# Test vault
|
||||
test-vault
|
||||
|
||||
# Other
|
||||
desktop.ini
|
||||
test-vault
|
||||
2
LICENSE
2
LICENSE
|
|
@ -1,6 +1,6 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2023 Cleon Pinto
|
||||
Copyright (c) 2021 Michael Brenan
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
|
|||
2
dist/manifest.json
vendored
2
dist/manifest.json
vendored
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"id": "meld-build",
|
||||
"name": "Meld Build",
|
||||
"version": "0.1.9",
|
||||
"version": "0.1.5",
|
||||
"minAppVersion": "1.0.1",
|
||||
"description": "Write and execute (sandboxed) JavaScript to render templates, query DataView and create dynamic notes.",
|
||||
"author": "meld-cp",
|
||||
|
|
|
|||
29
docs/api.md
29
docs/api.md
|
|
@ -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 2 line message with title
|
||||
await $.ui.message( 'A Title', 'A titled message\nLine 2' );
|
||||
// show a message with title
|
||||
await $.ui.message( 'A Title', 'A titled <b>message</b>' );
|
||||
await $.ui.message( 'Math', 13 * 67 );
|
||||
|
||||
// rebuild the current view, may be needed if you have an embedded note which was modified
|
||||
|
|
@ -96,7 +96,7 @@ 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
|
||||
- Optionally specify the mime type.
|
||||
- Optionaly 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`
|
||||
|
|
@ -146,10 +146,6 @@ 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()`
|
||||
|
|
@ -157,7 +153,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? )`
|
||||
- Applies set marker values to the target file
|
||||
- Applys 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
|
||||
|
|
@ -176,18 +172,12 @@ 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() );
|
||||
|
||||
|
|
@ -197,15 +187,6 @@ 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.
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ await $.ui.message('This is the init codeblock');
|
|||
```
|
||||
````
|
||||
|
||||
Multiple codeblocks with the same tag will be concatenated together before running.
|
||||
Multiple codeblocks with the same tag will be concatinated together before running.
|
||||
|
||||
To skip a codeblock all together, use the `skip` tag like this:
|
||||
````md
|
||||
|
|
@ -100,8 +100,8 @@ Say your note looks like this:
|
|||
# My Runnable Note
|
||||
|
||||
The template codeblock:
|
||||
```
|
||||
Greetings {{name}}, {{message}}
|
||||
```html
|
||||
<p>Greetings <strong>{{name}}</strong>, {{message}}</p>
|
||||
```
|
||||
|
||||
The meld-build block to run:
|
||||
|
|
@ -116,7 +116,7 @@ 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.
|
||||
|
||||
|
|
@ -143,7 +143,7 @@ See the [API](api.md) or another [example](examples/guess-the-number-marker.md)
|
|||
|
||||
## Accessing the DataView plugin API
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
For example:
|
||||
````md
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"id": "meld-build",
|
||||
"name": "Meld Build",
|
||||
"version": "0.1.9",
|
||||
"version": "0.1.5",
|
||||
"minAppVersion": "1.0.1",
|
||||
"description": "Write and execute (sandboxed) JavaScript to render templates, query DataView and create dynamic notes.",
|
||||
"author": "meld-cp",
|
||||
|
|
|
|||
4
package-lock.json
generated
4
package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "meld-build-obsidian-plugin",
|
||||
"version": "0.1.9",
|
||||
"version": "0.1.4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "meld-build-obsidian-plugin",
|
||||
"version": "0.1.9",
|
||||
"version": "0.1.4",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/handlebars": "^4.1.0",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "meld-build-obsidian-plugin",
|
||||
"version": "0.1.9",
|
||||
"version": "0.1.5",
|
||||
"description": "This is a sample plugin for Obsidian (https://obsidian.md)",
|
||||
"main": "main.js",
|
||||
"scripts": {
|
||||
|
|
|
|||
|
|
@ -6,11 +6,10 @@ 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 { AssertRunContextImplementation } from "./rci-assert";
|
||||
import { UiRunContextImplementation } from "./rci-ui";
|
||||
import { IoRunContextImplementation } from "./rci-io";
|
||||
import { MarkerRunContextImplementation } from "./rci-markers";
|
||||
import { MarkdownHelperRunContextImplementation } from "./rci-markdown";
|
||||
import { AssertRunContextImplemention } from "./rci-assert";
|
||||
import { UiRunContextImplemention } from "./rci-ui";
|
||||
import { IoRunContextImplemention } from "./rci-io";
|
||||
import { MarkerRunContextImplemention } from "./rci-markers";
|
||||
|
||||
export class Compiler{
|
||||
|
||||
|
|
@ -143,11 +142,11 @@ export class Compiler{
|
|||
return '';
|
||||
},
|
||||
|
||||
assert: new AssertRunContextImplementation(),
|
||||
assert: new AssertRunContextImplemention(),
|
||||
|
||||
ui: new UiRunContextImplementation(),
|
||||
ui: new UiRunContextImplemention(),
|
||||
|
||||
io: new IoRunContextImplementation(
|
||||
io: new IoRunContextImplemention(
|
||||
view.app.vault,
|
||||
view.app.workspace,
|
||||
log,
|
||||
|
|
@ -155,15 +154,13 @@ export class Compiler{
|
|||
consumableBlocks
|
||||
),
|
||||
|
||||
markers: new MarkerRunContextImplementation(
|
||||
markers: new MarkerRunContextImplemention(
|
||||
view.app.vault,
|
||||
log,
|
||||
view.file.path
|
||||
),
|
||||
|
||||
dv: dvGetAPI(),
|
||||
|
||||
md: new MarkdownHelperRunContextImplementation( log )
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,26 +1,5 @@
|
|||
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 {
|
||||
|
|
@ -35,13 +14,12 @@ export class DataSetRow implements IRowDataValueCollection{
|
|||
|
||||
[column: string]: unknown;
|
||||
|
||||
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);
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ 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();
|
||||
}
|
||||
}
|
||||
|
|
@ -104,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();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ export class MessageModal extends Modal {
|
|||
|
||||
private message:string;
|
||||
|
||||
constructor( app: App ) {
|
||||
super( app );
|
||||
constructor(app: App) {
|
||||
super(app);
|
||||
}
|
||||
|
||||
public async execute(
|
||||
|
|
@ -15,10 +15,12 @@ export class MessageModal extends Modal {
|
|||
|
||||
this.titleEl.setText( title );
|
||||
|
||||
this.contentEl.append( ...MessageModal.buildContent( message ) );
|
||||
this.message = message;
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
|
||||
this.open();
|
||||
|
||||
this.onClose = () => {
|
||||
this.contentEl.empty();
|
||||
resolve();
|
||||
|
|
@ -27,17 +29,10 @@ export class MessageModal extends Modal {
|
|||
|
||||
}
|
||||
|
||||
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;
|
||||
onOpen() {
|
||||
const { contentEl } = this;
|
||||
const formattedLines = this.message.split('\n').join('<br/>');
|
||||
contentEl.innerHTML = formattedLines;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -12,16 +12,16 @@ export class Parser {
|
|||
const result: NamedCodeBlock[] = [];
|
||||
|
||||
const file = view.file;
|
||||
const fileContent = await view.app.vault.cachedRead(file);
|
||||
const fileContent = await view.app.vault.read(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;
|
||||
}
|
||||
|
||||
|
|
@ -50,7 +50,7 @@ export class Parser {
|
|||
// filter languages
|
||||
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;
|
||||
}
|
||||
|
||||
|
|
@ -83,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;
|
||||
}
|
||||
|
||||
|
|
@ -104,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(',') ?? [];
|
||||
const columns = lines.first()?.split(',').map( e => this.extractAsColumnName(e) ) ?? [];
|
||||
|
||||
const ds = new DataSet( columns );
|
||||
|
||||
//const rows = new Array<DataSetRow>();
|
||||
const rows = new Array<DataSetRow>();
|
||||
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const rowData = lines[i].split(',').map( d => this.extractValueFromString(d));
|
||||
ds.push( new DataSetRow(ds, rowData));
|
||||
rows.push( new DataSetRow(columns, rowData));
|
||||
}
|
||||
|
||||
const ds = new DataSet( ...rows );
|
||||
|
||||
return ds;
|
||||
}
|
||||
|
||||
|
|
@ -181,15 +181,19 @@ 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 columns = tlines.first()?.split('|') ?? [];
|
||||
|
||||
const data: DataSet = new DataSet( columns );
|
||||
const tlines = tableLines
|
||||
.map( e=>e.trim().slice(1,-1).trim());
|
||||
|
||||
const columns = tlines
|
||||
.first()?.split('|')
|
||||
.map( e=> this.extractAsColumnName(e) )
|
||||
.filter( e=>e.length > 0)
|
||||
?? []
|
||||
;
|
||||
|
||||
for (let i = 2; i < tlines.length; i++) {
|
||||
for (let i = 1; i < tlines.length; i++) {
|
||||
const rowLine = tlines[i];
|
||||
if (rowLine.startsWith('---') ){
|
||||
continue;
|
||||
|
|
@ -198,7 +202,7 @@ export class Parser {
|
|||
continue;
|
||||
}
|
||||
const rowValues : unknown[] = rowLine.split('|').map( e => this.extractValueFromString(e) );
|
||||
data.push( new DataSetRow( data, rowValues ) );
|
||||
data.push( new DataSetRow( columns, rowValues ) );
|
||||
}
|
||||
|
||||
return data;
|
||||
|
|
@ -210,7 +214,7 @@ export class Parser {
|
|||
} = {};
|
||||
|
||||
const file = view.file;
|
||||
const fileContent = await view.app.vault.cachedRead(file);
|
||||
const fileContent = await view.app.vault.read(file);
|
||||
const fileCache = view.app.metadataCache.getFileCache( file );
|
||||
|
||||
if ( fileCache == null ){
|
||||
|
|
@ -232,6 +236,9 @@ 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
|
||||
|
|
@ -280,6 +287,10 @@ 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();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { MessageModal } from "./modal-message";
|
||||
import { TAssertRunContext } from "./run-context";
|
||||
|
||||
export class AssertRunContextImplementation implements TAssertRunContext {
|
||||
export class AssertRunContextImplemention implements TAssertRunContext {
|
||||
|
||||
private async showFailMessage( label:string, msg:string ) : Promise<void>{
|
||||
const title = '❗ Assert Failed' + ( label.length > 0 ? ` - ${label}` : '' );
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { TIoRunContext } from "./run-context";
|
|||
import { RunLogger } from "./run-logger";
|
||||
import { Utils } from "./utils";
|
||||
|
||||
export class IoRunContextImplementation implements TIoRunContext {
|
||||
export class IoRunContextImplemention implements TIoRunContext {
|
||||
|
||||
private vault: Vault;
|
||||
private workspace: Workspace;
|
||||
|
|
@ -32,27 +32,25 @@ export class IoRunContextImplementation implements TIoRunContext {
|
|||
}
|
||||
|
||||
private async data_loader(filepath:string, name?:string) : Promise<DataSet>{
|
||||
|
||||
let resultDataSet = new DataSet();
|
||||
|
||||
const absFilepath = this.getAbsoluteFilepathFromActiveFile(filepath);
|
||||
if (!absFilepath){
|
||||
return new DataSet([]);
|
||||
return resultDataSet;
|
||||
}
|
||||
|
||||
|
||||
const file = this.vault.getAbstractFileByPath(absFilepath);
|
||||
|
||||
|
||||
const pzr = new Parser();
|
||||
|
||||
if (file instanceof TFile){
|
||||
|
||||
if ( file.extension == 'csv'){
|
||||
const csvData = await this.vault.cachedRead( file );
|
||||
const dataSet = pzr.loadCsv(csvData);
|
||||
this.data[name??file.basename] = dataSet;
|
||||
return dataSet;
|
||||
if (file.extension == 'csv'){
|
||||
const csvdata = await this.vault.read( file );
|
||||
resultDataSet = pzr.loadCsv(csvdata);
|
||||
this.data[name??file.basename] = resultDataSet;
|
||||
}
|
||||
}
|
||||
|
||||
return new DataSet([]);
|
||||
return resultDataSet;
|
||||
}
|
||||
|
||||
async import(path: string): Promise<boolean> {
|
||||
|
|
@ -70,7 +68,7 @@ export class IoRunContextImplementation implements TIoRunContext {
|
|||
}
|
||||
|
||||
if ( file.extension == 'md' ){
|
||||
const content = await this.vault.cachedRead( file );
|
||||
const content = await this.vault.read( file );
|
||||
const pzr = new Parser();
|
||||
pzr.applyMarkdownContent(
|
||||
file.basename,
|
||||
|
|
@ -94,7 +92,7 @@ export class IoRunContextImplementation implements TIoRunContext {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
return await this.vault.cachedRead(af)
|
||||
return await this.vault.read(af)
|
||||
}
|
||||
|
||||
async load_data(path: string, name?: string | undefined): Promise<DataSet> {
|
||||
|
|
|
|||
|
|
@ -1,120 +0,0 @@
|
|||
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) );
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@ import { TFile, Vault } from "obsidian";
|
|||
import { MarkerChange, MarkerValue, TMarkerRunContext } from "./run-context";
|
||||
import { RunLogger } from "./run-logger";
|
||||
|
||||
export class MarkerRunContextImplementation implements TMarkerRunContext {
|
||||
export class MarkerRunContextImplemention implements TMarkerRunContext {
|
||||
|
||||
private markerStartPrefix = '%%';
|
||||
private markerStartSuffix = '=%%';
|
||||
|
|
@ -10,8 +10,6 @@ export class MarkerRunContextImplementation implements TMarkerRunContext {
|
|||
private markerEndPrefix = '%%=';
|
||||
private markerEndSuffix = '%%'
|
||||
|
||||
private markerValueRegEx = '((?:.|\\n|\\r)*?)';
|
||||
|
||||
private vault: Vault;
|
||||
private log: RunLogger;
|
||||
|
||||
|
|
@ -45,17 +43,6 @@ export class MarkerRunContextImplementation 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 );
|
||||
}
|
||||
|
|
@ -71,7 +58,7 @@ export class MarkerRunContextImplementation implements TMarkerRunContext {
|
|||
|
||||
private async getTargetContents() : Promise<string>{
|
||||
const targetFile = this.getTargetFileOrThrow();
|
||||
return await this.vault.cachedRead( targetFile );
|
||||
return await this.vault.read( targetFile );
|
||||
}
|
||||
|
||||
async fetch(): Promise<MarkerValue[]> {
|
||||
|
|
@ -84,24 +71,20 @@ export class MarkerRunContextImplementation implements TMarkerRunContext {
|
|||
const exp = this.escapeRegex(this.markerStartPrefix)
|
||||
+ '(.*?)' // marker name start
|
||||
+ this.escapeRegex(this.markerStartSuffix)
|
||||
+ this.markerValueRegEx // marker value
|
||||
+ '(\n?.*?\n?)' // marker value
|
||||
+ this.escapeRegex(this.markerEndPrefix)
|
||||
+ '(.*?)' // marker name end
|
||||
+ this.escapeRegex(this.markerEndSuffix)
|
||||
;
|
||||
|
||||
//console.debug('MarkerRunContextImplementation::findMarkers', {exp});
|
||||
|
||||
const rgexp = new RegExp(exp, 'gm');
|
||||
//console.debug({exp});
|
||||
const rgexp = new RegExp(exp, 'g');
|
||||
|
||||
const matches = text.matchAll( rgexp );
|
||||
|
||||
const result:MarkerValue[] = [];
|
||||
|
||||
for (const match of matches) {
|
||||
|
||||
//console.debug({match});
|
||||
|
||||
for (const match of matches) {
|
||||
//console.debug({match});
|
||||
if( match.index == undefined ){
|
||||
continue;
|
||||
}
|
||||
|
|
@ -155,14 +138,14 @@ export class MarkerRunContextImplementation implements TMarkerRunContext {
|
|||
|
||||
// build replacement regex
|
||||
const findExp = this.escapeRegex(this.markerStartPrefix + key + this.markerStartSuffix)
|
||||
+ this.markerValueRegEx // any old marker value
|
||||
+ this.escapeRegex(this.markerEndPrefix + key +this.markerEndSuffix)
|
||||
+ '(\n?.*?\n?)' // 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, 'gm');
|
||||
const findRegex = new RegExp(findExp, 'g');
|
||||
|
||||
targetFileContent = targetFileContent.replaceAll( findRegex, replacement );
|
||||
|
||||
|
|
@ -183,4 +166,4 @@ export class MarkerRunContextImplementation implements TMarkerRunContext {
|
|||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ import { AskModal } from "./modal-ask";
|
|||
import { MessageModal } from "./modal-message";
|
||||
import { TUiRunContext } from "./run-context";
|
||||
|
||||
export class UiRunContextImplementation implements TUiRunContext {
|
||||
export class UiRunContextImplemention implements TUiRunContext {
|
||||
|
||||
notice(
|
||||
message: string | DocumentFragment,
|
||||
|
|
|
|||
|
|
@ -24,8 +24,6 @@ export type TRunContext = {
|
|||
|
||||
dv: DataviewApi | undefined;
|
||||
|
||||
md: TMarkdownHelperRunContext;
|
||||
|
||||
}
|
||||
|
||||
export type TUiRunContext = {
|
||||
|
|
@ -75,10 +73,8 @@ 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[]>;
|
||||
|
|
@ -118,9 +114,3 @@ 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;
|
||||
}
|
||||
|
|
@ -3,9 +3,5 @@
|
|||
"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"
|
||||
"0.1.5": "1.0.1"
|
||||
}
|
||||
Loading…
Reference in a new issue