-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathpad_editor.ts
More file actions
309 lines (281 loc) · 11.3 KB
/
pad_editor.ts
File metadata and controls
309 lines (281 loc) · 11.3 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
// @ts-nocheck
'use strict';
/**
* This code is mostly from the old Etherpad. Please help us to comment this code.
* This helps other people to understand this code better and helps them to improve it.
* TL;DR COMMENTS ON THIS FILE ARE HIGHLY APPRECIATED
*/
/**
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import padutils,{Cookies} from "./pad_utils";
const padcookie = require('./pad_cookie').padcookie;
const Ace2Editor = require('./ace').Ace2Editor;
import html10n from '../js/vendors/html10n'
const skinVariants = require('./skin_variants');
const padeditor = (() => {
let pad = undefined;
let settings = undefined;
const self = {
ace: null,
// this is accessed directly from other files
viewZoom: 100,
init: async (initialViewOptions, _pad) => {
pad = _pad;
settings = pad.settings;
self.ace = new Ace2Editor();
await self.ace.init('editorcontainer', '');
$('#editorloadingbox').hide();
// Listen for clicks on sidediv items
const $outerdoc = $('iframe[name="ace_outer"]').contents().find('#outerdocbody');
$outerdoc.find('#sidedivinner').on('click', 'div', function () {
const targetLineNumber = $(this).index() + 1;
window.location.hash = `L${targetLineNumber}`;
});
exports.focusOnLine(self.ace);
self.ace.setProperty('wraps', true);
self.initViewOptions();
self.setViewOptions(initialViewOptions);
// view bar
$('#viewbarcontents').show();
},
initViewOptions: () => {
// Line numbers
padutils.bindCheckboxChange($('#options-linenoscheck'), () => {
pad.changeViewOption('showLineNumbers', padutils.getCheckbox($('#options-linenoscheck')));
});
// Author colors
padutils.bindCheckboxChange($('#options-colorscheck'), () => {
padcookie.setPref('showAuthorshipColors', padutils.getCheckbox('#options-colorscheck'));
pad.changeViewOption('showAuthorColors', padutils.getCheckbox('#options-colorscheck'));
});
// Right to left
padutils.bindCheckboxChange($('#options-rtlcheck'), () => {
pad.changeViewOption('rtlIsTrue', padutils.getCheckbox($('#options-rtlcheck')));
});
html10n.bind('localized', () => {
// Don't override RTL when explicitly set via URL/server or user cookie
if (settings && settings.rtlIsExplicit) return;
if (padcookie.getPref('rtlIsTrue') === true) return;
pad.changeViewOption('rtlIsTrue', ('rtl' === html10n.getDirection()));
padutils.setCheckbox($('#options-rtlcheck'), ('rtl' === html10n.getDirection()));
});
// font family change
$('#viewfontmenu').on('change', () => {
pad.changeViewOption('padFontFamily', $('#viewfontmenu').val());
});
// delete pad
$('#delete-pad').on('click', () => {
if (window.confirm(html10n.get('pad.delete.confirm'))) {
// Wait for the server to confirm deletion before navigating away.
// Navigating immediately caused a race condition where the browser
// (especially Firefox) would close the WebSocket before the delete
// message reached the server. See #7306.
let handled = false;
pad.socket.on('message', (data: any) => {
if (data && data.disconnect === 'deleted') {
handled = true;
window.location.href = '/';
}
});
// If the user is not the pad creator, the server sends a shout
// message instead of deleting. Listen for it and show the error.
pad.socket.on('shout', (data: any) => {
handled = true;
const msg = data?.data?.payload?.message?.message;
if (msg) window.alert(msg);
});
pad.collabClient.sendMessage({type: 'PAD_DELETE', data:{padId: pad.getPadId()}});
// Fallback: if the server doesn't respond within 5 seconds
// (e.g. socket dropped), navigate away anyway.
setTimeout(() => {
if (!handled) window.location.href = '/';
}, 5000);
}
})
// theme switch
$('#theme-switcher').on('click',()=>{
if (skinVariants.isDarkMode()) {
skinVariants.setDarkModeInLocalStorage(false);
skinVariants.updateSkinVariantsClasses(['super-light-toolbar super-light-editor light-background']);
} else {
skinVariants.setDarkModeInLocalStorage(true);
skinVariants.updateSkinVariantsClasses(['super-dark-editor', 'dark-background', 'super-dark-toolbar']);
}
})
// Language
html10n.bind('localized', () => {
$('#languagemenu').val(html10n.getLanguage());
// translate the value of 'unnamed' and 'Enter your name' textboxes in the userlist
// this does not interfere with html10n's normal value-setting because
// html10n just ingores <input>s
// also, a value which has been set by the user will be not overwritten
// since a user-edited <input> does *not* have the editempty-class
$('input[data-l10n-id]').each((key, input) => {
input = $(input);
if (input.hasClass('editempty')) {
input.val(html10n.get(input.attr('data-l10n-id')));
}
});
});
$('#languagemenu').val(html10n.getLanguage());
$('#languagemenu').on('change', () => {
const cp = (window as any).clientVars?.cookiePrefix || '';
Cookies.set(`${cp}language`, $('#languagemenu').val());
html10n.localize([$('#languagemenu').val(), 'en']);
if ($('select').niceSelect) {
$('select').niceSelect('update');
}
});
},
setViewOptions: (newOptions) => {
const getOption = (key, defaultValue) => {
const value = String(newOptions[key]);
if (value === 'true') return true;
if (value === 'false') return false;
return defaultValue;
};
let v;
v = getOption('rtlIsTrue', ('rtl' === html10n.getDirection()));
self.ace.setProperty('rtlIsTrue', v);
padutils.setCheckbox($('#options-rtlcheck'), v);
v = getOption('showLineNumbers', true);
self.ace.setProperty('showslinenumbers', v);
padutils.setCheckbox($('#options-linenoscheck'), v);
v = getOption('showAuthorColors', true);
self.ace.setProperty('showsauthorcolors', v);
$('#chattext').toggleClass('authorColors', v);
$('iframe[name="ace_outer"]').contents().find('#sidedivinner').toggleClass('authorColors', v);
padutils.setCheckbox($('#options-colorscheck'), v);
// Override from parameters if true
if (settings.noColors !== false) {
self.ace.setProperty('showsauthorcolors', !settings.noColors);
}
self.ace.setProperty('textface', newOptions.padFontFamily || '');
},
dispose: () => {
if (self.ace) {
self.ace.destroy();
self.ace = null;
}
},
enable: () => {
if (self.ace) {
self.ace.setEditable(true);
}
},
disable: () => {
if (self.ace) {
self.ace.setEditable(false);
}
},
restoreRevisionText: (dataFromServer) => {
pad.addHistoricalAuthors(dataFromServer.historicalAuthorData);
self.ace.importAText(dataFromServer.atext, dataFromServer.apool, true);
},
};
return self;
})();
exports.padeditor = padeditor;
const getHashedLineNumber = () => {
const lineNumber = window.location.hash.substr(1);
if (!lineNumber || lineNumber[0] !== 'L') return null;
const lineNumberInt = parseInt(lineNumber.substr(1));
return Number.isInteger(lineNumberInt) && lineNumberInt > 0 ? lineNumberInt : null;
};
const focusOnHashedLine = (ace, lineNumberInt) => {
const $aceOuter = $('iframe[name="ace_outer"]');
const $outerdoc = $aceOuter.contents().find('#outerdocbody');
const $inner = $aceOuter.contents().find('iframe').contents().find('#innerdocbody');
const line = $inner.find(`div:nth-child(${lineNumberInt})`);
if (line.length === 0) return false;
let offsetTop = line.offset().top;
offsetTop += parseInt($outerdoc.css('padding-top').replace('px', ''));
const hasMobileLayout = $('body').hasClass('mobile-layout');
if (!hasMobileLayout) offsetTop += parseInt($inner.css('padding-top').replace('px', ''));
const $outerdocHTML = $aceOuter.contents().find('#outerdocbody').parent();
$outerdoc.css({top: `${offsetTop}px`}); // Chrome
$outerdocHTML.scrollTop(offsetTop);
const node = line[0];
ace.callWithAce((ace) => {
const selection = {
startPoint: {
index: 0,
focusAtStart: true,
maxIndex: 1,
node,
},
endPoint: {
index: 0,
focusAtStart: true,
maxIndex: 1,
node,
},
};
ace.ace_setSelection(selection);
});
return true;
};
exports.focusOnLine = (ace) => {
const lineNumberInt = getHashedLineNumber();
if (lineNumberInt == null) return;
const $aceOuter = $('iframe[name="ace_outer"]');
const getCurrentTargetOffset = () => {
const $inner = $aceOuter.contents().find('iframe').contents().find('#innerdocbody');
const line = $inner.find(`div:nth-child(${lineNumberInt})`);
if (line.length === 0) return null;
return line.offset().top;
};
const maxSettleDuration = 10000;
const settleInterval = 250;
const startTime = Date.now();
let intervalId: number | null = null;
const userEventNames = ['wheel', 'touchmove', 'keydown', 'mousedown'];
const docs: Document[] = [];
const stop = () => {
if (intervalId != null) {
window.clearInterval(intervalId);
intervalId = null;
}
for (const doc of docs) {
for (const name of userEventNames) doc.removeEventListener(name, stop, true);
}
docs.length = 0;
};
const focusUntilStable = () => {
if (Date.now() - startTime >= maxSettleDuration) {
stop();
return;
}
const currentOffsetTop = getCurrentTargetOffset();
if (currentOffsetTop == null) return;
focusOnHashedLine(ace, lineNumberInt);
};
focusUntilStable();
intervalId = window.setInterval(focusUntilStable, settleInterval);
// Stop fighting the user: any deliberate scroll, tap, click, or keystroke cancels the
// reapply loop so late layout corrections do not steal focus once the user takes over.
// Listen on both the ace_outer and ace_inner documents in capture phase so we see the
// user's intent even if inner handlers stopPropagation().
const outerDoc = ($aceOuter.contents()[0] as any) as Document | undefined;
const innerIframe = $aceOuter.contents().find('iframe')[0] as HTMLIFrameElement | undefined;
const innerDoc = innerIframe?.contentDocument;
for (const doc of [outerDoc, innerDoc]) {
if (!doc) continue;
docs.push(doc);
for (const name of userEventNames) doc.addEventListener(name, stop, true);
}
// End of setSelection / set Y position of editor
};