dsh-jianji 1.0.21 → 1.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e;(function(e){e.Unimplemented=`UNIMPLEMENTED`,e.Unavailable=`UNAVAILABLE`})(e||={});var t=class extends Error{constructor(e,t,n){super(e),this.message=e,this.code=t,this.data=n}},n=e=>e?.androidBridge?`android`:e?.webkit?.messageHandlers?.bridge?`ios`:`web`,r=r=>{let i=r.CapacitorCustomPlatform||null,a=r.Capacitor||{},o=a.Plugins=a.Plugins||{},s=()=>i===null?n(r):i.name,c=()=>s()!==`web`,l=e=>!!(f.get(e)?.platforms.has(s())||u(e)),u=e=>a.PluginHeaders?.find(t=>t.name===e),d=e=>r.console.error(e),f=new Map;return a.convertFileSrc||=e=>e,a.getPlatform=s,a.handleError=d,a.isNativePlatform=c,a.isPluginAvailable=l,a.registerPlugin=(n,r={})=>{let c=f.get(n);if(c)return console.warn(`Capacitor plugin "${n}" already registered. Cannot register plugins twice.`),c.proxy;let l=s(),d=u(n),p,ee=async()=>(!p&&l in r?p=p=typeof r[l]==`function`?await r[l]():r[l]:i!==null&&!p&&`web`in r&&(p=p=typeof r.web==`function`?await r.web():r.web),p),te=(r,i)=>{if(d){let e=d?.methods.find(e=>i===e.name);if(e)return e.rtype===`promise`?e=>a.nativePromise(n,i.toString(),e):(e,t)=>a.nativeCallback(n,i.toString(),e,t);if(r)return r[i]?.bind(r)}else if(r)return r[i]?.bind(r);else throw new t(`"${n}" plugin is not implemented on ${l}`,e.Unimplemented)},ne=r=>{let i,a=(...a)=>{let o=ee().then(o=>{let s=te(o,r);if(s){let e=s(...a);return i=e?.remove,e}throw new t(`"${n}.${r}()" is not implemented on ${l}`,e.Unimplemented)});return r===`addListener`&&(o.remove=async()=>i()),o};return a.toString=()=>`${r.toString()}() { [capacitor code] }`,Object.defineProperty(a,"name",{value:r,writable:!1,configurable:!1}),a},re=ne(`addListener`),m=ne(`removeListener`),ie=(e,t)=>{let n=re({eventName:e},t),r=async()=>{let r=await n;m({eventName:e,callbackId:r},t)},i=new Promise(e=>n.then(()=>e({remove:r})));return i.remove=async()=>{console.warn(`Using addListener() without 'await' is deprecated.`),await r()},i},ae=new Proxy({},{get(e,t){switch(t){case`$$typeof`:return;case`toJSON`:return()=>({});case`addListener`:return d?ie:re;case`removeListener`:return m;default:return ne(t)}}});return o[n]=ae,f.set(n,{name:n,proxy:ae,platforms:new Set([...Object.keys(r),...d?[l]:[]])}),ae},a.Exception=t,a.DEBUG=!!a.DEBUG,a.isLoggingEnabled=!!a.isLoggingEnabled,a},i=(e=>e.Capacitor=r(e))(typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{}),a=i.registerPlugin,o=class{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(e,t){let n=!1;this.listeners[e]||(this.listeners[e]=[],n=!0),this.listeners[e].push(t);let r=this.windowListeners[e];return r&&!r.registered&&this.addWindowListener(r),n&&this.sendRetainedArgumentsForEvent(e),Promise.resolve({remove:async()=>this.removeListener(e,t)})}async removeAllListeners(){this.listeners={};for(let e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,t,n){let r=this.listeners[e];if(r)r.forEach(e=>e(t));else if(n){let n=this.retainedEventArguments[e];n||=[],n.push(t),this.retainedEventArguments[e]=n}}hasListeners(e){return!!this.listeners[e]?.length}registerWindowListener(e,t){this.windowListeners[t]={registered:!1,windowEventName:e,pluginEventName:t,handler:e=>{this.notifyListeners(t,e)}}}unimplemented(t=`not implemented`){return new i.Exception(t,e.Unimplemented)}unavailable(t=`not available`){return new i.Exception(t,e.Unavailable)}async removeListener(e,t){let n=this.listeners[e];if(!n)return;let r=n.indexOf(t);r!==-1&&this.listeners[e].splice(r,1),this.listeners[e].length||this.removeWindowListener(this.windowListeners[e])}addWindowListener(e){window.addEventListener(e.windowEventName,e.handler),e.registered=!0}removeWindowListener(e){e&&(window.removeEventListener(e.windowEventName,e.handler),e.registered=!1)}sendRetainedArgumentsForEvent(e){let t=this.retainedEventArguments[e];t&&(delete this.retainedEventArguments[e],t.forEach(t=>{this.notifyListeners(e,t)}))}},s=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),c=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent),l=class extends o{async getCookies(){let e=document.cookie,t={};return e.split(`;`).forEach(e=>{if(e.length<=0)return;let[n,r]=e.replace(/=/,`CAP_COOKIE`).split(`CAP_COOKIE`);n=c(n).trim(),r=c(r).trim(),t[n]=r}),t}async setCookie(e){try{let t=s(e.key),n=s(e.value),r=e.expires?`; expires=${e.expires.replace(`expires=`,``)}`:``,i=(e.path||`/`).replace(`path=`,``),a=e.url!=null&&e.url.length>0?`domain=${e.url}`:``;document.cookie=`${t}=${n||``}${r}; path=${i}; ${a};`}catch(e){return Promise.reject(e)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(e){return Promise.reject(e)}}async clearCookies(){try{let e=document.cookie.split(`;`)||[];for(let t of e)document.cookie=t.replace(/^ +/,``).replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(e){return Promise.reject(e)}}async clearAllCookies(){try{await this.clearCookies()}catch(e){return Promise.reject(e)}}};a(`CapacitorCookies`,{web:()=>new l});var u=async e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let e=r.result;t(e.indexOf(`,`)>=0?e.split(`,`)[1]:e)},r.onerror=e=>n(e),r.readAsDataURL(e)}),d=(e={})=>{let t=Object.keys(e);return Object.keys(e).map(e=>e.toLocaleLowerCase()).reduce((n,r,i)=>(n[r]=e[t[i]],n),{})},f=(e,t=!0)=>e?Object.entries(e).reduce((e,n)=>{let[r,i]=n,a,o;return Array.isArray(i)?(o=``,i.forEach(e=>{a=t?encodeURIComponent(e):e,o+=`${r}=${a}&`}),o.slice(0,-1)):(a=t?encodeURIComponent(i):i,o=`${r}=${a}`),`${e}&${o}`},``).substr(1):null,p=(e,t={})=>{let n=Object.assign({method:e.method||`GET`,headers:e.headers},t),r=d(e.headers)[`content-type`]||``;if(typeof e.data==`string`)n.body=e.data;else if(r.includes(`application/x-www-form-urlencoded`)){let t=new URLSearchParams;for(let[n,r]of Object.entries(e.data||{}))t.set(n,r);n.body=t.toString()}else if(r.includes(`multipart/form-data`)||e.data instanceof FormData){let t=new FormData;if(e.data instanceof FormData)e.data.forEach((e,n)=>{t.append(n,e)});else for(let n of Object.keys(e.data))t.append(n,e.data[n]);n.body=t;let r=new Headers(n.headers);r.delete(`content-type`),n.headers=r}else(r.includes(`application/json`)||typeof e.data==`object`)&&(n.body=JSON.stringify(e.data));return n},ee=class extends o{async request(e){let t=p(e,e.webFetchExtra),n=f(e.params,e.shouldEncodeUrlParams),r=n?`${e.url}?${n}`:e.url,i=await fetch(r,t),a=i.headers.get(`content-type`)||``,{responseType:o=`text`}=i.ok?e:{};a.includes(`application/json`)&&(o=`json`);let s,c;switch(o){case`arraybuffer`:case`blob`:c=await i.blob(),s=await u(c);break;case`json`:s=await i.json();break;default:s=await i.text()}let l={};return i.headers.forEach((e,t)=>{l[t]=e}),{data:s,headers:l,status:i.status,url:i.url}}async get(e){return this.request(Object.assign(Object.assign({},e),{method:`GET`}))}async post(e){return this.request(Object.assign(Object.assign({},e),{method:`POST`}))}async put(e){return this.request(Object.assign(Object.assign({},e),{method:`PUT`}))}async patch(e){return this.request(Object.assign(Object.assign({},e),{method:`PATCH`}))}async delete(e){return this.request(Object.assign(Object.assign({},e),{method:`DELETE`}))}},te=a(`CapacitorHttp`,{web:()=>new ee}),ne;(function(e){e.Dark=`DARK`,e.Light=`LIGHT`,e.Default=`DEFAULT`})(ne||={});var re;(function(e){e.StatusBar=`StatusBar`,e.NavigationBar=`NavigationBar`})(re||={});var m=class extends o{async setStyle(){this.unavailable(`not available for web`)}async setAnimation(){this.unavailable(`not available for web`)}async show(){this.unavailable(`not available for web`)}async hide(){this.unavailable(`not available for web`)}},ie=a(`SystemBars`,{web:()=>new m}),ae=`modulepreload`,h=function(e,t){return new URL(e,t).href},oe={},se=function(e){return e.pathname.endsWith(`.css`)},ce=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},le=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=h(t,n);let r=s(t),i=se(r);return ce(oe,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:ae,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},ue=a(`App`,{web:()=>le(()=>import(`./web-C6Uukio0.js`).then(e=>new e.AppWeb),[],import.meta.url)}),de;(function(e){e[e.Sunday=1]=`Sunday`,e[e.Monday=2]=`Monday`,e[e.Tuesday=3]=`Tuesday`,e[e.Wednesday=4]=`Wednesday`,e[e.Thursday=5]=`Thursday`,e[e.Friday=6]=`Friday`,e[e.Saturday=7]=`Saturday`})(de||={});var g=a(`LocalNotifications`,{web:()=>le(()=>import(`./web-CzF3m3w4.js`).then(e=>new e.LocalNotificationsWeb),[],import.meta.url)}),fe=`jianji.notifications.v1`,pe=`jianji.notificationIds.v1`,me=9,he=i.isNativePlatform()&&i.getPlatform()===`android`,ge=!1,_=null,_e=null;function ve(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function ye(e,t){localStorage.setItem(e,JSON.stringify(t))}function be(e){return String(e.title||``).trim()||String(e.notes||``).split(/\r?\n/).find(Boolean)?.trim()||`待办提醒`}function xe(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e||``);if(!t)return null;let n=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]),me,0,0,0);return Number.isNaN(n.getTime())?null:n}function Se(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0)%2e9+1}function Ce(){let e=ve(fe,{});return{enabled:!!e.enabled,permission:String(e.permission||`unknown`)}}async function we(){if(!he)return{supported:!1,enabled:!1,permission:`unsupported`};try{let e=await g.checkPermissions();return{supported:!0,...Ce(),permission:e.display}}catch{return{supported:!0,...Ce(),permission:`unknown`}}}async function Te(){if(!he)throw Error(`系统通知仅在 Android APK 中可用`);let e=await g.checkPermissions();if((e.display===`prompt`||e.display===`prompt-with-rationale`)&&(e=await g.requestPermissions()),e.display!==`granted`)throw ye(fe,{enabled:!1,permission:e.display}),Error(`通知权限未开启,请在 Android 系统设置中允许简记发送通知`);return await g.createChannel({id:`due-reminders`,name:`截止日提醒`,description:`待办到达截止日时的提醒`,importance:4,visibility:1,vibration:!0,lights:!0,lightColor:`#315f6b`}),ye(fe,{enabled:!0,permission:e.display}),e.display}async function Ee(){if(ye(fe,{enabled:!1,permission:`disabled`}),!he)return;let e=ve(pe,[]);Array.isArray(e)&&e.length&&await v(e),ye(pe,[])}async function De(e){clearTimeout(_e),_e=setTimeout(()=>Oe(e),250)}async function Oe(e){if(!he)return{scheduled:0,reason:`unsupported`};if(!Ce().enabled)return{scheduled:0,reason:`disabled`};let t=await g.checkPermissions();if(t.display!==`granted`)return ye(fe,{enabled:!1,permission:t.display}),{scheduled:0,reason:`permission-denied`};let n=ve(pe,[]);Array.isArray(n)&&n.length&&await v(n);let r=Date.now(),i=e.filter(e=>!e.deletedAt&&e.status!==`done`&&e.dueDate).map(e=>({task:e,at:xe(e.dueDate)})).filter(({at:e})=>e&&e.getTime()>r).sort((e,t)=>e.at-t.at).slice(0,100).map(({task:e,at:t})=>({id:Se(e.id),title:be(e),body:`今天是截止日期,记得完成这项待办。`,schedule:{at:t,allowWhileIdle:!0},channelId:`due-reminders`,isExactNotification:!0,isExactMandatory:!1,smallIcon:`ic_stat_jianji`,iconColor:`#315f6b`,extra:{taskId:e.id}}));return i.length&&await g.schedule({notifications:i}),ye(pe,i.map(e=>e.id)),{scheduled:i.length,reason:`ok`}}async function v(e){let t=e.map(Number).filter(Number.isFinite);t.length&&await Promise.all([g.cancel({notifications:t.map(e=>({id:e}))}).catch(()=>{}),g.removeDeliveredNotificationsById({ids:t}).catch(()=>{})])}function ke(e){_=e,he&&!ge&&(ge=!0,g.addListener(`localNotificationActionPerformed`,e=>{let t=e.notification.extra?.taskId;t&&typeof _==`function`&&_(t)}).catch(()=>{}))}var y=a(`AppUpdater`),b=i.getPlatform()===`android`,Ae=`2022-11-28`;function x(e,t=!1){return e.status===404?t?`未找到 Release,请检查发布状态和令牌权限`:`无法访问更新仓库,请填写 GitHub 只读令牌或确认仓库公开`:e.status===401?`GitHub 令牌无效或已过期`:e.status===403||e.status===429?`GitHub API 请求受限,请稍后重试`:`无法获取最新版本(GitHub ${e.status})`}function S(e){return e?{Authorization:`Bearer ${e}`}:{}}async function je(e,t=``){if(b){let n=await te.request({url:e,method:`GET`,headers:{Accept:`application/vnd.github+json`,"X-GitHub-Api-Version":Ae,"User-Agent":`Jianji-Android-Updater`,...S(t)}});if(n.status<200||n.status>=300)throw Error(x(n,!!t));return typeof n.data==`string`?JSON.parse(n.data):n.data}let n=await fetch(e,{cache:`no-store`,headers:{Accept:`application/vnd.github+json`,"X-GitHub-Api-Version":Ae,...S(t)}});if(!n.ok)throw Error(x(n,!!t));return n.json()}async function Me(e,t=``){if(b){let n=await te.request({url:e,method:`GET`,headers:{Accept:`application/octet-stream`,"User-Agent":`Jianji-Android-Updater`,...S(t)}});if(n.status<200||n.status>=300)throw Error(x(n,!!t));return typeof n.data==`string`?n.data:String(n.data??``)}let n=await fetch(e,{cache:`no-store`,headers:{Accept:`application/octet-stream`,...S(t)}});if(!n.ok)throw Error(x(n,!!t));return n.text()}function Ne(e){let t=String(e||``).trim().replace(/^v/i,``).match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);return t?{parts:t.slice(1,4).map(Number),prerelease:t[4]?t[4].split(`.`):[]}:null}function C(e,t){if(!e.length&&!t.length)return 0;if(!e.length)return 1;if(!t.length)return-1;let n=Math.max(e.length,t.length);for(let r=0;r<n;r+=1){if(e[r]===void 0)return-1;if(t[r]===void 0)return 1;if(e[r]===t[r])continue;let n=/^\d+$/.test(e[r]),i=/^\d+$/.test(t[r]);return n&&i?Number(e[r])-Number(t[r]):n===i?e[r].localeCompare(t[r]):n?-1:1}return 0}function Pe(e,t){let n=Ne(e),r=Ne(t);if(!n||!r)return 0;for(let e=0;e<3;e+=1){let t=n.parts[e]-r.parts[e];if(t)return t}return C(n.prerelease,r.prerelease)}function w(e){let t=typeof e.digest==`string`?e.digest.trim().toLowerCase():``;return t.startsWith(`sha256:`)?t.slice(7):``}function Fe(e){return String(e||``).match(/\b[a-f0-9]{64}\b/i)?.[0]?.toLowerCase()||``}async function Ie(e){if(!b)return{versionName:e,versionCode:0,canInstallPackages:!1,nativeInstaller:!1};try{let t=await y.getInfo();return{versionName:String(t.versionName||e),versionCode:Number(t.versionCode||0),canInstallPackages:!!t.canInstallPackages,nativeInstaller:!0}}catch{return{versionName:e,versionCode:0,canInstallPackages:!1,nativeInstaller:!1}}}function Le(e,t,n){if(!e||e.draft||e.prerelease)return null;let r=String(e.tag_name||``).trim();if(!Ne(r))return null;let i=Array.isArray(e.assets)?e.assets:[],a=i.find(e=>e&&e.state===`uploaded`&&String(e.name||``).toLowerCase()===`jianji.apk`)||i.find(e=>e&&e.state===`uploaded`&&String(e.name||``).toLowerCase().endsWith(`.apk`));if(!a)return null;let o=!!n,s=String(a.url||``),c=String(a.browser_download_url||``),l=o?s:c;if(!(o?/^https:\/\/api\.github\.com\/repos\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/releases\/assets\/\d+$/i.test(l):/^https:\/\/github\.com\//i.test(l)))return null;let u=w(a),d=i.find(e=>e&&e.state===`uploaded`&&String(e.name||``)===`${a.name}.sha256`),f=o&&d?.url?d.url:d?.browser_download_url||``;return{id:Number(e.id||0),version:r,name:String(e.name||r).slice(0,180),notes:String(e.body||``).trim().slice(0,12e3),publishedAt:e.published_at||``,releaseUrl:e.html_url||`https://github.com/${t}/releases`,assetName:String(a.name||`jianji.apk`),downloadUrl:l,checksumUrl:f,requiresAuth:o,size:Number(a.size||0),sha256:u}}function Re(e){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(e))throw Error(`应用更新仓库配置无效`)}async function ze(e,t=``){if(!e||e.sha256||!e.checksumUrl)return e;try{let n=Fe(await Me(e.checksumUrl,t));return n?{...e,sha256:n}:e}catch{return e}}async function Be(e,t=``){Re(e);let n=String(t||``).trim(),r=[];for(let t=1;t<=50;t+=1){let i=await je(`https://api.github.com/repos/${e}/releases?per_page=100&page=${t}`,n);if(!Array.isArray(i))throw Error(`GitHub Release 数据格式无效`);if(r.push(...i),i.length<100)break}let i=new Set,a=r.map(t=>Le(t,e,n)).filter(e=>e&&!i.has(e.version)&&i.add(e.version)).sort((e,t)=>Pe(t.version,e.version));if(!a.length)throw Error(`尚未找到可安装的 Release 版本`);return a}async function Ve(e,t=``){if(!b)throw Error(`当前平台不支持后台下载 Android APK`);let n=await ze(e,t);return y.startDownload({url:n.downloadUrl,expectedSha256:n.sha256||``,accessToken:t||``,versionName:n.version,size:Number(n.size||0)})}async function He(){return b?y.getDownloadState():null}async function Ue(){if(!b)throw Error(`当前平台不支持应用内安装 Android APK`);return y.installDownloadedUpdate()}async function We(){if(!b)throw Error(`当前平台不支持导出 Android 安装包`);return y.exportDownloadedUpdate()}async function Ge(){if(!b)throw Error(`当前平台不支持打开 Android 卸载页面`);return y.openAppUninstall()}async function Ke(){return b?y.cancelDownload():null}async function qe(){return b?(await y.openInstallSettings(),!0):!1}function Je(){return b}var Ye=a(`WidgetBridge`),Xe=500,Ze=new Set([`todo`,`doing`,`held`]),Qe=i.isNativePlatform()&&i.getPlatform()===`android`,$e=null;function et(e=new Date){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function tt(e){return String(e||``).split(/\r?\n/).map(e=>e.trim()).find(Boolean)||``}function nt(e){let t=String(e.title||``).trim()||tt(e.notes)||`未命名待办`;return{id:String(e.id||``),title:t.slice(0,180),dueDate:/^\d{4}-\d{2}-\d{2}$/.test(e.dueDate||``)?e.dueDate:``,status:Ze.has(e.status)?e.status:`todo`,pinned:!!e.pinned,order:Number.isFinite(e.order)?e.order:0}}function T(e,t){return e.dueDate&&e.dueDate<t?0:e.dueDate===t?1:e.status===`doing`?2:e.pinned?3:4}function rt(e,t,n){let r=T(e,n)-T(t,n);return r||(r<=1&&e.dueDate!==t.dueDate?e.dueDate.localeCompare(t.dueDate):e.pinned===t.pinned?e.order===t.order?e.title.localeCompare(t.title,`zh-CN`):e.order-t.order:e.pinned?-1:1)}function E(e,t=new Date){let n=et(t),r=Array.isArray(e)?e.filter(e=>e&&!e.deletedAt&&String(e.id||``)):[],i=r.filter(e=>e.status!==`done`).map(nt).sort((e,t)=>rt(e,t,n)),a=i.slice(0,Xe);return{version:1,generatedAt:new Date().toISOString(),today:n,complete:a.length===i.length,counts:{open:i.length,overdue:i.filter(e=>e.dueDate&&e.dueDate<n).length,today:i.filter(e=>e.dueDate===n).length,total:r.length},tasks:a}}async function it(e){if(!Qe)return!1;clearTimeout($e),$e=null;let t=JSON.stringify(E(e));return await Ye.sync({snapshot:t}),!0}function at(e,t=120){Qe&&(clearTimeout($e),$e=setTimeout(()=>{$e=null,it(e).catch(()=>{})},t))}var ot=`https://api.deepseek.com/chat/completions`,D=`https://api.deepseek.com/models`,O=`deepseek-flash`,k=1800,A=2516582.4,st=[.88,.78,.68,.58],j=new Set([`task`,`record`,`inspiration`]),M=class extends Error{constructor(e,t,n=0){super(t),this.name=`DeepseekError`,this.kind=e,this.status=n}};function ct(e){return String(e||``).replace(/\s+/g,``)}function lt(e){let t=ct(e);return t?t.startsWith(`sk-`)?t.length<20?`DeepSeek API Key 看起来不完整,请重新复制`:``:`DeepSeek API Key 应以 sk- 开头,请检查是否复制完整`:`请填写 DeepSeek API Key`}function ut(e){return/^data:image\/[\w.+-]+;base64,[a-z0-9+/=\s]+$/i.test(String(e||``))}function dt(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function ft(e){let t=String(e||``).split(`,`,2)[1]?.replace(/\s+/g,``)||``;return Math.max(0,Math.floor(t.length*.75))}function pt(e){return new Promise((t,n)=>{let r=new Image,i=setTimeout(()=>n(Error(`读取图片超时`)),12e3);r.onload=()=>{clearTimeout(i),t(r)},r.onerror=()=>{clearTimeout(i),n(Error(`无法读取这张图片,请换 JPG、PNG 或 WebP 格式`))},r.src=e})}async function mt(e){if(!(e instanceof Blob)||!e.type.startsWith(`image/`))throw new M(`format`,`请选择一张图片文件`);if(e.size>31457280)throw new M(`format`,`图片超过 30 MB,请先裁剪或压缩后再上传`);let t=`data:${e.type||`image/jpeg`};base64,${dt(new Uint8Array(await e.arrayBuffer()))}`;if(typeof document>`u`||typeof Image>`u`)return t;try{let e=await pt(t),n=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(!n||!r)return t;let i=Math.min(1,k/Math.max(n,r)),a=document.createElement(`canvas`);a.width=Math.max(1,Math.round(n*i)),a.height=Math.max(1,Math.round(r*i));let o=a.getContext(`2d`);if(!o)return t;o.fillStyle=`#ffffff`,o.fillRect(0,0,a.width,a.height),o.drawImage(e,0,0,a.width,a.height);let s=a.toDataURL(`image/jpeg`,st[0]);for(let e of st)if(s=a.toDataURL(`image/jpeg`,e),ft(s)<=A)break;return s}catch{return t}}function ht(e){return e===`record`?`识别为一条“记录”,只返回 {"title":"短标题","body":"完整正文"}。`:e===`inspiration`?`识别为一条“灵感”,只返回 {"topic":"主题","body":"完整灵感内容"}。`:`识别为一条“待办”,只返回 {"title":"简短标题","body":"待办正文","dueDate":"YYYY-MM-DD 或空字符串","tags":["标签"]}。`}function N(e,t,n=``){if(!j.has(e))throw new M(`format`,`不支持的识别类型`);if(!ut(t))throw new M(`format`,`图片内容无效,请重新上传`);return[{role:`system`,content:[`你是“简记”的图片文字识别与结构化助手。`,`请忠实读取图片中清晰可见的文字,保留原有顺序和换行;不要编造图片里没有的信息,也不要总结掉重要细节。`,`忽略手机状态栏、应用按钮、水印和与正文无关的界面文字。`,ht(e),`除 tags 外所有字段都必须返回字符串;tags 必须是字符串数组,没有标签时返回 []。`,`如果图片没有明确标题,可以根据正文提炼一个不超过 24 字的短标题;无法判断截止日期时返回空字符串。`,n?`今天是 ${n},相对日期请换算为 YYYY-MM-DD。`:``,`只输出合法 JSON,不要使用 Markdown 代码块,也不要解释。`].filter(Boolean).join(`
|
|
2
|
+
`)},{role:`user`,content:[{type:`text`,text:`请识别这张图片中的文字,并按指定 JSON 结构返回。`},{type:`image_url`,image_url:{url:t,detail:`high`}}]}]}function gt(e){let t=String(e||``).trim().replace(/^```(?:json)?\s*/i,``).replace(/\s*```$/,``);try{return JSON.parse(t)}catch{let e=t.indexOf(`{`),n=t.lastIndexOf(`}`);if(e<0||n<=e)return null;try{return JSON.parse(t.slice(e,n+1))}catch{return null}}}function _t(e,t){return String(e??``).replace(/\r\n?/g,`
|
|
3
|
+
`).trim().slice(0,t)}function vt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let e=String(r||``).trim().replace(/^#+/,``).replace(/\s+/g,` `).slice(0,20),i=e.toLocaleLowerCase(`zh-CN`);!e||n.has(i)||t.length>=8||(n.add(i),t.push(e))}return t}function yt(e,t){let n=t&&typeof t==`object`?t:{};if(e===`record`)return{title:_t(n.title??n.标题,180),body:_t(n.body??n.content??n.正文??n.内容,2e4)};if(e===`inspiration`)return{topic:_t(n.topic??n.title??n.主题??n.标题,120),body:_t(n.body??n.content??n.正文??n.内容,4e3)};let r=String(n.dueDate??n.due??n.截止日期??``).trim();return{title:_t(n.title??n.标题,180),body:_t(n.body??n.content??n.notes??n.正文??n.备注,4e3),dueDate:/^\d{4}-\d{2}-\d{2}$/.test(r)?r:``,tags:vt(n.tags??n.标签)}}async function bt(e){let t=``;try{let n=await e.json();t=String(n?.error?.message||n?.message||``).trim()}catch{}return e.status===401||e.status===403?new M(`auth`,`DeepSeek API Key 无效或已过期,请在设置中重新填写`,e.status):e.status===402?new M(`balance`,`DeepSeek 账户余额不足,充值后再试`,e.status):e.status===429?new M(`ratelimit`,`识别请求太频繁,请稍后再试`,e.status):e.status===400?new M(`badrequest`,t||`DeepSeek 无法识别这张图片,请换一张更清晰的图片`,e.status):e.status>=500?new M(`server`,`DeepSeek 服务暂时不可用,请稍后重试`,e.status):new M(`unknown`,t||`DeepSeek 返回了 ${e.status}`,e.status)}function xt(e){return new M(`network`,typeof DOMException<`u`&&e instanceof DOMException&&e.name===`AbortError`?`图片识别超时,请检查网络后重试`:`连不上 DeepSeek,请检查网络后重试`)}async function St(e,t,n,r={}){let i=ct(e),a=lt(i);if(a)throw new M(`auth`,a);let o={model:O,messages:N(n,t,r.today||new Date().toLocaleDateString(`zh-CN`)),response_format:{type:`json_object`},stream:!1,temperature:0,thinking:{type:`disabled`}},s;try{s=await fetch(ot,{method:`POST`,headers:{Authorization:`Bearer ${i}`,"Content-Type":`application/json`},body:JSON.stringify(o),signal:r.signal})}catch(e){throw r.signal?.aborted?e:xt(e)}if(!s.ok)throw await bt(s);let c;try{c=await s.json()}catch{throw new M(`format`,`DeepSeek 返回内容无法解析,请重试`)}let l=c?.choices?.[0]?.message?.content;if(typeof l!=`string`||!l.trim())throw new M(`format`,`DeepSeek 没有识别出文字,请换一张清晰的图片`);let u=gt(l);if(!u||typeof u!=`object`)throw new M(`format`,`DeepSeek 返回的数据格式不正确,请重试`);let d=yt(n,u);if(!(n===`inspiration`?d.topic||d.body:d.title||d.body))throw new M(`format`,`图片里没有识别到可用文字,请换一张更清晰的图片`);return d}async function Ct(e,t){let n=ct(e),r=lt(n);if(r)throw new M(`auth`,r);let i;try{i=await fetch(D,{headers:{Authorization:`Bearer ${n}`},signal:t})}catch(e){throw t?.aborted?e:xt(e)}if(!i.ok)throw await bt(i)}var wt=[`records`,`todos`,`inspirations`],Tt=Object.freeze({records:Object.freeze({key:`records`,filename:`records.json`,collection:`records`,label:`记录`}),todos:Object.freeze({key:`todos`,filename:`todos.json`,collection:`items`,label:`待办`}),inspirations:Object.freeze({key:`inspirations`,filename:`inspirations.json`,collection:`inspirations`,label:`灵感`})});function Et(e){return String(e||``).trim().replaceAll(`\\`,`/`).replace(/\/+/g,`/`).replace(/^\/+|\/+$/g,``).split(`/`).filter(e=>e&&e!==`.`).join(`/`)}function Dt(e){let t=String(e||``).trim().replaceAll(`\\`,`/`).replace(/^\/+/,``);if(!/\.json$/i.test(t))return Et(t);let n=t.lastIndexOf(`/`);return Et(n>=0?t.slice(0,n):``)}function Ot(e){let t=Et(e);return Object.fromEntries(wt.map(e=>[e,t?`${t}/${Tt[e].filename}`:Tt[e].filename]))}function kt(e){return!e?.remoteExists||e.force?!0:JSON.stringify(e.merged)!==JSON.stringify(e.remote)}function At(e,t,n={}){let r=Tt[e];if(!r)throw Error(`未知的同步文件:${e}`);let i={schemaVersion:Number(n.schemaVersion)||0,revision:Number(n.revision)||Date.now(),updatedAt:String(n.updatedAt||new Date().toISOString())};return e===`todos`?{...i,items:Array.isArray(t?.items)?t.items:[],commonTags:Array.isArray(t?.commonTags)?t.commonTags:[],commonTagRecords:Array.isArray(t?.commonTagRecords)?t.commonTagRecords:[],commonTagsUpdatedAt:String(t?.commonTagsUpdatedAt||``),commonTagsDeviceId:String(t?.commonTagsDeviceId||``)}:{...i,[r.collection]:Array.isArray(t?.[r.collection])?t[r.collection]:[]}}function jt(e,t){let n=Tt[e];if(!n)throw Error(`未知的同步文件:${e}`);if(Array.isArray(t)){if(e===`todos`)throw Error(`todos.json 必须是包含 items 数组的对象`);return{[n.collection]:t}}if(!t||typeof t!=`object`)throw Error(`${n.filename} 必须是 JSON 对象或数组`);if(!Array.isArray(t[n.collection]))throw Error(`${n.filename} 缺少 ${n.collection} 数组`);return t}var Mt=12;function P(e,t){return typeof e?.closest==`function`?e.closest(t):null}function Nt(e,t){let n=P(e,`[data-menu-action='status']`),r=P(n,`.task-row`),i=P(n,`[data-row-menu]`);return!n||!r||!i||i.hidden||!t||r.dataset?.id!==t?null:n}function Pt(e,t){let n=Nt(e,t);if(n)return{kind:`status`,taskId:P(n,`.task-row`)?.dataset?.id||``,status:n.dataset?.status||``,button:n};let r=P(e,`[data-action='select-task']`),i=P(r,`.task-row`)?.dataset?.id||``;return!r||!i?null:{kind:`select`,taskId:i,status:``,button:r}}function Ft(e,t,n=Mt){if(!e||!t||t.pointerType!==`touch`||t.pointerId!==e.pointerId||t.isPrimary===!1)return!1;let r=Number(t.clientX)-e.startX,i=Number(t.clientY)-e.startY;return!Number.isFinite(r)||!Number.isFinite(i)?!1:Math.hypot(r,i)<=n}(async()=>{let e=i.isNativePlatform(),t=window.parent!==window&&location.pathname.startsWith(`/jianji/app`),n=new URL(`../api/`,location.href),r=new URL(`events`,n);document.body.classList.toggle(`is-dsh-plugin`,t),e&&ie.setStyle({style:ne.Default}).catch(()=>{});let a=`1.0.23`,o=`LeonidasLux/jianji`,s=`jianji.tasks.v1`,c=`jianji.connection.v1`,l=`jianji.updater.v1`,u=`jianji.updateRelease.v1`,d=`jianji.updateHistory.v1`,f=`jianji.updateDismissed.v1`,p=`jianji.updateExported.v1`,ee=`jianji.ui.v1`,re=`jianji.deepseek.v1`,m=7776e6,ae=[300,800,1500],h=je(),oe=new Map,se=!1,ce=0,le=0,de=null,g=!1,fe=!1,pe=null,me=``,ge=``,_=null,_e=[`records`,`all`,`inspirations`],ve=[`all`,`inbox`,`doing`,`held`,`done`],ye=[`一`,`二`,`三`,`四`,`五`,`六`,`日`],be=[`todo`,`doing`,`held`,`done`],xe=[`normal`,`bold`,`underline`,`highlight`,`red`,`orange`,`green`,`blue`,`purple`],Se={normal:{label:`普通`,description:`默认文字`},bold:{label:`加粗`,description:`加粗显示`},underline:{label:`下划线`,description:`增加下划线`},highlight:{label:`强调`,description:`浅色块标记`},red:{label:`红色`,description:`重要或紧急`},orange:{label:`橙色`,description:`需要留意`},green:{label:`绿色`,description:`进展或完成`},blue:{label:`蓝色`,description:`信息与进行中`},purple:{label:`紫色`,description:`灵感与想法`}},Ce=xe.map(e=>({value:e,label:Se[e].label,description:Se[e].description,emphasis:e})),Oe=[{view:`all`,label:`全部`,tone:`all`},{view:`inbox`,label:`新建`,tone:`todo`},{view:`doing`,label:`进行中`,tone:`doing`},{view:`held`,label:`搁置`,tone:`held`},{view:`done`,label:`已完成`,tone:`done`}],v={todo:{label:`新建`,icon:`plus`},doing:{label:`进行中`,icon:`play`},held:{label:`搁置`,icon:`pause`},done:{label:`已完成`,icon:`check-circle`}},y={records:{title:`记录`,copy:`保存完整笔记、文章片段与随笔,不必进入待办流程。`},inspirations:{title:`灵感`,copy:`按主题收拢一闪而过的念头,让同一方向的想法慢慢长成体系。`},inbox:{title:`新建`,copy:`刚记录的事情会先放在这里。`,status:`todo`},all:{title:`全部`,copy:`集中查看全部待办,也可以按状态筛选。`,status:`todo`},doing:{title:`进行中`,copy:`保持工作区干净,只关注正在推进的事。`,status:`doing`},held:{title:`搁置`,copy:`暂时不做,但不要忘记为什么停下来。`,status:`held`},done:{title:`已完成`,copy:`完成过的事,也是一种进度。`,status:`done`}},b=be.map(e=>({value:e,label:v[e].label,status:e})),Ae={sortSelect:[{value:`manual`,label:`手动`},{value:`due`,label:`截止日期`},{value:`updated`,label:`最近更新`}],createStatusInput:b,detailStatusInput:b,createEmphasisInput:Ce,detailEmphasisInput:Ce},x={items:[],records:[],inspirations:[],view:`records`,sort:`manual`,mobileLayout:`list`,mobileDoneExpanded:!1,mosaicLanes:new Set,search:``,tagFilter:``,commonTags:[],commonTagRecords:[],commonTagsUpdatedAt:``,commonTagsDeviceId:``,selectedId:null,recordEditingId:null,inspirationEditingId:null,draft:null,draftTaskId:null,draftDirty:!1,draftAfter:null,createTags:[],deepseekKey:``,imageRecognition:new Map,dirty:!1,syncState:`local`,syncMessage:`仅保存在本机`,lastSyncedAt:``,syncing:!1,syncQueued:!1,deferredInstallPrompt:null,undo:null,toastTimer:null,toastExitTimer:null,pointerDragId:null,pointerDropId:null,openMenuId:null,settingsOpen:!1,settingsHistoryPushed:!1,confirmCallback:null,confirmCancelCallback:null,reminderStatus:`unknown`,reminderUpdating:!1,updateInfo:null,latestUpdate:null,updateTarget:null,releaseHistory:[],updateChecking:!1,updateHistoryOpen:!1,updateHistoryLoading:!1,updateRefreshing:!1,updateDownload:null,updatePollTimer:null,updateNoticeVersion:``,readyUpdateNoticeDismissedVersion:``,exportedUpdateVersion:``,statsOpen:!1,statsView:`overview`,statsYear:new Date().getFullYear(),statsSelectedDate:``,statsHistoryPushed:!1},S={appShell:document.getElementById(`appShell`),viewTitle:document.getElementById(`viewTitle`),viewSummary:document.getElementById(`viewSummary`),headerDate:document.getElementById(`headerDate`),listCount:document.getElementById(`listCount`),taskGroups:document.getElementById(`taskGroups`),taskScroll:document.getElementById(`taskScroll`),tagFilterWrap:document.getElementById(`tagFilterWrap`),tagFilter:document.getElementById(`tagFilter`),searchInput:document.getElementById(`searchInput`),searchLabel:document.getElementById(`searchLabel`),searchBox:document.getElementById(`searchBox`),statusFilter:document.getElementById(`statusFilter`),sortSelect:document.getElementById(`sortSelect`),layoutToggle:document.getElementById(`layoutToggle`),desktopCreateButton:document.getElementById(`desktopCreateButton`),desktopSyncDot:document.getElementById(`desktopSyncDot`),desktopSyncLabel:document.getElementById(`desktopSyncLabel`),mobileSyncBadge:document.getElementById(`mobileSyncBadge`),mobileMenuButton:document.getElementById(`mobileMenuButton`),mobileSearchPanel:document.getElementById(`mobileSearchPanel`),mobileSearchInput:document.getElementById(`mobileSearchInput`),mobileSearchLabel:document.getElementById(`mobileSearchLabel`),mobileSearchButton:document.getElementById(`mobileSearchButton`),mobileSearchClose:document.getElementById(`mobileSearchClose`),mobileRecordButton:document.getElementById(`mobileRecordButton`),mobileInspirationButton:document.getElementById(`mobileInspirationButton`),mobileCreateButton:document.getElementById(`mobileCreateButton`),syncButton:document.getElementById(`syncButton`),mobileSyncButton:document.getElementById(`mobileSyncButton`),heatmapButton:document.getElementById(`heatmapButton`),settingsButton:document.getElementById(`settingsButton`),mobileSettingsButton:document.getElementById(`mobileSettingsButton`),mobileInstallButton:document.getElementById(`mobileInstallButton`),inspector:document.getElementById(`inspector`),inspectorContent:document.getElementById(`inspectorContent`),inspectorClose:document.getElementById(`inspectorClose`),settingsPage:document.getElementById(`settingsPage`),settingsPageScroll:document.getElementById(`settingsPageScroll`),settingsForm:document.getElementById(`settingsForm`),repoInput:document.getElementById(`repoInput`),branchInput:document.getElementById(`branchInput`),pathInput:document.getElementById(`pathInput`),tokenInput:document.getElementById(`tokenInput`),autoSyncInput:document.getElementById(`autoSyncInput`),remindersEnabledInput:document.getElementById(`remindersEnabledInput`),notificationStatusHint:document.getElementById(`notificationStatusHint`),settingsError:document.getElementById(`settingsError`),settingsSyncMeta:document.getElementById(`settingsSyncMeta`),closeSettingsButton:document.getElementById(`closeSettingsButton`),cancelSettingsButton:document.getElementById(`cancelSettingsButton`),saveSettingsButton:document.getElementById(`saveSettingsButton`),disconnectButton:document.getElementById(`disconnectButton`),commonTagSettingsList:document.getElementById(`commonTagSettingsList`),commonTagInput:document.getElementById(`commonTagInput`),addCommonTagButton:document.getElementById(`addCommonTagButton`),deepseekKeyInput:document.getElementById(`deepseekKeyInput`),testDeepseekButton:document.getElementById(`testDeepseekButton`),saveDeepseekButton:document.getElementById(`saveDeepseekButton`),deepseekKeyStatus:document.getElementById(`deepseekKeyStatus`),aboutButton:document.getElementById(`aboutButton`),aboutDialog:document.getElementById(`aboutDialog`),aboutVersionLabel:document.getElementById(`aboutVersionLabel`),aboutUpdateFeedback:document.getElementById(`aboutUpdateFeedback`),closeAboutIconButton:document.getElementById(`closeAboutIconButton`),closeAboutButton:document.getElementById(`closeAboutButton`),appVersionLabel:document.getElementById(`appVersionLabel`),updateStatusHint:document.getElementById(`updateStatusHint`),updateTokenInput:document.getElementById(`updateTokenInput`),checkUpdateButton:document.getElementById(`checkUpdateButton`),updateDownloadRow:document.getElementById(`updateDownloadRow`),updateDownloadLabel:document.getElementById(`updateDownloadLabel`),updateDownloadDetail:document.getElementById(`updateDownloadDetail`),updateProgressTrack:document.getElementById(`updateProgressTrack`),updateProgressBar:document.getElementById(`updateProgressBar`),updateDownloadAction:document.getElementById(`updateDownloadAction`),updateUninstallAction:document.getElementById(`updateUninstallAction`),toggleUpdateHistoryButton:document.getElementById(`toggleUpdateHistoryButton`),updateHistoryHint:document.getElementById(`updateHistoryHint`),updateHistoryPanel:document.getElementById(`updateHistoryPanel`),updateHistoryList:document.getElementById(`updateHistoryList`),updateNotice:document.getElementById(`updateNotice`),updateNoticeTitle:document.getElementById(`updateNoticeTitle`),updateNoticeDetail:document.getElementById(`updateNoticeDetail`),updateNoticeAction:document.getElementById(`updateNoticeAction`),updateNoticeClose:document.getElementById(`updateNoticeClose`),updateNoticeIcon:document.getElementById(`updateNoticeIcon`),updateDialog:document.getElementById(`updateDialog`),updateDialogTitle:document.getElementById(`updateDialogTitle`),updateDialogCopy:document.getElementById(`updateDialogCopy`),updateReleaseVersion:document.getElementById(`updateReleaseVersion`),updateReleaseMeta:document.getElementById(`updateReleaseMeta`),updateReleaseNotes:document.getElementById(`updateReleaseNotes`),updateError:document.getElementById(`updateError`),closeUpdateButton:document.getElementById(`closeUpdateButton`),laterUpdateButton:document.getElementById(`laterUpdateButton`),installUpdateButton:document.getElementById(`installUpdateButton`),confirmDialog:document.getElementById(`confirmDialog`),confirmTitle:document.getElementById(`confirmTitle`),confirmMessage:document.getElementById(`confirmMessage`),confirmCancelButton:document.getElementById(`confirmCancelButton`),confirmAcceptButton:document.getElementById(`confirmAcceptButton`),dispatchDialog:document.getElementById(`dispatchDialog`),dispatchDialogTask:document.getElementById(`dispatchDialogTask`),dispatchPromptInput:document.getElementById(`dispatchPromptInput`),dispatchError:document.getElementById(`dispatchError`),dispatchCloseButton:document.getElementById(`dispatchCloseButton`),dispatchCancelButton:document.getElementById(`dispatchCancelButton`),dispatchConfirmButton:document.getElementById(`dispatchConfirmButton`),savePromptDialog:document.getElementById(`savePromptDialog`),continueEditingButton:document.getElementById(`continueEditingButton`),discardDraftButton:document.getElementById(`discardDraftButton`),saveAndLeaveButton:document.getElementById(`saveAndLeaveButton`),createDialog:document.getElementById(`createDialog`),createTaskForm:document.getElementById(`createTaskForm`),createTitleInput:document.getElementById(`createTitleInput`),createBodyInput:document.getElementById(`createBodyInput`),createStatusInput:document.getElementById(`createStatusInput`),createDueInput:document.getElementById(`createDueInput`),createEmphasisInput:document.getElementById(`createEmphasisInput`),createTagList:document.getElementById(`createTagList`),createTaskError:document.getElementById(`createTaskError`),createCloseButton:document.getElementById(`createCloseButton`),createCancelButton:document.getElementById(`createCancelButton`),createSaveButton:document.getElementById(`createSaveButton`),appPicker:document.getElementById(`appPicker`),appPickerClose:document.getElementById(`appPickerClose`),appPickerTitle:document.getElementById(`appPickerTitle`),appPickerBody:document.getElementById(`appPickerBody`),recordDialog:document.getElementById(`recordDialog`),recordDialogTitle:document.getElementById(`recordDialogTitle`),recordDialogCopy:document.getElementById(`recordDialogCopy`),recordDialogMeta:document.getElementById(`recordDialogMeta`),recordForm:document.getElementById(`recordForm`),recordTitleInput:document.getElementById(`recordTitleInput`),recordBodyInput:document.getElementById(`recordBodyInput`),recordError:document.getElementById(`recordError`),recordCloseButton:document.getElementById(`recordCloseButton`),recordCancelButton:document.getElementById(`recordCancelButton`),recordSaveButton:document.getElementById(`recordSaveButton`),recordDeleteButton:document.getElementById(`recordDeleteButton`),inspirationDialog:document.getElementById(`inspirationDialog`),inspirationDialogTitle:document.getElementById(`inspirationDialogTitle`),inspirationDialogCopy:document.getElementById(`inspirationDialogCopy`),inspirationDialogMeta:document.getElementById(`inspirationDialogMeta`),inspirationForm:document.getElementById(`inspirationForm`),inspirationTopicInput:document.getElementById(`inspirationTopicInput`),inspirationBodyInput:document.getElementById(`inspirationBodyInput`),inspirationError:document.getElementById(`inspirationError`),inspirationCloseButton:document.getElementById(`inspirationCloseButton`),inspirationCancelButton:document.getElementById(`inspirationCancelButton`),inspirationSaveButton:document.getElementById(`inspirationSaveButton`),inspirationDeleteButton:document.getElementById(`inspirationDeleteButton`),recordDrawer:document.getElementById(`recordDrawer`),recordDrawerCloseButton:document.getElementById(`recordDrawerCloseButton`),drawerHeatmapGrid:document.getElementById(`drawerHeatmapGrid`),drawerHeatmapHelpButton:document.getElementById(`drawerHeatmapHelpButton`),drawerStatsButton:document.getElementById(`drawerStatsButton`),drawerRecordCount:document.getElementById(`drawerRecordCount`),drawerRecordDays:document.getElementById(`drawerRecordDays`),drawerRecordTags:document.getElementById(`drawerRecordTags`),heatmapHelpDialog:document.getElementById(`heatmapHelpDialog`),closeHeatmapHelpButton:document.getElementById(`closeHeatmapHelpButton`),heatmapLearnMoreButton:document.getElementById(`heatmapLearnMoreButton`),statsPage:document.getElementById(`statsPage`),statsPageScroll:document.getElementById(`statsPageScroll`),statsPageContent:document.getElementById(`statsPageContent`),statsPageTitle:document.getElementById(`statsPageTitle`),statsPageCopy:document.getElementById(`statsPageCopy`),statsBackButton:document.getElementById(`statsBackButton`),statsCloseButton:document.getElementById(`statsCloseButton`),toast:document.getElementById(`toast`),toastMessage:document.getElementById(`toastMessage`),toastAction:document.getElementById(`toastAction`)};function je(){try{let e=localStorage.getItem(`jianji.device.v1`);if(e)return e;let t=crypto.randomUUID?crypto.randomUUID():`device-${Date.now()}-${Math.random().toString(16).slice(2)}`;return localStorage.setItem(`jianji.device.v1`,t),t}catch{return`device-${Date.now()}-${Math.random().toString(16).slice(2)}`}}function Me(e){try{return localStorage.getItem(e)}catch{return oe.get(e)||null}}function Ne(e,t){try{localStorage.setItem(e,t)}catch{oe.set(e,t)}}function C(e,t){try{let n=Me(e);return n?JSON.parse(n):t}catch{return t}}function w(e,t){Ne(e,JSON.stringify(t))}function Fe(e,t={}){return fetch(new URL(e,n),{cache:`no-store`,...t,headers:{Accept:`application/json`,"X-Jianji-Request":`1`,...t.body?{"Content-Type":`application/json`}:{},...t.headers||{}}})}function Le(e){return{schemaVersion:7,items:Array.isArray(e?.items)?e.items:[],records:Array.isArray(e?.records)?e.records:[],inspirations:Array.isArray(e?.inspirations)?e.inspirations:[],commonTags:A(e?.commonTags,50),commonTagRecords:j(e?.commonTagRecords),commonTagsUpdatedAt:String(e?.commonTagsUpdatedAt||``),commonTagsDeviceId:String(e?.commonTagsDeviceId||``),dirty:!!e?.dirty,lastSyncedAt:String(e?.lastSyncedAt||``)}}function Re(){return Le({items:x.items,records:x.records,inspirations:x.inspirations,commonTags:x.commonTags,commonTagRecords:x.commonTagRecords,commonTagsUpdatedAt:x.commonTagsUpdatedAt,commonTagsDeviceId:x.commonTagsDeviceId,dirty:x.dirty,lastSyncedAt:x.lastSyncedAt})}function ze(e){if(!e||typeof e!=`object`)return!1;let t=Le(e);return w(s,t),x.items=t.items.filter(gt).map(yt),x.records=t.records.filter(bt).map(xt),x.inspirations=t.inspirations.filter(Mt).map(Lt),x.commonTags=t.commonTags,x.commonTagRecords=t.commonTagRecords,x.commonTagsUpdatedAt=t.commonTagsUpdatedAt,x.commonTagsDeviceId=t.commonTagsDeviceId,x.dirty=t.dirty,x.lastSyncedAt=t.lastSyncedAt,ce=Number(e.revision)||ce,!0}async function Ye(){let e=await Fe(`state`);if(!e.ok)throw Error(await et(e,`读取 DSH 数据失败`));let t=await e.json();ce=Number(t.revision)||0,ce>0&&ze(t)}async function Xe({force:e=!1}={}){if(!(!t||fe||!e&&(g||de))){fe=!0;try{let t=await Fe(`state`);if(!t.ok)throw Error(await et(t,`读取 DSH 数据失败`));let n=await t.json(),r=Number(n.revision)||0;if(!e&&r===ce)return;ze(n),U()}catch(e){console.warn(`读取 DSH 简记数据失败`,e)}finally{fe=!1}}}async function Ze(){if(!t||!se||!le||g)return;let e=le;g=!0;try{let t=await Fe(`state`,{method:`POST`,body:JSON.stringify(Re())});if(!t.ok)throw Error(await et(t,`保存 DSH 数据失败`));let n=await t.json();e===le&&(ze(n),Er())}catch(e){console.warn(`保存 DSH 简记数据失败`,e),X(`error`,`保存到 DSH 失败,本机数据仍保留`)}finally{g=!1,e!==le&&Qe()}}function Qe(e=!1){t&&se&&(le+=1,clearTimeout(de),e?(de=null,Ze()):de=setTimeout(()=>{de=null,Ze()},120))}function $e(){t&&typeof EventSource==`function`&&(pe?.close(),pe=new EventSource(r),pe.onmessage=e=>{try{let t=JSON.parse(e.data);(Number(t.revision)||0)!==ce&&Xe()}catch{}},pe.onerror=()=>{Xe()},window.addEventListener(`focus`,()=>{Xe()}),document.addEventListener(`visibilitychange`,()=>{document.hidden||Xe()}))}async function et(e,t){try{let t=await e.json();if(t&&typeof t.message==`string`&&t.message.trim())return t.message}catch{}return`${t}(${e.status})`}function tt(e){t&&window.parent!==window&&window.parent.postMessage(e,`*`)}function nt(e){return typeof structuredClone==`function`?structuredClone(e):JSON.parse(JSON.stringify(e))}function T(){return new Date().toISOString()}function rt(e){return new Promise(t=>setTimeout(t,e))}function E(e=new Date){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function ot(e){let t=new Date;return t.setHours(12,0,0,0),t.setDate(t.getDate()+e),E(t)}function D(e){if(!e)return null;let[t,n,r]=e.split(`-`).map(Number);return!t||!n||!r?null:new Date(t,n-1,r,12,0,0,0)}function O(e){return String(e||``).trim().replace(/^#+/,``).replace(/\s+/g,` `).slice(0,20)}function k(e){return O(e).toLocaleLowerCase(`zh-CN`)}function A(e,t=8){if(!Array.isArray(e))return[];let n=[],r=new Set;return e.forEach(e=>{let i=O(e),a=k(i);!i||r.has(a)||n.length>=t||(r.add(a),n.push(i))}),n}function st(e){let t=O(e?.value??e?.tag);return t?{value:t,updatedAt:String(e?.updatedAt||``),deletedAt:String(e?.deletedAt||``),deviceId:String(e?.deviceId||``)}:null}function j(e){if(!Array.isArray(e))return[];let t=new Map;e.forEach(e=>{let n=st(e);if(!n)return;let r=k(n.value),i=t.get(r),a=i?Ao(n,i):1;(!i||a>0||a===0&&n.deletedAt&&!i.deletedAt)&&t.set(r,n)});let n=Date.now()-m;return[...t.values()].filter(e=>{if(!e.deletedAt)return!0;let t=new Date(e.deletedAt).getTime();return Number.isFinite(t)&&t>n})}function ut(e,t=``,n=``){return A(e,50).map(e=>({value:e,updatedAt:String(t||``),deletedAt:``,deviceId:String(n||``)}))}function dt(e){return A(j(e).filter(e=>!e.deletedAt).map(e=>e.value),50)}function ft(e){return A(e.flatMap(e=>Array.isArray(e.tags)?e.tags:[]),50)}function pt(){return[]}function ht(){let e=C(s,null);if(e&&Array.isArray(e.items)){x.items=e.items.filter(gt).map(yt),x.records=Array.isArray(e.records)?e.records.filter(bt).map(xt):[],x.inspirations=Array.isArray(e.inspirations)?e.inspirations.filter(Mt).map(Lt):[];let t=Object.hasOwn(e,`commonTags`),n=Object.hasOwn(e,`commonTagRecords`);if(x.commonTags=A(e.commonTags,50),x.commonTagRecords=j(e.commonTagRecords),x.commonTagsUpdatedAt=t?String(e.commonTagsUpdatedAt||``):``,x.commonTagsDeviceId=t?String(e.commonTagsDeviceId||``):``,x.dirty=!!e.dirty,x.lastSyncedAt=e.lastSyncedAt||``,!t){let e=ft(x.items.filter(e=>!e.deletedAt));e.length&&(x.commonTags=e,x.commonTagsUpdatedAt=T(),x.commonTagsDeviceId=h,x.dirty=!0)}n?x.commonTags=dt(x.commonTagRecords):x.commonTagRecords=ut(x.commonTags,x.commonTagsUpdatedAt,x.commonTagsDeviceId),t&&n&&Number(e.schemaVersion)===7||$r(!1)}else x.items=pt(),x.records=[],x.inspirations=[],x.commonTags=[],x.commonTagRecords=[],x.commonTagsUpdatedAt=``,x.commonTagsDeviceId=``,x.dirty=!1,$r(!1);let t=C(ee,{});x.view=y[t.view]?t.view:`records`,x.sort=[`manual`,`due`,`updated`].includes(t.sort)?t.sort:`manual`,x.mobileLayout=t.mobileLayout===`cards`?`cards`:`list`,x.mosaicLanes=new Set(Array.isArray(t.mosaicLanes)?t.mosaicLanes.filter(e=>be.includes(e)):[]),window.innerWidth<=760&&!_e.includes(x.view)&&(x.view=`records`)}function N(){w(ee,{view:x.view,sort:x.sort,mobileLayout:x.mobileLayout,mosaicLanes:[...x.mosaicLanes]})}function gt(e){return e&&typeof e.id==`string`&&typeof e.title==`string`}function _t(e){if(!e||typeof e!=`object`)return null;let t=String(e.sessionId||``),n=String(e.workspaceId||``);return!t||!n?null:{sessionId:t,workspaceId:n,prompt:String(e.prompt||``).slice(0,8e3),dispatchedAt:String(e.dispatchedAt||``)}}function vt(e){return Se[e]?e:`normal`}function yt(e){let t=String(e.id||``).replace(/[^a-zA-Z0-9_-]/g,``).slice(0,120)||`task-${Date.now()}-${Math.random().toString(16).slice(2)}`,n=v[e.status]?e.status:`todo`;return{id:t,title:String(e.title||``).slice(0,180),notes:String(e.notes||``).slice(0,4e3),status:n,emphasis:vt(e.emphasis),completedAt:n===`done`?String(e.completedAt||e.updatedAt||e.createdAt||T()):``,dueDate:/^\d{4}-\d{2}-\d{2}$/.test(e.dueDate||``)?e.dueDate:``,tags:A(e.tags,8),pinned:!!e.pinned,order:Number.isFinite(e.order)?e.order:0,createdAt:e.createdAt||T(),updatedAt:e.updatedAt||T(),deletedAt:e.deletedAt||``,deviceId:e.deviceId||h,dispatch:_t(e.dispatch)}}function bt(e){return e&&typeof e.id==`string`&&typeof e.body==`string`}function xt(e){return{id:String(e.id||``).replace(/[^a-zA-Z0-9_-]/g,``).slice(0,120)||`record-${Date.now()}-${Math.random().toString(16).slice(2)}`,title:String(e.title||``).slice(0,180),body:String(e.body||``).slice(0,2e4),createdAt:e.createdAt||T(),updatedAt:e.updatedAt||T(),deletedAt:e.deletedAt||``,deviceId:e.deviceId||h}}function Mt(e){return e&&typeof e.id==`string`&&typeof e.topic==`string`&&typeof e.body==`string`}function P(e){return String(e||``).trim().replace(/\s+/g,` `).slice(0,120)}function It(e){return P(e).toLocaleLowerCase(`zh-CN`)}function Lt(e){return{id:String(e.id||``).replace(/[^a-zA-Z0-9_-]/g,``).slice(0,120)||`inspiration-${Date.now()}-${Math.random().toString(16).slice(2)}`,topic:P(e.topic)||`未命名主题`,body:String(e.body||``).slice(0,4e3),createdAt:e.createdAt||T(),updatedAt:e.updatedAt||T(),deletedAt:e.deletedAt||``,deviceId:e.deviceId||h}}function Rt(){let e=C(c,{}),t=String(e.path||``).trim().replaceAll(`\\`,`/`).replace(/^\/+/,``),n=Object.hasOwn(e,`directory`),r=n?Et(e.directory):Dt(t),i=Ot(r),a=String(e.legacyPath||``).trim().replaceAll(`\\`,`/`).replace(/^\/+/,``)||(!n&&t&&!Object.values(i).includes(t)?t:``);return{repo:String(e.repo||``),branch:String(e.branch||`master`),directory:r,legacyPath:a,token:String(e.token||``),autoSync:e.autoSync!==!1}}let F=Rt();function zt(){return{apiKey:ct(C(re,{}).apiKey||``)}}let Bt=zt();x.deepseekKey=Bt.apiKey;function Vt(e){Bt={apiKey:ct(e)},x.deepseekKey=Bt.apiKey,w(re,Bt)}function Ht(){let e=C(l,{});return{token:String(e.token||``)}}let I=Ht();function Ut(e){I={token:String(e.token||``).trim()},w(l,I)}function Wt(e){let t=Object.hasOwn(e,`directory`)?Et(e.directory):Dt(e.path);F={repo:e.repo||``,branch:e.branch||`master`,directory:t,legacyPath:String(e.legacyPath||``).trim().replaceAll(`\\`,`/`).replace(/^\/+/,``),token:e.token||``,autoSync:e.autoSync!==!1},w(c,F)}function L(e){return String(e).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`)}function R(e){return`<svg class="od-icon" aria-hidden="true"><use href="#icon-${e}"></use></svg>`}function Gt(e){let t=e.dataset.pickerType||``;return{type:t,title:e.dataset.pickerTitle||`选择`,options:t===`select`?[...Ae[e.id]||[]]:[]}}function Kt(e){let t=D(e);return t?e===E()?`今天 · ${t.getMonth()+1}月${t.getDate()}日`:e===ot(1)?`明天 · ${t.getMonth()+1}月${t.getDate()}日`:new Intl.DateTimeFormat(`zh-CN`,{year:`numeric`,month:`long`,day:`numeric`}).format(t):`选择日期`}function qt(e){return e?.dataset.value||``}function Jt(e,t,{dispatch:n=!1}={}){if(!e)return;let r=String(t||``),i=qt(e)!==r,a=Gt(e),o=e.querySelector(`[data-picker-label]`),s=e.querySelector(`.picker-status-marker`),c=e.querySelector(`.picker-emphasis-marker`),l=r;a.type===`date`?(l=Kt(r),e.classList.toggle(`is-placeholder`,!r)):(l=a.options.find(e=>e.value===r)?.label||r,s&&(s.dataset.status=r),c&&(c.dataset.emphasisPreview=vt(r))),e.dataset.value=r,o&&(o.textContent=l),e.setAttribute(`aria-label`,`${a.title}:${l}`),e.title=a.type===`date`&&r?Xt(r):`${a.title}:${l}`,n&&i&&e.dispatchEvent(new Event(`change`,{bubbles:!0}))}function Yt(e){Jt(e,qt(e))}function Xt(e){let t=D(e);return t?new Intl.DateTimeFormat(`zh-CN`,{year:`numeric`,month:`long`,day:`numeric`,weekday:`long`}).format(t):``}function Zt(e){return new Intl.DateTimeFormat(`zh-CN`,{year:`numeric`,month:`long`}).format(e)}function Qt(){let{options:e}=_.config,t=qt(_.trigger);S.appPickerBody.innerHTML=`
|
|
4
|
+
<div class="app-picker-options" id="appPickerOptions" role="listbox" aria-label="${L(_.config.title)}">
|
|
5
|
+
${e.map((e,n)=>`
|
|
6
|
+
<button class="app-picker-option" id="appPickerOption-${n}" type="button" role="option" aria-selected="${e.value===t}" data-picker-value="${L(e.value)}">
|
|
7
|
+
<span class="app-picker-option-copy">
|
|
8
|
+
${e.emphasis?`<span class="app-picker-emphasis-preview" data-emphasis-preview="${e.emphasis}" aria-hidden="true"><span class="task-emphasis-text">文</span></span>`:e.status?`<span class="picker-status-marker" data-status="${e.status}" aria-hidden="true"></span>`:``}
|
|
9
|
+
<span class="app-picker-option-text">
|
|
10
|
+
<span>${L(e.label)}</span>
|
|
11
|
+
${e.description?`<small>${L(e.description)}</small>`:``}
|
|
12
|
+
</span>
|
|
13
|
+
</span>
|
|
14
|
+
<span class="app-picker-option-check" aria-hidden="true">${e.value===t?R(`check`):``}</span>
|
|
15
|
+
</button>`).join(``)}
|
|
16
|
+
</div>`,requestAnimationFrame(()=>{(S.appPickerBody.querySelector(`.app-picker-option[aria-selected="true"]`)||S.appPickerBody.querySelector(`.app-picker-option`))?.focus()})}function $t({focusMonth:e=``}={}){let t=qt(_.trigger),n=_.cursor,r=new Date(n.getFullYear(),n.getMonth(),1,12),i=En(r,-((r.getDay()+6)%7)),a=E(),o=Array.from({length:42},(e,n)=>{let o=En(i,n),s=E(o);return{key:s,date:o,outside:o.getMonth()!==r.getMonth(),today:s===a,selected:s===t}});S.appPickerBody.innerHTML=`
|
|
17
|
+
<div class="app-picker-calendar">
|
|
18
|
+
<div class="app-picker-month">
|
|
19
|
+
<button class="app-picker-month-nav" type="button" data-picker-month="-1" aria-label="上个月">${R(`chevron-left`)}</button>
|
|
20
|
+
<strong>${Zt(r)}</strong>
|
|
21
|
+
<button class="app-picker-month-nav" type="button" data-picker-month="1" aria-label="下个月">${R(`chevron-right`)}</button>
|
|
22
|
+
</div>
|
|
23
|
+
<div class="app-picker-weekdays" aria-hidden="true">
|
|
24
|
+
${ye.map(e=>`<span>${e}</span>`).join(``)}
|
|
25
|
+
</div>
|
|
26
|
+
<div class="app-picker-days" role="grid" aria-label="${Zt(r)}">
|
|
27
|
+
${o.map(e=>`
|
|
28
|
+
<button class="app-picker-day${e.outside?` is-outside`:``}${e.today?` is-today`:``}${e.selected?` is-selected`:``}" type="button" data-picker-date="${e.key}" aria-label="${Xt(e.key)}" aria-pressed="${e.selected}">
|
|
29
|
+
${e.date.getDate()}
|
|
30
|
+
</button>`).join(``)}
|
|
31
|
+
</div>
|
|
32
|
+
<div class="app-picker-quick" aria-label="快捷选择日期">
|
|
33
|
+
<button type="button" data-picker-date="${E()}">今天</button>
|
|
34
|
+
<button type="button" data-picker-date="${ot(1)}">明天</button>
|
|
35
|
+
<button type="button" data-picker-date="${ot(7)}">一周后</button>
|
|
36
|
+
<button class="is-clear" type="button" data-picker-clear>清除</button>
|
|
37
|
+
</div>
|
|
38
|
+
</div>`,requestAnimationFrame(()=>{e?S.appPickerBody.querySelector(`[data-picker-month="${e}"]`)?.focus():(S.appPickerBody.querySelector(`.app-picker-day.is-selected`)||S.appPickerBody.querySelector(`.app-picker-day.is-today`)||S.appPickerBody.querySelector(`.app-picker-day`))?.focus()})}function en(){_&&(S.appPickerTitle.textContent=_.config.title,S.appPicker.classList.toggle(`is-date`,_.config.type===`date`),S.appPicker.classList.toggle(`is-select`,_.config.type===`select`),_.config.type===`date`?$t():Qt())}function tn(){if(!_||!S.appPicker.open)return;if(window.innerWidth<=760){S.appPicker.classList.add(`is-sheet`),S.appPicker.style.removeProperty(`left`),S.appPicker.style.removeProperty(`top`),S.appPicker.style.removeProperty(`width`);return}S.appPicker.classList.remove(`is-sheet`);let e=_.trigger.getBoundingClientRect(),t=_.config.type===`date`?344:Math.max(240,Math.min(300,e.width));S.appPicker.style.width=`${t}px`,S.appPicker.style.left=`12px`,S.appPicker.style.top=`12px`;let n=S.appPicker.getBoundingClientRect(),r=e.left;r+t>window.innerWidth-12&&(r=e.right-t),r=Math.max(12,Math.min(r,window.innerWidth-t-12));let i=e.bottom+8;i+n.height>window.innerHeight-12&&(i=e.top-n.height-8),i=Math.max(12,Math.min(i,window.innerHeight-n.height-12)),S.appPicker.style.left=`${r}px`,S.appPicker.style.top=`${i}px`}function nn(e){if(!e)return;if(S.appPicker.open&&_?.trigger===e){rn();return}let t=Gt(e);t.type&&(_={trigger:e,config:t,cursor:D(qt(e))||V()},e.setAttribute(`aria-expanded`,`true`),en(),typeof S.appPicker.showModal==`function`?S.appPicker.showModal():S.appPicker.setAttribute(`open`,``),tn())}function rn(){S.appPicker.open?S.appPicker.close():S.appPicker.removeAttribute(`open`)}function an(e){if(!_)return;let t=_.trigger;Jt(t,e,{dispatch:!0}),rn()}function on(e){_&&_.config.type===`date`&&(_.cursor=new Date(_.cursor.getFullYear(),_.cursor.getMonth()+e,1,12),$t({focusMonth:e>0?`1`:`-1`}),tn())}function sn(){let e=Date.now()-m;return x.items.filter(t=>!t.deletedAt||new Date(t.deletedAt).getTime()>e)}function z(){return sn().filter(e=>!e.deletedAt)}function cn(){let e=Date.now()-m;return x.records.filter(t=>!t.deletedAt||new Date(t.deletedAt).getTime()>e)}function ln(){return cn().filter(e=>!e.deletedAt)}function un(){let e=Date.now()-m;return x.inspirations.filter(t=>!t.deletedAt||new Date(t.deletedAt).getTime()>e)}function dn(){return un().filter(e=>!e.deletedAt)}function fn(){return z().find(e=>e.id===x.selectedId)||null}function pn(e){if(!x.search)return!0;let t=x.search.trim().toLocaleLowerCase(`zh-CN`);return!t||[e.title,e.notes,e.tags.join(` `)].some(e=>String(e).toLocaleLowerCase(`zh-CN`).includes(t))}function mn(e){if(!x.search)return!0;let t=x.search.trim().toLocaleLowerCase(`zh-CN`);return!t||[e.title,e.body].some(e=>String(e).toLocaleLowerCase(`zh-CN`).includes(t))}function hn(e=!0){return ln().filter(t=>!e||mn(t)).sort((e,t)=>new Date(t.updatedAt)-new Date(e.updatedAt))}function gn(e){if(!x.search)return!0;let t=x.search.trim().toLocaleLowerCase(`zh-CN`);return!t||[e.topic,e.body].some(e=>String(e).toLocaleLowerCase(`zh-CN`).includes(t))}function _n(e=!0){return dn().filter(t=>!e||gn(t)).sort((e,t)=>new Date(t.updatedAt)-new Date(e.updatedAt))}function vn(){let e=new Map;return _n().forEach(t=>{let n=It(t.topic),r=e.get(n);r||(r={key:n,topic:t.topic,items:[],updatedAt:t.updatedAt},e.set(n,r)),r.items.push(t),new Date(t.updatedAt)>new Date(r.updatedAt)&&(r.updatedAt=t.updatedAt)}),[...e.values()].map(e=>({...e,items:e.items.sort((e,t)=>new Date(t.updatedAt)-new Date(e.updatedAt))})).sort((e,t)=>new Date(t.updatedAt)-new Date(e.updatedAt))}function yn(e=x.view){return ve.includes(e)}function bn(e){return!x.tagFilter||e.tags.includes(x.tagFilter)}function xn(e){let t=k(e);return!!t&&x.commonTags.some(e=>k(e)===t)}function B(e=x.view,t=!0,n=!0){return z().filter(t=>e===`all`?!0:e===`inbox`?t.status===`todo`:t.status===e).filter(e=>!t||pn(e)).filter(e=>!n||bn(e))}function Sn(e){let t=[...e];return x.sort===`due`?t.sort((e,t)=>e.pinned===t.pinned?!e.dueDate&&t.dueDate?1:e.dueDate&&!t.dueDate?-1:e.dueDate.localeCompare(t.dueDate)||e.order-t.order:e.pinned?-1:1):x.sort===`updated`?t.sort((e,t)=>e.pinned===t.pinned?new Date(t.updatedAt)-new Date(e.updatedAt):e.pinned?-1:1):t.sort((e,t)=>e.pinned===t.pinned?e.order-t.order||new Date(e.createdAt)-new Date(t.createdAt):e.pinned?-1:1)}function Cn(e){return[...e].sort((e,t)=>new Date(t.completedAt||t.updatedAt).getTime()-new Date(e.completedAt||e.updatedAt).getTime()||e.order-t.order)}function wn(){let e=B();if(x.view===`all`)return be.map(t=>({status:t,items:t===`done`?Cn(e.filter(e=>e.status===t)):Sn(e.filter(e=>e.status===t))})).filter(e=>e.items.length);let t=x.view===`inbox`?`todo`:x.view;return e.length?[{status:t,items:t===`done`?Cn(e):Sn(e)}]:[]}function Tn(){let e=new Intl.DateTimeFormat(`zh-CN`,{month:`long`,day:`numeric`,weekday:`long`}).format(new Date);S.headerDate.textContent=e}function V(e=new Date){let t=(e instanceof Date,new Date(e));return Number.isNaN(t.getTime())?null:(t.setHours(12,0,0,0),t)}function En(e,t){let n=V(e);return n.setDate(n.getDate()+t),n}function Dn(e=new Date){let t=V(e),n=(t.getDay()+6)%7;return t.setDate(t.getDate()-n),t}function On(e,t){let n=V(e),r=V(t);return Math.round((r-n)/864e5)}function kn(){return[...ln().map(e=>({kind:`record`,id:e.id,createdAt:e.createdAt,item:e})),...dn().map(e=>({kind:`inspiration`,id:e.id,createdAt:e.createdAt,item:e})),...z().map(e=>({kind:`task`,id:e.id,createdAt:e.createdAt,item:e}))].filter(e=>V(e.createdAt)).sort((e,t)=>new Date(t.createdAt)-new Date(e.createdAt))}function An(e=kn()){let t=new Map;return e.forEach(e=>{let n=V(e.createdAt);if(!n)return;let r=E(n);t.has(r)||t.set(r,[]),t.get(r).push(e)}),t}function jn(e){return e?Math.min(4,e):0}function Mn(e){return[...String(e||``).matchAll(/#([\p{L}\p{N}_-]{1,20})/gu)].map(e=>e[1])}function Nn(e){if(e.kind===`task`){let t=Array.isArray(e.item.tags)?e.item.tags:[];return[...new Set([...t,...Mn(`${e.item.title||``} ${e.item.notes||``}`)])]}return[...new Set(Mn(e.kind===`inspiration`?`${e.item.topic||``} ${e.item.body||``}`:e.item.body))]}function Pn(e){return e.kind===`task`?`${e.item.title||``}${e.item.notes||``}`.replace(/\s/g,``).length:e.kind===`inspiration`?`${e.item.topic||``}${e.item.body||``}`.replace(/\s/g,``).length:String(e.item.body||``).replace(/\s/g,``).length}function Fn(e=kn()){let t=An(e),n=new Set;e.forEach(e=>{Nn(e).forEach(e=>n.add(e))});let r=e.map(e=>V(e.createdAt)).filter(Boolean).sort((e,t)=>e-t),i=r.length?On(r[0],V()):0;return{contentCount:e.length,spanDays:Math.max(0,i),tagCount:n.size,grouped:t}}function In(e,t=new Date){let n=V(t),r=E(n),i=En(Dn(n),-(e-1)*7);return Array.from({length:e},(e,t)=>Array.from({length:7},(e,n)=>{let a=En(i,t*7+n);return{date:a,key:E(a),isFuture:E(a)>r}}))}function Ln(e){let t=D(e);return t?`${t.getFullYear()}/${String(t.getMonth()+1).padStart(2,`0`)}/${String(t.getDate()).padStart(2,`0`)}`:``}function Rn(e){let t=D(e);return t?new Intl.DateTimeFormat(`zh-CN`,{year:`numeric`,month:`long`,day:`numeric`}).format(t):``}function zn(e,t=An(),n=``){let r=e.map(e=>{let t=e.find(e=>e.date.getDate()===1);return t?`${t.date.getMonth()+1}月`:``});return`
|
|
39
|
+
<div class="heatmap-grid-layout">
|
|
40
|
+
<div class="heatmap-weeks">
|
|
41
|
+
${e.map(e=>`
|
|
42
|
+
<div class="heatmap-week">
|
|
43
|
+
${e.map(e=>{let r=(t.get(e.key)||[]).length,i=jn(r),a=r?`${r} 项内容`:`没有内容`;return`
|
|
44
|
+
<button
|
|
45
|
+
class="heatmap-cell level-${i}${e.isFuture?` is-future`:``}${e.key===E()?` is-today`:``}${e.key===n?` is-selected`:``}"
|
|
46
|
+
type="button"
|
|
47
|
+
data-heatmap-date="${e.key}"
|
|
48
|
+
aria-label="${Rn(e.key)},${a}"
|
|
49
|
+
${e.key===n?`aria-current="date"`:``}
|
|
50
|
+
${e.isFuture?`disabled`:``}
|
|
51
|
+
></button>`}).join(``)}
|
|
52
|
+
</div>`).join(``)}
|
|
53
|
+
</div>
|
|
54
|
+
<div class="heatmap-weekdays" aria-hidden="true">
|
|
55
|
+
${ye.map(e=>`<span>${e}</span>`).join(``)}
|
|
56
|
+
</div>
|
|
57
|
+
</div>
|
|
58
|
+
<div class="heatmap-months-layout" aria-hidden="true">
|
|
59
|
+
<div class="heatmap-months">
|
|
60
|
+
${r.map(e=>`<span>${e}</span>`).join(``)}
|
|
61
|
+
</div>
|
|
62
|
+
<span class="heatmap-months-spacer"></span>
|
|
63
|
+
</div>
|
|
64
|
+
<div class="heatmap-tooltip" role="status" hidden></div>
|
|
65
|
+
`}function Bn(){let e=Fn();S.drawerRecordCount.textContent=String(e.contentCount),S.drawerRecordDays.textContent=String(e.spanDays),S.drawerRecordTags.textContent=String(e.tagCount),S.drawerHeatmapGrid.innerHTML=zn(In(17),e.grouped)}function Vn(){document.querySelectorAll(`.heatmap-tooltip`).forEach(e=>{e.hidden=!0}),document.querySelectorAll(`.heatmap-cell[aria-expanded='true']`).forEach(e=>{e.removeAttribute(`aria-expanded`)})}function Hn(e){let t=e.closest(`.heatmap-grid-shell`),n=t?.querySelector(`.heatmap-tooltip`),r=e.dataset.heatmapDate;if(!t||!n||!r)return;Vn();let i=An().get(r)||[];n.innerHTML=`
|
|
66
|
+
<strong>${i.length?`${i.length} 项内容`:`没有内容`}</strong>
|
|
67
|
+
<span>${Ln(r)}</span>
|
|
68
|
+
`,n.hidden=!1,e.setAttribute(`aria-expanded`,`true`);let a=t.getBoundingClientRect(),o=e.getBoundingClientRect(),s=o.left-a.left+o.width/2,c=Math.max(82,t.clientWidth-82),l=Math.min(c,Math.max(82,s)),u=o.bottom-a.top+8,d=o.top-a.top-n.offsetHeight-8,f=u+n.offsetHeight<=t.clientHeight?u:Math.max(0,d);n.style.left=`${l}px`,n.style.top=`${f}px`}function Un(e){let t=[...e.keys()].sort();if(!t.length)return 0;let n=1,r=1;for(let e=1;e<t.length;e+=1)r=On(D(t[e-1]),D(t[e]))===1?r+1:1,n=Math.max(n,r);return n}function Wn(e){let t=kn().filter(t=>{let n=V(t.createdAt);return n&&n.getFullYear()===e}),n=An(t);return{entries:t,grouped:n,activeDays:n.size,characterCount:t.reduce((e,t)=>e+Pn(t),0),longestStreak:Un(n)}}function Gn(){return`
|
|
69
|
+
<div class="heatmap-legend" aria-label="颜色越深,当天创建的内容越多">
|
|
70
|
+
<span>少</span>
|
|
71
|
+
<span class="heatmap-legend-cell level-0" aria-hidden="true"></span>
|
|
72
|
+
<span class="heatmap-legend-cell level-1" aria-hidden="true"></span>
|
|
73
|
+
<span class="heatmap-legend-cell level-2" aria-hidden="true"></span>
|
|
74
|
+
<span class="heatmap-legend-cell level-3" aria-hidden="true"></span>
|
|
75
|
+
<span class="heatmap-legend-cell level-4" aria-hidden="true"></span>
|
|
76
|
+
<span>多</span>
|
|
77
|
+
</div>`}function Kn(e){return e.kind===`task`?Or(e.item):e.kind===`inspiration`?String(e.item.topic||``).trim()||`未命名主题`:String(e.item.title||``).trim()||String(e.item.body||``).split(/\r?\n/).map(e=>e.trim()).find(Boolean)||`未命名记录`}function qn(e){if(e.kind===`task`){let t=String(e.item.title||``).trim(),n=String(e.item.notes||``).trim();return n?t?n:n.split(/\r?\n/).slice(1).join(` `):``}if(e.kind===`inspiration`)return String(e.item.body||``).trim();let t=String(e.item.title||``).trim(),n=String(e.item.body||``).trim();return t?n:n.split(/\r?\n/).slice(1).join(` `)}function Jn(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Yn(e){let t=D(e);if(!t)return``;let n={month:`long`,day:`numeric`,weekday:`long`};return t.getFullYear()!==new Date().getFullYear()&&(n.year=`numeric`),new Intl.DateTimeFormat(`zh-CN`,n).format(t)}function Xn(e){let t=Kn(e),n=qn(e),r=Nn(e),i=e.kind===`task`,a=e.kind===`inspiration`,o=[i?Dr(e.item.status):``,...r.slice(0,6).map(e=>`<span class="stats-content-tag">#${L(e)}</span>`)].filter(Boolean).join(``);return`
|
|
78
|
+
<li>
|
|
79
|
+
<article class="stats-day-item" data-content-kind="${e.kind}">
|
|
80
|
+
<div class="stats-day-item-head">
|
|
81
|
+
<span class="stats-day-item-type">
|
|
82
|
+
${R(i?`check-circle`:a?`sparkles`:`note`)}
|
|
83
|
+
${i?`待办`:a?`灵感`:`记录`}
|
|
84
|
+
</span>
|
|
85
|
+
<time datetime="${L(e.createdAt)}">${Jn(e.createdAt)}</time>
|
|
86
|
+
</div>
|
|
87
|
+
<h4 class="stats-day-item-title">${L(t)}</h4>
|
|
88
|
+
${n?`<p class="stats-day-item-preview">${L(n)}</p>`:``}
|
|
89
|
+
${o?`<div class="stats-day-item-meta">${o}</div>`:``}
|
|
90
|
+
</article>
|
|
91
|
+
</li>`}function Zn(){let e=document.getElementById(`statsDayContent`);if(!e)return;let t=x.statsSelectedDate&&An().get(x.statsSelectedDate)||[];e.innerHTML=t.length?`
|
|
92
|
+
<section class="stats-day-content-card" aria-labelledby="statsDayContentTitle">
|
|
93
|
+
<header class="stats-day-content-head">
|
|
94
|
+
<div>
|
|
95
|
+
<p>当天内容</p>
|
|
96
|
+
<h3 id="statsDayContentTitle">${Yn(x.statsSelectedDate)}</h3>
|
|
97
|
+
</div>
|
|
98
|
+
<span>${t.length} 项</span>
|
|
99
|
+
</header>
|
|
100
|
+
<ul class="stats-day-list">
|
|
101
|
+
${t.map(Xn).join(``)}
|
|
102
|
+
</ul>
|
|
103
|
+
</section>`:``}function Qn(e){let t=e.dataset.heatmapDate;if(!t)return;let n=An().get(t)||[];document.querySelectorAll(`#statsPage .heatmap-cell.is-selected`).forEach(e=>{e.classList.remove(`is-selected`),e.removeAttribute(`aria-current`)}),n.length?(x.statsSelectedDate=t,e.classList.add(`is-selected`),e.setAttribute(`aria-current`,`date`),Vn(),Zn(),requestAnimationFrame(()=>{document.getElementById(`statsDayContent`)?.scrollIntoView({block:`nearest`,behavior:`smooth`})})):(x.statsSelectedDate=``,Zn(),Hn(e))}function $n(){let e=V(),t=E(e),n=Dn(e),r=t.slice(0,7),i=`${e.getFullYear()}-01-01`,a=kn(),o=An(a),s=[...o.keys()],c=s.filter(e=>e>=E(n)&&e<=t).length,l=s.filter(e=>e.startsWith(r)).length,u=a.filter(e=>{let n=V(e.createdAt);return n&&E(n)>=i&&E(n)<=t}).length,d=Math.max(1,On(D(i),e)+1),f=u?(u/d).toFixed(1):`0.0`,p=In(53,e);S.statsPageTitle.textContent=`记录热力图`,S.statsPageCopy.textContent=`回顾记录、灵感与待办的创建趋势。`,S.statsPageContent.innerHTML=`
|
|
104
|
+
<section class="stats-card stats-overview-card" aria-labelledby="overviewHeatmapTitle">
|
|
105
|
+
<header class="stats-card-head">
|
|
106
|
+
<h3 class="stats-card-title" id="overviewHeatmapTitle">记录热力图</h3>
|
|
107
|
+
<span class="stats-range-label">近 1 年</span>
|
|
108
|
+
</header>
|
|
109
|
+
<div class="stats-overview-chart">
|
|
110
|
+
<div class="heatmap-grid-shell">
|
|
111
|
+
${zn(p,o,x.statsSelectedDate)}
|
|
112
|
+
</div>
|
|
113
|
+
</div>
|
|
114
|
+
<div class="stats-heatmap-footer">
|
|
115
|
+
<span>横向滑动查看</span>
|
|
116
|
+
${Gn()}
|
|
117
|
+
</div>
|
|
118
|
+
<div class="stats-kpi-grid" aria-label="内容统计">
|
|
119
|
+
<div class="stats-kpi">
|
|
120
|
+
<strong>${Un(o)}<small>天</small></strong>
|
|
121
|
+
<span>连续创建</span>
|
|
122
|
+
</div>
|
|
123
|
+
<div class="stats-kpi">
|
|
124
|
+
<strong>${c}<small>天</small></strong>
|
|
125
|
+
<span>本周活跃</span>
|
|
126
|
+
</div>
|
|
127
|
+
<div class="stats-kpi">
|
|
128
|
+
<strong>${l}<small>天</small></strong>
|
|
129
|
+
<span>本月活跃</span>
|
|
130
|
+
</div>
|
|
131
|
+
<div class="stats-kpi">
|
|
132
|
+
<strong>${f}</strong>
|
|
133
|
+
<span>日均创建</span>
|
|
134
|
+
</div>
|
|
135
|
+
</div>
|
|
136
|
+
<button class="stats-all-records-button" type="button" data-stats-action="all-records">
|
|
137
|
+
查看全年热力图
|
|
138
|
+
<svg class="od-icon" aria-hidden="true"><use href="#icon-chevron-right"></use></svg>
|
|
139
|
+
</button>
|
|
140
|
+
</section>
|
|
141
|
+
<div class="stats-day-content" id="statsDayContent" aria-live="polite"></div>
|
|
142
|
+
`,Zn()}function er(e,t,n){let r=new Date(e,t,1,12),i=new Date(e,t+1,0,12),a=Dn(r),o=En(Dn(i),6),s=[];for(let e=a;e<=o;e=En(e,1)){if(e.getMonth()!==t){s.push(`<span class="annual-month-cell is-blank" aria-hidden="true"></span>`);continue}let r=E(e),i=(n.get(r)||[]).length;s.push(`<span class="annual-month-cell level-${jn(i)}" aria-hidden="true"></span>`)}return`<div class="annual-month-heatmap">${s.join(``)}</div>`}function tr(){let e=new Date().getFullYear(),t=kn().map(e=>V(e.createdAt)).filter(Boolean).map(e=>e.getFullYear()),n=t.length?Math.min(...t):e,r=Math.min(n,e),i=e;x.statsYear=Math.min(i,Math.max(r,x.statsYear));let a=Wn(x.statsYear);S.statsPageTitle.textContent=`记录热力图`,S.statsPageCopy.textContent=`按月回顾记录、灵感与待办的创建轨迹。`,S.statsPageContent.innerHTML=`
|
|
143
|
+
<section class="annual-stats-card" aria-label="${x.statsYear} 年记录概览">
|
|
144
|
+
<div class="annual-year-switch">
|
|
145
|
+
<button type="button" data-stats-year-step="-1" aria-label="查看上一年" ${x.statsYear<=r?`disabled`:``}>
|
|
146
|
+
<svg class="od-icon" aria-hidden="true"><use href="#icon-chevron-left"></use></svg>
|
|
147
|
+
</button>
|
|
148
|
+
<strong>${x.statsYear}</strong>
|
|
149
|
+
<button type="button" data-stats-year-step="1" aria-label="查看下一年" ${x.statsYear>=i?`disabled`:``}>
|
|
150
|
+
<svg class="od-icon" aria-hidden="true"><use href="#icon-chevron-right"></use></svg>
|
|
151
|
+
</button>
|
|
152
|
+
</div>
|
|
153
|
+
<div class="annual-kpi-grid">
|
|
154
|
+
<div class="annual-kpi"><strong>${a.entries.length}</strong><span>内容</span></div>
|
|
155
|
+
<div class="annual-kpi"><strong>${a.activeDays}</strong><span>活跃天</span></div>
|
|
156
|
+
<div class="annual-kpi"><strong>${a.characterCount.toLocaleString(`zh-CN`)}</strong><span>总字数</span></div>
|
|
157
|
+
<div class="annual-kpi"><strong>${a.longestStreak}天</strong><span>最长连续</span></div>
|
|
158
|
+
</div>
|
|
159
|
+
</section>
|
|
160
|
+
<div class="annual-month-grid">
|
|
161
|
+
${Array.from({length:12},(e,t)=>`
|
|
162
|
+
<section class="annual-month-card" aria-label="${t+1}月">
|
|
163
|
+
<h3>${t+1}月</h3>
|
|
164
|
+
${er(x.statsYear,t,a.grouped)}
|
|
165
|
+
</section>`).join(``)}
|
|
166
|
+
</div>
|
|
167
|
+
`}function nr({resetScroll:e=!1}={}){x.statsOpen&&(x.statsView===`year`?tr():$n(),x.statsView!==`year`&&requestAnimationFrame(()=>{let e=S.statsPageContent.querySelector(`.stats-overview-chart`);e&&(e.scrollLeft=e.scrollWidth)}),e&&(S.statsPageScroll.scrollTop=0))}function rr(e){x.statsOpen=e,e?(S.statsPage.open||(typeof S.statsPage.showModal==`function`?S.statsPage.showModal():S.statsPage.setAttribute(`open`,``)),Ga(),nr({resetScroll:!0}),S.statsPageScroll.scrollTop=0,requestAnimationFrame(()=>S.statsBackButton.focus())):(S.statsPage.open?S.statsPage.close():S.statsPage.removeAttribute(`open`),Vn(),Y())}function ir(e=`overview`){ur(),cr(!1),x.statsView=e===`year`?`year`:`overview`,x.statsYear=new Date().getFullYear(),x.statsSelectedDate=``,rr(!0),location.hash!==`#statistics`&&(history.pushState({jianjiPage:`statistics`},``,`#statistics`),x.statsHistoryPushed=!0)}function ar(){x.statsOpen&&(rr(!1),location.hash===`#statistics`&&(x.statsHistoryPushed?(x.statsHistoryPushed=!1,history.back()):history.replaceState(history.state,``,`${location.pathname}${location.search}`)))}function or(){x.statsView===`year`?(x.statsView=`overview`,nr({resetScroll:!0}),S.statsBackButton.focus()):ar()}function sr(){Bn(),S.recordDrawer.open||(typeof S.recordDrawer.showModal==`function`?S.recordDrawer.showModal():S.recordDrawer.setAttribute(`open`,``)),requestAnimationFrame(()=>S.recordDrawerCloseButton.focus())}function cr(e=!0){Vn(),S.recordDrawer.open?S.recordDrawer.close():S.recordDrawer.removeAttribute(`open`),e&&requestAnimationFrame(()=>S.mobileMenuButton.focus())}function lr(){S.heatmapHelpDialog.open||(typeof S.heatmapHelpDialog.showModal==`function`?S.heatmapHelpDialog.showModal():S.heatmapHelpDialog.setAttribute(`open`,``),requestAnimationFrame(()=>S.closeHeatmapHelpButton.focus()))}function ur(){S.heatmapHelpDialog.open?S.heatmapHelpDialog.close():S.heatmapHelpDialog.removeAttribute(`open`)}function dr(e){let t=D(e);return t?e===E()?`今天`:e===ot(1)?`明天`:e===ot(-1)?`昨天`:new Intl.DateTimeFormat(`zh-CN`,{month:`numeric`,day:`numeric`}).format(t):``}function fr(e){return!!(e.dueDate&&e.status!==`done`&&e.dueDate<E())}function pr(){return{records:hn(!1).length,inspirations:_n(!1).length,inbox:B(`inbox`,!1,!1).length,all:B(`all`,!1,!1).length,doing:B(`doing`,!1,!1).length,held:B(`held`,!1,!1).length,done:B(`done`,!1,!1).length}}function mr(){let e=pr();document.querySelectorAll(`[data-count]`).forEach(t=>{t.textContent=String(e[t.dataset.count]||0)})}function hr(){if(S.statusFilter.hidden=!yn()||window.innerWidth<=760,S.statusFilter.hidden)return;let e=pr();S.statusFilter.innerHTML=Oe.map(t=>`
|
|
168
|
+
<button
|
|
169
|
+
class="status-filter-item"
|
|
170
|
+
type="button"
|
|
171
|
+
data-filter-view="${t.view}"
|
|
172
|
+
data-tone="${t.tone}"
|
|
173
|
+
aria-pressed="${x.view===t.view}"
|
|
174
|
+
>
|
|
175
|
+
<span class="status-filter-dot" aria-hidden="true"></span>
|
|
176
|
+
<span>${t.label}</span>
|
|
177
|
+
<span class="status-filter-count">${e[t.view]}</span>
|
|
178
|
+
</button>
|
|
179
|
+
`).join(``)}function gr(){yn()?x.tagFilter&&(B(x.view,!1,!1).some(e=>e.tags.includes(x.tagFilter))||(x.tagFilter=``)):x.tagFilter=``}function _r(){if(!yn()){S.tagFilterWrap.hidden=!0,S.tagFilter.innerHTML=``;return}let e=B(x.view,!1,!1),t=new Map;e.forEach(e=>{e.tags.forEach(e=>t.set(e,(t.get(e)||0)+1))});let n=[...t.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0],`zh-CN`));S.tagFilterWrap.hidden=n.length===0,n.length?S.tagFilter.innerHTML=`
|
|
180
|
+
<button class="tag-filter-item" type="button" data-tag-filter="" aria-pressed="${!x.tagFilter}">
|
|
181
|
+
<span>全部</span>
|
|
182
|
+
</button>
|
|
183
|
+
${n.map(([e])=>`
|
|
184
|
+
<button class="tag-filter-item" type="button" data-tag-filter="${L(e)}" aria-pressed="${x.tagFilter===e}">
|
|
185
|
+
<span>#${L(e)}</span>
|
|
186
|
+
</button>`).join(``)}
|
|
187
|
+
`:S.tagFilter.innerHTML=``}function vr(e){let t=e&&e!==x.tagFilter?e:``;t!==x.tagFilter&&(x.tagFilter=t,x.openMenuId=null,H(),S.taskScroll.scrollTop=0)}function yr(){if(!S.commonTagSettingsList)return;x.commonTags.length?S.commonTagSettingsList.innerHTML=`
|
|
188
|
+
<ul class="settings-tag-cloud">
|
|
189
|
+
${x.commonTags.map(e=>`
|
|
190
|
+
<li class="settings-tag-chip">
|
|
191
|
+
<span class="settings-tag-name">#${L(e)}</span>
|
|
192
|
+
<button class="settings-tag-remove" type="button" data-remove-common-tag="${L(e)}" aria-label="从常用标签中移除 ${L(e)}">
|
|
193
|
+
${R(`close`)}
|
|
194
|
+
</button>
|
|
195
|
+
</li>`).join(``)}
|
|
196
|
+
</ul>`:S.commonTagSettingsList.innerHTML=`
|
|
197
|
+
<div class="settings-tag-empty">
|
|
198
|
+
${R(`tag`)}
|
|
199
|
+
<span>还没有常用标签</span>
|
|
200
|
+
</div>`;let e=x.commonTags.length>=50;S.commonTagInput.disabled=e,S.addCommonTagButton.disabled=e,S.commonTagInput.placeholder=e?`最多保存 50 个常用标签`:`输入标签名称`}function br(e,t){let n=T(),r=j(x.commonTagRecords),i=new Map(r.map(e=>[k(e.value),e]));!i.size&&e.length&&ut(e,x.commonTagsUpdatedAt,x.commonTagsDeviceId).forEach(e=>i.set(k(e.value),e));let a=new Set(t.map(k));return e.forEach(e=>{let t=k(e);if(a.has(t))return;let r=i.get(t);i.set(t,{value:r?.value||e,updatedAt:n,deletedAt:n,deviceId:h})}),t.forEach(e=>{let t=k(e),r=i.get(t);r?(r.deletedAt||r.value!==e)&&i.set(t,{value:e,updatedAt:n,deletedAt:``,deviceId:h}):i.set(t,{value:e,updatedAt:n,deletedAt:``,deviceId:h})}),j([...i.values()])}function xr(e,t={}){let n=A(x.commonTags,50),r=A(e,50);return JSON.stringify(r)!==JSON.stringify(x.commonTags)&&(x.commonTagRecords=br(n,r),x.commonTags=r,x.commonTagsUpdatedAt=T(),x.commonTagsDeviceId=h,$r(!0),yr(),S.createDialog.open&&Ri(),S.inspector.open&&fn()&&Jr(),Yo(),t.message&&Z(t.message,t.undo||null),!0)}function Sr(e,t={}){let n=[];return e.forEach(e=>{let t=O(e);t&&!xn(t)&&!n.some(e=>k(e)===k(t))&&n.push(t)}),n.length?x.commonTags.length+n.length>50?(Z(`最多保存 50 个常用标签`,null),!1):xr([...x.commonTags,...n],t):!1}function Cr(e){let t=k(e),n=x.commonTags.find(e=>k(e)===t);if(!n)return;let r=[...x.commonTags];xr(x.commonTags.filter(e=>k(e)!==t),{message:`已从常用标签移除 #${n}`,undo:()=>{xr(r),Yo()}})}function wr(){let e=O(S.commonTagInput.value);e?xn(e)?(Z(`#${e} 已在常用标签中`,null),S.commonTagInput.select()):(Sr([e])&&(S.commonTagInput.value=``,Z(`已添加常用标签 #${e}`,null)),S.commonTagInput.focus()):S.commonTagInput.focus()}function Tr(){mr();let e=window.innerWidth>760&&yn();document.querySelectorAll(`[data-view]`).forEach(t=>{let n=t.closest(`.desktop-primary-nav`)&&t.dataset.view===`all`&&e;t.dataset.view===x.view||n?t.setAttribute(`aria-current`,`page`):t.removeAttribute(`aria-current`)}),document.querySelectorAll(`[data-dock-view]`).forEach(e=>{let t=e.dataset.dockView;(t===`all`?yn():x.view===t)?e.setAttribute(`aria-current`,`page`):e.removeAttribute(`aria-current`)})}function Er(){let e=y[x.view],t=x.view===`records`,n=x.view===`inspirations`,r=window.innerWidth>760&&yn(),i=Oe.find(e=>e.view===x.view);S.viewTitle.textContent=r?`待办`:e.title;let a=t?hn().length:n?_n().length:B().length;S.viewSummary.textContent=x.search?`搜索“${x.search}” · ${a} 项结果`:x.tagFilter?`仅显示标签 #${x.tagFilter} 的待办。`:r&&x.view!==`all`&&i?`仅显示“${i.label}”状态的待办。`:e.copy;let o=n?vn().length:0;S.listCount.textContent=n?`${o} 个主题 · ${a} 条灵感`:`${a} ${t?`条`:`项`}`;let s=t?`搜索记录`:n?`搜索灵感`:`搜索待办`;S.searchLabel.textContent=s,S.searchInput.placeholder=s,S.mobileSearchLabel.textContent=s,S.mobileSearchInput.placeholder=n?`输入主题或灵感内容`:`输入标题或正文`,S.mobileSearchPanel.setAttribute(`aria-label`,s);let c=S.sortSelect.closest(`.sort-control`);c&&(c.hidden=t||n),S.layoutToggle.hidden=t||n,S.desktopCreateButton.innerHTML=t?`${R(`note`)}<span>新建记录</span>`:n?`${R(`sparkles`)}<span>记录灵感</span>`:`${R(`plus`)}<span>新建待办</span>`,Tr(),hr(),_r()}function Dr(e){return`<span class="status-chip" data-status="${e}"><span class="status-dot"></span>${v[e].label}</span>`}function Or(e){return String(e.title||``).trim()||String(e.notes||``).trim().split(/\r?\n/).find(Boolean)||`未填写正文`}function kr(e,n=`list`){let r=e.dueDate?dr(e.dueDate):``,i=e.dueDate===E()?` is-today`:fr(e)?` is-overdue`:``,a=e.tags.map(e=>`<span class="tag-chip">${L(e)}</span>`).join(``),o=e.dispatch?.sessionId?`<span class="dispatch-chip">${R(`play`)}DSH</span>`:``,s=e.status===`done`,c=s?jr(e.completedAt):``,l=!x.search,u=window.innerWidth<=760,d=e.id===x.openMenuId,f=n===`board`?` popover="manual"`:``,p=n===`card`||n===`board`,ee=!!String(e.title||``).trim(),te=!!String(e.notes||``).trim();return`
|
|
201
|
+
<li>
|
|
202
|
+
<article class="task-row${p?` task-card`:``}${e.id===x.selectedId?` is-selected`:``}" data-id="${e.id}" data-status="${e.status}" data-emphasis="${e.emphasis}">
|
|
203
|
+
${u?`<button class="drag-handle" type="button" data-drag-handle aria-label="按住拖动排序" ${l?``:`disabled`}>${R(`drag`)}</button>`:``}
|
|
204
|
+
<button class="task-main" type="button" data-action="select-task" aria-label="查看 ${L(Or(e))} 的详情">
|
|
205
|
+
${ee?`<span class="task-title"><span class="task-emphasis-text">${L(e.title)}</span></span>`:``}
|
|
206
|
+
${te?`<span class="task-body-preview${ee?``:` is-main`}"><span class="task-emphasis-text">${L(e.notes)}</span></span>`:ee?``:`<span class="task-title"><span class="task-emphasis-text">未填写正文</span></span>`}
|
|
207
|
+
<span class="task-meta">
|
|
208
|
+
${e.pinned?`<span class="pin-chip">${R(`pin`)}置顶</span>`:``}
|
|
209
|
+
${s&&c?`<time class="completed-chip" datetime="${L(e.completedAt)}">${R(`check`)}完成于 ${c}</time>`:Dr(e.status)}
|
|
210
|
+
${o}
|
|
211
|
+
${r?`<span class="due-chip${i}">${R(`calendar`)}${r}</span>`:``}
|
|
212
|
+
${a}
|
|
213
|
+
</span>
|
|
214
|
+
</button>
|
|
215
|
+
<div class="row-menu-wrap">
|
|
216
|
+
<button class="row-menu-button" type="button" data-action="toggle-row-menu" aria-label="更多操作" aria-expanded="${d}">
|
|
217
|
+
${R(`more`)}
|
|
218
|
+
</button>
|
|
219
|
+
<div class="row-menu" data-row-menu${f} ${d?``:`hidden`}>
|
|
220
|
+
<button class="menu-item" type="button" data-menu-action="toggle-pin">${R(`pin`)}${e.pinned?`取消置顶`:`置顶`}</button>
|
|
221
|
+
${t?`<button class="menu-item" type="button" data-menu-action="dispatch">${R(`play`)}${e.dispatch?.sessionId?`重新派发 DSH`:`派发给 DSH`}</button>`:``}
|
|
222
|
+
<p class="menu-caption">更改状态</p>
|
|
223
|
+
${Ar(e,`todo`,`plus`)}
|
|
224
|
+
${Ar(e,`doing`,`play`)}
|
|
225
|
+
${Ar(e,`held`,`pause`)}
|
|
226
|
+
${Ar(e,`done`,`check-circle`)}
|
|
227
|
+
<div class="menu-separator"></div>
|
|
228
|
+
<button class="menu-item is-danger" type="button" data-menu-action="delete">${R(`trash`)}删除</button>
|
|
229
|
+
</div>
|
|
230
|
+
</div>
|
|
231
|
+
</article>
|
|
232
|
+
</li>`}function Ar(e,t,n){let r=e.status===t;return`<button class="menu-item" type="button" data-tone="${t}" data-menu-action="status" data-status="${t}">${R(n)}${v[t].label}${r?` · 当前`:``}</button>`}function jr(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return``;let n=new Date;return`${t.getFullYear()===n.getFullYear()?``:`${t.getFullYear()}年`}${t.getMonth()+1}月${t.getDate()}日 ${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Mr(e){let t=e.title.trim(),n=e.body.trim(),r=n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean),i=r[0]||`未命名记录`,a=t?n:r.slice(1).join(` `),o=t||i,s=jr(e.updatedAt);return`
|
|
233
|
+
<li>
|
|
234
|
+
<article class="record-card" data-record-id="${e.id}">
|
|
235
|
+
<button class="record-main" type="button" data-action="open-record" data-record-id="${e.id}" aria-label="打开记录:${L(o)}">
|
|
236
|
+
<span class="record-title">${L(o)}</span>
|
|
237
|
+
${a?`<span class="record-preview">${L(a)}</span>`:``}
|
|
238
|
+
<span class="record-footer">
|
|
239
|
+
<span class="record-meta">
|
|
240
|
+
${s?`<time datetime="${L(e.updatedAt)}">${s}</time><span class="record-meta-separator" aria-hidden="true">·</span>`:``}
|
|
241
|
+
<span>${e.body.trim().length} 字</span>
|
|
242
|
+
</span>
|
|
243
|
+
<span class="record-open-hint">继续写 ${R(`chevron-right`)}</span>
|
|
244
|
+
</span>
|
|
245
|
+
</button>
|
|
246
|
+
</article>
|
|
247
|
+
</li>`}function Nr(){let e=hn(),t=!!x.search;S.taskGroups.classList.remove(`is-board`),S.taskGroups.classList.remove(`is-inspirations`),S.taskGroups.classList.add(`is-records`),S.taskScroll.classList.remove(`is-board-view`),e.length?(S.taskGroups.innerHTML=`<ul class="record-list">${e.map(Mr).join(``)}</ul>`,Er()):(S.taskGroups.innerHTML=`
|
|
248
|
+
<div class="empty-state record-empty">
|
|
249
|
+
<span class="empty-mark">${R(t?`search`:`note`)}</span>
|
|
250
|
+
<h3 class="empty-title">${t?`没有找到匹配的记录`:`还没有留下记录`}</h3>
|
|
251
|
+
<p class="empty-copy">${t?`换个关键词,或在右上角清除搜索。`:`完整笔记、文章片段和随笔都可以放在这里,不必急着整理成待办。`}</p>
|
|
252
|
+
${t?``:`<button class="secondary-button record-empty-action" type="button" data-action="create-record">${R(`plus`)}新建记录</button>`}
|
|
253
|
+
</div>`,Er())}function Pr(e,t){return`
|
|
254
|
+
<li>
|
|
255
|
+
<button
|
|
256
|
+
class="inspiration-idea"
|
|
257
|
+
type="button"
|
|
258
|
+
data-action="open-inspiration"
|
|
259
|
+
data-inspiration-id="${L(e.id)}"
|
|
260
|
+
aria-label="编辑灵感:${L(e.body.slice(0,80))}"
|
|
261
|
+
>
|
|
262
|
+
<span class="inspiration-idea-index" aria-hidden="true">${String(t+1).padStart(2,`0`)}</span>
|
|
263
|
+
<span class="inspiration-idea-copy">
|
|
264
|
+
<span class="inspiration-idea-text">${L(e.body)}</span>
|
|
265
|
+
</span>
|
|
266
|
+
<svg class="od-icon inspiration-idea-chevron" aria-hidden="true"><use href="#icon-chevron-right"></use></svg>
|
|
267
|
+
</button>
|
|
268
|
+
</li>`}function Fr(e){return`
|
|
269
|
+
<section class="inspiration-topic" data-topic-key="${L(e.key)}">
|
|
270
|
+
<header class="inspiration-topic-head">
|
|
271
|
+
<span class="inspiration-topic-mark" aria-hidden="true">${R(`sparkles`)}</span>
|
|
272
|
+
<div class="inspiration-topic-heading">
|
|
273
|
+
<h3 class="inspiration-topic-title">${L(e.topic)}</h3>
|
|
274
|
+
<span class="inspiration-topic-meta">${e.items.length} 条灵感</span>
|
|
275
|
+
</div>
|
|
276
|
+
<button
|
|
277
|
+
class="inspiration-topic-add"
|
|
278
|
+
type="button"
|
|
279
|
+
data-action="add-inspiration"
|
|
280
|
+
data-topic="${L(e.topic)}"
|
|
281
|
+
aria-label="在 ${L(e.topic)} 主题下添加灵感"
|
|
282
|
+
>
|
|
283
|
+
${R(`plus`)}
|
|
284
|
+
<span>添加</span>
|
|
285
|
+
</button>
|
|
286
|
+
</header>
|
|
287
|
+
<ul class="inspiration-idea-list">
|
|
288
|
+
${e.items.map(Pr).join(``)}
|
|
289
|
+
</ul>
|
|
290
|
+
</section>`}function Ir(){let e=vn(),t=!!x.search,n=e.reduce((e,t)=>e+t.items.length,0);S.taskGroups.classList.remove(`is-board`,`is-records`),S.taskGroups.classList.add(`is-inspirations`),S.taskScroll.classList.remove(`is-board-view`),e.length?(S.taskGroups.innerHTML=`
|
|
291
|
+
${t?``:`
|
|
292
|
+
<section class="inspiration-overview" aria-label="灵感概览">
|
|
293
|
+
<span class="inspiration-overview-mark" aria-hidden="true">${R(`sparkles`)}</span>
|
|
294
|
+
<span class="inspiration-overview-copy">
|
|
295
|
+
<span class="inspiration-overview-kicker">灵感地图</span>
|
|
296
|
+
<strong>先给念头一个主题,再让它慢慢长大。</strong>
|
|
297
|
+
</span>
|
|
298
|
+
<span class="inspiration-overview-stats">
|
|
299
|
+
<span><strong>${e.length}</strong> 个主题</span>
|
|
300
|
+
<span><strong>${n}</strong> 条灵感</span>
|
|
301
|
+
</span>
|
|
302
|
+
</section>`}
|
|
303
|
+
<div class="inspiration-topic-grid">
|
|
304
|
+
${e.map(Fr).join(``)}
|
|
305
|
+
</div>`,Er()):(S.taskGroups.innerHTML=`
|
|
306
|
+
<div class="empty-state inspiration-empty">
|
|
307
|
+
<span class="empty-mark">${R(t?`search`:`sparkles`)}</span>
|
|
308
|
+
<h3 class="empty-title">${t?`没有找到匹配的灵感`:`灵感还没有落点`}</h3>
|
|
309
|
+
<p class="empty-copy">${t?`换个关键词,主题和灵感内容都会一起搜索。`:`先建立一个主题,再把零散念头一条条放进去。同一方向的想法会自然聚在一起。`}</p>
|
|
310
|
+
${t?``:`<button class="secondary-button inspiration-empty-action" type="button" data-action="create-inspiration">${R(`sparkles`)}记录第一条灵感</button>`}
|
|
311
|
+
</div>`,Er())}function Lr(){window.innerWidth>760||x.mobileLayout!==`cards`||document.querySelectorAll(`.task-card-grid`).forEach(e=>{if(e.hidden||!e.getClientRects().length)return;let t=[...e.children];if(!t.length)return;e.classList.remove(`is-masonry-ready`),e.style.removeProperty(`height`),t.forEach(e=>{e.style.removeProperty(`left`),e.style.removeProperty(`top`)});let n=t.map(e=>e.getBoundingClientRect().height),r=Number.parseFloat(getComputedStyle(e).getPropertyValue(`--masonry-gap`))||8;e.classList.add(`is-masonry-ready`);let i=e.clientWidth,a=[0,0],o=Math.max(0,(i-r)/2);t.forEach((e,t)=>{let i=a[0]<=a[1]?0:1;e.style.left=`${i===0?0:o+r}px`,e.style.top=`${a[i]}px`,a[i]+=n[t]+r}),e.style.height=`${Math.max(0,Math.max(...a)-r)}px`})}function H(){if(gr(),x.view===`records`){Nr();return}if(x.view===`inspirations`){Ir();return}S.taskGroups.classList.remove(`is-records`),S.taskGroups.classList.remove(`is-inspirations`);let e=B(),t=window.innerWidth>760,n=!!x.search,r=!!x.tagFilter;if(S.taskGroups.classList.toggle(`is-board`,t),S.taskScroll.classList.toggle(`is-board-view`,t),S.layoutToggle.setAttribute(`aria-pressed`,String(x.mobileLayout===`cards`)),S.layoutToggle.setAttribute(`aria-label`,x.mobileLayout===`cards`?`切换为列表`:`切换为双列卡片`),S.layoutToggle.innerHTML=`${R(x.mobileLayout===`cards`?`layout-list`:`layout-grid`)}<span>${x.mobileLayout===`cards`?`列表`:`双列`}</span>`,!e.length)S.taskGroups.innerHTML=`
|
|
312
|
+
<div class="empty-state">
|
|
313
|
+
<span class="empty-mark">${R(n?`search`:r?`list`:`check`)}</span>
|
|
314
|
+
<h3 class="empty-title">${n?`没有找到匹配的待办`:r?`没有标签 #${L(x.tagFilter)} 的待办`:`这里已经清空`}</h3>
|
|
315
|
+
<p class="empty-copy">${n?`换个关键词,或在右上角清除搜索。`:r?`可以切换其他标签,或选择“全部”。`:Rr()}</p>
|
|
316
|
+
</div>`,Er();else{if(t)S.taskGroups.innerHTML=`
|
|
317
|
+
<div class="board-grid">
|
|
318
|
+
${be.map(t=>{let n=Sn(e.filter(e=>e.status===t)),r=x.mosaicLanes.has(t);return`
|
|
319
|
+
<section class="board-lane${x.mosaicLanes.has(t)?` is-mosaic`:``}" data-tone="${t}" data-lane-status="${t}" aria-label="${v[t].label}泳道">
|
|
320
|
+
<header class="board-lane-head">
|
|
321
|
+
<span class="board-lane-title">${R(v[t].icon)}${v[t].label}</span>
|
|
322
|
+
<span class="board-lane-head-actions">
|
|
323
|
+
<span class="board-lane-count">${n.length}</span>
|
|
324
|
+
<button class="lane-mosaic-toggle" type="button" data-action="toggle-lane-mosaic" data-status="${t}" aria-pressed="${r}" aria-label="${r?`还原`:`为`}${v[t].label}泳道内容${r?``:`打马赛克`}">${R(`mosaic`)}</button>
|
|
325
|
+
</span>
|
|
326
|
+
</header>
|
|
327
|
+
<div class="board-lane-body" data-lane-drop="${t}">
|
|
328
|
+
${n.length?`<ul class="task-list board-list">${n.map(e=>kr(e,`board`)).join(``)}</ul>`:`<div class="lane-empty">${R(`drag`)}拖到这里</div>`}
|
|
329
|
+
</div>
|
|
330
|
+
</section>`}).join(``)}
|
|
331
|
+
</div>`;else{let e=wn(),t=x.mobileLayout===`cards`?`task-list task-card-grid`:`task-list`;S.taskGroups.innerHTML=e.map(e=>{let n=x.view===`all`&&e.status===`done`,r=n&&!x.mobileDoneExpanded,i=e.status?n?`<button class="group-heading group-heading-toggle" type="button" data-action="toggle-done-group" data-tone="done" aria-expanded="${!r}" aria-controls="doneTaskList">
|
|
332
|
+
${R(v.done.icon)}
|
|
333
|
+
<span>${v.done.label}</span>
|
|
334
|
+
<span class="group-count">${e.items.length}</span>
|
|
335
|
+
<span class="group-toggle-icon" aria-hidden="true">${R(r?`chevron-right`:`down`)}</span>
|
|
336
|
+
</button>`:`<h3 class="group-heading" data-tone="${e.status}">${R(v[e.status].icon)}${v[e.status].label}<span class="group-count">${e.items.length}</span></h3>`:``;return`
|
|
337
|
+
<section class="task-group" aria-label="${e.status?v[e.status].label:y[x.view].title}">
|
|
338
|
+
${i}
|
|
339
|
+
<ul class="${t}"${n?` id="doneTaskList"`:``}${r?` hidden`:``}>${e.items.map(e=>kr(e,x.mobileLayout===`cards`?`card`:`list`)).join(``)}</ul>
|
|
340
|
+
</section>`}).join(``)}Lr(),Er()}}function Rr(){return x.view===`inbox`?`新建状态是空的。把脑海里的事情写进上方的输入框。`:x.view===`doing`?`没有正在推进的事项。从新建中选择一件开始。`:x.view===`held`?`没有搁置事项。`:x.view===`done`?`还没有完成记录。`:`还什么都没有。写下第一件要做的事。`}function zr(e,t){let n=A(e,8),r=t===`detail`?`detailTagEntry`:`createTagEntry`;return`
|
|
341
|
+
<div class="tag-editor" data-tag-editor="${t}">
|
|
342
|
+
<div class="tag-editor-row">
|
|
343
|
+
<div class="tag-editor-list">
|
|
344
|
+
${n.length?n.map(e=>`
|
|
345
|
+
<span class="tag-editor-chip${xn(e)?``:` is-temporary`}">
|
|
346
|
+
<span>#${L(e)}</span>
|
|
347
|
+
<button
|
|
348
|
+
type="button"
|
|
349
|
+
data-remove-editor-tag="${L(e)}"
|
|
350
|
+
data-tag-context="${t}"
|
|
351
|
+
aria-label="移除标签 ${L(e)}"
|
|
352
|
+
>${R(`close`)}</button>
|
|
353
|
+
</span>`).join(``):`<span class="tag-editor-placeholder">从下方点选,或临时添加</span>`}
|
|
354
|
+
</div>
|
|
355
|
+
<button
|
|
356
|
+
class="tag-temp-trigger"
|
|
357
|
+
type="button"
|
|
358
|
+
data-tag-action="show-entry"
|
|
359
|
+
data-tag-context="${t}"
|
|
360
|
+
${n.length>=8?`disabled`:``}
|
|
361
|
+
>
|
|
362
|
+
${R(`plus`)}标签
|
|
363
|
+
</button>
|
|
364
|
+
</div>
|
|
365
|
+
<div class="tag-entry-row" data-tag-entry-row hidden>
|
|
366
|
+
<input
|
|
367
|
+
id="${r}"
|
|
368
|
+
class="tag-entry"
|
|
369
|
+
type="text"
|
|
370
|
+
placeholder="输入临时标签后按 Enter"
|
|
371
|
+
aria-label="临时标签"
|
|
372
|
+
maxlength="20"
|
|
373
|
+
autocomplete="off"
|
|
374
|
+
>
|
|
375
|
+
<button class="tag-entry-add" type="button" data-tag-action="add-entry" data-tag-context="${t}">添加</button>
|
|
376
|
+
</div>
|
|
377
|
+
<div class="tag-editor-block tag-common-block">
|
|
378
|
+
<span class="tag-editor-label">常用</span>
|
|
379
|
+
<div class="tag-option-list" role="group" aria-label="常用标签">
|
|
380
|
+
${x.commonTags.length?x.commonTags.map(e=>`
|
|
381
|
+
<button
|
|
382
|
+
class="tag-option-button"
|
|
383
|
+
type="button"
|
|
384
|
+
data-toggle-editor-tag="${L(e)}"
|
|
385
|
+
data-tag-context="${t}"
|
|
386
|
+
aria-pressed="${n.some(t=>k(t)===k(e))}"
|
|
387
|
+
>#${L(e)}</button>`).join(``):`<span class="tag-editor-placeholder">可在设置中添加常用标签</span>`}
|
|
388
|
+
</div>
|
|
389
|
+
</div>
|
|
390
|
+
</div>`}function Br(e){return document.getElementById(e===`detail`?`detailTagEditor`:`createTagList`)}function Vr(e){return e===`detail`?x.draft?x.draft.tags:[]:x.createTags}function Hr(e,t=``){let n=Br(e);n&&(n.innerHTML=zr(Vr(e),e),e===`detail`&&Xr(),t&&requestAnimationFrame(()=>{let n=Br(e)?.querySelector(`[data-toggle-editor-tag="${CSS.escape(t)}"]`);n&&n.focus()}))}function Ur(e){let t=Br(e)?.querySelector(`[data-tag-entry-row]`);t&&(t.hidden=!1,t.querySelector(`input`)?.focus())}function Wr(e,t,{requestCommon:n=!0}={}){let r=O(t),i=Vr(e);if(!r)return{added:!1,tag:``,shouldAsk:!1};if(i.some(e=>k(e)===k(r)))return Hr(e),{added:!1,tag:r,shouldAsk:!1};if(i.length>=8)return Z(`最多添加 8 个标签`,null),{added:!1,tag:r,shouldAsk:!1};i.push(r),e===`detail`&&x.draft&&(x.draftDirty=!0),Hr(e);let a=n&&!xn(r);return a&&requestAnimationFrame(()=>qr([r])),{added:!0,tag:r,shouldAsk:a}}function Gr(e,t){let n=Vr(e),r=k(t),i=n.some(e=>k(e)===r);if(!i&&n.length>=8)Z(`最多添加 8 个标签`,null);else{if(i){let t=n.filter(e=>k(e)!==r);e===`detail`&&x.draft?x.draft.tags=t:x.createTags=t}else n.push(O(t)),e===`detail`&&x.draft?x.draft.tags=n:x.createTags=n;e===`detail`&&(x.draftDirty=!0),Hr(e,t)}}function Kr(e,t){let n=k(t),r=Vr(e).filter(e=>k(e)!==n);e===`detail`&&x.draft?(x.draft.tags=r,x.draftDirty=!0):x.createTags=r,Hr(e)}function qr(e){let t=A(e,50).filter(e=>!xn(e));if(!t.length||S.confirmDialog.open)return;let n=t.slice(0,3).map(e=>`#${e}`).join(`、`);Zo(`保存为常用标签?`,`${t.length>3?`${n} 等 ${t.length} 个标签`:n} 已作为临时标签选中。是否同时保存为常用标签,之后直接选择?`,()=>{Sr(t,{message:`已保存常用标签:${n}`})},{acceptLabel:`保存为常用`,cancelLabel:`仅本次使用`,acceptTone:`primary`})}function Jr(){let e=fn();if(!e){G(`detail`),x.draft=null,x.draftTaskId=null,x.draftDirty=!1,S.inspectorContent.innerHTML=`
|
|
391
|
+
<div class="inspector-empty">
|
|
392
|
+
${R(`note`)}
|
|
393
|
+
<p>选择一条待办,可以补充备注、日期和标签,也可以调整状态。</p>
|
|
394
|
+
</div>`,window.innerWidth<=1180&&Li();return}x.draftTaskId===e.id&&x.draft||(G(`detail`),x.draft={title:e.title,notes:e.notes,status:e.status,emphasis:e.emphasis,dueDate:e.dueDate,tags:[...e.tags]},x.draftTaskId=e.id,x.draftDirty=!1);let n=x.draft,r=Yr(),i=new Date(e.createdAt),a=Number.isNaN(i.getTime())?``:new Intl.DateTimeFormat(`zh-CN`,{year:`numeric`,month:`numeric`,day:`numeric`}).format(i),o=e.status===`done`?jr(e.completedAt):``;S.inspectorContent.innerHTML=`
|
|
395
|
+
<form class="settings-form create-form detail-form" id="detailForm" novalidate>
|
|
396
|
+
<div class="image-import-row">
|
|
397
|
+
<button class="image-import-button" type="button" data-image-scan="detail">
|
|
398
|
+
<svg class="od-icon" aria-hidden="true"><use href="#icon-scan"></use></svg>
|
|
399
|
+
<span>图片转文字</span>
|
|
400
|
+
</button>
|
|
401
|
+
<span class="image-import-status" data-image-status="detail" aria-live="polite">上传截图,自动识别并填入待办</span>
|
|
402
|
+
<input class="image-import-input" type="file" accept="image/*" data-image-input="detail" hidden>
|
|
403
|
+
</div>
|
|
404
|
+
<div class="field create-title-field">
|
|
405
|
+
<div class="detail-field-heading">
|
|
406
|
+
<label class="field-label" for="detailTitle">标题(可选)</label>
|
|
407
|
+
${a||o?`<span class="detail-inline-time">
|
|
408
|
+
${a?`创建 ${a}`:``}
|
|
409
|
+
${o?`${a?` · `:``}完成 ${o}`:``}
|
|
410
|
+
</span>`:``}
|
|
411
|
+
</div>
|
|
412
|
+
<textarea class="detail-title-input" id="detailTitle" data-draft-field="title" rows="2" maxlength="180" placeholder="给这件事起个标题,也可以留空">${L(n.title)}</textarea>
|
|
413
|
+
</div>
|
|
414
|
+
<div class="field">
|
|
415
|
+
<label class="field-label" for="detailNotes">正文(必填)</label>
|
|
416
|
+
<textarea class="create-body-input" id="detailNotes" data-draft-field="notes" maxlength="4000" placeholder="写下要完成的事情、验收标准、相关链接、联系人或需要注意的细节…" required>${L(n.notes)}</textarea>
|
|
417
|
+
</div>
|
|
418
|
+
<div class="field-grid create-meta-grid">
|
|
419
|
+
<div class="field">
|
|
420
|
+
<label class="field-label" for="detailStatusInput">状态</label>
|
|
421
|
+
<button class="picker-trigger field-picker-trigger" id="detailStatusInput" data-draft-field="status" data-picker-type="select" data-picker-title="状态" data-value="${n.status}" type="button" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-controls="appPickerOptions">
|
|
422
|
+
<span class="picker-status-marker" data-status="${n.status}" aria-hidden="true"></span>
|
|
423
|
+
<span class="picker-trigger-value" data-picker-label>${v[n.status].label}</span>
|
|
424
|
+
<svg class="od-icon picker-chevron" aria-hidden="true"><use href="#icon-down"></use></svg>
|
|
425
|
+
</button>
|
|
426
|
+
</div>
|
|
427
|
+
<div class="field">
|
|
428
|
+
<label class="field-label" for="detailDue">截止日期</label>
|
|
429
|
+
<button class="picker-trigger field-picker-trigger date-picker-trigger${n.dueDate?``:` is-placeholder`}" id="detailDue" data-draft-field="dueDate" data-picker-type="date" data-picker-title="截止日期" data-value="${n.dueDate}" type="button" role="combobox" aria-haspopup="dialog" aria-expanded="false" aria-controls="appPickerBody" aria-label="截止日期:${Kt(n.dueDate)}">
|
|
430
|
+
<svg class="od-icon picker-leading-icon" aria-hidden="true"><use href="#icon-calendar"></use></svg>
|
|
431
|
+
<span class="picker-trigger-value" data-picker-label>${Kt(n.dueDate)}</span>
|
|
432
|
+
<svg class="od-icon picker-chevron" aria-hidden="true"><use href="#icon-down"></use></svg>
|
|
433
|
+
</button>
|
|
434
|
+
</div>
|
|
435
|
+
</div>
|
|
436
|
+
<div class="field create-emphasis-field">
|
|
437
|
+
<label class="field-label" for="detailEmphasisInput">文字醒目</label>
|
|
438
|
+
<button class="picker-trigger field-picker-trigger emphasis-picker-trigger" id="detailEmphasisInput" data-draft-field="emphasis" data-picker-type="select" data-picker-title="文字醒目" data-value="${n.emphasis}" type="button" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-controls="appPickerOptions" aria-label="文字醒目:${Se[n.emphasis].label}">
|
|
439
|
+
<span class="picker-emphasis-marker" data-emphasis-preview="${n.emphasis}" aria-hidden="true"><span class="task-emphasis-text">文</span></span>
|
|
440
|
+
<span class="picker-trigger-value" data-picker-label>${Se[n.emphasis].label}</span>
|
|
441
|
+
<svg class="od-icon picker-chevron" aria-hidden="true"><use href="#icon-down"></use></svg>
|
|
442
|
+
</button>
|
|
443
|
+
</div>
|
|
444
|
+
<div class="field create-tag-field">
|
|
445
|
+
<span class="field-label">标签</span>
|
|
446
|
+
<div id="detailTagEditor">${zr(n.tags,`detail`)}</div>
|
|
447
|
+
</div>
|
|
448
|
+
<div class="detail-actions">
|
|
449
|
+
<button class="quiet-button detail-delete" type="button" data-detail-action="delete">${R(`trash`)}删除</button>
|
|
450
|
+
${t?`<div class="detail-dsh-actions">
|
|
451
|
+
${e.dispatch?.sessionId?`<button class="secondary-button detail-dispatch-open" type="button" data-detail-action="open-dsh">${R(`chevron-right`)}在 DSH 中查看</button>`:``}
|
|
452
|
+
<button class="secondary-button detail-dispatch-button" type="button" data-detail-action="dispatch">${R(`play`)}${e.dispatch?.sessionId?`重新派发`:`派发给 DSH`}</button>
|
|
453
|
+
</div>`:``}
|
|
454
|
+
<div class="detail-save-group">
|
|
455
|
+
<span class="detail-save-state" id="detailSaveState">${r?`尚未保存`:`已保存`}</span>
|
|
456
|
+
<button class="primary-button detail-save-button" id="detailSaveButton" type="button" data-detail-action="save" ${r?``:`disabled`}>
|
|
457
|
+
${R(`save`)}保存
|
|
458
|
+
</button>
|
|
459
|
+
</div>
|
|
460
|
+
</div>
|
|
461
|
+
</form>`,Yt(document.getElementById(`detailStatusInput`)),Yt(document.getElementById(`detailDue`)),Yt(document.getElementById(`detailEmphasisInput`))}function Yr(){let e=fn(),t=x.draft;if(!e||!t||x.draftTaskId!==e.id)return!1;let n=document.getElementById(`detailTagEntry`),r=!!(n&&n.value.trim());return t.title!==e.title||t.notes!==e.notes||t.status!==e.status||t.emphasis!==e.emphasis||t.dueDate!==e.dueDate||t.tags.join(`\0`)!==e.tags.join(`\0`)||r}function Xr(){x.draftDirty=Yr();let e=document.getElementById(`detailSaveState`),t=document.getElementById(`detailSaveButton`);e&&(e.textContent=x.draftDirty?`尚未保存`:`已保存`),t&&(t.disabled=!x.draftDirty)}function Zr(e,t){x.draft&&(x.draft[e]=t,Xr())}function Qr(e={}){let t=fn();if(!t||!x.draft)return!1;if(!x.draft.notes.trim()){Z(`请填写正文后再保存`,null);let e=document.getElementById(`detailNotes`);return e&&e.focus(),!1}let n=document.getElementById(`detailTagEntry`),r=n?O(n.value):``,i=!1,a=r&&x.draft.tags.some(e=>k(e)===k(r));if(r&&!a&&x.draft.tags.length<8?(x.draft.tags.push(r),i=!0):r&&!a&&Z(`最多添加 8 个标签`,null),n&&(n.value=``),!Yr())return Xr(),typeof e.after==`function`&&e.after(),!0;let o={title:x.draft.title.trim(),notes:x.draft.notes,status:x.draft.status,emphasis:x.draft.emphasis,dueDate:x.draft.dueDate,tags:[...x.draft.tags]};return x.draft=o,x.draftDirty=!1,W(`修改已保存`,()=>{ti(t,o.status),Object.assign(t,{...o,tags:[...o.tags]}),ei(t)},{undo:!1,render:()=>{H(),bo(),De(x.items).catch(()=>{}),i?Jr():Xr()}}),i&&!xn(r)&&setTimeout(()=>qr([r]),0),typeof e.after==`function`&&e.after(),!0}function $r(e=!0){e&&(x.dirty=!0),w(s,Re()),Qe(),at(x.items)}function U(){H(),Jr(),bo(),yr(),De(x.items).catch(()=>{}),S.recordDrawer.open&&Bn(),x.statsOpen&&nr()}function W(e,t,n={}){let r={items:nt(x.items),records:nt(x.records),inspirations:nt(x.inspirations)};t(),$r(!0),typeof n.render==`function`?n.render():U(),e&&Z(e,n.undo===!1?null:()=>{n.undoScope===`records`?x.records=r.records:n.undoScope===`inspirations`?x.inspirations=r.inspirations:x.items=r.items,$r(!0),U(),Yo()}),Yo()}function ei(e){e.updatedAt=T(),e.deviceId=h}function ti(e,t){let n=e.status===`done`;e.status=t,t===`done`?n&&e.completedAt||(e.completedAt=T()):e.completedAt=``}function ni(e){e.updatedAt=T(),e.deviceId=h}function ri(e){e.updatedAt=T(),e.deviceId=h}function ii({title:e=``,body:t,dueDate:n=``,tags:r=[],status:i=``,emphasis:a=`normal`}){let o=String(e).trim().slice(0,180),s=String(t||``).trim();if(!s)return!1;let c=A(r,8),l=v[i]?i:y[x.view].status||`todo`,u=Math.min(...z().filter(e=>e.status===l).map(e=>e.order),0),d={id:crypto.randomUUID?crypto.randomUUID():`task-${Date.now()}-${Math.random().toString(16).slice(2)}`,title:o,notes:s.slice(0,4e3),status:l,emphasis:vt(a),dueDate:n,tags:c,pinned:!1,order:u-100,createdAt:T(),updatedAt:T(),completedAt:l===`done`?T():``,deletedAt:``,deviceId:h};return W(`已添加待办`,()=>{x.items.push(d)}),!0}function ai({title:e=``,body:t}){let n=String(t||``).trim();if(!n)return null;let r={id:crypto.randomUUID?crypto.randomUUID():`record-${Date.now()}-${Math.random().toString(16).slice(2)}`,title:String(e||``).trim().slice(0,180),body:n.slice(0,2e4),createdAt:T(),updatedAt:T(),deletedAt:``,deviceId:h};return W(`记录已保存`,()=>{x.records.push(r)},{undoScope:`records`}),r}function oi({topic:e=``,body:t}){let n=String(t||``).trim(),r=P(e);if(!r||!n)return null;let i=dn().find(e=>It(e.topic)===It(r))?.topic,a={id:crypto.randomUUID?crypto.randomUUID():`inspiration-${Date.now()}-${Math.random().toString(16).slice(2)}`,topic:i||r,body:n.slice(0,4e3),createdAt:T(),updatedAt:T(),deletedAt:``,deviceId:h};return W(`灵感已收进主题`,()=>{x.inspirations.push(a)},{undoScope:`inspirations`}),a}function si(e){let t=[];return{body:e.replace(/(?:^|\s)#([\p{L}\p{N}_-]+)/gu,(e,n)=>{let r=O(n);return r&&!t.some(e=>k(e)===k(r))&&t.push(r),``}).replace(/\s{2,}/g,` `).trim(),tags:A(t,8)}}function ci(e){return e===`detail`?`task`:e}function li(e){return e===`record`?`上传截图,自动识别并填入记录`:e===`inspiration`?`上传截图,自动识别主题和灵感内容`:e===`detail`?`上传截图,自动识别并填入待办`:`上传截图,自动识别并填入下方内容`}function ui(e){return{button:document.querySelector(`[data-image-scan="${e}"]`),input:document.querySelector(`[data-image-input="${e}"]`),status:document.querySelector(`[data-image-status="${e}"]`)}}function di(e,t,n=``){let{button:r,status:i}=ui(e);if(i&&(i.textContent=t||li(e),i.dataset.state=n),r){r.disabled=n===`busy`,r.classList.toggle(`is-busy`,n===`busy`);let e=r.querySelector(`span`);e&&(e.textContent=n===`busy`?`识别中…`:`图片转文字`)}}function G(e){let t=x.imageRecognition.get(e);t?.controller&&t.controller.abort(),x.imageRecognition.delete(e);let{input:n}=ui(e);n&&(n.value=``),di(e,``,``)}function fi(e,t=`task`){if(t===`detail`){if(!x.draft)return;let t=document.getElementById(`detailTitle`),n=document.getElementById(`detailNotes`);e.title&&(x.draft.title=e.title,t&&(t.value=e.title)),e.body&&(x.draft.notes=e.body,n&&(n.value=e.body)),e.dueDate&&(x.draft.dueDate=e.dueDate,Jt(document.getElementById(`detailDue`),e.dueDate)),e.tags.length&&(x.draft.tags=A([...x.draft.tags,...e.tags],8),Hr(`detail`)),Xr()}else e.title&&(S.createTitleInput.value=e.title),e.body&&(S.createBodyInput.value=e.body),e.dueDate&&Jt(S.createDueInput,e.dueDate),e.tags.length&&(x.createTags=A([...x.createTags,...e.tags],8),Ri())}async function pi(e,t){if(!t)return;let n=ci(e);if(lt(x.deepseekKey)){di(e,`请先在设置中配置 DeepSeek API Key`,`error`),Z(`请先在设置 → 图片转文字中填写 DeepSeek API Key`,null);let{input:t}=ui(e);t&&(t.value=``);return}G(e);let r=new AbortController,i=!1,a=setTimeout(()=>{i=!0,r.abort()},35e3);x.imageRecognition.set(e,{controller:r}),di(e,`正在读取图片…`,`busy`);try{let i=await mt(t);di(e,`正在识别图片文字…`,`busy`);let a=await St(x.deepseekKey,i,n,{signal:r.signal,today:E()});n===`task`&&fi(a,e),n===`record`&&(a.title&&(S.recordTitleInput.value=a.title),a.body&&(S.recordBodyInput.value=a.body)),n===`inspiration`&&(a.topic&&(S.inspirationTopicInput.value=a.topic),a.body&&(S.inspirationBodyInput.value=a.body)),di(e,`识别完成,请检查后保存`,`success`),Z(`图片文字已识别并填入,请检查内容`,null)}catch(t){if(r.signal.aborted&&!i)return;let n=i?`图片识别超时,请检查网络后重试`:t instanceof M||t instanceof Error?t.message:`图片识别失败,请重试`;di(e,n,`error`),Z(n,null)}finally{clearTimeout(a),x.imageRecognition.get(e)?.controller===r&&x.imageRecognition.delete(e);let{input:t}=ui(e);t&&(t.value=``)}}function mi(e,t,n=`已移至${v[t].label}`){let r=z().find(t=>t.id===e);r&&r.status!==t&&(x.selectedId===e&&x.draft&&(x.draft.status=t),W(n,()=>{ti(r,t),ei(r)}))}function hi(e,t){let n=z().find(t=>t.id===e);n&&v[t]&&(n.status===t?Z(`当前已经是“${v[t].label}”`,null):Zo(`将状态改为“${v[t].label}”?`,`“${Or(n)}”会从“${v[n.status].label}”切换为“${v[t].label}”。`,()=>mi(e,t,`状态已切换为${v[t].label}`),{acceptLabel:`确认切换`,acceptTone:`primary`}))}function gi(e){let t=z().find(t=>t.id===e);if(!t)return;let n=t.status===`done`;x.selectedId===e&&x.draft&&(x.draft.status=n?`todo`:`done`),W(n?`已恢复为新建`:`已完成`,()=>{ti(t,n?`todo`:`done`),ei(t)})}function _i(e){let t=z().find(t=>t.id===e);t&&(!x.draftDirty||x.selectedId!==e||Qr())&&(me=e,ge=``,S.dispatchDialogTask.textContent=Or(t),S.dispatchPromptInput.value=``,S.dispatchError.hidden=!0,S.dispatchError.textContent=``,S.dispatchConfirmButton.disabled=!1,S.dispatchConfirmButton.innerHTML=`${R(`play`)}<span>派发并开始</span>`,typeof S.dispatchDialog.showModal==`function`?(S.dispatchDialog.showModal(),requestAnimationFrame(()=>S.dispatchPromptInput.focus())):S.dispatchDialog.setAttribute(`open`,``))}function vi(){me=``,ge=``,S.dispatchDialog.open?S.dispatchDialog.close():S.dispatchDialog.removeAttribute(`open`)}function yi(){let e=z().find(e=>e.id===me);if(!e||!t)return;ge=crypto.randomUUID?crypto.randomUUID():`dispatch-${Date.now()}-${Math.random().toString(16).slice(2)}`;let n=S.dispatchPromptInput.value.trim();S.dispatchError.hidden=!0,S.dispatchConfirmButton.disabled=!0,S.dispatchConfirmButton.textContent=`正在创建 DSH 会话…`,tt({type:`jianji:dispatch`,requestId:ge,task:nt(e),prompt:n})}async function bi(e){if(ge&&e.requestId===ge){if(!e.ok)S.dispatchError.textContent=String(e.message||`派发失败,请重试`),S.dispatchError.hidden=!1,S.dispatchConfirmButton.disabled=!1,S.dispatchConfirmButton.innerHTML=`${R(`play`)}<span>重试派发</span>`;else try{let t=await Fe(`dispatch`,{method:`POST`,body:JSON.stringify({taskId:me,sessionId:e.sessionId,workspaceId:e.workspaceId,prompt:e.prompt})});if(!t.ok)throw Error(await et(t,`保存派发状态失败`));let n=await t.json(),r=x.items.findIndex(e=>e.id===n.task?.id);r>=0&&(x.items[r]=yt(n.task)),w(s,Re()),vi(),U(),Z(`已派发给 DSH`,null),Xe({force:!0})}catch(e){S.dispatchError.textContent=e instanceof Error?e.message:`保存派发状态失败`,S.dispatchError.hidden=!1,S.dispatchConfirmButton.disabled=!1,S.dispatchConfirmButton.innerHTML=`${R(`play`)}<span>重试保存</span>`}}}function xi(e){t&&e.source===window.parent&&e.data&&typeof e.data==`object`&&e.data.type===`jianji:dispatch-result`&&bi(e.data)}function Si(e){e?.dispatch?.sessionId&&tt({type:`jianji:open-session`,sessionId:e.dispatch.sessionId})}function Ci(e){let t=z().find(t=>t.id===e);t&&W(t.pinned?`已取消置顶`:`已置顶`,()=>{t.pinned=!t.pinned,ei(t)})}function wi(e){let t=z().find(t=>t.id===e);t&&(W(`已删除待办`,()=>{t.deletedAt=T(),t.updatedAt=T(),t.deviceId=h,x.selectedId===e&&(x.selectedId=null)}),Li())}function Ti(e,t){let n=z().find(t=>t.id===e);if(!n)return;let r=Sn(z().filter(e=>e.status===n.status)),i=r[r.findIndex(t=>t.id===e)+t];i?W(`顺序已调整`,()=>{let e=n.order;n.order=i.order,i.order=e,ei(n),ei(i)}):Z(t<0?`已经是第一项`:`已经是最后一项`,null)}function Ei(e,t){if(!e||!t||e===t)return;let n=z().find(t=>t.id===e),r=z().find(e=>e.id===t);if(!n||!r)return;let i=n.status,a=Sn(z()),o=a.findIndex(t=>t.id===e),s=a.findIndex(e=>e.id===t);o<0||s<0||(x.selectedId===e&&x.draft&&(x.draft.status=r.status),W(i===r.status?`顺序已调整`:`已移至${v[r.status].label}`,()=>{let[e]=a.splice(o,1);ti(e,r.status);let n=a.findIndex(e=>e.id===t);a.splice(n<0?a.length:n,0,e);let i=new Set;a.forEach((e,t)=>{let n=t*100;e.order!==n&&(e.order=n,i.add(e))}),i.add(e),i.forEach(ei)},{undo:!1}))}function Di(e,t){let n=z().find(t=>t.id===e);if(!n||n.status===t)return;let r=z().filter(e=>e.status===t).map(e=>e.order);x.selectedId===e&&x.draft&&(x.draft.status=t),W(`已移至${v[t].label}`,()=>{ti(n,t),n.order=(r.length?Math.max(...r):0)+100,ei(n)},{undo:!1})}function Oi(e,t=``){y[e]&&(e!==x.view||x.search||x.tagFilter)&&ji(()=>{if(x.view=e,x.search=``,x.tagFilter=``,S.searchInput.value=``,S.mobileSearchInput.value=``,S.mobileSearchPanel.hidden=!0,S.searchBox.classList.remove(`is-open`),N(),U(),S.taskScroll.scrollTop=0,t){let e=t===`next`?`view-enter-next`:`view-enter-prev`;S.taskGroups.classList.add(e),setTimeout(()=>S.taskGroups.classList.remove(e),380)}})}function ki(e){ve.includes(e)&&e!==x.view&&ji(()=>{x.view=e,x.tagFilter=``,N(),U(),S.taskScroll.scrollTop=0})}function Ai(e){x.selectedId===e?Fi():ji(()=>{x.selectedId=e,H(),Jr(),Fi()})}function ji(e){Yr()?S.savePromptDialog.open||(x.draftAfter=e,typeof S.savePromptDialog.showModal==`function`?(S.savePromptDialog.showModal(),requestAnimationFrame(()=>S.continueEditingButton.focus())):S.savePromptDialog.setAttribute(`open`,``)):typeof e==`function`&&e()}function Mi(){S.savePromptDialog.open&&S.savePromptDialog.close()}function Ni(){x.draft=null,x.draftTaskId=null,x.draftDirty=!1,Mi(),Jr();let e=x.draftAfter;x.draftAfter=null,typeof e==`function`&&e()}function Pi(){let e=x.draftAfter;Qr()?(Mi(),x.draftAfter=null,typeof e==`function`&&e()):(x.draftAfter=null,Mi(),requestAnimationFrame(()=>{let e=document.getElementById(`detailTitle`);e&&e.focus()}))}function Fi(){S.inspector.open||(typeof S.inspector.showModal==`function`?S.inspector.showModal():S.inspector.setAttribute(`open`,``))}function Ii(){ji(Li)}function Li(){G(`detail`),S.inspector.open&&S.inspector.close()}function Ri(){S.createTagList.innerHTML=zr(x.createTags,`create`)}function zi(e,t={}){return Wr(`create`,e,t)}function Bi(){S.mobileSearchPanel.hidden||aa(),S.createTitleInput.value=``,S.createBodyInput.value=``,Jt(S.createStatusInput,y[x.view].status||`todo`),Jt(S.createDueInput,``),Jt(S.createEmphasisInput,`normal`),x.createTags=[],Ri(),G(`task`),S.createTaskError.hidden=!0,typeof S.createDialog.showModal==`function`?(S.createDialog.showModal(),requestAnimationFrame(()=>S.createBodyInput.focus())):S.createDialog.setAttribute(`open`,``)}function Vi(){G(`task`),S.createDialog.open&&S.createDialog.close()}function Hi(){let e=S.createBodyInput.value.trim();if(!e){S.createTaskError.textContent=`请填写正文后再创建待办。`,S.createTaskError.hidden=!1,S.createBodyInput.focus();return}let t=si(e);if(!t.body){S.createTaskError.textContent=`正文不能只包含标签。`,S.createTaskError.hidden=!1,S.createBodyInput.focus();return}let n=document.getElementById(`createTagEntry`),r=n&&n.value.trim()?zi(n.value,{requestCommon:!1}):{added:!1,tag:``};x.view===`records`&&(x.view=`all`,x.search=``,x.tagFilter=``,S.searchInput.value=``,S.mobileSearchInput.value=``,N());let i=A([...x.createTags,...t.tags],8),a=A(t.tags,8).filter(e=>!xn(e)&&!x.createTags.some(t=>k(t)===k(e))&&i.some(t=>k(t)===k(e)));if(ii({title:S.createTitleInput.value,body:t.body,dueDate:qt(S.createDueInput),tags:i,status:qt(S.createStatusInput),emphasis:qt(S.createEmphasisInput)})){S.createTaskError.hidden=!0,Vi();let e=A([...r.added?[r.tag]:[],...a],50).filter(e=>!xn(e));e.length&&setTimeout(()=>qr(e),0)}}function Ui(e=``){S.recordError.textContent=e,S.recordError.hidden=!e}function Wi(e=null){ji(()=>{let t=e?ln().find(t=>t.id===e):null;e&&!t?Z(`这条记录已不存在`,null):(x.recordEditingId=t?.id||null,S.recordDialogTitle.textContent=t?`编辑记录`:`新建记录`,S.recordDialogCopy.textContent=t?`修改会保存在本机,并同步到已连接的其他设备。`:`保存一段完整文字、笔记或随笔。`,S.recordTitleInput.value=t?.title||``,S.recordBodyInput.value=t?.body||``,S.recordDeleteButton.hidden=!t,S.recordDialogMeta.textContent=t?`最后修改 ${jr(t.updatedAt)}`:``,S.recordSaveButton.querySelector(`span`).textContent=t?`保存修改`:`保存记录`,Ui(),G(`record`),Vi(),Li(),S.mobileSearchPanel.hidden||aa(),typeof S.recordDialog.showModal==`function`?S.recordDialog.showModal():S.recordDialog.setAttribute(`open`,``),requestAnimationFrame(()=>S.recordBodyInput.focus()))})}function Gi(){G(`record`),S.recordDialog.open&&S.recordDialog.close(),x.recordEditingId=null,Ui()}function Ki(){x.view=`records`,x.search=``,x.tagFilter=``,S.searchInput.value=``,S.mobileSearchInput.value=``,S.mobileSearchPanel.hidden=!0,S.searchBox.classList.remove(`is-open`),N()}function qi(){let e=S.recordTitleInput.value.trim(),t=S.recordBodyInput.value.trim();if(!t){Ui(`先写下一点内容,再保存记录。`),S.recordBodyInput.focus();return}let n=x.recordEditingId?ln().find(e=>e.id===x.recordEditingId):null;if(n){if(n.title===e&&n.body===t){Gi();return}W(`记录已更新`,()=>{n.title=e.slice(0,180),n.body=t.slice(0,2e4),ni(n)},{undoScope:`records`})}else if(Ki(),!ai({title:e,body:t})){Ui(`记录保存失败,请重试。`);return}Gi()}function Ji(e){let t=ln().find(t=>t.id===e);t&&(W(`记录已删除`,()=>{t.deletedAt=T(),ni(t)},{undoScope:`records`}),Gi())}function Yi(){let e=x.recordEditingId?ln().find(e=>e.id===x.recordEditingId):null;e&&Zo(`删除这条记录`,`删除后会同步到已连接的仓库,可在提示消失前撤销。`,()=>Ji(e.id))}function Xi(e=``){S.inspirationError.textContent=e,S.inspirationError.hidden=!e}function Zi({topic:e=``,id:t=``}={}){ji(()=>{let n=t?dn().find(e=>e.id===t):null;if(t&&!n){Z(`这条灵感已不存在`,null);return}x.inspirationEditingId=n?.id||null;let r=n?.topic||P(e);S.inspirationDialogTitle.textContent=n?`编辑灵感`:`记录灵感`,S.inspirationDialogCopy.textContent=n?`可以调整主题,或继续打磨这次的想法。`:r?`继续补充「${r}」主题下的想法。`:`先给它一个主题,再写下这次想到的内容。`,S.inspirationTopicInput.value=r,S.inspirationBodyInput.value=n?.body||``,S.inspirationDeleteButton.hidden=!n,S.inspirationDialogMeta.textContent=n?`最后修改 ${jr(n.updatedAt)}`:``,S.inspirationSaveButton.querySelector(`span`).textContent=n?`保存修改`:`收进主题`,Xi(),G(`inspiration`),Vi(),Gi(),Li(),S.mobileSearchPanel.hidden||aa(),typeof S.inspirationDialog.showModal==`function`?S.inspirationDialog.showModal():S.inspirationDialog.setAttribute(`open`,``),requestAnimationFrame(()=>{r?S.inspirationBodyInput.focus():S.inspirationTopicInput.focus()})})}function Qi(){G(`inspiration`),S.inspirationDialog.open?S.inspirationDialog.close():S.inspirationDialog.removeAttribute(`open`),x.inspirationEditingId=null,Xi()}function $i(){x.view=`inspirations`,x.search=``,x.tagFilter=``,S.searchInput.value=``,S.mobileSearchInput.value=``,S.mobileSearchPanel.hidden=!0,S.searchBox.classList.remove(`is-open`),N()}function ea(){let e=P(S.inspirationTopicInput.value),t=S.inspirationBodyInput.value.trim();if(!e){Xi(`先填写灵感所属的主题。`),S.inspirationTopicInput.focus();return}if(!t){Xi(`再写下一点灵感内容。`),S.inspirationBodyInput.focus();return}let n=x.inspirationEditingId?dn().find(e=>e.id===x.inspirationEditingId):null;if(n){let r=dn().find(t=>t.id!==n.id&&It(t.topic)===It(e))?.topic||e;if(n.topic===r&&n.body===t){Qi();return}W(`灵感已更新`,()=>{n.topic=r,n.body=t.slice(0,4e3),ri(n)},{undoScope:`inspirations`})}else if($i(),!oi({topic:e,body:t})){Xi(`灵感保存失败,请重试。`);return}Qi()}function ta(e){let t=dn().find(t=>t.id===e);t&&(W(`灵感已删除`,()=>{t.deletedAt=T(),ri(t)},{undoScope:`inspirations`}),Qi())}function na(){let e=x.inspirationEditingId?dn().find(e=>e.id===x.inspirationEditingId):null;e&&Zo(`删除这条灵感`,`删除后会同步到已连接的仓库,可在提示消失前撤销。`,()=>ta(e.id))}function ra(){x.view===`records`?Wi():x.view===`inspirations`?Zi():Bi()}function ia(){S.mobileSearchPanel.hidden=!1,S.mobileSearchInput.value=x.search,Y(),requestAnimationFrame(()=>S.mobileSearchInput.focus())}function aa(e=!0){S.mobileSearchPanel.hidden=!0,e&&(x.search=``,S.mobileSearchInput.value=``,S.searchInput.value=``,H()),Y()}async function oa(){fa(),S.repoInput.value=F.repo,S.branchInput.value=F.branch,S.pathInput.value=F.directory,S.tokenInput.value=F.token,S.autoSyncInput.checked=F.autoSync,S.deepseekKeyInput.value=x.deepseekKey,sa(),S.settingsError.hidden=!0,S.settingsError.textContent=``,mo(),yr(),pa();let e=x.settingsOpen;ua(!0),!e&&location.hash!==`#settings`&&(history.pushState({jianjiPage:`settings`},``,`#settings`),x.settingsHistoryPushed=!0)}function sa(e=``,t=``){let n=!!x.deepseekKey;S.deepseekKeyStatus.textContent=e||(n?`Key 已保存在本机,可在待办新建或编辑表单中识别图片。`:`尚未配置,图片转文字暂不可用。`),S.deepseekKeyStatus.dataset.state=t||(n?`ready`:``)}function ca(){let e=ct(S.deepseekKeyInput.value),t=e?lt(e):``;t?(sa(t,`error`),S.deepseekKeyInput.focus()):(Vt(e),sa(e?`DeepSeek API Key 已保存在本机。`:`已清除 DeepSeek API Key,图片转文字已关闭。`,e?`success`:``),Z(e?`DeepSeek API Key 已保存`:`DeepSeek API Key 已清除`,null))}async function la(){let e=ct(S.deepseekKeyInput.value),t=lt(e);if(t)sa(t,`error`),S.deepseekKeyInput.focus();else{S.testDeepseekButton.disabled=!0,S.testDeepseekButton.textContent=`测试中…`,sa(`正在连接 DeepSeek…`,`busy`);try{await Ct(e),sa(`连接正常,保存 Key 后即可识别图片。`,`success`)}catch(e){sa(e instanceof Error?e.message:`连接 DeepSeek 失败`,`error`)}finally{S.testDeepseekButton.disabled=!1,S.testDeepseekButton.textContent=`测试连接`}}}function ua(e){x.settingsOpen=e,e?(S.settingsPage.open||(typeof S.settingsPage.showModal==`function`?S.settingsPage.showModal():S.settingsPage.setAttribute(`open`,``)),Ga()):(S.settingsPage.open?S.settingsPage.close():S.settingsPage.removeAttribute(`open`),Y()),e?(S.mobileSearchPanel.hidden=!0,S.searchBox.classList.remove(`is-open`),S.settingsPageScroll.scrollTop=0):fa()}function da(){S.updateTokenInput.value=I.token,ya(),Na(),Za({announce:!1}),S.aboutDialog.open||(typeof S.aboutDialog.showModal==`function`?S.aboutDialog.showModal():S.aboutDialog.setAttribute(`open`,``)),requestAnimationFrame(()=>S.closeAboutIconButton.focus())}function fa(){S.aboutDialog.open&&S.aboutDialog.close()}async function pa(){if(S.remindersEnabledInput&&S.notificationStatusHint){if(S.remindersEnabledInput.disabled=!0,!he)S.remindersEnabledInput.checked=!1,S.notificationStatusHint.textContent=`电脑端使用应用内提示;Android APK 安装后可开启系统通知`;else try{let e=await we();x.reminderStatus=e.permission;let t=e.permission===`granted`;S.remindersEnabledInput.checked=e.enabled&&t,S.remindersEnabledInput.disabled=x.reminderUpdating,e.enabled&&t?S.notificationStatusHint.textContent=`已开启 · 截止日当天 09:00`:e.permission===`denied`?S.notificationStatusHint.textContent=`权限已关闭,请在 Android 系统设置中允许简记通知`:S.notificationStatusHint.textContent=`开启后由 Android 弹出通知权限请求`}catch{x.reminderStatus=`error`,S.remindersEnabledInput.checked=!1,S.remindersEnabledInput.disabled=!1,S.notificationStatusHint.textContent=`无法读取通知权限,请稍后重试`}}}async function ma(){if(!he||x.reminderUpdating){pa();return}x.reminderUpdating=!0,S.remindersEnabledInput.disabled=!0;let e=S.remindersEnabledInput.checked;try{e?(await Te(),await De(x.items),Z(`已开启截止日提醒`,null)):(await Ee(),Z(`已关闭截止日提醒`,null))}catch(e){Z(e instanceof Error?e.message:`通知设置失败`,null)}finally{x.reminderUpdating=!1,pa()}}function ha(){x.settingsOpen&&(ua(!1),location.hash===`#settings`&&(x.settingsHistoryPushed?(x.settingsHistoryPushed=!1,history.back()):history.replaceState(history.state,``,`${location.pathname}${location.search}`)))}function ga(){return S.heatmapHelpDialog.open?(ur(),!0):S.recordDrawer.open?(cr(),!0):x.statsOpen?(or(),!0):S.savePromptDialog.open?(x.draftAfter=null,Mi(),!0):S.confirmDialog.open?($o(),!0):S.updateDialog.open?(lo(),!0):S.aboutDialog.open?(fa(),!0):S.createDialog.open?(Vi(),!0):S.recordDialog.open?(Gi(),!0):S.inspector.open?(Ii(),!0):x.openMenuId?(x.openMenuId=null,H(),!0):S.mobileSearchPanel.hidden?x.settingsOpen?(ha(),!0):!1:(aa(),!0)}function _a(){e&&ue.addListener(`backButton`,({canGoBack:e})=>{ga()||(e?history.back():ue.exitApp().catch(()=>{}))}).catch(()=>{})}function va(){location.hash===`#statistics`?(x.settingsOpen&&ua(!1),x.statsOpen||(x.statsView=`overview`,x.statsYear=new Date().getFullYear(),x.statsSelectedDate=``,rr(!0))):(x.statsOpen&&(rr(!1),x.statsHistoryPushed=!1),location.hash===`#settings`?x.settingsOpen||oa():(x.settingsOpen&&ua(!1),x.settingsHistoryPushed=!1))}function K(e){S.updateStatusHint.textContent=e}function ya(){S.aboutUpdateFeedback.hidden=!0,S.aboutUpdateFeedback.textContent=``,S.aboutUpdateFeedback.dataset.tone=``}function ba(e,t=`error`){S.aboutDialog.open?(S.aboutUpdateFeedback.textContent=e,S.aboutUpdateFeedback.dataset.tone=t,S.aboutUpdateFeedback.hidden=!1):Z(e,null)}function xa(e){let t=[],n=new Date(e.publishedAt);return Number.isNaN(n.getTime())||t.push(`发布于 ${new Intl.DateTimeFormat(`zh-CN`,{year:`numeric`,month:`long`,day:`numeric`}).format(n)}`),e.size>0&&t.push(`${(e.size/1024/1024).toFixed(1)} MB`),t.join(` · `)}function Sa(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:new Intl.DateTimeFormat(`zh-CN`,{year:`numeric`,month:`2-digit`,day:`2-digit`}).format(t)}function Ca(e){return String(e||`本次发布未提供更新说明。`).split(/\r?\n/).map(e=>{let t=e.match(/^#{1,6}\s+(.+)$/);if(t)return`<div class="release-note-heading">${L(t[1])}</div>`;let n=e.match(/^\s*[-*]\s+(.+)$/);return n?`<div class="release-note-item">${L(n[1])}</div>`:e.trim()?`<div class="release-note-line">${L(e)}</div>`:`<div class="release-note-gap"></div>`}).join(``)}function q(e){let t=typeof e==`string`?e:e?.version;if(!t)return`same`;let n=Pe(t,x.updateInfo?.versionName||a);return n>0?`upgrade`:n<0?`downgrade`:`same`}function wa(e){return{upgrade:`升级`,downgrade:`降级`,same:`重新安装`}[q(e)]}function Ta(e){return Array.isArray(e)?e.filter(e=>e&&/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(String(e.version||``).replace(/^v/i,``))&&typeof e.downloadUrl==`string`&&/^https:\/\//i.test(e.downloadUrl)):[]}function Ea(e){let t=Ta(e);return x.releaseHistory=t,w(d,t),Na(),t}function Da(){return Ta(C(d,[]))}function Oa(){let e=C(p,{});return typeof e.version==`string`?e.version:``}function ka(e){x.exportedUpdateVersion=e,w(p,{version:e}),Xa(),Na()}function Aa(e){let t=q(e);return t===`upgrade`?{label:`可升级`,className:`is-new`}:t===`same`?{label:`当前版本`,className:`is-current`}:{label:`历史版本`,className:``}}function ja(e){let t=x.updateDownload;if(t?.version===e.version&&t.phase===`downloaded`)return q(e)===`downgrade`?`导出降级包`:`立即安装`;if(t?.version===e.version&&J(t))return`下载中`;let n=q(e);return n===`upgrade`?`直接升级`:n===`downgrade`?`下载降级包`:`重新安装`}function Ma(e){return x.releaseHistory.find(t=>t.version===e)||(x.latestUpdate?.version===e?x.latestUpdate:null)||(x.updateTarget?.version===e?x.updateTarget:null)}function Na(){if(!S.updateHistoryList)return;let e=x.updateInfo?.versionName||a;if(S.updateHistoryPanel.hidden=!x.updateHistoryOpen,S.toggleUpdateHistoryButton.textContent=x.updateHistoryOpen?`收起`:`展开`,x.updateHistoryLoading?S.updateHistoryHint.textContent=`正在读取 GitHub Release…`:x.releaseHistory.length?S.updateHistoryHint.textContent=`共 ${x.releaseHistory.length} 个可安装版本 · 当前 v${String(e).replace(/^v/i,``)}`:S.updateHistoryHint.textContent=`查看每个版本的更新内容和安装包`,!x.updateHistoryOpen)return;if(x.updateHistoryLoading&&!x.releaseHistory.length){S.updateHistoryList.innerHTML=`<p class="update-history-empty">正在读取历史版本…</p>`;return}if(!x.releaseHistory.length){S.updateHistoryList.innerHTML=`<p class="update-history-empty">还没有历史版本数据,请先检查更新。</p>`;return}let t=J()?x.updateDownload.version:``;S.updateHistoryList.innerHTML=x.releaseHistory.map(e=>{let n=Aa(e),r=e.notes||`本次发布未提供更新说明。`,i=!!(t&&t!==e.version),a=ja(e);return`
|
|
462
|
+
<article class="version-history-item" data-version="${L(e.version)}">
|
|
463
|
+
<div class="version-history-head">
|
|
464
|
+
<div class="version-history-identity">
|
|
465
|
+
<span class="version-history-version">v${L(String(e.version).replace(/^v/i,``))}</span>
|
|
466
|
+
<span class="version-history-badge ${n.className}">${n.label}</span>
|
|
467
|
+
</div>
|
|
468
|
+
<time class="version-history-date" datetime="${L(e.publishedAt||``)}">${L(Sa(e.publishedAt))}</time>
|
|
469
|
+
</div>
|
|
470
|
+
<div class="version-history-notes">${Ca(r)}</div>
|
|
471
|
+
<div class="version-history-actions">
|
|
472
|
+
<button class="quiet-button version-history-action" type="button" data-version-action="details">查看详情</button>
|
|
473
|
+
<button class="secondary-button version-history-action" type="button" data-version-action="install" ${i?`disabled`:``}>${a}</button>
|
|
474
|
+
</div>
|
|
475
|
+
</article>
|
|
476
|
+
`}).join(``)}function Pa(e){x.updateHistoryOpen=!!e,Na(),x.updateHistoryOpen&&!x.releaseHistory.length&&!x.updateHistoryLoading&&Fa()}async function Fa({quiet:e=!1}={}){if(x.updateHistoryLoading)return x.releaseHistory;x.updateHistoryLoading=!0,Na();try{let e=await Be(o,I.token);return Ea(e),e}catch(t){let n=t instanceof Error?t.message:`历史版本读取失败`;return S.updateHistoryHint.textContent=`历史版本读取失败,可稍后重试`,e||Z(n,null),x.releaseHistory.length||(S.updateHistoryList.innerHTML=`<p class="update-history-empty">无法读取历史版本,请检查网络或 GitHub 令牌。</p>`),x.releaseHistory}finally{x.updateHistoryLoading=!1,Na()}}function Ia(e){S.updateError.textContent=e,S.updateError.hidden=!1}function La(){S.updateError.textContent=``,S.updateError.hidden=!0}function Ra(e){return!e||typeof e!=`object`?null:{version:String(e.version||``),phase:String(e.phase||`idle`),active:!!e.active,bytesDownloaded:Math.max(0,Number(e.bytesDownloaded)||0),totalBytes:Math.max(0,Number(e.totalBytes)||0),percent:Number.isFinite(Number(e.percent))?Number(e.percent):null,error:String(e.error||``),canInstallPackages:!!e.canInstallPackages}}function J(e=x.updateDownload){return!!(e&&(e.active||[`queued`,`downloading`,`verifying`,`retrying`].includes(e.phase)))}function za(e=x.updateDownload){return e?Number.isFinite(e.percent)?Math.max(0,Math.min(100,e.percent)):e.totalBytes>0?Math.max(0,Math.min(100,e.bytesDownloaded*100/e.totalBytes)):null:null}function Ba(e){let t=Number(e||0);return t<1024?`${Math.max(0,Math.round(t))} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function Va(e){e?w(u,e):Ne(u,``)}function Ha(){let e=C(u,null);return!e||!e.version||!e.downloadUrl?null:e}function Ua(){let e=C(f,{});return typeof e.version==`string`?e.version:``}function Wa(e){let t=Ua();return!!t&&Pe(e,t)<=0}function Ga(){S.updateNotice.hidden=!0,x.updateNoticeVersion=``}function Y(e=x.updateTarget||x.latestUpdate){let t=x.updateDownload,n=t?.phase===`downloaded`?Ma(t.version)||{version:t.version}:null,r=!!(n&&q(n)!==`downgrade`),i=r?n:e;if(!i||x.settingsOpen||!S.mobileSearchPanel.hidden||x.search||J()||r&&x.readyUpdateNoticeDismissedVersion===i.version||!r&&t?.phase===`downloaded`&&t.version===i.version||!r&&Wa(i.version)){Ga();return}if(r){S.updateNotice.classList.add(`is-ready`),S.updateNoticeIcon?.setAttribute(`href`,`#icon-check`),S.updateNoticeTitle.textContent=`简记 ${i.version} 已下载`,S.updateNoticeDetail.textContent=q(i)===`same`?`安装包已通过校验,点击按钮可重新安装`:`新版本安装包已通过校验,点击按钮完成更新`,S.updateNoticeAction.textContent=`立即更新`,S.updateNotice.hidden=!1,x.updateNoticeVersion=i.version;return}let o=x.updateInfo?.versionName||a,s=t?.phase===`failed`;S.updateNotice.classList.remove(`is-ready`),S.updateNoticeIcon?.setAttribute(`href`,`#icon-download`),S.updateNoticeTitle.textContent=`发现新版本 ${i.version}`,S.updateNoticeDetail.textContent=s?`上次下载未完成,点击重试更新`:`当前 v${String(o).replace(/^v/i,``)},确认后将后台下载`,S.updateNoticeAction.textContent=s?`重试`:`更新`,S.updateNotice.hidden=!1,x.updateNoticeVersion=i.version}function Ka(){let e=x.updateNoticeVersion||x.latestUpdate?.version||``;e&&x.updateDownload?.phase===`downloaded`&&x.updateDownload.version===e?x.readyUpdateNoticeDismissedVersion=e:e&&w(f,{version:e}),Ga()}function qa(e,t=!1){S.installUpdateButton.disabled=t,S.closeUpdateButton.disabled=!1,S.laterUpdateButton.disabled=!1,S.installUpdateButton.querySelector(`span`).textContent=e;let n=S.installUpdateButton.querySelector(`use`);n&&n.setAttribute(`href`,e===`立即安装`?`#icon-check`:`#icon-download`)}function Ja(){clearTimeout(x.updatePollTimer),x.updatePollTimer=null}function Ya(){Ja(),Je()&&J()&&(x.updatePollTimer=setTimeout(()=>{x.updatePollTimer=null,Za({announce:!0})},1e3))}function Xa(){Na();let e=x.updateDownload,t=x.updateTarget||x.latestUpdate,n=J(e),r=e?.phase===`downloaded`,i=e?.phase===`failed`,o=e?.phase===`retrying`,s=za(e),c=s===null?null:Math.round(s),l=e?.version||t?.version||``,u=Ma(l)||{version:l},d=q(u),f=!!l&&x.exportedUpdateVersion===l,p=!!(t||n||r||i||o);if(S.updateDownloadRow.hidden=!p,S.updateUninstallAction.hidden=!(r&&d===`downgrade`&&f),S.updateProgressTrack.hidden=!p||!n&&!r&&!(i&&e?.bytesDownloaded>0),S.updateProgressBar.style.width=`${s===null?0:s}%`,S.updateProgressTrack.setAttribute(`aria-valuenow`,String(c===null?0:c)),!p){let e=q(t);qa(Je()?e===`downgrade`?`下载降级包`:e===`same`?`重新安装`:`后台下载`:`前往下载 APK`,!t),x.updateChecking||K(`尚未发现可用更新`),Y();return}if(n){let t=e.phase===`queued`?`等待系统开始下载`:e.phase===`verifying`?`正在校验安装包`:e.phase===`retrying`?`网络中断,等待自动重试${e.error?`:${e.error}`:``}`:c===null?`已下载 ${Ba(e.bytesDownloaded)}`:`${c}% · ${Ba(e.bytesDownloaded)} / ${Ba(e.totalBytes)}`;S.updateDownloadLabel.textContent=`后台下载 ${l}`,S.updateDownloadDetail.textContent=t,S.updateDownloadAction.textContent=`取消`,qa(`后台下载中`,!0),K(`后台下载 ${l} · ${t}`),S.updateDialog.open&&(S.updateDialogCopy.textContent=`正在后台下载 ${l},可以关闭此窗口。`),Y();return}if(r){S.updateDownloadLabel.textContent=`${l} 已下载`,d===`downgrade`?(S.updateDownloadDetail.textContent=f?`降级包已导出;请先卸载当前版本,再从保存位置安装`:`Android 不允许直接覆盖降级,请先导出安装包`,S.updateDownloadAction.textContent=f?`重新导出`:`导出降级包`,qa(f?`卸载当前版本`:`导出降级包`),K(f?`${l} 安装包已导出,可卸载当前版本`:`${l} 已下载,降级前需导出安装包`)):(S.updateDownloadDetail.textContent=`安装包已通过校验,等待系统安装`,S.updateDownloadAction.textContent=`立即安装`,qa(`立即安装`),K(`${l} 已下载,等待安装`)),S.updateDialog.open&&(S.updateDialogCopy.textContent=d===`downgrade`?f?`${l} 降级包已导出。卸载当前版本后,请从保存位置完成安装。`:`${l} 已下载并通过校验。请先导出安装包,再卸载当前版本。`:`${l} 已下载并通过校验,点击立即安装。`),Y();return}if(i){S.updateDownloadLabel.textContent=`${l} 下载失败`,S.updateDownloadDetail.textContent=e.error||`请检查网络后重试`,S.updateDownloadAction.textContent=`重试`,qa(`重试下载`,!t),K(`${l} 下载失败,可重试`),S.updateDialog.open&&(S.updateDialogCopy.textContent=`后台下载暂时失败,可以稍后重试。`),Y();return}S.updateDownloadLabel.textContent=`发现新版本 ${l}`;let ee=wa(u);if(S.updateDownloadLabel.textContent=`${ee}版本 ${l}`,S.updateDownloadDetail.textContent=d===`downgrade`?`降级包下载后需先导出,再卸载当前版本安装`:`开始后可关闭弹窗,下载会在后台继续`,S.updateDownloadAction.textContent=d===`downgrade`?`下载降级包`:`后台下载`,qa(Je()?d===`downgrade`?`下载降级包`:d===`same`?`重新安装`:`后台下载`:`前往下载 APK`),K(`${ee}版本 ${l},可后台下载`),S.updateDialog.open){let e=x.updateInfo?.versionName||a;S.updateDialogCopy.textContent=d===`downgrade`?`当前 v${e},可下载 ${l} 降级包。系统不支持直接覆盖降级。`:d===`same`?`当前已安装 v${e},可重新下载并覆盖安装。`:`当前 v${e},可升级到 ${l}。开始后可关闭窗口。`}Y()}async function Za({announce:e=!0}={}){if(!Je()||x.updateRefreshing)return x.updateDownload;x.updateRefreshing=!0;let t=x.updateDownload;try{let n=Ra(await He());return x.updateDownload=n&&![`idle`,`cancelled`].includes(n.phase)?n:null,Xa(),e&&x.updateDownload?.phase===`failed`&&t?.phase!==`failed`&&Z(x.updateDownload.error||`后台下载失败,可在设置中重试`,null),x.updateDownload}catch{return e&&K(`无法读取后台下载状态,请稍后重试`),x.updateDownload}finally{x.updateRefreshing=!1,Ya()}}function Qa(e){if(e.requiresAuth){let e=`私有仓库的 APK 需要在 Android 应用内下载安装。`;return Ia(e),Z(e,null),!1}let t=document.createElement(`a`);return t.href=e.downloadUrl,t.target=`_blank`,t.rel=`noopener noreferrer`,t.click(),Z(`已打开 GitHub 下载页`,null),!0}async function $a(e){if(!e||J())return!1;if(x.updateTarget=e,x.readyUpdateNoticeDismissedVersion=``,La(),!Je())return Qa(e);K(`正在创建 ${e.version} 的后台下载任务`);try{let t=await Ve(e,I.token);return x.updateDownload=Ra(t),Xa(),lo(),Z(`已开始后台下载,完成后会在首页提示更新`,null),Ya(),!0}catch(e){let t=e instanceof Error?e.message:`无法开始后台下载,请稍后重试`;return Ia(t),K(`无法开始后台下载,可重试`),S.updateDialog.open||Z(t,null),!1}}async function eo(){if(!S.updateNoticeAction.disabled){if(x.updateDownload?.phase===`downloaded`){S.updateNoticeAction.disabled=!0,S.updateNoticeAction.textContent=`正在打开…`;try{await io()}finally{S.updateNoticeAction.disabled=!1,S.updateNotice.hidden||(S.updateNoticeAction.textContent=`立即更新`)}}else if(x.latestUpdate){S.updateNoticeAction.disabled=!0,S.updateNoticeAction.textContent=`准备中…`;try{await $a(x.latestUpdate)&&Ga()}finally{S.updateNoticeAction.disabled=!1,S.updateNotice.hidden||(S.updateNoticeAction.textContent=x.updateDownload?.phase===`failed`?`重试`:`更新`)}}}}async function to(){if(J())try{let e=await Ke();x.updateDownload=Ra(e),Ja(),Xa(),Z(`已取消后台下载`,null)}catch(e){Z(e instanceof Error?e.message:`取消下载失败,请稍后重试`,null)}}async function no(){let e=x.updateDownload;if(e?.phase!==`downloaded`||q(e.version)!==`downgrade`)return!1;La();try{return(await We())?.exported?(ka(e.version),K(`${e.version} 降级包已导出,可卸载当前版本`),Z(`降级包已导出;卸载当前版本后,请从保存位置安装`,null),!0):(K(`已取消导出,降级包仍保留在应用内`),!1)}catch(e){let t=e instanceof Error?e.message:`导出降级包失败,请重试`;return Ia(t),K(`导出降级包失败,可重试`),S.updateDialog.open||Z(t,null),!1}}function ro(){let e=x.updateDownload;e&&e.phase===`downloaded`&&q(e.version)===`downgrade`&&(x.exportedUpdateVersion===e.version?Zo(`卸载当前版本并安装降级包`,`系统不允许直接覆盖安装低版本,必须卸载当前版本的简记。卸载会清除本机数据;如已配置 Gitee 同步,重装后可恢复。请确认降级包已保存到可访问位置。`,async()=>{try{await Ge(),K(`已打开系统卸载页面,卸载后请安装导出的降级包`)}catch(e){let t=e instanceof Error?e.message:`无法打开系统卸载页面`;Ia(t),Z(t,null)}}):no())}async function io(){let e=x.updateDownload,t=e?.phase===`downloaded`?Ma(e.version)||{version:e.version}:x.updateTarget||x.latestUpdate;if(!J(e)){if(!t)await po({manual:!0,prompt:`dialog`});else if(e?.phase!==`downloaded`||e.version!==t.version)await $a(t);else if(q(t)===`downgrade`)x.exportedUpdateVersion===e.version?ro():no();else{La();try{await Ue(),K(`${e.version} 安装包已就绪,等待系统安装`),Z(`请按系统提示完成安装`,null)}catch(t){let n=t?.code||t?.data?.code;if(n===`INSTALL_PERMISSION_REQUIRED`)try{await qe(),Ia(`请在系统页面允许“简记”安装应用,然后返回并点击“立即安装”。`),K(`等待开启安装未知应用权限`)}catch{Ia(`无法打开安装权限设置,请在 Android 系统设置中允许简记安装未知应用。`)}else if(n===`DOWNGRADE_REQUIRES_UNINSTALL`)Ia(`Android 不允许直接覆盖安装低版本,请先导出降级包并卸载当前版本。`),K(`${e.version} 安装包已下载,等待导出降级包`);else{let e=t instanceof Error?t.message:`无法启动系统安装器,请重试`;Ia(e),K(`安装包已下载,可重新尝试安装`),S.updateDialog.open||Z(e,null)}}}}}function ao(){if(!J())return io()}function oo(){let e=x.updateDownload;if(J(e))return to();if(e?.phase===`downloaded`)return q(e.version)===`downgrade`?x.exportedUpdateVersion===e.version?ro():no():io();let t=x.updateTarget||x.latestUpdate;return t?$a(t):po({manual:!0})}async function so(e){let t=e.target.closest(`[data-version-action]`);if(!t)return;let n=Ma(t.closest(`[data-version]`)?.dataset.version||``);if(!n){Z(`无法找到该历史版本,请刷新后重试`,null);return}if(t.dataset.versionAction===`details`){co(n);return}if(t.dataset.versionAction!==`install`)return;x.updateTarget=n;let r=x.updateDownload;r?.version===n.version&&r.phase===`downloaded`?await io():await $a(n)}function co(e){if(!e)return;fa(),x.updateTarget=e;let t=x.updateInfo?.versionName||a,n=q(e);S.updateDialogTitle.textContent=n===`upgrade`?`发现新版本`:`版本详情`,S.updateDialogCopy.textContent=n===`upgrade`?`当前 v${t},可升级到 ${e.version}。`:n===`downgrade`?`当前 v${t},${e.version} 为较低版本。Android 需要先卸载当前版本才能降级安装。`:`当前已安装 v${t},可重新下载并覆盖安装。`,S.updateReleaseVersion.textContent=e.version,S.updateReleaseMeta.textContent=xa(e),S.updateReleaseNotes.innerHTML=Ca(e.notes),La(),Xa(),S.updateDialog.open||(typeof S.updateDialog.showModal==`function`?S.updateDialog.showModal():S.updateDialog.setAttribute(`open`,``))}function lo(){S.updateDialog.open&&S.updateDialog.close()}async function uo(){let e=await Ie(a);x.updateInfo=e,x.releaseHistory=Da(),x.exportedUpdateVersion=Oa(),S.updateTokenInput.value=I.token;let t=`v${String(e.versionName).replace(/^v/i,``)}`;S.appVersionLabel.textContent=`当前版本 ${t}`,S.aboutVersionLabel.textContent=t;let n=Ha();if(x.latestUpdate=n&&Pe(n.version,e.versionName)>0?n:null,x.latestUpdate||Va(null),await Za({announce:!1}),x.updateDownload?.version&&Pe(e.versionName,x.updateDownload.version)===0){try{await Ke()}catch{}x.updateDownload=null}Na(),Xa(),!x.latestUpdate&&!x.updateDownload&&(Je()&&!e.nativeInstaller?K(`此版本需手动安装一次,以启用应用内更新`):Je()?K(`启动时会自动检查 GitHub Release`):K(`发现新版后可下载 Android APK`))}function fo(){return Ut({token:S.updateTokenInput.value}),po({manual:!0,prompt:`dialog`})}async function po({manual:e=!1,prompt:t=e?`dialog`:`notice`}={}){if(x.updateChecking)return null;if(e&&ya(),!navigator.onLine)return K(`当前离线,联网后可检查更新`),e&&ba(`当前离线,无法检查更新`,`error`),null;x.updateChecking=!0,S.checkUpdateButton.disabled=!0,S.checkUpdateButton.textContent=`检查中…`,e&&K(`正在检查 GitHub Release`);try{let n=await Be(o,I.token);Ea(n),e&&(x.updateHistoryOpen=!0,Na());let r=n[0],i=x.updateInfo?.versionName||a;return Pe(r.version,i)<=0?(x.latestUpdate=null,x.updateTarget=null,Va(null),Ga(),Xa(),x.updateDownload||K(`已是最新版本`),e&&ba(`当前已是最新版本 v${String(i).replace(/^v/i,``)}`,`success`),null):(x.latestUpdate=r,x.updateTarget=r,Va(r),Xa(),t===`dialog`?co(r):t===`notice`&&Y(r),r)}catch(t){let n=t instanceof Error?t.message:`检查更新失败,请稍后重试`;return x.updateDownload?Xa():K(I.token?`令牌已保存,但 Release 检查失败`:/未找到|无法访问/.test(n)?`私有仓库请填写 GitHub 只读令牌`:`检查更新失败,可稍后重试`),e&&ba(n,`error`),null}finally{x.updateChecking=!1,S.checkUpdateButton.disabled=!1,S.checkUpdateButton.textContent=`检查更新`}}function mo(){if(!F.repo){S.settingsSyncMeta.textContent=`尚未连接仓库`,S.disconnectButton.disabled=!0;return}let e=x.lastSyncedAt?new Intl.DateTimeFormat(`zh-CN`,{hour:`2-digit`,minute:`2-digit`}).format(new Date(x.lastSyncedAt)):`尚未完成`;S.settingsSyncMeta.textContent=`上次同步:${e}`,S.disconnectButton.disabled=!1}function ho(e){let t=e.trim().replace(/\.git$/,``).replace(/\/$/,``),n=t.match(/gitee\.com[/:]([^/]+)\/([^/]+)/i);if(n)return{owner:n[1],repo:n[2]};let r=t.match(/^([^/\s]+)\/([^/\s]+)$/);return r?{owner:r[1],repo:r[2]}:null}function go(e){if(!ho(e.repo))return`请填写有效的 Gitee 仓库地址。`;if(!/^[^\s]+$/.test(e.branch)||e.branch.includes(`..`))return`请填写有效的分支名称。`;let t=Et(e.directory);return t&&!/^(?:[^/]+\/)*[^/]+$/.test(t)||t.split(`/`).includes(`..`)||/\.json$/i.test(t)?`数据目录必须是仓库内的相对目录。`:e.token?``:`请填写 Gitee 私人令牌。`}async function _o(){let e={repo:S.repoInput.value.trim(),branch:S.branchInput.value.trim()||`master`,directory:Et(S.pathInput.value),legacyPath:``,token:S.tokenInput.value.trim(),autoSync:S.autoSyncInput.checked},t=go(e);t?vo(t):(Wt(e),S.settingsError.hidden=!0,await qo({manual:!0}),x.syncState!==`error`&&ha())}function vo(e){S.settingsError.textContent=e,S.settingsError.hidden=!1}function yo(){Zo(`断开 Gitee 仓库`,`本机待办不会被删除,之后仍可重新连接并继续同步。`,()=>{Wt({repo:``,branch:`master`,directory:``,token:``,autoSync:!0}),X(`local`,`仅保存在本机`),mo(),S.repoInput.value=``,S.tokenInput.value=``,ha(),Z(`已断开仓库,本机数据仍保留`,null)})}function X(e,t){x.syncState=e,x.syncMessage=t,bo(),mo()}function bo(){let e=x.syncMessage,t=``;F.repo?navigator.onLine?x.syncState===`syncing`?(e=`正在同步`,t=`is-syncing`):x.syncState===`synced`?(e=x.dirty?`有修改待同步`:`已同步`,t=`is-synced`):x.syncState===`error`?(e=`同步失败`,t=`is-error`):e=`已连接`:(e=`离线,修改待同步`,t=`is-error`):e=`仅保存在本机`,S.desktopSyncLabel.textContent=e,S.syncButton.setAttribute(`aria-label`,`同步状态:${e},点击立即同步`),S.desktopSyncDot.className=`sync-dot ${t}`,S.mobileSyncButton.className=`mobile-sync ${t}`,S.mobileSyncButton.setAttribute(`aria-label`,`同步状态:${e},点击立即同步`),S.mobileSyncButton.title=e,S.mobileSyncBadge.hidden=t!==`is-error`}function xo(e){let t=new TextEncoder().encode(e),n=``;for(let e=0;e<t.length;e+=8192)n+=String.fromCharCode(...t.subarray(e,e+8192));return btoa(n)}function So(e){let t=atob(e.replace(/\s/g,``)),n=Uint8Array.from(t,e=>e.charCodeAt(0));return new TextDecoder().decode(n)}function Co(e,t,n=!1){let r=ho(F.repo);if(!r)throw Error(`仓库地址无效`);let i=e.split(`/`).map(encodeURIComponent).join(`/`),a=n?`&_=${Date.now()}`:``;return`repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}/contents/${i}?ref=${encodeURIComponent(t)}${a}`}async function wo(n,r={},i=F.branch){let a;if(e){let e=`https://gitee.com/api/v5/${n}`;try{let t=await te.request({url:e,method:r.method||`GET`,headers:{Accept:`application/json`,Authorization:`token ${F.token}`,...r.body?{"Content-Type":`application/json`}:{}},data:r.body||void 0}),n=typeof t.data==`string`?t.data:JSON.stringify(t.data??``);a=new Response(n,{status:t.status,headers:t.headers||{}})}catch{throw Error(`无法连接 Gitee,请检查网络与仓库权限`)}}else{let e=[`localhost`,`127.0.0.1`,`::1`].includes(location.hostname),i=t?new URL(`../api/gitee/`,location.href).href:e?`/api/gitee/`:`https://gitee.com/api/v5/`;a=await fetch(`${i}${n}`,{method:r.method||`GET`,cache:`no-store`,headers:{Accept:`application/json`,Authorization:`token ${F.token}`,...r.body?{"Content-Type":`application/json`}:{}},body:r.body?JSON.stringify(r.body):void 0})}if(a.status===401||a.status===403)throw Error(`令牌无效或没有该仓库的读写权限`);if(!a.ok&&a.status!==404){let e=``;try{let t=await a.json();e=t.message||t.error||``}catch{}let t=Error(e||`Gitee 请求失败(${a.status})`);throw t.giteeStatus=a.status,t}return a}function To(){let e=Ot(F.directory);return wt.map(t=>({...Tt[t],path:e[t]}))}async function Eo(e,{cacheBust:t=!1}={}){let n=await wo(Co(e.path,F.branch,t));if(n.status===404||n.status===204)return{exists:!1,data:null,sha:``};let r=await n.text();if(!r.trim())return{exists:!1,data:null,sha:``};let i;try{i=JSON.parse(r)}catch{throw Error(`远端 ${e.filename} 返回内容无法解析`)}if(Array.isArray(i)){if(!i.length)return{exists:!1,data:null,sha:``};throw Error(`远端路径指向目录,请填写 JSON 文件路径`)}if(!i||typeof i!=`object`)throw Error(`远端 ${e.filename} 格式不正确`);let a=typeof i.sha==`string`?i.sha:``;if(Number(i.size)===0||Object.hasOwn(i,`content`)&&typeof i.content==`string`&&!i.content.trim())return{exists:!1,data:null,sha:a};if(typeof i.content!=`string`)throw Error(`远端数据文件格式不正确`);let o;try{o=So(i.content).trim()}catch{throw Error(`远端 ${e.filename} 无法解码,请先检查文件内容`)}if(!o)return{exists:!1,data:null,sha:a};let s;try{s=JSON.parse(o)}catch{throw Error(`远端 ${e.filename} 中的 JSON 无法解析`)}try{s=jt(e.key,s)}catch(t){throw Error(t.message||`远端 ${e.filename} 格式不正确`)}return{exists:!0,data:s,sha:a}}function Do(e){let t=e&&e.message?e.message:``;return/文件名已存在|文件已存在|already exists|file exists/i.test(t)}async function Oo(e){let t=await Eo(e,{cacheBust:!0});for(let n of ae){if(t.sha)return t;await rt(n),t=await Eo(e,{cacheBust:!0})}return t}async function ko(e,t){let n=ho(F.repo);if(!n)throw Error(`仓库地址无效`);let r=e.path.split(`/`).map(encodeURIComponent).join(`/`),i=At(e.key,{items:x.items,records:x.records,inspirations:x.inspirations,commonTags:x.commonTags,commonTagRecords:x.commonTagRecords,commonTagsUpdatedAt:x.commonTagsUpdatedAt,commonTagsDeviceId:x.commonTagsDeviceId},{schemaVersion:7,revision:Date.now(),updatedAt:T()}),a={content:xo(JSON.stringify(i,null,2)),message:`update ${e.filename} ${new Date().toISOString()}`,branch:F.branch};t&&(a.sha=t);let o=await wo(`repos/${encodeURIComponent(n.owner)}/${encodeURIComponent(n.repo)}/contents/${r}`,{method:t?`PUT`:`POST`,body:a});if(!o.ok)throw Error(`写入 ${e.filename} 失败(${o.status})`)}function Ao(e,t){let n=new Date(e.updatedAt||0).getTime(),r=new Date(t.updatedAt||0).getTime();return n===r?String(e.deviceId||``).localeCompare(String(t.deviceId||``)):n-r}function jo(e,t){let n=new Map;[...t,...e].filter(gt).map(yt).forEach(e=>{let t=n.get(e.id);(!t||Ao(e,t)>0)&&n.set(e.id,e)});let r=Date.now()-m;return[...n.values()].filter(e=>!e.deletedAt||new Date(e.deletedAt).getTime()>r)}function Mo(e,t){let n=new Map;[...t,...e].filter(bt).map(xt).forEach(e=>{let t=n.get(e.id);(!t||Ao(e,t)>0)&&n.set(e.id,e)});let r=Date.now()-m;return[...n.values()].filter(e=>!e.deletedAt||new Date(e.deletedAt).getTime()>r)}function No(e,t){let n=new Map;[...t,...e].filter(Mt).map(Lt).forEach(e=>{let t=n.get(e.id);(!t||Ao(e,t)>0)&&n.set(e.id,e)});let r=Date.now()-m;return[...n.values()].filter(e=>!e.deletedAt||new Date(e.deletedAt).getTime()>r)}function Po(e){let t=A(x.commonTags,50),n=A(e?.commonTags,50),r=j(x.commonTagRecords),i=j(e?.commonTagRecords),a=String(e?.commonTagsUpdatedAt||``),o=String(e?.commonTagsDeviceId||``),s=j([...i,...ut(n,a,o),...r,...ut(t,x.commonTagsUpdatedAt,x.commonTagsDeviceId)]),c=s.reduce((e,t)=>e?Ao(t,e)>0?t:e:t,null);return{commonTags:dt(s),commonTagRecords:s,commonTagsUpdatedAt:c?.updatedAt||``,commonTagsDeviceId:c?.deviceId||``}}function Fo(e){return j(e).sort((e,t)=>k(e.value).localeCompare(k(t.value),`zh-CN`))}function Io(e){return{items:e?.items||[],records:e?.records||[],inspirations:e?.inspirations||[],commonTags:A(e?.commonTags,50).sort((e,t)=>k(e).localeCompare(k(t),`zh-CN`)),commonTagRecords:Fo(e?.commonTagRecords),commonTagsUpdatedAt:String(e?.commonTagsUpdatedAt||``),commonTagsDeviceId:String(e?.commonTagsDeviceId||``)}}function Lo(e,t){let n=Io(t);return e===`records`?n.records:e===`inspirations`?n.inspirations:{items:n.items,commonTags:n.commonTags,commonTagRecords:n.commonTagRecords,commonTagsUpdatedAt:n.commonTagsUpdatedAt,commonTagsDeviceId:n.commonTagsDeviceId}}function Ro(e){x.items=e.items,x.records=e.records,x.inspirations=e.inspirations,x.commonTags=e.commonTags,x.commonTagRecords=e.commonTagRecords,x.commonTagsUpdatedAt=e.commonTagsUpdatedAt,x.commonTagsDeviceId=e.commonTagsDeviceId}function zo(e){let t=Po(e);return{items:jo(x.items,e?.items||[]),records:Mo(x.records,e?.records||[]),inspirations:No(x.inspirations,e?.inspirations||[]),...t}}function Bo(e,t){if(e===`records`){x.records=Mo(x.records,t?.records||[]);return}if(e===`inspirations`){x.inspirations=No(x.inspirations,t?.inspirations||[]);return}x.items=jo(x.items,t?.items||[]);let n=Po(t);x.commonTags=n.commonTags,x.commonTagRecords=n.commonTagRecords,x.commonTagsUpdatedAt=n.commonTagsUpdatedAt,x.commonTagsDeviceId=n.commonTagsDeviceId}function Vo(e){let t=j(e.flatMap(e=>{if(!e)return[];let t=A(e.commonTags,50),n=String(e.commonTagsUpdatedAt||``),r=String(e.commonTagsDeviceId||``);return[...Array.isArray(e.commonTagRecords)?e.commonTagRecords:[],...ut(t,n,r)]})),n=t.reduce((e,t)=>e?Ao(t,e)>0?t:e:t,null);return{commonTags:dt(t),commonTagRecords:t,commonTagsUpdatedAt:n?.updatedAt||``,commonTagsDeviceId:n?.deviceId||``}}function Ho(e,t){let n=e.todos.data,r=e.records.data,i=e.inspirations.data,a=e.records.exists?[]:[n?.records,t?.data?.records],o=e.inspirations.exists?[]:[n?.inspirations,t?.data?.inspirations];return{items:[...n?.items||[],...t?.data?.items||[]],records:e.records.exists?r?.records||[]:a.flatMap(e=>Array.isArray(e)?e:[]),inspirations:e.inspirations.exists?i?.inspirations||[]:o.flatMap(e=>Array.isArray(e)?e:[]),...Vo([n,t?.data])}}async function Uo(){let e=To(),t=await Promise.all(e.map(e=>Eo(e,{cacheBust:!0}))),n=Object.fromEntries(e.map((e,n)=>[e.key,t[n]])),r={exists:!1,data:null,sha:``};return F.legacyPath&&(r=await Eo({key:`todos`,filename:F.legacyPath,path:F.legacyPath},{cacheBust:!0})),{files:n,legacyRemote:r}}function Wo(e,t){return t.exists?JSON.stringify(Lo(e,x))===JSON.stringify(Lo(e,t.data)):!1}function Go(e){return!!(e.exists&&e.data&&(Object.hasOwn(e.data,`records`)||Object.hasOwn(e.data,`inspirations`)))}async function Ko(e,t){let n=t,r=0;for(;r<4;)try{await ko(e,n.sha);return}catch(t){if(r+=1,r>=4)throw t;if(n=Do(t)?await Oo(e):await Eo(e,{cacheBust:!0}),Bo(e.key,n.data),$r(!0),Wo(e.key,n))return}}async function qo({manual:e=!1}={}){if(x.syncing)x.syncQueued=!0;else if(!F.repo||!F.token)e&&oa(),X(`local`,`仅保存在本机`);else if(!navigator.onLine)X(`error`,`当前离线,恢复网络后会自动同步`),e&&Z(`当前离线,修改已保存在本机`,null);else{x.syncing=!0,X(`syncing`,`正在同步`);try{let{files:t,legacyRemote:n}=await Uo();Ro(zo(Ho(t,n))),$r(!0);for(let e of To()){let n=t[e.key];kt({remoteExists:n.exists,force:e.key===`todos`&&Go(n),merged:Lo(e.key,x),remote:Lo(e.key,n.data)})&&await Ko(e,n)}x.dirty=!1,x.lastSyncedAt=T(),F.legacyPath&&Wt({...F,legacyPath:``}),$r(!1),X(`synced`,`已同步`),U(),e&&Z(`同步完成`,null)}catch(t){let n=t&&t.message?t.message:`同步失败,请稍后重试`,r=Do(t)?`远端同步文件发生并发冲突,请稍后重试`:/failed to fetch|networkerror|load failed/i.test(n)?`无法连接 Gitee,请检查网络与仓库权限`:n;$r(!0),X(`error`,r),e&&Z(r,null)}finally{x.syncing=!1,x.syncQueued&&(x.syncQueued=!1,Yo())}}}let Jo=null;function Yo(){F.repo&&F.token&&F.autoSync&&navigator.onLine&&(clearTimeout(Jo),Jo=setTimeout(()=>qo(),1200))}function Z(e,t){clearTimeout(x.toastTimer),clearTimeout(x.toastExitTimer),S.toastMessage.textContent=e,x.undo=t,S.toastAction.hidden=typeof t!=`function`,S.toast.hidden=!1,S.toast.classList.remove(`is-visible`,`is-leaving`),S.toast.offsetWidth,S.toast.classList.add(`is-visible`),x.toastTimer=setTimeout(Xo,t?6e3:3600)}function Xo(){S.toast.hidden||(clearTimeout(x.toastTimer),clearTimeout(x.toastExitTimer),S.toast.classList.remove(`is-visible`),S.toast.classList.add(`is-leaving`),x.toastExitTimer=setTimeout(()=>{S.toast.hidden=!0,S.toast.classList.remove(`is-leaving`),x.undo=null},280))}function Zo(e,t,n,r={}){S.confirmTitle.textContent=e,S.confirmMessage.textContent=t,S.confirmCancelButton.textContent=r.cancelLabel||`取消`,S.confirmAcceptButton.textContent=r.acceptLabel||`确认`,S.confirmCancelButton.className=r.cancelTone===`quiet`?`quiet-button`:`secondary-button`,S.confirmAcceptButton.className=r.acceptTone===`primary`?`primary-button`:`danger-button`,x.confirmCallback=n,x.confirmCancelCallback=r.onCancel||null,typeof S.confirmDialog.showModal==`function`?(S.confirmDialog.showModal(),requestAnimationFrame(()=>S.confirmCancelButton.focus())):S.confirmDialog.setAttribute(`open`,``)}function Qo(e){let t=e?x.confirmCallback:x.confirmCancelCallback;x.confirmCallback=null,x.confirmCancelCallback=null,S.confirmDialog.open?S.confirmDialog.close():S.confirmDialog.removeAttribute(`open`),S.confirmCancelButton.textContent=`取消`,S.confirmAcceptButton.textContent=`确认`,S.confirmCancelButton.className=`secondary-button`,S.confirmAcceptButton.className=`danger-button`,typeof t==`function`&&t()}function $o(){Qo(!1)}function es(){Qo(!0)}function ts(){x.deferredInstallPrompt?(x.deferredInstallPrompt.prompt(),x.deferredInstallPrompt.userChoice.finally(()=>{x.deferredInstallPrompt=null,ns()})):Z(/iphone|ipad|ipod/i.test(navigator.userAgent)?`在 Safari 分享菜单中选择“添加到主屏幕”`:`请使用浏览器菜单中的“安装应用”或“添加到主屏幕”`,null)}function ns(){let t=window.innerWidth<=760&&!e&&(!!x.deferredInstallPrompt||/iphone|ipad|ipod/i.test(navigator.userAgent));S.mobileInstallButton.hidden=!t}function rs(e){ji(()=>{z().find(t=>t.id===e)?(x.view=`all`,x.search=``,x.tagFilter=``,S.searchInput.value=``,S.mobileSearchInput.value=``,x.selectedId=e,N(),U(),Fi()):Z(`提醒对应的待办已被删除`,null)})}let is=``,as=0;function os(e){let t=``;try{let n=new URL(e);n.protocol===`com.jianji.todo:`&&n.hostname===`task`&&(t=decodeURIComponent(n.pathname.replace(/^\/+/,``)))}catch{}if(!t)return;let n=Date.now();t===is&&n-as<2500||(is=t,as=n,rs(t))}function ss(){e&&(ue.addListener(`appUrlOpen`,({url:e})=>{os(e)}).catch(()=>{}),ue.getLaunchUrl().then(e=>os(e&&e.url)).catch(()=>{}))}function cs(e){x.openMenuId=x.openMenuId===e?null:e,H(),x.openMenuId&&requestAnimationFrame(()=>{let t=document.querySelector(`.task-row[data-id="${CSS.escape(e)}"]`),n=t&&t.querySelector(`[data-action='toggle-row-menu']`);n&&n.focus(),ls(e)})}function ls(e){if(window.innerWidth<=760)return;let t=document.querySelector(`.task-row[data-id="${CSS.escape(e)}"]`),n=t?.querySelector(`[data-row-menu]`),r=t?.querySelector(`[data-action='toggle-row-menu']`);if(n&&!n.hidden&&r&&typeof n.showPopover==`function`)try{n.style.visibility=`hidden`,n.matches(`:popover-open`)||n.showPopover();let e=r.getBoundingClientRect(),t=n.offsetWidth,i=n.offsetHeight,a=e.right-t,o=e.bottom+5;if(a=Math.max(8,Math.min(a,window.innerWidth-t-8)),o+i>window.innerHeight-8){let t=e.top-i-5;o=t>=8?t:Math.max(8,window.innerHeight-i-8)}n.style.left=`${Math.round(a)}px`,n.style.top=`${Math.round(o)}px`,n.style.visibility=``}catch{n.style.visibility=``,n.removeAttribute(`popover`)}}let us=0;function ds(){x.openMenuId&&!us&&(us=requestAnimationFrame(()=>{us=0,x.openMenuId&&ls(x.openMenuId)}))}S.taskScroll.addEventListener(`scroll`,ds,{capture:!0,passive:!0}),window.addEventListener(`resize`,ds,{passive:!0});function fs(e,t){requestAnimationFrame(()=>{let n=document.querySelector(`.task-row[data-id="${CSS.escape(e)}"]`),r=n?n.querySelector(t):null;r?r.focus():window.innerWidth<=760?S.mobileCreateButton.focus():S.desktopCreateButton.focus()})}document.querySelectorAll(`[data-view]`).forEach(e=>{e.addEventListener(`click`,()=>Oi(e.dataset.view))}),S.statusFilter.addEventListener(`click`,e=>{let t=e.target.closest(`[data-filter-view]`);t&&ki(t.dataset.filterView)}),S.tagFilter.addEventListener(`click`,e=>{let t=e.target.closest(`[data-tag-filter]`);t&&vr(t.dataset.tagFilter||``)});let Q=null,ps=null,ms=null,hs=0,gs=window.matchMedia(`(prefers-reduced-motion: reduce)`);function _s(e){let t=Nt(e,x.openMenuId),n=(t?.closest(`.task-row`))?.dataset.id||``,r=t?.dataset.status||``;return!n||!v[r]?!1:(hs=Date.now()+380,x.openMenuId=null,H(),hi(n,r),!0)}S.taskGroups.addEventListener(`pointerdown`,e=>{if(ms=null,e.pointerType!==`touch`||e.isPrimary===!1)return;let t=Pt(e.target,x.openMenuId);t&&(ms={...t,pointerId:e.pointerId,startX:e.clientX,startY:e.clientY})},{passive:!0}),S.taskGroups.addEventListener(`pointerup`,e=>{let t=ms;if(ms=null,!(!Ft(t,e)||Q?.active||Q?.vertical)){if(t.kind===`status`){let n=Nt(e.target,x.openMenuId);if(n!==t.button||!_s(n))return}else if(t.kind===`select`)hs=Date.now()+380,Ai(t.taskId);else return;e.preventDefault(),e.stopPropagation()}},{passive:!1}),S.taskGroups.addEventListener(`pointercancel`,()=>{ms=null},{passive:!0});function vs(e){let t=_e.indexOf(x.view);if(t<0)return{direction:``,view:``};let n=e<0?`next`:`prev`,r=n===`next`?t+1:t-1;return{direction:n,view:_e[r]||``}}function ys(){clearTimeout(ps),S.taskGroups.classList.remove(`is-swiping`);let e=gs.matches?0:320;S.taskGroups.style.transition=`transform ${e}ms cubic-bezier(.22,.85,.24,1), opacity ${Math.min(160,e)}ms ease-out`,S.taskGroups.style.transform=`translate3d(0, 0, 0) scale(1)`,S.taskGroups.style.opacity=`1`,ps=setTimeout(()=>{S.taskGroups.style.transition=``,S.taskGroups.style.transform=``,S.taskGroups.style.opacity=``},e+20)}function bs(e,t){clearTimeout(ps),S.taskGroups.classList.remove(`is-swiping`);let n=gs.matches?0:180,r=gs.matches?0:Math.max(120,n-40),i=Math.min(150,window.innerWidth*.36),a=t===`next`?-1:1;S.taskGroups.style.transition=`transform ${n}ms cubic-bezier(.4,0,.8,.2), opacity ${r}ms ease-in`,S.taskGroups.style.transform=`translate3d(${a*i}px, 0, 0) scale(.99)`,S.taskGroups.style.opacity=`0`,ps=setTimeout(()=>{S.taskGroups.style.transition=``,S.taskGroups.style.transform=``,S.taskGroups.style.opacity=``,Oi(e,t)},n+10)}function xs(){clearTimeout(ps),S.taskGroups.classList.remove(`is-swiping`),S.taskGroups.style.transition=``,S.taskGroups.style.transform=``,S.taskGroups.style.opacity=``}S.taskScroll.addEventListener(`touchstart`,e=>{e.touches.length===1?e.target.closest(`[data-drag-handle],.row-menu-wrap,.tag-filter-wrap`)?Q=null:(xs(),Q={x:e.touches[0].clientX,y:e.touches[0].clientY,startedAt:Date.now(),active:!1,vertical:!1,offset:0}):Q=null},{passive:!0}),S.taskScroll.addEventListener(`touchmove`,e=>{if(!Q||Q.vertical||e.touches.length!==1)return;let t=e.touches[0].clientX-Q.x,n=e.touches[0].clientY-Q.y;if(!Q.active){if(Math.abs(t)<8&&Math.abs(n)<8)return;if(Math.abs(n)>Math.abs(t)*1.12){Q.vertical=!0;return}Q.active=!0,S.taskGroups.classList.add(`is-swiping`)}e.preventDefault();let r=vs(t).view?.92:.14,i=Math.min(132,window.innerWidth*.34),a=Math.max(-i,Math.min(i,t*r));Q.offset=a;let o=Math.min(1,Math.abs(a)/i);S.taskGroups.style.transform=`translate3d(${a}px, 0, 0) scale(${1-o*.006})`,S.taskGroups.style.opacity=String(1-o*.06)},{passive:!1}),S.taskScroll.addEventListener(`touchend`,e=>{let t=Q;if(Q=null,!t||!t.active||e.changedTouches.length!==1){ys();return}let n=e.changedTouches[0].clientX-t.x,r=Date.now()-t.startedAt,i=Math.min(82,Math.max(54,window.innerWidth*.16)),a=vs(n),o=!!a.view&&(Math.abs(n)>=i||r<320&&Math.abs(n)>=34);hs=Date.now()+380,o?bs(a.view,a.direction):ys()},{passive:!1}),S.taskScroll.addEventListener(`touchcancel`,()=>{Q=null,ys()}),S.searchInput.addEventListener(`input`,()=>{x.search=S.searchInput.value,S.mobileSearchInput.value=x.search,H(),Y()}),S.searchInput.addEventListener(`keydown`,e=>{e.key===`Escape`&&(S.searchInput.value=``,S.mobileSearchInput.value=``,x.search=``,S.searchBox.classList.remove(`is-open`),H(),Y(),S.desktopCreateButton.focus())}),S.mobileSearchButton.addEventListener(`click`,()=>{S.mobileSearchPanel.hidden?ia():aa()}),S.mobileSearchClose.addEventListener(`click`,()=>aa()),S.mobileSearchInput.addEventListener(`input`,()=>{x.search=S.mobileSearchInput.value,S.searchInput.value=x.search,H(),Y()}),S.mobileSearchInput.addEventListener(`keydown`,e=>{e.key===`Escape`&&aa()}),S.mobileCreateButton.addEventListener(`click`,Bi),S.mobileRecordButton.addEventListener(`click`,()=>Wi()),S.mobileInspirationButton.addEventListener(`click`,()=>Zi()),S.desktopCreateButton.addEventListener(`click`,ra),[S.createCloseButton,S.createCancelButton].forEach(e=>{e.addEventListener(`click`,Vi)}),S.createTaskForm.addEventListener(`submit`,e=>{e.preventDefault(),Hi()}),S.createSaveButton.addEventListener(`click`,Hi),S.createTagList.addEventListener(`click`,e=>{js(e)}),S.createTagList.addEventListener(`keydown`,e=>{Ms(e)}),[S.createTitleInput,S.createBodyInput].forEach(e=>{e.addEventListener(`input`,()=>{S.createTaskError.hidden=!0})}),S.createDialog.addEventListener(`cancel`,e=>{e.preventDefault(),Vi()}),document.addEventListener(`click`,e=>{let t=e.target.closest(`[data-image-scan]`);t&&(e.preventDefault(),t.closest(`.image-import-row`)?.querySelector(`[data-image-input]`)?.click())}),document.addEventListener(`change`,e=>{let t=e.target.closest(`[data-image-input]`);t&&pi(t.dataset.imageInput,t.files?.[0])}),[S.recordCloseButton,S.recordCancelButton].forEach(e=>{e.addEventListener(`click`,Gi)}),S.recordForm.addEventListener(`submit`,e=>{e.preventDefault(),qi()}),S.recordSaveButton.addEventListener(`click`,qi),S.recordDeleteButton.addEventListener(`click`,Yi),[S.recordTitleInput,S.recordBodyInput].forEach(e=>{e.addEventListener(`input`,()=>Ui())}),S.recordDialog.addEventListener(`cancel`,e=>{e.preventDefault(),Gi()}),[S.inspirationCloseButton,S.inspirationCancelButton].forEach(e=>{e.addEventListener(`click`,Qi)}),S.inspirationForm.addEventListener(`submit`,e=>{e.preventDefault(),ea()}),S.inspirationSaveButton.addEventListener(`click`,ea),S.inspirationDeleteButton.addEventListener(`click`,na),[S.inspirationTopicInput,S.inspirationBodyInput].forEach(e=>{e.addEventListener(`input`,()=>Xi())}),S.inspirationDialog.addEventListener(`cancel`,e=>{e.preventDefault(),Qi()}),S.sortSelect.addEventListener(`change`,()=>{x.sort=qt(S.sortSelect),N(),H()}),document.addEventListener(`click`,e=>{let t=e.target.closest(`[data-picker-type]`);t&&!t.disabled&&(e.preventDefault(),nn(t))}),document.addEventListener(`keydown`,e=>{let t=e.target.closest(`[data-picker-type]`);t&&[`ArrowDown`,`ArrowUp`].includes(e.key)&&(e.preventDefault(),nn(t))}),S.appPickerClose.addEventListener(`click`,rn),S.appPicker.addEventListener(`cancel`,e=>{e.preventDefault(),rn()}),S.appPicker.addEventListener(`close`,()=>{let e=_?.trigger;e&&e.setAttribute(`aria-expanded`,`false`),_=null,requestAnimationFrame(()=>{e?.isConnected&&e.focus()})}),S.appPicker.addEventListener(`click`,e=>{if(e.target===S.appPicker){rn();return}let t=e.target.closest(`[data-picker-month]`);if(t){on(Number(t.dataset.pickerMonth));return}let n=e.target.closest(`[data-picker-value]`);if(n){an(n.dataset.pickerValue);return}if(e.target.closest(`[data-picker-clear]`)){an(``);return}let r=e.target.closest(`[data-picker-date]`);r&&an(r.dataset.pickerDate)}),S.appPicker.addEventListener(`keydown`,e=>{let t=[...S.appPickerBody.querySelectorAll(`[data-picker-value]`)];if(t.length&&[`ArrowDown`,`ArrowUp`,`Home`,`End`].includes(e.key)){e.preventDefault();let n=Math.max(0,t.indexOf(document.activeElement)),r=n;e.key===`ArrowDown`&&(r=Math.min(t.length-1,n+1)),e.key===`ArrowUp`&&(r=Math.max(0,n-1)),e.key===`Home`&&(r=0),e.key===`End`&&(r=t.length-1),t[r].focus();return}let n=e.target.closest(`[data-picker-date]`);if(!n||![`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`].includes(e.key))return;e.preventDefault();let r=e.key===`ArrowLeft`?-1:e.key===`ArrowRight`?1:e.key===`ArrowUp`?-7:7,i=En(D(n.dataset.pickerDate),r);S.appPickerBody.querySelector(`[data-picker-date="${E(i)}"]`)?.focus()}),S.layoutToggle.addEventListener(`click`,()=>{x.mobileLayout=x.mobileLayout===`cards`?`list`:`cards`,N(),H()}),S.taskGroups.addEventListener(`click`,e=>{if(Date.now()<hs){e.preventDefault(),e.stopImmediatePropagation();return}if(e.target.closest(`[data-action='toggle-done-group']`)){x.mobileDoneExpanded=!x.mobileDoneExpanded,x.openMenuId=null,H(),requestAnimationFrame(()=>{document.querySelector(`[data-action='toggle-done-group']`)?.focus()});return}let t=e.target.closest(`[data-action='create-inspiration'],[data-action='add-inspiration'],[data-action='open-inspiration']`);if(t){let e=t.dataset.action;e===`create-inspiration`&&Zi(),e===`add-inspiration`&&Zi({topic:t.dataset.topic||``}),e===`open-inspiration`&&Zi({id:t.dataset.inspirationId||``});return}let n=e.target.closest(`[data-action='open-record'],[data-action='create-record']`);if(n){n.dataset.action===`create-record`?Wi():Wi(n.dataset.recordId);return}let r=e.target.closest(`[data-action='toggle-lane-mosaic']`);if(r){let e=r.dataset.status;x.mosaicLanes.has(e)?x.mosaicLanes.delete(e):x.mosaicLanes.add(e),N(),H(),requestAnimationFrame(()=>{document.querySelector(`[data-action="toggle-lane-mosaic"][data-status="${e}"]`)?.focus()});return}let i=e.target.closest(`.task-row`);if(!i)return;let a=i.dataset.id,o=e.target.closest(`[data-action]`);if(o){let e=o.dataset.action;e===`select-task`&&Ai(a),e===`toggle-row-menu`&&cs(a);return}let s=e.target.closest(`[data-menu-action]`);if(s){let t=s.dataset.menuAction;if(e.preventDefault(),e.stopPropagation(),t===`dispatch`){x.openMenuId=null,H(),_i(a);return}if(t===`status`){_s(s);return}t===`toggle-pin`&&Ci(a),t===`delete`&&wi(a),x.openMenuId=null,H(),fs(a,`[data-action='toggle-row-menu']`)}});let $={id:``,pointerId:null,captureTarget:null,sourceRow:null,ghost:null,startX:0,startY:0,offsetX:0,offsetY:0,active:!1,targetId:``,targetStatus:``};function Ss(){document.querySelectorAll(`.is-drop-target,.is-lane-drop`).forEach(e=>{e.classList.remove(`is-drop-target`,`is-lane-drop`)}),$.targetId=``,$.targetStatus=``}function Cs(e){if(!$.ghost)return;let t=e.clientX-$.offsetX,n=e.clientY-$.offsetY;$.ghost.style.transform=`translate3d(${t}px, ${n}px, 0)`}function ws(e){if($.active||!$.sourceRow)return;let t=$.sourceRow.getBoundingClientRect(),n=document.createElement(`div`),r=$.sourceRow.cloneNode(!0);n.className=`task-drag-ghost board-list`,n.style.width=`${t.width}px`,n.setAttribute(`aria-hidden`,`true`),n.inert=!0,r.classList.add(`task-drag-ghost-card`),r.classList.remove(`is-selected`),r.removeAttribute(`data-id`),r.querySelectorAll(`[id]`).forEach(e=>e.removeAttribute(`id`)),n.append(r),document.body.append(n),$.ghost=n,$.active=!0,$.sourceRow.classList.add(`is-drag-origin`),document.body.classList.add(`is-task-dragging`),$.sourceRow.hasPointerCapture($.pointerId)||$.sourceRow.setPointerCapture($.pointerId),Cs(e)}function Ts(e,t){let n=document.elementFromPoint(e,t),r=n?n.closest(`.board-lane`):null,i=n?n.closest(`.task-row`):null;Ss(),r&&r.querySelector(`[data-lane-drop]`)&&(r.classList.add(`is-lane-drop`),$.targetStatus=r.dataset.laneStatus||``,i&&i!==$.sourceRow&&i.closest(`.board-lane`)===r&&(i.classList.add(`is-drop-target`),$.targetId=i.dataset.id||``))}function Es(e){requestAnimationFrame(()=>{let t=document.querySelector(`.task-row[data-id="${CSS.escape(e)}"]`);if(!t)return;let n=t.closest(`.board-lane`);t.classList.add(`is-jelly-landing`),n?.classList.add(`is-jelly-landing`),setTimeout(()=>{t.classList.remove(`is-jelly-landing`),n?.classList.remove(`is-jelly-landing`)},760)})}function Ds({animateReturn:e=!1}={}){let t=$.sourceRow;$.captureTarget?.hasPointerCapture?.($.pointerId)&&$.captureTarget.releasePointerCapture($.pointerId),Ss(),$.ghost?.remove(),t?.classList.remove(`is-drag-origin`),document.body.classList.remove(`is-task-dragging`),e&&t?.isConnected&&(t.classList.add(`is-jelly-return`),setTimeout(()=>t.classList.remove(`is-jelly-return`),460)),$.id=``,$.pointerId=null,$.captureTarget=null,$.sourceRow=null,$.ghost=null,$.active=!1,$.targetId=``,$.targetStatus=``}function Os(e=!1){let t=$.id,n=$.targetId,r=$.targetStatus,i=$.active;Ds({animateReturn:!e&&i&&!n&&!r}),!e&&i&&(hs=Date.now()+380),!e&&i&&t&&(n?Ei(t,n):r&&Di(t,r),Es(t))}function ks(e){if(!$.id)return;let t=Math.hypot(e.clientX-$.startX,e.clientY-$.startY);if(!$.active&&t<5)return;e.preventDefault(),ws(e),Cs(e);let n=document.elementFromPoint(e.clientX,e.clientY)?.closest(`.board-lane-body`)||$.sourceRow?.closest(`.board-lane-body`),r=n?.getBoundingClientRect();r&&e.clientY<r.top+56&&n.scrollBy({top:-14}),r&&e.clientY>r.bottom-56&&n.scrollBy({top:14}),Ts(e.clientX,e.clientY)}S.taskGroups.addEventListener(`pointerdown`,e=>{if(e.pointerType!==`touch`){let t=e.target.closest(`.task-row`);if(e.isPrimary===!1||e.button!==0||window.innerWidth<=760||!t?.closest(`.board-lane`))return;let n=t.getBoundingClientRect();$.id=t.dataset.id,$.pointerId=e.pointerId,$.captureTarget=t,$.sourceRow=t,$.startX=e.clientX,$.startY=e.clientY,$.offsetX=e.clientX-n.left,$.offsetY=e.clientY-n.top;return}let t=e.target.closest(`[data-drag-handle]`),n=t?t.closest(`.task-row`):null;n&&!t.disabled&&(e.preventDefault(),x.pointerDragId=n.dataset.id,x.pointerDropId=null,n.classList.add(`is-pointer-dragging`),t.setPointerCapture(e.pointerId))}),window.addEventListener(`pointermove`,e=>{if($.id){ks(e);return}if(!x.pointerDragId)return;e.preventDefault();let t=S.taskScroll.getBoundingClientRect();e.clientY<t.top+56&&S.taskScroll.scrollBy({top:-14}),e.clientY>t.bottom-56&&S.taskScroll.scrollBy({top:14});let n=document.elementFromPoint(e.clientX,e.clientY),r=z().find(e=>e.id===x.pointerDragId),i=n?n.closest(`.task-row`):null,a=i?z().find(e=>e.id===i.dataset.id):null;document.querySelectorAll(`.is-drop-target`).forEach(e=>e.classList.remove(`is-drop-target`)),x.pointerDropId=null,a&&r&&a.id!==r.id&&a.status===r.status&&(i.classList.add(`is-drop-target`),x.pointerDropId=a.id)});function As(){document.querySelectorAll(`.is-pointer-dragging,.is-drop-target`).forEach(e=>{e.classList.remove(`is-pointer-dragging`,`is-drop-target`)}),x.pointerDragId=null,x.pointerDropId=null}window.addEventListener(`pointerup`,e=>{if($.id){Os(e.type===`pointercancel`);return}let t=x.pointerDragId,n=x.pointerDropId;As(),t&&n&&Ei(t,n)}),window.addEventListener(`pointercancel`,()=>{$.id?Os(!0):As()}),window.addEventListener(`blur`,()=>{$.id&&Os(!0)});function js(e){let t=e.target.closest(`[data-tag-action]`);if(t){let e=t.dataset.tagContext===`detail`?`detail`:`create`;if(t.dataset.tagAction===`show-entry`)Ur(e);else if(t.dataset.tagAction===`add-entry`){let t=Br(e)?.querySelector(`[data-tag-entry-row] input`);Wr(e,t?t.value:``)}return!0}let n=e.target.closest(`[data-toggle-editor-tag]`);if(n)return Gr(n.dataset.tagContext===`detail`?`detail`:`create`,n.dataset.toggleEditorTag),!0;let r=e.target.closest(`[data-remove-editor-tag]`);return r?(Kr(r.dataset.tagContext===`detail`?`detail`:`create`,r.dataset.removeEditorTag),!0):!1}function Ms(e){let t=e.target.id===`detailTagEntry`,n=e.target.id===`createTagEntry`;if(!t&&!n)return;let r=t?`detail`:`create`;if(e.key===`Enter`||e.key===`,`){e.preventDefault(),Wr(r,e.target.value);return}let i=Vr(r);e.key===`Backspace`&&!e.target.value&&i.length&&(e.preventDefault(),Kr(r,i[i.length-1]))}if(S.inspectorContent.addEventListener(`click`,e=>{if(js(e))return;let t=e.target.closest(`[data-detail-action]`);t&&(t.dataset.detailAction===`save`&&Qr()&&Li(),t.dataset.detailAction===`delete`&&x.selectedId&&Zo(`删除这条待办`,`删除会同步到已连接的仓库,可在提示消失前撤销。`,()=>wi(x.selectedId)),t.dataset.detailAction===`dispatch`&&x.selectedId&&_i(x.selectedId),t.dataset.detailAction===`open-dsh`&&Si(fn()))}),S.inspectorContent.addEventListener(`submit`,e=>{e.preventDefault()}),S.inspectorContent.addEventListener(`input`,e=>{if(e.target.id===`detailTagEntry`){Xr();return}let t=e.target.dataset.draftField;t&&Zr(t,e.target.value)}),S.inspectorContent.addEventListener(`change`,e=>{let t=e.target.dataset.draftField;t&&Zr(t,e.target.dataset.value??e.target.value)}),S.inspectorContent.addEventListener(`keydown`,e=>{Ms(e)}),[S.syncButton,S.mobileSyncButton].forEach(e=>{e.addEventListener(`click`,()=>qo({manual:!0}))}),S.heatmapButton.addEventListener(`click`,()=>ir(`overview`)),S.settingsButton.addEventListener(`click`,oa),S.mobileSettingsButton.addEventListener(`click`,()=>{cr(!1),oa()}),S.mobileMenuButton.addEventListener(`click`,sr),S.recordDrawerCloseButton.addEventListener(`click`,()=>cr()),S.recordDrawer.addEventListener(`click`,e=>{e.target===S.recordDrawer&&cr()}),S.recordDrawer.addEventListener(`cancel`,e=>{e.preventDefault(),cr()}),S.drawerHeatmapHelpButton.addEventListener(`click`,lr),S.drawerStatsButton.addEventListener(`click`,()=>ir(`overview`)),S.closeHeatmapHelpButton.addEventListener(`click`,ur),S.heatmapLearnMoreButton.addEventListener(`click`,()=>ir(`overview`)),S.heatmapHelpDialog.addEventListener(`cancel`,e=>{e.preventDefault(),ur()}),S.statsBackButton.addEventListener(`click`,or),S.statsCloseButton.addEventListener(`click`,ar),S.statsPage.addEventListener(`cancel`,e=>{e.preventDefault(),or()}),S.statsPageContent.addEventListener(`click`,e=>{if(e.target.closest(`[data-stats-action='all-records']`)){x.statsView=`year`,x.statsYear=new Date().getFullYear(),x.statsSelectedDate=``,nr({resetScroll:!0}),S.statsBackButton.focus();return}let t=e.target.closest(`[data-stats-year-step]`);t&&!t.disabled&&(x.statsYear+=Number(t.dataset.statsYearStep),nr({resetScroll:!0}),S.statsBackButton.focus())}),S.remindersEnabledInput?.addEventListener(`change`,ma),S.updateTokenInput.addEventListener(`change`,()=>{Ut({token:S.updateTokenInput.value}),K(I.token?`GitHub 只读令牌已保存`:`GitHub 只读令牌已清除`)}),S.checkUpdateButton.addEventListener(`click`,fo),S.toggleUpdateHistoryButton.addEventListener(`click`,()=>{Pa(!x.updateHistoryOpen)}),S.updateHistoryList.addEventListener(`click`,so),[S.closeUpdateButton,S.laterUpdateButton].forEach(e=>{e.addEventListener(`click`,()=>lo())}),S.installUpdateButton.addEventListener(`click`,ao),S.updateDownloadAction.addEventListener(`click`,oo),S.updateUninstallAction.addEventListener(`click`,ro),S.updateNoticeAction.addEventListener(`click`,eo),S.updateNoticeClose.addEventListener(`click`,Ka),S.settingsForm.addEventListener(`submit`,e=>{e.preventDefault()}),S.addCommonTagButton.addEventListener(`click`,wr),S.commonTagInput.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),wr())}),S.commonTagSettingsList.addEventListener(`click`,e=>{let t=e.target.closest(`[data-remove-common-tag]`);t&&Cr(t.dataset.removeCommonTag)}),S.saveDeepseekButton.addEventListener(`click`,ca),S.testDeepseekButton.addEventListener(`click`,()=>{la()}),S.deepseekKeyInput.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),ca())}),[S.closeSettingsButton,S.cancelSettingsButton].forEach(e=>{e.addEventListener(`click`,ha)}),S.settingsPage.addEventListener(`cancel`,e=>{e.preventDefault(),ha()}),S.saveSettingsButton.addEventListener(`click`,_o),S.disconnectButton.addEventListener(`click`,yo),S.mobileInstallButton.addEventListener(`click`,ts),S.inspectorClose.addEventListener(`click`,Ii),S.aboutButton.addEventListener(`click`,da),[S.closeAboutIconButton,S.closeAboutButton].forEach(e=>{e.addEventListener(`click`,fa)}),S.aboutDialog.addEventListener(`cancel`,e=>{e.preventDefault(),fa()}),S.inspector.addEventListener(`cancel`,e=>{e.preventDefault(),Ii()}),S.continueEditingButton.addEventListener(`click`,()=>{x.draftAfter=null,Mi()}),S.discardDraftButton.addEventListener(`click`,Ni),S.saveAndLeaveButton.addEventListener(`click`,Pi),S.savePromptDialog.addEventListener(`cancel`,()=>{x.draftAfter=null}),S.dispatchCloseButton.addEventListener(`click`,vi),S.dispatchCancelButton.addEventListener(`click`,vi),S.dispatchConfirmButton.addEventListener(`click`,yi),S.dispatchDialog.addEventListener(`cancel`,e=>{e.preventDefault(),vi()}),window.addEventListener(`message`,xi),S.toastAction.addEventListener(`click`,()=>{let e=x.undo;x.undo=null,Xo(),typeof e==`function`&&e()}),S.confirmCancelButton.addEventListener(`click`,$o),S.confirmAcceptButton.addEventListener(`click`,es),S.confirmDialog.addEventListener(`cancel`,e=>{e.preventDefault(),$o()}),S.searchBox.addEventListener(`click`,()=>{window.innerWidth<=760&&!S.searchBox.classList.contains(`is-open`)&&(S.searchBox.classList.add(`is-open`),requestAnimationFrame(()=>S.searchInput.focus()))}),document.addEventListener(`click`,e=>{let t=e.target.closest(`.heatmap-cell[data-heatmap-date]`);t?.closest(`#statsPage`)?Qn(t):t?Hn(t):e.target.closest(`.heatmap-tooltip`)||Vn(),x.openMenuId&&!e.target.closest(`.row-menu-wrap`)&&(x.openMenuId=null,H())}),document.addEventListener(`keydown`,e=>{if(S.updateDialog.open||S.confirmDialog.open||S.dispatchDialog.open||S.savePromptDialog.open||S.inspector.open||S.createDialog.open||S.recordDialog.open||S.inspirationDialog.open||S.recordDrawer.open||S.heatmapHelpDialog.open||S.aboutDialog.open||S.statsPage.open||S.settingsPage.open)return;if(x.statsOpen){e.key===`Escape`&&(e.preventDefault(),or());return}if(x.settingsOpen){e.key===`Escape`&&(e.preventDefault(),ha());return}let t=/input|textarea|select/i.test(document.activeElement.tagName);if(e.key===`/`&&!t&&(e.preventDefault(),window.innerWidth<=760?ia():(S.searchBox.classList.add(`is-open`),S.searchInput.focus())),e.key!==`n`&&e.key!==`N`||t||e.metaKey||e.ctrlKey||e.altKey||(e.preventDefault(),ra()),(e.key===`x`||e.key===`X`)&&!t&&x.selectedId&&(e.preventDefault(),gi(x.selectedId)),e.key===`Escape`){if(!S.mobileSearchPanel.hidden){aa();return}x.openMenuId&&(x.openMenuId=null,H()),Ii()}!t&&x.selectedId&&e.altKey&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&(e.preventDefault(),Ti(x.selectedId,e.key===`ArrowUp`?-1:1))}),window.addEventListener(`online`,()=>{X(F.repo?`synced`:`local`,F.repo?`网络已恢复`:`仅保存在本机`),Yo(),Za({announce:!1})}),window.addEventListener(`offline`,()=>{X(`error`,`当前离线,修改待同步`)}),window.addEventListener(`hashchange`,va),_a(),window.addEventListener(`beforeunload`,e=>{Yr()&&(e.preventDefault(),e.returnValue=``)}),document.addEventListener(`visibilitychange`,()=>{document.hidden||(De(x.items).catch(()=>{}),it(x.items).catch(()=>{}),x.dirty&&Yo(),Za({announce:!0}))}),window.addEventListener(`beforeinstallprompt`,e=>{window.innerWidth>760||(e.preventDefault(),x.deferredInstallPrompt=e,ns())}),window.addEventListener(`appinstalled`,()=>{x.deferredInstallPrompt=null,ns(),Z(`简记已安装到设备`,null)}),window.addEventListener(`resize`,()=>{let e=yn()&&window.innerWidth>760;!e&&!_e.includes(x.view)&&(x.view=`records`,N(),U()),S.taskGroups.classList.contains(`is-board`)===e?x.mobileLayout===`cards`&&!e&&Lr():H(),window.innerWidth>760&&S.searchBox.classList.remove(`is-open`),S.appPicker.open&&tn()}),t)try{await Ye()}catch(e){console.warn(`连接 DSH 简记存储失败,将先使用本机数据`,e)}ht(),se=!0,at(x.items),Jt(S.sortSelect,x.sort),Yt(S.createStatusInput),Yt(S.createDueInput),Yt(S.createEmphasisInput),Tn(),ke(rs),U(),ss(),va(),ns(),$e(),t&&ce===0&&Qe(!0),t||uo().finally(()=>{setTimeout(()=>po({manual:!1,prompt:`notice`}),1200)}),!e&&!t&&`serviceWorker`in navigator&&location.protocol!==`file:`&&window.addEventListener(`load`,()=>navigator.serviceWorker.register(`./sw.js`).catch(()=>{})),F.repo&&F.token&&(X(`synced`,`等待同步`),setTimeout(()=>qo(),400))})();export{o as t};
|