placeholder.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. (function(mod) {
  4. if (typeof exports == "object" && typeof module == "object") // CommonJS
  5. mod(require("../../lib/codemirror"));
  6. else if (typeof define == "function" && define.amd) // AMD
  7. define(["../../lib/codemirror"], mod);
  8. else // Plain browser env
  9. mod(CodeMirror);
  10. })(function(CodeMirror) {
  11. CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
  12. var prev = old && old != CodeMirror.Init;
  13. if (val && !prev) {
  14. cm.on("blur", onBlur);
  15. cm.on("change", onChange);
  16. cm.on("swapDoc", onChange);
  17. onChange(cm);
  18. } else if (!val && prev) {
  19. cm.off("blur", onBlur);
  20. cm.off("change", onChange);
  21. cm.off("swapDoc", onChange);
  22. clearPlaceholder(cm);
  23. var wrapper = cm.getWrapperElement();
  24. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
  25. }
  26. if (val && !cm.hasFocus()) onBlur(cm);
  27. });
  28. function clearPlaceholder(cm) {
  29. if (cm.state.placeholder) {
  30. cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
  31. cm.state.placeholder = null;
  32. }
  33. }
  34. function setPlaceholder(cm) {
  35. clearPlaceholder(cm);
  36. var elt = cm.state.placeholder = document.createElement("pre");
  37. elt.style.cssText = "height: 0; overflow: visible";
  38. elt.style.direction = cm.getOption("direction");
  39. elt.className = "CodeMirror-placeholder";
  40. var placeHolder = cm.getOption("placeholder")
  41. if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)
  42. elt.appendChild(placeHolder)
  43. cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
  44. }
  45. function onBlur(cm) {
  46. if (isEmpty(cm)) setPlaceholder(cm);
  47. }
  48. function onChange(cm) {
  49. var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
  50. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
  51. if (empty) setPlaceholder(cm);
  52. else clearPlaceholder(cm);
  53. }
  54. function isEmpty(cm) {
  55. return (cm.lineCount() === 1) && (cm.getLine(0) === "");
  56. }
  57. });