view.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. function cacheDataURLFrom(text, toCache) {
  2. var urlMap = {};
  3. var attachmentCount = 0;
  4. var test = /\[(.*?)\]\((data:.*?)\)/g;
  5. var newText = text.replace(test, function (_, label, dataURL) {
  6. fileName = encodeURIComponent(label.split(/[\\/]/).pop());
  7. var fakeURL = location.href + '/' + ++attachmentCount +'/' + fileName;
  8. urlMap[fakeURL] = dataURL;
  9. return '[' + label + '](' + fakeURL + ')';
  10. });
  11. return Promise.all(
  12. Object.entries(urlMap).map(function([fakeURL, dataURL]) {
  13. return fetch(dataURL).then(function(res) {
  14. return toCache.put(fakeURL, new Response(res.body, res));
  15. });
  16. })
  17. ).then(function() {
  18. return newText;
  19. });
  20. }
  21. Vue.component('vue-easymde', VueEasyMDE.VueEasyMDE)
  22. var origText
  23. // 查看消息需要用到的JS
  24. app = new Vue({
  25. el: '#app',
  26. data: {
  27. status: -1,
  28. text: null,
  29. easyMDEOpts: {
  30. maxHeight: '70vh',
  31. onToggleFullScreen: function() { $('.navbar').toggle(); },
  32. spellChecker: false,
  33. toolbar: [
  34. {
  35. name: 'copy no-disable',
  36. action: function() {
  37. if (!origText) return;
  38. navigator.clipboard.writeText(origText);
  39. },
  40. className: 'fa fa-clipboard',
  41. title: 'Copy to clipboard',
  42. },
  43. 'preview',
  44. 'fullscreen',
  45. ],
  46. renderingConfig: { codeSyntaxHighlighting: true },
  47. },
  48. },
  49. mounted: function() {
  50. // 从URL获取GUID,然后透过POST获取消息
  51. var guid = reg_guid.exec(location.href)[0];
  52. navigator.serviceWorker.register('./sw.js').then(function () {
  53. return navigator.serviceWorker.ready;
  54. }).then(function() {
  55. return axios.post('/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. this.$nextTick(() => {
  80. var easyMDE = this.$refs.preview.getMDEInstance();
  81. easyMDE.togglePreview();
  82. easyMDE.codemirror.setOption('readOnly', true);
  83. });
  84. }
  85. }
  86. })