view.js 2.3 KB

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