-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdocs.js
313 lines (265 loc) · 11.9 KB
/
docs.js
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
var docs = docs || {
// The document's unique ID that appears in the address bar.
id: window.location.href.split("/document/d/")[1].split("/")[0],
// The document's user-specified name (may change over time).
get name() {
return $(".docs-title-input-label-inner").text().trim();
},
};
/*********** UTILITIES ***********/
// Helper method to observe changes to a DOM element. Used in the getSelection
// and getCurrentParagraph methods, where we watch the element that Kix puts
// the selection into when you press ctrl+C.
docs.observe = function (el, config, callback, observeOnce) {
observeOnce = (typeof observeOnce !== "undefined") && observeOnce;
var observer = new MutationObserver(function(mutations) {
if (observeOnce) {
observer.disconnect();
}
callback(mutations);
});
observer.observe(el, config);
return observer;
};
// Helper method to translate keys (including a few special/command keys) to
// keyCodes for use with docs.pressKey(keyCode, ...).
docs.codeFromKey = function(key) {
var specialKeys = {
"/": 191, "Escape": 27, "Shift": 16, "Control": 17, "Alt": 18,
"Backspace": 8, " ": 32, "Enter": 13, "Tab": 9, "ArrowLeft": 37,
"ArrowUp": 38, "ArrowRight": 39, "ArrowDown": 40, "Delete": 46
};
if (key in specialKeys) {
return specialKeys[key];
}
return key.charCodeAt(key);
};
/*********** KEYBOARD INTERACTION ***********/
// texttarget is the underlying text editor that Docs uses for catching
// keyboard input, etc.
docs.texttarget = $(".docs-texteventtarget-iframe").contents();
docs.texttarget = docs.texttarget.find("[contenteditable=\"true\"]");
// You can catch user input in the editor by setting docs.keydown to be your
// handler. Key presses generated by Docs+ will be ignored. You should be able
// to use e.key in all modern browsers.
docs.keydown_ = function (e) {
if (e.docs_plus_ || !docs.keydown) {
return;
}
return docs.keydown(e);
};
docs.texttarget.on("keydown", docs.keydown_);
// Simulate a key press.
docs.pressKey = function (keyCode, ctrlKey, shiftKey) {
var el = document.getElementsByClassName("docs-texteventtarget-iframe")[0];
el = el.contentDocument;
var is_command = (keyCode <= 46) || ctrlKey;
var data = {"keyCode": keyCode, "ctrlKey": ctrlKey, "shiftKey": shiftKey};
var key_event;
if (is_command) {
key_event = new KeyboardEvent("keydown", data);
} else {
key_event = new KeyboardEvent("keypress", data);
}
key_event.docs_plus_ = true;
el.dispatchEvent(key_event);
};
// Simulates pressing >= 1 *character* keys. Note that this has very limited
// support, and only really works for letters --- in most cases, you should use
// docs.pasteText. The imagined use case is to replace the charCodeAt
// boilerplate in, eg., docs.pressKey("a".charCodeAt(0)).
docs.pressLetters = function (text, ctrlKey, shiftKey) {
for (var i = 0; i < text.length; i++) {
docs.pressKey(text.charCodeAt(i), ctrlKey, shiftKey);
}
};
// Helper to simulate pressing the backspace key.
docs.backspace = function (counts) {
docs.pressKey(8);
};
// Pastes a block of plaintext into the document. Note that spaces before/after
// @text don't seem to work. Also note that repeated pastes can cause serious
// problems --- please give each paste a few hunderd milliseconds to finish
// before sending another pasteText. See test.js for an example of this.
docs.pasteText = function (text) {
var el = document.getElementsByClassName("docs-texteventtarget-iframe")[0];
el = el.contentDocument.querySelector("[contenteditable=true]");
var data = new DataTransfer();
data.setData("text/plain", text);
var paste = new ClipboardEvent("paste", {
"clipboardData": data,
"data": text,
"dataType": "text/plain"
});
paste.docs_plus_ = true;
el.dispatchEvent(paste);
};
/*********** MOUSE INTERACTION ***********/
docs.pressButton = function (el) {
el.dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
el.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
el.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
el.dispatchEvent(new MouseEvent("click", { bubbles: true }));
el.dispatchEvent(new MouseEvent("mouseleave", { bubbles: true }));
};
/*********** TEXT FORMATTING ***********/
docs.colors = {
"black": "#docs-material-colorpalette-cell-0 > div:nth-child(1)",
"gray": "#docs-material-colorpalette-cell-5 > div:nth-child(1)",
"white": "#docs-material-colorpalette-cell-9 > div:nth-child(1)",
};
// Sets the color of inserted (or selected) text. @color can either be a
// color-palatte DOM element selector or one of the supported color names in
// docs.colors.
docs.setColor = function (color) {
if (color in docs.colors) {
color = docs.colors[color];
}
var sel = $("#textColorButton > div:nth-child(1) > div:nth-child(1)")[0];
// It seems this is all Docs needs.
sel.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
docs.pressButton($(color)[0]);
};
// Toggles whether inserted (selected) text is superscripted or not. Note that
// entering newlines, etc. may disrupt this setting. TODO(matthewsot):
// isSuperscript() method.
docs.toggleSuperscript = function () {
docs.pressKey(190, true, false);
};
// Toggles whether inserted (selected) text is subscripted or not. Note that
// entering newlines, etc. may disrupt this setting. TODO(matthewsot):
// isSubscript() method.
docs.toggleSubscript = function () {
docs.pressKey(188, true, false);
};
// Toggles whether inserted (selected) text is bolded or not. TODO(matthewsot):
// isBold() method.
docs.toggleBold = function () {
docs.pressKey(66, true, false);
};
// Inserts a link with the given text.
docs.insertLink = function (target, text) {
docs.pressButton($("[aria-label='Insert link (Ctrl+K)']")[0]);
$("[aria-label='Paste a link, or search']")[0].value = target;
$(".docs-link-insertlinkbubble-text.jfk-textinput.label-input-label")[0].value = text;
$("[aria-label='Paste a link, or search']")[0].dispatchEvent(new CustomEvent("input"));
docs.pressButton($(".docs-link-insertlinkbubble-buttonbar > div")[0]);
};
/*********** MENU OPTIONS ***********/
docs.undo = function () {
docs.pressButton($("[aria-label='Undo u']")[0]);
};
docs.redo = function () {
docs.pressButton($("[aria-label='Redo r']")[0]);
};
/*********** USER SELECTIONS ***********/
// Gets the raw DOM element corresponding to the user's selection, used by
// docs.hasSelection and docs.getSelection.
docs.getSelectionEl = function () {
var selection = null;
$(".kix-selection-overlay").each(function () {
if (selection !== null) return;
var hasOverriddenColor = $(this).attr("style").indexOf("background-color") !== -1;
var isBlack = $(this).css("background-color").replace(/\s/g, "").replace(/,/g, "");
isBlack = isBlack.indexOf("000") !== -1;
if (!hasOverriddenColor || isBlack) {
selection = $(this);
}
});
return selection;
};
// True iff the user is selecting some text.
docs.hasSelection = function () {
return docs.getSelectionEl() !== null;
};
// callback(text) is called where text is the contents of the user's selection.
// If @defaultToParagraph, empty selections are replaced with the paragraph of
// the user's current selection. getRaw will return the raw HTML selection
// element instead of processed text.
docs.getSelection = function (callback, defaultToParagraph, getRaw) {
defaultToParagraph = typeof defaultToParagraph !== "undefined" && defaultToParagraph;
getRaw = (typeof getRaw !== "undefined" && getRaw);
var anySelection = $(".kix-selection-overlay").length > 0;
if (!anySelection) {
if (defaultToParagraph) {
//If the caller expects a raw element, we need to give it to them
docs.getCurrentParagraphText(getRaw ? function (text) { callback($("<span></span>").text(text)[0]); } : callback);
} else {
callback(getRaw ? $("<span></span>").text("")[0] : "");
}
return;
}
docs.observe($(".docs-texteventtarget-iframe").contents().find("[contenteditable=\"true\"]")[0], {
childList: true
}, function(mutations) {
callback(getRaw ? mutations[0].target : $(mutations[0].target).text().trim());
}, true);
//Send a copy event to get it to update the contents of the div with the current selection
var e = new CustomEvent("copy");
$(".docs-texteventtarget-iframe").contents().find("[contenteditable=\"true\"]")[0].dispatchEvent(e);
};
// callback(text) is called where text is the contents of the current paragraph
// that the user's insertion pointer is on. WILL NOT WORK correctly if
// __docs_plus__ is part of the current paragraph.
docs.getCurrentParagraphText = function(callback) {
//Set up an observer to observe all the paragraphs
var calledAlready = false;
var observer = docs.observe($(".kix-paginateddocumentplugin")[0], {
childList: true,
subtree: true
}, function(mutations) {
mutations.forEach(function(mutation) {
if($(mutation.target).hasClass("kix-lineview-content")) {
observer.disconnect();
if (!calledAlready) {
var cloned = $(mutation.target).closest(".kix-paragraphrenderer").clone();
cloned.find(".goog-inline-block.kix-lineview-text-block").each(function () {
var text = $(this).text().trim().toLowerCase();
var isSimpleBullet = text.length <= 2;
var isParenthBullet = text.length === 3 && text.indexOf("(") === 0 && text.lastIndexOf(")") === 2;
var isIIBullet = text.indexOf(".") === (text.length - 1) && (text.match(/i/g) || []).length === text.length - 1;
var isNumDotBullet = text.indexOf(".") === (text.length - 1) && (text.match(/\d/g) || []).length === text.length - 1;
if ($(this).parent().css("padding-left") === "0px" && (isSimpleBullet || isParenthBullet || isIIBullet || isNumDotBullet)) {
$(this).remove(); //It's a dot/#/letter bullet for the list
}
});
var rawText = cloned.text().replace(/\s/g, " ").trim();
rawText = rawText.replace("__docs_plus__", "");
for (var i = 0; i < "__docs_plus__".length; i++) {
docs.backspace();
}
callback(rawText);
}
calledAlready = true;
}
});
});
docs.pasteText("__docs_plus__");
};
/*********** USER CURSOR ***********/
// Gets the DOM element corresponding to the user's insertion point marker.
docs.getUserCursor = function () {
var myCursor = null;
$(".kix-cursor").each(function () {
var caretColor = $(this).find(".kix-cursor-caret");
caretColor = caretColor.css("border-left-color").replace(/,/g, "");
caretColor = caretColor.replace(/\s/g, "").toLowerCase();
var isCaretBlack = (caretColor.indexOf("(000)") !== -1 ||
caretColor.indexOf("#000") !== -1 ||
caretColor.indexOf("black") !== -1);
var cursor_name = $(this).find(".kix-cursor-name").text().trim();
if (cursor_name.length <= 0 && isCaretBlack) {
myCursor = $(this);
}
});
if (myCursor !== null) {
return myCursor;
}
console.log("Couldn't locate the cursor!");
return $(".kix-cursor").first();
};
// Sets the width of the user's insertion point marker. @width should be a
// width value compatible with CSS border-width: @width;
docs.setCursorWidth = function(width) {
docs.getUserCursor().find(".kix-cursor-caret").css("border-width", width);
};