1
0

placeholder.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. (function() {
  2. CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
  3. var prev = old && old != CodeMirror.Init;
  4. if (val && !prev) {
  5. cm.on("focus", onFocus);
  6. cm.on("blur", onBlur);
  7. cm.on("change", onChange);
  8. onChange(cm);
  9. } else if (!val && prev) {
  10. cm.off("focus", onFocus);
  11. cm.off("blur", onBlur);
  12. cm.off("change", onChange);
  13. clearPlaceholder(cm);
  14. var wrapper = cm.getWrapperElement();
  15. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
  16. }
  17. if (val && !cm.hasFocus()) onBlur(cm);
  18. });
  19. function clearPlaceholder(cm) {
  20. if (cm.state.placeholder) {
  21. cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
  22. cm.state.placeholder = null;
  23. }
  24. }
  25. function setPlaceholder(cm) {
  26. clearPlaceholder(cm);
  27. var elt = cm.state.placeholder = document.createElement("pre");
  28. elt.style.cssText = "height: 0; overflow: visible";
  29. elt.className = "CodeMirror-placeholder";
  30. elt.appendChild(document.createTextNode(cm.getOption("placeholder")));
  31. cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
  32. }
  33. function onFocus(cm) {
  34. clearPlaceholder(cm);
  35. }
  36. function onBlur(cm) {
  37. if (isEmpty(cm)) setPlaceholder(cm);
  38. }
  39. function onChange(cm) {
  40. var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
  41. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
  42. if (cm.hasFocus()) return;
  43. if (empty) setPlaceholder(cm);
  44. else clearPlaceholder(cm);
  45. }
  46. function isEmpty(cm) {
  47. return (cm.lineCount() === 1) && (cm.getLine(0) === "");
  48. }
  49. })();