-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathsync.ts
More file actions
362 lines (309 loc) · 11.1 KB
/
sync.ts
File metadata and controls
362 lines (309 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/* eslint-disable prefer-const */
/*
* connection.ts
*
* Copyright (C) 2022 by Posit Software, PBC
*
* Unless you have received this program directly from Posit Software pursuant
* to the terms of a commercial license agreement with Posit Software, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
import throttle from "lodash.throttle";
import { WebviewApi } from "vscode-webview";
import {
jsonRpcPostMessageRequestTransport,
jsonRpcPostMessageServer,
JsonRpcPostMessageTarget,
JsonRpcRequestTransport
} from "core";
import { windowJsonRpcPostMessageTarget } from "core-browser";
import {
VSC_VE_ApplyExternalEdit,
VSC_VE_PrefsChanged,
VSC_VE_ImageChanged,
VSC_VE_GetMarkdownFromState,
VSC_VE_GetSlideIndex,
VSC_VE_GetActiveBlockContext,
VSC_VE_SetBlockSelection,
VSC_VE_Init,
VSC_VE_Focus,
VSC_VEH_FlushEditorUpdates,
VSC_VEH_SaveDocument,
VSC_VEH_RenderDocument,
VSC_VEH_SelectImage,
VSC_VEH_EditorResourceUri,
VSC_VEH_GetHostContext,
VSC_VEH_ReopenSourceMode,
VSC_VEH_OnEditorUpdated,
VSC_VEH_OnEditorStateChanged,
VSC_VEH_OnEditorReady,
VSC_VEH_OpenURL,
VSC_VEH_NavigateToXRef,
VSC_VEH_NavigateToFile,
VSC_VEH_ResolveImageUris,
VSC_VEH_ResolveBase64Images,
VSCodeVisualEditor,
VSCodeVisualEditorHost,
EditorServer,
EditorServices,
XRef,
VSC_VE_IsFocused,
Prefs,
SourcePos,
NavLocation,
CodeViewActiveBlockContext,
CodeViewSelectionAction
} from "editor-types";
import {
editorJsonRpcServer,
editorJsonRpcServices
} from "editor-core";
import {
EditorOperations,
EditorTheme,
PandocWriterOptions,
StateChangeEvent,
UpdateEvent
} from "editor";
import { Command, EditorUIStore, readPrefsApi, t, updatePrefsApi } from "editor-ui";
import { editorThemeFromStore } from "./theme";
export interface VisualEditorHostClient extends VSCodeVisualEditorHost {
vscode: WebviewApi<unknown>;
server: EditorServer;
services: EditorServices;
}
// json rpc request client
export function visualEditorJsonRpcRequestTransport(vscode: WebviewApi<unknown>) {
const target = windowJsonRpcPostMessageTarget(vscode, window);
const { request } = jsonRpcPostMessageRequestTransport(target);
return request;
}
// interface to visual editor host (vs code extension)
export function visualEditorHostClient(
vscode: WebviewApi<unknown>,
request: JsonRpcRequestTransport
) : VisualEditorHostClient {
return {
vscode,
server: editorJsonRpcServer(request),
services: editorJsonRpcServices(request),
...editorJsonRpcContainer(request)
}
}
export interface ImageChangeSink {
notifyImageChanged(file: string): void;
}
export async function syncEditorToHost(
editor: EditorOperations,
imageChange: ImageChangeSink,
host: VisualEditorHostClient,
store: EditorUIStore,
applyTheme: (theme: EditorTheme) => void
) {
// get the current prefs
const readPrefs = () => readPrefsApi(store);
// determine markdown writer options from current state of the prefs store
const writerOptions = () => {
const prefs = readPrefs();
const options: PandocWriterOptions = {};
options.wrap = prefs.markdownWrap === "column"
? String(prefs.markdownWrapColumn)
: prefs.markdownWrap;
options.references = {
location: prefs.markdownReferences,
prefix: prefs.markdownReferencesPrefix || undefined,
links: prefs.markdownReferenceLinks
}
return options;
}
// apply the current theme (including bootstrap class on body)
const applyDisplayPrefs = () => {
// determine current theme
const theme = editorThemeFromStore(store);
// callback host (allows for reactive re-render w/ new theme)
applyTheme(theme);
// apply theme to prosemirror editor instance
editor.applyTheme(theme);
// NOTE: sync with variables.scss => $sideGutterNarrowWidth
const prefs = readPrefsApi(store);
editor.setMaxContentWidth(prefs.maxContentWidth, 22);
}
// sync from text editor (throttled)
const kThrottleDelayMs = 1000;
const receiveEdit = throttle((markdown) => {
editor.setMarkdown(markdown, writerOptions(), false)
.finally(() => {
// done
});
}, kThrottleDelayMs, { leading: false, trailing: true});
// setup communication channel for host
visualEditorHostServer(host.vscode, {
async init(markdown: string, navigation?: NavLocation) {
try {
// apply initial theme
applyDisplayPrefs();
// init editor contents and sync canonical version back to text editor
const result = await editor.setMarkdown(markdown, writerOptions(), false);
if (result) {
// focus editor
editor.focus(navigation);
// visual editor => text editor (just send the state, host will call back for markdown)
editor.subscribe(UpdateEvent, () => host.onEditorUpdated(editor.getStateJson()));
editor.subscribe(StateChangeEvent, () => host.onEditorStateChanged(editor.getEditorSourcePos()));
// return canonical markdown
return result.canonical;
} else {
return null;
}
} catch(error) {
editor.onLoadFailed(error);
return null;
}
},
async prefsChanged(prefs: Prefs): Promise<void> {
// save existing writer options (for comparison)
const prevOptions = writerOptions();
// update prefs
await updatePrefsApi(store, prefs);
// apply theme
applyDisplayPrefs();
// if markdown writing options changed then force a refresh
const options = writerOptions();
if (prevOptions.wrap !== options.wrap ||
prevOptions.references?.location !== options.references?.location ||
prevOptions.references?.prefix !== options.references?.prefix) {
await host.onEditorUpdated(editor.getStateJson());
await host.flushEditorUpdates();
}
},
async imageChanged(file: string) {
imageChange.notifyImageChanged(file);
},
async focus(navigation?: NavLocation) {
editor.focus(navigation);
},
async isFocused() {
return editor.hasFocus();
},
async applyExternalEdit(markdown: string) {
// only receive external text edits if we don't have focus (prevents circular updates)
if (!editor.hasFocus() && !window.document.hasFocus()) {
receiveEdit(markdown);
}
},
async getMarkdownFromState(state: unknown): Promise<string> {
const markdown = await editor.getMarkdownFromStateJson(state, writerOptions());
return markdown;
},
async getSlideIndex(): Promise<number> {
return editor.getSlideIndex();
},
async getActiveBlockContext(): Promise<CodeViewActiveBlockContext | null> {
return editor.getCodeViewActiveBlockContext() || null;
},
async setBlockSelection(context: CodeViewActiveBlockContext, action: CodeViewSelectionAction) {
editor.setBlockSelection(context, action);
}
})
// let the host know we are ready
await host.onEditorReady();
}
export enum EditorHostCommands {
Save = "33AFE7B9-24B0-42B4-8ED0-BE9C0015773D",
Render = "297E16BF-B801-4DBB-BC1F-7F9C603B4456",
EditSource = "E3B3EFC1-0183-4AD1-9E34-B1C11187775D"
}
export function editorHostCommands(host: VisualEditorHostClient) {
const commands: Command[] = [
{
id: EditorHostCommands.Save,
menuText: t('commands:save_menu_text'),
group: t('commands:group_file'),
keymap: ['Mod-s'],
isEnabled: () => true,
isActive: () => false,
execute: async () => {
await host.saveDocument();
},
},
{
id: EditorHostCommands.Render,
menuText: t('commands:render_menu_text'),
group: t('commands:group_file'),
keymap: ['Mod-Shift-k'],
isEnabled: () => true,
isActive: () => false,
execute: async () => {
await host.renderDocument();
},
},
{
id: EditorHostCommands.EditSource,
menuText: t('commands:edit_source_menu_text'),
group: t('commands:group_file'),
keymap: ['Mod-Shift-f4'],
isEnabled: () => true,
isActive: () => false,
execute: async () => {
await host.reopenSourceMode();
},
}
];
return commands;
}
// interface provided to visual editor host (vs code extension)
function visualEditorHostServer(vscode: WebviewApi<unknown>, editor: VSCodeVisualEditor) {
// target for message bus
const target: JsonRpcPostMessageTarget = {
postMessage: (data) => {
vscode.postMessage(data);
},
onMessage: (handler: (data: unknown) => void) => {
const messageListener = (event: MessageEvent) => {
const message = event.data; // The json data that the extension sent
handler(message);
};
window.addEventListener('message', messageListener);
return () => {
window.removeEventListener('message', messageListener);
}
}
};
// create a server
return jsonRpcPostMessageServer(target, {
[VSC_VE_Init]: args => editor.init(args[0], args[1]),
[VSC_VE_Focus]: args => editor.focus(args[0]),
[VSC_VE_IsFocused]: () => editor.isFocused(),
[VSC_VE_GetMarkdownFromState]: args => editor.getMarkdownFromState(args[0]),
[VSC_VE_GetSlideIndex]: () => editor.getSlideIndex(),
[VSC_VE_ApplyExternalEdit]: args => editor.applyExternalEdit(args[0]),
[VSC_VE_GetActiveBlockContext]: () => editor.getActiveBlockContext(),
[VSC_VE_SetBlockSelection]: args => editor.setBlockSelection(args[0], args[1]),
[VSC_VE_PrefsChanged]: args => editor.prefsChanged(args[0]),
[VSC_VE_ImageChanged]: args => editor.imageChanged(args[0])
})
}
function editorJsonRpcContainer(request: JsonRpcRequestTransport) : VSCodeVisualEditorHost {
return {
getHostContext: () => request(VSC_VEH_GetHostContext, []),
reopenSourceMode: () => request(VSC_VEH_ReopenSourceMode, []),
onEditorReady: () => request(VSC_VEH_OnEditorReady, []),
onEditorUpdated: (state: unknown) => request(VSC_VEH_OnEditorUpdated, [state]),
onEditorStateChanged: (sourcePos: SourcePos) => request(VSC_VEH_OnEditorStateChanged, [sourcePos]),
flushEditorUpdates: () => request(VSC_VEH_FlushEditorUpdates, []),
saveDocument: () => request(VSC_VEH_SaveDocument, []),
renderDocument: () => request(VSC_VEH_RenderDocument, []),
editorResourceUri: (path: string) => request(VSC_VEH_EditorResourceUri, [path]),
openURL: (url: string) => request(VSC_VEH_OpenURL, [url]),
navigateToXRef: (file: string, xref: XRef) => request(VSC_VEH_NavigateToXRef, [file, xref]),
navigateToFile: (file: string) => request(VSC_VEH_NavigateToFile, [file]),
resolveImageUris: (uris: string[]) => request(VSC_VEH_ResolveImageUris, [uris]),
resolveBase64Images: (base64Images: string[]) => request(VSC_VEH_ResolveBase64Images, [base64Images]),
selectImage: () => request(VSC_VEH_SelectImage, [])
};
}