Files

1099 lines
51 KiB
JavaScript
Raw Permalink Normal View History

/*
THIS IS A GENERATED/BUNDLED FILE BY ROLLUP
if you want to view the source visit the plugins github repository
*/
'use strict';
var obsidian = require('obsidian');
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
const SAFE_DB_FLUSH_INTERVAL = 5000;
const DEFAULT_DB_FILENAME_LEGACY = '.obsidian/plugins/remember-cursor-position/cursor-positions.json';
const DEFAULT_SETTINGS = {
dbFileName: '',
delayAfterFileOpening: 100,
saveTimer: SAFE_DB_FLUSH_INTERVAL,
pruneOrphans: false,
maxAgeDays: 0,
maxCount: 0,
defaultPosition: 'default',
skipRestoreFromSearch: false,
restorePositionOnWorkspaceLoad: true,
excludedFiles: [],
};
// Skip re-restoring the same (leaf, file) combination within this window.
// It keeps the "don't jump the cursor when a document is already open" intent
// without blocking restoration on startup or when a workspace is loaded.
const RESTORE_GUARD_WINDOW_MS = 1500;
// Delay after the layout is ready before forcing a restore of the active file.
const LAYOUT_READY_RESTORE_DELAY = 600;
// Window during which a detected workspace load suppresses position restoration
// when the "restore on workspace load" option is disabled.
const WORKSPACE_LOAD_WINDOW_MS = 3000;
// Throttle for the position check: at most one per 100 ms after a scroll or
// selection event. It equals the period of the polling it replaces, so a quick
// note switch loses no more than it did before.
const STATE_CHECK_THROTTLE_MS = 100;
// Debounce for workspace layout change handling.
const LAYOUT_CHANGE_DEBOUNCE_MS = 250;
function globToRegex(glob) {
let pattern = glob.trim().replace(/\\/g, '/');
let folderOnly = false;
if (pattern.endsWith('/')) {
folderOnly = true;
pattern = pattern.slice(0, -1);
}
let re = '';
for (let i = 0; i < pattern.length; i++) {
const c = pattern[i];
if (c === '*') {
if (pattern[i + 1] === '*') {
i++;
if (pattern[i + 1] === '/') {
// "**/" matches zero or more path segments
i++;
re += '(?:.*/)?';
}
else {
re += '.*';
}
}
else {
re += '[^/]*';
}
}
else if (c === '?') {
re += '[^/]';
}
else {
re += c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
}
if (folderOnly) {
return new RegExp('^' + re + '(?:/.*)?$');
}
return new RegExp('^' + re + '$');
}
class RememberCursorPosition extends obsidian.Plugin {
constructor() {
super(...arguments);
this.lastRestoredLeafFile = '';
this.lastRestoredAt = 0;
// File each visible pane was last seen showing. Obsidian reports a focus
// change inside a pane that already shows a note as a `file-open` for that
// note, so this map tells a real open apart from a mere focus change.
this.shownFiles = new WeakMap();
this.loadingFile = false;
this.stateCheckTimer = 0;
this.unloaded = false;
this.lastKnownMarkdownFiles = new Set();
this.workspaceLoadUntil = 0;
this.pendingWorkspaceRestore = false;
this.startupPending = true;
this.layoutReadyTimer = 0;
this.excludedPatterns = [];
this.excludedPatternsCache = '';
}
onload() {
return __awaiter(this, void 0, void 0, function* () {
yield this.loadSettings();
try {
this.db = yield this.readDb();
this.lastSavedDb = yield this.readDb();
}
catch (e) {
console.error("Remember Cursor Position plugin can\'t read database: " + e);
this.db = {};
this.lastSavedDb = {};
}
this.addSettingTab(new SettingTab(this.app, this));
this.registerEvent(this.app.workspace.on('file-open', (file) => this.restoreEphemeralState(file)));
// Obsidian fires `file-open` from `activeLeafEvents()` whenever the
// active file changes, which includes moving the focus to a pane that
// already shows the note. Record what every visible pane shows before a
// click or a focus change, so that `restoreEphemeralState()` can tell the
// two cases apart.
const rememberBeforeFocusChange = () => {
this.flushStateCheck();
this.rememberShownFiles(null);
};
this.registerDomEvent(document, 'pointerdown', rememberBeforeFocusChange, { capture: true });
this.registerEvent(this.app.workspace.on('window-open', (win) => this.registerDomEvent(win.doc, 'pointerdown', rememberBeforeFocusChange, { capture: true })));
this.registerEvent(this.app.workspace.on('active-leaf-change', (leaf) => this.rememberShownFiles(leaf)));
this.registerEvent(this.app.workspace.on('layout-change', () => this.onLayoutChanged()));
this.registerEvent(this.app.workspace.on('quit', () => this.flushState()));
this.registerEvent(this.app.vault.on('rename', (file, oldPath) => this.renameFile(file, oldPath)));
this.registerEvent(this.app.vault.on('delete', (file) => this.deleteFile(file)));
// Track the position on scroll and selection events instead of polling.
// `scroll` does not bubble, so it is caught in the capture phase. Windows
// opened later (popouts) get the same listeners.
const scheduleStateCheck = () => this.scheduleStateCheck();
const trackWindow = (doc) => {
this.registerDomEvent(doc, 'scroll', scheduleStateCheck, { capture: true, passive: true });
this.registerDomEvent(doc, 'selectionchange', scheduleStateCheck);
};
trackWindow(document);
this.registerEvent(this.app.workspace.on('window-open', (win) => trackWindow(win.doc)));
// Mobile may suspend the app without firing `quit`.
this.registerDomEvent(document, 'visibilitychange', () => {
if (document.visibilityState === 'hidden')
this.flushState();
});
this.registerDomEvent(window, 'pagehide', () => this.flushState());
this.saveTimerIntervalId = this.registerInterval(window.setInterval(() => this.writeDb(this.db), this.settings.saveTimer));
this.app.workspace.onLayoutReady(() => {
this.layoutReadyTimer = window.setTimeout(() => __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c;
// Defer pruning until the vault/workspace is ready, so entries are
// not dropped because files have not been loaded yet.
this.pruneDb();
this.lastSavedDb = yield this.readDb();
const activeFile = this.app.workspace.getActiveFile();
const leaf = this.app.workspace.getMostRecentLeaf();
//@ts-ignore no-official-API
const leafId = leaf ? leaf.id : '';
//@ts-ignore no-official-API
const leafFile = leaf ? (_a = leaf.getViewState().state) === null || _a === void 0 ? void 0 : _a.file : '';
const guardKey = leafId + ':' + leafFile;
// Panes visible at startup count as already shown, except the
// active one, so the forced restore below still runs for it.
this.rememberShownFiles((_c = (_b = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView)) === null || _b === void 0 ? void 0 : _b.leaf) !== null && _c !== void 0 ? _c : null);
// Startup is no longer pending: allow restoration and tracking.
this.startupPending = false;
this.scheduleStateCheck();
if (activeFile && this.lastRestoredLeafFile !== guardKey) {
yield this.restoreEphemeralState();
}
}), LAYOUT_READY_RESTORE_DELAY);
});
});
}
onunload() {
this.unloaded = true;
window.clearTimeout(this.layoutChangeTimer);
window.clearTimeout(this.layoutReadyTimer);
window.clearTimeout(this.stateCheckTimer);
}
// Coalesces bursts of scroll and selection events into one check.
scheduleStateCheck() {
if (this.unloaded || this.stateCheckTimer)
return;
this.stateCheckTimer = window.setTimeout(() => {
this.stateCheckTimer = 0;
if (this.unloaded)
return;
// A hover preview suppresses tracking only while it is focused.
if (this.isHoverPopoverActive()) {
this.scheduleStateCheck();
return;
}
this.checkEphemeralStateChanged();
}, STATE_CHECK_THROTTLE_MS);
}
// Records a pending change now, before the active note can change.
flushStateCheck() {
// With a hover preview focused the check is suppressed, so keep it pending.
if (!this.stateCheckTimer || this.isHoverPopoverActive())
return;
window.clearTimeout(this.stateCheckTimer);
this.stateCheckTimer = 0;
this.checkEphemeralStateChanged();
}
flushState() {
this.flushStateCheck();
this.writeDb(this.db);
}
renameFile(file, oldPath) {
let newName = file.path;
let oldName = oldPath;
this.db[newName] = this.db[oldName];
delete this.db[oldName];
}
deleteFile(file) {
let fileName = file.path;
delete this.db[fileName];
}
compileExcludedPatterns() {
this.excludedPatterns = (this.settings.excludedFiles || [])
.map((pattern) => {
const trimmed = pattern.trim();
if (!trimmed)
return null;
try {
return globToRegex(trimmed);
}
catch (e) {
console.error("Remember Cursor Position plugin: invalid exclusion pattern \"" + trimmed + "\": " + e);
return null;
}
})
.filter((re) => re !== null);
}
isExcluded(filePath) {
if (!this.settings.excludedFiles || this.settings.excludedFiles.length === 0)
return false;
const cacheKey = JSON.stringify(this.settings.excludedFiles);
if (cacheKey !== this.excludedPatternsCache) {
this.compileExcludedPatterns();
this.excludedPatternsCache = cacheKey;
}
return this.excludedPatterns.some((re) => re.test(filePath));
}
hasSearchMatchInActiveLeaf() {
const view = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView);
if (!view)
return false;
const leaf = view.leaf;
if (!leaf)
return false;
const eState = leaf.getEphemeralState();
if (eState && eState['match'] != null)
return true;
const state = leaf.getViewState().state;
if (state && state['match'] != null)
return true;
return false;
}
// Obsidian's hover preview (Page preview) and the Hover Editor plugin both
// render a markdown view inside a popover carrying the `hover-popover` class;
// Hover Editor additionally adds the `hover-editor` class. Such windows are
// transient, so they must never jump to, or record, a saved position.
isHoverPopoverActive() {
var _a;
const container = (_a = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView)) === null || _a === void 0 ? void 0 : _a.containerEl;
if (!container)
return false;
return container.closest('.hover-popover') !== null || container.closest('.hover-editor') !== null;
}
// Records the file of every visible markdown pane, so that a pane which
// already shows a note can be told apart from a pane that is about to show
// it. Pass the leaf that is about to change when the caller cannot know yet
// which file it will display.
rememberShownFiles(except) {
this.app.workspace.iterateAllLeaves((leaf) => {
const view = leaf.view;
if (leaf !== except && view instanceof obsidian.MarkdownView && view.file && view.containerEl.offsetParent !== null)
this.shownFiles.set(leaf, view.file);
});
}
getOpenMarkdownFiles() {
const files = new Set();
this.app.workspace.iterateAllLeaves((leaf) => {
var _a;
if (leaf.getViewState().type === 'markdown') {
const file = (_a = leaf.getViewState().state) === null || _a === void 0 ? void 0 : _a.file;
if (file)
files.add(file);
}
});
return files;
}
onLayoutChanged() {
const current = this.getOpenMarkdownFiles();
const added = [...current].filter((f) => !this.lastKnownMarkdownFiles.has(f));
const removed = [...this.lastKnownMarkdownFiles].filter((f) => !current.has(f));
this.lastKnownMarkdownFiles = current;
// A workspace load swaps the whole layout at once: several files are opened
// and/or closed in a single change. A normal open/close touches one file.
// Set the window immediately so file-opens that follow the layout change are
// suppressed when the "restore on workspace load" option is disabled.
if (added.length >= 2 || removed.length >= 2) {
this.workspaceLoadUntil = Date.now() + WORKSPACE_LOAD_WINDOW_MS;
this.pendingWorkspaceRestore = true;
}
// When the option is enabled, wait for the layout to settle, then restore the
// active file once. This catches files that were opened by the workspace load
// but were not restored through the regular file-open path.
window.clearTimeout(this.layoutChangeTimer);
this.layoutChangeTimer = window.setTimeout(() => {
if (this.pendingWorkspaceRestore) {
this.pendingWorkspaceRestore = false;
if (this.settings.restorePositionOnWorkspaceLoad && this.app.workspace.getActiveFile()) {
this.restoreEphemeralState();
}
}
}, LAYOUT_CHANGE_DEBOUNCE_MS);
}
checkEphemeralStateChanged() {
var _a;
// Suppress position tracking until startup restoration has completed.
if (this.startupPending)
return;
// Never track positions while a hover preview window is focused.
if (this.isHoverPopoverActive())
return;
let fileName = (_a = this.app.workspace.getActiveFile()) === null || _a === void 0 ? void 0 : _a.path;
//waiting for load new file
if (!fileName || !this.lastLoadedFileName || fileName != this.lastLoadedFileName || this.loadingFile)
return;
let st = this.getEphemeralState();
let hadPriorState = this.lastEphemeralState && Object.keys(this.lastEphemeralState).length > 0;
if (!this.lastEphemeralState)
this.lastEphemeralState = st;
if (!isNaN(st.scroll) && (!hadPriorState || !this.isEphemeralStatesEquals(st, this.lastEphemeralState))) {
this.saveEphemeralState(st);
this.lastEphemeralState = st;
}
}
isEphemeralStatesEquals(state1, state2) {
if (state1.cursor && !state2.cursor)
return false;
if (!state1.cursor && state2.cursor)
return false;
if (state1.cursor) {
if (state1.cursor.from.ch != state2.cursor.from.ch)
return false;
if (state1.cursor.from.line != state2.cursor.from.line)
return false;
if (state1.cursor.to.ch != state2.cursor.to.ch)
return false;
if (state1.cursor.to.line != state2.cursor.to.line)
return false;
}
if (state1.scroll && !state2.scroll)
return false;
if (!state1.scroll && state2.scroll)
return false;
if (state1.scroll && state1.scroll != state2.scroll)
return false;
return true;
}
saveEphemeralState(st) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
// Guards against recording a position from a hover preview window.
if (this.isHoverPopoverActive())
return;
let fileName = (_a = this.app.workspace.getActiveFile()) === null || _a === void 0 ? void 0 : _a.path;
if (fileName && fileName == this.lastLoadedFileName) { //do not save if file changed or was not loaded
if (this.isExcluded(fileName))
return;
this.db[fileName] = Object.assign(Object.assign({}, st), { lastModified: Date.now() });
}
});
}
// A restore that is still waiting out its delay must not be applied once
// another note has become active: the saved position belongs to the first
// note, and applying it would move the cursor of the second one.
isStillActive(fileName) {
var _a;
return ((_a = this.app.workspace.getActiveFile()) === null || _a === void 0 ? void 0 : _a.path) === fileName && this.lastLoadedFileName == fileName;
}
// Checks that arrived while a note was loading were skipped, and polling
// retried them on the next tick, so record the settled state afterwards.
restoreEphemeralState(file) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield this.restoreEphemeralStateOnce(file);
}
finally {
this.scheduleStateCheck();
}
});
}
restoreEphemeralStateOnce(file) {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {
// Suppress early restoration until the workspace layout is ready.
if (this.startupPending)
return;
let fileName = (_a = this.app.workspace.getActiveFile()) === null || _a === void 0 ? void 0 : _a.path;
if (fileName && this.loadingFile && this.lastLoadedFileName == fileName) //if already started loading
return;
// Hover preview windows (Obsidian's Page preview and the Hover Editor
// plugin) must never restore a position. Forgetting the note's saved
// position also stops these windows from causing erratic cursor jumps.
if (this.isHoverPopoverActive()) {
if (fileName)
delete this.db[fileName];
return;
}
// Focusing a pane that already shows the note is reported as a `file-open`
// for the same file. Restoring there would overwrite the cursor and scroll
// position the user has just set, and a double click would turn the jump
// into a text selection. Start tracking the note instead and leave the
// saved position alone.
const activeView = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView);
if (fileName && (activeView === null || activeView === void 0 ? void 0 : activeView.file) && activeView.file.path === fileName) {
const alreadyShown = this.shownFiles.get(activeView.leaf) === activeView.file;
this.shownFiles.set(activeView.leaf, activeView.file);
if (alreadyShown && this.lastLoadedFileName != fileName) {
this.lastLoadedFileName = fileName;
this.lastEphemeralState = {};
return;
}
}
// When a workspace is loaded and the user disabled workspace restoration,
// skip restoring positions during the load window.
if (this.workspaceLoadUntil > Date.now() && !this.settings.restorePositionOnWorkspaceLoad)
return;
// Narrowed guard: skip only the same (leaf, file) combination restored very
// recently. The old guard skipped every currently open leaf, which blocked
// startup/workspace restoration (notes left open at quit were never restored).
let activeLeaf = this.app.workspace.getMostRecentLeaf();
//@ts-ignore no-official-API
const leafId = activeLeaf ? activeLeaf.id : '';
//@ts-ignore no-official-API
const leafFile = activeLeaf ? (_b = activeLeaf.getViewState().state) === null || _b === void 0 ? void 0 : _b.file : '';
const guardKey = leafId + ':' + leafFile;
if (fileName && this.lastRestoredLeafFile === guardKey && Date.now() - this.lastRestoredAt < RESTORE_GUARD_WINDOW_MS)
return;
this.loadingFile = true;
if (this.lastLoadedFileName != fileName) {
this.lastEphemeralState = {};
this.lastLoadedFileName = fileName;
let st = {};
if (fileName && !this.isExcluded(fileName)) {
st = this.db[fileName];
// When the note was opened from a search result, Obsidian already
// jumped to the first match. If the user enabled the option, keep that
// position instead of restoring the saved one.
const openedFromSearch = this.settings.skipRestoreFromSearch && this.hasSearchMatchInActiveLeaf();
if (st) {
//waiting for load note
yield this.delay(this.settings.delayAfterFileOpening);
// Don't scroll when a link scrolls and highlights text
// i.e. if file is open by links like [link](note.md#header) and wikilinks
// See #10, #32, #46, #51
let containsFlashingSpan = this.app.workspace.containerEl.querySelector('.is-flashing');
if (!containsFlashingSpan && !openedFromSearch) {
yield this.delay(10);
// The delay can outlive the note: if another file became
// active in the meantime, the saved position belongs to a
// note that is no longer shown.
if (!this.isStillActive(fileName)) {
this.loadingFile = false;
return;
}
this.setEphemeralState(st);
}
}
else if (this.settings.defaultPosition !== 'default') {
yield this.delay(this.settings.delayAfterFileOpening);
let containsFlashingSpan = this.app.workspace.containerEl.querySelector('.is-flashing');
if (!containsFlashingSpan && !openedFromSearch) {
yield this.delay(10);
if (!this.isStillActive(fileName)) {
this.loadingFile = false;
return;
}
if (this.settings.defaultPosition === 'beginning') {
yield this.setCursorToBeginning(file || this.app.workspace.getActiveFile());
}
else if (this.settings.defaultPosition === 'end') {
this.setCursorToEnd();
}
else if (this.settings.defaultPosition === 'beforeFootnotes') {
yield this.setCursorToBeforeFootnotes(file || this.app.workspace.getActiveFile());
}
}
}
// Only register the "already restored" state when the file name is
// non-empty, so the workspace-not-ready no-op call does not consume
// the dedup window and block the file-open that follows.
this.lastRestoredLeafFile = guardKey;
this.lastRestoredAt = Date.now();
}
this.lastEphemeralState = st;
}
this.loadingFile = false;
});
}
pruneDb() {
var _a;
const { pruneOrphans, maxAgeDays, maxCount } = this.settings;
if (pruneOrphans) {
for (const key of Object.keys(this.db)) {
if (!this.app.vault.getAbstractFileByPath(key)) {
delete this.db[key];
}
}
}
if (maxAgeDays > 0) {
const cutoff = Date.now() - maxAgeDays * 86400000;
for (const key of Object.keys(this.db)) {
if (((_a = this.db[key].lastModified) !== null && _a !== void 0 ? _a : 0) < cutoff) {
delete this.db[key];
}
}
}
if (maxCount > 0 && Object.keys(this.db).length > maxCount) {
const sorted = Object.entries(this.db)
.sort((a, b) => { var _a, _b; return ((_a = b[1].lastModified) !== null && _a !== void 0 ? _a : 0) - ((_b = a[1].lastModified) !== null && _b !== void 0 ? _b : 0); });
this.db = Object.fromEntries(sorted.slice(0, maxCount));
}
}
readDb() {
return __awaiter(this, void 0, void 0, function* () {
let db = {};
if (yield this.app.vault.adapter.exists(this.settings.dbFileName)) {
let data = yield this.app.vault.adapter.read(this.settings.dbFileName);
db = JSON.parse(data);
const now = Date.now();
for (const key of Object.keys(db)) {
if (db[key].lastModified === undefined) {
db[key].lastModified = now;
}
}
}
return db;
});
}
writeDb(db) {
return __awaiter(this, void 0, void 0, function* () {
//create folder for db file if not exist
let newParentFolder = this.settings.dbFileName.substring(0, this.settings.dbFileName.lastIndexOf("/"));
if (!(yield this.app.vault.adapter.exists(newParentFolder)))
this.app.vault.adapter.mkdir(newParentFolder);
if (JSON.stringify(this.db) !== JSON.stringify(this.lastSavedDb)) {
this.app.vault.adapter.write(this.settings.dbFileName, JSON.stringify(db));
this.lastSavedDb = JSON.parse(JSON.stringify(db));
}
});
}
getEphemeralState() {
// let state: EphemeralState = this.app.workspace.getActiveViewOfType(MarkdownView)?.getEphemeralState(); //doesn't work properly
var _a, _b, _c;
let state = {};
state.scroll = Number((_c = (_b = (_a = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView)) === null || _a === void 0 ? void 0 : _a.currentMode) === null || _b === void 0 ? void 0 : _b.getScroll()) === null || _c === void 0 ? void 0 : _c.toFixed(4));
let editor = this.getEditor();
if (editor) {
let from = editor.getCursor("anchor");
let to = editor.getCursor("head");
if (from && to) {
state.cursor = {
from: {
ch: from.ch,
line: from.line
},
to: {
ch: to.ch,
line: to.line
}
};
}
}
return state;
}
setEphemeralState(state) {
const view = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView);
if (state.cursor) {
let editor = this.getEditor();
if (editor) {
editor.setSelection(state.cursor.from, state.cursor.to);
}
}
if (view && state.scroll) {
view.setEphemeralState(state);
// view.previewMode.applyScroll(state.scroll);
// view.sourceMode.applyScroll(state.scroll);
}
// Anchor the cursor line into view after the scroll is applied. This guards
// against drift when dynamic content (e.g. Dataview tables) renders after the
// restore and changes the document height.
if (state.cursor) {
let editor = this.getEditor();
if (editor) {
editor.scrollIntoView({ from: state.cursor.from, to: state.cursor.to }, true);
}
}
}
setCursorToBeginning(file) {
return __awaiter(this, void 0, void 0, function* () {
let content = yield this.app.vault.read(file);
let lines = content.split('\n');
let startLine = 0;
if (lines.length > 0 && lines[0].trim() === '---') {
for (let i = 1; i < lines.length; i++) {
if (lines[i].trim() === '---') {
startLine = i + 1;
break;
}
}
}
let editor = this.getEditor();
if (editor) {
if (startLine >= editor.lineCount()) {
startLine = Math.max(0, editor.lineCount() - 1);
}
editor.setCursor({ line: startLine, ch: 0 });
editor.scrollIntoView({ from: { line: startLine, ch: 0 }, to: { line: startLine, ch: 0 } }, true);
}
});
}
setCursorToEnd() {
let editor = this.getEditor();
if (editor) {
let lastLine = editor.lastLine();
let lastLineLength = editor.getLine(lastLine).length;
editor.setCursor({ line: lastLine, ch: lastLineLength });
editor.scrollIntoView({ from: { line: lastLine, ch: 0 }, to: { line: lastLine, ch: lastLineLength } }, true);
}
}
setCursorToBeforeFootnotes(file) {
return __awaiter(this, void 0, void 0, function* () {
let content = yield this.app.vault.read(file);
let lines = content.split('\n');
let footnoteLine = -1;
for (let i = 0; i < lines.length; i++) {
if (/^\s*\[\^[^\]]+\]:\s/.test(lines[i])) {
footnoteLine = i;
break;
}
}
if (footnoteLine === -1) {
this.setCursorToEnd();
return;
}
let targetLine = footnoteLine - 1;
while (targetLine >= 0 && lines[targetLine].trim() === '') {
targetLine--;
}
if (targetLine < 0) {
targetLine = 0;
}
let editor = this.getEditor();
if (editor) {
if (targetLine >= editor.lineCount()) {
targetLine = Math.max(0, editor.lineCount() - 1);
}
let ch = editor.getLine(targetLine).length;
editor.setCursor({ line: targetLine, ch: ch });
editor.scrollIntoView({ from: { line: targetLine, ch: 0 }, to: { line: targetLine, ch: ch } }, true);
}
});
}
getEditor() {
var _a;
return (_a = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView)) === null || _a === void 0 ? void 0 : _a.editor;
}
loadSettings() {
return __awaiter(this, void 0, void 0, function* () {
let settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData());
if ((settings === null || settings === void 0 ? void 0 : settings.saveTimer) < SAFE_DB_FLUSH_INTERVAL) {
settings.saveTimer = SAFE_DB_FLUSH_INTERVAL;
}
if (!settings.dbFileName || settings.dbFileName === DEFAULT_DB_FILENAME_LEGACY) {
settings.dbFileName = this.manifest.dir + '/cursor-positions.json';
}
this.settings = settings;
this.compileExcludedPatterns();
});
}
saveSettings() {
return __awaiter(this, void 0, void 0, function* () {
yield this.saveData(this.settings);
this.compileExcludedPatterns();
});
}
delay(ms) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => setTimeout(resolve, ms));
});
}
}
class PathSuggest extends obsidian.AbstractInputSuggest {
constructor(app, inputEl) {
super(app, inputEl);
this.limit = 50;
}
getSuggestions(query) {
const q = query.trim().toLowerCase();
if (!q)
return [];
const out = [];
for (const file of this.app.vault.getAllLoadedFiles()) {
const path = file instanceof obsidian.TFolder ? `${file.path}/` : file.path;
if (path.toLowerCase().includes(q))
out.push(path);
}
return out.slice(0, this.limit || 50);
}
renderSuggestion(value, el) {
el.setText(value);
}
}
class AddExclusionModal extends obsidian.Modal {
constructor(app, onAdd) {
super(app);
this.onAdd = onAdd;
this.inputEl = null;
this.suggest = null;
this.errorTimer = 0;
this.errorInput = null;
this.errorTooltip = null;
this.errorScrollContainer = null;
this.onErrorScroll = () => {
const input = this.errorInput;
const container = this.errorScrollContainer;
if (!input || !container)
return;
const rect = input.getBoundingClientRect();
const cRect = container.getBoundingClientRect();
const visible = rect.bottom >= cRect.top &&
rect.top <= cRect.bottom &&
rect.right >= cRect.left &&
rect.left <= cRect.right;
if (!visible)
this.clearError();
};
}
onOpen() {
const { contentEl } = this;
contentEl.createEl('h3', { text: 'Add exclusion' });
contentEl.createEl('p', {
cls: 'rcp-modal-desc',
text: 'Select a file or folder from the vault, or type a path or glob pattern. Patterns ending with "/" match a folder and everything inside it.',
});
const inputWrap = contentEl.createDiv({ cls: 'rcp-modal-input-wrap' });
const input = new obsidian.TextComponent(inputWrap);
input.setPlaceholder('e.g. dashboards/ or **/templates/*.md');
input.inputEl.addClass('rcp-modal-input');
this.inputEl = input.inputEl;
this.suggest = new PathSuggest(this.app, input.inputEl);
this.suggest.onSelect((value) => {
input.setValue(value);
input.inputEl.focus();
});
input.inputEl.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
this.submit();
}
});
const buttons = contentEl.createDiv({ cls: 'modal-button-container' });
new obsidian.ButtonComponent(buttons)
.setButtonText('Cancel')
.onClick(() => this.close());
new obsidian.ButtonComponent(buttons)
.setButtonText('Add')
.setCta()
.onClick(() => this.submit());
}
onClose() {
var _a;
this.clearError();
(_a = this.suggest) === null || _a === void 0 ? void 0 : _a.close();
this.contentEl.empty();
}
submit() {
const input = this.inputEl;
if (!input)
return;
const value = input.value.trim();
if (!value) {
this.showRequiredError(input, 'Path is required.');
return;
}
this.onAdd(value);
this.close();
}
getScrollContainer(el) {
let node = el;
while (node) {
const overflowY = window.getComputedStyle(node).overflowY;
if (overflowY === 'auto' || overflowY === 'scroll')
return node;
node = node.parentElement;
}
return null;
}
showRequiredError(input, message) {
var _a;
this.clearError();
const parent = input.parentElement;
if (!parent)
return;
parent.addClass('rcp-validation-relative');
input.addClass('rcp-input-error');
const tooltip = parent.createDiv({ cls: 'rcp-validation-tooltip' });
tooltip.setText(message);
const container = this.getScrollContainer(input);
if (container) {
this.errorScrollContainer = container;
container.addEventListener('scroll', this.onErrorScroll);
const cRect = container.getBoundingClientRect();
const tRect = tooltip.getBoundingClientRect();
let left = input.offsetLeft;
let top = ((_a = parent.clientHeight) !== null && _a !== void 0 ? _a : 0) + 4;
if (tRect.left < cRect.left)
left += cRect.left - tRect.left;
if (tRect.right > cRect.right)
left -= tRect.right - cRect.right;
if (tRect.bottom > cRect.bottom)
top -= tRect.bottom - cRect.bottom;
tooltip.setCssProps({
'--rcp-vt-left': `${left}px`,
'--rcp-vt-top': `${top}px`,
});
}
this.errorInput = input;
this.errorTooltip = tooltip;
this.errorTimer = window.setTimeout(() => this.clearError(), 3000);
input.addEventListener('input', () => this.clearError(), { once: true });
input.addEventListener('blur', () => this.clearError(), { once: true });
}
clearError() {
window.clearTimeout(this.errorTimer);
if (this.errorInput) {
this.errorInput.removeClass('rcp-input-error');
this.errorInput = null;
}
if (this.errorTooltip && this.errorTooltip.parentElement) {
this.errorTooltip.parentElement.removeChild(this.errorTooltip);
}
this.errorTooltip = null;
if (this.errorScrollContainer) {
this.errorScrollContainer.removeEventListener('scroll', this.onErrorScroll);
this.errorScrollContainer = null;
}
}
}
class SettingTab extends obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
getScrollContainer() {
let node = this.containerEl;
while (node) {
const overflowY = window.getComputedStyle(node).overflowY;
if (overflowY === 'auto' || overflowY === 'scroll') {
return node;
}
node = node.parentElement;
}
return null;
}
display() {
let { containerEl } = this;
// Preserve the scroll position across re-renders so that updates to
// settings (e.g. adding/removing exclusions) don't reset the viewport.
const scrollContainer = this.getScrollContainer();
const scrollTop = scrollContainer ? scrollContainer.scrollTop : 0;
containerEl.empty();
new obsidian.SettingGroup(containerEl)
.addSetting((setting) => setting
.setName('Default cursor position')
.setDesc('When no saved position exists for a file, jump to this position. "Default" means do nothing.')
.addDropdown((drop) => drop
.addOption('beginning', 'Beginning')
.addOption('end', 'End')
.addOption('beforeFootnotes', 'Before footnotes')
.addOption('default', 'Default (do nothing)')
.setValue(this.plugin.settings.defaultPosition)
.onChange((value) => __awaiter(this, void 0, void 0, function* () {
this.plugin.settings.defaultPosition = value;
yield this.plugin.saveSettings();
}))))
.addSetting((setting) => setting
.setName('Skip restoring position when opening from a search result')
.setDesc('When enabled, opening a note from a search result jumps to the match instead of the saved cursor position. ' +
'When disabled, the saved position is restored as usual.')
.addToggle((toggle) => toggle
.setValue(this.plugin.settings.skipRestoreFromSearch)
.onChange((value) => __awaiter(this, void 0, void 0, function* () {
this.plugin.settings.skipRestoreFromSearch = value;
yield this.plugin.saveSettings();
}))))
.addSetting((setting) => setting
.setName('Restore position when loading a workspace')
.setDesc('When enabled, notes opened by loading a workspace (Workspaces core plugin) restore their saved position, ' +
'or the configured default position when no position is saved. When disabled, they open at the top.')
.addToggle((toggle) => toggle
.setValue(this.plugin.settings.restorePositionOnWorkspaceLoad)
.onChange((value) => __awaiter(this, void 0, void 0, function* () {
this.plugin.settings.restorePositionOnWorkspaceLoad = value;
yield this.plugin.saveSettings();
}))))
.addSetting((setting) => setting
.setName('Data file name')
.setDesc('Save positions to this file')
.addText((text) => text
.setPlaceholder('Example: cursor-positions.json')
.setValue(this.plugin.settings.dbFileName)
.onChange((value) => __awaiter(this, void 0, void 0, function* () {
this.plugin.settings.dbFileName = value;
yield this.plugin.saveSettings();
}))))
.addSetting((setting) => setting
.setName('Delay after opening a new note')
.setDesc("This plugin shouldn't scroll if you used a link to the note header like [link](note.md#header). If it did, then increase the delay until everything works. If you are not using links to page sections, set the delay to zero (slider to the left). Slider values: 0-300 ms (default value: 100 ms).")
.addSlider((text) => text
.setLimits(0, 300, 10)
.setDynamicTooltip()
.setValue(this.plugin.settings.delayAfterFileOpening)
.onChange((value) => __awaiter(this, void 0, void 0, function* () {
this.plugin.settings.delayAfterFileOpening = value;
yield this.plugin.saveSettings();
}))))
.addSetting((setting) => setting
.setName('Delay between saving the cursor position to file')
.setDesc("Useful for multi-device users. If you don't want to wait until closing Obsidian to the cursor position been saved.")
.addSlider((text) => text
.setLimits(SAFE_DB_FLUSH_INTERVAL, SAFE_DB_FLUSH_INTERVAL * 10, 10)
.setDynamicTooltip()
.setValue(this.plugin.settings.saveTimer)
.onChange((value) => __awaiter(this, void 0, void 0, function* () {
this.plugin.settings.saveTimer = value;
yield this.plugin.saveSettings();
window.clearInterval(this.plugin.saveTimerIntervalId);
this.plugin.saveTimerIntervalId = this.plugin.registerInterval(window.setInterval(() => this.plugin.writeDb(this.plugin.db), value));
}))));
const exclusionsGroup = new obsidian.SettingGroup(containerEl)
.setHeading('Exclusions')
.addClass('rcp-exclusion-group');
exclusionsGroup.addSetting((setting) => {
setting.settingEl.addClass('rcp-exclusion-setting');
setting
.setName('Excluded files and folders')
.setDesc('Files and folders matching these paths or glob patterns are never saved or restored. ' +
'Patterns ending with "/" match a folder and everything inside it. ' +
'Examples: "dashboard.md", "dashboards/", "**/templates/*.md".')
.addButton((btn) => btn
.setButtonText('Add exclusion')
.setCta()
.onClick(() => {
new AddExclusionModal(this.app, (pattern) => {
this.plugin.settings.excludedFiles.push(pattern);
this.plugin.saveSettings().then(() => this.display());
}).open();
}));
const excludedFiles = this.plugin.settings.excludedFiles || [];
const tagsContainer = setting.settingEl.createDiv({ cls: 'rcp-exclusion-tags' });
if (excludedFiles.length === 0) {
tagsContainer.createSpan({ cls: 'rcp-exclusion-empty', text: 'No excluded files or folders.' });
}
else {
excludedFiles.forEach((pattern, index) => {
const tag = tagsContainer.createSpan({ cls: 'rcp-exclusion-tag' });
tag.createSpan({ cls: 'rcp-exclusion-tag-text', text: pattern });
const removeBtn = tag.createEl('button', {
cls: 'rcp-exclusion-tag-remove',
text: '×',
attr: { type: 'button', 'aria-label': 'Remove exclusion' },
});
removeBtn.addEventListener('click', () => {
this.plugin.settings.excludedFiles.splice(index, 1);
this.plugin.saveSettings().then(() => this.display());
});
});
}
});
const { pruneOrphans, maxAgeDays, maxCount } = this.plugin.settings;
const pruningEnabled = pruneOrphans || maxAgeDays > 0 || maxCount > 0;
const entryCount = Object.keys(this.plugin.db).length;
new obsidian.SettingGroup(containerEl)
.setHeading('Data Management')
.addSetting((setting) => setting
.setName('Remove entries for deleted or missing files')
.setDesc('On startup, remove saved positions for files that no longer exist in the vault. ' +
'Disable this if you use junctions, removable drives, or other setups where files may be temporarily unavailable.')
.addToggle((toggle) => toggle
.setValue(this.plugin.settings.pruneOrphans)
.onChange((value) => __awaiter(this, void 0, void 0, function* () {
this.plugin.settings.pruneOrphans = value;
yield this.plugin.saveSettings();
this.display();
}))))
.addSetting((setting) => setting
.setName('Remove entries older than')
.setDesc('On startup, remove saved positions for files that have not been visited within the selected period.')
.addDropdown((drop) => drop
.addOption('30', '30 days')
.addOption('60', '60 days')
.addOption('90', '90 days')
.addOption('365', '1 year')
.addOption('0', 'Never')
.setValue(String(this.plugin.settings.maxAgeDays))
.onChange((value) => __awaiter(this, void 0, void 0, function* () {
this.plugin.settings.maxAgeDays = Number(value);
yield this.plugin.saveSettings();
this.display();
}))))
.addSetting((setting) => setting
.setName('Maximum number of entries to keep')
.setDesc('On startup, if the number of saved positions exceeds this limit, the oldest entries are removed. Most-recently visited files are kept. "None" means no maximum limit.')
.addDropdown((drop) => drop
.addOption('50', '50')
.addOption('100', '100')
.addOption('250', '250')
.addOption('500', '500')
.addOption('0', 'None')
.setValue(String(this.plugin.settings.maxCount))
.onChange((value) => __awaiter(this, void 0, void 0, function* () {
this.plugin.settings.maxCount = Number(value);
yield this.plugin.saveSettings();
this.display();
}))))
.addSetting((setting) => setting
.setName('Apply pruning rules')
.setDesc(`Currently tracking ${entryCount} ${entryCount === 1 ? 'entry' : 'entries'}. Pruning runs automatically on next reload; use this to apply immediately.`)
.addButton((btn) => {
btn.setButtonText('Prune now')
.setDisabled(!pruningEnabled);
if (pruningEnabled)
btn.setCta();
btn.onClick(() => __awaiter(this, void 0, void 0, function* () {
this.plugin.pruneDb();
yield this.plugin.writeDb(this.plugin.db);
this.display();
}));
}))
.addSetting((setting) => setting
.setName('Forget all saved positions')
.setDesc('Remove every saved cursor position from the database. This cannot be undone.')
.addButton((btn) => {
btn.setButtonText('Forget all')
.setWarning();
btn.onClick(() => __awaiter(this, void 0, void 0, function* () {
const count = Object.keys(this.plugin.db).length;
this.plugin.db = {};
// Force writeDb to persist the empty database even though
// both snapshots are now empty.
this.plugin.lastSavedDb = { __forceWrite: true };
yield this.plugin.writeDb(this.plugin.db);
new obsidian.Notice(`Remember cursor position: forgot ${count} saved ${count === 1 ? 'position' : 'positions'}.`);
this.display();
}));
}));
if (scrollContainer) {
scrollContainer.scrollTop = scrollTop;
}
}
}
module.exports = RememberCursorPosition;
/* nosourcemap */