1
0
silverbullet/web/open_pages.ts

58 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-07-29 10:19:35 +00:00
import { Client } from "./client.ts";
2023-07-14 11:58:16 +00:00
import { EditorSelection, EditorView } from "./deps.ts";
class PageState {
constructor(
readonly scrollTop: number,
readonly selection: EditorSelection,
) {}
}
export class OpenPages {
openPages = new Map<string, PageState>();
2023-07-29 10:19:35 +00:00
constructor(private client: Client) {}
2023-07-14 11:58:16 +00:00
restoreState(pageName: string): boolean {
const pageState = this.openPages.get(pageName);
2023-07-29 10:19:35 +00:00
const editorView = this.client.editorView;
2023-07-14 11:58:16 +00:00
if (pageState) {
// Restore state
try {
editorView.dispatch({
selection: pageState.selection,
2023-07-27 13:25:25 +00:00
// scrollIntoView: true,
2023-07-14 11:58:16 +00:00
});
} catch {
// This is fine, just go to the top
editorView.dispatch({
selection: { anchor: 0 },
scrollIntoView: true,
});
}
2023-07-27 13:25:25 +00:00
setTimeout(() => {
// Next tick, to allow the editor to process the render
editorView.scrollDOM.scrollTop = pageState.scrollTop;
});
2023-07-14 11:58:16 +00:00
} else {
editorView.scrollDOM.scrollTop = 0;
editorView.dispatch({
selection: { anchor: 0 },
scrollIntoView: true,
});
}
2023-07-29 10:19:35 +00:00
this.client.focus();
2023-07-14 11:58:16 +00:00
return !!pageState;
}
saveState(currentPage: string) {
this.openPages.set(
currentPage,
new PageState(
2023-07-29 10:19:35 +00:00
this.client.editorView.scrollDOM.scrollTop,
this.client.editorView.state.selection,
2023-07-14 11:58:16 +00:00
),
);
}
}