agent-for-hackmd.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * GROWI agent for HackMD
  3. *
  4. * This file will be transpiled as a single JS
  5. * and should be load from HackMD head via 'lib/routes/hackmd.js' route
  6. *
  7. * USAGE:
  8. * <script src="${hostname of GROWI}/_hackmd/load-agent"></script>
  9. *
  10. * @author Yuki Takei <yuki@weseek.co.jp>
  11. */
  12. import { debounce } from 'throttle-debounce';
  13. /* eslint-disable no-console */
  14. const allowedOrigin = '{{origin}}'; // will be replaced by swig
  15. const styleFilePath = '{{styleFilePath}}'; // will be replaced by swig
  16. /**
  17. * Validate origin
  18. * @param {object} event
  19. */
  20. function validateOrigin(event) {
  21. if (event.origin !== allowedOrigin) {
  22. console.error('[HackMD] Message is rejected.', 'Cause: "event.origin" and "allowedOrigin" does not match');
  23. return;
  24. }
  25. }
  26. /**
  27. * Insert link tag to load style file
  28. */
  29. function insertStyle() {
  30. const element = document.createElement('link');
  31. element.href = styleFilePath;
  32. element.rel = 'stylesheet';
  33. document.getElementsByTagName('head')[0].appendChild(element);
  34. }
  35. function postMessageOnSave() {
  36. const data = '{ "operation": "notifyBodyChanges" }';
  37. window.parent.postMessage(data, allowedOrigin);
  38. }
  39. function addEventListenersToCodemirror() {
  40. // get CodeMirror instance
  41. const editor = window.editor;
  42. // generate debounced function
  43. const debouncedFunc = debounce(1500, postMessageOnSave);
  44. editor.on('change', (cm, change) => {
  45. debouncedFunc();
  46. });
  47. }
  48. /**
  49. * main
  50. */
  51. (function() {
  52. // check HackMD is in iframe
  53. if (window === window.parent) {
  54. console.log('[GROWI] Loading agent for HackMD is not processed because currently not in iframe');
  55. return;
  56. }
  57. console.log('[HackMD] Loading GROWI agent for HackMD...');
  58. insertStyle();
  59. // Add event listeners
  60. window.addEventListener('message', (event) => {
  61. validateOrigin(event);
  62. const data = JSON.parse(event.data);
  63. switch (data.operation) {
  64. case 'getValue':
  65. console.log('getValue called');
  66. break;
  67. case 'setValue':
  68. console.log('setValue called');
  69. break;
  70. }
  71. });
  72. window.addEventListener('load', (event) => {
  73. console.log('loaded');
  74. addEventListenersToCodemirror();
  75. });
  76. console.log('[HackMD] GROWI agent for HackMD has successfully loaded.');
  77. }());