Skip to content

Commit

Permalink
feat: Merge pull request #126 from samuele-cozzi:124-synchronize-scro…
Browse files Browse the repository at this point in the history
…lling-of-markdown-editing-view-and-slide-preview-view

feat: sync code editor and preview
  • Loading branch information
samuele-cozzi committed Dec 24, 2023
2 parents 857cff7 + f5d9dc7 commit 9ebc658
Show file tree
Hide file tree
Showing 7 changed files with 199 additions and 22 deletions.
86 changes: 83 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
"@marp-team/marpit": "^2.4.2",
"esbuild-plugin-copy": "^2.1.1",
"fs-extra": "^11.1.1",
"request": "^2.88.2",
"jszip": "^3.10.1"
"gray-matter": "^4.0.3",
"jszip": "^3.10.1",
"request": "^2.88.2"
}
}
73 changes: 71 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MarkdownView, TAbstractFile, Plugin, addIcon, App, PluginSettingTab, Setting } from 'obsidian';
import { MarkdownView, TAbstractFile, Plugin, addIcon, App, PluginSettingTab, Setting, EditorSuggest, EditorPosition, Editor, TFile, EditorSuggestTriggerInfo, EditorSuggestContext } from 'obsidian';

import { MARP_PREVIEW_VIEW, MarpPreviewView } from './views/marpPreviewView';
import { MarpExport } from './utilities/marpExport';
Expand Down Expand Up @@ -77,6 +77,9 @@ export default class MarpSlides extends Plugin {
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new MarpSlidesSettingTab(this.app, this));

if (this.settings.EnableSyncPreview)
this.registerEditorSuggest(new LineSelectionListener(this.app, this));

this.registerEvent(this.app.vault.on('modify', this.onChange.bind(this)));
}

Expand Down Expand Up @@ -131,6 +134,14 @@ export default class MarpSlides extends Plugin {

return leaf.view as MarpPreviewView;
}

getViewInstance(): MarpPreviewView {
const leaf = this.app.workspace.getLeavesOfType(MARP_PREVIEW_VIEW)[0];

this.app.workspace.revealLeaf(leaf);

return leaf.view as MarpPreviewView;
}
}


Expand Down Expand Up @@ -207,7 +218,7 @@ export class MarpSlidesSettingTab extends PluginSettingTab {

new Setting(containerEl)
.setName('HTML Export Mode')
.setDesc('Controls HTML library for eporting HTML File in Marp Cli. bespoke.js is experimental')
.setDesc('(Experimental) Controls HTML library for eporting HTML File in Marp Cli. bespoke.js is experimental')
.addDropdown(toggle => toggle
.addOption("bare","bare.js")
.addOption("bespoke","bespoke.js")
Expand All @@ -216,5 +227,63 @@ export class MarpSlidesSettingTab extends PluginSettingTab {
this.plugin.settings.HTMLExportMode = value;
await this.plugin.saveSettings();
}));

new Setting(containerEl)
.setName('Sync Preview')
.setDesc('(Experimental) Sync the slide preview with the editor cursor')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.EnableSyncPreview)
.onChange(async (value) => {
this.plugin.settings.EnableSyncPreview = value;
await this.plugin.saveSettings();
}));
}
}

class LineSelectionListener extends EditorSuggest<string> {
private plugin: MarpSlides;

constructor(app: App, plugin: MarpSlides) {
super(app);
this.plugin = plugin;
}

onTrigger(cursor: EditorPosition, editor: Editor, file: TFile): EditorSuggestTriggerInfo {
//console.log("line: " + cursor.line);
//console.log("ch: " + cursor.ch);
//console.log("value: " + editor.getValue());

let triggerInfo: EditorSuggestTriggerInfo = {start:cursor, end:cursor, query:""};
const instance = this.plugin.getViewInstance();

const lines = editor.getValue().split('\n');
const firstNLines = lines.slice(0, cursor.line);
const text = firstNLines.join('\n');

if (instance) {

const regex = new RegExp('---', 'g');
let matches = text.match(regex);
let slide = matches ? matches.length : 0;
var matter = require('gray-matter');
const frontMatter = matter(text);
if (frontMatter.data !== null && Object.keys(frontMatter.data).length > 0) {
instance.onLineChanged(slide - 2);
} else {
instance.onLineChanged(slide);
}
}
return triggerInfo;
}
getSuggestions(context: EditorSuggestContext): string[] | Promise<string[]> {
let suggestion :string[] = [];
return suggestion;
//throw new Error('Method not implemented.');
}
renderSuggestion(value: string, el: HTMLElement): void {
throw new Error('Method not implemented.');
}
selectSuggestion(value: string, evt: MouseEvent | KeyboardEvent): void {
throw new Error('Method not implemented.');
}
}
16 changes: 8 additions & 8 deletions src/utilities/filePath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class FilePath {
}

private getLinkFormat(file: TFile): string {
console.log(`newLinkFormat: ${(file.vault as any).getConfig("newLinkFormat")}`);
//console.log(`newLinkFormat: ${(file.vault as any).getConfig("newLinkFormat")}`);
return (file.vault as any).getConfig("newLinkFormat");
}

Expand All @@ -34,7 +34,7 @@ export class FilePath {
basePath = `${normalizePath(basePath)}/`;
}

console.log(`Root Path: ${basePath}`);
//console.log(`Root Path: ${basePath}`);
return basePath;
}

Expand All @@ -47,7 +47,7 @@ export class FilePath {
{
resourcePath = (file.vault.adapter as FileSystemAdapter).getResourcePath(normalizePath(file.parent.path)).split("?");
}
console.log(`Complete File Base Path: ${resourcePath}`);
//console.log(`Complete File Base Path: ${resourcePath}`);
return `${resourcePath[0]}/`;
}

Expand All @@ -57,14 +57,14 @@ export class FilePath {
if(this.isAbsoluteLinkFormat(file)){
basePath = `${this.getRootPath(file)}${normalizePath(file.name)}`;
}
console.log(`Complete File Path: ${basePath}`);
//console.log(`Complete File Path: ${basePath}`);
return basePath;
}

public async copyFileToRoot(file: TFile) {
if(this.isAbsoluteLinkFormat(file)){
await (file.vault.adapter as FileSystemAdapter).copy(file.path, file.name);
console.log(`copied!`);
//console.log(`copied!`);
}
}

Expand All @@ -77,7 +77,7 @@ export class FilePath {

public getThemePath(file: TFile): string{
const themePath = `${this.getRootPath(file)}${normalizePath(this.settings.ThemePath)}`;
console.log(`Theme Path: ${themePath}`);
//console.log(`Theme Path: ${themePath}`);
if (this.settings.ThemePath != ''){
return themePath;
}
Expand All @@ -90,14 +90,14 @@ export class FilePath {
private getPluginDirectory(vault: Vault): string {
const fileSystem = vault.adapter as FileSystemAdapter;
const path = normalizePath(`${fileSystem.getBasePath()}/${vault.configDir}/plugins/marp-slides`) + '/';
console.log(path);
//console.log(path);
return path;
}

public getLibDirectory(vault: Vault): string {
const pluginDirectory = this.getPluginDirectory(vault);
const path = normalizePath(`${pluginDirectory}lib`) + '/';
console.log(path);
//console.log(path);
return path;
}
}
4 changes: 3 additions & 1 deletion src/utilities/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export interface MarpSlidesSettings {
MathTypesettings: string ;
HTMLExportMode: string;
EXPORT_PATH: string;
EnableSyncPreview: boolean;
}

export const DEFAULT_SETTINGS: MarpSlidesSettings = {
Expand All @@ -13,5 +14,6 @@ export const DEFAULT_SETTINGS: MarpSlidesSettings = {
EnableHTML: false,
MathTypesettings: 'mathjax',
HTMLExportMode: 'bare',
EXPORT_PATH: ''
EXPORT_PATH: '',
EnableSyncPreview: true
}
11 changes: 9 additions & 2 deletions src/views/marpPreviewView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,14 @@ export class MarpPreviewView extends ItemView {
this.displaySlides(view);
}

async onLineChanged(line: number) {
try {
this.containerEl.children[1].children[2].children[line].scrollIntoView();
} catch {
console.log("Preview slide not found!")
}
}

async addActions() {
const marpCli = new MarpExport(this.settings);

Expand Down Expand Up @@ -136,7 +144,6 @@ export class MarpPreviewView extends ItemView {
`;

container.innerHTML = htmlFile;
this.marpBrowser?.update()

this.marpBrowser?.update();
}
}
Loading

0 comments on commit 9ebc658

Please sign in to comment.