agent-for-hackmd.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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(body) {
  36. const data = {
  37. operation: 'notifyBodyChanges',
  38. body
  39. };
  40. window.parent.postMessage(window.JSON.stringify(data), allowedOrigin);
  41. }
  42. function addEventListenersToCodemirror() {
  43. // get CodeMirror instance
  44. const editor = window.editor;
  45. // generate debounced function
  46. const debouncedFunc = debounce(1500, postMessageOnSave);
  47. editor.on('change', (cm, change) => {
  48. debouncedFunc(cm.doc.getValue());
  49. });
  50. }
  51. /**
  52. * main
  53. */
  54. (function() {
  55. // check HackMD is in iframe
  56. if (window === window.parent) {
  57. console.log('[GROWI] Loading agent for HackMD is not processed because currently not in iframe');
  58. return;
  59. }
  60. console.log('[HackMD] Loading GROWI agent for HackMD...');
  61. insertStyle();
  62. // Add event listeners
  63. window.addEventListener('message', (event) => {
  64. validateOrigin(event);
  65. const data = JSON.parse(event.data);
  66. switch (data.operation) {
  67. case 'getValue':
  68. console.log('getValue called');
  69. break;
  70. case 'setValue':
  71. console.log('setValue called');
  72. break;
  73. }
  74. });
  75. window.addEventListener('load', (event) => {
  76. console.log('loaded');
  77. addEventListenersToCodemirror();
  78. });
  79. console.log('[HackMD] GROWI agent for HackMD has successfully loaded.');
  80. }());