obsidian#Notice TypeScript Examples

The following examples show how to use obsidian#Notice. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.ts    From obsidian-citation-plugin with MIT License 8 votes vote down vote up
/**
   * @returns true if the notice was shown, and false otherwise
   */
  show(message?: string): boolean {
    message = message || this.defaultMessage;
    if (this.currentNotice) return false;

    this.currentNotice = new Notice(message) as NoticeExt;

    // Set up mutation observer to watch for when the notice disappears.
    this.mutationObserver?.disconnect();
    this.mutationObserver = new MutationObserver((changes, observer) => {
      const isDisappearing = changes.some((change) => {
        const el = change.target as HTMLElement;
        return (
          change.type == 'attributes' &&
          el.hasClass(NoticeExt.DISAPPEARING_CLASS)
        );
      });
      if (isDisappearing) {
        this.currentNotice = null;
        observer.disconnect();
        this.mutationObserver = null;
      }
    });
    this.mutationObserver.observe(this.currentNotice.noticeEl, {
      attributeFilter: ['class'],
    });
  }
Example #2
Source File: main.ts    From obsidian-ReadItLater with MIT License 6 votes vote down vote up
async writeFile(fileName: string, content: string): Promise<void> {
        let filePath;
        fileName = normalizeFilename(fileName);
        await checkAndCreateFolder(this.app.vault, this.settings.inboxDir);

        if (this.settings.inboxDir) {
            filePath = normalizePath(`${this.settings.inboxDir}/${fileName}`);
        } else {
            filePath = normalizePath(`/${fileName}`);
        }

        if (await this.app.vault.adapter.exists(filePath)) {
            new Notice(`${fileName} already exists!`);
        } else {
            const newFile = await this.app.vault.create(filePath, content);
            if (this.settings.openNewNote) {
                this.app.workspace.getLeaf(false).openFile(newFile);
            }
            new Notice(`${fileName} created successful`);
        }
    }
Example #3
Source File: renderer.ts    From obsidian-pandoc with MIT License 6 votes vote down vote up
async function getCustomCSS(settings: PandocPluginSettings, vaultBasePath: string): Promise<string> {
    if (!settings.customCSSFile) return;
    let file = settings.customCSSFile;
    let buffer: Buffer = null;
    // Try absolute path
    try {
        let test = await fs.promises.readFile(file);
        buffer = test;
    } catch(e) { }
    // Try relative path
    try {
        let test = await fs.promises.readFile(path.join(vaultBasePath, file));
        buffer = test;
    } catch(e) { }

    if(!buffer) {
        new Notice('Failed to load custom Pandoc CSS file: ' + settings.customCSSFile);
        return '';
    } else {
        return buffer.toString();
    }
}
Example #4
Source File: main.ts    From Obsidian_to_Anki with GNU General Public License v3.0 6 votes vote down vote up
async loadSettings(): Promise<PluginSettings> {
		let current_data = await this.loadData()
		if (current_data == null || Object.keys(current_data).length != 4) {
			new Notice("Need to connect to Anki generate default settings...")
			const default_sets = await this.getDefaultSettings()
			this.saveData(
				{
					settings: default_sets,
					"Added Media": [],
					"File Hashes": {},
					fields_dict: {}
				}
			)
			new Notice("Default settings successfully generated!")
			return default_sets
		} else {
			return current_data.settings
		}
	}
Example #5
Source File: Log.ts    From Templater with GNU Affero General Public License v3.0 6 votes vote down vote up
export function log_error(e: Error | TemplaterError): void {
    const notice = new Notice("", 8000);
    if (e instanceof TemplaterError && e.console_msg) {
        // TODO: Find a better way for this
        // @ts-ignore
        notice.noticeEl.innerHTML = `<b>Templater Error</b>:<br/>${e.message}<br/>Check console for more information`;
        console.error(`Templater Error:`, e.message, "\n", e.console_msg);
    } else {
        // @ts-ignore
        notice.noticeEl.innerHTML = `<b>Templater Error</b>:<br/>${e.message}`;
    }
}
Example #6
Source File: misc.ts    From alx-folder-note with MIT License 6 votes vote down vote up
export class ClickNotice extends Notice {
  constructor(
    message: string | ((desc: DocumentFragment) => void),
    action: (evt: MouseEvent) => any,
    timeout?: number,
  ) {
    super(typeof message === "string" ? message : "", timeout);
    this.noticeEl.addEventListener("click", action);
    if (typeof message === "function") {
      this.noticeEl.empty();
      let frag = new DocumentFragment();
      message(frag);
      this.noticeEl.append(frag);
    }
  }
}
Example #7
Source File: main.ts    From obsidian-consistent-attachments-and-links with MIT License 6 votes vote down vote up
async collectAttachmentsCurrentNote(editor: Editor, view: MarkdownView) {
		let note = view.file;
		if (this.isPathIgnored(note.path)) {
			new Notice("Note path is ignored");
			return;
		}

		let result = await this.fh.collectAttachmentsForCachedNote(
			note.path,
			this.settings.attachmentsSubfolder,
			this.settings.deleteExistFilesWhenMoveNote);

		if (result && result.movedAttachments && result.movedAttachments.length > 0) {
			await this.lh.updateChangedPathsInNote(note.path, result.movedAttachments)
		}

		if (result.movedAttachments.length == 0)
			new Notice("No files found that need to be moved");
		else
			new Notice("Moved " + result.movedAttachments.length + " attachment" + (result.movedAttachments.length > 1 ? "s" : ""));
	}
Example #8
Source File: main.tsx    From obsidian-annotator with GNU Affero General Public License v3.0 6 votes vote down vote up
async loadResources() {
        await loadResourcesZip(jszip.loadAsync(stringEncodedResourcesFolder));
        if (this.settings.annotateTvUrl) {
            try {
                const response = await corsFetch(this.settings.annotateTvUrl);
                if (response.ok) {
                    await loadResourcesZip(jszip.loadAsync(await response.arrayBuffer()));
                } else {
                    new Notice('Annotator: Could not fetch Annotate.TV resource zip');
                }
            } catch (e) {
                new Notice('Annotator: Could not fetch Annotate.TV resource zip');
            }
        }
        await awaitResourceLoading();
    }
Example #9
Source File: locationSuggest.ts    From obsidian-map-view with GNU General Public License v3.0 6 votes vote down vote up
selectSuggestion(value: SuggestInfo, evt: MouseEvent | KeyboardEvent) {
        // Replace the link under the cursor with the retrieved location.
        // We call getGeolinkOfCursor again instead of using the original context because it's possible that
        // the user continued to type text after the suggestion was made
        const currentCursor = value.context.editor.getCursor();
        const linkOfCursor = this.getGeolinkOfCursor(
            currentCursor,
            value.context.editor
        );
        const finalResult = `[${value.context.query}](geo:${value.location.lat},${value.location.lng})`;
        value.context.editor.replaceRange(
            finalResult,
            { line: currentCursor.line, ch: linkOfCursor.index },
            { line: currentCursor.line, ch: linkOfCursor.linkEnd }
        );
        if (utils.verifyOrAddFrontMatter(value.context.editor, 'locations', ''))
            new Notice(
                "The note's front matter was updated to denote locations are present"
            );
    }
Example #10
Source File: index.ts    From obsidian-fantasy-calendar with MIT License 6 votes vote down vote up
/**
     * Go to the next month index. Used to change months on the calendar.
     */
    goToNext() {
        const index = this.getNextMonthIndex();

        if (index < this.displayed.month) {
            if (!this.canGoToNextYear()) {
                new Notice(
                    "This is the last year. Additional years can be created in settings."
                );
                return;
            }
            this.goToNextYear();
        }
        this.setCurrentMonth(index);
    }
Example #11
Source File: plugin-callback.ts    From obsidian-imgur-plugin with MIT License 6 votes vote down vote up
editorCheckCallbackFor =
  (size: ImgurSize) => (checking: boolean, editor: Editor) => {
    const lineNumber = editor.getCursor().line;
    const match = findImgurMarkdownImage(
      editor.getLine(lineNumber),
      editor.getCursor().ch
    );

    if (!match.exists) return false;
    if (checking && match.exists) return true;

    let replacement;
    try {
      replacement = resizeTo(size)(match.mdImagePieces);
    } catch (e) {
      if (e instanceof Error)
        // eslint-disable-next-line no-new
        new Notice(e.message);
      // eslint-disable-next-line no-console
      else console.error(e);
      return false;
    }

    editor.replaceRange(
      replacement.content,
      { line: lineNumber, ch: replacement.from },
      { line: lineNumber, ch: replacement.to }
    );
    return true;
  }
Example #12
Source File: modals.ts    From obsidian-citation-plugin with MIT License 6 votes vote down vote up
onChooseItem(item: Entry, evt: MouseEvent | KeyboardEvent): void {
    if (evt instanceof MouseEvent || evt.key == 'Enter') {
      const newPane =
        evt instanceof KeyboardEvent && (evt as KeyboardEvent).ctrlKey;
      this.plugin.openLiteratureNote(item.id, newPane);
    } else if (evt.key == 'Tab') {
      if (evt.shiftKey) {
        const files = item.files || [];
        const pdfPaths = files.filter((path) =>
          path.toLowerCase().endsWith('pdf'),
        );
        if (pdfPaths.length == 0) {
          new Notice('This reference has no associated PDF files.');
        } else {
          open(`file://${pdfPaths[0]}`);
        }
      } else {
        open(item.zoteroSelectURI);
      }
    }
  }
Example #13
Source File: Action.ts    From obsidian-rss with GNU General Public License v3.0 6 votes vote down vote up
static READ = new Action(t("mark_as_read_unread"), "eye", ((async (plugin, item) : Promise<void> => {
        if (item.read) {
            item.read = false;
            new Notice(t("marked_as_unread"));
        } else {
            item.read = true;
            new Notice(t("marked_as_read"));
        }
        const items = plugin.settings.items;
        await plugin.writeFeedContent(() => {
            return items;
        });
        return Promise.resolve();
    })));
Example #14
Source File: main.ts    From obsidian-banners with MIT License 6 votes vote down vote up
// Helper to use clipboard for banner
  async pasteBanner(file: TFile) {
    const clipboard = await navigator.clipboard.readText();
    if (!isURL(clipboard)) {
      new Notice('Your clipboard didn\'t had a valid URL! Please try again (and check the console if you wanna debug).');
      console.error({ clipboard });
    } else {
      await this.metaManager.upsertBannerData(file, { src: `"${clipboard}"` });
      new Notice('Pasted a new banner!');
    }
  }
Example #15
Source File: chartFromTable.ts    From obsidian-charts with GNU Affero General Public License v3.0 6 votes vote down vote up
export function generateTableData(table: string, layout: 'columns' | 'rows', selected?: string[]) {
    let fields: any;
    try {
        fields = Extractor.extractObject(table, layout, false);
    } catch (error) {
        new Notice('Table malformed')
        throw error;
    }
    const labels = Object.keys(Object.values(fields)[0]);
    let dataFields: DataField[] = Object.keys(fields).map((key) => {
        return {
            dataTitle: key,
            data: Object.values(fields[key]) as string[]
        }
    });

    if(selected) {
        dataFields = dataFields.filter(value => selected.contains(value.dataTitle));
    }

    return {labels, dataFields};
}
Example #16
Source File: iconPicker.ts    From obsidian-customizable-sidebar with MIT License 6 votes vote down vote up
async onChooseItem(item: string): Promise<void> {
		this.command.icon = item;

		if (!this.editMode) {
			this.plugin.addRibbonIcon(item, this.command.name, () => {
				//@ts-ignore
				this.app.commands.executeCommandById(this.command.id);
			})
			this.plugin.settings.sidebarCommands.push(this.command);
		} else {
			new Notice("You will need to restart Obsidian for the changes to take effect.")
		}

		await this.plugin.saveSettings();

		setTimeout(() => {
			dispatchEvent(new Event("CS-addedCommand"));
		}, 100);
	}
Example #17
Source File: main.ts    From obsidian-linter with MIT License 6 votes vote down vote up
async runLinterFile(file: TFile) {
      const oldText = stripCr(await this.app.vault.read(file));

      try {
        const newText = this.lintText(oldText, file);
        await this.app.vault.modify(file, newText);
      } catch (error) {
        new Notice('An error occured during linting. See console for details');
        console.log(`Linting error in file: ${file.path}`);
        console.error(error);
      }
    }
Example #18
Source File: main.ts    From obsidian-readwise with GNU General Public License v3.0 6 votes vote down vote up
notice(msg: string, show = false, timeout = 0, forcing: boolean = false) {
    if (show) {
      new Notice(msg);
    }
    // @ts-ignore
    if (!this.app.isMobile) {
      this.statusBar.displayMessage(msg.toLowerCase(), timeout, forcing);
    } else {
      if (!show) {
        new Notice(msg);
      }
    }
  }
Example #19
Source File: settings.ts    From remotely-save with Apache License 2.0 6 votes vote down vote up
async onOpen() {
    let { contentEl } = this;

    const { authUrl, verifier } = await getAuthUrlAndVerifierOnedrive(
      this.plugin.settings.onedrive.clientID,
      this.plugin.settings.onedrive.authority
    );
    this.plugin.oauth2Info.verifier = verifier;

    const t = (x: TransItemType, vars?: any) => {
      return this.plugin.i18n.t(x, vars);
    };

    t("modal_onedriveauth_shortdesc")
      .split("\n")
      .forEach((val) => {
        contentEl.createEl("p", {
          text: val,
        });
      });
    const div2 = contentEl.createDiv();
    div2.createEl(
      "button",
      {
        text: t("modal_onedriveauth_copybutton"),
      },
      (el) => {
        el.onclick = async () => {
          await navigator.clipboard.writeText(authUrl);
          new Notice(t("modal_onedriveauth_copynotice"));
        };
      }
    );

    contentEl.createEl("p").createEl("a", {
      href: authUrl,
      text: authUrl,
    });
  }
Example #20
Source File: main.ts    From obsidian-spaced-repetition with MIT License 6 votes vote down vote up
async reviewNextNote(deckKey: string): Promise<void> {
        if (!Object.prototype.hasOwnProperty.call(this.reviewDecks, deckKey)) {
            new Notice(t("NO_DECK_EXISTS", { deckName: deckKey }));
            return;
        }

        this.lastSelectedReviewDeck = deckKey;
        const deck = this.reviewDecks[deckKey];

        if (deck.dueNotesCount > 0) {
            const index = this.data.settings.openRandomNote
                ? Math.floor(Math.random() * deck.dueNotesCount)
                : 0;
            this.app.workspace.activeLeaf.openFile(deck.scheduledNotes[index].note);
            return;
        }

        if (deck.newNotes.length > 0) {
            const index = this.data.settings.openRandomNote
                ? Math.floor(Math.random() * deck.newNotes.length)
                : 0;
            this.app.workspace.activeLeaf.openFile(deck.newNotes[index]);
            return;
        }

        new Notice(t("ALL_CAUGHT_UP"));
    }
Example #21
Source File: manager.ts    From obsidian-admonition with MIT License 6 votes vote down vote up
async downloadIcon(pack: DownloadableIconPack) {
        try {
            const icons: Record<string, string> = await (
                await fetch(this.iconPath(pack))
            ).json();
            this.plugin.data.icons.push(pack);
            this.plugin.data.icons = [...new Set(this.plugin.data.icons)];
            await this.plugin.app.vault.adapter.write(
                this.localIconPath(pack),
                JSON.stringify(icons)
            );
            this.DOWNLOADED[pack] = icons;
            await this.plugin.saveSettings();
            this.setIconDefinitions();

            new Notice(`${DownloadableIcons[pack]} successfully downloaded.`);
        } catch (e) {
            console.error(e);
            new Notice("Could not download icon pack");
        }
    }
Example #22
Source File: index.ts    From obsidian-initiative-tracker with GNU General Public License v3.0 6 votes vote down vote up
async postprocess() {
        const encounters = this.src.split("---") ?? [];
        const containerEl = this.containerEl.createDiv("encounter-container");
        const empty = containerEl.createSpan({
            text: "No encounters created. Please check your syntax and try again."
        });

        for (let encounter of encounters) {
            if (!encounter?.trim().length) continue;
            try {
                const params: EncounterParameters = parseYaml(encounter);
                new EncounterComponent(
                    await this.parser.parse(params),
                    containerEl.createDiv("encounter-instance"),
                    this.plugin
                );
                empty.detach();
            } catch (e) {
                console.error(e);
                new Notice(
                    "Initiative Tracker: here was an issue parsing: \n\n" +
                        encounter
                );
            }
        }
        this.registerEvent(
            this.plugin.app.workspace.on("initiative-tracker:unload", () => {
                this.containerEl.empty();
                this.containerEl.createEl("pre").createEl("code", {
                    text: `\`\`\`encounter\n${this.src}\`\`\``
                });
            })
        );
    }
Example #23
Source File: api.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
async getProfile() {
    try {
      const response = await axios.get(`${this.baseUrl}/profile`, { headers: this.getHeaders() })
      return response.data.userid
    }
    catch (e) {
      new Notice('Failed to authorize Hypothes.is user. Please check your API token and try again.')
      console.error(e);
      return;
    }
  }
Example #24
Source File: main.ts    From obsidian-pandoc with MIT License 5 votes vote down vote up
async startPandocExport(inputFile: string, format: OutputFormat, extension: string, shortName: string) {
        new Notice(`Exporting ${inputFile} to ${shortName}`);

        // Instead of using Pandoc to process the raw Markdown, we use Obsidian's
        // internal markdown renderer, and process the HTML it generates instead.
        // This allows us to more easily deal with Obsidian specific Markdown syntax.
        // However, we provide an option to use MD instead to use citations

        let outputFile: string = replaceFileExtension(inputFile, extension);
        if (this.settings.outputFolder) {
            outputFile = path.join(this.settings.outputFolder, path.basename(outputFile));
        }
        const view = this.app.workspace.getActiveViewOfType(MarkdownView);
        
        try {
            let error, command;

            switch (this.settings.exportFrom) {
                case 'html': {
                    const { html, metadata } = await render(this, view, inputFile, format);

                    if (format === 'html') {
                        // Write to HTML file
                        await fs.promises.writeFile(outputFile, html);
                        new Notice('Successfully exported via Pandoc to ' + outputFile);
                        return;
                    } else {
                        // Spawn Pandoc
                        const metadataFile = temp.path();
                        const metadataString = YAML.stringify(metadata);
                        await fs.promises.writeFile(metadataFile, metadataString);
                        const result = await pandoc(
                            {
                                file: 'STDIN', contents: html, format: 'html', metadataFile,
                                pandoc: this.settings.pandoc, pdflatex: this.settings.pdflatex
                            },
                            { file: outputFile, format },
                            this.settings.extraArguments.split('\n')
                        );
                        error = result.error;
                        command = result.command;
                    }
                    break;
                }
                case 'md': {
                    const result = await pandoc(
                        {
                            file: inputFile, format: 'markdown',
                            pandoc: this.settings.pandoc, pdflatex: this.settings.pdflatex
                        },
                        { file: outputFile, format },
                        this.settings.extraArguments.split('\n')
                    );
                    error = result.error;
                    command = result.command;
                    break;
                }
            }

            if (error.length) {
                new Notice('Exported via Pandoc to ' + outputFile + ' with warnings');
                new Notice('Pandoc warnings:' + error, 10000);
            } else {
                new Notice('Successfully exported via Pandoc to ' + outputFile);
            }
            if (this.settings.showCLICommands) {
                new Notice('Pandoc command: ' + command, 10000);
                console.log(command);
            }

        } catch (e) {
            new Notice('Pandoc export failed: ' + e.toString(), 15000);
            console.error(e);
        }
    }
Example #25
Source File: main.ts    From Obsidian_to_Anki with GNU General Public License v3.0 5 votes vote down vote up
async onload() {
		console.log('loading Obsidian_to_Anki...');
		addIcon('anki', ANKI_ICON)

		try {
			this.settings = await this.loadSettings()
		}
		catch(e) {
			new Notice("Couldn't connect to Anki! Check console for error message.")
			return
		}

		this.note_types = Object.keys(this.settings["CUSTOM_REGEXPS"])
		this.fields_dict = await this.loadFieldsDict()
		if (Object.keys(this.fields_dict).length == 0) {
			new Notice('Need to connect to Anki to generate fields dictionary...')
			try {
				this.fields_dict = await this.generateFieldsDict()
				new Notice("Fields dictionary successfully generated!")
			}
			catch(e) {
				new Notice("Couldn't connect to Anki! Check console for error message.")
				return
			}
		}
		this.added_media = await this.loadAddedMedia()
		this.file_hashes = await this.loadFileHashes()

		this.addSettingTab(new SettingsTab(this.app, this));

		this.addRibbonIcon('anki', 'Obsidian_to_Anki - Scan Vault', async () => {
			await this.scanVault()
		})

		this.addCommand({
			id: 'anki-scan-vault',
			name: 'Scan Vault',
			callback: async () => {
			 	await this.scanVault()
			 }
		})
	}
Example #26
Source File: Log.ts    From Templater with GNU Affero General Public License v3.0 5 votes vote down vote up
export function log_update(msg: string): void {
    const notice = new Notice("", 15000);
    // TODO: Find better way for this
    // @ts-ignore
    notice.noticeEl.innerHTML = `<b>Templater update</b>:<br/>${msg}`;
}
Example #27
Source File: fn-main.ts    From alx-folder-note with MIT License 5 votes vote down vote up
async onload() {
    console.log("loading alx-folder-note");

    await this.loadSettings();

    let tab = new ALxFolderNoteSettingTab(this.app, this);
    if (!tab.checkMigrated())
      new Notice(
        "Old config not yet migrated, \n" +
          "Open Settings Tab of ALx Folder Note for details",
      );
    this.addSettingTab(tab);

    let initCalled = false;
    const init = () => {
      initCalled = true;
      registerSetFolderIconCmd(this);
      this.app.workspace.onLayoutReady(this.initialize.bind(this));
      PatchDragManager(this);
      this.noticeFoldervChange();
    };

    if (getFNCApi(this)) {
      init();
    } else {
      if (this.app.plugins.enabledPlugins.has("folder-note-core")) {
        const timeoutId = window.setTimeout(() => {
          if (!initCalled) {
            this.app.vault.offref(evtRef);
            throw new Error(
              "folder-note-core enabled but fail to load within 5s",
            );
          }
        }, 5e3);
        const evtRef = this.app.vault.on("folder-note:api-ready", () => {
          init();
          if (timeoutId) window.clearTimeout(timeoutId);
          this.app.vault.offref(evtRef); // register event only once
        });
      } else {
        this.CoreApi; // prompt to enable folder-note-core
      }
    }
  }
Example #28
Source File: resolver.ts    From folder-note-core with MIT License 5 votes vote down vote up
/**
   * @returns return false if folder already exists
   */
  createFolderForNote: API["createFolderForNote"] = async (
    file: TFile,
    dryrun = false,
  ): Promise<boolean> => {
    const result = this._createFolderForNote(file);
    if (!result) return false;
    const { newFolderPath, folderExist } = result;
    if (folderExist) {
      log.info(
        "createFolderForNote(%o): target folder to create already exists",
        file,
        file.path,
      );
      if (!dryrun) new Notice("Target folder to create already exists");
      return false;
    } else if (!newFolderPath) {
      log.info(
        "createFolderForNote(%o): no vaild linked folder path for %s",
        file,
        file.path,
      );
      if (!dryrun) new Notice("No vaild linked folder path for: " + file.path);
    } else if (!dryrun) {
      await this.vault.createFolder(newFolderPath);
      let newNotePath: string | null;
      switch (this.settings.folderNotePref) {
        case NoteLoc.Index:
          newNotePath = join(newFolderPath, this.settings.indexName + ".md");
          break;
        case NoteLoc.Inside:
          newNotePath = join(newFolderPath, file.name);
          break;
        case NoteLoc.Outside:
          newNotePath = null;
          break;
        default:
          assertNever(this.settings.folderNotePref);
      }
      if (newNotePath)
        await this.plugin.app.fileManager.renameFile(file, newNotePath);
    }
    return !!(!folderExist && newFolderPath);
  };
Example #29
Source File: guiLogger.ts    From quickadd with MIT License 5 votes vote down vote up
logError(msg: string): void {
        const error = this.getQuickAddError(msg, ErrorLevel.Error);
        new Notice(this.formatOutputString(error));
    }