view.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. var basePath = document.currentScript.src + '/../../';
  2. var cleanURL = location.origin + location.pathname
  3. var origText
  4. function cacheDataURLFrom(text, toCache) {
  5. var urlMap = {};
  6. var attachmentCount = 0;
  7. var test = /\[(.*?)\]\((data:.*?)\)/g;
  8. var newText = text.replace(test, function (_, label, dataURL) {
  9. fileName = encodeURIComponent(label.split(/[\\/]/).pop());
  10. var fakeURL = cleanURL + '/' + ++attachmentCount +'/' + fileName;
  11. urlMap[fakeURL] = dataURL;
  12. return '[' + label + '](' + fakeURL + ')';
  13. });
  14. return Promise.all(
  15. Object.entries(urlMap).map(function([fakeURL, dataURL]) {
  16. return fetch(dataURL).then(function(res) {
  17. return toCache.put(fakeURL, new Response(res.body, res));
  18. });
  19. })
  20. ).then(function() {
  21. return newText;
  22. });
  23. }
  24. Vue.component('vue-easymde', VueEasyMDE.VueEasyMDE)
  25. // 查看消息需要用到的JS
  26. app = new Vue({
  27. el: '#app',
  28. data: {
  29. status: -1,
  30. text: null,
  31. easyMDEOpts: {
  32. maxHeight: '70vh',
  33. onToggleFullScreen: function() { $('.navbar').toggle(); },
  34. spellChecker: false,
  35. toolbar: [
  36. {
  37. name: 'copy no-disable',
  38. action: function() {
  39. if (!origText) return;
  40. navigator.clipboard.writeText(origText);
  41. },
  42. className: 'fa fa-clipboard',
  43. title: 'Copy to clipboard',
  44. },
  45. 'preview',
  46. 'fullscreen',
  47. ],
  48. renderingConfig: { codeSyntaxHighlighting: true },
  49. },
  50. },
  51. mounted: function() {
  52. navigator.serviceWorker.register(basePath + 'sw.js').then(function () {
  53. return navigator.serviceWorker.ready;
  54. }).then(function() {
  55. return axios.post(basePath + 'api/get-msg', {
  56. guid: guid
  57. });
  58. }).then(function(response) {
  59. var data = response.data;
  60. app.status = data.status;
  61. if (app.status !== 1) return null;
  62. origText = data.text;
  63. $(window).on('navigate unload', function() {
  64. caches.delete(guid);
  65. });
  66. return caches.open(guid);
  67. }).then(function(toCache) {
  68. return toCache && cacheDataURLFrom(origText, toCache);
  69. }).then(function(text) {
  70. app.text = text;
  71. }).catch(function(error) {
  72. throw error;
  73. });
  74. },
  75. watch: {
  76. status: function(status) {
  77. if (status !== 1) return;
  78. // 获取成功,等待装载并设定编辑器状态
  79. app.$nextTick(function() {
  80. var easyMDE = app.$refs.preview.getMDEInstance();
  81. easyMDE.togglePreview();
  82. easyMDE.codemirror.setOption('readOnly', true);
  83. });
  84. }
  85. }
  86. })