tern.js 22 KB

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