123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
- <title>memos记录</title>
- <!-- 引入Quill样式 -->
- <link rel="stylesheet" href="./js/quill.snow.css">
- <script src="js/util.js"></script>
- <style>
- #editor {
- height: 150px;
- }
- #mask {
- position: fixed;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
- display: flex;
- justify-content: center;
- align-items: center;
- }
- #model {
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- background-color: white;
- width: 50%;
- padding: 20px;
- border-radius: 5px;
- }
- </style>
- </head>
- <body>
- <div id="all">
- <div style="position: fixed;top: 10px;">
- <a href="https://memos.tianyunperfect.cn/">memos主页</a>
- <!-- 页码输入框,默认为1,修改触发查询-->
- <span style="margin-left: 20px">页码:</span>
- <input style="width: 50px; margin-left: 20px" type="number" id="page" value="1" onkeydown="if(event.keyCode===13) {search()}">
- <!--输入框,绑定回车事件,触发查询-->
- <input style="margin-left: 30px; width: 70vw;" placeholder="搜索" type="text" id="search" onkeydown="if(event.keyCode===13) {search()}">
- </div>
- <br><br>
- <div></div>
- <!-- 创建一个用于编辑的容器 -->
- <div id="editor"></div>
- <!-- 添加多选按钮 -->
- <div id="tags"></div>
- <br>
- <br>
- <!-- 添加发送按钮 -->
- <button id="log" style="float: right; height: 100px;width: 200px; font-size: 40px" onclick="sendData()">记录</button>
- <div id="memos_list">
- </div>
- </div>
- <div id="mask" style="display: none">
- <div id="model">
- <!-- 创建时间的input-->
- <div style="margin: 10px">
- <label for="created_ts">创建时间</label>
- <input id="created_ts"></input>
- </div>
- <div id="editorModel"></div>
- <br>
- <!-- 取消 和 确认按钮-->
- <button onclick="hideModel()" style="margin-right: 50px">取消</button>
- <button onclick="updateById()">确认</button>
- </div>
- </div>
- <!-- 引入Quill库 -->
- <script src="./js/cdn.quilljs.com_1.3.6_quill.js"></script>
- <!--异步请求示例:requestUtil.sync('https://jsonplaceholder.typicode.com/posts/1', 'post', data, headers) .then(data => console.log(data))-->
- <script>
- let authStr = "bearer eyJhbGciOiJIUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJuYW1lIjoidGlhbnl1bnBlcmZlY3QiLCJpc3MiOiJtZW1vcyIsInN1YiI6IjEiLCJhdWQiOlsidXNlci5hY2Nlc3MtdG9rZW4iXSwiaWF0IjoxNzA5MTc5NTUyfQ.LFxWB4efya1sL7VoJ42xpXxbAip-udT_Kx2OwZ8Y3-E";
- let myHeaders = {
- 'Content-type': 'application/json',
- 'Authorization': authStr
- };
- // console.log(location.href)
- // console.log(location.href.indexOf(tag))
- // 设置多选按钮 标签
- requestUtil.async('https://memos.tianyunperfect.cn/api/v1/tag', 'get', null, {'Authorization': authStr}).then(res => {
- // console.log(res); ['tag1','tag2']
- // 在 id tags 里面拼接res数组 ,示例todo标签 <input type="checkbox" id="todo" name="category" value="todo" checked> <label for="todo">todo</label>
- let tags = document.getElementById('tags');
- res.forEach(tag => {
- let input = document.createElement('input');
- // 如果是location.href 包含tag,则设置为选中状态, href 要反编译以识别中文
- if (decodeURI(location.href).indexOf(tag) !== -1) {
- input.checked = true;
- }
- input.type = 'checkbox';
- input.id = tag;
- input.name = 'category';
- input.value = tag;
- let label = document.createElement('label');
- // 设置margin-right 20
- label.style.marginRight = '10px';
- label.htmlFor = tag;
- label.innerText = tag;
- tags.appendChild(input);
- tags.appendChild(label);
- });
- search();
- // id="tags" 里面的多选按钮,点击后触发search
- let checkboxes = document.querySelectorAll('input[name="category"]');
- checkboxes.forEach(checkbox => {
- checkbox.onclick = function () {
- search();
- }
- });
- });
- function showModel() {
- document.getElementById('mask').style.display = 'block';
- }
- function hideModel() {
- document.getElementById('mask').style.display = 'none';
- }
- let option = {
- theme: 'snow', // 指定使用的主题
- modules: {
- toolbar: [
- [{'header': [1, 2, false]}, 'bold', 'italic', 'blockquote', 'code-block', 'link'],
- [{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}, 'image', 'video'],
- ]
- }
- };
- const quill = new Quill('#editor', option);
- const quillModel = new Quill('#editorModel', option);
- quill.focus();
- let contentStr = 'content';
- // 从localStorage中获取内容
- let item = localStorage.getItem(contentStr);
- if (item != null) {
- quill.root.innerHTML = item;
- }
- // 如果处于编辑状态,则执行esc取消
- window.onkeydown = function (event) {
- if (event.keyCode === 27 && document.getElementById('mask').style.display === 'block') {
- hideModel();
- }
- // 如果是meta + enter 则保存
- if (event.metaKey && event.keyCode === 13) {
- updateById();
- }
- // 如果是ctrl + enter 则保存
- if (event.ctrlKey && event.keyCode === 13) {
- updateById();
- }
- };
- quill.on('text-change', function (delta, oldDelta, source) {
- localStorage.setItem(contentStr, quill.root.innerHTML);
- });
- async function convertToWebPAsync(base64Image) {
- // 检查图像格式是否为WebP
- if (base64Image.startsWith('data:image/webp')) {
- // 如果是WebP格式,直接返回原始的base64字符串
- return base64Image;
- } else {
- // 将图像转换为WebP格式
- const image = new Image();
- image.src = base64Image;
- await new Promise((resolve, reject) => {
- image.onload = resolve;
- image.onerror = reject;
- });
- const canvas = document.createElement('canvas');
- canvas.width = image.width;
- canvas.height = image.height;
- const ctx = canvas.getContext('2d');
- ctx.drawImage(image, 0, 0);
- const webpData = canvas.toDataURL('image/webp');
- return webpData;
- }
- }
- /**
- * 获取 markdown 格式的内容
- * @param delta
- * @returns {string}
- */
- async function deltaToMarkdown(delta) {
- let markdown = '';
- for (const op of delta['ops']) {
- if (op.insert) {
- if (typeof op.insert === 'string') {
- markdown += op.insert;
- } else if (op.insert.image) {
- // 如果是图片,转换为webp
- const webpBase64 = await convertToWebPAsync(op.insert.image);
- markdown += ``;
- }
- }
- }
- return markdown;
- }
- // 获取编辑器内容
- // function getContent() {
- // const content = quill.root.innerHTML;
- // console.log(content);
- // }
- // 发送数据
- async function sendData() {
- // 使id=log 不可用
- let logBtn = document.getElementById('log');
- logBtn.disabled = true;
- logBtn.innerText = '正在发送...';
- const content = await deltaToMarkdown(quill.getContents());
- const categories = getSelectedCategories();
- // 添加多选按钮选择的分类到内容前面
- let updatedContent = content;
- if (categories.length > 0) {
- updatedContent = `#${categories.join(' ')} ${content}`;
- }
- // updatedContent 去除尾部的\n,可能有多个
- updatedContent = updatedContent.replace(/\n+$/, '');
- // 调用数据备份接口
- const data = {
- content: updatedContent
- };
- // 发送异步请求
- requestUtil.async('https://memos.tianyunperfect.cn/api/v1/memo', 'post', data, myHeaders).then(res => {
- // alert(JSON.stringify(res));
- if (res['name']) {
- // window.location.href = `https://memos.tianyunperfect.cn/m/${res['name']}`;
- showMsg('记录成功', 1);
- }
- logBtn.disabled = false;
- logBtn.innerText = '记录';
- quill.root.innerHTML = '';
- localStorage.removeItem(contentStr);
- search();
- });
- }
- // 获取选择的分类
- function getSelectedCategories() {
- const checkboxes = document.querySelectorAll('input[name="category"]:checked');
- const categories = [];
- checkboxes.forEach(checkbox => {
- categories.push(checkbox.value);
- });
- return categories;
- }
- let tmpId;
- // 更新数据
- async function updateById() {
- let content = await deltaToMarkdown(quillModel.getContents());
- content = content.replace(/\n+$/, '');
- let data = {
- id: tmpId,
- content: content,
- created_ts: document.getElementById('created_ts').value
- };
- requestUtil.async(`https://web_history.tianyunperfect.cn/memos/update`, 'post', data, {}).then(res => {
- showMsg('保存成功', 1);
- hideModel();
- search();
- });
- }
- function formatTimeStr(timeStr) {
- // "2024-04-25T08:25:54" 转为 "2024-04-25 08:25:54"
- return timeStr.replace('T', ' ').substring(0, 19);
- }
- function search() {
- // 页面滚动到顶部
- document.documentElement.scrollTo(0, 0);
- let searchStr = document.getElementById('search').value;
- // 如果标签不为空,则 拼接成 tag_str ,逗号分隔
- let tag_str = '';
- let checkboxes = document.querySelectorAll('input[name="category"]:checked');
- checkboxes.forEach(checkbox => {
- tag_str += checkbox.value + ',';
- });
- // https://web_history.tianyunperfect.cn/memos/list
- // get
- // 入参:search tag_str
- //
- // {'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'}]}
- let params = {'search': searchStr, tag_str: tag_str, page: document.getElementById('page').value, page_size: 100};
- let url = 'https://web_history.tianyunperfect.cn/memos/list';
- // 拼接url
- let urlWithParams = requestUtil.buildUrl(url, params);
- requestUtil.async(urlWithParams, 'get', null, null).then(res => {
- // console.log(res);
- res = res['res'];
- // 循环获取里面所有的id数组
- let idArr = [];
- res.forEach(item => {
- idArr.push(item['id']);
- });
- let sourceUrl = "https://web_history.tianyunperfect.cn/memos/resource"
- let sourceData = {
- ids: idArr.join(',') // 逗号分隔的字符串
- }
- // 获取资源
- let sourceRes = requestUtil.sync(sourceUrl, 'post', sourceData, {});
- // {'code': 200, 'res': [{'memo_id': 1, 'resource_name': 'EfdmvRsodBviDQWRmDiTaV'}, {'memo_id': 4, 'resource_name': '2rY5kmn3AHsy23vK4vSskV'}, {'memo_id': 7, 'resource_name': 'FMhzJXjoTa7fdtbbCBjXnt'}]}
- // 循环遍历,以memo_id为key,resource_name数组为value
- let resourceMap = {};
- sourceRes['res'].forEach(item => {
- if (resourceMap[item['memo_id']]) {
- resourceMap[item['memo_id']].push(item['internal_path']);
- } else {
- resourceMap[item['memo_id']] = [item['internal_path']];
- }
- });
- let div = document.querySelector('#memos_list');
- // flex 定位
- div.innerHTML = '';
- res.forEach(item => {
- let lineDiv = document.createElement('div');
- div.appendChild(lineDiv);
- let tmpDiv = document.createElement('div');
- tmpDiv.innerText = formatTimeStr(item['created_ts']) + "\n" + item['content'];
- // 样式加上border,点击跳转到对应的url https://memos.tianyunperfect.cn/m/ + item['resource_name']
- tmpDiv.style.border = '1px solid #000';
- // 宽度 70vw
- tmpDiv.style.width = '70vw';
- tmpDiv.style.margin = '10px';
- tmpDiv.style.padding = '10px';
- tmpDiv.style.cursor = 'pointer';
- // inline
- tmpDiv.style.display = 'inline-block';
- tmpDiv.ondblclick = function () {
- tmpId = item['id'];
- quillModel.root.innerHTML = item['content'];
- document.getElementById('created_ts').value = formatTimeStr(item['created_ts']);
- showModel();
- // focus
- quillModel.focus();
- };
- // 根据id,查找是否存在资源
- if (resourceMap[item['id']]) {
- // tmpDiv 新增一个换行
- tmpDiv.appendChild(document.createElement('br'));
- // 循环遍历,以memo_id为key,resource_name数组为value
- resourceMap[item['id']].forEach(internal_path => {
- // 创建img
- let img = document.createElement('img');
- img.src = `https://memos_assert.tianyunperfect.cn/${internal_path}?width=150`;
- img.style.maxHeight = '200px';
- img.style.maxWidth = '200px';
- img.style.margin = '10px';
- img.style.cursor = 'pointer';
- // 添加到div
- tmpDiv.appendChild(img);
- });
- }
- lineDiv.appendChild(tmpDiv);
- // 右侧添加一个编辑按钮
- let editBtn = document.createElement('button');
- editBtn.innerText = '跳转查看';
- // margin 10
- editBtn.style.margin = '10px';
- // inline
- editBtn.style.display = 'inline-block';
- editBtn.onclick = function () {
- window.open(`https://memos.tianyunperfect.cn/m/${item['resource_name']}`);
- };
- lineDiv.appendChild(editBtn);
- // 归档按钮
- let archiveBtn = document.createElement('button');
- archiveBtn.innerText = '归档';
- archiveBtn.style.margin = '10px';
- // inline
- archiveBtn.style.display = 'inline-block';
- archiveBtn.onclick = function () {
- let data = {
- id: item['id']
- };
- requestUtil.async(`https://web_history.tianyunperfect.cn/memos/archive`, 'post', data, {}).then(res => {
- showMsg('归档成功', 1);
- lineDiv.style.display = 'none';
- });
- };
- lineDiv.appendChild(archiveBtn);
- // 删除按钮
- let delBtn = document.createElement('button');
- delBtn.innerText = '删除';
- delBtn.style.margin = '10px';
- // inline
- delBtn.style.display = 'inline-block';
- delBtn.onclick = function () {
- // 确认是否删除
- if (!confirm('确认删除吗?')) {
- return;
- }
- let data = {
- id: item['id']
- };
- requestUtil.async(`https://web_history.tianyunperfect.cn/memos/delete`, 'post', data, {}).then(res => {
- showMsg('删除成功', 1);
- lineDiv.style.display = 'none';
- });
- };
- lineDiv.appendChild(delBtn);
- });
- });
- }
- </script>
- </body>
- </html>
|