Skip to content

Commit

Permalink
Fix for non-angular page
Browse files Browse the repository at this point in the history
  • Loading branch information
hrjakobsen committed Feb 20, 2024
1 parent 3d2b9b5 commit 1b6da8a
Show file tree
Hide file tree
Showing 8 changed files with 139 additions and 141 deletions.
2 changes: 2 additions & 0 deletions app/scripts/dispatcher.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Logger } from "./logger";
export type Listener = (d: any) => any;

export class Dispatcher {
protected listeners = new Map<string, Array<Listener>>();

protected dispatch(event: string, data?: any): void {
Logger.debug(`[${this.constructor.name}]: ${event}`);
if (!this.listeners.has(event)) return;
this.listeners.get(event).forEach(function (listener) {
listener(data);
Expand Down
45 changes: 20 additions & 25 deletions app/scripts/injected.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
/* global document, CustomEvent, _debug_editors, Event */
document.addEventListener("variable_query", function (evt) {
var query = evt.detail;
var res = eval(query);
var resEvent = new CustomEvent("variable_query_" + query, { detail: res });
document.dispatchEvent(resEvent);
/* global document, CustomEvent, Event */

Check failure on line 1 in app/scripts/injected.js

View workflow job for this annotation

GitHub Actions / build

'Event' is defined but never used

document.addEventListener("slext:initializeStoreWatchers", () => {
window.overleaf?.unstable.store.watch(

Check failure on line 4 in app/scripts/injected.js

View workflow job for this annotation

GitHub Actions / build

'window' is not defined
"project",
(project) => {
var resEvent = new CustomEvent("slext:setProject", { detail: project });
document.dispatchEvent(resEvent);
},
true
);

window.overleaf?.unstable.store.watch("editor.open_doc_id", (id) => {

Check failure on line 13 in app/scripts/injected.js

View workflow job for this annotation

GitHub Actions / build

'window' is not defined
var resEvent = new CustomEvent("slext:fileChanged", { detail: id });
document.dispatchEvent(resEvent);
});
});

document.addEventListener("slext:doFileChange", ({ detail: id }) => {
window.dispatchEvent(new CustomEvent("editor.openDoc", { detail: id }));

Check failure on line 20 in app/scripts/injected.js

View workflow job for this annotation

GitHub Actions / build

'window' is not defined
});

// eslint-disable-next-line no-undef
Expand Down Expand Up @@ -104,22 +118,3 @@ window.addEventListener("UNSTABLE_editor:extensions", (event) => {
});
extensions.push(requestWrapInCommand);
});

var limit = 50;
var tries = 0;
var int = setInterval(function () {
try {
if (_debug_editors && _debug_editors.length) {
clearInterval(int);
var editor = _debug_editors[0];
editor.on("changeSession", function () {
var event = new Event("slext_editorChanged");
document.dispatchEvent(event);
});
}
tries++;
} catch (e) {
if (!(e instanceof ReferenceError)) throw e;
if (tries++ >= limit) clearInterval(int);
}
}, 100);
3 changes: 2 additions & 1 deletion app/scripts/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@ function projectLoaded(url) {
const i = setInterval(() => {
if (projectLoaded(window.location.href)) {
clearInterval(i);
PageHook.initialize();
PageHook.inject();
const slext: Slext = Container.get(Slext);
const interval = setInterval(() => {
if (!slext.isLoaded()) return;
PageHook.initialize();
clearInterval(interval);
Container.get(Settings);
Container.get(Shortcut);
Expand Down
24 changes: 4 additions & 20 deletions app/scripts/pagehook.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,16 @@ import { Service } from "typedi";

@Service()
export class PageHook {
public static evaluateJS(variable: string): Promise<any> {
const promise = new Promise<any>((accept, _resolve) => {
const query = new CustomEvent("variable_query", { detail: variable });
const eventListener = (res: CustomEvent) => {
document.removeEventListener("variable_query_" + variable, eventListener);
accept(res.detail);
};
document.addEventListener("variable_query_" + variable, eventListener);
document.dispatchEvent(query);
});
return promise;
}

public static initialize(): void {
public static inject(): void {
const s = document.createElement("script");
s.src = chrome.extension.getURL("scripts/injected.js");
s.src = chrome.runtime.getURL("scripts/injected.js");
s.onload = function () {
s.remove();
};
(document.head || document.documentElement).appendChild(s);
}

// eslint-disable-next-line @typescript-eslint/ban-types
public static call(fun: Function, args?: Array<string>): Promise<any> {
args = args || [];
const jscode = `(${String(fun)})(${args.map((x) => '"' + x + '"').join(", ")});`;
return PageHook.evaluateJS(jscode);
public static initialize(): void {
document.dispatchEvent(new Event("slext:initializeStoreWatchers"));
}
}
4 changes: 2 additions & 2 deletions app/scripts/persistence.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ export class PersistenceService {
return PersistenceService.save(key + project, object);
}

public static loadLocal(key: string, object: any): void {
public static loadLocal(key: string, callback: any): void {
const project = PersistenceService.getProjectId();
return PersistenceService.load(key + project, object);
return PersistenceService.load(key + project, callback);
}

public static save(key: string, object: any): void {
Expand Down
82 changes: 27 additions & 55 deletions app/scripts/slext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import { Dispatcher } from "./dispatcher";
import { File, FileUtils } from "./file";
import * as $ from "jquery";
import { Service } from "typedi";
import { PageHook } from "./pagehook.service";
import { Logger } from "./logger";

Check failure on line 5 in app/scripts/slext.ts

View workflow job for this annotation

GitHub Actions / build

'Logger' is defined but never used
import { Utils } from "./utils";

@Service()
export class Slext extends Dispatcher {
private _files: Array<File> = [];
private _currentlySelectedFile: File | null = null;
private static id = 0;
private loaded = false;

Expand Down Expand Up @@ -37,15 +38,15 @@ export class Slext extends Dispatcher {
}

public isFullScreenPDF(): boolean {
return $(".full-size.ng-scope:not(.ng-hide)[ng-show=\"ui.view == 'pdf'\"]").length > 0;
return $(".full-size.ng-scope:not(.ng-hide)[ng-show=\"ui.view == 'pdf'\"],.pdf.full-size").length > 0;
}

public isFullScreenEditor(): boolean {
return !this.isFullScreenPDF() && !this.isSplitScreen();
}

public isHistoryOpen(): boolean {
return $("#ide-body.ide-history-open").length > 0;
return $("#ide-body.ide-history-open,.history-react").length > 0;
}

private _toggleFullScreenPDFEditor(): void {
Expand Down Expand Up @@ -103,36 +104,20 @@ export class Slext extends Dispatcher {
}

private loadingFinished(): void {
const mo = new MutationObserver((mutations, _observer) => {
if (mutations[0].addedNodes.length != 0 || mutations[0].removedNodes.length != 0) {
// Files have been added or removed from file tree
this.updateFiles();
}
});
const mainDocument =
document.querySelector('select[name="rootDoc_id"]') ?? document.querySelector("#settings-menu-rootDocId");
console.log(mainDocument);
if (mainDocument) {
mo.observe(mainDocument, {
childList: true,
subtree: true,
});
}

this.updateFiles();
this.setupListeners();
}

private setupListeners(): void {
window.addEventListener("editor.openDoc", (e: CustomEvent) => {
document.addEventListener("slext:fileChanged", (e: CustomEvent) => {
const file_id = e.detail;
const matches = this._files.filter((f, _i) => f.id == file_id);
const file = matches.length ? matches[0] : null;
this._currentlySelectedFile = file;
this.dispatch("FileSelected", file);
});

document.addEventListener("slext_editorChanged", (_e) => {
this.dispatch("editorChanged");
document.addEventListener("slext:setProject", (e: CustomEvent) => {
this.updateFiles(e.detail);
});

$(document).on(
Expand All @@ -146,22 +131,19 @@ export class Slext extends Dispatcher {
);
}

public updateFiles(): Promise<File[]> {
return new Promise((resolve, _reject) => {
this.indexFiles().then((files: Array<File>) => {
this._files = files;
this.dispatch("FilesChanged");
resolve(this._files);
});
});
}

private indexFiles(): Promise<File[]> {
return new Promise((resolve, _reject) => {
PageHook.evaluateJS("_ide.$scope.docs").then((response: any) => {
const res = response.map((f) => FileUtils.newFile(f.doc.name, f.path, f.doc.id, "doc"));
resolve(res);
});
public updateFiles(project: any): Promise<File[]> {
function getDocsFromFolder(folder, path) {
const files = folder.docs.map((d) => FileUtils.newFile(d.name, path + "/" + d.name, d._id, "doc"));
for (const subFolder of folder.folders) {
files.push(...getDocsFromFolder(subFolder, path + "/" + subFolder.name));
}
return files;
}
return new Promise((resolve) => {
const files = getDocsFromFolder(project.rootFolder[0], "");
this._files = files;
this.dispatch("FilesChanged");
resolve(this._files);
});
}

Expand All @@ -171,27 +153,17 @@ export class Slext extends Dispatcher {

public currentFile(): Promise<File> {
return new Promise((resolve, reject) => {
PageHook.evaluateJS("_ide.editorManager.$scope.editor.open_doc_id").then((id) => {
const matches = this._files.filter((f, _i) => f.id == id);
if (matches.length == 0) {
reject();
}
resolve(matches[0]);
});
if (this._currentlySelectedFile) {
resolve(this._currentlySelectedFile);
} else {
reject();
}
});
}

public selectFile(file: File): void {
if (this._files.filter((f) => f.id == file.id && f.path == file.path).length > 0) {
PageHook.evaluateJS(
"_ide.$scope.$emit('entity:selected', {type: '" +
file.type +
"', id:'" +
file.id +
"', name:'" +
file.name +
"'})"
);
document.dispatchEvent(new CustomEvent("slext:doFileChange", { detail: file.id }));
}
}
}
Loading

0 comments on commit 1b6da8a

Please sign in to comment.