contentScript.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. (function()
  2. {
  3. // Specifies if images should be changed for dark mode
  4. var convertImages = true;
  5. var backgroundColor = '#2F3437';
  6. var convertAttrib = 'data-drawio-src';
  7. var editor = 'https://embed.diagrams.net/?embedInline=1&libraries=1&configure=1';
  8. //editor = 'https://test.draw.io/?dev=1&embedInline=1&libraries=1&configure=1';
  9. var notionScrollers = document.getElementsByClassName('notion-scroller vertical');
  10. var notionFrames = document.getElementsByClassName('notion-frame');
  11. var dark = document.body.className.includes('dark');
  12. var initialized = false;
  13. var activeImage = null;
  14. var editBlockId = null;
  15. var iframe = document.createElement('iframe');
  16. iframe.style.position = 'absolute';
  17. iframe.style.border = '0';
  18. iframe.style.top = '0px';
  19. iframe.style.left = '0px';
  20. iframe.style.width = '100%';
  21. iframe.style.height = '100%';
  22. iframe.style.zIndex = '4';
  23. function logEvent(data)
  24. {
  25. try
  26. {
  27. var img = new Image();
  28. img.src = 'https://log.draw.io/images/1x1.png?' +
  29. 'data=' + encodeURIComponent(
  30. JSON.stringify(data));
  31. }
  32. catch (e)
  33. {
  34. console.error(e);
  35. }
  36. };
  37. function invertImage(img, done)
  38. {
  39. var req = new XMLHttpRequest();
  40. req.addEventListener('load', function()
  41. {
  42. if (req.status >= 200 && req.status <= 299 && this.responseXML != null)
  43. {
  44. img.src = createSvgDataUri(invertSvg(this.responseXML));
  45. }
  46. done();
  47. });
  48. req.open('GET', img.src);
  49. req.send();
  50. };
  51. function installInverter(img)
  52. {
  53. var busy = false;
  54. img.setAttribute(convertAttrib, img.src);
  55. if (dark)
  56. {
  57. busy = true;
  58. invertImage(img, function()
  59. {
  60. busy = false;
  61. });
  62. }
  63. var mutationObserver = new MutationObserver(function(evt)
  64. {
  65. if (!isSvgDataUri(img.src) && img.src != '' && !busy)
  66. {
  67. if (dark)
  68. {
  69. busy = true;
  70. img.setAttribute(convertAttrib, img.src);
  71. invertImage(img, function()
  72. {
  73. busy = false;
  74. });
  75. }
  76. }
  77. });
  78. mutationObserver.observe(img, {attributes: true});
  79. };
  80. function darkModeChanged()
  81. {
  82. if (activeImage != null)
  83. {
  84. iframe.contentWindow.postMessage(JSON.stringify(
  85. {action: 'exit'}), '*');
  86. }
  87. var imgs = document.getElementsByTagName('img');
  88. for (var i = 0; i < imgs.length; i++)
  89. {
  90. var src = imgs[i].getAttribute(convertAttrib);
  91. if (src != null)
  92. {
  93. if (!isSvgDataUri(imgs[i].src))
  94. {
  95. src = imgs[i].src;
  96. imgs[i].src = '';
  97. imgs[i].src = src;
  98. }
  99. else
  100. {
  101. imgs[i].src = src;
  102. }
  103. }
  104. }
  105. };
  106. function editImage(img, isNew, onChange)
  107. {
  108. iframe.doResize = function(msg)
  109. {
  110. setFullscreen(msg.fullscreen);
  111. img.style.width = msg.rect.width + 'px';
  112. img.style.height = (msg.rect.height - 22) + 'px';
  113. };
  114. var prev = img.parentNode.style.cursor;
  115. img.parentNode.style.cursor = 'wait';
  116. iframe.style.cursor = 'wait';
  117. iframe.doInit = function(errorCode)
  118. {
  119. if (errorCode != null)
  120. {
  121. img.parentNode.style.cursor = prev;
  122. onChange({});
  123. alert('Error ' + errorCode + ': Cannot load editor');
  124. }
  125. else
  126. {
  127. setControlsVisible(img, false);
  128. crossfade(img, iframe);
  129. iframe.style.cursor = '';
  130. img.parentNode.style.cursor = prev;
  131. }
  132. };
  133. iframe.doUpdate = onChange;
  134. startEditor(img, isNew);
  135. };
  136. function startEditor(img, isNew)
  137. {
  138. var req = new XMLHttpRequest();
  139. req.addEventListener('load', function()
  140. {
  141. if (req.status >= 200 && req.status <= 299)
  142. {
  143. try
  144. {
  145. var rect = img.parentNode.getBoundingClientRect();
  146. var r = iframe.parentNode.getBoundingClientRect();
  147. if (rect.y < r.y + 66 || rect.y > iframe.parentNode.scrollTop + r.height)
  148. {
  149. img.scrollIntoView();
  150. iframe.parentNode.scrollTop -= 60
  151. rect = img.parentNode.getBoundingClientRect();
  152. }
  153. var border = 8;
  154. rect.x -= border + 3 + r.x;
  155. rect.y -= border + 3 - iframe.parentNode.scrollTop + r.y;
  156. rect.width += 2 * border + 2;
  157. rect.height = (isNew) ? Math.max(rect.height, 500) : rect.height + 2 * border + 2;
  158. iframe.contentWindow.postMessage(JSON.stringify(
  159. {action: 'load', xml: this.responseText, border: border,
  160. background: '#ffffff', rect: rect, dark: dark,
  161. viewport: getViewport()}), '*');
  162. updateFrame();
  163. logEvent({category: 'NOTION',
  164. action: (isNew) ? 'create' : 'edit',
  165. label: getBlockId(img)});
  166. }
  167. catch (e)
  168. {
  169. iframe.doInit(e.message);
  170. }
  171. }
  172. else
  173. {
  174. iframe.doInit(req.status);
  175. }
  176. });
  177. req.open('GET', img.src);
  178. req.send();
  179. };
  180. function installEditor(img, filename, url)
  181. {
  182. img.parentNode.addEventListener('click', function()
  183. {
  184. if (!initialized)
  185. {
  186. var prev = img.parentNode.style.cursor;
  187. img.parentNode.style.cursor = 'not-allowed';
  188. window.setTimeout(function()
  189. {
  190. img.parentNode.style.cursor = prev;
  191. }, 300);
  192. }
  193. else
  194. {
  195. prepareEditor(img, filename, url);
  196. }
  197. });
  198. };
  199. function editBlock(id)
  200. {
  201. editBlockId = id;
  202. };
  203. function mergeChanges(url)
  204. {
  205. var req = new XMLHttpRequest();
  206. req.addEventListener('load', function()
  207. {
  208. if (req.status >= 200 && req.status <= 299)
  209. {
  210. iframe.contentWindow.postMessage(JSON.stringify({action: 'merge',
  211. xml: this.responseText}), '*');
  212. }
  213. });
  214. req.open('GET', url);
  215. req.send();
  216. };
  217. var lastSnapshot = null;
  218. function prepareEditor(img, filename, url, isNew)
  219. {
  220. if (!iframe.busy)
  221. {
  222. var elt = document.activeElement;
  223. iframe.busy = true;
  224. activeImage = img;
  225. var width = img.style.width;
  226. var height = img.style.height;
  227. var boxSizing = img.style.boxSizing;
  228. // Listens for remote changes
  229. var mutationObserver = new MutationObserver(function(evt)
  230. {
  231. if (!isSvgDataUri(img.src) && url != img.src &&
  232. activeImage == img)
  233. {
  234. url = img.src;
  235. mergeChanges(url);
  236. }
  237. });
  238. mutationObserver.observe(img, {attributes: true});
  239. editImage(img, isNew, function(msg, override)
  240. {
  241. if (msg.data != null && msg.exit != null &&
  242. !msg.exit && !override)
  243. {
  244. lastSnapshot = msg;
  245. }
  246. else
  247. {
  248. var rect = iframe.getBoundingClientRect();
  249. mutationObserver.disconnect();
  250. setFullscreen(false);
  251. img.style.width = width;
  252. img.style.height = height;
  253. img.style.boxSizing = boxSizing;
  254. imageChanged(img, filename, msg.data);
  255. crossfade(iframe, img, function()
  256. {
  257. setControlsVisible(img, true);
  258. iframe.busy = false;
  259. lastSnapshot = null;
  260. activeImage = null;
  261. if (msg != null && msg.point != null)
  262. {
  263. var temp = document.elementFromPoint(rect.x + msg.point.x, rect.y + msg.point.y);
  264. if (temp != null && temp.click != null)
  265. {
  266. elt = temp;
  267. elt.click();
  268. }
  269. }
  270. elt.focus();
  271. });
  272. }
  273. });
  274. }
  275. };
  276. function imageChanged(img, filename, data)
  277. {
  278. if (data != null)
  279. {
  280. var svg = getSvg(data);
  281. replaceDiagram({blockId: getBlockId(img), filename: filename, data: svg}, function(msg)
  282. {
  283. if (msg.error != null)
  284. {
  285. alert('Error ' + msg.errStatus + ': Cannot update diagram');
  286. }
  287. });
  288. if (dark && convertImages)
  289. {
  290. data = createSvgDataUri(invertSvg(new DOMParser().
  291. parseFromString(svg, 'text/xml')));
  292. }
  293. // Restores state and shows preview
  294. img.setAttribute('src', data);
  295. }
  296. iframe.style.width = '100%';
  297. iframe.style.height = '100%';
  298. iframe.doUpdate = null;
  299. iframe.doResize = null;
  300. };
  301. window.addEventListener('message', function(evt)
  302. {
  303. if (evt, evt.source === iframe.contentWindow)
  304. {
  305. var msg = JSON.parse(evt.data);
  306. if (msg.event == 'init')
  307. {
  308. initialized = true;
  309. }
  310. else if (msg.event == 'configure')
  311. {
  312. iframe.contentWindow.postMessage(JSON.stringify({action: 'configure',
  313. config: {
  314. darkColor: backgroundColor,
  315. settingsName: 'notion'
  316. }
  317. }), '*');
  318. }
  319. else if (msg.event == 'load' && iframe.doInit != null)
  320. {
  321. iframe.doInit();
  322. }
  323. else if ((msg.event == 'export' || msg.event == 'exit') &&
  324. iframe.doUpdate != null)
  325. {
  326. iframe.doUpdate(msg);
  327. }
  328. else if (msg.event == 'resize' && iframe.doResize != null)
  329. {
  330. iframe.doResize(msg);
  331. }
  332. }
  333. });
  334. var checked = [];
  335. function updateChecked()
  336. {
  337. var temp = [];
  338. // Forgets old images
  339. for (var i = 0; i < checked.length; i++)
  340. {
  341. if (document.body.contains(checked[i]))
  342. {
  343. temp.push(checked[i]);
  344. }
  345. }
  346. return temp;
  347. };
  348. function checkDiagram(img)
  349. {
  350. var filename = getFilename(img.src);
  351. var result = false;
  352. if (filename.endsWith('.drawio.svg'))
  353. {
  354. installEditor(img, filename, img.src);
  355. if (convertImages)
  356. {
  357. installInverter(img);
  358. }
  359. if (editBlockId != null && getBlockId(img) == editBlockId)
  360. {
  361. editBlockId = null;
  362. prepareEditor(img, filename, img.src, true);
  363. }
  364. result = true;
  365. }
  366. return result;
  367. };
  368. function checkImage(img)
  369. {
  370. if (checked.indexOf(img) < 0)
  371. {
  372. checked.push(img);
  373. if (!checkDiagram(img))
  374. {
  375. var mutationObserver = new MutationObserver(function()
  376. {
  377. if (checkDiagram(img))
  378. {
  379. mutationObserver.disconnect();
  380. }
  381. });
  382. mutationObserver.observe(img, {attributes: true});
  383. }
  384. };
  385. };
  386. function scrollHandler()
  387. {
  388. if (iframe.style.visibility != 'hidden')
  389. {
  390. iframe.contentWindow.postMessage(JSON.stringify(
  391. {action: 'viewport', viewport: getViewport()}), '*');
  392. }
  393. };
  394. // Creates a snapshot in case ppl click off the diagram so that it
  395. // is removed from the DOM (eg, if they click on the background or
  396. // if they click in the navigation).
  397. iframe.addEventListener('mouseleave', function()
  398. {
  399. if (activeImage != null && iframe.contentWindow != null)
  400. {
  401. iframe.contentWindow.postMessage(JSON.stringify(
  402. {action: 'snapshot'}), '*');
  403. }
  404. }, true);
  405. function checkFrame()
  406. {
  407. // Checks if pending snapshot exists
  408. if (iframe.doUpdate != null && lastSnapshot != null &&
  409. !document.body.contains(iframe))
  410. {
  411. iframe.doUpdate(lastSnapshot, true);
  412. }
  413. // Checks if parent node was removed and reinserts editor
  414. // Adding to body would avoid this but doesn't allow
  415. // the iframe to be scrolled with the page content.
  416. // LATER: Can we use cloneNode to avoid this?
  417. if (notionScrollers.length > 0 &&
  418. !notionScrollers[notionScrollers.length - 1].contains(iframe))
  419. {
  420. if (iframe.parentNode != null)
  421. {
  422. iframe.parentNode.removeEventListener('scroll', scrollHandler);
  423. }
  424. initialized = false;
  425. iframe.busy = false;
  426. iframe.style.visibility = 'hidden';
  427. notionScrollers[notionScrollers.length - 1].appendChild(iframe);
  428. iframe.setAttribute('src', editor);
  429. iframe.parentNode.addEventListener('scroll', scrollHandler);
  430. }
  431. };
  432. function checkImages()
  433. {
  434. // Removes old images
  435. // LATER: Move to other listener with fewer invocations
  436. checked = updateChecked();
  437. var imgs = document.getElementsByTagName('img');
  438. for (var i = 0; i < imgs.length; i++)
  439. {
  440. checkImage(imgs[i]);
  441. }
  442. };
  443. function getViewport()
  444. {
  445. var viewport = iframe.parentNode.getBoundingClientRect();
  446. viewport.x = iframe.parentNode.scrollLeft;
  447. viewport.y = iframe.parentNode.scrollTop;
  448. return viewport;
  449. };
  450. function pageChanged()
  451. {
  452. checkFrame();
  453. checkImages();
  454. };
  455. function installDarkModeListener()
  456. {
  457. new MutationObserver(pageChanged).observe(
  458. document.body, {childList: true,
  459. subtree: true});
  460. new MutationObserver(function()
  461. {
  462. var newDark = document.body.className.includes('dark');
  463. if (newDark != dark)
  464. {
  465. dark = newDark;
  466. darkModeChanged();
  467. }
  468. }).observe(document.body, {attributes: true});
  469. }
  470. installDarkModeListener();
  471. window.addEventListener('resize', function()
  472. {
  473. if (iframe.style.visibility != 'hidden')
  474. {
  475. iframe.contentWindow.postMessage(JSON.stringify(
  476. {action: 'viewport', viewport: getViewport()}), '*');
  477. updateFrame();
  478. }
  479. });
  480. var fullscreen = false;
  481. var prevOverflow = null;
  482. function updateFrame()
  483. {
  484. if (fullscreen)
  485. {
  486. var r = notionFrames[0].getBoundingClientRect();
  487. prevOverflow = document.body.style.overflow;
  488. document.body.style.overflow = 'hidden';
  489. iframe.style.position = 'fixed';
  490. iframe.style.top = r.y + 'px';
  491. iframe.style.left = r.x + 'px';
  492. iframe.style.width = r.width + 'px';
  493. iframe.style.height = r.height + 'px';
  494. }
  495. else
  496. {
  497. document.body.style.overflow = prevOverflow;
  498. iframe.style.position = 'absolute';
  499. iframe.style.left = '0px';
  500. iframe.style.top = '0px';
  501. iframe.style.width = iframe.parentNode.clientWidth + 'px';
  502. iframe.style.height = iframe.parentNode.scrollHeight + 'px';
  503. }
  504. };
  505. function setFullscreen(value)
  506. {
  507. if (fullscreen != value)
  508. {
  509. fullscreen = value;
  510. updateFrame();
  511. }
  512. };
  513. function setControlsVisible(img, visible)
  514. {
  515. try
  516. {
  517. // Hides halo
  518. img.parentNode.parentNode.parentNode.parentNode.parentNode.
  519. nextSibling.style.visibility = 'hidden';
  520. iframe.parentNode.nextSibling.style.visibility =
  521. (visible) ? '' : 'hidden';
  522. }
  523. catch (e)
  524. {
  525. // ignore
  526. }
  527. };
  528. function invertSvg(doc)
  529. {
  530. var defs = doc.getElementsByTagName('defs');
  531. var style = doc.createElementNS('http://www.w3.org/2000/svg', 'style');
  532. style.appendChild(doc.createTextNode(
  533. '[stroke="rgb(0, 0, 0)"] {stroke: #f0f0f0}\n' +
  534. '[stroke="rgb(255, 255, 255)"] {stroke: ' + backgroundColor + '}\n' +
  535. '[fill="rgb(0, 0, 0)"] {fill: #f0f0f0}\n' +
  536. '[fill="rgb(255, 255, 255)"] {fill: ' + backgroundColor + '}\n' +
  537. 'g[fill="rgb(0, 0, 0)"] text {fill: #f0f0f0}\n' +
  538. 'div[data-drawio-colors*="color: rgb(0, 0, 0)"] div ' +
  539. '{color: #f0f0f0 !important;}\n' +
  540. 'div[data-drawio-colors*="background-color: rgb(255, 255, 255)"] div ' +
  541. '{background-color: ' + backgroundColor + ' !important;}' +
  542. 'div[data-drawio-colors*="border-color: rgb(0, 0, 0)"] div ' +
  543. '{border-color: #f0f0f0 !important;}' +
  544. 'div[data-drawio-colors*="background-color: rgb(255, 255, 255)"] ' +
  545. '{background-color: ' + backgroundColor + ' !important;}' +
  546. 'div[data-drawio-colors*="border-color: rgb(0, 0, 0)"] ' +
  547. '{border-color: #f0f0f0 !important;}' +
  548. // Invert old rgba output
  549. '[stroke="rgba(0, 0, 0, 1)"] {stroke: #f0f0f0}\n' +
  550. '[stroke="rgba(255, 255, 255, 1)"] {stroke: ' + backgroundColor + '}\n' +
  551. '[fill="rgba(0, 0, 0, 1)"] {fill: #f0f0f0}\n' +
  552. '[fill="rgba(255, 255, 255, 1)"] {fill: ' + backgroundColor + '}\n' +
  553. 'g[fill="rgba(0, 0, 0, 1)"] text {fill: #f0f0f0}\n' +
  554. 'div[data-drawio-colors*="color: rgba(0, 0, 0, 1)"] div ' +
  555. '{color: #f0f0f0 !important;}\n' +
  556. 'div[data-drawio-colors*="background-color: rgba(255, 255, 255, 1)"] div ' +
  557. '{background-color: ' + backgroundColor + ' !important;}' +
  558. 'div[data-drawio-colors*="border-color: rgba(0, 0, 0, 1)"] div ' +
  559. '{border-color: #f0f0f0 !important;}' +
  560. 'div[data-drawio-colors*="background-color: rgba(255, 255, 255, 1)"] ' +
  561. '{background-color: ' + backgroundColor + ' !important;}' +
  562. 'div[data-drawio-colors*="border-color: rgba(0, 0, 0, 1)"] ' +
  563. '{border-color: #f0f0f0 !important;}'));
  564. defs[0].appendChild(style);
  565. if (doc.documentElement.style.backgroundColor == 'rgb(255, 255, 255)')
  566. {
  567. doc.documentElement.style.backgroundColor = backgroundColor;
  568. var g = doc.getElementsByTagName('g');
  569. if (g != null && g.length > 0 && g[0].getAttribute('filter') == 'url(#dropShadow)')
  570. {
  571. g[0].removeAttribute('filter');
  572. }
  573. }
  574. return doc;
  575. };
  576. function isSvgDataUri(url)
  577. {
  578. return url.startsWith('data:image/svg+xml;base64,');
  579. };
  580. function createSvgDataUri(doc)
  581. {
  582. return 'data:image/svg+xml;base64,' +
  583. btoa(unescape(encodeURIComponent(
  584. new XMLSerializer().serializeToString(
  585. doc.documentElement))));
  586. };
  587. function getSvg(data)
  588. {
  589. return '<?xml version="1.0" encoding="UTF-8"?>\n' +
  590. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  591. decodeURIComponent(escape(atob(data.substring(data.indexOf(',') + 1))));
  592. };
  593. function getFilename(url)
  594. {
  595. var tokens = url.split('?')[0].split('/');
  596. var filename = tokens[tokens.length - 1];
  597. if (filename.startsWith('https%3A%2F%2F'))
  598. {
  599. filename = getFilename(decodeURIComponent(filename));
  600. }
  601. return filename;
  602. };
  603. function getBlockId(node)
  604. {
  605. var blockId = null;
  606. while (blockId == null && node != null && node != document.body)
  607. {
  608. blockId = node.getAttribute('data-block-id');
  609. node = node.parentNode;
  610. }
  611. return blockId;
  612. };
  613. function crossfade(source, target, done)
  614. {
  615. target.style.visibility = '';
  616. window.setTimeout(function()
  617. {
  618. source.style.visibility = 'hidden';
  619. if (done != null)
  620. {
  621. done();
  622. }
  623. }, 50);
  624. };
  625. function extractId(url, isBlock)
  626. {
  627. if (isBlock)
  628. {
  629. url = url.split('#').pop();
  630. }
  631. let id = url.split('/').pop().split('&p=').pop().split('?p=').pop().split('?').shift().split('-').pop().split('&').shift();
  632. //Return the id in the form 12345678-1234-5678-1234-567812345678
  633. return id.substring(0,8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16) +
  634. '-' + id.substring(16, 20) + '-' + id.substring(20);
  635. };
  636. function uuidv4()
  637. {
  638. return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
  639. (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  640. );
  641. }
  642. function callNotionAPI(api, data, onsuccess, onerror, origMsg, absUrl, method, directData, mimeType, respAsTxt)
  643. {
  644. fetch(absUrl || ('https://www.notion.so/api/v3/' + api),
  645. { method: method || 'post',
  646. body: directData? data : JSON.stringify(data),
  647. headers: {'Content-Type': mimeType || 'application/json'}})
  648. .then(async res =>
  649. {
  650. try
  651. {
  652. if (res.ok)
  653. {
  654. onsuccess(respAsTxt? await res.text() : await res.json());
  655. }
  656. else
  657. {
  658. origMsg = origMsg || {};
  659. origMsg.error = true;
  660. origMsg.errStatus = res.status;
  661. onerror(origMsg);
  662. try
  663. {
  664. console.log(await res.json());
  665. }
  666. catch(e){}
  667. }
  668. }
  669. catch(e)
  670. {
  671. console.log(e);
  672. origMsg.error = true;
  673. onerror(origMsg);
  674. }
  675. })
  676. .catch((err) =>
  677. {
  678. console.log(err);
  679. origMsg.error = true;
  680. onerror(origMsg);
  681. });
  682. };
  683. function replaceDiagram(msg, sendResponse)
  684. {
  685. callNotionAPI('loadUserContent', {},
  686. function(data)
  687. {
  688. let userId = Object.keys(data.recordMap.notion_user)[0];
  689. let blockId = msg.blockId;
  690. //Upload the file
  691. callNotionAPI('getUploadFileUrl', {bucket: 'secure', name: msg.filename, contentType: 'image/svg+xml'},
  692. function(urls)
  693. {
  694. let ts = Date.now();
  695. let url = urls.url;
  696. const S3_URL_PREFIX = 'https://s3-us-west-2.amazonaws.com/secure.notion-static.com/';
  697. let fileId = url.substring(S3_URL_PREFIX.length).split('/')[0];
  698. callNotionAPI(null, msg.data, function()
  699. {
  700. //Update Image block with file info
  701. callNotionAPI('saveTransactions', {
  702. 'requestId': uuidv4(),
  703. 'transactions': [{
  704. 'id': uuidv4(),
  705. 'operations': [
  706. {'id': blockId, 'path': ['format', 'display_source'],
  707. 'args': url,
  708. 'command': 'set', 'table': 'block'
  709. },
  710. {
  711. 'args': {'last_edited_by_id': userId, 'last_edited_by_table': 'notion_user', 'last_edited_time': ts},
  712. 'command': 'update', 'id': blockId, 'path': [], 'table': 'block'
  713. },
  714. {'id': blockId, 'path': ['properties', 'source'],
  715. 'args': [[url]],
  716. 'command': 'set', 'table': 'block'
  717. },
  718. {
  719. 'args': {'last_edited_by_id': userId, 'last_edited_by_table': 'notion_user', 'last_edited_time': ts},
  720. 'command': 'update', 'id': blockId, 'path': [], 'table': 'block'
  721. },
  722. {'id': blockId, 'path': ['file_ids', 0],
  723. 'args': fileId,
  724. 'command': 'set', 'table': 'block'
  725. },
  726. {
  727. 'args': {'last_edited_by_id': userId, 'last_edited_by_table': 'notion_user', 'last_edited_time': ts},
  728. 'command': 'update', 'id': blockId, 'path': [], 'table': 'block'
  729. }
  730. ]
  731. }]
  732. },
  733. function()
  734. {
  735. msg.newUrl = url;
  736. sendResponse(msg);
  737. }, sendResponse, msg);
  738. }, sendResponse, msg, urls.signedPutUrl, 'put', true, 'image/svg+xml', true);
  739. }, sendResponse, msg);
  740. }, sendResponse, msg);
  741. };
  742. chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse)
  743. {
  744. switch (msg.msg)
  745. {
  746. case 'insertDiagram':
  747. // Stops active editing
  748. if (activeImage != null)
  749. {
  750. iframe.contentWindow.postMessage(JSON.stringify(
  751. {action: 'exit'}), '*');
  752. }
  753. //Get user ID
  754. callNotionAPI('loadUserContent', {},
  755. function(data)
  756. {
  757. let userId = Object.keys(data.recordMap.notion_user)[0];
  758. let blockId = uuidv4();
  759. let pageId = msg.pageId || extractId(window.location.href);
  760. let ts = Date.now();
  761. //Add Image block
  762. callNotionAPI('saveTransactions', {
  763. 'requestId': uuidv4(),
  764. 'transactions': [{
  765. 'id': uuidv4(),
  766. 'operations': [
  767. {'id': blockId, 'path': [],
  768. 'args': {'id': blockId, 'version': 1, 'alive': true, 'created_by_id': userId, 'created_by_table': 'notion_user',
  769. 'created_time': ts, 'parent_id': pageId, 'parent_table': 'block', 'type': 'image', 'child_list_key': null},
  770. 'command': 'set', 'table': 'block'
  771. },
  772. {
  773. 'args': {'last_edited_by_id': userId, 'last_edited_by_table': 'notion_user', 'last_edited_time': ts},
  774. 'command': 'update', 'id': blockId, 'path': [], 'table': 'block'
  775. },
  776. {'id': pageId, 'path': ['content'],
  777. 'args': {'id': blockId},
  778. 'command': 'listAfter', 'table': 'block'
  779. },
  780. {
  781. 'args': {'last_edited_by_id': userId, 'last_edited_by_table': 'notion_user', 'last_edited_time': ts},
  782. 'command': 'update', 'id': pageId, 'path': [], 'table': 'block'
  783. },
  784. {
  785. 'args': {'last_edited_by_id': userId, 'last_edited_by_table': 'notion_user', 'last_edited_time': ts},
  786. 'command': 'update', 'id': pageId, 'path': [], 'table': 'block'
  787. },
  788. {
  789. 'args': {'last_edited_by_id': userId, 'last_edited_by_table': 'notion_user', 'last_edited_time': ts},
  790. 'command': 'update', 'id': blockId, 'path': [], 'table': 'block'
  791. }
  792. ]
  793. }]
  794. },
  795. function()
  796. {
  797. //Now, upload the file
  798. callNotionAPI('getUploadFileUrl', {bucket: 'secure', name: msg.filename, contentType: 'image/svg+xml'},
  799. function(urls)
  800. {
  801. ts = Date.now();
  802. let url = urls.url;
  803. const S3_URL_PREFIX = 'https://s3-us-west-2.amazonaws.com/secure.notion-static.com/';
  804. let fileId = url.substring(S3_URL_PREFIX.length).split('/')[0];
  805. callNotionAPI(null, msg.data, function()
  806. {
  807. //Update Image block with file info
  808. callNotionAPI('saveTransactions', {
  809. 'requestId': uuidv4(),
  810. 'transactions': [{
  811. 'id': uuidv4(),
  812. 'operations': [
  813. {'id': blockId, 'path': ['format', 'display_source'],
  814. 'args': url,
  815. 'command': 'set', 'table': 'block'
  816. },
  817. {
  818. 'args': {'last_edited_by_id': userId, 'last_edited_by_table': 'notion_user', 'last_edited_time': ts},
  819. 'command': 'update', 'id': blockId, 'path': [], 'table': 'block'
  820. },
  821. {'id': blockId, 'path': ['properties', 'source'],
  822. 'args': [[url]],
  823. 'command': 'set', 'table': 'block'
  824. },
  825. {
  826. 'args': {'last_edited_by_id': userId, 'last_edited_by_table': 'notion_user', 'last_edited_time': ts},
  827. 'command': 'update', 'id': blockId, 'path': [], 'table': 'block'
  828. },
  829. {'id': blockId, 'path': ['file_ids', 0],
  830. 'args': fileId,
  831. 'command': 'set', 'table': 'block'
  832. },
  833. {
  834. 'args': {'last_edited_by_id': userId, 'last_edited_by_table': 'notion_user', 'last_edited_time': ts},
  835. 'command': 'update', 'id': blockId, 'path': [], 'table': 'block'
  836. }
  837. ]
  838. }]
  839. },
  840. function()
  841. {
  842. msg.newBlock = {id: blockId, url: url};
  843. editBlock(blockId);
  844. sendResponse(msg);
  845. }, sendResponse, msg);
  846. }, sendResponse, msg, urls.signedPutUrl, 'put', true, 'image/svg+xml', true);
  847. }, sendResponse, msg);
  848. }, sendResponse, msg);
  849. }, sendResponse, msg);
  850. break;
  851. }
  852. return true;
  853. });
  854. })();