| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- /**
- * GROWI agent for HackMD
- *
- * This file will be transpiled as a single JS
- * and should be load from HackMD head via 'lib/routes/hackmd.js' route
- *
- * USAGE:
- * <script src="${hostname of GROWI}/_hackmd/load-agent"></script>
- *
- * @author Yuki Takei <yuki@weseek.co.jp>
- */
- import { debounce } from 'throttle-debounce';
- const JSON = window.JSON;
- /* eslint-disable no-console */
- const allowedOrigin = '{{origin}}'; // will be replaced by swig
- const styleFilePath = '{{styleFilePath}}'; // will be replaced by swig
- /**
- * Validate origin
- * @param {object} event
- */
- function validateOrigin(event) {
- if (event.origin !== allowedOrigin) {
- console.error('[HackMD] Message is rejected.', 'Cause: "event.origin" and "allowedOrigin" does not match');
- return;
- }
- }
- /**
- * Insert link tag to load style file
- */
- function insertStyle() {
- const element = document.createElement('link');
- element.href = styleFilePath;
- element.rel = 'stylesheet';
- document.getElementsByTagName('head')[0].appendChild(element);
- }
- function postMessageOnSave(body) {
- const data = {
- operation: 'notifyBodyChanges',
- body
- };
- window.parent.postMessage(JSON.stringify(data), allowedOrigin);
- }
- function addEventListenersToCodemirror() {
- // get CodeMirror instance
- const editor = window.editor;
- // generate debounced function
- const debouncedFunc = debounce(1500, postMessageOnSave);
- editor.on('change', (cm, change) => {
- debouncedFunc(cm.doc.getValue());
- });
- }
- function setValue(document) {
- // get CodeMirror instance
- const editor = window.editor;
- editor.doc.setValue(document);
- }
- /**
- * main
- */
- (function() {
- // check HackMD is in iframe
- if (window === window.parent) {
- console.log('[GROWI] Loading agent for HackMD is not processed because currently not in iframe');
- return;
- }
- console.log('[HackMD] Loading GROWI agent for HackMD...');
- insertStyle();
- // Add event listeners
- window.addEventListener('message', (event) => {
- validateOrigin(event);
- const data = JSON.parse(event.data);
- switch (data.operation) {
- case 'getValue':
- console.log('getValue called');
- break;
- case 'setValue':
- setValue(data.document);
- break;
- }
- });
- window.addEventListener('load', (event) => {
- console.log('loaded');
- addEventListenersToCodemirror();
- });
- console.log('[HackMD] GROWI agent for HackMD has successfully loaded.');
- }());
|