1
0

placeholder.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://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. onChange(cm);
  17. } else if (!val && prev) {
  18. cm.off("blur", onBlur);
  19. cm.off("change", onChange);
  20. clearPlaceholder(cm);
  21. var wrapper = cm.getWrapperElement();
  22. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
  23. }
  24. if (val && !cm.hasFocus()) onBlur(cm);
  25. });
  26. function clearPlaceholder(cm) {
  27. if (cm.state.placeholder) {
  28. cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
  29. cm.state.placeholder = null;
  30. }
  31. }
  32. function setPlaceholder(cm) {
  33. clearPlaceholder(cm);
  34. var elt = cm.state.placeholder = document.createElement("pre");
  35. elt.style.cssText = "height: 0; overflow: visible";
  36. elt.className = "CodeMirror-placeholder";
  37. elt.appendChild(document.createTextNode(cm.getOption("placeholder")));
  38. cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
  39. }
  40. function onBlur(cm) {
  41. if (isEmpty(cm)) setPlaceholder(cm);
  42. }
  43. function onChange(cm) {
  44. var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
  45. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
  46. if (empty) setPlaceholder(cm);
  47. else clearPlaceholder(cm);
  48. }
  49. function isEmpty(cm) {
  50. return (cm.lineCount() === 1) && (cm.getLine(0) === "");
  51. }
  52. });