send_memos.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
  6. <title>memos记录</title>
  7. <!-- 引入Quill样式 -->
  8. <link rel="stylesheet" href="./js/quill.snow.css">
  9. <script src="js/util.js"></script>
  10. <style>
  11. #editor {
  12. height: 150px;
  13. }
  14. #model {
  15. position: absolute;
  16. top: 50%;
  17. left: 50%;
  18. transform: translate(-50%, -50%);
  19. width: 50%;
  20. height: 50%;
  21. }
  22. </style>
  23. </head>
  24. <body>
  25. <div id="all">
  26. <div style="position: fixed;top: 10px;">
  27. <a href="https://memos.tianyunperfect.cn/">memos主页</a>
  28. <!--输入框,绑定回车事件,触发查询-->
  29. <input style="margin-left: 30px; width: 70vw;" placeholder="搜索" type="text" id="search" onkeydown="if(event.keyCode===13) {search()}">
  30. </div>
  31. <br><br>
  32. <div></div>
  33. <!-- 创建一个用于编辑的容器 -->
  34. <div id="editor"></div>
  35. <!-- 添加多选按钮 -->
  36. <div id="tags"></div>
  37. <br>
  38. <br>
  39. <!-- 添加发送按钮 -->
  40. <button id="log" style="float: right; height: 100px;width: 200px; font-size: 40px" onclick="sendData()">记录</button>
  41. <div id="memos_list">
  42. </div>
  43. </div>
  44. <div id="model" style="display: none">
  45. <div id="editorModel"></div>
  46. <br>
  47. <!-- 取消 和 确认按钮-->
  48. <button onclick="hideModel()" style="margin-right: 50px">取消</button>
  49. <button onclick="updateById()">确认</button>
  50. </div>
  51. <!-- 引入Quill库 -->
  52. <script src="./js/cdn.quilljs.com_1.3.6_quill.js"></script>
  53. <!--异步请求示例:requestUtil.sync('https://jsonplaceholder.typicode.com/posts/1', 'post', data, headers) .then(data => console.log(data))-->
  54. <script>
  55. let authStr = "bearer eyJhbGciOiJIUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJuYW1lIjoidGlhbnl1bnBlcmZlY3QiLCJpc3MiOiJtZW1vcyIsInN1YiI6IjEiLCJhdWQiOlsidXNlci5hY2Nlc3MtdG9rZW4iXSwiaWF0IjoxNzA5MTc5NTUyfQ.LFxWB4efya1sL7VoJ42xpXxbAip-udT_Kx2OwZ8Y3-E";
  56. let myHeaders = {
  57. 'Content-type': 'application/json',
  58. 'Authorization': authStr
  59. };
  60. // console.log(location.href)
  61. // console.log(location.href.indexOf(tag))
  62. // 设置多选按钮 标签
  63. requestUtil.async('https://memos.tianyunperfect.cn/api/v1/tag', 'get', null, {'Authorization': authStr}).then(res => {
  64. // console.log(res); ['tag1','tag2']
  65. // 在 id tags 里面拼接res数组 ,示例todo标签 <input type="checkbox" id="todo" name="category" value="todo" checked> <label for="todo">todo</label>
  66. let tags = document.getElementById('tags');
  67. res.forEach(tag => {
  68. let input = document.createElement('input');
  69. // 如果是location.href 包含tag,则设置为选中状态, href 要反编译以识别中文
  70. if (decodeURI(location.href).indexOf(tag) !== -1) {
  71. input.checked = true;
  72. }
  73. input.type = 'checkbox';
  74. input.id = tag;
  75. input.name = 'category';
  76. input.value = tag;
  77. let label = document.createElement('label');
  78. // 设置margin-right 20
  79. label.style.marginRight = '10px';
  80. label.htmlFor = tag;
  81. label.innerText = tag;
  82. tags.appendChild(input);
  83. tags.appendChild(label);
  84. });
  85. search();
  86. // id="tags" 里面的多选按钮,点击后触发search
  87. let checkboxes = document.querySelectorAll('input[name="category"]');
  88. checkboxes.forEach(checkbox => {
  89. checkbox.onclick = function () {
  90. search();
  91. }
  92. });
  93. });
  94. function showModel() {
  95. document.getElementById('model').style.display = 'block';
  96. // 隐藏编辑器
  97. document.getElementById('all').style.display = 'none';
  98. }
  99. function hideModel() {
  100. document.getElementById('model').style.display = 'none';
  101. // 显示编辑器
  102. document.getElementById('all').style.display = 'block';
  103. }
  104. let option = {
  105. theme: 'snow', // 指定使用的主题
  106. modules: {
  107. toolbar: [
  108. [{'header': [1, 2, false]}, 'bold', 'italic', 'blockquote', 'code-block', 'link'],
  109. [{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}, 'image', 'video'],
  110. ]
  111. }
  112. };
  113. const quill = new Quill('#editor', option);
  114. const quillModel = new Quill('#editorModel', option);
  115. quill.focus();
  116. let contentStr = 'content';
  117. // 从localStorage中获取内容
  118. let item = localStorage.getItem(contentStr);
  119. if (item != null) {
  120. quill.root.innerHTML = item;
  121. }
  122. // 如果处于编辑状态,则执行esc取消
  123. window.onkeydown = function (event) {
  124. if (event.keyCode === 27 && document.getElementById('model').style.display === 'block') {
  125. hideModel();
  126. }
  127. // 如果是meta + enter 则保存
  128. if (event.metaKey && event.keyCode === 13) {
  129. updateById();
  130. }
  131. // 如果是ctrl + enter 则保存
  132. if (event.ctrlKey && event.keyCode === 13) {
  133. updateById();
  134. }
  135. };
  136. quill.on('text-change', function (delta, oldDelta, source) {
  137. localStorage.setItem(contentStr, quill.root.innerHTML);
  138. });
  139. async function convertToWebPAsync(base64Image) {
  140. // 检查图像格式是否为WebP
  141. if (base64Image.startsWith('data:image/webp')) {
  142. // 如果是WebP格式,直接返回原始的base64字符串
  143. return base64Image;
  144. } else {
  145. // 将图像转换为WebP格式
  146. const image = new Image();
  147. image.src = base64Image;
  148. await new Promise((resolve, reject) => {
  149. image.onload = resolve;
  150. image.onerror = reject;
  151. });
  152. const canvas = document.createElement('canvas');
  153. canvas.width = image.width;
  154. canvas.height = image.height;
  155. const ctx = canvas.getContext('2d');
  156. ctx.drawImage(image, 0, 0);
  157. const webpData = canvas.toDataURL('image/webp');
  158. return webpData;
  159. }
  160. }
  161. /**
  162. * 获取 markdown 格式的内容
  163. * @param delta
  164. * @returns {string}
  165. */
  166. async function deltaToMarkdown(delta) {
  167. let markdown = '';
  168. for (const op of delta['ops']) {
  169. if (op.insert) {
  170. if (typeof op.insert === 'string') {
  171. markdown += op.insert;
  172. } else if (op.insert.image) {
  173. // 如果是图片,转换为webp
  174. const webpBase64 = await convertToWebPAsync(op.insert.image);
  175. markdown += `![${op.insert.alt}](${webpBase64})`;
  176. }
  177. }
  178. }
  179. return markdown;
  180. }
  181. // 获取编辑器内容
  182. // function getContent() {
  183. // const content = quill.root.innerHTML;
  184. // console.log(content);
  185. // }
  186. // 发送数据
  187. async function sendData() {
  188. // 使id=log 不可用
  189. let logBtn = document.getElementById('log');
  190. logBtn.disabled = true;
  191. logBtn.innerText = '正在发送...';
  192. const content = await deltaToMarkdown(quill.getContents());
  193. const categories = getSelectedCategories();
  194. // 添加多选按钮选择的分类到内容前面
  195. let updatedContent = content;
  196. if (categories.length > 0) {
  197. updatedContent = `#${categories.join(' ')} ${content}`;
  198. }
  199. // 调用数据备份接口
  200. const data = {
  201. content: updatedContent
  202. };
  203. // 发送异步请求
  204. requestUtil.async('https://memos.tianyunperfect.cn/api/v1/memo', 'post', data, myHeaders).then(res => {
  205. // alert(JSON.stringify(res));
  206. if (res['name']) {
  207. // window.location.href = `https://memos.tianyunperfect.cn/m/${res['name']}`;
  208. showMsg('记录成功', 1);
  209. }
  210. logBtn.disabled = false;
  211. logBtn.innerText = '记录';
  212. quill.root.innerHTML = '';
  213. localStorage.removeItem(contentStr);
  214. search();
  215. });
  216. }
  217. // 获取选择的分类
  218. function getSelectedCategories() {
  219. const checkboxes = document.querySelectorAll('input[name="category"]:checked');
  220. const categories = [];
  221. checkboxes.forEach(checkbox => {
  222. categories.push(checkbox.value);
  223. });
  224. return categories;
  225. }
  226. let tmpId;
  227. // 更新数据
  228. async function updateById() {
  229. let content = await deltaToMarkdown(quillModel.getContents());
  230. let data = {
  231. id: tmpId,
  232. content: content
  233. };
  234. requestUtil.async(`https://web_history.tianyunperfect.cn/memos/update`, 'post', data, {}).then(res => {
  235. showMsg('保存成功', 1);
  236. hideModel();
  237. search();
  238. });
  239. }
  240. function search() {
  241. let searchStr = document.getElementById('search').value;
  242. // 如果标签不为空,则 拼接成 tag_str ,逗号分隔
  243. let tag_str = '';
  244. let checkboxes = document.querySelectorAll('input[name="category"]:checked');
  245. checkboxes.forEach(checkbox => {
  246. tag_str += checkbox.value + ',';
  247. });
  248. // https://web_history.tianyunperfect.cn/api/memos/list
  249. // get
  250. // 入参:search tag_str
  251. //
  252. // {'code': 200, 'res': [{'id': 11, 'resource_name': 'g2cyE6nXNCdqsm4ZH2R3Bs', 'creator_id': 1, 'created_ts': '2023-07-04T13:35:18', 'updated_ts': '2024-04-22T13:55:25', 'row_status': 'NORMAL', 'content': '康宁的女儿 易安 \n小名:气气\n#备份', 'visibility': 'PRIVATE'}]}
  253. let params = {'search': searchStr, tag_str: tag_str}
  254. let url = 'https://web_history.tianyunperfect.cn/memos/list';
  255. // 拼接url
  256. let urlWithParams = requestUtil.buildUrl(url, params);
  257. requestUtil.async(urlWithParams, 'get', null, null).then(res => {
  258. // console.log(res);
  259. res = res['res'];
  260. let div = document.querySelector('#memos_list');
  261. // flex 定位
  262. div.innerHTML = '';
  263. res.forEach(item => {
  264. let tmpDiv = document.createElement('div');
  265. tmpDiv.innerText = item['content'];
  266. // 样式加上border,点击跳转到对应的url https://memos.tianyunperfect.cn/m/ + item['resource_name']
  267. tmpDiv.style.border = '1px solid #000';
  268. // 宽度 70vw
  269. tmpDiv.style.width = '70vw';
  270. tmpDiv.style.margin = '10px';
  271. tmpDiv.style.padding = '10px';
  272. tmpDiv.style.cursor = 'pointer';
  273. // inline
  274. tmpDiv.style.display = 'inline-block';
  275. tmpDiv.ondblclick = function () {
  276. tmpId = item['id'];
  277. quillModel.root.innerHTML = item['content'];
  278. showModel();
  279. // focus
  280. quillModel.focus();
  281. };
  282. div.appendChild(tmpDiv);
  283. // 右侧添加一个编辑按钮
  284. let editBtn = document.createElement('button');
  285. editBtn.innerText = '跳转查看';
  286. // margin 10
  287. editBtn.style.margin = '10px';
  288. // inline
  289. editBtn.style.display = 'inline-block';
  290. editBtn.onclick = function () {
  291. window.open(`https://memos.tianyunperfect.cn/m/${item['resource_name']}`);
  292. };
  293. div.appendChild(editBtn);
  294. // 删除按钮
  295. let delBtn = document.createElement('button');
  296. delBtn.innerText = '删除';
  297. delBtn.style.margin = '10px';
  298. // inline
  299. delBtn.style.display = 'inline-block';
  300. delBtn.onclick = function () {
  301. // 确认是否删除
  302. if (!confirm('确认删除吗?')) {
  303. return;
  304. }
  305. let data = {
  306. id: item['id']
  307. };
  308. requestUtil.async(`https://web_history.tianyunperfect.cn/memos/delete`, 'post', data, {}).then(res => {
  309. showMsg('删除成功', 1);
  310. search();
  311. });
  312. };
  313. div.appendChild(delBtn);
  314. });
  315. });
  316. }
  317. </script>
  318. </body>
  319. </html>