Skip to content

Commit

Permalink
Add default folder and prompt for name settings (#204)
Browse files Browse the repository at this point in the history
* added option to specify folder

* added option for folder

* succesfully added prompt for name setting

* Changed manifect and package files to original from source

---------

Co-authored-by: unxok <anderluke707@gmail.com>
Co-authored-by: Sam <sam@sbgood.ca>
  • Loading branch information
3 people authored Feb 1, 2024
1 parent 6ceced5 commit 0efb381
Show file tree
Hide file tree
Showing 9 changed files with 2,447 additions and 514 deletions.
2,029 changes: 2,029 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

28 changes: 14 additions & 14 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import typescript from '@rollup/plugin-typescript'
import commonjs from "@rollup/plugin-commonjs";
import json from "@rollup/plugin-json";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";

const banner = `/*
THIS IS A GENERATED/BUNDLED FILE BY ROLLUP
if you want to view the source visit the plugins github repository
*/
`
`;

export default {
input: 'src/index.ts',
input: "src/index.ts",
output: {
file: 'main.js',
sourcemap: 'inline',
format: 'cjs',
exports: 'default',
banner
file: "main.js",
sourcemap: "inline",
format: "cjs",
exports: "default",
banner,
},
external: ['obsidian'],
plugins: [typescript(), nodeResolve({ browser: true }), commonjs(), json()]
}
external: ["obsidian"],
plugins: [typescript(), nodeResolve({ browser: true }), commonjs(), json()],
};
73 changes: 58 additions & 15 deletions src/buttonTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export const text = async (
await appendContent(app, args.action, position.lineEnd);
}
if (args.type.includes("note")) {
await createNote(app, args.action, args.type);
createNote(app, args.action, args.type, args.folder, args.prompt);
}
if (args.type.includes("line")) {
await addContentAtLine(app, args.action, args.type);
Expand All @@ -95,20 +95,22 @@ export const template = async (
position: Position
): Promise<void> => {
const templatesEnabled = app.internalPlugins.plugins.templates.enabled;
const templaterPluginEnabled =
app.plugins.plugins["templater-obsidian"];
const templaterPluginEnabled = app.plugins.plugins["templater-obsidian"];

// only run if templates plugin is enabled
if (templatesEnabled || templaterPluginEnabled) {
const folders: string[] = [
templatesEnabled && app.internalPlugins.plugins.templates.instance.options.folder?.toLowerCase(),
templaterPluginEnabled && app.plugins?.plugins[
"templater-obsidian"
]?.settings.template_folder?.toLowerCase(),
templaterPluginEnabled && app.plugins?.plugins[
"templater-obsidian"
]?.settings.templates_folder?.toLowerCase(),
].filter((folder) => folder).map((folder) => folder.replace(/^\//, ''));
templatesEnabled &&
app.internalPlugins.plugins.templates.instance.options.folder?.toLowerCase(),
templaterPluginEnabled &&
app.plugins?.plugins[
"templater-obsidian"
]?.settings.template_folder?.toLowerCase(),
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) => {
Expand All @@ -134,9 +136,7 @@ export const template = async (
await runTemplater(app);
}
if (args.type.includes("note")) {

createNote(app, content, args.type, file, args.templater);

createNote(app, content, args.type, file, args.templater args.folder, args.prompt);
}
if (args.type.includes("line")) {
await addContentAtLine(app, content, args.type);
Expand Down Expand Up @@ -261,7 +261,50 @@ export const templater = async (
const content = await app.vault.cachedRead(file);
await runTemplater(app);
const { args } = await getNewArgs(app, position);
await app.vault.modify(file, content);
const cachedData: string[] = [];
const cacheChange = app.vault.on("modify", (file) => {
cachedData.push(file.unsafeCachedData);
});
setTimeout(async () => {
const button = content
.split("\n")
.splice(position.lineStart, position.lineEnd - position.lineStart + 2)
.join("\n");
let finalContent;
if (cachedData[0]) {
const cachedContent = cachedData[cachedData.length - 1].split("\n");
let addOne = false;
if (args.type.includes("prepend")) {
addOne = true;
} else if (args.type.includes("line")) {
const lineNumber = args.type.match(/(\d+)/g);
if (lineNumber[0]) {
const line = parseInt(lineNumber[0]) - 1;
if (line < position.lineStart && !args.replace) {
addOne = true;
}
}
}
if (addOne) {
cachedContent.splice(
position.lineStart + 1,
position.lineEnd - position.lineStart + 2,
button
);
} else {
cachedContent.splice(
position.lineStart,
position.lineEnd - position.lineStart + 2,
button
);
}
finalContent = cachedContent.join("\n");
} else {
finalContent = content;
}
await app.vault.modify(file, finalContent);
app.metadataCache.offref(cacheChange);
}, 200);
return args;
}
};
Expand Down
13 changes: 13 additions & 0 deletions src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { MarkdownView, App, Notice, TFile } from "obsidian";
import { ExtendedBlockCache } from "./types";
import { getStore } from "./buttonStore";
import { createContentArray, handleValueArray } from "./utils";
import { nameModal } from "./nameModal";

export const removeButton = async (
app: App,
Expand Down Expand Up @@ -149,6 +150,8 @@ export const createNote = async (
app: App,
content: string,
type: string,
folder: string,
prompt: string
filePath?: TFile,
templater?: string
): Promise<void> => {
Expand All @@ -159,13 +162,22 @@ export const createNote = async (
const directoryPath = fullPath.substring(0, fullPath.lastIndexOf('/'));

try {
if (prompt === "true") {
const promptedName = await new Promise<string>((res) =>
new nameModal(app, res, path[1]).open()
);
path[1] = promptedName ? promptedName : path[1];
}
path[1] = folder ? `${folder}/${path[1]}` : path[1];

// Check if the directory exists, if not, create it
if (!app.vault.getAbstractFileByPath(directoryPath)) {
await app.vault.createFolder(directoryPath);
}

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

if (path[2]) {
await app.workspace.splitActiveLeaf().openFile(file);
} else if (path[2] == "tab") {
Expand All @@ -183,6 +195,7 @@ export const createNote = async (
}
}
} catch (e) {
console.error("Error in Buttons: ", e);
new Notice("There was an error! Maybe the file already exists?", 2000);
}
} else {
Expand Down
30 changes: 28 additions & 2 deletions src/modal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export class ButtonModal extends Modal {
activeView: MarkdownView;
activeEditor: Editor;
activeCursor: CodeMirror.Position;
actionInterval: Timeout;
// actionInterval: Timeout;
buttonPreviewEl: HTMLElement = createEl("p");
commandSuggestEl: HTMLInputElement = createEl("input", { type: "text" });
fileSuggestEl: HTMLInputElement = createEl("input", { type: "text" });
Expand Down Expand Up @@ -77,6 +77,8 @@ export class ButtonModal extends Modal {
customColor: "",
customTextColor: "",
blockId: "",
folder: "",
prompt: false,
};

onOpen(): void {
Expand Down Expand Up @@ -177,11 +179,35 @@ export class ButtonModal extends Modal {
});
}
if (value == "note template") {
new Setting(action)
.setName("Prompt")
.setDesc(
"Should you be prompted to enter a name for the file on creation?"
)
.addToggle((toggleEl) => {
this.outputObject.prompt = false;
toggleEl.onChange(
(bool) => (this.outputObject.prompt = bool)
);
});
new Setting(action)
.setName("Note Name")
.setDesc("What should the new note be named?")
.setDesc(
"What should the new note be named? Note: if prompt is on, this will be the default name"
)
.addText((textEl) => {
textEl.setPlaceholder("My New Note");
new Setting(action)
.setName("Default Folder")
.setDesc(
"Enter a folder path to place the note in. Defaults to root"
)
.addText((textEl) => {
this.outputObject.folder = "";
textEl.onChange((textVal) => {
this.outputObject.folder = textVal;
});
});
new Setting(action)
.setName("Split")
.setDesc("Should the new note open in a split pane?")
Expand Down
45 changes: 45 additions & 0 deletions src/nameModal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { App, Modal, Setting } from "obsidian";

export class nameModal extends Modal {
result: string;
defaultName: string;
onSubmit: (result: string) => void;

constructor(
app: App,
onSubmit: (result: string) => void,
defaultName: string
) {
super(app);
this.onSubmit = onSubmit;
this.defaultName = defaultName;
}

onOpen(): void {
const { contentEl } = this;

contentEl.createEl("h1", { text: "Name of new note" });

new Setting(contentEl).setName("Name").addText((text) => {
text.setPlaceholder(this.defaultName);
text.onChange((value: string) => {
this.result = value;
});
});

new Setting(contentEl).addButton((btn) =>
btn
.setButtonText("Create Note")
.setCta()
.onClick(() => {
this.close();
this.onSubmit(this.result);
})
);
}

onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
4 changes: 3 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ declare module "obsidian" {
plugins: {
"templater-obsidian": {
_loaded: boolean;
settings: { template_folder: string, templates_folder: string };
settings: { template_folder: string; templates_folder: string };
};
};
};
Expand Down Expand Up @@ -51,6 +51,8 @@ export interface Arguments {
id?: string;
remove?: string;
replace?: string;
folder?: string;
// prompt?: string;
[key: string]: string;
}

Expand Down
9 changes: 8 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ interface OutputObject {
customColor: string;
customTextColor: string;
blockId: string;
folder: string;
prompt: boolean;
}

export const insertButton = (app: App, outputObject: OutputObject): void => {
Expand All @@ -44,6 +46,8 @@ export const insertButton = (app: App, outputObject: OutputObject): void => {
outputObject.customColor && buttonArr.push(`customColor ${outputObject.customColor}`);
outputObject.customTextColor && buttonArr.push(`customTextColor ${outputObject.customTextColor}`);
outputObject.class && buttonArr.push(`class ${outputObject.class}`);
outputObject.folder && buttonArr.push(`folder ${outputObject.folder}`);
outputObject.folder && buttonArr.push(`prompt ${outputObject.prompt}`);
buttonArr.push("```");
outputObject.blockId
? buttonArr.push(`^button-${outputObject.blockId}`)
Expand All @@ -64,7 +68,10 @@ export const createArgumentObject = (source: string): Arguments =>
source.split("\n").reduce((acc: Arguments, i: string) => {
const split: string[] = i.split(" ");
const key: string = split[0].toLowerCase();
acc[key] = split.filter((item) => item !== split[0]).join(" ").trim();
acc[key] = split
.filter((item) => item !== split[0])
.join(" ")
.trim();
return acc;
}, {});

Expand Down
Loading

0 comments on commit 0efb381

Please sign in to comment.