.
This commit is contained in:
parent
0c42c23669
commit
352c71af65
185 changed files with 20165 additions and 0 deletions
8
frontend/obsidian-plugin/.claude/settings.local.json
Normal file
8
frontend/obsidian-plugin/.claude/settings.local.json
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(npm run test:*)"
|
||||
],
|
||||
"deny": []
|
||||
}
|
||||
}
|
||||
0
frontend/obsidian-plugin/.hotreload
Normal file
0
frontend/obsidian-plugin/.hotreload
Normal file
92
frontend/obsidian-plugin/README.md
Normal file
92
frontend/obsidian-plugin/README.md
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
# Obsidian Sample Plugin
|
||||
|
||||
This is a sample plugin for Obsidian (https://obsidian.md).
|
||||
|
||||
This project uses TypeScript to provide type checking and documentation.
|
||||
The repo depends on the latest plugin API (obsidian.d.ts) in TypeScript Definition format, which contains TSDoc comments describing what it does.
|
||||
|
||||
**Note:** The Obsidian API is still in early alpha and is subject to change at any time!
|
||||
|
||||
This sample plugin demonstrates some of the basic functionality the plugin API can do.
|
||||
- Adds a ribbon icon, which shows a Notice when clicked.
|
||||
- Adds a command "Open Sample Modal" which opens a Modal.
|
||||
- Adds a plugin setting tab to the settings page.
|
||||
- Registers a global click event and output 'click' to the console.
|
||||
- Registers a global interval which logs 'setInterval' to the console.
|
||||
|
||||
## First time developing plugins?
|
||||
|
||||
Quick starting guide for new plugin devs:
|
||||
|
||||
- Check if [someone already developed a plugin for what you want](https://obsidian.md/plugins)! There might be an existing plugin similar enough that you can partner up with.
|
||||
- Make a copy of this repo as a template with the "Use this template" button (login to GitHub if you don't see it).
|
||||
- Clone your repo to a local development folder. For convenience, you can place this folder in your `.obsidian/plugins/your-plugin-name` folder.
|
||||
- Install NodeJS, then run `npm i` in the command line under your repo folder.
|
||||
- Run `npm run dev` to compile your plugin from `main.ts` to `main.js`.
|
||||
- Make changes to `main.ts` (or create new `.ts` files). Those changes should be automatically compiled into `main.js`.
|
||||
- Reload Obsidian to load the new version of your plugin.
|
||||
- Enable plugin in settings window.
|
||||
- For updates to the Obsidian API run `npm update` in the command line under your repo folder.
|
||||
|
||||
## Releasing new releases
|
||||
|
||||
- Update your `manifest.json` with your new version number, such as `1.0.1`, and the minimum Obsidian version required for your latest release.
|
||||
- Update your `versions.json` file with `"new-plugin-version": "minimum-obsidian-version"` so older versions of Obsidian can download an older version of your plugin that's compatible.
|
||||
- Create new GitHub release using your new version number as the "Tag version". Use the exact version number, don't include a prefix `v`. See here for an example: https://github.com/obsidianmd/obsidian-sample-plugin/releases
|
||||
- Upload the files `manifest.json`, `main.js`, `styles.css` as binary attachments. Note: The manifest.json file must be in two places, first the root path of your repository and also in the release.
|
||||
- Publish the release.
|
||||
|
||||
> You can simplify the version bump process by running `npm version patch`, `npm version minor` or `npm version major` after updating `minAppVersion` manually in `manifest.json`.
|
||||
> The command will bump version in `manifest.json` and `package.json`, and add the entry for the new version to `versions.json`
|
||||
|
||||
## Adding your plugin to the community plugin list
|
||||
|
||||
- Check the [plugin guidelines](https://docs.obsidian.md/Plugins/Releasing/Plugin+guidelines).
|
||||
- Publish an initial version.
|
||||
- Make sure you have a `README.md` file in the root of your repo.
|
||||
- Make a pull request at https://github.com/obsidianmd/obsidian-releases to add your plugin.
|
||||
|
||||
## How to use
|
||||
|
||||
- Clone this repo.
|
||||
- Make sure your NodeJS is at least v16 (`node --version`).
|
||||
- `npm i` or `yarn` to install dependencies.
|
||||
- `npm run dev` to start compilation in watch mode.
|
||||
|
||||
## Manually installing the plugin
|
||||
|
||||
- Copy over `main.js`, `styles.css`, `manifest.json` to your vault `VaultFolder/.obsidian/plugins/your-plugin-id/`.
|
||||
|
||||
|
||||
## Funding URL
|
||||
|
||||
You can include funding URLs where people who use your plugin can financially support it.
|
||||
|
||||
The simple way is to set the `fundingUrl` field to your link in your `manifest.json` file:
|
||||
|
||||
```json
|
||||
{
|
||||
"fundingUrl": "https://buymeacoffee.com"
|
||||
}
|
||||
```
|
||||
|
||||
If you have multiple URLs, you can also do:
|
||||
|
||||
```json
|
||||
{
|
||||
"fundingUrl": {
|
||||
"Buy Me a Coffee": "https://buymeacoffee.com",
|
||||
"GitHub Sponsor": "https://github.com/sponsors",
|
||||
"Patreon": "https://www.patreon.com/"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## API Documentation
|
||||
|
||||
See https://github.com/obsidianmd/obsidian-api
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
10
frontend/obsidian-plugin/manifest.json
Normal file
10
frontend/obsidian-plugin/manifest.json
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"id": "vault-link",
|
||||
"name": "VaultLink",
|
||||
"version": "0.8.0",
|
||||
"minAppVersion": "0.0.0",
|
||||
"description": "Self-hosted synchronization and collaboration for your Vault.",
|
||||
"author": "Andras Schmelczer",
|
||||
"authorUrl": "https://schmelczer.dev",
|
||||
"isDesktopOnly": false
|
||||
}
|
||||
40
frontend/obsidian-plugin/package.json
Normal file
40
frontend/obsidian-plugin/package.json
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
{
|
||||
"name": "vault-link-obsidian-plugin",
|
||||
"version": "0.8.0",
|
||||
"description": "This is a sample plugin for Obsidian (https://obsidian.md)",
|
||||
"main": "main.js",
|
||||
"scripts": {
|
||||
"dev": "webpack watch --mode development",
|
||||
"build": "webpack --mode production",
|
||||
"test": "echo \"no tests defined\" && exit 0",
|
||||
"version": "node version-bump.mjs"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@plausible-analytics/tracker": "^0.4.0",
|
||||
"@sentry/browser": "^10.8.0",
|
||||
"@types/node": "^22.15.30",
|
||||
"css-loader": "^7.1.2",
|
||||
"date-fns": "^4.1.0",
|
||||
"file-loader": "^6.2.0",
|
||||
"fs-extra": "^11.3.0",
|
||||
"mini-css-extract-plugin": "^2.9.2",
|
||||
"obsidian": "1.8.7",
|
||||
"reconcile-text": "^0.5.0",
|
||||
"resolve-url-loader": "^5.0.0",
|
||||
"sass": "^1.91.0",
|
||||
"sass-loader": "^16.0.5",
|
||||
"sync-client": "file:../sync-client",
|
||||
"terser-webpack-plugin": "^5.3.14",
|
||||
"ts-loader": "^9.5.2",
|
||||
"tslib": "2.8.1",
|
||||
"tsx": "^4.20.5",
|
||||
"typescript": "5.8.3",
|
||||
"url": "^0.11.4",
|
||||
"virtual-scroller": "^1.13.1",
|
||||
"webpack": "^5.99.9",
|
||||
"webpack-cli": "^6.0.1"
|
||||
}
|
||||
}
|
||||
174
frontend/obsidian-plugin/src/obsidian-file-system.ts
Normal file
174
frontend/obsidian-plugin/src/obsidian-file-system.ts
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
import type { Stat, Vault, Workspace } from "obsidian";
|
||||
import { MarkdownView, normalizePath } from "obsidian";
|
||||
import {
|
||||
utils,
|
||||
type FileSystemOperations,
|
||||
type RelativePath
|
||||
} from "sync-client";
|
||||
import { getSelectionsFromEditor } from "./views/cursors/get-selections-from-editor";
|
||||
import type { TextWithCursors, CursorPosition } from "reconcile-text";
|
||||
|
||||
export class ObsidianFileSystemOperations implements FileSystemOperations {
|
||||
public constructor(
|
||||
private readonly vault: Vault,
|
||||
private readonly workspace: Workspace
|
||||
) {}
|
||||
|
||||
public async listAllFiles(): Promise<RelativePath[]> {
|
||||
// Let's implement this by hand because vault.adapter.listAllFiles doesn't always return all files.
|
||||
const allFiles = [];
|
||||
const remainingFolders = [this.vault.getRoot().path];
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
while (true) {
|
||||
const folder = remainingFolders.pop();
|
||||
if (folder == undefined) {
|
||||
break;
|
||||
}
|
||||
|
||||
// This would be a very bad idea to sync as it would mess with
|
||||
// the integrity of the sync database.
|
||||
if (folder.endsWith(".obsidian/plugins/vault-link/data.json")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const files = await this.vault.adapter.list(normalizePath(folder));
|
||||
allFiles.push(...files.files);
|
||||
remainingFolders.push(...files.folders);
|
||||
}
|
||||
|
||||
return allFiles;
|
||||
}
|
||||
|
||||
public async read(path: RelativePath): Promise<Uint8Array> {
|
||||
path = normalizePath(path);
|
||||
const view = this.workspace.getActiveViewOfType(MarkdownView);
|
||||
if (view?.file?.path === path) {
|
||||
return new TextEncoder().encode(view.editor.getValue());
|
||||
}
|
||||
|
||||
return new Uint8Array(await this.vault.adapter.readBinary(path));
|
||||
}
|
||||
|
||||
public async write(path: RelativePath, content: Uint8Array): Promise<void> {
|
||||
path = normalizePath(path);
|
||||
|
||||
const view = this.workspace.getActiveViewOfType(MarkdownView);
|
||||
if (view?.file?.path === path) {
|
||||
const position = view.editor.getCursor();
|
||||
view.editor.setValue(new TextDecoder().decode(content));
|
||||
view.editor.setCursor(position);
|
||||
return;
|
||||
}
|
||||
|
||||
return this.vault.adapter.writeBinary(
|
||||
path,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
|
||||
content.buffer as ArrayBuffer
|
||||
);
|
||||
}
|
||||
|
||||
public async atomicUpdateText(
|
||||
path: RelativePath,
|
||||
updater: (current: TextWithCursors) => TextWithCursors
|
||||
): Promise<string> {
|
||||
path = normalizePath(path);
|
||||
|
||||
const view = this.workspace.getActiveViewOfType(MarkdownView);
|
||||
|
||||
if (view?.file?.path === path) {
|
||||
const text = view.editor.getValue();
|
||||
|
||||
const cursors: CursorPosition[] = getSelectionsFromEditor(
|
||||
view.editor
|
||||
).flatMap(({ id, start: anchor, end: head }) => [
|
||||
{
|
||||
id: 2 * id,
|
||||
position: anchor
|
||||
},
|
||||
{
|
||||
id: 2 * id + 1,
|
||||
position: head
|
||||
}
|
||||
]);
|
||||
|
||||
const result = updater({
|
||||
text,
|
||||
cursors
|
||||
});
|
||||
|
||||
if (result.text === text) {
|
||||
return text;
|
||||
}
|
||||
|
||||
view.editor.setValue(result.text);
|
||||
|
||||
const selections = [];
|
||||
for (let i = 0; i < result.cursors.length / 2; i++) {
|
||||
const from = result.cursors[2 * i];
|
||||
const to = result.cursors[2 * i + 1];
|
||||
const { line: fromLine, column: fromColumn } =
|
||||
utils.positionToLineAndColumn(result.text, from.position);
|
||||
|
||||
const { line: toLine, column: toColumn } =
|
||||
utils.positionToLineAndColumn(result.text, to.position);
|
||||
|
||||
selections.push({
|
||||
anchor: { line: fromLine, ch: fromColumn },
|
||||
head: { line: toLine, ch: toColumn }
|
||||
});
|
||||
}
|
||||
view.editor.setSelections(selections);
|
||||
|
||||
return result.text;
|
||||
}
|
||||
|
||||
return this.vault.adapter.process(
|
||||
path,
|
||||
(text) =>
|
||||
updater({
|
||||
text,
|
||||
cursors: []
|
||||
}).text
|
||||
);
|
||||
}
|
||||
|
||||
public async getFileSize(path: RelativePath): Promise<number> {
|
||||
return (await this.statFile(path)).size;
|
||||
}
|
||||
|
||||
public async getModificationTime(path: RelativePath): Promise<Date> {
|
||||
return new Date((await this.statFile(path)).mtime);
|
||||
}
|
||||
|
||||
public async exists(path: RelativePath): Promise<boolean> {
|
||||
return this.vault.adapter.exists(normalizePath(path));
|
||||
}
|
||||
|
||||
public async createDirectory(path: RelativePath): Promise<void> {
|
||||
return this.vault.adapter.mkdir(normalizePath(path));
|
||||
}
|
||||
|
||||
public async delete(path: RelativePath): Promise<void> {
|
||||
if (!(await this.vault.adapter.trashSystem(normalizePath(path)))) {
|
||||
return this.vault.adapter.remove(normalizePath(path));
|
||||
}
|
||||
}
|
||||
|
||||
public async rename(
|
||||
oldPath: RelativePath,
|
||||
newPath: RelativePath
|
||||
): Promise<void> {
|
||||
return this.vault.adapter.rename(oldPath, newPath);
|
||||
}
|
||||
|
||||
private async statFile(path: string): Promise<Stat> {
|
||||
const file = await this.vault.adapter.stat(normalizePath(path));
|
||||
|
||||
if (!file) {
|
||||
throw new Error(`File not found: ${path}`);
|
||||
}
|
||||
|
||||
return file;
|
||||
}
|
||||
}
|
||||
287
frontend/obsidian-plugin/src/vault-link-plugin.ts
Normal file
287
frontend/obsidian-plugin/src/vault-link-plugin.ts
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
import type {
|
||||
MarkdownView,
|
||||
Editor,
|
||||
MarkdownFileInfo,
|
||||
TAbstractFile,
|
||||
WorkspaceLeaf
|
||||
} from "obsidian";
|
||||
import { Platform, Plugin, TFile } from "obsidian";
|
||||
import "../manifest.json";
|
||||
import { HistoryView } from "./views/history/history-view";
|
||||
import { StatusBar } from "./views/status-bar/status-bar";
|
||||
import { LogsView } from "./views/logs/logs-view";
|
||||
import { StatusDescription } from "./views/status-description/status-description";
|
||||
import * as Sentry from "@sentry/browser";
|
||||
import { init as plausibleInit } from "@plausible-analytics/tracker";
|
||||
import {
|
||||
SyncClient,
|
||||
rateLimit,
|
||||
DEFAULT_SETTINGS,
|
||||
Logger,
|
||||
debugging
|
||||
} from "sync-client";
|
||||
import { ObsidianFileSystemOperations } from "./obsidian-file-system";
|
||||
import { SyncSettingsTab } from "./views/settings/settings-tab";
|
||||
import { EditorStatusDisplayManager } from "./views/editor-status-display-manager/editor-status-display-manager";
|
||||
import { remoteCursorsTheme } from "./views/cursors/remote-cursor-theme";
|
||||
import {
|
||||
remoteCursorsPlugin,
|
||||
RemoteCursorsPluginValue
|
||||
} from "./views/cursors/remote-cursors-plugin";
|
||||
import { LocalCursorUpdateListener } from "./views/cursors/local-cursor-update-listener";
|
||||
import { renderCursorsInFileExplorer } from "./views/cursors/file-explorer";
|
||||
|
||||
const MIN_WAIT_BETWEEN_UPDATES_IN_MS = 250;
|
||||
|
||||
export default class VaultLinkPlugin extends Plugin {
|
||||
private readonly disposables: (() => unknown)[] = [];
|
||||
|
||||
private settingsTab: SyncSettingsTab | undefined;
|
||||
private client!: SyncClient;
|
||||
private readonly rateLimitedUpdatesPerFile = new Map<
|
||||
string,
|
||||
() => Promise<unknown>
|
||||
>();
|
||||
|
||||
public async onload(): Promise<void> {
|
||||
DEFAULT_SETTINGS.ignorePatterns.push(
|
||||
".obsidian/**",
|
||||
".git/**",
|
||||
".trash/**"
|
||||
);
|
||||
|
||||
const isDebugBuild = process.env.NODE_ENV === "development";
|
||||
|
||||
if (!isDebugBuild) {
|
||||
plausibleInit({
|
||||
domain: "vault-link",
|
||||
endpoint: "https://stats.schmelczer.dev/status",
|
||||
autoCapturePageviews: true,
|
||||
captureOnLocalhost: true,
|
||||
logging: true
|
||||
});
|
||||
|
||||
Sentry.init({
|
||||
dsn: "https://56accd39d92442e788a457a04623cf57@bugs.schmelczer.dev/1",
|
||||
skipBrowserExtensionCheck: false
|
||||
});
|
||||
|
||||
const onError = (event: ErrorEvent): void => {
|
||||
Sentry.captureException(event.error, {
|
||||
extra: {
|
||||
message: event.message,
|
||||
filename: event.filename,
|
||||
lineno: event.lineno,
|
||||
colno: event.colno
|
||||
}
|
||||
});
|
||||
};
|
||||
window.addEventListener("error", onError);
|
||||
this.disposables.push(() => {
|
||||
window.removeEventListener("error", onError);
|
||||
});
|
||||
|
||||
const onUnhandledRejection = (
|
||||
event: PromiseRejectionEvent
|
||||
): void => {
|
||||
Sentry.captureException(event.reason);
|
||||
};
|
||||
window.addEventListener("unhandledrejection", onUnhandledRejection);
|
||||
this.disposables.push(() => {
|
||||
window.removeEventListener(
|
||||
"unhandledrejection",
|
||||
onUnhandledRejection
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const debugOptions = isDebugBuild
|
||||
? {
|
||||
fetch: debugging.slowFetchFactory(1),
|
||||
webSocket: debugging.slowWebSocketFactory(1, new Logger())
|
||||
}
|
||||
: {};
|
||||
|
||||
this.client = await SyncClient.create({
|
||||
fs: new ObsidianFileSystemOperations(
|
||||
this.app.vault,
|
||||
this.app.workspace
|
||||
),
|
||||
persistence: {
|
||||
load: this.loadData.bind(this),
|
||||
save: this.saveData.bind(this)
|
||||
},
|
||||
nativeLineEndings: Platform.isWin ? "\r\n" : "\n",
|
||||
...debugOptions
|
||||
});
|
||||
|
||||
if (isDebugBuild) {
|
||||
debugging.logToConsole(this.client);
|
||||
}
|
||||
|
||||
const statusDescription = new StatusDescription(this.client);
|
||||
|
||||
this.settingsTab = new SyncSettingsTab({
|
||||
app: this.app,
|
||||
plugin: this,
|
||||
syncClient: this.client,
|
||||
statusDescription
|
||||
});
|
||||
this.addSettingTab(this.settingsTab);
|
||||
|
||||
new StatusBar(this, this.client);
|
||||
|
||||
this.registerView(
|
||||
HistoryView.TYPE,
|
||||
(leaf) => new HistoryView(this.client, leaf)
|
||||
);
|
||||
|
||||
this.registerView(
|
||||
LogsView.TYPE,
|
||||
(leaf) => new LogsView(this.client, leaf)
|
||||
);
|
||||
|
||||
this.registerEditorExtension([remoteCursorsTheme, remoteCursorsPlugin]);
|
||||
|
||||
this.client.addRemoteCursorsUpdateListener((cursors) => {
|
||||
RemoteCursorsPluginValue.setCursors(cursors, this.app);
|
||||
renderCursorsInFileExplorer(cursors, this.app);
|
||||
});
|
||||
|
||||
const cursorListener = new LocalCursorUpdateListener(
|
||||
this.client,
|
||||
this.app.workspace
|
||||
);
|
||||
this.disposables.push(() => {
|
||||
cursorListener.dispose();
|
||||
});
|
||||
|
||||
this.app.workspace.updateOptions();
|
||||
|
||||
this.addRibbonIcon(
|
||||
HistoryView.ICON,
|
||||
"Open VaultLink events",
|
||||
async (_: MouseEvent) => this.activateView(HistoryView.TYPE)
|
||||
);
|
||||
|
||||
this.addRibbonIcon(
|
||||
LogsView.ICON,
|
||||
"Open VaultLink logs",
|
||||
async (_: MouseEvent) => this.activateView(LogsView.TYPE)
|
||||
);
|
||||
|
||||
this.app.workspace.onLayoutReady(async () => {
|
||||
this.registerEditorEvents();
|
||||
await this.client.start();
|
||||
|
||||
const editorStatusDisplayManager = new EditorStatusDisplayManager(
|
||||
this,
|
||||
this.app.workspace,
|
||||
this.client
|
||||
);
|
||||
this.disposables.push(() => {
|
||||
editorStatusDisplayManager.stop();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public onunload(): void {
|
||||
this.client.waitAndStop().catch((err: unknown) => {
|
||||
this.client.logger.error(
|
||||
`Error while stopping the sync client: ${err}`
|
||||
);
|
||||
});
|
||||
this.disposables.forEach((disposable) => {
|
||||
disposable();
|
||||
});
|
||||
}
|
||||
|
||||
public openSettings(): void {
|
||||
// eslint-disable-next-line
|
||||
(this.app as any).setting.open(); // this is undocumented
|
||||
// eslint-disable-next-line
|
||||
(this.app as any).setting.openTab(this.settingsTab); // this is undocumented
|
||||
}
|
||||
|
||||
public closeSettings(): void {
|
||||
// eslint-disable-next-line
|
||||
(this.app as any).setting.close(); // this is undocumented
|
||||
}
|
||||
|
||||
public async activateView(type: string): Promise<void> {
|
||||
const { workspace } = this.app;
|
||||
|
||||
let leaf: WorkspaceLeaf | null = null;
|
||||
const leaves = workspace.getLeavesOfType(type);
|
||||
|
||||
if (leaves.length > 0) {
|
||||
[leaf] = leaves;
|
||||
} else {
|
||||
leaf = workspace.getRightLeaf(false);
|
||||
await leaf?.setViewState({ type: type, active: true });
|
||||
}
|
||||
|
||||
if (leaf) {
|
||||
await workspace.revealLeaf(leaf);
|
||||
}
|
||||
}
|
||||
|
||||
private registerEditorEvents(): void {
|
||||
[
|
||||
this.app.workspace.on(
|
||||
"editor-change",
|
||||
async (
|
||||
_editor: Editor,
|
||||
info: MarkdownView | MarkdownFileInfo
|
||||
) => {
|
||||
const { file } = info;
|
||||
if (file) {
|
||||
await this.rateLimitedUpdate(file.path);
|
||||
}
|
||||
}
|
||||
),
|
||||
this.app.vault.on("create", async (file: TAbstractFile) => {
|
||||
if (file instanceof TFile) {
|
||||
await this.client.syncLocallyCreatedFile(file.path);
|
||||
}
|
||||
}),
|
||||
this.app.vault.on("modify", async (file: TAbstractFile) => {
|
||||
if (file instanceof TFile) {
|
||||
await this.rateLimitedUpdate(file.path);
|
||||
}
|
||||
}),
|
||||
this.app.vault.on("delete", async (file: TAbstractFile) => {
|
||||
await this.client.syncLocallyDeletedFile(file.path);
|
||||
}),
|
||||
this.app.vault.on(
|
||||
"rename",
|
||||
async (file: TAbstractFile, oldPath: string) => {
|
||||
if (file instanceof TFile) {
|
||||
await this.client.syncLocallyUpdatedFile({
|
||||
oldPath,
|
||||
relativePath: file.path
|
||||
});
|
||||
}
|
||||
}
|
||||
)
|
||||
].forEach((event) => {
|
||||
this.registerEvent(event);
|
||||
});
|
||||
}
|
||||
|
||||
private async rateLimitedUpdate(path: string): Promise<void> {
|
||||
if (!this.rateLimitedUpdatesPerFile.has(path)) {
|
||||
this.rateLimitedUpdatesPerFile.set(
|
||||
path,
|
||||
rateLimit(
|
||||
async () =>
|
||||
this.client.syncLocallyUpdatedFile({
|
||||
relativePath: path
|
||||
}),
|
||||
MIN_WAIT_BETWEEN_UPDATES_IN_MS
|
||||
)
|
||||
);
|
||||
}
|
||||
await this.rateLimitedUpdatesPerFile.get(path)?.();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
.remote-users {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--size-4-2);
|
||||
margin-left: var(--size-4-2);
|
||||
|
||||
span {
|
||||
border-radius: var(--radius-l);
|
||||
padding: 0 var(--size-4-1);
|
||||
border-width: 1.4px;
|
||||
border-style: solid;
|
||||
font-size: var(--font-smallest);
|
||||
font-style: italic;
|
||||
}
|
||||
}
|
||||
55
frontend/obsidian-plugin/src/views/cursors/file-explorer.ts
Normal file
55
frontend/obsidian-plugin/src/views/cursors/file-explorer.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import "./file-explorer.scss";
|
||||
|
||||
import type { App, View } from "obsidian";
|
||||
import {
|
||||
utils,
|
||||
type MaybeOutdatedClientCursors,
|
||||
type RelativePath
|
||||
} from "sync-client";
|
||||
|
||||
const REMOTE_USER_CONTAINER_CLASS = "remote-users";
|
||||
|
||||
export function renderCursorsInFileExplorer(
|
||||
cursors: MaybeOutdatedClientCursors[],
|
||||
app: App
|
||||
): void {
|
||||
const fileExplorers = app.workspace.getLeavesOfType("file-explorer");
|
||||
if (fileExplorers.length == 0) return;
|
||||
|
||||
const [fileExplorer] = fileExplorers;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const fileExplorerView: View & {
|
||||
fileItems: Record<RelativePath, { el: Element }>; // it's an internal API
|
||||
} = fileExplorer.view as any; // eslint-disable-line
|
||||
|
||||
for (const key in fileExplorerView.fileItems) {
|
||||
const element =
|
||||
fileExplorerView.fileItems[key].el.querySelector(".tree-item-self");
|
||||
|
||||
const customElement = createDiv(
|
||||
{
|
||||
cls: REMOTE_USER_CONTAINER_CLASS
|
||||
},
|
||||
(parent) => {
|
||||
cursors.forEach((cursor) => {
|
||||
cursor.documentsWithCursors.forEach((document) => {
|
||||
if (document.relative_path === key) {
|
||||
parent.appendChild(
|
||||
createSpan({
|
||||
text: cursor.userName,
|
||||
attr: {
|
||||
style: `border-color: ${utils.getRandomColor(cursor.userName)}`
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
element?.querySelector("." + REMOTE_USER_CONTAINER_CLASS)?.remove();
|
||||
element?.appendChild(customElement);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
import type { Editor } from "obsidian";
|
||||
import { utils } from "sync-client";
|
||||
|
||||
export interface Selection {
|
||||
id: number;
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
export function getSelectionsFromEditor(editor: Editor): Selection[] {
|
||||
const text = editor.getValue();
|
||||
return editor.listSelections().map(({ anchor, head }, i) => ({
|
||||
id: i,
|
||||
start: utils.lineAndColumnToPosition(text, anchor.line, anchor.ch),
|
||||
end: utils.lineAndColumnToPosition(text, head.line, head.ch)
|
||||
}));
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
import type { Workspace } from "obsidian";
|
||||
import { MarkdownView } from "obsidian";
|
||||
import type { SyncClient } from "sync-client";
|
||||
import type { Selection } from "./get-selections-from-editor";
|
||||
import { getSelectionsFromEditor } from "./get-selections-from-editor";
|
||||
|
||||
export class LocalCursorUpdateListener {
|
||||
private static readonly UPDATE_INTERVAL_MS = 50;
|
||||
private readonly eventHandle: NodeJS.Timeout;
|
||||
|
||||
public constructor(
|
||||
private readonly client: SyncClient,
|
||||
private readonly workspace: Workspace
|
||||
) {
|
||||
this.eventHandle = setInterval(() => {
|
||||
this.updateAllSelections();
|
||||
}, LocalCursorUpdateListener.UPDATE_INTERVAL_MS);
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
clearInterval(this.eventHandle);
|
||||
}
|
||||
|
||||
private updateAllSelections(): void {
|
||||
const currentCursors = this.getAllSelections();
|
||||
this.client
|
||||
.updateLocalCursors(currentCursors)
|
||||
.catch((error: unknown) => {
|
||||
this.client.logger.error(
|
||||
`Failed to update local cursors: ${error}`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private getAllSelections(): Record<string, Selection[]> {
|
||||
const cursors: Record<string, Selection[]> = {};
|
||||
this.workspace
|
||||
.getLeavesOfType("markdown")
|
||||
.map((leaf) => leaf.view)
|
||||
.filter((view) => view instanceof MarkdownView)
|
||||
.forEach((view) => {
|
||||
const { file } = view;
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
cursors[file.path] = getSelectionsFromEditor(view.editor);
|
||||
});
|
||||
return cursors;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
import { EditorView } from "@codemirror/view";
|
||||
|
||||
const CARET_WIDTH = 2;
|
||||
const DOT_RADIUS = 4;
|
||||
|
||||
export const remoteCursorsTheme = EditorView.baseTheme({
|
||||
".selection-caret": {
|
||||
position: "relative"
|
||||
},
|
||||
|
||||
".selection-caret > *": {
|
||||
position: "absolute",
|
||||
backgroundColor: "inherit"
|
||||
},
|
||||
|
||||
".selection-caret > .stick": {
|
||||
left: 0,
|
||||
top: 0,
|
||||
transform: "translateX(-50%)",
|
||||
width: `${CARET_WIDTH}px`,
|
||||
height: "100%",
|
||||
display: "block",
|
||||
borderRadius: `${CARET_WIDTH / 2}px`,
|
||||
animation: "blink-stick 1s steps(1) infinite"
|
||||
},
|
||||
|
||||
"@keyframes blink-stick": {
|
||||
"0%, 100%": { opacity: 1 },
|
||||
"50%": { opacity: 0 }
|
||||
},
|
||||
|
||||
".selection-caret > .dot": {
|
||||
borderRadius: "50%",
|
||||
width: `${DOT_RADIUS * 2}px`,
|
||||
height: `${DOT_RADIUS * 2}px`,
|
||||
top: `-${DOT_RADIUS}px`,
|
||||
left: `-${DOT_RADIUS}px`,
|
||||
transition: "transform .3s ease-in-out",
|
||||
transformOrigin: "bottom center",
|
||||
boxSizing: "border-box"
|
||||
},
|
||||
|
||||
".selection-caret:hover > .dot": {
|
||||
transform: "scale(0)"
|
||||
},
|
||||
|
||||
".selection-caret > .info": {
|
||||
top: "-1.3em",
|
||||
left: `-${CARET_WIDTH / 2}px`,
|
||||
fontSize: "0.9em",
|
||||
userSelect: "none",
|
||||
color: "white",
|
||||
padding: "0 2px",
|
||||
transition: "opacity .3s ease-in-out",
|
||||
opacity: 0,
|
||||
whiteSpace: "nowrap",
|
||||
borderRadius: "3px 3px 3px 0"
|
||||
},
|
||||
|
||||
".selection-caret:hover > .info": {
|
||||
opacity: 1
|
||||
}
|
||||
});
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
import { AnnotationType, Annotation, RangeSet, Range } from "@codemirror/state";
|
||||
import {
|
||||
ViewUpdate,
|
||||
ViewPlugin,
|
||||
Decoration,
|
||||
WidgetType
|
||||
} from "@codemirror/view";
|
||||
|
||||
import type { PluginValue, DecorationSet, EditorView } from "@codemirror/view";
|
||||
|
||||
export class RemoteCursorWidget extends WidgetType {
|
||||
public constructor(
|
||||
private readonly color: string,
|
||||
private readonly name: string
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
public toDOM(editor: EditorView): HTMLElement {
|
||||
return editor.contentDOM.createEl(
|
||||
"span",
|
||||
{
|
||||
cls: "selection-caret",
|
||||
attr: {
|
||||
style: `background-color: ${this.color}; border-color: ${this.color}`
|
||||
}
|
||||
},
|
||||
(span) => {
|
||||
span.createEl("div", {
|
||||
cls: "stick"
|
||||
});
|
||||
span.createEl("div", {
|
||||
cls: "dot"
|
||||
});
|
||||
span.createEl("div", {
|
||||
cls: "info",
|
||||
text: this.name
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public eq(other: RemoteCursorWidget): boolean {
|
||||
return other.color === this.color && other.name === this.name;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,236 @@
|
|||
import type { Range } from "@codemirror/state";
|
||||
import { RangeSet } from "@codemirror/state";
|
||||
import { ViewPlugin, Decoration } from "@codemirror/view";
|
||||
|
||||
import type {
|
||||
PluginValue,
|
||||
DecorationSet,
|
||||
EditorView,
|
||||
ViewUpdate
|
||||
} from "@codemirror/view";
|
||||
import { RemoteCursorWidget } from "./remote-cursor-widget";
|
||||
import {
|
||||
utils,
|
||||
type CursorSpan,
|
||||
type MaybeOutdatedClientCursors
|
||||
} from "sync-client";
|
||||
import type { App } from "obsidian";
|
||||
import { MarkdownView } from "obsidian";
|
||||
|
||||
import { StateEffect } from "@codemirror/state";
|
||||
import type { SpanWithHistory } from "reconcile-text";
|
||||
import { reconcileWithHistory } from "reconcile-text";
|
||||
|
||||
const forceUpdate = StateEffect.define();
|
||||
|
||||
export class RemoteCursorsPluginValue implements PluginValue {
|
||||
private static cursors: {
|
||||
name: string;
|
||||
path: string;
|
||||
span: CursorSpan;
|
||||
deviceId: string;
|
||||
isOutdated: boolean;
|
||||
}[] = [];
|
||||
|
||||
public decorations: DecorationSet = RangeSet.of([]);
|
||||
|
||||
public static setCursors(
|
||||
clients: MaybeOutdatedClientCursors[],
|
||||
app: App
|
||||
): void {
|
||||
RemoteCursorsPluginValue.cursors = [
|
||||
...RemoteCursorsPluginValue.cursors.filter(({ deviceId }) =>
|
||||
clients.some(
|
||||
(client) =>
|
||||
client.deviceId === deviceId && client.isOutdated
|
||||
)
|
||||
),
|
||||
...clients
|
||||
.filter(
|
||||
({ isOutdated, deviceId }) =>
|
||||
!isOutdated ||
|
||||
RemoteCursorsPluginValue.cursors.every(
|
||||
(c) => deviceId !== c.deviceId
|
||||
)
|
||||
)
|
||||
.flatMap((client) => {
|
||||
const clientCursors = client.documentsWithCursors;
|
||||
return clientCursors.flatMap((cursor) =>
|
||||
cursor.cursors.map((span) => ({
|
||||
name: client.userName,
|
||||
path: cursor.relative_path,
|
||||
deviceId: client.deviceId,
|
||||
isOutdated: client.isOutdated,
|
||||
span: { ...span }
|
||||
}))
|
||||
);
|
||||
})
|
||||
];
|
||||
|
||||
app.workspace
|
||||
.getLeavesOfType("markdown")
|
||||
.map((leaf) => leaf.view)
|
||||
.filter((view) => view instanceof MarkdownView)
|
||||
.forEach((view) => {
|
||||
// @ts-expect-error, not typed
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
|
||||
const editor = view.editor.cm as EditorView;
|
||||
|
||||
editor.dispatch({
|
||||
effects: [forceUpdate.of(null)]
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private static interpolateRemoteCursorPositions(
|
||||
original: string,
|
||||
edited: string
|
||||
): void {
|
||||
if (
|
||||
original === edited ||
|
||||
RemoteCursorsPluginValue.cursors.length === 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedPositions: number[] = [];
|
||||
const reconciled = reconcileWithHistory(
|
||||
original,
|
||||
{
|
||||
text: original,
|
||||
cursors: RemoteCursorsPluginValue.cursors.flatMap(
|
||||
({ span }, i) => [
|
||||
{ id: i * 2, position: span.start },
|
||||
{ id: i * 2 + 1, position: span.end }
|
||||
]
|
||||
)
|
||||
},
|
||||
edited
|
||||
);
|
||||
|
||||
reconciled.cursors.forEach(({ id, position }) => {
|
||||
const whereToJump = RemoteCursorsPluginValue.findWhereToMoveCursor(
|
||||
position,
|
||||
reconciled.history
|
||||
);
|
||||
if (whereToJump !== null) {
|
||||
updatedPositions[id] = whereToJump;
|
||||
} else {
|
||||
updatedPositions[id] = position;
|
||||
}
|
||||
});
|
||||
|
||||
RemoteCursorsPluginValue.cursors.forEach(({ span }, i) => {
|
||||
span.start = updatedPositions[i * 2];
|
||||
span.end = updatedPositions[i * 2 + 1];
|
||||
});
|
||||
}
|
||||
|
||||
private static findWhereToMoveCursor(
|
||||
cursor: number,
|
||||
spans: SpanWithHistory[]
|
||||
): number | null {
|
||||
let position = 0;
|
||||
for (const span of spans) {
|
||||
// left and origin are the same
|
||||
if (position === cursor && span.history === "AddedFromRight") {
|
||||
return position + span.text.length;
|
||||
}
|
||||
position += span.text.length;
|
||||
if (position === cursor && span.history === "RemovedFromRight") {
|
||||
return position - span.text.length;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public update(update: ViewUpdate): void {
|
||||
const original = update.startState.doc.toString();
|
||||
const edited = update.state.doc.toString();
|
||||
|
||||
RemoteCursorsPluginValue.interpolateRemoteCursorPositions(
|
||||
original,
|
||||
edited
|
||||
);
|
||||
|
||||
const decorations: Range<Decoration>[] = [];
|
||||
|
||||
RemoteCursorsPluginValue.cursors.forEach(
|
||||
({ name, span: { start, end } }) => {
|
||||
const color = utils.getRandomColor(name);
|
||||
const startLine = update.view.state.doc.lineAt(start);
|
||||
const endLine = update.view.state.doc.lineAt(end);
|
||||
|
||||
const attributes = {
|
||||
style: `background-color: ${color};`
|
||||
};
|
||||
|
||||
if (startLine.number === endLine.number) {
|
||||
// selected content in a single line.
|
||||
decorations.push({
|
||||
from: start,
|
||||
to: end,
|
||||
value: Decoration.mark({
|
||||
attributes
|
||||
})
|
||||
});
|
||||
} else {
|
||||
// selected content in multiple lines
|
||||
// first, render text-selection in the first line
|
||||
decorations.push({
|
||||
from: start,
|
||||
to: startLine.from + startLine.length,
|
||||
value: Decoration.mark({
|
||||
attributes
|
||||
})
|
||||
});
|
||||
|
||||
// render text-selection in the lines between the first and last line
|
||||
for (
|
||||
let i = startLine.number + 1;
|
||||
i < endLine.number;
|
||||
i++
|
||||
) {
|
||||
const currentLine = update.view.state.doc.line(i);
|
||||
decorations.push({
|
||||
from: currentLine.from,
|
||||
to: currentLine.to,
|
||||
value: Decoration.mark({
|
||||
attributes
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// render text-selection in the last line
|
||||
decorations.push({
|
||||
from: endLine.from,
|
||||
to: end,
|
||||
value: Decoration.mark({
|
||||
attributes
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
decorations.push({
|
||||
from: end,
|
||||
to: end,
|
||||
value: Decoration.widget({
|
||||
side: end - start > 0 ? -1 : 1, // the local cursor should be rendered outside the remote selection
|
||||
block: false,
|
||||
widget: new RemoteCursorWidget(color, name)
|
||||
})
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
this.decorations = Decoration.set(decorations, true);
|
||||
}
|
||||
}
|
||||
|
||||
export const remoteCursorsPlugin = ViewPlugin.fromClass(
|
||||
RemoteCursorsPluginValue,
|
||||
{
|
||||
decorations: (v) => v.decorations
|
||||
}
|
||||
);
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
.vault-link-sync-status {
|
||||
position: absolute;
|
||||
right: var(--size-4-4);
|
||||
top: var(--size-4-2);
|
||||
opacity: 0.7;
|
||||
cursor: pointer;
|
||||
|
||||
> span {
|
||||
opacity: 0;
|
||||
position: absolute;
|
||||
min-width: 200px;
|
||||
text-align: right;
|
||||
padding-right: var(--size-2-2);
|
||||
|
||||
top: 50%;
|
||||
left: 0;
|
||||
transform: translateY(-50%) translateX(-100%) translateY(-2px);
|
||||
transition: opacity 200ms;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
> span {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
> .icon {
|
||||
line-height: 0;
|
||||
}
|
||||
|
||||
&.loading > .icon {
|
||||
animation: spin 2s linear infinite;
|
||||
|
||||
@keyframes spin {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
import type { Workspace } from "obsidian";
|
||||
import { FileView, setIcon } from "obsidian";
|
||||
import type { SyncClient } from "sync-client";
|
||||
import { DocumentSyncStatus } from "sync-client";
|
||||
import "./editor-status-display-manager.scss";
|
||||
import type VaultLinkPlugin from "src/vault-link-plugin";
|
||||
import { HistoryView } from "../history/history-view";
|
||||
|
||||
export class EditorStatusDisplayManager {
|
||||
private static readonly UPDATE_INTERVAL_IN_MS = 100;
|
||||
|
||||
private readonly intervalId: NodeJS.Timeout;
|
||||
private readonly lastStatuses = new Map<string, DocumentSyncStatus>();
|
||||
|
||||
public constructor(
|
||||
private readonly plugin: VaultLinkPlugin,
|
||||
private readonly workspace: Workspace,
|
||||
private readonly client: SyncClient
|
||||
) {
|
||||
this.intervalId = setInterval(() => {
|
||||
this.updateEditorStatusDisplay();
|
||||
}, EditorStatusDisplayManager.UPDATE_INTERVAL_IN_MS);
|
||||
}
|
||||
|
||||
public stop(): void {
|
||||
clearInterval(this.intervalId);
|
||||
}
|
||||
|
||||
private updateEditorStatusDisplay(): void {
|
||||
this.workspace.iterateAllLeaves((leaf) => {
|
||||
if (leaf.view instanceof FileView) {
|
||||
const filePath = leaf.view.file?.path;
|
||||
if (filePath == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const element = this.getElementFromLeaf(leaf.view);
|
||||
if (element == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const previousStatus = this.lastStatuses.get(filePath);
|
||||
const currentStatus =
|
||||
this.client.getDocumentSyncingStatus(filePath);
|
||||
if (previousStatus === currentStatus) {
|
||||
return;
|
||||
}
|
||||
this.lastStatuses.set(filePath, currentStatus);
|
||||
|
||||
if (currentStatus == DocumentSyncStatus.SYNCING_IS_DISABLED) {
|
||||
element.remove();
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentStatus == DocumentSyncStatus.SYNCING) {
|
||||
element.classList.add("loading");
|
||||
} else {
|
||||
element.classList.remove("loading");
|
||||
}
|
||||
|
||||
const iconContainer = element.querySelector(".icon");
|
||||
if (iconContainer != null) {
|
||||
setIcon(
|
||||
iconContainer as HTMLElement, // eslint-disable-line @typescript-eslint/no-unsafe-type-assertion
|
||||
currentStatus == DocumentSyncStatus.SYNCING
|
||||
? "loader"
|
||||
: "circle-check"
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getElementFromLeaf(fileView: FileView): Element | undefined {
|
||||
const parent = fileView.contentEl.querySelector(".cm-editor");
|
||||
if (parent == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
parent.querySelector(".vault-link-sync-status") ??
|
||||
parent.createDiv(
|
||||
{
|
||||
cls: "vault-link-sync-status"
|
||||
},
|
||||
(el) => {
|
||||
el.createSpan({ text: "VaultLink sync state" });
|
||||
el.createDiv({
|
||||
cls: "icon"
|
||||
});
|
||||
el.onclick = async (): Promise<void> =>
|
||||
this.plugin.activateView(HistoryView.TYPE);
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
61
frontend/obsidian-plugin/src/views/history/history-view.scss
Normal file
61
frontend/obsidian-plugin/src/views/history/history-view.scss
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
.history-card {
|
||||
padding: var(--size-4-4);
|
||||
margin: var(--size-4-2);
|
||||
background-color: var(--color-base-00);
|
||||
border-radius: var(--radius-l);
|
||||
container-type: inline-size;
|
||||
|
||||
&.clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
&.success {
|
||||
background-color: rgba(var(--color-green-rgb), 0.2);
|
||||
}
|
||||
|
||||
&.error {
|
||||
background-color: rgba(var(--color-red-rgb), 0.2);
|
||||
}
|
||||
|
||||
&.skipped {
|
||||
background-color: rgba(var(--color-green-rgb), 0.08);
|
||||
}
|
||||
|
||||
.history-card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: var(--size-4-2);
|
||||
gap: var(--size-4-2);
|
||||
|
||||
@container (max-width: 300px) {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.history-card-title {
|
||||
font: var(--font-monospace);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--size-4-2);
|
||||
word-break: break-all;
|
||||
margin: 0;
|
||||
|
||||
> span {
|
||||
margin-bottom: var(--size-4-1);
|
||||
}
|
||||
}
|
||||
|
||||
.history-card-timestamp {
|
||||
font-size: var(--font-ui-small);
|
||||
font-style: italic;
|
||||
color: var(--italic-color);
|
||||
}
|
||||
}
|
||||
|
||||
.history-card-message {
|
||||
font-size: var(--font-ui-medium);
|
||||
color: var(--color-base-70);
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
234
frontend/obsidian-plugin/src/views/history/history-view.ts
Normal file
234
frontend/obsidian-plugin/src/views/history/history-view.ts
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
import "./history-view.scss";
|
||||
|
||||
import type { IconName, WorkspaceLeaf } from "obsidian";
|
||||
import { ItemView, setIcon } from "obsidian";
|
||||
import { intlFormatDistance } from "date-fns";
|
||||
import type { HistoryEntry, SyncClient } from "sync-client";
|
||||
import { SyncType } from "sync-client";
|
||||
|
||||
export class HistoryView extends ItemView {
|
||||
public static readonly TYPE = "history-view";
|
||||
public static readonly ICON = "square-stack";
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
|
||||
private historyContainer: HTMLElement | undefined;
|
||||
private readonly historyEntryToElement = new Map<
|
||||
HistoryEntry,
|
||||
HTMLElement
|
||||
>();
|
||||
|
||||
public constructor(
|
||||
private readonly client: SyncClient,
|
||||
leaf: WorkspaceLeaf
|
||||
) {
|
||||
super(leaf);
|
||||
this.icon = HistoryView.ICON;
|
||||
|
||||
this.client.addSyncHistoryUpdateListener(async () =>
|
||||
this.updateView().catch((error: unknown) => {
|
||||
this.client.logger.error(
|
||||
`Failed to update history view: ${error}`
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private static getSyncTypeIcon(type: SyncType | undefined): IconName {
|
||||
switch (type) {
|
||||
case SyncType.CREATE:
|
||||
return "file-plus";
|
||||
case SyncType.DELETE:
|
||||
return "trash-2";
|
||||
case SyncType.UPDATE:
|
||||
return "file-pen-line";
|
||||
case SyncType.MOVE:
|
||||
return "move-right";
|
||||
case SyncType.SKIPPED:
|
||||
return "circle-slash";
|
||||
case undefined:
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static renderSyncItemTitle(
|
||||
element: HTMLElement,
|
||||
entry: HistoryEntry
|
||||
): void {
|
||||
const syncTypeIcon = HistoryView.getSyncTypeIcon(entry.details.type);
|
||||
if (syncTypeIcon) {
|
||||
setIcon(element.createDiv(), syncTypeIcon);
|
||||
}
|
||||
|
||||
let fileName = entry.details.relativePath.split("/").pop() ?? "";
|
||||
fileName = fileName.replace(/\.md$/, "");
|
||||
|
||||
element.createEl("span", {
|
||||
text:
|
||||
entry.details.type === SyncType.SKIPPED
|
||||
? `Skipped: ${fileName}`
|
||||
: fileName
|
||||
});
|
||||
}
|
||||
|
||||
private static updateTimeSince(
|
||||
element: HTMLElement,
|
||||
entry: HistoryEntry
|
||||
): void {
|
||||
const timestampElement = element.querySelector(
|
||||
".history-card-timestamp"
|
||||
);
|
||||
|
||||
if (timestampElement != null) {
|
||||
timestampElement.textContent =
|
||||
HistoryView.getTimestampAndAuthor(entry);
|
||||
}
|
||||
}
|
||||
|
||||
private static getTimestampAndAuthor(entry: HistoryEntry): string {
|
||||
let content = intlFormatDistance(entry.timestamp, new Date());
|
||||
if ("author" in entry && entry.author !== undefined) {
|
||||
content += ` by ${entry.author}`;
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
public getViewType(): string {
|
||||
return HistoryView.TYPE;
|
||||
}
|
||||
|
||||
public getDisplayText(): string {
|
||||
return "VaultLink history";
|
||||
}
|
||||
|
||||
public async onOpen(): Promise<void> {
|
||||
const container = this.containerEl.children[1];
|
||||
container.createEl("h4", { text: "VaultLink history" });
|
||||
|
||||
this.historyContainer = container.createDiv({ cls: "logs-container" });
|
||||
|
||||
await this.updateView();
|
||||
this.timer = setInterval(
|
||||
() =>
|
||||
void this.updateView().catch((error: unknown) => {
|
||||
this.client.logger.error(
|
||||
`Failed to update history view: ${error}`
|
||||
);
|
||||
}),
|
||||
1000
|
||||
);
|
||||
}
|
||||
|
||||
public async onClose(): Promise<void> {
|
||||
if (this.timer) {
|
||||
clearInterval(this.timer);
|
||||
}
|
||||
}
|
||||
|
||||
private async updateView(): Promise<void> {
|
||||
const container = this.historyContainer;
|
||||
if (container === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
// entries are newest first, but we prepend new ones
|
||||
const entries = this.client.getHistoryEntries().toReversed();
|
||||
|
||||
if (this.historyEntryToElement.size === 0 && entries.length > 0) {
|
||||
// Clear the "No update has happened yet" message
|
||||
container.empty();
|
||||
}
|
||||
|
||||
entries.forEach((entry) => {
|
||||
const element = this.historyEntryToElement.get(entry);
|
||||
if (element !== undefined) {
|
||||
HistoryView.updateTimeSince(element, entry);
|
||||
return;
|
||||
}
|
||||
|
||||
const newElement = this.createHistoryCard(container, entry);
|
||||
container.prepend(newElement);
|
||||
this.historyEntryToElement.set(entry, newElement);
|
||||
});
|
||||
|
||||
const newEntries = new Set(entries);
|
||||
for (const [entry, element] of this.historyEntryToElement) {
|
||||
if (!newEntries.has(entry)) {
|
||||
element.remove();
|
||||
this.historyEntryToElement.delete(entry);
|
||||
}
|
||||
}
|
||||
|
||||
if (entries.length === 0) {
|
||||
container.empty();
|
||||
container.createEl("p", {
|
||||
text: "No update has happened yet."
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private createHistoryCard(
|
||||
container: HTMLElement,
|
||||
entry: HistoryEntry
|
||||
): HTMLElement {
|
||||
return container.createDiv(
|
||||
{
|
||||
cls: ["history-card", entry.status.toLocaleLowerCase()]
|
||||
},
|
||||
(card) => {
|
||||
if (
|
||||
this.app.vault.getFileByPath(entry.details.relativePath) !=
|
||||
null
|
||||
) {
|
||||
card.addEventListener("click", () => {
|
||||
this.app.workspace
|
||||
.openLinkText(
|
||||
entry.details.relativePath,
|
||||
entry.details.relativePath,
|
||||
false
|
||||
)
|
||||
.catch((error: unknown) => {
|
||||
this.client.logger.error(
|
||||
`Failed to open link for ${entry.details.relativePath}: ${error}`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
card.addClass("clickable");
|
||||
}
|
||||
|
||||
card.createDiv(
|
||||
{
|
||||
cls: "history-card-header"
|
||||
},
|
||||
(header) => {
|
||||
header.createEl(
|
||||
"h5",
|
||||
{
|
||||
cls: "history-card-title"
|
||||
},
|
||||
(title) => {
|
||||
HistoryView.renderSyncItemTitle(title, entry);
|
||||
}
|
||||
);
|
||||
|
||||
header.createSpan({
|
||||
text: HistoryView.getTimestampAndAuthor(entry),
|
||||
cls: "history-card-timestamp"
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const body =
|
||||
entry.details.type === SyncType.MOVE
|
||||
? `${entry.message}. Moved from '${entry.details.movedFrom}' to '${entry.details.relativePath}'`
|
||||
: `${entry.message}.`;
|
||||
|
||||
card.createEl("p", {
|
||||
text: body,
|
||||
cls: "history-card-message"
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
60
frontend/obsidian-plugin/src/views/logs/logs-view.scss
Normal file
60
frontend/obsidian-plugin/src/views/logs/logs-view.scss
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
.logs-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.verbosity-selector {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-weight: normal;
|
||||
gap: var(--size-4-2);
|
||||
margin: var(--size-4-4) var(--size-4-2);
|
||||
|
||||
h4 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
select {
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.logs-container {
|
||||
max-width: 100%;
|
||||
overflow-y: auto;
|
||||
|
||||
.log-message {
|
||||
font: var(--font-monospace);
|
||||
margin-bottom: var(--size-2-1);
|
||||
overflow-wrap: break-word;
|
||||
white-space: pre-wrap;
|
||||
user-select: all;
|
||||
|
||||
.timestamp {
|
||||
padding: var(--size-2-1) var(--size-4-1);
|
||||
border-radius: var(--radius-s);
|
||||
background-color: var(--color-base-30);
|
||||
font-size: var(--font-ui-small);
|
||||
font-family: var(--font-monospace);
|
||||
font-weight: var(--bold-weight);
|
||||
margin-right: var(--size-4-1);
|
||||
}
|
||||
|
||||
&.DEBUG {
|
||||
color: var(--color-base-50);
|
||||
}
|
||||
|
||||
&.INFO {
|
||||
color: var(--color-base-100);
|
||||
}
|
||||
|
||||
&.WARNING {
|
||||
color: rgb(var(--color-yellow-rgb));
|
||||
}
|
||||
|
||||
&.ERROR {
|
||||
color: rgb(var(--color-red-rgb));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
152
frontend/obsidian-plugin/src/views/logs/logs-view.ts
Normal file
152
frontend/obsidian-plugin/src/views/logs/logs-view.ts
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
import "./logs-view.scss";
|
||||
|
||||
import type { WorkspaceLeaf } from "obsidian";
|
||||
import { ItemView } from "obsidian";
|
||||
import type { LogLine } from "sync-client";
|
||||
import { LogLevel, type SyncClient } from "sync-client";
|
||||
|
||||
export class LogsView extends ItemView {
|
||||
public static readonly TYPE = "logs-view";
|
||||
public static readonly ICON = "logs";
|
||||
|
||||
private static readonly MAX_OFFSET_FROM_BOTTOM_WITH_AUTO_SCROLL_PX = 300;
|
||||
|
||||
private logsContainer: HTMLElement | undefined;
|
||||
private readonly logLineToElement = new Map<LogLine, HTMLElement>();
|
||||
private minLogLevel: LogLevel = LogLevel.INFO;
|
||||
|
||||
public constructor(
|
||||
private readonly client: SyncClient,
|
||||
leaf: WorkspaceLeaf
|
||||
) {
|
||||
super(leaf);
|
||||
this.icon = LogsView.ICON;
|
||||
this.client.logger.addOnMessageListener(() => {
|
||||
this.updateView();
|
||||
});
|
||||
}
|
||||
|
||||
private static createLogLineElement(
|
||||
container: HTMLElement,
|
||||
logLine: LogLine
|
||||
): HTMLElement {
|
||||
return container.createDiv(
|
||||
{
|
||||
cls: ["log-message", logLine.level]
|
||||
},
|
||||
(messageContainer) => {
|
||||
messageContainer.createEl("span", {
|
||||
text: LogsView.formatTimestamp(logLine.timestamp),
|
||||
cls: "timestamp"
|
||||
});
|
||||
messageContainer.createEl("span", {
|
||||
text: logLine.message
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private static formatTimestamp(timestamp: Date): string {
|
||||
return timestamp.toTimeString().split(" ")[0];
|
||||
}
|
||||
|
||||
public getViewType(): string {
|
||||
return LogsView.TYPE;
|
||||
}
|
||||
|
||||
public getDisplayText(): string {
|
||||
return "VaultLink logs";
|
||||
}
|
||||
|
||||
public async onOpen(): Promise<void> {
|
||||
const container = this.containerEl.children[1];
|
||||
container.addClass("logs-view");
|
||||
|
||||
const logLevels = [
|
||||
{ label: "Debug", value: LogLevel.DEBUG },
|
||||
{ label: "Info", value: LogLevel.INFO },
|
||||
{ label: "Warn", value: LogLevel.WARNING },
|
||||
{ label: "Error", value: LogLevel.ERROR }
|
||||
];
|
||||
|
||||
container.createDiv(
|
||||
{
|
||||
cls: "verbosity-selector"
|
||||
},
|
||||
(verbositySection) => {
|
||||
verbositySection.createEl("h4", {
|
||||
text: "VaultLink logs"
|
||||
});
|
||||
|
||||
verbositySection.createEl("select", {}, (dropdown) => {
|
||||
logLevels.forEach(({ label, value }) =>
|
||||
dropdown.createEl("option", { text: label, value })
|
||||
);
|
||||
|
||||
dropdown.value = this.minLogLevel;
|
||||
|
||||
dropdown.addEventListener("change", () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
|
||||
this.minLogLevel = dropdown.value as LogLevel;
|
||||
|
||||
this.logsContainer?.empty();
|
||||
this.logLineToElement.clear();
|
||||
this.updateView();
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
this.logsContainer = container.createDiv({ cls: "logs-container" });
|
||||
|
||||
this.updateView();
|
||||
}
|
||||
|
||||
private updateView(): void {
|
||||
const container = this.logsContainer;
|
||||
if (container === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const logs = this.client.logger.getMessages(this.minLogLevel);
|
||||
|
||||
if (this.logLineToElement.size === 0 && logs.length > 0) {
|
||||
// Clear the "No logs available yet" message
|
||||
container.empty();
|
||||
}
|
||||
|
||||
const shouldScroll =
|
||||
container.scrollTop == 0 ||
|
||||
container.scrollHeight -
|
||||
container.clientHeight -
|
||||
container.scrollTop <
|
||||
LogsView.MAX_OFFSET_FROM_BOTTOM_WITH_AUTO_SCROLL_PX;
|
||||
|
||||
logs.forEach((message) => {
|
||||
if (this.logLineToElement.has(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const element = LogsView.createLogLineElement(container, message);
|
||||
|
||||
this.logLineToElement.set(message, element);
|
||||
});
|
||||
|
||||
const newLines = new Set(logs);
|
||||
for (const [logLine, element] of this.logLineToElement) {
|
||||
if (!newLines.has(logLine)) {
|
||||
element.remove();
|
||||
this.logLineToElement.delete(logLine);
|
||||
}
|
||||
}
|
||||
|
||||
if (logs.length === 0) {
|
||||
container.empty();
|
||||
container.createEl("p", {
|
||||
text: "No logs available yet."
|
||||
});
|
||||
} else if (shouldScroll) {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
@mixin number-card {
|
||||
padding: var(--size-2-1) var(--size-4-1);
|
||||
border-radius: var(--radius-s);
|
||||
background-color: var(--color-base-30);
|
||||
font-size: var(--font-ui-small);
|
||||
|
||||
&.good {
|
||||
background-color: rgba(var(--color-green-rgb), 0.35);
|
||||
}
|
||||
|
||||
&.bad {
|
||||
background-color: rgba(var(--color-red-rgb), 0.35);
|
||||
}
|
||||
}
|
||||
|
||||
.vault-link-settings {
|
||||
h2 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-size: var(--h2-size);
|
||||
|
||||
.version {
|
||||
@include number-card;
|
||||
margin: var(--size-2-2) 0 0 var(--size-4-2);
|
||||
background-color: var(--color-base-30);
|
||||
color: var(--color-base-70);
|
||||
font-size: var(--font-ui-smaller);
|
||||
}
|
||||
}
|
||||
|
||||
.button-container {
|
||||
display: flex;
|
||||
gap: var(--size-4-2);
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: var(--font-ui-large);
|
||||
margin-top: var(--heading-spacing);
|
||||
}
|
||||
|
||||
button,
|
||||
input[type="range"],
|
||||
.checkbox-container,
|
||||
.slider::-webkit-slider-thumb {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
input[type="text"],
|
||||
textarea {
|
||||
width: 250px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: none;
|
||||
height: 75px;
|
||||
}
|
||||
}
|
||||
384
frontend/obsidian-plugin/src/views/settings/settings-tab.ts
Normal file
384
frontend/obsidian-plugin/src/views/settings/settings-tab.ts
Normal file
|
|
@ -0,0 +1,384 @@
|
|||
import "./settings-tab.scss";
|
||||
|
||||
import type { App } from "obsidian";
|
||||
import { Notice, PluginSettingTab, Setting } from "obsidian";
|
||||
import type VaultLinkPlugin from "src/vault-link-plugin";
|
||||
import type { SyncClient, SyncSettings } from "sync-client";
|
||||
import { HistoryView } from "../history/history-view";
|
||||
import { LogsView } from "../logs/logs-view";
|
||||
import type { StatusDescription } from "../status-description/status-description";
|
||||
|
||||
export class SyncSettingsTab extends PluginSettingTab {
|
||||
private editedServerUri: string;
|
||||
private editedToken: string;
|
||||
private editedVaultName: string;
|
||||
|
||||
private readonly plugin: VaultLinkPlugin;
|
||||
private readonly syncClient: SyncClient;
|
||||
private readonly statusDescription: StatusDescription;
|
||||
private statusDescriptionSubscription: (() => unknown) | undefined;
|
||||
|
||||
public constructor({
|
||||
app,
|
||||
plugin,
|
||||
syncClient,
|
||||
statusDescription
|
||||
}: {
|
||||
app: App;
|
||||
plugin: VaultLinkPlugin;
|
||||
syncClient: SyncClient;
|
||||
statusDescription: StatusDescription;
|
||||
}) {
|
||||
super(app, plugin);
|
||||
this.plugin = plugin;
|
||||
this.syncClient = syncClient;
|
||||
this.statusDescription = statusDescription;
|
||||
|
||||
this.editedServerUri = this.syncClient.getSettings().remoteUri;
|
||||
this.editedToken = this.syncClient.getSettings().token;
|
||||
this.editedVaultName = this.syncClient.getSettings().vaultName;
|
||||
|
||||
this.syncClient.addOnSettingsChangeListener(
|
||||
(newSettings, oldSettings) => {
|
||||
let hasChanged = false;
|
||||
|
||||
if (newSettings.remoteUri !== oldSettings.remoteUri) {
|
||||
this.editedServerUri = newSettings.remoteUri;
|
||||
hasChanged = true;
|
||||
}
|
||||
|
||||
if (newSettings.token !== oldSettings.token) {
|
||||
this.editedToken = newSettings.token;
|
||||
hasChanged = true;
|
||||
}
|
||||
|
||||
if (newSettings.vaultName !== oldSettings.vaultName) {
|
||||
this.editedVaultName = newSettings.vaultName;
|
||||
hasChanged = true;
|
||||
}
|
||||
|
||||
if (hasChanged) {
|
||||
this.display();
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public display(): void {
|
||||
const { containerEl } = this;
|
||||
containerEl.empty();
|
||||
containerEl.addClass("vault-link-settings");
|
||||
|
||||
this.renderSettingsHeader(containerEl);
|
||||
this.renderConnectionSettings(containerEl);
|
||||
this.renderSyncSettings(containerEl);
|
||||
}
|
||||
|
||||
public hide(): void {
|
||||
super.hide();
|
||||
this.setStatusDescriptionSubscription();
|
||||
}
|
||||
|
||||
private renderSettingsHeader(containerEl: HTMLElement): void {
|
||||
containerEl.createEl("h2", { text: "VaultLink" }).createSpan({
|
||||
text: this.plugin.manifest.version,
|
||||
cls: "version"
|
||||
});
|
||||
|
||||
containerEl.createDiv(
|
||||
{
|
||||
cls: "description"
|
||||
},
|
||||
(descriptionContainer) => {
|
||||
this.setStatusDescriptionSubscription(
|
||||
this.statusDescription.renderStatusDescription.bind(
|
||||
this.statusDescription,
|
||||
descriptionContainer
|
||||
)
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
containerEl.createDiv(
|
||||
{
|
||||
cls: "button-container"
|
||||
},
|
||||
(buttonContainer) => {
|
||||
buttonContainer.createEl(
|
||||
"button",
|
||||
{
|
||||
text: "Show history"
|
||||
},
|
||||
(button) =>
|
||||
(button.onclick = async (): Promise<void> => {
|
||||
this.plugin.closeSettings();
|
||||
await this.plugin.activateView(HistoryView.TYPE);
|
||||
})
|
||||
);
|
||||
|
||||
buttonContainer.createEl(
|
||||
"button",
|
||||
{
|
||||
text: "Show logs"
|
||||
},
|
||||
(button) =>
|
||||
(button.onclick = async (): Promise<void> => {
|
||||
this.plugin.closeSettings();
|
||||
await this.plugin.activateView(LogsView.TYPE);
|
||||
})
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private renderConnectionSettings(containerEl: HTMLElement): void {
|
||||
containerEl.createEl("h3", { text: "Connection" });
|
||||
|
||||
const [title, updateTitle] = this.unsavedAwareSettingName(
|
||||
"Server address",
|
||||
"remoteUri"
|
||||
);
|
||||
new Setting(containerEl)
|
||||
.setName(title)
|
||||
.setDesc(
|
||||
"Your VaultLink server's URL including the protocol and full path."
|
||||
)
|
||||
.setTooltip("This is the URL of the server you want to sync with.")
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("https://example.com:3000")
|
||||
.setValue(this.editedServerUri.toLowerCase().trim())
|
||||
.onChange((value) => {
|
||||
this.editedServerUri = value.toLowerCase().trim();
|
||||
updateTitle(value.toLowerCase().trim());
|
||||
})
|
||||
);
|
||||
|
||||
const [tokenTitle, updateTokenTitle] = this.unsavedAwareSettingName(
|
||||
"Access token",
|
||||
"token"
|
||||
);
|
||||
new Setting(containerEl)
|
||||
.setName(tokenTitle)
|
||||
.setClass("sync-settings-access-token")
|
||||
.setDesc(
|
||||
"Set the access token for the server that you can get from the server"
|
||||
)
|
||||
.setTooltip("todo, links to dcocs")
|
||||
.addTextArea((text) =>
|
||||
text
|
||||
.setPlaceholder("ey...")
|
||||
.setValue(this.editedToken.trim())
|
||||
.onChange((value) => {
|
||||
this.editedToken = value.trim();
|
||||
updateTokenTitle(value.trim());
|
||||
})
|
||||
);
|
||||
|
||||
const [vaultNameTitle, updateVaultNameTitle] =
|
||||
this.unsavedAwareSettingName("Vault name", "vaultName");
|
||||
new Setting(containerEl)
|
||||
.setName(vaultNameTitle)
|
||||
.setDesc(
|
||||
"Set the name of the remote vault that you want to sync with"
|
||||
)
|
||||
.setTooltip("todo, links to dcocs")
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("My Obsidian Vault")
|
||||
.setValue(this.editedVaultName.toLowerCase().trim())
|
||||
.onChange((value) => {
|
||||
this.editedVaultName = value.toLowerCase().trim();
|
||||
updateVaultNameTitle(value.toLowerCase().trim());
|
||||
})
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.addButton((button) =>
|
||||
button.setButtonText("Apply").onClick(async () => {
|
||||
if (this.areThereUnsavedChanges()) {
|
||||
await this.syncClient.setSettings({
|
||||
vaultName: this.editedVaultName,
|
||||
remoteUri: this.editedServerUri,
|
||||
token: this.editedToken
|
||||
});
|
||||
new Notice(
|
||||
"The changes have been applied successfully!"
|
||||
);
|
||||
await this.statusDescription.updateConnectionState();
|
||||
} else {
|
||||
new Notice("No changes to apply");
|
||||
}
|
||||
})
|
||||
)
|
||||
.addButton((button) =>
|
||||
button.setButtonText("Test connection").onClick(async () => {
|
||||
if (this.areThereUnsavedChanges()) {
|
||||
new Notice(
|
||||
"There are unsaved changes, testing with the currently saved settings"
|
||||
);
|
||||
}
|
||||
|
||||
new Notice(
|
||||
(await this.syncClient.checkConnection()).serverMessage
|
||||
);
|
||||
await this.statusDescription.updateConnectionState();
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private areThereUnsavedChanges(): boolean {
|
||||
return (
|
||||
this.editedServerUri !== this.syncClient.getSettings().remoteUri ||
|
||||
this.editedToken !== this.syncClient.getSettings().token ||
|
||||
this.editedVaultName !== this.syncClient.getSettings().vaultName
|
||||
);
|
||||
}
|
||||
|
||||
private renderSyncSettings(containerEl: HTMLElement): void {
|
||||
containerEl.createEl("h3", { text: "Sync" });
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName("Enable sync")
|
||||
.setDesc(
|
||||
"Enable pulling and pushing changes to the remote server. The first time it's enabled, or after the sync state has been reset, all local files will be pushed to the server."
|
||||
)
|
||||
.setTooltip(
|
||||
"Enable pulling and pushing changes to the remote server."
|
||||
)
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.syncClient.getSettings().isSyncEnabled)
|
||||
.onChange(async (value) =>
|
||||
this.syncClient.setSetting("isSyncEnabled", value)
|
||||
)
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName("Ignore patterns")
|
||||
.setDesc(
|
||||
"Patterns to ignore when syncing. Each line is a separate glob pattern. Patterns are matched against the relative path of the file. For example, to ignore all files in a folder named 'ignore', enter 'ignore/*'. To ignore all files with the extension '.log', enter '*.log'."
|
||||
)
|
||||
.addTextArea((text) =>
|
||||
text
|
||||
.setValue(
|
||||
this.syncClient.getSettings().ignorePatterns.join("\n")
|
||||
)
|
||||
.setPlaceholder("Enter patterns to ignore, one per line")
|
||||
.onChange(async (value) => {
|
||||
const patterns = value
|
||||
.split("\n")
|
||||
.map((pattern) => pattern.trim())
|
||||
.filter((pattern) => pattern.length > 0);
|
||||
return this.syncClient.setSetting(
|
||||
"ignorePatterns",
|
||||
patterns
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName("Sync concurrency")
|
||||
.setDesc(
|
||||
"How many concurrent sync operations to run. Setting this value higher may increase the overall performance, however, it will require more memory as well. If you notice frequent crashes, especially on mobile, set this to 1."
|
||||
)
|
||||
.addSlider((text) =>
|
||||
text
|
||||
.setLimits(1, 16, 1)
|
||||
.setDynamicTooltip()
|
||||
.setInstant(false)
|
||||
.setValue(this.syncClient.getSettings().syncConcurrency)
|
||||
.onChange(async (value) =>
|
||||
this.syncClient.setSetting("syncConcurrency", value)
|
||||
)
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName("Maximum file size to be uploaded (MB)")
|
||||
.setDesc(
|
||||
"Set the maximum file size that can be uploaded to the server. Files larger than this size will be ignored."
|
||||
)
|
||||
.addText((input) =>
|
||||
input
|
||||
.setValue(
|
||||
this.syncClient.getSettings().maxFileSizeMB.toString()
|
||||
)
|
||||
.onChange(async (value) => {
|
||||
if (value === "") {
|
||||
return;
|
||||
}
|
||||
let parsedValue = Number.parseFloat(value);
|
||||
if (Number.isNaN(parsedValue) || parsedValue < 0) {
|
||||
parsedValue =
|
||||
this.syncClient.getSettings().maxFileSizeMB;
|
||||
}
|
||||
|
||||
if (value !== parsedValue.toString()) {
|
||||
input.setValue(parsedValue.toString());
|
||||
}
|
||||
|
||||
return this.syncClient.setSetting(
|
||||
"maxFileSizeMB",
|
||||
parsedValue
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName("Danger zone")
|
||||
.setDesc(
|
||||
"Delete the local metadata database while leaving the local and remote files intact."
|
||||
)
|
||||
.addButton((button) =>
|
||||
button.setButtonText("Reset sync state").onClick(async () => {
|
||||
await this.syncClient.reset();
|
||||
new Notice(
|
||||
"Sync state has been reset, you will need to resync"
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private setStatusDescriptionSubscription(
|
||||
newSubscription?: () => unknown
|
||||
): void {
|
||||
if (this.statusDescriptionSubscription) {
|
||||
this.statusDescription.removeStatusChangeListener(
|
||||
this.statusDescriptionSubscription
|
||||
);
|
||||
}
|
||||
this.statusDescriptionSubscription = newSubscription;
|
||||
if (this.statusDescriptionSubscription) {
|
||||
this.statusDescriptionSubscription();
|
||||
this.statusDescription.addStatusChangeListener(
|
||||
this.statusDescriptionSubscription
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private unsavedAwareSettingName(
|
||||
name: string,
|
||||
settingName: keyof SyncSettings
|
||||
): [
|
||||
DocumentFragment,
|
||||
(newValue: SyncSettings[keyof SyncSettings]) => unknown
|
||||
] {
|
||||
const titleContainer = document.createDocumentFragment();
|
||||
const title = titleContainer.createEl("div", {
|
||||
text: name,
|
||||
cls: "setting-item-name"
|
||||
});
|
||||
|
||||
const updateTitle = (
|
||||
currentValue: SyncSettings[keyof SyncSettings]
|
||||
): void => {
|
||||
title.innerText = `${name}${
|
||||
currentValue !== this.syncClient.getSettings()[settingName]
|
||||
? " (unsaved)"
|
||||
: ""
|
||||
}`;
|
||||
};
|
||||
|
||||
return [titleContainer, updateTitle];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
.sync-status {
|
||||
display: flex;
|
||||
gap: var(--size-4-2);
|
||||
|
||||
* {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.initialize-button {
|
||||
padding: 0 var(--size-4-2);
|
||||
background: rgba(var(--color-red-rgb), 0.4);
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
75
frontend/obsidian-plugin/src/views/status-bar/status-bar.ts
Normal file
75
frontend/obsidian-plugin/src/views/status-bar/status-bar.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import "./status-bar.scss";
|
||||
|
||||
import type { HistoryStats, SyncClient } from "sync-client";
|
||||
import type VaultLinkPlugin from "../../vault-link-plugin";
|
||||
|
||||
export class StatusBar {
|
||||
private readonly statusBarItem: HTMLElement;
|
||||
|
||||
private lastHistoryStats: HistoryStats | undefined;
|
||||
private lastRemaining: number | undefined;
|
||||
|
||||
public constructor(
|
||||
private readonly plugin: VaultLinkPlugin,
|
||||
private readonly syncClient: SyncClient
|
||||
) {
|
||||
this.statusBarItem = plugin.addStatusBarItem();
|
||||
this.syncClient.addSyncHistoryUpdateListener((status) => {
|
||||
this.lastHistoryStats = status;
|
||||
this.updateStatus();
|
||||
});
|
||||
|
||||
this.syncClient.addRemainingSyncOperationsListener(
|
||||
(remainingOperations) => {
|
||||
this.lastRemaining = remainingOperations;
|
||||
this.updateStatus();
|
||||
}
|
||||
);
|
||||
|
||||
this.syncClient.addOnSettingsChangeListener(() => {
|
||||
this.updateStatus();
|
||||
});
|
||||
}
|
||||
|
||||
private updateStatus(): void {
|
||||
this.statusBarItem.empty();
|
||||
const container = this.statusBarItem.createDiv({
|
||||
cls: ["sync-status"]
|
||||
});
|
||||
|
||||
if (!this.syncClient.getSettings().isSyncEnabled) {
|
||||
const button = container.createEl("button", {
|
||||
text: "VaultLink is disabled, click to configure",
|
||||
cls: "initialize-button"
|
||||
});
|
||||
button.onclick = this.plugin.openSettings.bind(this.plugin);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
let hasShownMessage = false;
|
||||
|
||||
if ((this.lastRemaining ?? 0) > 0) {
|
||||
hasShownMessage = true;
|
||||
container.createSpan({ text: `${this.lastRemaining} ⏳` });
|
||||
}
|
||||
|
||||
if ((this.lastHistoryStats?.success ?? 0) > 0) {
|
||||
hasShownMessage = true;
|
||||
container.createSpan({
|
||||
text: `${this.lastHistoryStats?.success ?? 0} ✅`
|
||||
});
|
||||
}
|
||||
|
||||
if ((this.lastHistoryStats?.error ?? 0) > 0) {
|
||||
hasShownMessage = true;
|
||||
container.createSpan({
|
||||
text: `${this.lastHistoryStats?.error ?? 0} ❌`
|
||||
});
|
||||
}
|
||||
|
||||
if (!hasShownMessage) {
|
||||
container.createSpan({ text: "VaultLink is idle" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
@mixin number-card {
|
||||
padding: var(--size-2-1) var(--size-4-1);
|
||||
border-radius: var(--radius-s);
|
||||
background-color: var(--color-base-30);
|
||||
font-size: var(--font-ui-small);
|
||||
|
||||
&.good {
|
||||
background-color: rgba(var(--color-green-rgb), 0.35);
|
||||
}
|
||||
|
||||
&.bad {
|
||||
background-color: rgba(var(--color-red-rgb), 0.35);
|
||||
}
|
||||
}
|
||||
|
||||
.status-description {
|
||||
margin: var(--p-spacing) 0;
|
||||
|
||||
.number {
|
||||
@include number-card;
|
||||
font-family: var(--font-monospace);
|
||||
font-weight: var(--bold-weight);
|
||||
}
|
||||
|
||||
.error {
|
||||
color: rgb(var(--color-red-rgb));
|
||||
}
|
||||
|
||||
.warning {
|
||||
color: rgb(var(--color-yellow-rgb));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
import "./status-description.scss";
|
||||
|
||||
import type {
|
||||
HistoryStats,
|
||||
NetworkConnectionStatus,
|
||||
SyncClient
|
||||
} from "sync-client";
|
||||
|
||||
export class StatusDescription {
|
||||
private lastHistoryStats: HistoryStats | undefined;
|
||||
private lastRemaining: number | undefined;
|
||||
private lastConnectionState: NetworkConnectionStatus | undefined;
|
||||
|
||||
private statusChangeListeners: (() => unknown)[] = [];
|
||||
|
||||
public constructor(private readonly syncClient: SyncClient) {
|
||||
void this.updateConnectionState();
|
||||
|
||||
syncClient.addSyncHistoryUpdateListener((status) => {
|
||||
this.lastHistoryStats = status;
|
||||
this.updateDescription();
|
||||
});
|
||||
|
||||
this.syncClient.addRemainingSyncOperationsListener(
|
||||
(remainingOperations) => {
|
||||
this.lastRemaining = remainingOperations;
|
||||
this.updateDescription();
|
||||
}
|
||||
);
|
||||
|
||||
this.syncClient.addWebSocketStatusChangeListener(async () =>
|
||||
this.updateConnectionState()
|
||||
);
|
||||
|
||||
this.syncClient.addOnSettingsChangeListener(async () =>
|
||||
this.updateConnectionState()
|
||||
);
|
||||
}
|
||||
|
||||
public async updateConnectionState(): Promise<void> {
|
||||
this.lastConnectionState = await this.syncClient.checkConnection();
|
||||
this.updateDescription();
|
||||
}
|
||||
|
||||
public addStatusChangeListener(listener: () => unknown): void {
|
||||
this.statusChangeListeners.push(listener);
|
||||
}
|
||||
public removeStatusChangeListener(listener: () => unknown): void {
|
||||
this.statusChangeListeners = this.statusChangeListeners.filter(
|
||||
(l) => l !== listener
|
||||
);
|
||||
}
|
||||
|
||||
public renderStatusDescription(container: HTMLElement): void {
|
||||
container.empty();
|
||||
container.addClass("status-description");
|
||||
|
||||
if (this.lastConnectionState == undefined) {
|
||||
container.createSpan({
|
||||
text: "VaultLink is starting up…",
|
||||
cls: "warning"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.lastConnectionState.isSuccessful) {
|
||||
container.createSpan({
|
||||
text: `VaultLink failed to connect to the remote server with error '${this.lastConnectionState.serverMessage}'`,
|
||||
cls: "error"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.lastConnectionState.isWebSocketConnected) {
|
||||
container.createSpan({
|
||||
text: `${this.lastConnectionState.serverMessage} but the WebSocket connection could not be established.`,
|
||||
cls: "error"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
container.createSpan({ text: "VaultLink is connected to the server " });
|
||||
container.createEl("a", {
|
||||
text: this.syncClient.getSettings().remoteUri,
|
||||
href: this.syncClient.getSettings().remoteUri
|
||||
});
|
||||
|
||||
container.createSpan({
|
||||
text: ` and has indexed approximately `
|
||||
});
|
||||
container.createSpan({
|
||||
text: `${this.syncClient.documentCount}`,
|
||||
cls: "number"
|
||||
});
|
||||
container.createSpan({
|
||||
text: ` documents. `
|
||||
});
|
||||
|
||||
if (
|
||||
(this.lastRemaining ?? 0) === 0 &&
|
||||
(this.lastHistoryStats?.success ?? 0) === 0 &&
|
||||
(this.lastHistoryStats?.error ?? 0) === 0
|
||||
) {
|
||||
if (this.syncClient.getSettings().isSyncEnabled) {
|
||||
container.createSpan({
|
||||
text: "Syncing is enabled but VaultLink hasn't found anything to sync yet."
|
||||
});
|
||||
} else {
|
||||
container.createSpan({
|
||||
text: "However, syncing is disabled right now.",
|
||||
cls: "warning"
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
container.createSpan({
|
||||
text: "The plugin has "
|
||||
});
|
||||
container.createSpan({
|
||||
text: `${this.lastRemaining ?? 0}`,
|
||||
cls: "number"
|
||||
});
|
||||
container.createSpan({
|
||||
text: " outstanding operations while having succeeded "
|
||||
});
|
||||
container.createSpan({
|
||||
text: `${this.lastHistoryStats?.success ?? 0}`,
|
||||
cls: ["number", "good"]
|
||||
});
|
||||
container.createSpan({
|
||||
text: " times and failed "
|
||||
});
|
||||
container.createSpan({
|
||||
text: `${this.lastHistoryStats?.error ?? 0}`,
|
||||
cls: ["number", "bad"]
|
||||
});
|
||||
container.createSpan({
|
||||
text: " times."
|
||||
});
|
||||
}
|
||||
|
||||
private updateDescription(): void {
|
||||
this.statusChangeListeners.forEach((listener) => {
|
||||
listener();
|
||||
});
|
||||
}
|
||||
}
|
||||
17
frontend/obsidian-plugin/tsconfig.json
Normal file
17
frontend/obsidian-plugin/tsconfig.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"module": "ESNext",
|
||||
"target": "ES2023",
|
||||
"strict": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"lib": [
|
||||
"DOM",
|
||||
"ES2024"
|
||||
]
|
||||
},
|
||||
"exclude": [
|
||||
"./dist"
|
||||
]
|
||||
}
|
||||
7
frontend/obsidian-plugin/version-bump.mjs
Normal file
7
frontend/obsidian-plugin/version-bump.mjs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import { readFileSync, writeFileSync } from "fs";
|
||||
|
||||
const targetVersion = process.env.npm_package_version;
|
||||
|
||||
let manifest = JSON.parse(readFileSync("manifest.json", "utf8"));
|
||||
manifest.version = targetVersion;
|
||||
writeFileSync("manifest.json", JSON.stringify(manifest, null, "\t"));
|
||||
117
frontend/obsidian-plugin/webpack.config.js
Normal file
117
frontend/obsidian-plugin/webpack.config.js
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
const path = require("path");
|
||||
const TerserPlugin = require("terser-webpack-plugin");
|
||||
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
|
||||
const fs = require("fs-extra");
|
||||
|
||||
module.exports = (env, argv) => ({
|
||||
devtool: argv.mode === "development" ? "inline-source-map" : false,
|
||||
entry: {
|
||||
index: "./src/vault-link-plugin.ts"
|
||||
},
|
||||
watchOptions: {
|
||||
ignored: "**/node_modules"
|
||||
},
|
||||
externals: {
|
||||
obsidian: "commonjs obsidian",
|
||||
electron: "commonjs electron",
|
||||
"@codemirror/autocomplete": "commonjs @codemirror/autocomplete",
|
||||
"@codemirror/collab": "commonjs @codemirror/collab",
|
||||
"@codemirror/commands": "commonjs @codemirror/commands",
|
||||
"@codemirror/language": "commonjs @codemirror/language",
|
||||
"@codemirror/lint": "commonjs @codemirror/lint",
|
||||
"@codemirror/search": "commonjs @codemirror/search",
|
||||
"@codemirror/state": "commonjs @codemirror/state",
|
||||
"@codemirror/view": "commonjs @codemirror/view"
|
||||
},
|
||||
optimization: {
|
||||
minimizer: [
|
||||
new TerserPlugin({
|
||||
terserOptions: {
|
||||
module: true
|
||||
}
|
||||
})
|
||||
]
|
||||
},
|
||||
plugins: [
|
||||
new MiniCssExtractPlugin({
|
||||
filename: "styles.css"
|
||||
}),
|
||||
{
|
||||
apply: (compiler) => {
|
||||
if (argv.mode !== "development") {
|
||||
return;
|
||||
}
|
||||
|
||||
compiler.hooks.done.tap("Copy Files Plugin", (stats) => {
|
||||
const source = path.resolve(__dirname, "dist");
|
||||
const destinations = [
|
||||
"/mnt/c/Users/Andras/Desktop/test/test/.obsidian/plugins/vault-link",
|
||||
"/mnt/c/Users/Andras/Desktop/test/test2/.obsidian/plugins/vault-link",
|
||||
"/home/andras/obsidian-test/.obsidian/plugins/vault-link"
|
||||
];
|
||||
destinations.forEach((destination) => {
|
||||
fs.copy(source, destination)
|
||||
.then(() =>
|
||||
console.log(
|
||||
"Files copied successfully after build!"
|
||||
)
|
||||
)
|
||||
.catch((err) =>
|
||||
console.error("Error copying files:", err)
|
||||
);
|
||||
|
||||
fs.createFile(path.join(destination, ".hotreload"));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
],
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.json$/i,
|
||||
type: "asset/resource",
|
||||
generator: {
|
||||
filename: "[name][ext]"
|
||||
}
|
||||
},
|
||||
{
|
||||
test: /\.scss$/i,
|
||||
use: [
|
||||
MiniCssExtractPlugin.loader,
|
||||
"css-loader",
|
||||
"resolve-url-loader",
|
||||
{
|
||||
loader: "sass-loader",
|
||||
options: {
|
||||
sourceMap: true // required by resolve-url-loader
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
test: /\.ts$/,
|
||||
use: ["ts-loader"]
|
||||
}
|
||||
]
|
||||
},
|
||||
resolve: {
|
||||
extensions: [
|
||||
".ts",
|
||||
".js" // required for development
|
||||
],
|
||||
alias: {
|
||||
root: __dirname,
|
||||
src: path.resolve(__dirname, "src")
|
||||
}
|
||||
},
|
||||
output: {
|
||||
clean: true,
|
||||
filename: "main.js",
|
||||
library: {
|
||||
type: "commonjs" // required for Obsidian
|
||||
},
|
||||
path: path.resolve(__dirname, "dist"),
|
||||
publicPath: ""
|
||||
}
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue