Repository navigation
Expand file tree
/
Copy pathpad.ts
More file actions
1138 lines (1059 loc) · 42.5 KB
/
Copy pathpad.ts
File metadata and controls
1138 lines (1059 loc) · 42.5 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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-nocheck
'use strict';
const skinVariants = require('./skin_variants');
/**
* 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., 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
*
* 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.
*/
let socket;
// These jQuery things should create local references, but for now `require()`
// assigns to the global `$` and augments it with plugins.
require('./vendors/jquery');
require('./vendors/farbtastic');
require('./vendors/gritter');
import html10n from './vendors/html10n'
import {Cookies} from "./pad_utils";
const chat = require('./chat').chat;
const getCollabClient = require('./collab_client').getCollabClient;
const padconnectionstatus = require('./pad_connectionstatus').padconnectionstatus;
const padcookie = require('./pad_cookie').padcookie;
const padeditbar = require('./pad_editbar').padeditbar;
const padMode = require('./pad_mode').padMode;
const padeditor = require('./pad_editor').padeditor;
const padimpexp = require('./pad_impexp').padimpexp;
const padmodals = require('./pad_modals').padmodals;
const padsavedrevs = require('./pad_savedrevs');
const paduserlist = require('./pad_userlist').paduserlist;
import padutils from './pad_utils'
const colorutils = require('./colorutils').colorutils;
import {randomString} from "./pad_utils";
const socketio = require('./socketio');
const hooks = require('./pluginfw/hooks');
import {showPrivacyBannerIfEnabled} from './privacy_banner';
import {maybeShowOutdatedNotice} from './pad_outdated_notice';
// This array represents all GET-parameters which can be used to change a setting.
// name: the parameter-name, eg `?noColors=true` => `noColors`
// checkVal: the callback is only executed when
// * the parameter was supplied and matches checkVal
// * the parameter was supplied and checkVal is null
// callback: the function to call when all above succeeds, `val` is the value supplied by the user
const getParameters = [
{
name: 'noColors',
checkVal: 'true',
callback: (val) => {
settings.noColors = true;
$('#clearAuthorship').hide();
},
},
{
name: 'fadeInactiveAuthorColors',
checkVal: 'false',
callback: (val) => {
if (!clientVars.initialOptions) return;
if (!clientVars.initialOptions.view) clientVars.initialOptions.view = {};
clientVars.initialOptions.view.fadeInactiveAuthorColors = false;
},
},
{
name: 'showControls',
checkVal: 'true',
callback: (val) => {
$('#editbar').css('display', 'flex');
},
},
{
// showMenuRight accepts 'true' or 'false'. Explicit 'false' hides the
// right-side toolbar (import/export/timeslider/settings/embed/home/
// users) — useful for iframe-embedded readonly pads where the menu
// is just chrome (issue #5182). Explicit 'true' forces the menu
// visible (a no-op against the default, kept for symmetry and for
// overriding any future caller-applied hide). Any other value is a
// no-op — the menu stays in its default state.
name: 'showMenuRight',
checkVal: null,
callback: (val) => {
if (val === 'false') {
$('#editbar .menu_right').hide();
} else if (val === 'true') {
$('#editbar .menu_right').show();
}
},
},
{
name: 'showChat',
checkVal: null,
callback: (val) => {
clientVars.initialOptions.showChat = val !== 'false';
if (val === 'false') {
settings.hideChat = true;
chat.hide();
$('#chaticon').hide();
} else {
settings.hideChat = false;
}
},
},
{
name: 'showLineNumbers',
checkVal: 'false',
callback: (val) => {
settings.LineNumbersDisabled = true;
},
},
{
name: 'useMonospaceFont',
checkVal: 'true',
callback: (val) => {
settings.useMonospaceFontGlobal = true;
},
},
{
name: 'userName',
checkVal: null,
callback: (val) => {
// The default for globalUserName/globalUserColor is the boolean `false`
// (sentinel meaning "no enforced value"). Older settings.json files used
// boolean `false` for these options too, which getParams() coerces to
// the string "false" — that fooled the !== false sentinel checks at
// _afterHandshake and shipped the literal string "false" as the user's
// name and color (#7686). Reject the sentinel string here so URL
// parameters like ?userName=false also no-op.
if (!val || val === 'false') return;
settings.globalUserName = val;
clientVars.userName = val;
},
},
{
name: 'userColor',
checkVal: null,
callback: (val) => {
if (!val || val === 'false') return;
settings.globalUserColor = val;
clientVars.userColor = val;
},
},
{
name: 'rtl',
checkVal: null,
callback: (val, fromUrl) => {
settings.rtlIsTrue = val === 'true';
if (fromUrl) settings.rtlIsExplicit = true;
},
},
{
name: 'alwaysShowChat',
checkVal: 'true',
callback: (val) => {
if (!settings.hideChat) chat.stickToScreen();
},
},
{
name: 'chatAndUsers',
checkVal: 'true',
callback: (val) => {
chat.chatAndUsers();
},
},
{
name: 'lang',
checkVal: null,
callback: (val) => {
console.log('Val is', val)
html10n.localize([val, 'en']);
const prefix = (window as any).clientVars?.cookiePrefix || '';
Cookies.set(`${prefix}language`, val);
},
},
];
const getParams = () => {
const params = getUrlVars();
for (const setting of getParameters) {
// URL query params take priority over server-enforced options.
// This prevents race conditions where both fire async callbacks
// (e.g., lang setting triggers html10n.localize twice).
const urlValue = params.get(setting.name);
if (urlValue && (urlValue === setting.checkVal || setting.checkVal == null)) {
setting.callback(urlValue, true);
continue;
}
// Fall back to server-enforced option
let serverValue = clientVars.padOptions[setting.name];
if (serverValue == null) continue;
serverValue = serverValue.toString();
if (serverValue === setting.checkVal || setting.checkVal == null) {
setting.callback(serverValue, false);
}
}
};
const getUrlVars = () => new URL(window.location.href).searchParams;
const getCookieLanguage = () => {
const cp = (window as any).clientVars?.cookiePrefix || '';
return Cookies.get(`${cp}language`) || Cookies.get('language');
};
const getMyViewOverrides = () => {
const language = getCookieLanguage();
const overrides = {
showChat: padcookie.getPref('showChat'),
alwaysShowChat: padcookie.getPref('chatAlwaysVisible'),
chatAndUsers: padcookie.getPref('chatAndUsers'),
lang: language,
view: {
showAuthorColors: padcookie.getPref('showAuthorshipColors'),
showLineNumbers: padcookie.getPref('showLineNumbers'),
rtlIsTrue: padcookie.getPref('rtlIsTrue'),
padFontFamily: padcookie.getPref('padFontFamily'),
fadeInactiveAuthorColors: padcookie.getPref('fadeInactiveAuthorColors'),
},
};
if (language == null) delete overrides.lang;
return overrides;
};
const normalizeChatOptions = (options) => {
if (options.showChat === false) {
options.alwaysShowChat = false;
options.chatAndUsers = false;
}
if (options.chatAndUsers === true) {
options.showChat = true;
options.alwaysShowChat = true;
} else if (options.alwaysShowChat === true) {
options.showChat = true;
}
return options;
};
// Surfaces the one-time pad deletion token when the server sends it in
// clientVars (creator session, first CLIENT_READY). The token is cleared from
// clientVars on acknowledgement so it is not re-exposed to later code paths.
const showDeletionTokenModalIfPresent = () => {
const token: string | null = (window as any).clientVars?.padDeletionToken;
if (!token) return;
const $modal = $('#deletiontoken-modal');
const $input = $('#deletiontoken-value');
const $copy = $('#deletiontoken-copy');
const $ack = $('#deletiontoken-ack');
if ($modal.length === 0) return;
$input.val(token);
const previouslyFocused = document.activeElement as HTMLElement | null;
$modal.prop('hidden', false).addClass('popup-show');
// Focus the token input so screen readers announce the dialog body and the
// user lands on the value they need to copy.
setTimeout(() => ($input[0] as HTMLInputElement)?.focus(), 0);
$copy.off('click.gdpr').on('click.gdpr', async () => {
try {
await navigator.clipboard.writeText(token);
} catch (_e) {
($input[0] as HTMLInputElement).select();
document.execCommand('copy');
}
$copy.text(html10n.get('pad.deletionToken.copied'));
});
$ack.off('click.gdpr').on('click.gdpr', () => {
$input.val('');
$modal.prop('hidden', true).removeClass('popup-show');
(window as any).clientVars.padDeletionToken = null;
if (previouslyFocused && document.body.contains(previouslyFocused)) {
previouslyFocused.focus();
}
});
};
// Drop the current pad from the "Recent pads" list shown on the welcome
// screen once the server reports it deleted, so the homepage no longer offers
// a link that would silently recreate it (issue #8201). The name is derived
// from the URL path the same way the entry was stored.
const forgetRecentPad = () => {
try {
const stored = localStorage.getItem('recentPads');
if (stored == null) return;
const pathSegments = window.location.pathname.split('/');
const padName = decodeURIComponent(pathSegments[pathSegments.length - 1]);
const recentPads = JSON.parse(stored);
if (!Array.isArray(recentPads)) return;
const deleted = new Set([padName, pad.getPadId()]);
// Entries written by older versions may hold a URL-encoded name; normalize
// the same way the welcome screen does before comparing.
const decodeName = (name) => {
try {
return decodeURIComponent(name);
} catch {
return name;
}
};
localStorage.setItem('recentPads', JSON.stringify(recentPads.filter(
(p) => p == null || !(deleted.has(p.name) || deleted.has(decodeName(p.name))))));
} catch (err) {
console.warn('Unable to update recent pads after pad deletion', err);
}
};
const sendClientReady = (isReconnect) => {
let padId = document.location.pathname.substring(document.location.pathname.lastIndexOf('/') + 1);
// unescape necessary due to Safari and Opera interpretation of spaces
padId = decodeURIComponent(padId);
if (!isReconnect) {
const titleArray = document.title.split('|');
const title = titleArray[titleArray.length - 1];
document.title = `${padId.replace(/_+/g, ' ')} | ${title}`;
}
// The author token lives in an HttpOnly cookie set by the server (GDPR PR3 /
// ether/etherpad#6701). The integrator-set `sessionID` cookie can also be
// HttpOnly now (issue #7045). The browser never reads or writes either; the
// server reads them from the socket.io handshake inside handleClientReady.
// If known, propagate the display name and color to the server in the CLIENT_READY message. This
// allows the server to include the values in its reply CLIENT_VARS message (which avoids
// initialization race conditions) and in the USER_NEWINFO messages sent to the other users on the
// pad (which enables them to display a user join notification with the correct name).
const params = getUrlVars();
const userInfo = {
colorId: params.get('userColor'),
name: params.get('userName'),
};
// The integrator-set `sessionID` cookie is read server-side from the
// socket.io handshake (issue #7045) so it can be HttpOnly. We no longer
// forward it via the CLIENT_READY payload.
const msg: any = {
component: 'pad',
type: 'CLIENT_READY',
padId,
userInfo,
};
const overrides = getMyViewOverrides();
const viewOverrides = Object.fromEntries(
Object.entries(overrides.view || {}).filter(([, v]) => v != null));
const hasTopLevelOverrides = ['showChat', 'alwaysShowChat', 'chatAndUsers', 'lang']
.some((k) => overrides[k] != null);
if (Object.keys(viewOverrides).length > 0 || hasTopLevelOverrides) {
if (Object.keys(viewOverrides).length > 0) overrides.view = viewOverrides;
else delete overrides.view;
msg.padSettingsDefaults = overrides;
}
// this is a reconnect, lets tell the server our revisionnumber
if (isReconnect) {
msg.client_rev = pad.collabClient.getCurrentRevisionNumber();
msg.reconnect = true;
}
socket.emit("message", msg);
};
const handshake = async () => {
let receivedClientVars = false;
let padId = document.location.pathname.substring(document.location.pathname.lastIndexOf('/') + 1);
// unescape necessary due to Safari and Opera interpretation of spaces
padId = decodeURIComponent(padId);
// padId is used here for sharding / scaling. We prefix the padId with padId: so it's clear
// to the proxy/gateway/whatever that this is a pad connection and should be treated as such
socket = pad.socket = socketio.connect(exports.baseURL, '/', {
query: {padId},
reconnectionAttempts: 5,
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
});
socket.once('connect', () => {
sendClientReady(false);
});
socket.io.on('reconnect', () => {
// pad.collabClient might be null if the hanshake failed (or it never got that far).
if (pad.collabClient != null) {
pad.collabClient.setChannelState('CONNECTED');
}
sendClientReady(receivedClientVars);
});
const socketReconnecting = () => {
// pad.collabClient might be null if the hanshake failed (or it never got that far).
if (pad.collabClient != null) {
pad.collabClient.setStateIdle();
pad.collabClient.setIsPendingRevision(true);
pad.collabClient.setChannelState('RECONNECTING');
}
};
socket.on('disconnect', (reason) => {
// The socket.io client will automatically try to reconnect for all reasons other than "io
// server disconnect".
console.log(`Socket disconnected: ${reason}`)
//if (reason !== 'io server disconnect' || reason !== 'ping timeout') return;
socketReconnecting();
});
socket.on('shout', (obj) => {
if(obj.type === "COLLABROOM") {
const payload = obj.data.payload;
const msgObj = payload?.message || {};
// Pad-deletion denial shouts are surfaced inline by pad_editor.ts as an
// alert tied to the delete action; suppress the global "Admin message"
// gritter so the user doesn't see a confusing duplicate.
if (typeof msgObj.messageKey === 'string'
&& msgObj.messageKey.startsWith('pad.deletionToken.')) return;
// Updater drain announcements get their own title and dodge the generic
// "Admin message" framing so the user knows it's a system event.
const isUpdate = typeof msgObj.messageKey === 'string'
&& msgObj.messageKey.startsWith('update.drain.');
const text = msgObj.messageKey
? html10n.get(msgObj.messageKey, msgObj.values || {})
: msgObj.message;
if (!text) return;
const date = new Date(payload.timestamp);
$.gritter.add({
title: isUpdate ? html10n.get('update.banner.title') : 'Admin message',
text: '[' + date.toLocaleTimeString() + ']: ' + text,
sticky: !!msgObj.sticky
});
}
})
socket.io.on('reconnect_attempt', socketReconnecting);
socket.io.on('reconnect_failed', (error) => {
// pad.collabClient might be null if the hanshake failed (or it never got that far).
if (pad.collabClient != null) {
pad.collabClient.setChannelState('DISCONNECTED', 'reconnect_timeout');
} else {
throw new Error('Reconnect timed out');
}
});
socket.on('error', (error) => {
// pad.collabClient might be null if the error occurred before the hanshake completed.
if (pad.collabClient != null) {
pad.collabClient.setStateIdle();
pad.collabClient.setIsPendingRevision(true);
}
// Don't throw an exception. Error events do not indicate problems that are not already
// addressed by reconnection logic, so throwing an exception each time there's a socket.io error
// just annoys users and fills logs.
});
socket.on('message', (obj) => {
// the access was not granted, give the user a message
if (obj.accessStatus) {
if (obj.accessStatus === 'deny') {
$('#loading').hide();
$('#permissionDenied').show();
if (receivedClientVars) {
// got kicked
$('#editorcontainer').hide();
$('#editorloadingbox').show();
}
}
} else if (!receivedClientVars && obj.type === 'CLIENT_VARS') {
receivedClientVars = true;
window.clientVars = obj.data;
if (window.clientVars.sessionRefreshInterval) {
const ping =
() => $.ajax('../_extendExpressSessionLifetime', {method: 'PUT'}).catch(() => {});
setInterval(ping, window.clientVars.sessionRefreshInterval);
}
if(window.clientVars.mode === "development") {
console.warn('Enabling development mode with live update')
socket.on('liveupdate', ()=>{
console.log('Live reload update received')
location.reload()
})
}
} else if (obj.disconnect) {
if (obj.disconnect === 'deleted') forgetRecentPad();
padconnectionstatus.disconnected(obj.disconnect);
socket.disconnect();
// block user from making any change to the pad
padeditor.disable();
padeditbar.disable();
padimpexp.disable();
return;
} else {
pad._messageQ.enqueue(obj);
}
});
await Promise.all([
new Promise((resolve) => {
const h = (obj) => {
if (obj.accessStatus || obj.type !== 'CLIENT_VARS') return;
socket.off('message', h);
resolve();
};
socket.on('message', h);
}),
// This hook is only intended to be used by test code. If a plugin would like to use this hook,
// the hook must first be promoted to officially supported by deleting the leading underscore
// from the name, adding documentation to `doc/api/hooks_client-side.md`, and deleting this
// comment.
hooks.aCallAll('_socketCreated', {socket}),
]);
};
/** Defers message handling until setCollabClient() is called with a non-null value. */
class MessageQueue {
constructor() {
this._q = [];
this._cc = null;
}
setCollabClient(cc) {
this._cc = cc;
this.enqueue(); // Flush.
}
enqueue(...msgs) {
if (this._cc == null) {
this._q.push(...msgs);
} else {
while (this._q.length > 0) this._cc.handleMessageFromServer(this._q.shift());
for (const msg of msgs) this._cc.handleMessageFromServer(msg);
}
}
}
const pad = {
// don't access these directly from outside this file, except
// for debugging
collabClient: null,
myUserInfo: null,
diagnosticInfo: {},
initTime: 0,
clientTimeOffset: null,
padOptions: {},
_messageQ: new MessageQueue(),
// these don't require init; clientVars should all go through here
getPadId: () => clientVars.padId,
// Retained as a plugin-compat shim. The server no longer populates
// clientIp on clientVars (value was always '127.0.0.1'; see #6701 /
// privacy audit). pad_utils.uniqueId still consumes this as a prefix.
getClientIp: () => '127.0.0.1',
getColorPalette: () => clientVars.colorPalette,
getPrivilege: (name) => clientVars.accountPrivs[name],
canEditPadSettings: () => !!clientVars.canEditPadSettings,
getUserId: () => pad.myUserInfo.userId,
getUserName: () => pad.myUserInfo.name,
userList: () => paduserlist.users(),
isPadSettingsEnforcedForMe: () => !!pad.padOptions.enforceSettings && !pad.canEditPadSettings(),
sendClientMessage: (msg) => {
pad.collabClient.sendClientMessage(msg);
},
getEffectivePadOptions: () => {
const effectiveOptions = $.extend(true, {}, pad.padOptions);
if (pad.isPadSettingsEnforcedForMe()) return normalizeChatOptions(effectiveOptions);
const overrides = getMyViewOverrides();
for (const key of ['showChat', 'alwaysShowChat', 'chatAndUsers', 'lang']) {
if (overrides[key] != null) effectiveOptions[key] = overrides[key];
}
if (!effectiveOptions.view) effectiveOptions.view = {};
for (const [key, value] of Object.entries(overrides.view)) {
if (value != null) effectiveOptions.view[key] = value;
}
return normalizeChatOptions(effectiveOptions);
},
refreshPadSettingsControls: () => {
const padOptions = normalizeChatOptions($.extend(true, {}, pad.padOptions || {}));
const view = padOptions.view || {};
$('#padsettings-options-disablechat').prop('checked', padOptions.showChat === false);
$('#padsettings-options-stickychat').prop('checked', !!padOptions.alwaysShowChat);
$('#padsettings-options-chatandusers').prop('checked', !!padOptions.chatAndUsers);
$('#padsettings-options-colorscheck').prop('checked', view.showAuthorColors !== false);
$('#padsettings-options-fadeauthorcheck')
.prop('checked', view.fadeInactiveAuthorColors !== false);
$('#padsettings-options-linenoscheck').prop('checked', view.showLineNumbers !== false);
$('#padsettings-options-rtlcheck').prop('checked', !!view.rtlIsTrue);
$('#padsettings-viewfontmenu').val(view.padFontFamily || '');
// When no pad-wide lang is set, reflect the language html10n actually
// detected and rendered (e.g. from the browser) instead of defaulting the
// dropdown to English while the UI is in another language. See #7925.
$('#padsettings-languagemenu').val(padOptions.lang || html10n.getLanguage() || 'en');
$('#padsettings-enforcecheck').prop('checked', !!padOptions.enforceSettings);
$('#padsettings-options-stickychat, #padsettings-options-chatandusers')
.prop('disabled', padOptions.showChat === false);
if ($('select').niceSelect) $('select').niceSelect('update');
},
refreshMyViewControls: () => {
const effectiveOptions = pad.getEffectivePadOptions();
const disabled = pad.isPadSettingsEnforcedForMe();
$('#options-disablechat').prop('checked', effectiveOptions.showChat === false);
$('#options-stickychat').prop('checked', !!effectiveOptions.alwaysShowChat);
$('#options-chatandusers').prop('checked', !!effectiveOptions.chatAndUsers);
$('#options-colorscheck').prop('checked', effectiveOptions.view?.showAuthorColors !== false);
$('#options-fadeauthorcheck')
.prop('checked', effectiveOptions.view?.fadeInactiveAuthorColors !== false);
$('#options-linenoscheck').prop('checked', effectiveOptions.view?.showLineNumbers !== false);
$('#options-rtlcheck').prop('checked', !!effectiveOptions.view?.rtlIsTrue);
$('#viewfontmenu').val(effectiveOptions.view?.padFontFamily || '');
// Fall back to the detected language rather than hardcoded English when the
// user has not explicitly chosen one, so the dropdown matches the rendered
// UI language. See #7925.
$('#languagemenu').val(effectiveOptions.lang || html10n.getLanguage() || 'en');
$('#settings input[id^="options-"]').prop('disabled', disabled);
$('#viewfontmenu, #languagemenu').prop('disabled', disabled);
$('#options-stickychat, #options-chatandusers')
.prop('disabled', disabled || effectiveOptions.showChat === false);
$('#enforce-settings-notice').prop('hidden', !disabled);
if ($('select').niceSelect) $('select').niceSelect('update');
},
setMyViewOption: (key, value) => {
switch (key) {
case 'showChat':
padcookie.setPref('showChat', value);
if (!value) {
padcookie.setPref('chatAlwaysVisible', false);
padcookie.setPref('chatAndUsers', false);
}
break;
case 'alwaysShowChat':
padcookie.setPref('chatAlwaysVisible', value);
if (value) padcookie.setPref('showChat', true);
break;
case 'chatAndUsers':
padcookie.setPref('chatAndUsers', value);
if (value) padcookie.setPref('chatAlwaysVisible', true);
if (value) padcookie.setPref('showChat', true);
break;
case 'showAuthorColors':
padcookie.setPref('showAuthorshipColors', value);
break;
default:
padcookie.setPref(key, value);
break;
}
pad.refreshMyViewControls();
pad.applyOptionsChange();
},
setMyViewLanguage: (lang) => {
const cp = (window as any).clientVars?.cookiePrefix || '';
Cookies.set(`${cp}language`, lang);
pad.refreshMyViewControls();
pad.applyOptionsChange();
},
applyShowChat: (enabled) => {
settings.hideChat = !enabled;
if (enabled) {
if (!window.clientVars.readonly) $('#chaticon').show();
} else {
$('#users, .sticky-container').removeClass('chatAndUsers popup-show stickyUsers');
$('#chatbox').removeClass('chatAndUsersChat stickyChat visible').hide();
$('#options-stickychat, #options-chatandusers').prop('checked', false);
$('#chaticon').hide();
}
},
applyStickyChat: (enabled) => {
const isSticky = $('#chatbox').hasClass('stickyChat');
$('#options-stickychat').prop('checked', enabled);
if (enabled !== isSticky) chat.stickToScreen(enabled, false);
if (!enabled) $('#options-stickychat').prop('disabled', false);
},
applyChatAndUsers: (enabled) => {
const isEnabled = $('#users').hasClass('chatAndUsers');
$('#options-chatandusers').prop('checked', enabled);
if (enabled !== isEnabled) chat.chatAndUsers(enabled, false);
if (!enabled) $('#options-stickychat').prop('disabled', false);
},
applyLanguage: (lang) => {
html10n.localize([lang, 'en']);
$('#languagemenu').val(lang);
if ($('select').niceSelect) $('select').niceSelect('update');
},
init() {
padutils.setupGlobalExceptionHandler();
// $(handler), $().ready(handler), $.wait($.ready).then(handler), etc. don't work if handler is
// an async function for some bizarre reason, so the async function is wrapped in a non-async
// function.
$(() => (async () => {
if (window.customStart != null) window.customStart();
$('#colorpicker').farbtastic({callback: '#mycolorpickerpreview', width: 220});
$('#readonlyinput').on('click', () => { padeditbar.setEmbedLinks(); });
padcookie.init();
padMode.init();
await handshake();
this._afterHandshake();
})());
},
_afterHandshake() {
pad.clientTimeOffset = Date.now() - clientVars.serverTimestamp;
// initialize the chat
chat.init(this);
getParams();
padcookie.init(); // initialize the cookies
pad.initTime = +(new Date());
pad.padOptions = clientVars.initialOptions;
pad.myUserInfo = {
userId: clientVars.userId,
name: clientVars.userName,
ip: pad.getClientIp(),
colorId: clientVars.userColor,
};
const postAceInit = () => {
padeditbar.init();
// Skip link (a11y, ether/etherpad#7255): href="#editorcontainer" gives
// a working no-JS fallback, but the real focus target is the inner
// contenteditable inside two nested iframes — route through ace_focus.
$('#skip-to-content').on('click', (e) => {
e.preventDefault();
padeditor.ace.focus();
});
// Auto-focusing the editor on load traps Tab inside the editor iframe
// (Tab inserts an indent there, not bubbling out), which makes the
// skip link above unreachable via Tab from the URL bar — i.e., the
// standard WCAG 2.4.1 entry path. Users now click or Tab into the
// editor; the skip link is the first tabbable element.
pad.refreshPadSettingsControls();
pad.applyOptionsChange();
pad.refreshMyViewControls();
// The following view overrides MUST run inside postAceInit (after
// padeditor.init resolves), not in the synchronous tail of
// _afterHandshake. Running them sync queues a setProperty in the
// Ace2Editor pending-init queue; the queue is flushed when ace
// finishes loading, but padeditor.init's own
// setViewOptions(initialViewOptions) call runs immediately *after*
// that flush and clobbers the URL-driven value. See #7464 for the
// RTL incarnation of this race (now generalised here for #7840).
if (settings.rtlIsExplicit) {
// URL or server config explicitly set RTL — takes priority over cookie
pad.changeViewOption('rtlIsTrue', settings.rtlIsTrue === true);
}
if (settings.LineNumbersDisabled === true) {
pad.changeViewOption('showLineNumbers', false);
}
if (settings.noColors === true) {
pad.changeViewOption('noColors', true);
}
if (settings.useMonospaceFontGlobal === true) {
pad.changeViewOption('padFontFamily', 'RobotoMono');
}
// Prevent sticky chat or chat and users to be checked for mobiles
const checkChatAndUsersVisibility = (x) => {
if (x.matches) { // If media query matches
$('#options-chatandusers:checked').trigger('click');
$('#options-stickychat:checked').trigger('click');
}
};
const mobileMatch = window.matchMedia('(max-width: 800px)');
mobileMatch.addListener(checkChatAndUsersVisibility); // check if window resized
setTimeout(() => { checkChatAndUsersVisibility(mobileMatch); }, 0); // check now after load
$('#editorcontainer').addClass('initialized');
if (window.location.hash.toLowerCase() !== '#skinvariantsbuilder' && window.clientVars.enableDarkMode && (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) && !skinVariants.isWhiteModeEnabledInLocalStorage()) {
skinVariants.updateSkinVariantsClasses(['super-dark-editor', 'dark-background', 'super-dark-toolbar']);
}
if (window.clientVars.enableDarkMode) {
$('#theme-toggle-row').prop('hidden', false);
$('#options-darkmode').prop('checked', skinVariants.isDarkMode());
}
showDeletionTokenModalIfPresent();
showPrivacyBannerIfEnabled((clientVars as any).privacyBanner);
void maybeShowOutdatedNotice();
hooks.aCallAll('postAceInit', {ace: padeditor.ace, clientVars, pad});
};
// order of inits is important here:
padimpexp.init(this);
padsavedrevs.init(this);
padeditor.init(pad.getEffectivePadOptions().view || {}, this).then(postAceInit);
paduserlist.init(pad.myUserInfo, this);
padconnectionstatus.init();
padmodals.init(this);
pad.collabClient = getCollabClient(
padeditor.ace, clientVars.collab_client_vars, pad.myUserInfo,
{colorPalette: pad.getColorPalette()}, pad);
this._messageQ.setCollabClient(this.collabClient);
pad.collabClient.setOnUserJoin(pad.handleUserJoin);
pad.collabClient.setOnUpdateUserInfo(pad.handleUserUpdate);
pad.collabClient.setOnUserLeave(pad.handleUserLeave);
pad.collabClient.setOnClientMessage(pad.handleClientMessage);
pad.collabClient.setOnChannelStateChange(pad.handleChannelStateChange);
pad.collabClient.setOnInternalAction(pad.handleCollabAction);
// load initial chat-messages
if (clientVars.chatHead !== -1) {
const chatHead = clientVars.chatHead;
const start = Math.max(chatHead - 100, 0);
pad.collabClient.sendMessage({type: 'GET_CHAT_MESSAGES', start, end: chatHead});
} else {
// there are no messages
$('#chatloadmessagesbutton').css('display', 'none');
}
if (window.clientVars.readonly) {
chat.hide();
$('#myusernameedit').attr('disabled', true);
$('#chatinput').attr('disabled', true);
$('#chaticon').hide();
$('#options-chatandusers').parent().hide();
$('#options-stickychat').parent().hide();
// The right-side toolbar stays visible on readonly pads. The
// server-side `toolbar.menu(buttons, isReadOnly)` (see
// src/node/utils/toolbar.ts) already strips `savedrevision`, and
// `.readonly .acl-write { display: none }` hides the Import column
// inside the import/export popup, so the remaining controls
// (export, timeslider, settings, embed, home, showusers) are all
// safe for readonly viewers — and the userlist is the surface that
// plugins like ep_guest hang their "Log In" button off, so hiding
// it traps guests in readonly with no way out. Iframe-embed use
// cases that want a clean look (issue #5182) opt in to the hide
// via `?showMenuRight=false`, or hide the whole editbar via
// `?showControls=false`.
} else if (!settings.hideChat) { $('#chaticon').show(); }
$('body').addClass(window.clientVars.readonly ? 'readonly' : 'readwrite');
padeditor.ace.callWithAce((ace) => {
ace.ace_setEditable(!window.clientVars.readonly);
});
// if the globalUserName value is set we need to tell the server and
// the client about the new authorname
if (settings.globalUserName !== false) {
this.notifyChangeName(settings.globalUserName); // Notifies the server
this.myUserInfo.name = settings.globalUserName;
$('#myusernameedit').val(settings.globalUserName); // Updates the current users UI
}
if (settings.globalUserColor !== false && colorutils.isCssHex(settings.globalUserColor)) {
// Add a 'globalUserColor' property to myUserInfo,
// so collabClient knows we have a query parameter.
this.myUserInfo.globalUserColor = settings.globalUserColor;
this.notifyChangeColor(settings.globalUserColor); // Updates this.myUserInfo.colorId
paduserlist.setMyUserInfo(this.myUserInfo);
}
},
dispose: () => {
padeditor.dispose();
},
notifyChangeName: (newName) => {
pad.myUserInfo.name = newName;
pad.collabClient.updateUserInfo(pad.myUserInfo);
},
notifyChangeColor: (newColorId) => {
pad.myUserInfo.colorId = newColorId;
pad.collabClient.updateUserInfo(pad.myUserInfo);
},
changePadOption: (key, value) => {
const options = {};
options[key] = value;
pad.applyPadSettings(options);
pad.collabClient.sendClientMessage(
{
type: 'padoptions',
options,
changedBy: pad.myUserInfo.name || 'unnamed',
});
},
changePadViewOption: (key, value) => {
const options = {
view: {},
};
options.view[key] = value;
pad.applyPadSettings(options);
pad.collabClient.sendClientMessage(
{
type: 'padoptions',
options,
changedBy: pad.myUserInfo.name || 'unnamed',
});
// The pad creator is never "enforced upon themselves", so their personal
// view overrides (cookies) are always merged on top of the pad-wide value
// in getEffectivePadOptions. A stale personal pref would therefore mask the
// pad-wide value they just set, making the control appear to do nothing
// (#7900). Sync the creator's personal pref to the value they chose so
// their own view adopts it immediately. They can still override it
// afterwards via the "My view" controls.
pad.setMyViewOption(key, value);
},
changeViewOption: (key, value) => {
const effectiveOptions = pad.getEffectivePadOptions();
if (!effectiveOptions.view) effectiveOptions.view = {};
effectiveOptions.view[key] = value;
padeditor.setViewOptions(effectiveOptions.view);
},
applyPadSettings: (opts = {}) => {
// opts object is a full set of options or just
// some options to change
for (const key of ['enforceSettings', 'showChat', 'alwaysShowChat', 'chatAndUsers', 'lang']) {
if (opts[key] == null) continue;
pad.padOptions[key] = key === 'lang' ? opts[key] : `${opts[key]}` === 'true';
}
if (opts.view) {
if (!pad.padOptions.view) {
pad.padOptions.view = {};
}
for (const [k, v] of Object.entries(opts.view)) {
pad.padOptions.view[k] = v;
}
}
// Plugin-namespaced keys (ep_*) are passed through verbatim so plugins
// can ride the existing padoptions broadcast/persist rail. Gated on
// settings.enablePluginPadOptions (mirrored to clientVars by
// getPublicSettings). Server-side normalizePadSettings preserves the
// same keys symmetrically.
if (clientVars.enablePluginPadOptions) {
for (const [k, v] of Object.entries(opts)) {
if (/^ep_[a-z0-9_]+$/.test(k)) pad.padOptions[k] = v;
}
}
normalizeChatOptions(pad.padOptions);
pad.refreshPadSettingsControls();
pad.applyOptionsChange();
},
applyOptionsChange: () => {
const effectiveOptions = pad.getEffectivePadOptions();
padeditor.setViewOptions(effectiveOptions.view || {});
pad.applyShowChat(effectiveOptions.showChat !== false);
if (effectiveOptions.showChat !== false) {
if (effectiveOptions.lang) pad.applyLanguage(effectiveOptions.lang);
pad.applyChatAndUsers(!!effectiveOptions.chatAndUsers);
if (!effectiveOptions.chatAndUsers) pad.applyStickyChat(!!effectiveOptions.alwaysShowChat);
}
pad.refreshMyViewControls();
},
handleOptionsChange: (opts) => {
pad.applyPadSettings(opts);
},
// caller shouldn't mutate the object
getPadOptions: () => pad.padOptions,
suggestUserName: (userId, name) => {
pad.collabClient.sendClientMessage(
{
type: 'suggestUserName',
unnamedId: userId,
newName: name,
});
},
handleUserJoin: (userInfo) => {
paduserlist.userJoinOrUpdate(userInfo);
},
handleUserUpdate: (userInfo) => {
paduserlist.userJoinOrUpdate(userInfo);
},
handleUserLeave: (userInfo) => {
paduserlist.userLeave(userInfo);
},
handleClientMessage: (msg) => {
if (msg.type === 'suggestUserName') {
if (msg.unnamedId === pad.myUserInfo.userId && msg.newName && !pad.myUserInfo.name) {
pad.notifyChangeName(msg.newName);
paduserlist.setMyUserInfo(pad.myUserInfo);
}
} else if (msg.type === 'newRevisionList') {
padsavedrevs.newRevisionList(msg.revisionList);
} else if (msg.type === 'revisionLabel') {