Skip to content

Commit

Permalink
Revert templater (#211)
Browse files Browse the repository at this point in the history
* remove duplicate copy command

* update templater handling

* update to handle built in templates function

* remove unused templater handler from button.ts

* templater working as expected

* built in templates working as expected

* update manifest and readme

* handle appending note title

* handle append/prepend of templates

* handle file.title templater commands

* fix template name popper

* remove logging

---------

Co-authored-by: Sam Morrison <[email protected]>
Co-authored-by: Sam Morrison <[email protected]>
  • Loading branch information
3 people authored Feb 10, 2024
1 parent a2d519f commit 73c87f6
Show file tree
Hide file tree
Showing 8 changed files with 154 additions and 83 deletions.
29 changes: 25 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ Run commands and open links by clicking on ✨ Buttons ✨

---

**last updated:** February 1st, 2024
**last updated:** February 9th, 2024

0.5.1 - fixed all those templater issues

0.5.0
Holy shit, look at all these awesome people that helped improve Buttons!

- Enhancement: Moved to more reliable templater processor ([shabegom])
Expand Down Expand Up @@ -333,15 +336,33 @@ Note: swap count is reset if you close the note.

## Releases

### 0.5.0

### 0.5.1
- Bugfix: Templater commands that move, rename, etc should be working again
- The default templates plugin should be working again
- sets a default name for a button so problems don't happen.

### 0.5.0
- Enhancement: Moved to more reliable templater processor ([shabegom])
- Bugfix: buttons now render in Live Preview mode when Obsidian starts ([Lx])
- Bugfix: improve reliability of `templater` option ([Lx])
- improve speed of `remove` option ([Lx])
- Enhancement: improve speed of `remove` option ([Lx])
- Feature: Add default folder and prompt for name settings ([unxok])
- Features: Button type copy for "copy text to clipboard", and custom color for button background and tex ([rafa-carmo])
- Feature: adds hidden attribute to buttons ([Liimurr])
- Enhancement: Create folder for new note if it doesn't exist ([SabriDW])
- Bugfix: fix template search with folders having "/" prefixed ([Balake])
- Feature: Open new tab when creating new file ([0snug0])
- Update Readme: new note from template ([antulik])


[Lx]: https://github.com/Lx
[unxok]: https://github.com/unxok
[rafa-carmo]: https://github.com/rafa-carmo
[Liimurr]: https://github.com/Liimurr
[SabriDW]: https://github.com/SabriDW
[Balake]: https://github.com/Balake
[0snug0]: https://github.com/0snug0
[antulik]: https://github.com/antulik


### 0.4.4
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"id": "buttons",
"name": "Buttons",
"description": "Create Buttons in your Obsidian notes to run commands, open links, and insert templates",
"version": "0.5.0",
"version": "0.5.1",
"author": "shabegom",
"authorUrl": "https://shbgm.ca",
"isDesktopOnly": false,
Expand Down
6 changes: 0 additions & 6 deletions src/button.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@ import {
calculate,
command,
copy,
copyText,
link,
remove,
replace,
swap,
template,
templater,
text,
} from "./buttonTypes";
import { getButtonPosition, getInlineButtonPosition } from "./parser";
Expand Down Expand Up @@ -93,10 +91,6 @@ const clickHandler = async (
if (args.type === "link") {
link(args);
}
// handle copy text buttons
if (args.type === "copy") {
copyText(args);
}
// handle template buttons
if (args.type && args.type.includes("template")) {
content = await app.vault.read(activeView.file);
Expand Down
61 changes: 35 additions & 26 deletions src/buttonTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
setButtonSwapById,
getButtonById,
} from "./buttonStore";
import { processTemplate } from "./templater"
import {processTemplate} from "./templater"

export const calculate = async (
app: App,
Expand Down Expand Up @@ -76,17 +76,17 @@ export const text = async (
): Promise<void> => {
// prepend template above the button
if (args.type.includes("prepend")) {
await prependContent(app, args.action, position.lineStart);
await prependContent(app, args.action, position.lineStart, false);
}
// append template below the button
if (args.type.includes("append")) {
await appendContent(app, args.action, position.lineEnd);
await appendContent(app, args.action, position.lineEnd, false);
}
if (args.type.includes("note")) {
createNote(app, args.action, args.type, args.folder, args.prompt);
createNote(app, args.type, args.folder, args.prompt, args.action, false);
}
if (args.type.includes("line")) {
await addContentAtLine(app, args.action, args.type);
await addContentAtLine(app, args.action, args.type, false);
}
};

Expand All @@ -97,44 +97,57 @@ export const template = async (
): Promise<void> => {
const templatesEnabled = app.internalPlugins.plugins.templates.enabled;
const templaterPluginEnabled = app.plugins.plugins["templater-obsidian"];
let isTemplater = false
const templateFile = args.action.toLowerCase();
const allFiles = app.vault.getFiles();
let file = null

// only run if templates plugin is enabled
if (templatesEnabled || templaterPluginEnabled) {
const folders: string[] = [
if (templatesEnabled) {
const folder: string =
templatesEnabled &&
app.internalPlugins.plugins.templates.instance.options.folder?.toLowerCase(),
app.internalPlugins.plugins.templates.instance.options.folder?.toLowerCase()
const isFound = allFiles.filter((file) => {
let found = false;
if (file.path.toLowerCase() === `${folder}/${templateFile}.md`) {
found = true;
}
return found
})
file = isFound[0]
}

if (!file && templaterPluginEnabled) {
const folder: string =
templaterPluginEnabled &&
app.plugins?.plugins[
"templater-obsidian"
]?.settings.templates_folder?.toLowerCase(),
].filter((folder) => folder);
const templateFile = args.action.toLowerCase();
const allFiles = app.vault.getFiles();
const file: TFile = allFiles.filter((file) => {
]?.settings.templates_folder?.toLowerCase()
const isFound = allFiles.filter((file) => {
let found = false;
folders[0] &&
folders.forEach((folder) => {
if (file.path.toLowerCase() === `${folder}/${templateFile}.md`) {
found = true;
isTemplater = true;
}
});
return found;
})[0];
})
file = isFound[0]
}

if (file) {
const content = await processTemplate(file)
// prepend template above the button
if (args.type.includes("prepend")) {
await prependContent(app, content, position.lineStart);
await prependContent(app, file, position.lineStart, isTemplater);
}
// append template below the button
if (args.type.includes("append")) {
await appendContent(app, content, position.lineEnd);
await appendContent(app, file, position.lineEnd, isTemplater);
}
if (args.type.includes("note")) {
createNote(app, content, args.type, args.folder, args.prompt, file, args.templater);
createNote(app, args.type, args.folder, args.prompt, file, isTemplater);
}
if (args.type.includes("line")) {
await addContentAtLine(app, content, args.type);
await addContentAtLine(app, file, args.type, isTemplater);
}
} else {
new Notice(
Expand Down Expand Up @@ -303,7 +316,3 @@ export const templater = async (
}
};

export const copyText = ({ action }: Arguments): void => {
navigator.clipboard.writeText(action);
new Notice('Text Copied!');
}
97 changes: 73 additions & 24 deletions src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ExtendedBlockCache } from "./types";
import { getStore } from "./buttonStore";
import { createContentArray, handleValueArray } from "./utils";
import { nameModal } from "./nameModal";
import { Z_FULL_FLUSH } from "node:zlib";
import templater from "./templater";

export const removeButton = async (
app: App,
Expand Down Expand Up @@ -80,15 +80,29 @@ export const removeSection = async (

export const prependContent = async (
app: App,
insert: string,
insert: string | TFile,
lineStart: number,
isTemplater: boolean,
): Promise<void> => {
const activeView = app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
const file = activeView.file;
let content = await app.vault.read(file);
const contentArray = content.split("\n");
contentArray.splice(lineStart, 0, insert);
if (typeof insert === "string") {
contentArray.splice(lineStart, 0, `${insert}`);
} else {
if (isTemplater) {
const runTemplater = await templater(insert, file);
const content = await app.vault.read(insert);
const processed = await runTemplater(content);
contentArray.splice(lineStart, 0, `${processed}`);
} else {
activeView.editor.setCursor(lineStart)
await (app as any).internalPlugins?.plugins["templates"].instance
.insertTemplate(insert);
}
}
content = contentArray.join("\n");
await app.vault.modify(file, content);
} else {
Expand All @@ -98,8 +112,9 @@ export const prependContent = async (

export const appendContent = async (
app: App,
insert: string,
insert: any,
lineEnd: number,
isTemplater: boolean,
): Promise<void> => {
const activeView = app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
Expand All @@ -112,11 +127,23 @@ export const appendContent = async (
contentArray[lineEnd + 1].includes("^button")
) {
insertionPoint = lineEnd + 2;
insert = `\n${insert}`;
} else {
insertionPoint = lineEnd + 1;
}
contentArray.splice(insertionPoint, 0, `${insert}`);
if (typeof insert === "string") {
contentArray.splice(insertionPoint, 0, `\n${insert}`);
} else {
if (isTemplater) {
const runTemplater = await templater(insert, file);
const content = await app.vault.read(insert);
const processed = await runTemplater(content);
contentArray.splice(insertionPoint, 0, `${processed}`);
} else {
activeView.editor.setCursor(insertionPoint)
await (app as any).internalPlugins?.plugins["templates"].instance
.insertTemplate(insert);
}
}
content = contentArray.join("\n");
await app.vault.modify(file, content);
} else {
Expand All @@ -126,8 +153,9 @@ export const appendContent = async (

export const addContentAtLine = async (
app: App,
insert: string,
insert: string | TFile,
type: string,
isTemplater: boolean,
): Promise<void> => {
const lineNumber = type.match(/(\d+)/g);
if (lineNumber[0]) {
Expand All @@ -137,7 +165,20 @@ export const addContentAtLine = async (
const file = activeView.file;
let content = await app.vault.read(file);
const contentArray = content.split("\n");
contentArray.splice(insertionPoint, 0, `${insert}`);
if (typeof insert === "string") {
contentArray.splice(insertionPoint, 0, `${insert}`);
} else {
if (isTemplater) {
const runTemplater = await templater(insert, file);
const content = await app.vault.read(insert);
const processed = await runTemplater(content);
contentArray.splice(insertionPoint, 0, `${processed}`);
} else {
activeView.editor.setCursor(insertionPoint)
await (app as any).internalPlugins?.plugins["templates"].instance
.insertTemplate(insert);
}
}
content = contentArray.join("\n");
await app.vault.modify(file, content);
}
Expand All @@ -148,12 +189,11 @@ export const addContentAtLine = async (

export const createNote = async (
app: App,
content: string,
type: string,
folder: string,
prompt: string,
filePath?: TFile,
templater?: string,
filePath: TFile | string,
isTemplater?: boolean,
): Promise<void> => {
const path = type.match(/\(([\s\S]*?),?\s?(split|tab)?\)/);

Expand All @@ -168,7 +208,7 @@ export const createNote = async (
const directoryPath = fullPath.substring(0, fullPath.lastIndexOf("/"));
// Check if the directory exists, if not, create it
if (directoryPath && !app.vault.getAbstractFileByPath(directoryPath)) {
console.log("trying to create folder at: ", directoryPath)
console.log("trying to create folder at: ", directoryPath);
await app.vault.createFolder(directoryPath);
}

Expand All @@ -181,9 +221,24 @@ export const createNote = async (
? `${directoryPath}/${promptedName}.md`
: fullPath;
}
let file: TFile;

if (typeof filePath === "string") {
file = await app.vault.create(fullPath, filePath);
}

await app.vault.create(fullPath, content);
const file = app.vault.getAbstractFileByPath(fullPath) as TFile;

const templateContent = await app.vault.read(filePath as TFile);
if (isTemplater) {
file = await app.vault.create(fullPath, templateContent);
const runTemplater = await templater(filePath, file);
const content = await app.vault.read(filePath);
const processed = await runTemplater(content);
await app.vault.modify(file, processed);
}
if (!isTemplater && typeof filePath !== "string") {
file = await app.vault.create(fullPath, "");
}

if (path[2] === "split") {
await app.workspace.splitActiveLeaf().openFile(file);
Expand All @@ -192,16 +247,10 @@ export const createNote = async (
} else {
await app.workspace.getLeaf().openFile(file);
}
// I don't know what this was supposed to do...
// if (filePath) {
// if (templater) {
// (app as any).plugins.plugins["templater-obsidian"].templater
// .append_template_to_active_file(filePath);
// } else {
// (app as any).internalPlugins?.plugins["templates"].instance
// .insertTemplate(filePath);
// }
// }
if (!isTemplater && typeof filePath !== "string") {
await (app as any).internalPlugins?.plugins["templates"].instance
.insertTemplate(filePath);
}
} catch (e) {
console.error("Error in Buttons: ", e);
new Notice("There was an error! Maybe the file already exists?", 2000);
Expand Down
2 changes: 1 addition & 1 deletion src/suggest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ export class TemplateSuggest extends TextInputSuggest<TFile> {
folders.push(folder.toLowerCase());
}
if (this.templaterPlugin) {
const folder = this.templaterPlugin.settings.template_folder;
const folder = this.templaterPlugin.settings.templates_folder;
if (folder) {
folders.push(folder.toLowerCase());
}
Expand Down
Loading

0 comments on commit 73c87f6

Please sign in to comment.