您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

751 行
26KB

  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. // Glue code between CodeMirror and Tern.
  4. //
  5. // Create a CodeMirror.TernServer to wrap an actual Tern server,
  6. // register open documents (CodeMirror.Doc instances) with it, and
  7. // call its methods to activate the assisting functions that Tern
  8. // provides.
  9. //
  10. // Options supported (all optional):
  11. // * defs: An array of JSON definition data structures.
  12. // * plugins: An object mapping plugin names to configuration
  13. // options.
  14. // * getFile: A function(name, c) that can be used to access files in
  15. // the project that haven't been loaded yet. Simply do c(null) to
  16. // indicate that a file is not available.
  17. // * fileFilter: A function(value, docName, doc) that will be applied
  18. // to documents before passing them on to Tern.
  19. // * switchToDoc: A function(name, doc) that should, when providing a
  20. // multi-file view, switch the view or focus to the named file.
  21. // * showError: A function(editor, message) that can be used to
  22. // override the way errors are displayed.
  23. // * completionTip: Customize the content in tooltips for completions.
  24. // Is passed a single argument—the completion's data as returned by
  25. // Tern—and may return a string, DOM node, or null to indicate that
  26. // no tip should be shown. By default the docstring is shown.
  27. // * typeTip: Like completionTip, but for the tooltips shown for type
  28. // queries.
  29. // * responseFilter: A function(doc, query, request, error, data) that
  30. // will be applied to the Tern responses before treating them
  31. //
  32. //
  33. // It is possible to run the Tern server in a web worker by specifying
  34. // these additional options:
  35. // * useWorker: Set to true to enable web worker mode. You'll probably
  36. // want to feature detect the actual value you use here, for example
  37. // !!window.Worker.
  38. // * workerScript: The main script of the worker. Point this to
  39. // wherever you are hosting worker.js from this directory.
  40. // * workerDeps: An array of paths pointing (relative to workerScript)
  41. // to the Acorn and Tern libraries and any Tern plugins you want to
  42. // load. Or, if you minified those into a single script and included
  43. // them in the workerScript, simply leave this undefined.
  44. (function(mod) {
  45. if (typeof exports == "object" && typeof module == "object") // CommonJS
  46. mod(require("../../lib/codemirror"));
  47. else if (typeof define == "function" && define.amd) // AMD
  48. define(["../../lib/codemirror"], mod);
  49. else // Plain browser env
  50. mod(CodeMirror);
  51. })(function(CodeMirror) {
  52. "use strict";
  53. // declare global: tern
  54. CodeMirror.TernServer = function(options) {
  55. var self = this;
  56. this.options = options || {};
  57. var plugins = this.options.plugins || (this.options.plugins = {});
  58. if (!plugins.doc_comment) plugins.doc_comment = true;
  59. this.docs = Object.create(null);
  60. if (this.options.useWorker) {
  61. this.server = new WorkerServer(this);
  62. } else {
  63. this.server = new tern.Server({
  64. getFile: function(name, c) { return getFile(self, name, c); },
  65. async: true,
  66. defs: this.options.defs || [],
  67. plugins: plugins
  68. });
  69. }
  70. this.trackChange = function(doc, change) { trackChange(self, doc, change); };
  71. this.cachedArgHints = null;
  72. this.activeArgHints = null;
  73. this.jumpStack = [];
  74. this.getHint = function(cm, c) { return hint(self, cm, c); };
  75. this.getHint.async = true;
  76. };
  77. CodeMirror.TernServer.prototype = {
  78. addDoc: function(name, doc) {
  79. var data = {doc: doc, name: name, changed: null};
  80. this.server.addFile(name, docValue(this, data));
  81. CodeMirror.on(doc, "change", this.trackChange);
  82. return this.docs[name] = data;
  83. },
  84. delDoc: function(id) {
  85. var found = resolveDoc(this, id);
  86. if (!found) return;
  87. CodeMirror.off(found.doc, "change", this.trackChange);
  88. delete this.docs[found.name];
  89. this.server.delFile(found.name);
  90. },
  91. hideDoc: function(id) {
  92. closeArgHints(this);
  93. var found = resolveDoc(this, id);
  94. if (found && found.changed) sendDoc(this, found);
  95. },
  96. complete: function(cm) {
  97. cm.showHint({hint: this.getHint});
  98. },
  99. showType: function(cm, pos, c) { showContextInfo(this, cm, pos, "type", c); },
  100. showDocs: function(cm, pos, c) { showContextInfo(this, cm, pos, "documentation", c); },
  101. updateArgHints: function(cm) { updateArgHints(this, cm); },
  102. jumpToDef: function(cm) { jumpToDef(this, cm); },
  103. jumpBack: function(cm) { jumpBack(this, cm); },
  104. rename: function(cm) { rename(this, cm); },
  105. selectName: function(cm) { selectName(this, cm); },
  106. request: function (cm, query, c, pos) {
  107. var self = this;
  108. var doc = findDoc(this, cm.getDoc());
  109. var request = buildRequest(this, doc, query, pos);
  110. var extraOptions = request.query && this.options.queryOptions && this.options.queryOptions[request.query.type]
  111. if (extraOptions) for (var prop in extraOptions) request.query[prop] = extraOptions[prop];
  112. this.server.request(request, function (error, data) {
  113. if (!error && self.options.responseFilter)
  114. data = self.options.responseFilter(doc, query, request, error, data);
  115. c(error, data);
  116. });
  117. },
  118. destroy: function () {
  119. closeArgHints(this)
  120. if (this.worker) {
  121. this.worker.terminate();
  122. this.worker = null;
  123. }
  124. }
  125. };
  126. var Pos = CodeMirror.Pos;
  127. var cls = "CodeMirror-Tern-";
  128. var bigDoc = 250;
  129. function getFile(ts, name, c) {
  130. var buf = ts.docs[name];
  131. if (buf)
  132. c(docValue(ts, buf));
  133. else if (ts.options.getFile)
  134. ts.options.getFile(name, c);
  135. else
  136. c(null);
  137. }
  138. function findDoc(ts, doc, name) {
  139. for (var n in ts.docs) {
  140. var cur = ts.docs[n];
  141. if (cur.doc == doc) return cur;
  142. }
  143. if (!name) for (var i = 0;; ++i) {
  144. n = "[doc" + (i || "") + "]";
  145. if (!ts.docs[n]) { name = n; break; }
  146. }
  147. return ts.addDoc(name, doc);
  148. }
  149. function resolveDoc(ts, id) {
  150. if (typeof id == "string") return ts.docs[id];
  151. if (id instanceof CodeMirror) id = id.getDoc();
  152. if (id instanceof CodeMirror.Doc) return findDoc(ts, id);
  153. }
  154. function trackChange(ts, doc, change) {
  155. var data = findDoc(ts, doc);
  156. var argHints = ts.cachedArgHints;
  157. if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) >= 0)
  158. ts.cachedArgHints = null;
  159. var changed = data.changed;
  160. if (changed == null)
  161. data.changed = changed = {from: change.from.line, to: change.from.line};
  162. var end = change.from.line + (change.text.length - 1);
  163. if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end);
  164. if (end >= changed.to) changed.to = end + 1;
  165. if (changed.from > change.from.line) changed.from = change.from.line;
  166. if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() {
  167. if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data);
  168. }, 200);
  169. }
  170. function sendDoc(ts, doc) {
  171. ts.server.request({files: [{type: "full", name: doc.name, text: docValue(ts, doc)}]}, function(error) {
  172. if (error) window.console.error(error);
  173. else doc.changed = null;
  174. });
  175. }
  176. // Completion
  177. function hint(ts, cm, c) {
  178. ts.request(cm, {type: "completions", types: true, docs: true, urls: true}, function(error, data) {
  179. if (error) return showError(ts, cm, error);
  180. var completions = [], after = "";
  181. var from = data.start, to = data.end;
  182. if (cm.getRange(Pos(from.line, from.ch - 2), from) == "[\"" &&
  183. cm.getRange(to, Pos(to.line, to.ch + 2)) != "\"]")
  184. after = "\"]";
  185. for (var i = 0; i < data.completions.length; ++i) {
  186. var completion = data.completions[i], className = typeToIcon(completion.type);
  187. if (data.guess) className += " " + cls + "guess";
  188. completions.push({text: completion.name + after,
  189. displayText: completion.displayName || completion.name,
  190. className: className,
  191. data: completion});
  192. }
  193. var obj = {from: from, to: to, list: completions};
  194. var tooltip = null;
  195. CodeMirror.on(obj, "close", function() { remove(tooltip); });
  196. CodeMirror.on(obj, "update", function() { remove(tooltip); });
  197. CodeMirror.on(obj, "select", function(cur, node) {
  198. remove(tooltip);
  199. var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc;
  200. if (content) {
  201. tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset,
  202. node.getBoundingClientRect().top + window.pageYOffset, content, cm, cls + "hint-doc");
  203. }
  204. });
  205. c(obj);
  206. });
  207. }
  208. function typeToIcon(type) {
  209. var suffix;
  210. if (type == "?") suffix = "unknown";
  211. else if (type == "number" || type == "string" || type == "bool") suffix = type;
  212. else if (/^fn\(/.test(type)) suffix = "fn";
  213. else if (/^\[/.test(type)) suffix = "array";
  214. else suffix = "object";
  215. return cls + "completion " + cls + "completion-" + suffix;
  216. }
  217. // Type queries
  218. function showContextInfo(ts, cm, pos, queryName, c) {
  219. ts.request(cm, queryName, function(error, data) {
  220. if (error) return showError(ts, cm, error);
  221. if (ts.options.typeTip) {
  222. var tip = ts.options.typeTip(data);
  223. } else {
  224. var tip = elt("span", null, elt("strong", null, data.type || "not found"));
  225. if (data.doc)
  226. tip.appendChild(document.createTextNode(" — " + data.doc));
  227. if (data.url) {
  228. tip.appendChild(document.createTextNode(" "));
  229. var child = tip.appendChild(elt("a", null, "[docs]"));
  230. child.href = data.url;
  231. child.target = "_blank";
  232. }
  233. }
  234. tempTooltip(cm, tip, ts);
  235. if (c) c();
  236. }, pos);
  237. }
  238. // Maintaining argument hints
  239. function updateArgHints(ts, cm) {
  240. closeArgHints(ts);
  241. if (cm.somethingSelected()) return;
  242. var state = cm.getTokenAt(cm.getCursor()).state;
  243. var inner = CodeMirror.innerMode(cm.getMode(), state);
  244. if (inner.mode.name != "javascript") return;
  245. var lex = inner.state.lexical;
  246. if (lex.info != "call") return;
  247. var ch, argPos = lex.pos || 0, tabSize = cm.getOption("tabSize");
  248. for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {
  249. var str = cm.getLine(line), extra = 0;
  250. for (var pos = 0;;) {
  251. var tab = str.indexOf("\t", pos);
  252. if (tab == -1) break;
  253. extra += tabSize - (tab + extra) % tabSize - 1;
  254. pos = tab + 1;
  255. }
  256. ch = lex.column - extra;
  257. if (str.charAt(ch) == "(") {found = true; break;}
  258. }
  259. if (!found) return;
  260. var start = Pos(line, ch);
  261. var cache = ts.cachedArgHints;
  262. if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0)
  263. return showArgHints(ts, cm, argPos);
  264. ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) {
  265. if (error || !data.type || !(/^fn\(/).test(data.type)) return;
  266. ts.cachedArgHints = {
  267. start: start,
  268. type: parseFnType(data.type),
  269. name: data.exprName || data.name || "fn",
  270. guess: data.guess,
  271. doc: cm.getDoc()
  272. };
  273. showArgHints(ts, cm, argPos);
  274. });
  275. }
  276. function showArgHints(ts, cm, pos) {
  277. closeArgHints(ts);
  278. var cache = ts.cachedArgHints, tp = cache.type;
  279. var tip = elt("span", cache.guess ? cls + "fhint-guess" : null,
  280. elt("span", cls + "fname", cache.name), "(");
  281. for (var i = 0; i < tp.args.length; ++i) {
  282. if (i) tip.appendChild(document.createTextNode(", "));
  283. var arg = tp.args[i];
  284. tip.appendChild(elt("span", cls + "farg" + (i == pos ? " " + cls + "farg-current" : ""), arg.name || "?"));
  285. if (arg.type != "?") {
  286. tip.appendChild(document.createTextNode(":\u00a0"));
  287. tip.appendChild(elt("span", cls + "type", arg.type));
  288. }
  289. }
  290. tip.appendChild(document.createTextNode(tp.rettype ? ") ->\u00a0" : ")"));
  291. if (tp.rettype) tip.appendChild(elt("span", cls + "type", tp.rettype));
  292. var place = cm.cursorCoords(null, "page");
  293. var tooltip = ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip, cm)
  294. setTimeout(function() {
  295. tooltip.clear = onEditorActivity(cm, function() {
  296. if (ts.activeArgHints == tooltip) closeArgHints(ts) })
  297. }, 20)
  298. }
  299. function parseFnType(text) {
  300. var args = [], pos = 3;
  301. function skipMatching(upto) {
  302. var depth = 0, start = pos;
  303. for (;;) {
  304. var next = text.charAt(pos);
  305. if (upto.test(next) && !depth) return text.slice(start, pos);
  306. if (/[{\[\(]/.test(next)) ++depth;
  307. else if (/[}\]\)]/.test(next)) --depth;
  308. ++pos;
  309. }
  310. }
  311. // Parse arguments
  312. if (text.charAt(pos) != ")") for (;;) {
  313. var name = text.slice(pos).match(/^([^, \(\[\{]+): /);
  314. if (name) {
  315. pos += name[0].length;
  316. name = name[1];
  317. }
  318. args.push({name: name, type: skipMatching(/[\),]/)});
  319. if (text.charAt(pos) == ")") break;
  320. pos += 2;
  321. }
  322. var rettype = text.slice(pos).match(/^\) -> (.*)$/);
  323. return {args: args, rettype: rettype && rettype[1]};
  324. }
  325. // Moving to the definition of something
  326. function jumpToDef(ts, cm) {
  327. function inner(varName) {
  328. var req = {type: "definition", variable: varName || null};
  329. var doc = findDoc(ts, cm.getDoc());
  330. ts.server.request(buildRequest(ts, doc, req), function(error, data) {
  331. if (error) return showError(ts, cm, error);
  332. if (!data.file && data.url) { window.open(data.url); return; }
  333. if (data.file) {
  334. var localDoc = ts.docs[data.file], found;
  335. if (localDoc && (found = findContext(localDoc.doc, data))) {
  336. ts.jumpStack.push({file: doc.name,
  337. start: cm.getCursor("from"),
  338. end: cm.getCursor("to")});
  339. moveTo(ts, doc, localDoc, found.start, found.end);
  340. return;
  341. }
  342. }
  343. showError(ts, cm, "Could not find a definition.");
  344. });
  345. }
  346. if (!atInterestingExpression(cm))
  347. dialog(cm, "Jump to variable", function(name) { if (name) inner(name); });
  348. else
  349. inner();
  350. }
  351. function jumpBack(ts, cm) {
  352. var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file];
  353. if (!doc) return;
  354. moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end);
  355. }
  356. function moveTo(ts, curDoc, doc, start, end) {
  357. doc.doc.setSelection(start, end);
  358. if (curDoc != doc && ts.options.switchToDoc) {
  359. closeArgHints(ts);
  360. ts.options.switchToDoc(doc.name, doc.doc);
  361. }
  362. }
  363. // The {line,ch} representation of positions makes this rather awkward.
  364. function findContext(doc, data) {
  365. var before = data.context.slice(0, data.contextOffset).split("\n");
  366. var startLine = data.start.line - (before.length - 1);
  367. var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length);
  368. var text = doc.getLine(startLine).slice(start.ch);
  369. for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur)
  370. text += "\n" + doc.getLine(cur);
  371. if (text.slice(0, data.context.length) == data.context) return data;
  372. var cursor = doc.getSearchCursor(data.context, 0, false);
  373. var nearest, nearestDist = Infinity;
  374. while (cursor.findNext()) {
  375. var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000;
  376. if (!dist) dist = Math.abs(from.ch - start.ch);
  377. if (dist < nearestDist) { nearest = from; nearestDist = dist; }
  378. }
  379. if (!nearest) return null;
  380. if (before.length == 1)
  381. nearest.ch += before[0].length;
  382. else
  383. nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length);
  384. if (data.start.line == data.end.line)
  385. var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch));
  386. else
  387. var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch);
  388. return {start: nearest, end: end};
  389. }
  390. function atInterestingExpression(cm) {
  391. var pos = cm.getCursor("end"), tok = cm.getTokenAt(pos);
  392. if (tok.start < pos.ch && tok.type == "comment") return false;
  393. return /[\w)\]]/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1));
  394. }
  395. // Variable renaming
  396. function rename(ts, cm) {
  397. var token = cm.getTokenAt(cm.getCursor());
  398. if (!/\w/.test(token.string)) return showError(ts, cm, "Not at a variable");
  399. dialog(cm, "New name for " + token.string, function(newName) {
  400. ts.request(cm, {type: "rename", newName: newName, fullDocs: true}, function(error, data) {
  401. if (error) return showError(ts, cm, error);
  402. applyChanges(ts, data.changes);
  403. });
  404. });
  405. }
  406. function selectName(ts, cm) {
  407. var name = findDoc(ts, cm.doc).name;
  408. ts.request(cm, {type: "refs"}, function(error, data) {
  409. if (error) return showError(ts, cm, error);
  410. var ranges = [], cur = 0;
  411. var curPos = cm.getCursor();
  412. for (var i = 0; i < data.refs.length; i++) {
  413. var ref = data.refs[i];
  414. if (ref.file == name) {
  415. ranges.push({anchor: ref.start, head: ref.end});
  416. if (cmpPos(curPos, ref.start) >= 0 && cmpPos(curPos, ref.end) <= 0)
  417. cur = ranges.length - 1;
  418. }
  419. }
  420. cm.setSelections(ranges, cur);
  421. });
  422. }
  423. var nextChangeOrig = 0;
  424. function applyChanges(ts, changes) {
  425. var perFile = Object.create(null);
  426. for (var i = 0; i < changes.length; ++i) {
  427. var ch = changes[i];
  428. (perFile[ch.file] || (perFile[ch.file] = [])).push(ch);
  429. }
  430. for (var file in perFile) {
  431. var known = ts.docs[file], chs = perFile[file];;
  432. if (!known) continue;
  433. chs.sort(function(a, b) { return cmpPos(b.start, a.start); });
  434. var origin = "*rename" + (++nextChangeOrig);
  435. for (var i = 0; i < chs.length; ++i) {
  436. var ch = chs[i];
  437. known.doc.replaceRange(ch.text, ch.start, ch.end, origin);
  438. }
  439. }
  440. }
  441. // Generic request-building helper
  442. function buildRequest(ts, doc, query, pos) {
  443. var files = [], offsetLines = 0, allowFragments = !query.fullDocs;
  444. if (!allowFragments) delete query.fullDocs;
  445. if (typeof query == "string") query = {type: query};
  446. query.lineCharPositions = true;
  447. if (query.end == null) {
  448. query.end = pos || doc.doc.getCursor("end");
  449. if (doc.doc.somethingSelected())
  450. query.start = doc.doc.getCursor("start");
  451. }
  452. var startPos = query.start || query.end;
  453. if (doc.changed) {
  454. if (doc.doc.lineCount() > bigDoc && allowFragments !== false &&
  455. doc.changed.to - doc.changed.from < 100 &&
  456. doc.changed.from <= startPos.line && doc.changed.to > query.end.line) {
  457. files.push(getFragmentAround(doc, startPos, query.end));
  458. query.file = "#0";
  459. var offsetLines = files[0].offsetLines;
  460. if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch);
  461. query.end = Pos(query.end.line - offsetLines, query.end.ch);
  462. } else {
  463. files.push({type: "full",
  464. name: doc.name,
  465. text: docValue(ts, doc)});
  466. query.file = doc.name;
  467. doc.changed = null;
  468. }
  469. } else {
  470. query.file = doc.name;
  471. }
  472. for (var name in ts.docs) {
  473. var cur = ts.docs[name];
  474. if (cur.changed && cur != doc) {
  475. files.push({type: "full", name: cur.name, text: docValue(ts, cur)});
  476. cur.changed = null;
  477. }
  478. }
  479. return {query: query, files: files};
  480. }
  481. function getFragmentAround(data, start, end) {
  482. var doc = data.doc;
  483. var minIndent = null, minLine = null, endLine, tabSize = 4;
  484. for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) {
  485. var line = doc.getLine(p), fn = line.search(/\bfunction\b/);
  486. if (fn < 0) continue;
  487. var indent = CodeMirror.countColumn(line, null, tabSize);
  488. if (minIndent != null && minIndent <= indent) continue;
  489. minIndent = indent;
  490. minLine = p;
  491. }
  492. if (minLine == null) minLine = min;
  493. var max = Math.min(doc.lastLine(), end.line + 20);
  494. if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize))
  495. endLine = max;
  496. else for (endLine = end.line + 1; endLine < max; ++endLine) {
  497. var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize);
  498. if (indent <= minIndent) break;
  499. }
  500. var from = Pos(minLine, 0);
  501. return {type: "part",
  502. name: data.name,
  503. offsetLines: from.line,
  504. text: doc.getRange(from, Pos(endLine, end.line == endLine ? null : 0))};
  505. }
  506. // Generic utilities
  507. var cmpPos = CodeMirror.cmpPos;
  508. function elt(tagname, cls /*, ... elts*/) {
  509. var e = document.createElement(tagname);
  510. if (cls) e.className = cls;
  511. for (var i = 2; i < arguments.length; ++i) {
  512. var elt = arguments[i];
  513. if (typeof elt == "string") elt = document.createTextNode(elt);
  514. e.appendChild(elt);
  515. }
  516. return e;
  517. }
  518. function dialog(cm, text, f) {
  519. if (cm.openDialog)
  520. cm.openDialog(text + ": <input type=text>", f);
  521. else
  522. f(prompt(text, ""));
  523. }
  524. // Tooltips
  525. function tempTooltip(cm, content, ts) {
  526. if (cm.state.ternTooltip) remove(cm.state.ternTooltip);
  527. var where = cm.cursorCoords();
  528. var tip = cm.state.ternTooltip = makeTooltip(where.right + 1, where.bottom, content, cm);
  529. function maybeClear() {
  530. old = true;
  531. if (!mouseOnTip) clear();
  532. }
  533. function clear() {
  534. cm.state.ternTooltip = null;
  535. if (tip.parentNode) fadeOut(tip)
  536. clearActivity()
  537. }
  538. var mouseOnTip = false, old = false;
  539. CodeMirror.on(tip, "mousemove", function() { mouseOnTip = true; });
  540. CodeMirror.on(tip, "mouseout", function(e) {
  541. var related = e.relatedTarget || e.toElement
  542. if (!related || !CodeMirror.contains(tip, related)) {
  543. if (old) clear();
  544. else mouseOnTip = false;
  545. }
  546. });
  547. setTimeout(maybeClear, ts.options.hintDelay ? ts.options.hintDelay : 1700);
  548. var clearActivity = onEditorActivity(cm, clear)
  549. }
  550. function onEditorActivity(cm, f) {
  551. cm.on("cursorActivity", f)
  552. cm.on("blur", f)
  553. cm.on("scroll", f)
  554. cm.on("setDoc", f)
  555. return function() {
  556. cm.off("cursorActivity", f)
  557. cm.off("blur", f)
  558. cm.off("scroll", f)
  559. cm.off("setDoc", f)
  560. }
  561. }
  562. function makeTooltip(x, y, content, cm, className) {
  563. var node = elt("div", cls + "tooltip" + " " + (className || ""), content);
  564. node.style.left = x + "px";
  565. node.style.top = y + "px";
  566. var container = ((cm.options || {}).hintOptions || {}).container || document.body;
  567. container.appendChild(node);
  568. var pos = cm.cursorCoords();
  569. var winW = window.innerWidth;
  570. var winH = window.innerHeight;
  571. var box = node.getBoundingClientRect();
  572. var hints = document.querySelector(".CodeMirror-hints");
  573. var overlapY = box.bottom - winH;
  574. var overlapX = box.right - winW;
  575. if (hints && overlapX > 0) {
  576. node.style.left = 0;
  577. var box = node.getBoundingClientRect();
  578. node.style.left = (x = x - hints.offsetWidth - box.width) + "px";
  579. overlapX = box.right - winW;
  580. }
  581. if (overlapY > 0) {
  582. var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
  583. if (curTop - height > 0) { // Fits above cursor
  584. node.style.top = (pos.top - height) + "px";
  585. } else if (height > winH) {
  586. node.style.height = (winH - 5) + "px";
  587. node.style.top = (pos.bottom - box.top) + "px";
  588. }
  589. }
  590. if (overlapX > 0) {
  591. if (box.right - box.left > winW) {
  592. node.style.width = (winW - 5) + "px";
  593. overlapX -= (box.right - box.left) - winW;
  594. }
  595. node.style.left = (x - overlapX) + "px";
  596. }
  597. return node;
  598. }
  599. function remove(node) {
  600. var p = node && node.parentNode;
  601. if (p) p.removeChild(node);
  602. }
  603. function fadeOut(tooltip) {
  604. tooltip.style.opacity = "0";
  605. setTimeout(function() { remove(tooltip); }, 1100);
  606. }
  607. function showError(ts, cm, msg) {
  608. if (ts.options.showError)
  609. ts.options.showError(cm, msg);
  610. else
  611. tempTooltip(cm, String(msg), ts);
  612. }
  613. function closeArgHints(ts) {
  614. if (ts.activeArgHints) {
  615. if (ts.activeArgHints.clear) ts.activeArgHints.clear()
  616. remove(ts.activeArgHints)
  617. ts.activeArgHints = null
  618. }
  619. }
  620. function docValue(ts, doc) {
  621. var val = doc.doc.getValue();
  622. if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc);
  623. return val;
  624. }
  625. // Worker wrapper
  626. function WorkerServer(ts) {
  627. var worker = ts.worker = new Worker(ts.options.workerScript);
  628. worker.postMessage({type: "init",
  629. defs: ts.options.defs,
  630. plugins: ts.options.plugins,
  631. scripts: ts.options.workerDeps});
  632. var msgId = 0, pending = {};
  633. function send(data, c) {
  634. if (c) {
  635. data.id = ++msgId;
  636. pending[msgId] = c;
  637. }
  638. worker.postMessage(data);
  639. }
  640. worker.onmessage = function(e) {
  641. var data = e.data;
  642. if (data.type == "getFile") {
  643. getFile(ts, data.name, function(err, text) {
  644. send({type: "getFile", err: String(err), text: text, id: data.id});
  645. });
  646. } else if (data.type == "debug") {
  647. window.console.log(data.message);
  648. } else if (data.id && pending[data.id]) {
  649. pending[data.id](data.err, data.body);
  650. delete pending[data.id];
  651. }
  652. };
  653. worker.onerror = function(e) {
  654. for (var id in pending) pending[id](e);
  655. pending = {};
  656. };
  657. this.addFile = function(name, text) { send({type: "add", name: name, text: text}); };
  658. this.delFile = function(name) { send({type: "del", name: name}); };
  659. this.request = function(body, c) { send({type: "req", body: body}, c); };
  660. }
  661. });