Compare commits
11
Commits
v0.0.9
...
98c4b6a96f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98c4b6a96f | ||
|
|
1cc35f147d | ||
|
|
199b6c177f | ||
|
|
63b1a75b03 | ||
|
|
d993dd3d4b | ||
|
|
b7bc4b5403 | ||
|
|
96335728f5 | ||
|
|
a32c049199 | ||
|
|
6ab7bcfb76 | ||
|
|
8e0c08ccfb | ||
|
|
8be539d8a3 |
+2
-2
@@ -2,8 +2,8 @@
|
|||||||
"app": {
|
"app": {
|
||||||
"bundleName": "synccalendar.yangyq.net",
|
"bundleName": "synccalendar.yangyq.net",
|
||||||
"vendor": "yangyq",
|
"vendor": "yangyq",
|
||||||
"versionCode": 900,
|
"versionCode": 10000,
|
||||||
"versionName": "0.0.9",
|
"versionName": "0.1.0",
|
||||||
"buildVersion": "1",
|
"buildVersion": "1",
|
||||||
"icon": "$media:layered_image",
|
"icon": "$media:layered_image",
|
||||||
"label": "$string:app_name"
|
"label": "$string:app_name"
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
一款以**同步为核心**的鸿蒙原生日历应用,基于 HarmonyOS NEXT(ArkTS / Stage 模型)开发。对接标准 CalDAV 服务器(群晖、Nextcloud、Radicale、Baikal 等),让你的日程真正掌握在自己手里——不经过第三方云服务,数据始终同步在你自己的 NAS 上。
|
一款以**同步为核心**的鸿蒙原生日历应用,基于 HarmonyOS NEXT(ArkTS / Stage 模型)开发。对接标准 CalDAV 服务器(群晖、Nextcloud、Radicale、Baikal 等),让你的日程真正掌握在自己手里——不经过第三方云服务,数据始终同步在你自己的 NAS 上。
|
||||||
|
|
||||||
- 应用市场送审版本:**0.0.6** | 仓库当前:**0.0.6**(versionCode 600)
|
- 应用市场送审版本:**0.1.0** | 仓库当前:**0.1.0**(versionCode 10000)
|
||||||
- 官网:<https://synccalendar.yangyq.net> | 问题反馈:<https://synccalendar.yangyq.net/feedback/>
|
- 官网:<https://synccalendar.yangyq.net> | 问题反馈:<https://synccalendar.yangyq.net/feedback/>
|
||||||
- 开源协议:Apache License 2.0
|
- 开源协议:Apache License 2.0
|
||||||
|
|
||||||
@@ -32,10 +32,19 @@
|
|||||||
### 日程编辑与提醒
|
### 日程编辑与提醒
|
||||||
|
|
||||||
- 新建 / 编辑 / 删除日程并推送回服务器,支持全天日程、地点、描述、重复规则、多级提前提醒
|
- 新建 / 编辑 / 删除日程并推送回服务器,支持全天日程、地点、描述、重复规则、多级提前提醒
|
||||||
|
- **地点搜索补全**:在「地点」栏输入关键词即可列出匹配地点(华为 Map Kit / Site Kit),点一下填入完整地址;也可点「地图」进入系统地图界面搜索、拖动图钉选点。**不申请任何定位权限**,手动输入同样可用
|
||||||
|
- **一键导航**:日程详情中点击「导航 ›」,用系统地理编码把地点地址换算为坐标后唤起高德地图;未安装则回退网页版。**不申请定位权限**(`getAddressesFromLocationName` 无需该权限),不会读取设备实时位置
|
||||||
|
- **必填项校验强提醒**:未填标题等必填项时,以 Toast + 输入框标红 + 自动滚回定位三管齐下提示,不会出现"提示在屏幕外看不到"的情况
|
||||||
- 自动读取服务器端 **VALARM** 提醒(如"开始前 10 分钟")
|
- 自动读取服务器端 **VALARM** 提醒(如"开始前 10 分钟")
|
||||||
- 基于**系统级代理提醒**(`reminderAgentManager`)发送通知,App 被杀、手机重启后依然生效,通知可右滑删除
|
- 基于**系统级代理提醒**(`reminderAgentManager`)发送通知,App 被杀、手机重启后依然生效,通知可右滑删除
|
||||||
- 保存带提醒的日程时会**在那一刻**申请通知权限;被拒绝也不影响日程保存,之后可在设置页再开启
|
- 保存带提醒的日程时会**在那一刻**申请通知权限;被拒绝也不影响日程保存,之后可在设置页再开启
|
||||||
|
|
||||||
|
### CalDAV 地址自动发现
|
||||||
|
|
||||||
|
- 只填服务器域名也能用:按标准 **`/.well-known/caldav`** 自动发现端点,并在常见路径(Nextcloud、群晖等)中依次尝试
|
||||||
|
- 发现时只认 `resourcetype` 含 `calendar` 的集合,避免把 DAV 根或分享链接误当成日历
|
||||||
|
- 失败时给出**人话错误提示**(如"正确形式通常为 `https://域名/remote.php/dav/calendars/用户名/`"),而不是抛原始状态码
|
||||||
|
|
||||||
### 系统日历镜像(可选增强,默认关闭)
|
### 系统日历镜像(可选增强,默认关闭)
|
||||||
|
|
||||||
镜像是**可选项**,App 本体不依赖它也能完整使用。开启后:
|
镜像是**可选项**,App 本体不依赖它也能完整使用。开启后:
|
||||||
@@ -81,10 +90,12 @@
|
|||||||
|
|
||||||
我们遵循"**数据自持、最小必要**"原则:
|
我们遵循"**数据自持、最小必要**"原则:
|
||||||
|
|
||||||
- 开发者**不保存**你的日程与账号数据(账号密码只存在本机)
|
- 开发者**不保存**你的日程与账号数据(账号密码只存在本机,且以 **AES-256-GCM** 加密存储,密钥由系统 HUKS/TEE 保管、不可导出)
|
||||||
- **不收集**通讯录、相册、剪贴板等信息,**不含**任何第三方统计或广告 SDK
|
- **不收集**通讯录、相册、剪贴板等信息,**不含**任何第三方统计或广告 SDK
|
||||||
- 页面从不展示他人邮箱;日志对日程标题、地点等敏感字段做**脱敏**处理
|
- 页面从不展示他人邮箱;日志对日程标题、地点等敏感字段做**脱敏**处理
|
||||||
- 权限**按需申请**:只有当你主动使用某个功能(如开启镜像、设置提醒、点击地点导航)时才弹窗申请,启动、首启、同意隐私政策时都**不会**提前申请
|
- **不申请定位权限**:本应用从不读取设备实时位置。「一键导航」所需的坐标由系统地理编码服务按**你填写的地址文本**换算,故 `module.json5` 中不含 `LOCATION` / `APPROXIMATELY_LOCATION`
|
||||||
|
- 地点关键词检索由 HarmonyOS 系统能力**华为地图服务**(Map Kit / Site Kit)提供,仅用于检索,不用于广告、画像或统计分析
|
||||||
|
- 权限**按需申请**:只有当你主动使用某个功能(如开启镜像、设置提醒)时才弹窗申请,启动、首启、同意隐私政策时都**不会**提前申请
|
||||||
- 权限被拒绝后,对应功能默认关闭,可随时在系统设置或本应用设置页重新开启
|
- 权限被拒绝后,对应功能默认关闭,可随时在系统设置或本应用设置页重新开启
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -699,4 +699,45 @@ export class AccountStore {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ⭐ 账号库是否**确认为空白**(不是"读取失败导致的空")。
|
||||||
|
*
|
||||||
|
* 为什么需要它:`loadAll()` 内部把所有异常都 catch 掉并返回 `[]`,
|
||||||
|
* 于是调用方无法从返回值区分两种情况:
|
||||||
|
* ① 账号库真的空(全新安装 / 用户重置 / **卸载重装**);
|
||||||
|
* ② 密文存在但解不开,或读取过程抛错(临时故障)。
|
||||||
|
*
|
||||||
|
* 系统日历镜像的孤儿清理必须只在 ① 时动手 —— ② 若照常清理,
|
||||||
|
* 会把"账号其实还在"的镜像账户全部误删(用户日程从系统日历里消失)。
|
||||||
|
*
|
||||||
|
* 判定口径(三者同时成立才算"确认空白"):
|
||||||
|
* - 偏好里**没有**账号密文(`data_b64` 为空);
|
||||||
|
* - 旧版明文存储也没有账号;
|
||||||
|
* - 读取过程没有抛异常。
|
||||||
|
*
|
||||||
|
* @returns true = 确认空白,可安全清理孤儿镜像;false = 拿不准,调用方必须保守跳过
|
||||||
|
*/
|
||||||
|
static async isEmptyVaultConfirmed(context: common.Context): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const store: preferences.Preferences = await Vault.prefs(context);
|
||||||
|
const data: string = await store.get(VAULT_DATA, '') as string;
|
||||||
|
if (data !== '') {
|
||||||
|
// 有密文:只有能解出"0 个账号"才算确认空白;解不开一律视为拿不准
|
||||||
|
const plain: string | null = await Vault.decrypt(context, data);
|
||||||
|
if (plain === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const arr: Array<Record<string, Object>> = JSON.parse(plain) as Array<Record<string, Object>>;
|
||||||
|
return arr.length === 0;
|
||||||
|
}
|
||||||
|
// 无密文:再看旧版明文存储是否还有残留账号
|
||||||
|
const legacy: DavAccount[] | null = await AccountStore.loadLegacy(context);
|
||||||
|
return legacy === null || legacy.length === 0;
|
||||||
|
} catch (err) {
|
||||||
|
const e = err as BusinessError;
|
||||||
|
console.error(`[AccountStore] isEmptyVaultConfirmed 判定失败(按"拿不准"处理): ${e.message}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,8 +45,13 @@ export class AppSettings {
|
|||||||
|
|
||||||
// 在线文档网址(自托管,AGC 上架的"隐私政策网址"填 PRIVACY_URL)。
|
// 在线文档网址(自托管,AGC 上架的"隐私政策网址"填 PRIVACY_URL)。
|
||||||
// ⚠️ 隐私政策与用户协议必须与安装包实际申请的 user_grant 权限保持一致:
|
// ⚠️ 隐私政策与用户协议必须与安装包实际申请的 user_grant 权限保持一致:
|
||||||
// 应用仅申请 READ_CALENDAR / READ_WHOLE_CALENDAR / LOCATION / APPROXIMATELY_LOCATION(均前台),
|
// 应用仅申请 READ_CALENDAR / READ_WHOLE_CALENDAR / WRITE_CALENDAR(均前台)。
|
||||||
// 文档中不得出现"在后台获取位置"(LOCATION_IN_BACKGROUND)与"添加/修改/删除日历活动"(WRITE_CALENDAR)。
|
// 文档中不得出现"在后台获取位置"(LOCATION_IN_BACKGROUND)。
|
||||||
|
// ⚠️ 0.1.0 起已**移除 LOCATION / APPROXIMATELY_LOCATION**:实测本 SDK(API 26)的
|
||||||
|
// `geoLocationManager.getAddressesFromLocationName`(地址→坐标)无 @permission 标注,
|
||||||
|
// 地理编码不需要定位权限;且应用从不调用 getCurrentLocation,本就不读实时位置。
|
||||||
|
// ⇒ 隐私政策/隐私标签里都**不得**再声称"读取设备精确位置或大致位置"。
|
||||||
|
// ⇒ 若将来真要用实时定位,必须同时改 module.json5、本注释、upa.html 与 AGC 隐私标签。
|
||||||
// 四份文档均在设置页通过内置浏览器(DocViewer)打开,内容在线更新、无需重新发版。
|
// 四份文档均在设置页通过内置浏览器(DocViewer)打开,内容在线更新、无需重新发版。
|
||||||
/** 隐私政策网址 */
|
/** 隐私政策网址 */
|
||||||
static readonly PRIVACY_URL: string = 'https://synccalendar.yangyq.net/upa.html';
|
static readonly PRIVACY_URL: string = 'https://synccalendar.yangyq.net/upa.html';
|
||||||
|
|||||||
@@ -250,6 +250,37 @@ export class DavClient {
|
|||||||
return 'Basic ' + buffer.from(`${username}:${password}`).toString('base64');
|
return 'Basic ' + buffer.from(`${username}:${password}`).toString('base64');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET 拉取单个资源原文,**失败抛错**(与 getRaw 相反)。
|
||||||
|
*
|
||||||
|
* 为什么需要严格版:待办写回要"先 GET 原文、改字段、再 PUT"。
|
||||||
|
* 若 GET 失败却拿到一个 `"HTTP 404"` 之类的字符串并当 ICS 内容 PUT 回去,
|
||||||
|
* 会把服务器上那条待办**覆盖成一句错误信息**(数据破坏)。
|
||||||
|
* 原 getRaw 保留原行为不动(诊断用,已有调用方)。
|
||||||
|
*/
|
||||||
|
static async getRawStrict(url: string, auth: string): Promise<string> {
|
||||||
|
const httpRequest = http.createHttp();
|
||||||
|
try {
|
||||||
|
const resp: http.HttpResponse = await httpRequest.request(url, {
|
||||||
|
method: http.RequestMethod.GET,
|
||||||
|
header: {
|
||||||
|
'Authorization': auth,
|
||||||
|
'Content-Type': 'text/calendar; charset=utf-8',
|
||||||
|
'User-Agent': 'SyncCalendar/1.0'
|
||||||
|
},
|
||||||
|
connectTimeout: 10000,
|
||||||
|
readTimeout: 20000,
|
||||||
|
expectDataType: http.HttpDataType.STRING
|
||||||
|
});
|
||||||
|
if (resp.responseCode < 200 || resp.responseCode >= 300) {
|
||||||
|
throw new DavHttpError(resp.responseCode, `拉取待办原文失败,服务器返回 ${resp.responseCode}`);
|
||||||
|
}
|
||||||
|
return resp.result as string;
|
||||||
|
} finally {
|
||||||
|
httpRequest.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** GET 拉取单个资源的原始 ICS(调试诊断用) */
|
/** GET 拉取单个资源的原始 ICS(调试诊断用) */
|
||||||
static async getRaw(url: string, auth: string): Promise<string> {
|
static async getRaw(url: string, auth: string): Promise<string> {
|
||||||
const httpRequest = http.createHttp();
|
const httpRequest = http.createHttp();
|
||||||
|
|||||||
@@ -336,6 +336,36 @@ export class EventDb {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 全部未删除的待办(VTODO),未完成在前、按截止时间升序 */
|
/** 全部未删除的待办(VTODO),未完成在前、按截止时间升序 */
|
||||||
|
/** 按本地行 id 查一行(待办完成时用来取 uid / href / remotePath / etag) */
|
||||||
|
/** 更新待办的完成状态与 etag(推送成功后调用,保证本地与服务器一致) */
|
||||||
|
static async setTodoCompleted(context: common.Context, id: number, completed: boolean,
|
||||||
|
etag: string): Promise<void> {
|
||||||
|
const store = await EventDb.getDb(context);
|
||||||
|
const values: relationalStore.ValuesBucket = {
|
||||||
|
'completed': completed ? 1 : 0,
|
||||||
|
'dirty': 0,
|
||||||
|
'etag': etag
|
||||||
|
};
|
||||||
|
const predicates = new relationalStore.RdbPredicates('events');
|
||||||
|
predicates.equalTo('id', id);
|
||||||
|
await store.update(values, predicates);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async queryById(context: common.Context, id: number): Promise<LocalEvent | null> {
|
||||||
|
const store = await EventDb.getDb(context);
|
||||||
|
const predicates = new relationalStore.RdbPredicates('events');
|
||||||
|
predicates.equalTo('id', id);
|
||||||
|
const rs = await store.query(predicates);
|
||||||
|
try {
|
||||||
|
if (rs.goToNextRow()) {
|
||||||
|
return EventDb.fromRow(rs);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
rs.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static async queryTodos(context: common.Context): Promise<LocalEvent[]> {
|
static async queryTodos(context: common.Context): Promise<LocalEvent[]> {
|
||||||
const store = await EventDb.getDb(context);
|
const store = await EventDb.getDb(context);
|
||||||
const predicates = new relationalStore.RdbPredicates('events');
|
const predicates = new relationalStore.RdbPredicates('events');
|
||||||
|
|||||||
@@ -170,6 +170,163 @@ export class IcsUtil {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ⭐ 在**服务器原文**上改写某个 VTODO 的完成状态,返回新的整份 ICS。
|
||||||
|
*
|
||||||
|
* 为什么不从本地字段重建:VTODO 上还有 SUMMARY / DESCRIPTION / DUE / PRIORITY /
|
||||||
|
* CATEGORIES / X-* 等大量字段,本地库只保存了其中少数几个。
|
||||||
|
* 若按本地字段重新拼一份 VTODO 再 PUT,等于**把没保存的字段全部删掉**(丢用户数据)。
|
||||||
|
* 因此这里只做"在原文上精确改那几行",其余内容原样保留。
|
||||||
|
*
|
||||||
|
* 改动范围(按 RFC 5545,三者要一起维护,否则各客户端显示不一致):
|
||||||
|
* - `STATUS:COMPLETED` ⇄ `STATUS:NEEDS-ACTION`
|
||||||
|
* - `COMPLETED:<UTC时间>`(完成时写入,取消完成时删除)
|
||||||
|
* - `PERCENT-COMPLETE:100` ⇄ `PERCENT-COMPLETE:0`
|
||||||
|
*
|
||||||
|
* @param ics 服务器上的原始 .ics 全文
|
||||||
|
* @param uid 目标待办的 UID(一个资源里理论上只有一个 VTODO,但仍按 uid 定位更稳)
|
||||||
|
* @param done true=标记完成;false=取消完成
|
||||||
|
* @returns 改写后的完整 ICS(调用方直接 PUT)
|
||||||
|
*/
|
||||||
|
static rewriteTodoCompletion(ics: string, uid: string, done: boolean): string {
|
||||||
|
const crlf: string = '\r\n';
|
||||||
|
// 折行还原(RFC 5545 允许续行,续行以空格/Tab 开头)
|
||||||
|
const unfolded: string = ics.replace(/\r?\n[ \t]/g, '');
|
||||||
|
const lines: string[] = unfolded.split(/\r?\n/).map((s: string): string => s.replace(/\r$/, ''));
|
||||||
|
const upperOf = (s: string): string => s.toUpperCase();
|
||||||
|
const nowUtc: string = IcsUtil.fmtUtcNow();
|
||||||
|
|
||||||
|
// ---------- 第 1 遍:找出"含目标 uid 的 VTODO"的 [begin, end] 行号区间 ----------
|
||||||
|
// 必须两遍:RFC 5545 不规定字段顺序,UID 可能出现在 STATUS 之后。
|
||||||
|
// 单遍实现会漏改(实测风险:STATUS 在前时 matched 仍为 false → 用户点了没反应)。
|
||||||
|
let targetBegin: number = -1;
|
||||||
|
let targetEnd: number = -1;
|
||||||
|
let targetOrdinal: number = -1; // 目标 VTODO 是第几个块(0 基),供插入段按结构定位
|
||||||
|
let curBegin: number = -1;
|
||||||
|
let curHasUid: boolean = false;
|
||||||
|
let blockIdx: number = -1;
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const u: string = upperOf(lines[i]);
|
||||||
|
if (u.startsWith('BEGIN:VTODO')) {
|
||||||
|
blockIdx++;
|
||||||
|
curBegin = i;
|
||||||
|
curHasUid = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (u.startsWith('UID:') && curBegin >= 0) {
|
||||||
|
if (lines[i].substring(4).trim() === uid) {
|
||||||
|
curHasUid = true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (u.startsWith('END:VTODO')) {
|
||||||
|
if (curBegin >= 0 && curHasUid && targetBegin < 0) {
|
||||||
|
targetBegin = curBegin;
|
||||||
|
targetEnd = i;
|
||||||
|
targetOrdinal = blockIdx;
|
||||||
|
}
|
||||||
|
curBegin = -1;
|
||||||
|
curHasUid = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (targetBegin < 0) {
|
||||||
|
// 找不到目标 uid:原样返回(调用方会 PUT 回去,内容未变,等于无操作)
|
||||||
|
return ics;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 第 2 遍:在区间内改写状态字段 ----------
|
||||||
|
const out: string[] = [];
|
||||||
|
let sawStatus: boolean = false;
|
||||||
|
let sawPercent: boolean = false;
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const line: string = lines[i];
|
||||||
|
const u: string = upperOf(line);
|
||||||
|
const inTarget: boolean = i > targetBegin && i < targetEnd;
|
||||||
|
|
||||||
|
if (!inTarget) {
|
||||||
|
out.push(line);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (u.startsWith('STATUS:')) {
|
||||||
|
sawStatus = true;
|
||||||
|
out.push(done ? 'STATUS:COMPLETED' : 'STATUS:NEEDS-ACTION');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (u.startsWith('COMPLETED')) {
|
||||||
|
continue; // 丢弃旧的,完成时下面统一补
|
||||||
|
}
|
||||||
|
if (u.startsWith('PERCENT-COMPLETE')) {
|
||||||
|
sawPercent = true;
|
||||||
|
out.push(done ? 'PERCENT-COMPLETE:100' : 'PERCENT-COMPLETE:0');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.push(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 缺字段则在目标 VTODO 的 END 之前补齐(有的客户端缺 STATUS 就不显示完成态)
|
||||||
|
const extra: string[] = [];
|
||||||
|
if (!sawStatus) {
|
||||||
|
extra.push(done ? 'STATUS:COMPLETED' : 'STATUS:NEEDS-ACTION');
|
||||||
|
}
|
||||||
|
if (done) {
|
||||||
|
extra.push('COMPLETED:' + nowUtc);
|
||||||
|
}
|
||||||
|
if (!sawPercent) {
|
||||||
|
extra.push(done ? 'PERCENT-COMPLETE:100' : 'PERCENT-COMPLETE:0');
|
||||||
|
}
|
||||||
|
if (extra.length === 0) {
|
||||||
|
const plain: string = out.join(crlf);
|
||||||
|
return plain.endsWith(crlf) ? plain : plain + crlf;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ⭐ 插入点必须按"结构"定位,不能按行号:
|
||||||
|
// 改动可能删掉了旧的 COMPLETED 行,out 与第一遍的 lines 行号已不对齐,
|
||||||
|
// 用行号定位会把字段写到 END:VTODO 之外(实测会落到 END:VCALENDAR 之后,
|
||||||
|
// 结构非法,部分服务端直接 400)。
|
||||||
|
// 这里重新数 VTODO 块,找到"第 targetOrdinal 个"块的 END 行插进去。
|
||||||
|
const result: string[] = [];
|
||||||
|
let vtodoIdx: number = -1; // 当前处于第几个 VTODO 块内(-1=不在块内)
|
||||||
|
let inserted: boolean = false;
|
||||||
|
for (let i = 0; i < out.length; i++) {
|
||||||
|
const u: string = upperOf(out[i]);
|
||||||
|
if (u.startsWith('BEGIN:VTODO')) {
|
||||||
|
vtodoIdx++;
|
||||||
|
result.push(out[i]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (u.startsWith('END:VTODO')) {
|
||||||
|
// 走到目标块的 END 之前先补字段
|
||||||
|
if (!inserted && vtodoIdx === targetOrdinal) {
|
||||||
|
for (const ex of extra) {
|
||||||
|
result.push(ex);
|
||||||
|
}
|
||||||
|
inserted = true;
|
||||||
|
}
|
||||||
|
vtodoIdx = -1;
|
||||||
|
result.push(out[i]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
result.push(out[i]);
|
||||||
|
}
|
||||||
|
if (!inserted) {
|
||||||
|
// 兜底(理论上不会发生):退回到"整份文本末尾 END:VCALENDAR 之前"插入
|
||||||
|
const tail0: string = result.join(crlf);
|
||||||
|
const idxVc: number = tail0.lastIndexOf('END:VCALENDAR');
|
||||||
|
if (idxVc > 0) {
|
||||||
|
const head: string = tail0.substring(0, idxVc);
|
||||||
|
const tail: string = tail0.substring(idxVc);
|
||||||
|
const merged: string = head + extra.join(crlf) + crlf + tail;
|
||||||
|
return merged.endsWith(crlf) ? merged : merged + crlf;
|
||||||
|
}
|
||||||
|
for (const ex of extra) {
|
||||||
|
result.push(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const text2: string = result.join(crlf);
|
||||||
|
return text2.endsWith(crlf) ? text2 : text2 + crlf;
|
||||||
|
}
|
||||||
|
|
||||||
/** 解析 VCALENDAR 中的 VTODO 待办列表(待办为只读展示,不参与推送) */
|
/** 解析 VCALENDAR 中的 VTODO 待办列表(待办为只读展示,不参与推送) */
|
||||||
static parseTodos(ics: string): RemoteEvent[] {
|
static parseTodos(ics: string): RemoteEvent[] {
|
||||||
const unfolded: string = ics.replace(/\r?\n[ \t]/g, '');
|
const unfolded: string = ics.replace(/\r?\n[ \t]/g, '');
|
||||||
|
|||||||
@@ -0,0 +1,253 @@
|
|||||||
|
// entry/src/main/ets/common/PlaceSuggest.ets
|
||||||
|
// 地点补全/选点:基于鸿蒙系统内置的 Map Kit(Site Kit + sceneMap)
|
||||||
|
//
|
||||||
|
// 为什么用华为 Map Kit 而不是高德:
|
||||||
|
// 1) 系统内置、无需第三方 SDK 依赖,也不需要我们自己维护一个 API Key;
|
||||||
|
// 2) Site Kit 的 queryAutoComplete / searchByText / reverseGeocode **不需要任何权限**
|
||||||
|
// (SDK 声明里没有 @permission),符合本项目「权限只在用户主动点该功能时申请」的硬约束;
|
||||||
|
// 3) HarmonyOS 5.0 及以上 Map Kit 的地图加载/POI 搜索/地理编码当前免费(官方论坛口径)。
|
||||||
|
//
|
||||||
|
// ⚠️ 前置条件(必须由用户在 AGC 完成,代码无法替代):
|
||||||
|
// AGC 项目 → 开放能力管理 → 打开「地图服务」,并**重新申请 Profile**(旧的 Profile 不含地图能力)。
|
||||||
|
// 未开通时调用会抛 1002600004(The Map permission is not enabled)。
|
||||||
|
// 因此本类所有入口都必须**优雅降级**:失败只返回空列表,绝不影响日程本身的保存。
|
||||||
|
import { site, sceneMap, mapCommon } from '@kit.MapKit';
|
||||||
|
import { common } from '@kit.AbilityKit';
|
||||||
|
import { BusinessError } from '@kit.BasicServicesKit';
|
||||||
|
import { LogUtil } from './LogUtil';
|
||||||
|
|
||||||
|
/** 一条地点候选(界面直接消费) */
|
||||||
|
export class PlaceItem {
|
||||||
|
/** Site Kit 的地点 ID,可用于 searchById 取详情 */
|
||||||
|
siteId: string = '';
|
||||||
|
/** 地点名称,如「星巴克(中关村店)」 */
|
||||||
|
name: string = '';
|
||||||
|
/** 完整格式化地址,如「北京市海淀区中关村大街1号」 */
|
||||||
|
address: string = '';
|
||||||
|
/** 纬度(无法取得时为 0) */
|
||||||
|
lat: number = 0;
|
||||||
|
/** 经度(无法取得时为 0) */
|
||||||
|
lng: number = 0;
|
||||||
|
/** 是否有有效坐标 */
|
||||||
|
hasCoord: boolean = false;
|
||||||
|
|
||||||
|
/** 界面上第一行显示:有名称用名称,否则用地址 */
|
||||||
|
get title(): string {
|
||||||
|
return this.name !== '' ? this.name : this.address;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 界面上第二行显示:名称+地址重复时不显示 */
|
||||||
|
get subtitle(): string {
|
||||||
|
if (this.address === '') {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
if (this.name === '' || this.address === this.name) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
return this.address;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 写入日程 location 字段的文本:优先完整地址,退化为名称 */
|
||||||
|
get locationText(): string {
|
||||||
|
return this.address !== '' ? this.address : this.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PlaceSuggest {
|
||||||
|
/** 地图能力是否可用(false 时界面应显示提示而不是反复重试) */
|
||||||
|
private static unavailable: boolean = false;
|
||||||
|
/** 最近一次失败原因(给界面显示,便于用户/开发者判断是"没开通"还是"网络问题") */
|
||||||
|
private static lastError: string = '';
|
||||||
|
/** 当前在途请求序号:用于丢弃过期结果(边打字边搜时后发先至) */
|
||||||
|
private static seq: number = 0;
|
||||||
|
|
||||||
|
static isUnavailable(): boolean {
|
||||||
|
return PlaceSuggest.unavailable;
|
||||||
|
}
|
||||||
|
|
||||||
|
static getLastError(): string {
|
||||||
|
return PlaceSuggest.lastError;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关键字补全:输入几个字返回候选地点。
|
||||||
|
* 失败/未开通一律返回空数组(不抛异常,不影响其他功能)。
|
||||||
|
* @param keyword 用户已输入的关键字
|
||||||
|
* @param context 可选,传了就用带 context 的重载(定位更准)
|
||||||
|
*/
|
||||||
|
static async query(keyword: string, context?: common.Context): Promise<PlaceItem[]> {
|
||||||
|
const q: string = keyword.trim();
|
||||||
|
if (q === '') {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
if (PlaceSuggest.unavailable) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
// 序号机制:只接受最后一次请求的结果
|
||||||
|
PlaceSuggest.seq++;
|
||||||
|
const mySeq: number = PlaceSuggest.seq;
|
||||||
|
try {
|
||||||
|
const params: site.QueryAutoCompleteParams = {
|
||||||
|
query: q,
|
||||||
|
language: 'zh-CN',
|
||||||
|
isCityLimit: false
|
||||||
|
};
|
||||||
|
const res: site.QueryAutoCompleteResult = context !== undefined
|
||||||
|
? await site.queryAutoComplete(context, params)
|
||||||
|
: await site.queryAutoComplete(params);
|
||||||
|
if (mySeq !== PlaceSuggest.seq) {
|
||||||
|
// 已有更新的请求发出,丢弃本次结果
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return PlaceSuggest.toItems(res.sites);
|
||||||
|
} catch (err) {
|
||||||
|
PlaceSuggest.handleError('补全', err);
|
||||||
|
// 补全失败时退一步用关键字搜索(部分环境 autoComplete 不可用但 searchByText 可用)
|
||||||
|
return await PlaceSuggest.searchFallback(q, context, mySeq);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关键字搜索(补全失败时的兜底,也用于用户直接点"搜索")。
|
||||||
|
*/
|
||||||
|
static async search(keyword: string, context?: common.Context): Promise<PlaceItem[]> {
|
||||||
|
const q: string = keyword.trim();
|
||||||
|
if (q === '' || PlaceSuggest.unavailable) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
PlaceSuggest.seq++;
|
||||||
|
const mySeq: number = PlaceSuggest.seq;
|
||||||
|
return await PlaceSuggest.searchFallback(q, context, mySeq);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async searchFallback(keyword: string, context: common.Context | undefined,
|
||||||
|
mySeq: number): Promise<PlaceItem[]> {
|
||||||
|
try {
|
||||||
|
const params: site.SearchByTextParams = {
|
||||||
|
query: keyword,
|
||||||
|
language: 'zh-CN'
|
||||||
|
};
|
||||||
|
const res: site.SearchByTextResult = context !== undefined
|
||||||
|
? await site.searchByText(context, params)
|
||||||
|
: await site.searchByText(params);
|
||||||
|
if (mySeq !== PlaceSuggest.seq) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return PlaceSuggest.toItems(res.sites);
|
||||||
|
} catch (err) {
|
||||||
|
PlaceSuggest.handleError('搜索', err);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开系统地图选点页,返回用户选中的地点(用户取消返回 null)。
|
||||||
|
* 这是最省事也最不容易出错的方式:地图、搜索、周边都由系统界面提供。
|
||||||
|
*/
|
||||||
|
static async pickOnMap(context: common.UIAbilityContext): Promise<PlaceItem | null> {
|
||||||
|
try {
|
||||||
|
const options: sceneMap.LocationChoosingOptions = {
|
||||||
|
language: 'zh-CN',
|
||||||
|
searchEnabled: true,
|
||||||
|
showNearbyPoi: true
|
||||||
|
};
|
||||||
|
const r: sceneMap.LocationChoosingResult = await sceneMap.chooseLocation(context, options);
|
||||||
|
const item: PlaceItem = new PlaceItem();
|
||||||
|
item.siteId = r.siteId !== undefined ? r.siteId : '';
|
||||||
|
item.name = r.name !== undefined ? r.name : '';
|
||||||
|
item.address = r.address !== undefined ? r.address : '';
|
||||||
|
if (r.location !== undefined) {
|
||||||
|
item.lat = r.location.latitude;
|
||||||
|
item.lng = r.location.longitude;
|
||||||
|
item.hasCoord = true;
|
||||||
|
}
|
||||||
|
// 两者都空视为取消/无效选择
|
||||||
|
if (item.name === '' && item.address === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return item;
|
||||||
|
} catch (err) {
|
||||||
|
PlaceSuggest.handleError('地图选点', err);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 生成"名称 — 地址"这种便于粘贴进备注/地点的单行文本 */
|
||||||
|
static formatOneLine(item: PlaceItem): string {
|
||||||
|
if (item.name !== '' && item.address !== '' && item.name !== item.address) {
|
||||||
|
return `${item.name}|${item.address}`;
|
||||||
|
}
|
||||||
|
return item.locationText;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static toItems(sites: site.Site[] | undefined): PlaceItem[] {
|
||||||
|
const out: PlaceItem[] = [];
|
||||||
|
if (sites === undefined) {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
for (let i = 0; i < sites.length; i++) {
|
||||||
|
const s: site.Site = sites[i];
|
||||||
|
const item: PlaceItem = new PlaceItem();
|
||||||
|
item.siteId = s.siteId !== undefined ? s.siteId : '';
|
||||||
|
item.name = s.name !== undefined ? s.name : '';
|
||||||
|
// formatAddress 是"省市区+街道门牌"的完整串,最适合写进 LOCATION
|
||||||
|
item.address = s.formatAddress !== undefined ? s.formatAddress : '';
|
||||||
|
if (item.address === '' && s.addressComponent !== undefined) {
|
||||||
|
// 极少数数据只有结构化 addressComponent(字段仅 countryName/locality/city/streetNumber),
|
||||||
|
// 按"国 → 城市 → 区县(locality) → 街道门牌"拼一个保底地址
|
||||||
|
item.address = PlaceSuggest.joinAddress(s.addressComponent);
|
||||||
|
}
|
||||||
|
if (s.location !== undefined) {
|
||||||
|
item.lat = s.location.latitude;
|
||||||
|
item.lng = s.location.longitude;
|
||||||
|
item.hasCoord = true;
|
||||||
|
}
|
||||||
|
if (item.name !== '' || item.address !== '') {
|
||||||
|
out.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从结构化地址组件拼一条保底地址(SDK 里就这几个字段) */
|
||||||
|
private static joinAddress(ac: site.AddressComponent): string {
|
||||||
|
const parts: string[] = [];
|
||||||
|
if (ac.countryName !== undefined && ac.countryName !== '') {
|
||||||
|
parts.push(ac.countryName);
|
||||||
|
}
|
||||||
|
if (ac.city !== undefined && ac.city.cityName !== undefined && ac.city.cityName !== '') {
|
||||||
|
parts.push(ac.city.cityName);
|
||||||
|
}
|
||||||
|
if (ac.locality !== undefined && ac.locality !== '') {
|
||||||
|
parts.push(ac.locality);
|
||||||
|
}
|
||||||
|
if (ac.streetNumber !== undefined) {
|
||||||
|
const sn: site.StreetNumber = ac.streetNumber;
|
||||||
|
if (sn.streetName !== undefined && sn.streetName !== '') {
|
||||||
|
parts.push(sn.streetName);
|
||||||
|
}
|
||||||
|
if (sn.streetNumber !== undefined && sn.streetNumber !== '') {
|
||||||
|
parts.push(sn.streetNumber);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return parts.join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一错误处理:
|
||||||
|
* - 1002600004 地图权限未开通 → 标记不可用,界面不再重试(避免每次打字都打一遍网络)
|
||||||
|
* - 1002600003 鉴权失败(Profile 未含地图能力)
|
||||||
|
* - 1002600002 连不上服务器
|
||||||
|
*/
|
||||||
|
private static handleError(op: string, err: Object): void {
|
||||||
|
const e = err as BusinessError;
|
||||||
|
const code: number = e.code !== undefined ? e.code : 0;
|
||||||
|
PlaceSuggest.lastError = `${op}失败(code=${code}): ${e.message}`;
|
||||||
|
if (code === 1002600004 || code === 1002600003) {
|
||||||
|
PlaceSuggest.unavailable = true;
|
||||||
|
LogUtil.write(`[地点] ${op}不可用(code=${code}):需在 AGC 打开「地图服务」并重新申请 Profile`);
|
||||||
|
} else {
|
||||||
|
LogUtil.write(`[地点] ${PlaceSuggest.lastError}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -795,10 +795,13 @@ export class SystemCalendarMirror {
|
|||||||
/**
|
/**
|
||||||
* ⭐ 兜底:清理"账号已不存在"的孤儿镜像账户(同步时调用,防止删除路径万一漏掉)。
|
* ⭐ 兜底:清理"账号已不存在"的孤儿镜像账户(同步时调用,防止删除路径万一漏掉)。
|
||||||
*
|
*
|
||||||
* ⚠️ **安全阀**:当前账号列表为空时**直接跳过** —— 无法区分"用户删光了账号"与
|
* 三种情况(0.1.1 起,配合"卸载残留"问题):
|
||||||
* "账号存储临时读失败返回空",后者若照常清理会把所有镜像账户误删。
|
* ① **还有账号** → 只清"accId 不在当前账号集合里"的 —— 原逻辑,精准不误伤。
|
||||||
* "删光账号"这种场景已由 `removeByAccount` / 重置账号库两条显式路径覆盖。
|
* ② **账号库为空、且确认是真空**(`isEmptyVaultConfirmed()`)→ **全部清掉**。
|
||||||
* 只要还剩至少一个账号,就只清"accId 前缀不在当前账号集合里"的那些 —— 精准、不会误伤。
|
* 这是卸载重装 / 用户重置账号库后的场景:旧镜像账户的 accId 不可能再匹配上,
|
||||||
|
* 留着只会变成系统日历里永远删不掉的幽灵本,还会继续提醒。
|
||||||
|
* ③ **账号库为空、但拿不准**(读取异常 / 密文解不开)→ **仍然跳过**。
|
||||||
|
* `loadAll()` 会把异常吞掉返回 `[]`,若不区分就会把用户真实在用的镜像全删了。
|
||||||
*
|
*
|
||||||
* @returns 删除的账户数
|
* @returns 删除的账户数
|
||||||
*/
|
*/
|
||||||
@@ -812,8 +815,14 @@ export class SystemCalendarMirror {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
return 0; // 读失败一律不动
|
return 0; // 读失败一律不动
|
||||||
}
|
}
|
||||||
|
let wipeAll: boolean = false;
|
||||||
if (accounts.length === 0) {
|
if (accounts.length === 0) {
|
||||||
return 0; // 安全阀:见注释
|
// 空账号库:只有"确认空白"才敢全清,否则保守跳过(见上方 ③)
|
||||||
|
wipeAll = await AccountStore.isEmptyVaultConfirmed(context);
|
||||||
|
if (!wipeAll) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
LogUtil.write('兜底清理孤儿镜像:账号库确认为空 → 清理全部镜像账户(卸载/重置后残留)');
|
||||||
}
|
}
|
||||||
const validAccIds: Set<string> = new Set<string>();
|
const validAccIds: Set<string> = new Set<string>();
|
||||||
for (const a of accounts) {
|
for (const a of accounts) {
|
||||||
@@ -838,11 +847,13 @@ export class SystemCalendarMirror {
|
|||||||
} else {
|
} else {
|
||||||
sep = dash >= 0 ? dash : under;
|
sep = dash >= 0 ? dash : under;
|
||||||
}
|
}
|
||||||
if (sep <= 0) {
|
// 非全清模式:必须能解析出 accId 才能比对,解析不出就跳过(宁可留,不误删)
|
||||||
continue; // 解析不出 accId → 不动(宁可留,不误删)
|
// 全清模式:前缀已命中就是本应用建的,脏账户(解析不出 accId)也要删干净
|
||||||
|
if (!wipeAll && sep <= 0) {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
const accId: string = bucket.substring(0, sep);
|
const accId: string = sep > 0 ? bucket.substring(0, sep) : bucket;
|
||||||
if (validAccIds.has(accId)) {
|
if (!wipeAll && validAccIds.has(accId)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { common } from '@kit.AbilityKit';
|
||||||
|
import { BusinessError } from '@kit.BasicServicesKit';
|
||||||
|
import { DavAccount } from './AccountStore';
|
||||||
|
import { AccountStore } from './AccountStore';
|
||||||
|
import { LocalEvent } from './EventDb';
|
||||||
|
import { EventDb } from './EventDb';
|
||||||
|
import { DavClient, DavHttpError } from './DavClient';
|
||||||
|
import { IcsUtil } from './IcsUtil';
|
||||||
|
import { LogUtil } from './LogUtil';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 待办(VTODO)操作。
|
||||||
|
*
|
||||||
|
* 现状:待办**只读展示**已实现(拉取/解析/入库/列表),本类补上唯一的写操作
|
||||||
|
* ——「勾选完成 / 取消完成」。
|
||||||
|
*
|
||||||
|
* ⚠️ 为什么不做"从本地字段重建 VTODO 再 PUT":
|
||||||
|
* VTODO 上有 SUMMARY / DESCRIPTION / DUE / PRIORITY / CATEGORIES / X-* 等字段,
|
||||||
|
* 本地库只存了其中几个。重建后 PUT 等于把没存的字段**全部抹掉**。
|
||||||
|
* 所以走"GET 原文 → 就地改 STATUS/COMPLETED/PERCENT-COMPLETE → PUT"。
|
||||||
|
*
|
||||||
|
* ⚠️ 为什么不能同步到手机系统待办:
|
||||||
|
* 系统未开放待办 API(@ohos.calendarManager 只有日程/VEVENT,无 Todo 对象),
|
||||||
|
* 第三方应用无法读写系统日历的「待办」页签。详见工单 #5。
|
||||||
|
*/
|
||||||
|
export class TodoService {
|
||||||
|
/**
|
||||||
|
* 设置待办完成状态并回写服务器。
|
||||||
|
*
|
||||||
|
* @param localId 本地 events 表行 id(DisplayEvent.id)
|
||||||
|
* @param done true=标记完成;false=取消完成
|
||||||
|
* @returns 成功返回 true;失败返回 false(**本地状态不变**,避免界面与服务器不一致)
|
||||||
|
*/
|
||||||
|
static async setCompleted(context: common.Context, localId: number, done: boolean): Promise<boolean> {
|
||||||
|
const row: LocalEvent | null = await EventDb.queryById(context, localId);
|
||||||
|
if (row === null) {
|
||||||
|
LogUtil.write(`待办完成失败:本地行不存在 id=${localId}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (row.kind !== 'todo') {
|
||||||
|
LogUtil.write(`待办完成失败:该行不是待办 id=${localId} kind=${row.kind}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (row.href === '' || row.remotePath === '') {
|
||||||
|
LogUtil.write(`待办完成失败:缺少服务器路径(不可写)id=${localId}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (row.completed === done) {
|
||||||
|
return true; // 状态没变化,直接算成功(幂等)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1) 找到该 href 所属账号,构造鉴权
|
||||||
|
const accounts: DavAccount[] = await AccountStore.loadAll(context);
|
||||||
|
let acc: DavAccount | null = null;
|
||||||
|
for (const a of accounts) {
|
||||||
|
if (a.calendarHrefs.includes(row.href)) {
|
||||||
|
acc = a;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (acc === null) {
|
||||||
|
LogUtil.write(`待办完成失败:找不到所属账号 href=${row.href}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// 只读日历本:推送必然 403,提前拦下给出明确结果
|
||||||
|
const idx: number = acc.calendarHrefs.indexOf(row.href);
|
||||||
|
if (idx >= 0 && acc.calendarWritable.length > idx && acc.calendarWritable[idx] === '0') {
|
||||||
|
LogUtil.write(`待办完成失败:该日历本只读 id=${localId}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auth: string = DavClient.authHeader(acc.username, acc.password);
|
||||||
|
const url: string = row.href.endsWith('/') ? row.href + row.remotePath : `${row.href}/${row.remotePath}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 2) GET 原文(保住本地没存的字段)
|
||||||
|
const original: string = await DavClient.getRawStrict(url, auth);
|
||||||
|
if (!original.toUpperCase().includes('BEGIN:VTODO')) {
|
||||||
|
LogUtil.write(`待办完成失败:服务器返回的内容不是 VTODO id=${localId}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) 只改状态相关字段
|
||||||
|
const updated: string = IcsUtil.rewriteTodoCompletion(original, row.uid, done);
|
||||||
|
|
||||||
|
// 4) PUT 回去,拿新 etag
|
||||||
|
const newEtag: string = await DavClient.putEvent(url, auth, updated);
|
||||||
|
|
||||||
|
// 5) 同步本地(成功后才改,保证两边一致)
|
||||||
|
await EventDb.setTodoCompleted(context, localId, done, newEtag);
|
||||||
|
LogUtil.write(`待办${done ? '完成' : '取消完成'}成功 id=${localId}(标题已脱敏)`);
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof DavHttpError) {
|
||||||
|
const he = err as DavHttpError;
|
||||||
|
LogUtil.write(`待办写回失败 HTTP ${he.status}:id=${localId}(本地状态未改)`);
|
||||||
|
} else {
|
||||||
|
const e = err as BusinessError;
|
||||||
|
LogUtil.write(`待办写回失败:id=${localId} ${e.message ?? ''}(本地状态未改)`);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// entry/src/main/ets/pages/EventEditPage.ets
|
// entry/src/main/ets/pages/EventEditPage.ets
|
||||||
// 日程编辑页:新建 / 修改 / 删除日程(一律属于某个 CalDAV 日历本,不再支持"本机"日程)
|
// 日程编辑页:新建 / 修改 / 删除日程(一律属于某个 CalDAV 日历本,不再支持"本机"日程)
|
||||||
import { curves, router } from '@kit.ArkUI';
|
import { curves, router, KeyboardAvoidMode } from '@kit.ArkUI';
|
||||||
import { common } from '@kit.AbilityKit';
|
import { common } from '@kit.AbilityKit';
|
||||||
import { BusinessError } from '@kit.BasicServicesKit';
|
import { BusinessError } from '@kit.BasicServicesKit';
|
||||||
import { notificationManager } from '@kit.NotificationKit';
|
import { notificationManager } from '@kit.NotificationKit';
|
||||||
@@ -13,6 +13,7 @@ import { ReminderService } from '../common/ReminderService';
|
|||||||
import { LogUtil } from '../common/LogUtil';
|
import { LogUtil } from '../common/LogUtil';
|
||||||
import { IcsUtil } from '../common/IcsUtil';
|
import { IcsUtil } from '../common/IcsUtil';
|
||||||
import { RruleUtil } from '../common/RruleUtil';
|
import { RruleUtil } from '../common/RruleUtil';
|
||||||
|
import { PlaceSuggest, PlaceItem } from '../common/PlaceSuggest';
|
||||||
|
|
||||||
/** 重复系列某次发生的前后边界(用于 EXDATE / UNTIL / 拆分) */
|
/** 重复系列某次发生的前后边界(用于 EXDATE / UNTIL / 拆分) */
|
||||||
class SeriesBounds {
|
class SeriesBounds {
|
||||||
@@ -34,6 +35,34 @@ class BookChoice {
|
|||||||
struct EventEditPage {
|
struct EventEditPage {
|
||||||
@State title: string = '';
|
@State title: string = '';
|
||||||
@State location: string = '';
|
@State location: string = '';
|
||||||
|
/**
|
||||||
|
* ⭐ 地点补全(鸿蒙 Map Kit / Site Kit):
|
||||||
|
* placeItems —— 候选数据(**不参与页面布局**,由 bindPopup 渲染成浮层)
|
||||||
|
* placeLoading —— 是否正在请求,浮层内显示"搜索中"
|
||||||
|
* placeOpen —— 浮层是否弹出(绑在输入框上,向上弹)
|
||||||
|
* placeHint —— 无结果/地图能力不可用时的提示(不阻塞手输地点)
|
||||||
|
*
|
||||||
|
* ⚠️ 为什么必须是浮层而不是内联列表:内联列表改变表单高度 ⇒ 输入框跟着移动 ⇒
|
||||||
|
* 每次"搜索中/出结果/结果变少"都要滚动纠正 ⇒ 用户看到输入框反复上下跳。
|
||||||
|
*/
|
||||||
|
@State placeItems: PlaceItem[] = [];
|
||||||
|
@State placeLoading: boolean = false;
|
||||||
|
@State placeOpen: boolean = false;
|
||||||
|
@State placeHint: string = '';
|
||||||
|
/** 用户是否已从候选里选中(选中后不再自动弹候选,避免"选完又弹出") */
|
||||||
|
private placePicked: boolean = false;
|
||||||
|
/**
|
||||||
|
* 最后一次**程序写入**输入框的文本(选中候选后回写的地址)。
|
||||||
|
* TextInput 的 text 被程序改写同样会触发 onChange;用它精确识别"这次 onChange
|
||||||
|
* 不是用户打字造成的",从而不重复发起搜索。
|
||||||
|
*/
|
||||||
|
private lastAppliedText: string = '';
|
||||||
|
/** 地点输入框当前是否聚焦(仅用于日志/状态,不再驱动滚动) */
|
||||||
|
private placeFocused: boolean = false;
|
||||||
|
/** 输入防抖定时器 */
|
||||||
|
private placeTimer: number = -1;
|
||||||
|
/** 表单滚动控制器(键盘避让由系统 RESIZE 模式负责,这里不再主动滚) */
|
||||||
|
private formScroller: Scroller = new Scroller();
|
||||||
@State description: string = '';
|
@State description: string = '';
|
||||||
@State allDay: boolean = false;
|
@State allDay: boolean = false;
|
||||||
@State startMs: number = 0;
|
@State startMs: number = 0;
|
||||||
@@ -41,7 +70,20 @@ struct EventEditPage {
|
|||||||
@State books: BookChoice[] = [];
|
@State books: BookChoice[] = [];
|
||||||
@State chosenKey: string = '';
|
@State chosenKey: string = '';
|
||||||
@State isSaving: boolean = false;
|
@State isSaving: boolean = false;
|
||||||
|
/**
|
||||||
|
* 表单状态行文字。
|
||||||
|
* ⚠️ 它渲染在表单**最底部**("删除日程"按钮上方),用户在顶部点"保存"时根本看不见。
|
||||||
|
* 所以它只能作为"事后可复查的记录",**不能**作为唯一的错误反馈手段 ——
|
||||||
|
* 真正的提醒必须走 showFormError():Toast(必可见)+ 字段标红 + 滚到出错字段。
|
||||||
|
*/
|
||||||
@State statusMsg: string = '';
|
@State statusMsg: string = '';
|
||||||
|
/**
|
||||||
|
* ⭐ 哪个字段校验没过('' = 没有)。
|
||||||
|
* 用途:把对应输入框描红并显示一条紧贴字段的红字说明,
|
||||||
|
* 让用户一眼看到"哪儿错了",而不是在一屏之外找一行小字。
|
||||||
|
* 取值:'title' | 'time' | ''
|
||||||
|
*/
|
||||||
|
@State errorField: string = '';
|
||||||
@State isExisting: boolean = false;
|
@State isExisting: boolean = false;
|
||||||
@State repeatMode: string = 'none'; // none|daily|workday|weekly|monthly|yearly|custom
|
@State repeatMode: string = 'none'; // none|daily|workday|weekly|monthly|yearly|custom
|
||||||
/**
|
/**
|
||||||
@@ -70,6 +112,8 @@ struct EventEditPage {
|
|||||||
@State sheetMode: string = 'picker';
|
@State sheetMode: string = 'picker';
|
||||||
@State pickerIsEnd: boolean = false;
|
@State pickerIsEnd: boolean = false;
|
||||||
@State pickDate: Date = new Date();
|
@State pickDate: Date = new Date();
|
||||||
|
/** 新建"非今天"日程时的默认开始小时(24 小时制) */
|
||||||
|
private static readonly DEFAULT_START_HOUR: number = 9;
|
||||||
@State pickHour: number = 9;
|
@State pickHour: number = 9;
|
||||||
@State pickMin: number = 0;
|
@State pickMin: number = 0;
|
||||||
/** ⭐ 重复日程编辑范围:'one' 仅此次 / 'future' 此次及以后 / 'all' 全部 */
|
/** ⭐ 重复日程编辑范围:'one' 仅此次 / 'future' 此次及以后 / 'all' 全部 */
|
||||||
@@ -87,9 +131,36 @@ struct EventEditPage {
|
|||||||
private event: LocalEvent | null = null;
|
private event: LocalEvent | null = null;
|
||||||
|
|
||||||
aboutToAppear(): Promise<void> {
|
aboutToAppear(): Promise<void> {
|
||||||
|
// 键盘避让不阻塞页面加载:拿窗口是异步的,失败也只是少一层滚动校正
|
||||||
|
this.setupKeyboardAvoid();
|
||||||
return this.initPage();
|
return this.initPage();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 页面销毁:清掉地点补全的防抖定时器 */
|
||||||
|
aboutToDisappear(): void {
|
||||||
|
this.cancelSuggestTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ⭐ 键盘避让:改成 RESIZE 模式。
|
||||||
|
* 默认 OFFSET 是「整页上移」,页面上移后表单底部(地点/备注/按钮)会被顶出屏幕。
|
||||||
|
* RESIZE 是「把页面高度压缩到键盘上沿」,滚动区域随之变矮,
|
||||||
|
* 聚焦的输入框由系统自动滚入可见区,**无需再手动 scrollBy**。
|
||||||
|
*
|
||||||
|
* ⚠️ 曾经写过"手动量矩形 + scrollBy 对齐"的方案,是错的方向:
|
||||||
|
* ① getRectangleById 返回 px、scrollBy 收 vp,单位混用会把输入框推飞;
|
||||||
|
* ② 更根本的是——只要候选参与布局,位置就会反复变化,
|
||||||
|
* 靠"事后纠正"必然表现为抖动。所以候选改成了浮层(见 placePopup)。
|
||||||
|
*/
|
||||||
|
private setupKeyboardAvoid(): void {
|
||||||
|
try {
|
||||||
|
this.getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE);
|
||||||
|
} catch (err) {
|
||||||
|
const e = err as BusinessError;
|
||||||
|
LogUtil.write(`设置键盘避让模式失败: ${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async initPage(): Promise<void> {
|
private async initPage(): Promise<void> {
|
||||||
const context = this.getUIContext().getHostContext();
|
const context = this.getUIContext().getHostContext();
|
||||||
if (context === undefined) {
|
if (context === undefined) {
|
||||||
@@ -202,18 +273,214 @@ struct EventEditPage {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 新建:日期取所选日(未选则今天),时间取当前时刻;结束 = 开始 + 1 小时
|
// 新建:日期取所选日(未选则今天)。默认开始时刻分两种情况:
|
||||||
|
// ① 今天 → 取当前时刻("现在就记一笔"最自然;而且今天的 09:00 往往已经过了)
|
||||||
|
// ② 非今天 → 固定 09:00("现在几点"对别的日子毫无参考价值,09:00 才是通用默认)
|
||||||
|
// 结束时间统一 = 开始 + 1 小时。
|
||||||
const base: number = AppStorage.get<number>('pendingEventDate') ?? Date.now();
|
const base: number = AppStorage.get<number>('pendingEventDate') ?? Date.now();
|
||||||
const dayStart = new Date(new Date(base).getFullYear(), new Date(base).getMonth(),
|
const pickedDay = new Date(base);
|
||||||
new Date(base).getDate()).getTime();
|
const dayStart = new Date(pickedDay.getFullYear(), pickedDay.getMonth(),
|
||||||
|
pickedDay.getDate()).getTime();
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
|
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
||||||
|
if (dayStart === todayStart) {
|
||||||
|
// ① 今天:当前时刻
|
||||||
this.startMs = dayStart + now.getHours() * 3600000 + now.getMinutes() * 60000;
|
this.startMs = dayStart + now.getHours() * 3600000 + now.getMinutes() * 60000;
|
||||||
|
} else {
|
||||||
|
// ② 非今天:09:00
|
||||||
|
this.startMs = dayStart + EventEditPage.DEFAULT_START_HOUR * 3600000;
|
||||||
|
}
|
||||||
this.endMs = this.startMs + 3600000;
|
this.endMs = this.startMs + 3600000;
|
||||||
if (choices.length > 0) {
|
if (choices.length > 0) {
|
||||||
this.chosenKey = choices[0].calKey;
|
this.chosenKey = choices[0].calKey;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== 地点补全(鸿蒙 Map Kit / Site Kit) ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 输入防抖:停止输入 350ms 后才真正发请求。
|
||||||
|
* 好处:① 不把服务端配额/网络浪费在"每敲一个字"上;② 避免结果闪烁。
|
||||||
|
* ⚠️ 这里只用「关键词补全」这一种能力(不需要定位权限),
|
||||||
|
* 所以**不需要**申请 LOCATION 权限,符合"权限只在用户主动点该功能时申请"的约束。
|
||||||
|
*/
|
||||||
|
private scheduleSuggest(v: string): void {
|
||||||
|
this.cancelSuggestTimer();
|
||||||
|
const q: string = v.trim();
|
||||||
|
if (q.length < 1) {
|
||||||
|
this.closePlacePopup();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.placeTimer = setTimeout(() => {
|
||||||
|
this.placeTimer = -1;
|
||||||
|
this.runSuggest(q, false);
|
||||||
|
}, 350);
|
||||||
|
}
|
||||||
|
|
||||||
|
private cancelSuggestTimer(): void {
|
||||||
|
if (this.placeTimer !== -1) {
|
||||||
|
clearTimeout(this.placeTimer);
|
||||||
|
this.placeTimer = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async runSuggest(q: string, forceOpen: boolean): Promise<void> {
|
||||||
|
if (this.placePicked && !forceOpen) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (PlaceSuggest.isUnavailable()) {
|
||||||
|
// 地图服务没开通:给一次明确提示,然后永久静默(不阻塞手输)
|
||||||
|
this.placeHint = '地图服务不可用,可直接手动输入地点';
|
||||||
|
this.placeItems = [];
|
||||||
|
this.placeOpen = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// ⭐ 浮层一直保持展开(从"搜索中"过渡到结果),中间不收起、不重弹 ——
|
||||||
|
// 收起再弹会让浮层闪一下,看起来像"消失了又出现"。
|
||||||
|
this.placeLoading = true;
|
||||||
|
this.placeHint = '';
|
||||||
|
this.placeOpen = true;
|
||||||
|
try {
|
||||||
|
const c = this.getUIContext().getHostContext();
|
||||||
|
const ctx: common.Context | undefined = c;
|
||||||
|
// 先补全;补全空则内部会自动退到关键字搜索
|
||||||
|
let items: PlaceItem[] = await PlaceSuggest.query(q, ctx);
|
||||||
|
if (items.length === 0 && !PlaceSuggest.isUnavailable()) {
|
||||||
|
items = await PlaceSuggest.search(q, ctx);
|
||||||
|
}
|
||||||
|
// ⭐ 丢弃过期结果:用户又改了输入框,就别再覆盖成旧候选
|
||||||
|
if (q !== this.location.trim()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.placeItems = items.slice(0, 6);
|
||||||
|
if (this.placeItems.length === 0) {
|
||||||
|
this.placeHint = PlaceSuggest.isUnavailable()
|
||||||
|
? '地图服务不可用,可直接手动输入地点'
|
||||||
|
: '没有找到匹配地点,可直接手动输入';
|
||||||
|
// 无结果也留在浮层里给提示;用户再输入会被下一次请求覆盖
|
||||||
|
this.placeOpen = true;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const e = err as BusinessError;
|
||||||
|
LogUtil.write(`地点补全异常: ${e.message}`);
|
||||||
|
this.placeItems = [];
|
||||||
|
this.placeHint = '地点搜索失败,可直接手动输入';
|
||||||
|
this.placeOpen = true;
|
||||||
|
} finally {
|
||||||
|
this.placeLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ⭐ 候选浮层(bindPopup)的内容。
|
||||||
|
*
|
||||||
|
* 为什么是浮层而不是内联列表:
|
||||||
|
* 内联列表会改变表单高度 ⇒ 输入框位置随之变化 ⇒ 每次"搜索中/出结果/结果变少"
|
||||||
|
* 都要靠滚动去纠正 ⇒ 用户看到的就是**输入框上下跳好几次**。
|
||||||
|
* 浮层不参与布局,出现与消失**完全不移动输入框**,这是唯一能根治该问题的结构。
|
||||||
|
*
|
||||||
|
* 为什么向上弹(Placement.Top):
|
||||||
|
* 输入框在表单下部、键盘又在下方,向下弹必然被键盘盖住;
|
||||||
|
* 向上弹则整块候选都落在输入框与标题之间的空白区。
|
||||||
|
*/
|
||||||
|
@Builder
|
||||||
|
placePopup() {
|
||||||
|
Column({ space: 0 }) {
|
||||||
|
if (this.placeLoading) {
|
||||||
|
Row({ space: 8 }) {
|
||||||
|
LoadingProgress().width(16).height(16).color($r('app.color.text_hint'))
|
||||||
|
Text('搜索中…')
|
||||||
|
.fontSize(13)
|
||||||
|
.fontColor($r('app.color.text_hint'))
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
.padding({ left: 14, right: 14, top: 12, bottom: 12 })
|
||||||
|
} else if (this.placeItems.length > 0) {
|
||||||
|
// 限高 + 内部滚动:候选最多 6 条,一次全铺开会顶到屏幕顶部
|
||||||
|
List() {
|
||||||
|
ForEach(this.placeItems, (it: PlaceItem, idx: number) => {
|
||||||
|
ListItem() {
|
||||||
|
Column({ space: 2 }) {
|
||||||
|
Text(it.title)
|
||||||
|
.fontSize(14)
|
||||||
|
.fontColor($r('app.color.text_primary'))
|
||||||
|
.maxLines(1)
|
||||||
|
.textOverflow({ overflow: TextOverflow.Ellipsis })
|
||||||
|
.width('100%')
|
||||||
|
.textAlign(TextAlign.Start)
|
||||||
|
if (it.subtitle !== '') {
|
||||||
|
Text(it.subtitle)
|
||||||
|
.fontSize(12)
|
||||||
|
.fontColor($r('app.color.text_secondary'))
|
||||||
|
.maxLines(1)
|
||||||
|
.textOverflow({ overflow: TextOverflow.Ellipsis })
|
||||||
|
.width('100%')
|
||||||
|
.textAlign(TextAlign.Start)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.alignItems(HorizontalAlign.Start)
|
||||||
|
.width('100%')
|
||||||
|
.padding({ left: 14, right: 14, top: 10, bottom: 10 })
|
||||||
|
}
|
||||||
|
.onClick(() => {
|
||||||
|
this.applyPlace(it);
|
||||||
|
})
|
||||||
|
}, (it: PlaceItem, idx: number) => `${it.siteId}_${idx}`)
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
.constraintSize({ maxHeight: 216 })
|
||||||
|
.scrollBar(BarState.Auto)
|
||||||
|
.divider({ strokeWidth: 0.5, color: $r('app.color.shadow_color') })
|
||||||
|
} else {
|
||||||
|
Text(this.placeHint !== '' ? this.placeHint : '没有找到匹配地点,可直接手动输入')
|
||||||
|
.fontSize(12)
|
||||||
|
.fontColor($r('app.color.text_hint'))
|
||||||
|
.width('100%')
|
||||||
|
.padding({ left: 14, right: 14, top: 12, bottom: 12 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
.padding({ top: 4, bottom: 4 })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 选中一条候选:写进地点输入框并收起列表 */
|
||||||
|
private applyPlace(it: PlaceItem): void {
|
||||||
|
// ⭐ 顺序很关键:先收起浮层,再写文本。
|
||||||
|
// TextInput 的 text 被程序改写会触发 onChange,若此时 placePicked 已被
|
||||||
|
// onChange 重置为 false,就会**重新发起一次搜索** → 用户看到
|
||||||
|
// "候选框消失了一下又冒出来一次"。用 lastAppliedText 精确识别这类回写。
|
||||||
|
this.cancelSuggestTimer();
|
||||||
|
this.closePlacePopup();
|
||||||
|
this.placePicked = true;
|
||||||
|
this.lastAppliedText = it.locationText;
|
||||||
|
this.location = it.locationText;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 收起候选浮层(统一入口,保证 placePicked 之外的状态都被清干净) */
|
||||||
|
private closePlacePopup(): void {
|
||||||
|
this.placeOpen = false;
|
||||||
|
this.placeLoading = false;
|
||||||
|
this.placeItems = [];
|
||||||
|
this.placeHint = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 打开系统地图选点页(可搜索、可周边、可拖图钉) */
|
||||||
|
private async pickOnMap(): Promise<void> {
|
||||||
|
const c = this.getUIContext().getHostContext();
|
||||||
|
if (c === undefined) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const it: PlaceItem | null = await PlaceSuggest.pickOnMap(c as common.UIAbilityContext);
|
||||||
|
if (it === null) {
|
||||||
|
// 用户取消,或地图服务不可用
|
||||||
|
if (PlaceSuggest.isUnavailable()) {
|
||||||
|
this.placeHint = '地图服务不可用,可直接手动输入地点';
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.applyPlace(it);
|
||||||
|
}
|
||||||
|
|
||||||
private chosenBook(): BookChoice | null {
|
private chosenBook(): BookChoice | null {
|
||||||
const found = this.books.find((b: BookChoice): boolean => b.calKey === this.chosenKey);
|
const found = this.books.find((b: BookChoice): boolean => b.calKey === this.chosenKey);
|
||||||
if (found !== undefined) {
|
if (found !== undefined) {
|
||||||
@@ -432,20 +699,74 @@ struct EventEditPage {
|
|||||||
this.endMs = dayStart + 86399999;
|
this.endMs = dayStart + 86399999;
|
||||||
} else {
|
} else {
|
||||||
const s = new Date(this.startMs);
|
const s = new Date(this.startMs);
|
||||||
this.startMs = s.getTime() + 9 * 3600000;
|
this.startMs = new Date(s.getFullYear(), s.getMonth(), s.getDate()).getTime()
|
||||||
|
+ EventEditPage.DEFAULT_START_HOUR * 3600000;
|
||||||
this.endMs = this.startMs + 3600000;
|
this.endMs = this.startMs + 3600000;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ⭐ 统一的表单错误提示(**唯一的错误出口**)。
|
||||||
|
*
|
||||||
|
* 为什么需要专门做这件事:
|
||||||
|
* 校验提示原本只写进 `statusMsg`,而它渲染在表单最底部("删除日程"按钮上方)。
|
||||||
|
* 用户在顶部点"保存"时,那行红字远在屏幕之外 —— 看起来就是"点了没反应"。
|
||||||
|
*
|
||||||
|
* 三件事一起做,保证用户一定看得见、也知道该改哪儿:
|
||||||
|
* ① **Toast**:系统级浮在屏幕中上部,不受滚动位置影响,必定可见;
|
||||||
|
* ② **字段标红**:给对应输入框加红框 + 紧贴字段的红字说明;
|
||||||
|
* ③ **滚回出错字段并聚焦**:把视野直接带到问题所在(标题 → 打光标;时间 → 滚到时间卡片)。
|
||||||
|
*
|
||||||
|
* @param msg 给用户看的话术(要具体,说清"该做什么",不要只说"错误")
|
||||||
|
* @param field 'title' | 'time' | ''('' 表示没有具体字段,只弹 Toast)
|
||||||
|
*/
|
||||||
|
private showFormError(msg: string, field: string): void {
|
||||||
|
this.statusMsg = msg;
|
||||||
|
this.errorField = field;
|
||||||
|
// ① Toast:不走布局,无论滚到哪儿都能看到
|
||||||
|
try {
|
||||||
|
this.getUIContext().getPromptAction().showToast({
|
||||||
|
message: msg,
|
||||||
|
duration: 2500,
|
||||||
|
bottom: '70%' // 抬到屏幕偏上方,避免被键盘/底部按钮遮挡
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
// Toast 失败也不影响其它两种提示
|
||||||
|
}
|
||||||
|
// ③ 滚回出错位置:延时一帧,等状态刷新(标红后高度可能变化)后再滚
|
||||||
|
setTimeout(() => {
|
||||||
|
try {
|
||||||
|
if (field === 'title') {
|
||||||
|
this.formScroller.scrollEdge(Edge.Top);
|
||||||
|
try {
|
||||||
|
this.getUIContext().getFocusController().requestFocus('titleInput');
|
||||||
|
} catch (e2) {
|
||||||
|
// 聚焦失败(例如输入法正在切换)不阻塞流程
|
||||||
|
}
|
||||||
|
} else if (field === 'time') {
|
||||||
|
// 时间卡片在表单上部,滚到顶基本就能看到;再留一点余量
|
||||||
|
this.formScroller.scrollEdge(Edge.Top);
|
||||||
|
} else {
|
||||||
|
this.formScroller.scrollEdge(Edge.Top);
|
||||||
|
}
|
||||||
|
} catch (err2) {
|
||||||
|
const e = err2 as BusinessError;
|
||||||
|
LogUtil.write(`错误提示定位失败: ${e.message}`);
|
||||||
|
}
|
||||||
|
}, 60);
|
||||||
|
}
|
||||||
|
|
||||||
private validate(): boolean {
|
private validate(): boolean {
|
||||||
if (this.title.trim() === '') {
|
if (this.title.trim() === '') {
|
||||||
this.statusMsg = '请输入日程标题';
|
this.showFormError('请先填写日程标题', 'title');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (this.endMs < this.startMs) {
|
if (this.endMs < this.startMs) {
|
||||||
this.statusMsg = '结束时间不能早于开始时间';
|
this.showFormError('结束时间不能早于开始时间', 'time');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
// 通过校验:清掉上一轮的错误标记
|
||||||
|
this.errorField = '';
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -711,9 +1032,10 @@ struct EventEditPage {
|
|||||||
// 日程必须落在某个 CalDAV 日历本上("本机"不再是可选目标)——没选到就直接拦下
|
// 日程必须落在某个 CalDAV 日历本上("本机"不再是可选目标)——没选到就直接拦下
|
||||||
const book = this.chosenBook();
|
const book = this.chosenBook();
|
||||||
if (book === null) {
|
if (book === null) {
|
||||||
this.statusMsg = this.books.length === 0
|
// 这也是"必填项缺失",同样要弹 Toast + 滚到对应字段,不能只写底部状态行
|
||||||
|
this.showFormError(this.books.length === 0
|
||||||
? '还没有可写入的 CalDAV 日历本,请先到「更多 → 账号管理」添加账号'
|
? '还没有可写入的 CalDAV 日历本,请先到「更多 → 账号管理」添加账号'
|
||||||
: '请选择要同步到的 CalDAV 日历本';
|
: '请选择要同步到的 CalDAV 日历本', 'book');
|
||||||
LogUtil.write(`保存判定:日历本解析失败(选本=${this.books.length} chosenKey=${this.chosenKey})`);
|
LogUtil.write(`保存判定:日历本解析失败(选本=${this.books.length} chosenKey=${this.chosenKey})`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -726,19 +1048,20 @@ struct EventEditPage {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// ⭐ 范围确认后回到这里再校验一次:范围弹层打开时并未跳过校验,
|
// ⭐ 范围确认后回到这里再校验一次:范围弹层打开时并未跳过校验,
|
||||||
// 只是把它推迟到"选完范围"之后(失败时弹层已关闭,错误显示在表单状态行)。
|
// 只是把它推迟到"选完范围"之后(失败时弹层已关闭,错误用 showFormError 强提示)。
|
||||||
if (!this.validate()) {
|
if (!this.validate()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const book = this.chosenBook();
|
const book = this.chosenBook();
|
||||||
if (book === null) {
|
if (book === null) {
|
||||||
this.statusMsg = this.books.length === 0
|
this.showFormError(this.books.length === 0
|
||||||
? '还没有可写入的 CalDAV 日历本,请先到「更多 → 账号管理」添加账号'
|
? '还没有可写入的 CalDAV 日历本,请先到「更多 → 账号管理」添加账号'
|
||||||
: '请选择要同步到的 CalDAV 日历本';
|
: '请选择要同步到的 CalDAV 日历本', 'book');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.isSaving = true;
|
this.isSaving = true;
|
||||||
this.statusMsg = '';
|
this.statusMsg = '';
|
||||||
|
this.errorField = '';
|
||||||
try {
|
try {
|
||||||
const context = this.getUIContext().getHostContext();
|
const context = this.getUIContext().getHostContext();
|
||||||
if (context === undefined) {
|
if (context === undefined) {
|
||||||
@@ -798,6 +1121,16 @@ struct EventEditPage {
|
|||||||
const ex = err as BusinessError;
|
const ex = err as BusinessError;
|
||||||
LogUtil.write(`保存日程流程失败(数据已存本地待重试):${ex.message}`);
|
LogUtil.write(`保存日程流程失败(数据已存本地待重试):${ex.message}`);
|
||||||
this.statusMsg = `保存失败:${ex.message}(已保存到本地,稍后同步会重试)`;
|
this.statusMsg = `保存失败:${ex.message}(已保存到本地,稍后同步会重试)`;
|
||||||
|
// ⭐ 这里紧接着会 router.back(),底部状态行根本来不及被看到 → 必须用 Toast
|
||||||
|
try {
|
||||||
|
this.getUIContext().getPromptAction().showToast({
|
||||||
|
message: '已保存到本地,同步到服务器失败,稍后会自动重试',
|
||||||
|
duration: 3000,
|
||||||
|
bottom: '70%'
|
||||||
|
});
|
||||||
|
} catch (e2) {
|
||||||
|
// Toast 失败不影响返回
|
||||||
|
}
|
||||||
// 数据仍在本地且带 dirty 标记,不会丢
|
// 数据仍在本地且带 dirty 标记,不会丢
|
||||||
router.back();
|
router.back();
|
||||||
}
|
}
|
||||||
@@ -968,10 +1301,12 @@ struct EventEditPage {
|
|||||||
.width('100%')
|
.width('100%')
|
||||||
.padding({ left: 16, right: 16 })
|
.padding({ left: 16, right: 16 })
|
||||||
|
|
||||||
Scroll() {
|
Scroll(this.formScroller) {
|
||||||
Column({ space: 14 }) {
|
Column({ space: 14 }) {
|
||||||
// 标题
|
// 标题(必填)
|
||||||
TextInput({ text: this.title, placeholder: '标题' })
|
// ⭐ 校验失败时:输入框描红 + 紧贴下方一条红字说明。
|
||||||
|
// 只在 errorField === 'title' 时出现,用户开始输入即自动清除。
|
||||||
|
TextInput({ text: this.title, placeholder: '标题(必填)' })
|
||||||
.height(46)
|
.height(46)
|
||||||
.fontSize(16)
|
.fontSize(16)
|
||||||
.backgroundColor($r('app.color.card_bg'))
|
.backgroundColor($r('app.color.card_bg'))
|
||||||
@@ -981,9 +1316,28 @@ struct EventEditPage {
|
|||||||
.fontColor($r('app.color.text_primary'))
|
.fontColor($r('app.color.text_primary'))
|
||||||
.placeholderColor($r('app.color.text_hint'))
|
.placeholderColor($r('app.color.text_hint'))
|
||||||
.caretColor($r('app.color.brand'))
|
.caretColor($r('app.color.brand'))
|
||||||
|
// 标红:用边框而不是背景,深色/浅色主题下都醒目且不难看
|
||||||
|
.border({
|
||||||
|
width: this.errorField === 'title' ? 1.5 : 0,
|
||||||
|
color: $r('app.color.error')
|
||||||
|
})
|
||||||
.onChange((v: string) => {
|
.onChange((v: string) => {
|
||||||
this.title = v;
|
this.title = v;
|
||||||
|
// 用户开始填写就把红框撤掉,避免"改了还一直红着"
|
||||||
|
if (v.trim() !== '' && this.errorField === 'title') {
|
||||||
|
this.errorField = '';
|
||||||
|
this.statusMsg = '';
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
.id('titleInput')
|
||||||
|
|
||||||
|
if (this.errorField === 'title') {
|
||||||
|
Text('请填写标题后再保存')
|
||||||
|
.fontSize(12)
|
||||||
|
.fontColor($r('app.color.error'))
|
||||||
|
.width('100%')
|
||||||
|
.padding({ left: 4 })
|
||||||
|
}
|
||||||
|
|
||||||
// 全天
|
// 全天
|
||||||
Row() {
|
Row() {
|
||||||
@@ -1012,6 +1366,19 @@ struct EventEditPage {
|
|||||||
.padding(6)
|
.padding(6)
|
||||||
.borderRadius(12)
|
.borderRadius(12)
|
||||||
.backgroundColor($r('app.color.card_bg'))
|
.backgroundColor($r('app.color.card_bg'))
|
||||||
|
// 时间顺序错误时整卡描红,用户一眼能看到问题在这个卡片里
|
||||||
|
.border({
|
||||||
|
width: this.errorField === 'time' ? 1.5 : 0,
|
||||||
|
color: $r('app.color.error')
|
||||||
|
})
|
||||||
|
|
||||||
|
if (this.errorField === 'time') {
|
||||||
|
Text('结束时间不能早于开始时间')
|
||||||
|
.fontSize(12)
|
||||||
|
.fontColor($r('app.color.error'))
|
||||||
|
.width('100%')
|
||||||
|
.padding({ left: 4 })
|
||||||
|
}
|
||||||
|
|
||||||
// 重复
|
// 重复
|
||||||
Column({ space: 8 }) {
|
Column({ space: 8 }) {
|
||||||
@@ -1173,6 +1540,11 @@ struct EventEditPage {
|
|||||||
.backgroundColor(this.chosenKey === b.calKey ? b.color : $r('app.color.chip_off_bg'))
|
.backgroundColor(this.chosenKey === b.calKey ? b.color : $r('app.color.chip_off_bg'))
|
||||||
.onClick(() => {
|
.onClick(() => {
|
||||||
this.chosenKey = b.calKey;
|
this.chosenKey = b.calKey;
|
||||||
|
// 选了日历本就把红框撤掉
|
||||||
|
if (this.errorField === 'book') {
|
||||||
|
this.errorField = '';
|
||||||
|
this.statusMsg = '';
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}, (b: BookChoice) => b.calKey)
|
}, (b: BookChoice) => b.calKey)
|
||||||
}
|
}
|
||||||
@@ -1183,11 +1555,20 @@ struct EventEditPage {
|
|||||||
.width('100%')
|
.width('100%')
|
||||||
.padding(14)
|
.padding(14)
|
||||||
.borderRadius(12)
|
.borderRadius(12)
|
||||||
|
// 日历本未选且用户点了保存 → 描红,提示"必填"
|
||||||
|
.border({
|
||||||
|
width: this.errorField === 'book' ? 1.5 : 0,
|
||||||
|
color: $r('app.color.error')
|
||||||
|
})
|
||||||
.backgroundColor($r('app.color.card_bg'))
|
.backgroundColor($r('app.color.card_bg'))
|
||||||
|
|
||||||
// 地点
|
// 地点(输入几个字 → 系统地图服务补全候选)
|
||||||
TextInput({ text: this.location, placeholder: '地点(可选)' })
|
// ⭐ 候选列表**不在布局流里**:它通过 bindPopup 挂在输入框上、向**上方**弹出。
|
||||||
|
// 这样候选的出现/消失完全不改变输入框位置 —— 从根上消除"输入框上下跳"。
|
||||||
|
Row({ space: 8 }) {
|
||||||
|
TextInput({ text: this.location, placeholder: '地点(可选,输入几个字可搜索)' })
|
||||||
.height(44)
|
.height(44)
|
||||||
|
.layoutWeight(1)
|
||||||
.fontSize(14)
|
.fontSize(14)
|
||||||
.backgroundColor($r('app.color.card_bg'))
|
.backgroundColor($r('app.color.card_bg'))
|
||||||
.borderRadius(12)
|
.borderRadius(12)
|
||||||
@@ -1195,8 +1576,69 @@ struct EventEditPage {
|
|||||||
.placeholderColor($r('app.color.text_hint'))
|
.placeholderColor($r('app.color.text_hint'))
|
||||||
.caretColor($r('app.color.brand'))
|
.caretColor($r('app.color.brand'))
|
||||||
.onChange((v: string) => {
|
.onChange((v: string) => {
|
||||||
|
// ⭐ 程序改写 text(选中候选后回写地址)也会触发 onChange。
|
||||||
|
// 精确比对最后一次程序写入值:命中就不再发起搜索,
|
||||||
|
// 否则会"选完 → 候选框消失 → 又冒出来一次"。
|
||||||
|
if (v === this.lastAppliedText) {
|
||||||
|
this.lastAppliedText = '';
|
||||||
this.location = v;
|
this.location = v;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.lastAppliedText = '';
|
||||||
|
this.location = v;
|
||||||
|
// 用户重新输入时解除"已选中"状态,恢复自动补全
|
||||||
|
this.placePicked = false;
|
||||||
|
this.scheduleSuggest(v);
|
||||||
})
|
})
|
||||||
|
.onSubmit(() => {
|
||||||
|
// 回车:立刻搜一次(不等防抖)
|
||||||
|
this.cancelSuggestTimer();
|
||||||
|
this.runSuggest(this.location, true);
|
||||||
|
})
|
||||||
|
.onFocus(() => {
|
||||||
|
// 键盘避让交给系统(RESIZE 已保证光标可见);
|
||||||
|
// 候选是浮层,不需要再滚动页面去给它腾位置
|
||||||
|
this.placeFocused = true;
|
||||||
|
})
|
||||||
|
.onBlur(() => {
|
||||||
|
// 失焦(点"地图"按钮、点别处、收起键盘)→ 收起候选浮层
|
||||||
|
this.placeFocused = false;
|
||||||
|
this.closePlacePopup();
|
||||||
|
})
|
||||||
|
.bindPopup($$this.placeOpen, {
|
||||||
|
builder: (): void => {
|
||||||
|
this.placePopup()
|
||||||
|
},
|
||||||
|
placement: Placement.Top,
|
||||||
|
popupColor: $r('app.color.card_bg'),
|
||||||
|
enableArrow: false,
|
||||||
|
showInSubWindow: false,
|
||||||
|
focusable: false,
|
||||||
|
autoCancel: true,
|
||||||
|
radius: 12,
|
||||||
|
onStateChange: (e: PopupStateChangeParam) => {
|
||||||
|
// 用户点浮层外部/floating 自动关闭时,同步状态,避免下次不弹
|
||||||
|
if (!e.isVisible && this.placeOpen) {
|
||||||
|
this.placeOpen = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.id('placeAnchor')
|
||||||
|
// 在地图上选点(系统地图界面,可选可搜可周边)
|
||||||
|
Text('地图')
|
||||||
|
.fontSize(13)
|
||||||
|
.fontColor($r('app.color.brand_text'))
|
||||||
|
.padding({ left: 12, right: 12 })
|
||||||
|
.height(44)
|
||||||
|
.textAlign(TextAlign.Center)
|
||||||
|
.borderRadius(12)
|
||||||
|
.backgroundColor($r('app.color.card_bg'))
|
||||||
|
.onClick(() => {
|
||||||
|
this.pickOnMap();
|
||||||
|
})
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
.id('placeRow')
|
||||||
|
|
||||||
// 描述
|
// 描述
|
||||||
TextArea({ text: this.description, placeholder: '备注(可选)' })
|
TextArea({ text: this.description, placeholder: '备注(可选)' })
|
||||||
@@ -1211,7 +1653,10 @@ struct EventEditPage {
|
|||||||
this.description = v;
|
this.description = v;
|
||||||
})
|
})
|
||||||
|
|
||||||
if (this.statusMsg !== '') {
|
// 状态行:只用于"保存失败/账号未配置"这类**系统级**信息,且必须有 Toast 同时提示。
|
||||||
|
// ⚠️ 校验类错误不走这里 —— 它们已经在对应字段旁就地显示,
|
||||||
|
// 再在这里重复一遍只会让用户以为有两处不同的问题。
|
||||||
|
if (this.statusMsg !== '' && this.errorField === '') {
|
||||||
Text(this.statusMsg)
|
Text(this.statusMsg)
|
||||||
.fontSize(13)
|
.fontSize(13)
|
||||||
.fontColor($r('app.color.error'))
|
.fontColor($r('app.color.error'))
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// 同步日历主界面:月视图(左右滑动翻月)/ 周视图 / 日视图 / 日程列表
|
// 同步日历主界面:月视图(左右滑动翻月)/ 周视图 / 日视图 / 日程列表
|
||||||
// 混合展示 DAV 与系统日历;每分钟自动同步;可"回到今天"
|
// 混合展示 DAV 与系统日历;每分钟自动同步;可"回到今天"
|
||||||
import { curves, display, router, window } from '@kit.ArkUI';
|
import { curves, display, router, window } from '@kit.ArkUI';
|
||||||
import { common, abilityAccessCtrl, bundleManager } from '@kit.AbilityKit';
|
import { common } from '@kit.AbilityKit';
|
||||||
import { geoLocationManager } from '@kit.LocationKit';
|
import { geoLocationManager } from '@kit.LocationKit';
|
||||||
import { BusinessError, pasteboard } from '@kit.BasicServicesKit';
|
import { BusinessError, pasteboard } from '@kit.BasicServicesKit';
|
||||||
import { DavAccount, AccountStore, CalSource, TYPE_CALDAV } from '../common/AccountStore';
|
import { DavAccount, AccountStore, CalSource, TYPE_CALDAV } from '../common/AccountStore';
|
||||||
@@ -23,6 +23,7 @@ import { SystemCalendarImport } from '../common/SystemCalendarImport';
|
|||||||
import { SystemCalendarMirror } from '../common/SystemCalendarMirror';
|
import { SystemCalendarMirror } from '../common/SystemCalendarMirror';
|
||||||
import { MirrorInbound } from '../common/MirrorInbound';
|
import { MirrorInbound } from '../common/MirrorInbound';
|
||||||
import { ScreenKeeper } from '../common/ScreenKeeper';
|
import { ScreenKeeper } from '../common/ScreenKeeper';
|
||||||
|
import { TodoService } from '../common/TodoService';
|
||||||
import { TimelineUtil, TimelineBlock, TimelineGroup, DayTimeline, ViewRange } from '../common/TimelineUtil';
|
import { TimelineUtil, TimelineBlock, TimelineGroup, DayTimeline, ViewRange } from '../common/TimelineUtil';
|
||||||
|
|
||||||
/** 月视图单元格 */
|
/** 月视图单元格 */
|
||||||
@@ -32,12 +33,16 @@ class MonthCell {
|
|||||||
inMonth: boolean = false;
|
inMonth: boolean = false;
|
||||||
isToday: boolean = false;
|
isToday: boolean = false;
|
||||||
lunar: string = ''; // 农历(初一时显示月名)
|
lunar: string = ''; // 农历(初一时显示月名)
|
||||||
|
/** ⭐ 该日期是否有任意事件 → 决定是否画一个小圆点。
|
||||||
|
* **只用一个布尔**:早先按"每个日历本一个点"渲染,3 个本就有 3 个点,
|
||||||
|
* 15 个本时整个月视图全是点,所以那个实现被整体砍掉了。 */
|
||||||
|
hasEvent: boolean = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const WEEK_LABELS: string[] = ['一', '二', '三', '四', '五', '六', '日'];
|
const WEEK_LABELS: string[] = ['一', '二', '三', '四', '五', '六', '日'];
|
||||||
|
|
||||||
/** 视图前后顺序(决定手势/标签切换时的转场方向):月 → 周 → 列表 */
|
/** 视图前后顺序(决定手势/标签切换时的转场方向):月 → 周 → 列表 */
|
||||||
const VIEW_ORDER: string[] = ['month', 'week', 'agenda'];
|
const VIEW_ORDER: string[] = ['month', 'week', 'agenda', 'todo'];
|
||||||
|
|
||||||
@Entry
|
@Entry
|
||||||
@Component
|
@Component
|
||||||
@@ -48,6 +53,7 @@ struct Index {
|
|||||||
@Watch('onSelectedDateChange') @State selectedDate: number = 0; // 当天 0 点毫秒
|
@Watch('onSelectedDateChange') @State selectedDate: number = 0; // 当天 0 点毫秒
|
||||||
@State events: DisplayEvent[] = [];
|
@State events: DisplayEvent[] = [];
|
||||||
@State todos: DisplayEvent[] = []; // 待办(VTODO,单独展示)
|
@State todos: DisplayEvent[] = []; // 待办(VTODO,单独展示)
|
||||||
|
@State todoBusy: boolean = false; // 正在写回待办状态(防连点)
|
||||||
@State agendaEvents: DisplayEvent[] = []; // 列表视图全量数据(今天 ~ 未来2年)
|
@State agendaEvents: DisplayEvent[] = []; // 列表视图全量数据(今天 ~ 未来2年)
|
||||||
private agendaStale: boolean = true; // 全量数据是否需要重新加载
|
private agendaStale: boolean = true; // 全量数据是否需要重新加载
|
||||||
@State monthPages: MonthCell[][] = [[], [], []]; // 上月/本月/下月
|
@State monthPages: MonthCell[][] = [[], [], []]; // 上月/本月/下月
|
||||||
@@ -449,12 +455,42 @@ struct Index {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 构建某年某月的 42 格 */
|
/** 构建某年某月的 42 格 */
|
||||||
|
/**
|
||||||
|
* ⭐ 预先算出"有事件的日期"集合(按 dayStart 归一化)。
|
||||||
|
*
|
||||||
|
* 为什么要预计算:月视图一次渲染 42 个格子,若每格都去 filter 一遍全部事件,
|
||||||
|
* 就是 O(42 × 事件数);本机 15 个本、近 3000 条数据,翻月会明显卡顿。
|
||||||
|
* 这里只遍历事件一次,把区间相交的每一天都塞进 Set,之后每格 O(1) 查询。
|
||||||
|
*
|
||||||
|
* 与 `eventsOfDate()` 用**完全相同**的区间相交口径
|
||||||
|
* (`startOfDay(start) <= day && end >= day`),
|
||||||
|
* 因此跨天/多天事件覆盖的每一天都会有点,不会出现"点进去有日程、格子上却没点"的不一致。
|
||||||
|
* 另:待办(isTodo)不计入 —— 待办没有时间点语义,混进月视图会让点失去意义。
|
||||||
|
*/
|
||||||
|
private buildEventDaySet(): Set<number> {
|
||||||
|
const set: Set<number> = new Set<number>();
|
||||||
|
for (const e of this.events) {
|
||||||
|
const s: number = this.startOfDay(e.startTime);
|
||||||
|
const end: number = e.endTime > 0 ? e.endTime : s;
|
||||||
|
// 兜底:异常数据(end < start)或跨度大得离谱(>1 年)不入集合,避免循环失控
|
||||||
|
if (end < s || end - s > 366 * 86400000) {
|
||||||
|
set.add(s);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (let t = s; t <= end; t += 86400000) {
|
||||||
|
set.add(this.startOfDay(t));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return set;
|
||||||
|
}
|
||||||
|
|
||||||
private buildMonthCells(year: number, month: number): MonthCell[] {
|
private buildMonthCells(year: number, month: number): MonthCell[] {
|
||||||
const first: number = new Date(year, month, 1).getTime();
|
const first: number = new Date(year, month, 1).getTime();
|
||||||
const firstDay = new Date(first).getDay();
|
const firstDay = new Date(first).getDay();
|
||||||
const offset: number = (firstDay + 6) % 7; // 周一为一周开始
|
const offset: number = (firstDay + 6) % 7; // 周一为一周开始
|
||||||
const gridStart: number = first - offset * 86400000;
|
const gridStart: number = first - offset * 86400000;
|
||||||
const todayStart: number = this.startOfDay(Date.now());
|
const todayStart: number = this.startOfDay(Date.now());
|
||||||
|
const eventDays: Set<number> = this.buildEventDaySet();
|
||||||
const cells: MonthCell[] = [];
|
const cells: MonthCell[] = [];
|
||||||
for (let i = 0; i < 42; i++) {
|
for (let i = 0; i < 42; i++) {
|
||||||
const dateMs: number = gridStart + i * 86400000;
|
const dateMs: number = gridStart + i * 86400000;
|
||||||
@@ -465,6 +501,7 @@ struct Index {
|
|||||||
cell.inMonth = d.getMonth() === month;
|
cell.inMonth = d.getMonth() === month;
|
||||||
cell.isToday = dateMs === todayStart;
|
cell.isToday = dateMs === todayStart;
|
||||||
cell.lunar = LunarUtil.lunarDayText(dateMs);
|
cell.lunar = LunarUtil.lunarDayText(dateMs);
|
||||||
|
cell.hasEvent = eventDays.has(this.startOfDay(dateMs));
|
||||||
cells.push(cell);
|
cells.push(cell);
|
||||||
}
|
}
|
||||||
return cells;
|
return cells;
|
||||||
@@ -756,11 +793,10 @@ struct Index {
|
|||||||
}
|
}
|
||||||
const ctx = context as common.UIAbilityContext;
|
const ctx = context as common.UIAbilityContext;
|
||||||
const enc: string = encodeURIComponent(address);
|
const enc: string = encodeURIComponent(address);
|
||||||
// 高德鸿蒙深链 dlat/dlon 为必填(dname 仅作名称显示),先地理编码拿坐标
|
// 高德鸿蒙深链 dlat/dlon 为必填(dname 仅作名称显示),先地理编码拿坐标。
|
||||||
let coords: number[] | null = null;
|
// 地理编码(getAddressesFromLocationName)在本 SDK 上不要求定位权限,
|
||||||
if (await this.ensureLocationPermission()) {
|
// 因此这里既不申请、也不使用定位权限 —— 应用自始至终不读取设备实时位置。
|
||||||
coords = await this.geocodeAddress(address);
|
const coords: number[] | null = await this.geocodeAddress(address);
|
||||||
}
|
|
||||||
const base: string = 'amapuri://route/plan/?sourceApplication=SyncCalendar';
|
const base: string = 'amapuri://route/plan/?sourceApplication=SyncCalendar';
|
||||||
let link: string;
|
let link: string;
|
||||||
if (coords !== null) {
|
if (coords !== null) {
|
||||||
@@ -782,33 +818,7 @@ struct Index {
|
|||||||
this.getUIContext().getPromptAction().showToast({ message: '未安装高德地图或无法打开' });
|
this.getUIContext().getPromptAction().showToast({ message: '未安装高德地图或无法打开' });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 确认定位权限(地理编码依赖),未授权时向用户申请一次 */
|
/** 正向地理编码:地址 → 坐标(系统服务,无需高德 key、无需定位权限) */
|
||||||
private async ensureLocationPermission(): Promise<boolean> {
|
|
||||||
try {
|
|
||||||
const atManager = abilityAccessCtrl.createAtManager();
|
|
||||||
const bundleInfo = bundleManager.getBundleInfoForSelfSync(
|
|
||||||
bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
|
|
||||||
const tokenId = bundleInfo.appInfo.accessTokenId;
|
|
||||||
const status = await atManager.checkAccessToken(tokenId, 'ohos.permission.LOCATION');
|
|
||||||
if (status === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
// 未授权会走申请流程
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const context = this.getUIContext().getHostContext() as common.UIAbilityContext;
|
|
||||||
const atManager = abilityAccessCtrl.createAtManager();
|
|
||||||
// LOCATION 与 APPROXIMATELY_LOCATION 必须一起申请
|
|
||||||
const result = await atManager.requestPermissionsFromUser(context,
|
|
||||||
['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION']);
|
|
||||||
return result.authResults.every((r: number): boolean => r === 0);
|
|
||||||
} catch (err) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 正向地理编码:地址 → 坐标(系统服务,无需高德 key) */
|
|
||||||
private async geocodeAddress(address: string): Promise<number[] | null> {
|
private async geocodeAddress(address: string): Promise<number[] | null> {
|
||||||
try {
|
try {
|
||||||
if (!geoLocationManager.isGeocoderAvailable()) {
|
if (!geoLocationManager.isGeocoderAvailable()) {
|
||||||
@@ -1414,12 +1424,20 @@ struct Index {
|
|||||||
this.modeTab('month', '月')
|
this.modeTab('month', '月')
|
||||||
this.modeTab('week', '周')
|
this.modeTab('week', '周')
|
||||||
this.modeTab('agenda', '列表')
|
this.modeTab('agenda', '列表')
|
||||||
|
// ⭐ TODO_TAB 待办页签:与列表同一套布局(未完成在前、已完成在后),点击可勾选完成
|
||||||
|
this.modeTab('todo', '待办')
|
||||||
Blank()
|
Blank()
|
||||||
if (this.mode === 'month') {
|
if (this.mode === 'month') {
|
||||||
Text(this.fmtMonthTitle())
|
Text(this.fmtMonthTitle())
|
||||||
.fontSize(15)
|
.fontSize(15)
|
||||||
.fontWeight(FontWeight.Medium)
|
.fontWeight(FontWeight.Medium)
|
||||||
.fontColor($r('app.color.text_primary'))
|
.fontColor($r('app.color.text_primary'))
|
||||||
|
} else if (this.mode === 'todo') {
|
||||||
|
// 待办与具体日期无关,显示剩余未完成数量更有用
|
||||||
|
Text(`${this.todos.filter((t: DisplayEvent): boolean => !t.completed).length} 项待办`)
|
||||||
|
.fontSize(15)
|
||||||
|
.fontWeight(FontWeight.Medium)
|
||||||
|
.fontColor($r('app.color.text_primary'))
|
||||||
} else {
|
} else {
|
||||||
Text(this.fmtDateCn(this.selectedDate))
|
Text(this.fmtDateCn(this.selectedDate))
|
||||||
.fontSize(15)
|
.fontSize(15)
|
||||||
@@ -2536,6 +2554,11 @@ struct Index {
|
|||||||
.fontSize(12)
|
.fontSize(12)
|
||||||
.fontColor($r('app.color.text_hint'))
|
.fontColor($r('app.color.text_hint'))
|
||||||
.textAlign(TextAlign.Center)
|
.textAlign(TextAlign.Center)
|
||||||
|
Text('提示:系统日历未开放待办接口,这里的待办不会出现在系统「待办」页签中')
|
||||||
|
.fontSize(11)
|
||||||
|
.fontColor($r('app.color.text_hint'))
|
||||||
|
.textAlign(TextAlign.Center)
|
||||||
|
.margin({ top: 6 })
|
||||||
}
|
}
|
||||||
.width('100%')
|
.width('100%')
|
||||||
.padding(32)
|
.padding(32)
|
||||||
@@ -2592,11 +2615,39 @@ struct Index {
|
|||||||
.border({ width: 1, color: $r('app.color.shadow_color') })
|
.border({ width: 1, color: $r('app.color.shadow_color') })
|
||||||
.opacity(t.completed ? 0.7 : 1)
|
.opacity(t.completed ? 0.7 : 1)
|
||||||
.onClick(() => {
|
.onClick(() => {
|
||||||
this.getUIContext().getPromptAction()
|
this.toggleTodo(t);
|
||||||
.showToast({ message: '待办来自服务器,请在群晖日历等源端修改' });
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 待办完成状态切换:写回服务器成功后刷新列表;失败保持原状并提示。
|
||||||
|
* ⚠️ 不做"先改界面再回滚":待办写回要走网络,若先改后失败,
|
||||||
|
* 用户会看到状态闪一下又跳回去,容易误以为操作没生效。这里直接等结果。 */
|
||||||
|
private async toggleTodo(t: DisplayEvent): Promise<void> {
|
||||||
|
const ctx = this.getUIContext().getHostContext();
|
||||||
|
if (ctx === undefined || this.todoBusy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.todoBusy = true;
|
||||||
|
try {
|
||||||
|
const ok: boolean = await TodoService.setCompleted(ctx, t.id, !t.completed);
|
||||||
|
if (ok) {
|
||||||
|
this.getUIContext().getPromptAction().showToast({
|
||||||
|
message: t.completed ? '已标记为未完成' : '已完成'
|
||||||
|
});
|
||||||
|
// 重新读库刷新列表(服务层已更新 completed)
|
||||||
|
this.todos = await CalendarDataService.loadTodos(ctx, this.sources);
|
||||||
|
} else {
|
||||||
|
this.getUIContext().getPromptAction().showToast({
|
||||||
|
message: '更新失败:需联网,且该日历本需可写'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.getUIContext().getPromptAction().showToast({ message: '更新失败,请稍后重试' });
|
||||||
|
} finally {
|
||||||
|
this.todoBusy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 是否跨天(结束日期晚于开始日期) */
|
/** 是否跨天(结束日期晚于开始日期) */
|
||||||
private spansDays(e: DisplayEvent): boolean {
|
private spansDays(e: DisplayEvent): boolean {
|
||||||
return this.startOfDay(e.endTime) > this.startOfDay(e.startTime);
|
return this.startOfDay(e.endTime) > this.startOfDay(e.startTime);
|
||||||
@@ -2626,9 +2677,22 @@ struct Index {
|
|||||||
? $r('app.color.text_secondary') : $r('app.color.text_hint'))
|
? $r('app.color.text_secondary') : $r('app.color.text_hint'))
|
||||||
.maxLines(1)
|
.maxLines(1)
|
||||||
}
|
}
|
||||||
|
// ⭐ EVENT_DOT 有事件的日期标记:**每个日期最多一个**圆点。
|
||||||
|
// 只表达"这天有安排",不区分是哪个日历本、有几条。
|
||||||
|
// (旧实现按日历本逐个画,3 个本 3 个点,15 个本满屏都是点,故被废弃。)
|
||||||
|
// 无事件时用等高的透明占位,避免有/无点导致格子高度跳动、整月行高不一致。
|
||||||
|
Row()
|
||||||
|
.width(this.wideLayout ? 4 : 5)
|
||||||
|
.height(this.wideLayout ? 4 : 5)
|
||||||
|
.borderRadius(this.wideLayout ? 2 : 2.5)
|
||||||
|
.backgroundColor(cell.hasEvent
|
||||||
|
? (cell.dateMs === this.selectedDate
|
||||||
|
? $r('app.color.button_text') // 选中日深底 → 用白点保证对比度
|
||||||
|
: $r('app.color.brand')) // 其余用主题色,比纯红柔和
|
||||||
|
: Color.Transparent)
|
||||||
}
|
}
|
||||||
.layoutWeight(1)
|
.layoutWeight(1)
|
||||||
.padding({ top: 4, bottom: 4 })
|
.padding({ top: this.wideLayout ? 2 : 3, bottom: this.wideLayout ? 2 : 3 })
|
||||||
.borderRadius(8)
|
.borderRadius(8)
|
||||||
.onClick(() => {
|
.onClick(() => {
|
||||||
this.selectedDate = cell.dateMs;
|
this.selectedDate = cell.dateMs;
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ struct SettingsPage {
|
|||||||
@State mirrorKeys: string[] = []; // 要镜像的 DAV 日历本 **bookId**(稳定标识,不用会变的 calKey)
|
@State mirrorKeys: string[] = []; // 要镜像的 DAV 日历本 **bookId**(稳定标识,不用会变的 calKey)
|
||||||
@State mirrorRunning: boolean = false; // 正在执行镜像
|
@State mirrorRunning: boolean = false; // 正在执行镜像
|
||||||
@State purgeRunning: boolean = false; // 正在清理残留镜像账户
|
@State purgeRunning: boolean = false; // 正在清理残留镜像账户
|
||||||
|
@State wipeAllRunning: boolean = false; // 正在清除全部镜像(卸载前清干净)
|
||||||
@State mirrorCandidates: BackupTarget[] = []; // 可镜像的本(已排除"系统日历备份目标本",防回灌)
|
@State mirrorCandidates: BackupTarget[] = []; // 可镜像的本(已排除"系统日历备份目标本",防回灌)
|
||||||
@State mirrorInbound: boolean = false; // 是否把系统日历的改动回写 CalDAV(默认关)
|
@State mirrorInbound: boolean = false; // 是否把系统日历的改动回写 CalDAV(默认关)
|
||||||
@State accountDump: string = ''; // 系统日历账户清单(诊断用,清理后填充)
|
@State accountDump: string = ''; // 系统日历账户清单(诊断用,清理后填充)
|
||||||
@@ -681,6 +682,81 @@ struct SettingsPage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ⭐「彻底清除全部镜像数据」(卸载前清干净用)。
|
||||||
|
*
|
||||||
|
* 为什么需要它:鸿蒙**没有**「应用即将被卸载」的回调,系统日历属于**沙箱外**数据,
|
||||||
|
* 卸载时不会自动清理。用户卸载后,系统日历里会永久留着一堆
|
||||||
|
* 「同步日历·xxx」账户(还会继续提醒),只有重装并重新同步才能被当孤儿清掉。
|
||||||
|
* ⇒ 提供显式入口,让用户在卸载前主动清干净。
|
||||||
|
*
|
||||||
|
* ⚠️ 清除范围(务必与文案一致):
|
||||||
|
* - 只删**系统日历里本应用建立的镜像账户及其日程**
|
||||||
|
* - **不动** CalDAV 账号配置(账号密码仍保留,重装后可直接用)
|
||||||
|
* - **不动** 服务器上的任何日程(同步过去的内容一条都不会少)
|
||||||
|
*/
|
||||||
|
private confirmWipeAllMirrors(): void {
|
||||||
|
if (this.context === undefined || this.wipeAllRunning) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.getUIContext().showAlertDialog({
|
||||||
|
title: '彻底清除系统日历镜像数据',
|
||||||
|
message: '将删除本应用写入系统日历的全部镜像日历本及其日程。\n\n'
|
||||||
|
+ '只影响系统日历:你的 CalDAV 账号与服务器上的日程完全不受影响。\n'
|
||||||
|
+ '清除后系统日历里不再显示这些日程,也不再提醒;镜像开关会一并关闭。\n\n'
|
||||||
|
+ '准备卸载本应用时,请先点这里清干净(卸载时系统不会自动清除)。',
|
||||||
|
autoCancel: true,
|
||||||
|
alignment: DialogAlignment.Center,
|
||||||
|
primaryButton: {
|
||||||
|
value: '取消',
|
||||||
|
action: (): void => {
|
||||||
|
}
|
||||||
|
},
|
||||||
|
secondaryButton: {
|
||||||
|
value: '确认清除',
|
||||||
|
action: (): void => {
|
||||||
|
this.doWipeAllMirrors();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async doWipeAllMirrors(): Promise<void> {
|
||||||
|
if (this.context === undefined || this.wipeAllRunning) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.wipeAllRunning = true;
|
||||||
|
try {
|
||||||
|
const n: number = await SystemCalendarMirror.removeAll(this.context);
|
||||||
|
// ⭐ 必须同时把"镜像开关"关掉并落库:否则下一轮同步会立刻按勾选重新建回来,
|
||||||
|
// 用户会以为"清了等于没清"。
|
||||||
|
this.mirrorEnabled = false;
|
||||||
|
await AppSettings.setMirrorEnabled(this.context, false);
|
||||||
|
// 镜像本没了 → 提醒要交回 App 负责,否则这些本会既没系统提醒、也没 App 提醒(漏提醒)
|
||||||
|
ReminderService.invalidateMirrorCache();
|
||||||
|
await ReminderService.refreshReminders(this.context as common.UIAbilityContext);
|
||||||
|
// ⭐ 清空结果必须说清楚:用户点这个按钮就是为了"确认卸载后不留东西",
|
||||||
|
// 所以"0 个"也要区分是权限没给(没清成)还是本来就干净(放心)
|
||||||
|
const granted: boolean = await SystemCalendarMirror.hasPermission();
|
||||||
|
let msg: string = '';
|
||||||
|
if (n > 0) {
|
||||||
|
msg = `已清除 ${n} 个镜像日历本,系统日历中不再有本应用的日程;镜像开关已关闭`;
|
||||||
|
} else if (!granted) {
|
||||||
|
msg = '未授予"写入系统日历"权限,无法清除。请先在设置中允许本应用读写日历后重试';
|
||||||
|
} else {
|
||||||
|
msg = '系统日历中已没有本应用的镜像数据,无需清除';
|
||||||
|
}
|
||||||
|
this.getUIContext().getPromptAction().showToast({ message: msg, duration: 5000 });
|
||||||
|
} catch (err) {
|
||||||
|
const e = err as BusinessError;
|
||||||
|
this.getUIContext().getPromptAction().showToast({
|
||||||
|
message: `清除失败:${e.message ?? '请确认已授予"写入系统日历"权限'}`
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
this.wipeAllRunning = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async saveInterval(minutes: number): Promise<void> {
|
private async saveInterval(minutes: number): Promise<void> {
|
||||||
if (this.context === undefined) {
|
if (this.context === undefined) {
|
||||||
return;
|
return;
|
||||||
@@ -1163,6 +1239,7 @@ struct SettingsPage {
|
|||||||
this.runMirrorNow();
|
this.runMirrorNow();
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
Button(this.purgeRunning ? '正在清理…' : '清理残留镜像账户(诊断)')
|
Button(this.purgeRunning ? '正在清理…' : '清理残留镜像账户(诊断)')
|
||||||
.fontSize(13)
|
.fontSize(13)
|
||||||
.fontColor($r('app.color.brand_text'))
|
.fontColor($r('app.color.brand_text'))
|
||||||
@@ -1206,6 +1283,82 @@ struct SettingsPage {
|
|||||||
.backgroundColor($r('app.color.card_bg'))
|
.backgroundColor($r('app.color.card_bg'))
|
||||||
.border({ width: 1, color: $r('app.color.shadow_color') })
|
.border({ width: 1, color: $r('app.color.shadow_color') })
|
||||||
|
|
||||||
|
// ⭐ WIPE_CARD_MOVED:数据清除独立成卡(不依赖镜像开关是否开启)
|
||||||
|
// 鸿蒙没有"应用即将被卸载"的回调,而系统日历属于沙箱外的系统数据,
|
||||||
|
// 卸载时不会自动清理 ⇒ 必须提供显式入口,让用户卸载前主动清干净。
|
||||||
|
Column({ space: 8 }) {
|
||||||
|
Row({ space: 10 }) {
|
||||||
|
Column({ space: 2 }) {
|
||||||
|
Text('清除系统日历数据')
|
||||||
|
.fontSize(15)
|
||||||
|
.fontWeight(FontWeight.Medium)
|
||||||
|
.fontColor($r('app.color.text_primary'))
|
||||||
|
Text('卸载本应用前请先清除,否则系统日历里会一直留着这些日程(还会提醒)')
|
||||||
|
.fontSize(12)
|
||||||
|
.fontColor($r('app.color.text_secondary'))
|
||||||
|
}
|
||||||
|
.alignItems(HorizontalAlign.Start)
|
||||||
|
.layoutWeight(1)
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
|
||||||
|
Button(this.wipeAllRunning ? '正在清除…' : '彻底清除系统日历镜像数据')
|
||||||
|
.fontSize(14)
|
||||||
|
.fontColor($r('app.color.error'))
|
||||||
|
.backgroundColor(Color.Transparent)
|
||||||
|
.border({ width: 1, color: $r('app.color.error') })
|
||||||
|
.width('100%')
|
||||||
|
.enabled(!this.wipeAllRunning)
|
||||||
|
.onClick(() => {
|
||||||
|
this.confirmWipeAllMirrors();
|
||||||
|
})
|
||||||
|
|
||||||
|
Text('只删系统日历里的镜像本;CalDAV 账号与服务器上的日程一条都不会少。清除后镜像开关会自动关闭。')
|
||||||
|
.fontSize(11)
|
||||||
|
.fontColor($r('app.color.text_hint'))
|
||||||
|
.width('100%')
|
||||||
|
|
||||||
|
Button(this.purgeRunning ? '正在清理…' : '清理残留镜像账户(诊断)')
|
||||||
|
.fontSize(13)
|
||||||
|
.fontColor($r('app.color.brand_text'))
|
||||||
|
.backgroundColor(Color.Transparent)
|
||||||
|
.width('100%')
|
||||||
|
.enabled(!this.purgeRunning)
|
||||||
|
.onClick(() => {
|
||||||
|
this.runPurgeOrphans();
|
||||||
|
})
|
||||||
|
|
||||||
|
if (this.accountDump !== '') {
|
||||||
|
Column({ space: 4 }) {
|
||||||
|
Text('系统日历账户清单(MINE=我们建的,KEEP=本次保留;长按可复制):')
|
||||||
|
.fontSize(11)
|
||||||
|
.fontColor($r('app.color.text_secondary'))
|
||||||
|
.width('100%')
|
||||||
|
Scroll() {
|
||||||
|
Text(this.accountDump)
|
||||||
|
.fontSize(10)
|
||||||
|
.lineHeight(14)
|
||||||
|
.fontColor($r('app.color.text_primary'))
|
||||||
|
.copyOption(CopyOptions.LocalDevice)
|
||||||
|
.width('100%')
|
||||||
|
}
|
||||||
|
.height(150)
|
||||||
|
.width('100%')
|
||||||
|
.backgroundColor($r('app.color.page_bg'))
|
||||||
|
.borderRadius(8)
|
||||||
|
.padding(6)
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
.padding({ top: 4 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.alignItems(HorizontalAlign.Start)
|
||||||
|
.width('100%')
|
||||||
|
.padding(14)
|
||||||
|
.borderRadius(12)
|
||||||
|
.backgroundColor($r('app.color.card_bg'))
|
||||||
|
.border({ width: 1, color: $r('app.color.shadow_color') })
|
||||||
|
|
||||||
// 默认视图:打开 App 后默认展示的视图(月/周/列表)
|
// 默认视图:打开 App 后默认展示的视图(月/周/列表)
|
||||||
Column({ space: 8 }) {
|
Column({ space: 8 }) {
|
||||||
Row({ space: 10 }) {
|
Row({ space: 10 }) {
|
||||||
|
|||||||
@@ -44,26 +44,6 @@
|
|||||||
],
|
],
|
||||||
"when": "inuse"
|
"when": "inuse"
|
||||||
}
|
}
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "ohos.permission.LOCATION",
|
|
||||||
"reason": "$string:perm_location",
|
|
||||||
"usedScene": {
|
|
||||||
"abilities": [
|
|
||||||
"EntryAbility"
|
|
||||||
],
|
|
||||||
"when": "inuse"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "ohos.permission.APPROXIMATELY_LOCATION",
|
|
||||||
"reason": "$string:perm_location_approx",
|
|
||||||
"usedScene": {
|
|
||||||
"abilities": [
|
|
||||||
"EntryAbility"
|
|
||||||
],
|
|
||||||
"when": "inuse"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"deliveryWithInstall": true,
|
"deliveryWithInstall": true,
|
||||||
|
|||||||
@@ -24,14 +24,6 @@
|
|||||||
"name": "perm_read_whole_calendar",
|
"name": "perm_read_whole_calendar",
|
||||||
"value": "读取所有日历账户的日程,用于在日历中统一展示"
|
"value": "读取所有日历账户的日程,用于在日历中统一展示"
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"name": "perm_location",
|
|
||||||
"value": "将日程中的地址转换为坐标,用于发起高德地图导航"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "perm_location_approx",
|
|
||||||
"value": "将日程中的地址转换为坐标,用于发起高德地图导航"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"name": "card_ability_desc",
|
"name": "card_ability_desc",
|
||||||
"value": "同步日历服务卡片"
|
"value": "同步日历服务卡片"
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
// 验证 IcsUtil.rewriteTodoCompletion(第二版:按结构定位插入点)
|
||||||
|
function fmtUtcNow() {
|
||||||
|
return new Date().toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
|
||||||
|
}
|
||||||
|
|
||||||
|
function rewrite(ics, uid, done) {
|
||||||
|
const crlf = '\r\n';
|
||||||
|
const unfolded = ics.replace(/\r?\n[ \t]/g, '');
|
||||||
|
const lines = unfolded.split(/\r?\n/).map(s => s.replace(/\r$/, ''));
|
||||||
|
const upperOf = s => s.toUpperCase();
|
||||||
|
const nowUtc = fmtUtcNow();
|
||||||
|
|
||||||
|
let targetBegin = -1, targetEnd = -1, targetOrdinal = -1;
|
||||||
|
let curBegin = -1, curHasUid = false, blockIdx = -1;
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const u = upperOf(lines[i]);
|
||||||
|
if (u.startsWith('BEGIN:VTODO')) { blockIdx++; curBegin = i; curHasUid = false; continue; }
|
||||||
|
if (u.startsWith('UID:') && curBegin >= 0) {
|
||||||
|
if (lines[i].substring(4).trim() === uid) curHasUid = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (u.startsWith('END:VTODO')) {
|
||||||
|
if (curBegin >= 0 && curHasUid && targetBegin < 0) {
|
||||||
|
targetBegin = curBegin; targetEnd = i; targetOrdinal = blockIdx;
|
||||||
|
}
|
||||||
|
curBegin = -1; curHasUid = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (targetBegin < 0) return ics;
|
||||||
|
|
||||||
|
const out = [];
|
||||||
|
let sawStatus = false, sawPercent = false;
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const line = lines[i], u = upperOf(line);
|
||||||
|
if (!(i > targetBegin && i < targetEnd)) { out.push(line); continue; }
|
||||||
|
if (u.startsWith('STATUS:')) { sawStatus = true; out.push(done ? 'STATUS:COMPLETED' : 'STATUS:NEEDS-ACTION'); continue; }
|
||||||
|
if (u.startsWith('COMPLETED')) { continue; }
|
||||||
|
if (u.startsWith('PERCENT-COMPLETE')) { sawPercent = true; out.push(done ? 'PERCENT-COMPLETE:100' : 'PERCENT-COMPLETE:0'); continue; }
|
||||||
|
out.push(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
const extra = [];
|
||||||
|
if (!sawStatus) extra.push(done ? 'STATUS:COMPLETED' : 'STATUS:NEEDS-ACTION');
|
||||||
|
if (done) extra.push('COMPLETED:' + nowUtc);
|
||||||
|
if (!sawPercent) extra.push(done ? 'PERCENT-COMPLETE:100' : 'PERCENT-COMPLETE:0');
|
||||||
|
if (extra.length === 0) {
|
||||||
|
const plain = out.join(crlf);
|
||||||
|
return plain.endsWith(crlf) ? plain : plain + crlf;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = [];
|
||||||
|
let vtodoIdx = -1, inserted = false;
|
||||||
|
for (let i = 0; i < out.length; i++) {
|
||||||
|
const u = upperOf(out[i]);
|
||||||
|
if (u.startsWith('BEGIN:VTODO')) { vtodoIdx++; result.push(out[i]); continue; }
|
||||||
|
if (u.startsWith('END:VTODO')) {
|
||||||
|
if (!inserted && vtodoIdx === targetOrdinal) {
|
||||||
|
for (const ex of extra) result.push(ex);
|
||||||
|
inserted = true;
|
||||||
|
}
|
||||||
|
vtodoIdx = -1; result.push(out[i]); continue;
|
||||||
|
}
|
||||||
|
result.push(out[i]);
|
||||||
|
}
|
||||||
|
if (!inserted) {
|
||||||
|
const tail0 = result.join(crlf);
|
||||||
|
const idxVc = tail0.lastIndexOf('END:VCALENDAR');
|
||||||
|
if (idxVc > 0) {
|
||||||
|
const merged = tail0.substring(0, idxVc) + extra.join(crlf) + crlf + tail0.substring(idxVc);
|
||||||
|
return merged.endsWith(crlf) ? merged : merged + crlf;
|
||||||
|
}
|
||||||
|
for (const ex of extra) result.push(ex);
|
||||||
|
}
|
||||||
|
const text2 = result.join(crlf);
|
||||||
|
return text2.endsWith(crlf) ? text2 : text2 + crlf;
|
||||||
|
}
|
||||||
|
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
function assert(name, cond, detail) {
|
||||||
|
if (cond) { console.log(' ✅', name); pass++; }
|
||||||
|
else { console.log(' ❌', name, detail || ''); fail++; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 关键结构校验:任何字段都不能跑到 END:VCALENDAR 之后 */
|
||||||
|
function structureIntact(ics) {
|
||||||
|
const iEnd = ics.indexOf('END:VCALENDAR');
|
||||||
|
if (iEnd < 0) return false;
|
||||||
|
const after = ics.substring(iEnd + 'END:VCALENDAR'.length).replace(/[\r\n]/g, '');
|
||||||
|
return after === ''; // END:VCALENDAR 之后不应有任何内容
|
||||||
|
}
|
||||||
|
function balanced(ics, tag) {
|
||||||
|
const b = (ics.match(new RegExp('BEGIN:' + tag, 'g')) || []).length;
|
||||||
|
const e = (ics.match(new RegExp('END:' + tag, 'g')) || []).length;
|
||||||
|
return b === e;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. STATUS 在 UID 之前(触发补字段的路径)
|
||||||
|
const ics1 = 'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VTODO\r\nDTSTAMP:20260101T000000Z\r\nSTATUS:NEEDS-ACTION\r\nSUMMARY:买菜\r\nUID:todo-abc-123\r\nDUE:20260105T090000Z\r\nEND:VTODO\r\nEND:VCALENDAR\r\n';
|
||||||
|
const r1 = rewrite(ics1, 'todo-abc-123', true);
|
||||||
|
assert('STATUS 在 UID 之前 → COMPLETED', r1.includes('STATUS:COMPLETED'));
|
||||||
|
assert('旧状态消失', !r1.includes('STATUS:NEEDS-ACTION'));
|
||||||
|
assert('有 COMPLETED 时间戳', /COMPLETED:\d{8}T\d{6}Z/.test(r1));
|
||||||
|
assert('补 PERCENT-COMPLETE:100', r1.includes('PERCENT-COMPLETE:100'));
|
||||||
|
assert('保留 SUMMARY', r1.includes('SUMMARY:买菜'));
|
||||||
|
assert('保留 DUE', r1.includes('DUE:20260105T090000Z'));
|
||||||
|
assert('⭐ 结构完整(END:VCALENDAR 后无残留)', structureIntact(r1), JSON.stringify(r1.slice(r1.indexOf('END:VCALENDAR'))));
|
||||||
|
assert('BEGIN/END VTODO 配对', balanced(r1, 'VTODO'));
|
||||||
|
|
||||||
|
// 2. UID 在前 + 已有 STATUS/PERCENT(不触发补字段)
|
||||||
|
const ics2 = 'BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nUID:todo-xyz\r\nDTSTAMP:20260101T000000Z\r\nSUMMARY:写报告\r\nPRIORITY:1\r\nSTATUS:NEEDS-ACTION\r\nPERCENT-COMPLETE:0\r\nEND:VTODO\r\nEND:VCALENDAR\r\n';
|
||||||
|
const r2 = rewrite(ics2, 'todo-xyz', true);
|
||||||
|
assert('UID 在前 → COMPLETED', r2.includes('STATUS:COMPLETED'));
|
||||||
|
assert('PERCENT 改 100', r2.includes('PERCENT-COMPLETE:100'));
|
||||||
|
assert('保留 SUMMARY/PRIORITY', r2.includes('SUMMARY:写报告') && r2.includes('PRIORITY:1'));
|
||||||
|
assert('⭐ 结构完整', structureIntact(r2));
|
||||||
|
assert('COMPLETED 时间戳在 VTODO 内部', (() => {
|
||||||
|
const body = r2.substring(r2.indexOf('BEGIN:VTODO'), r2.indexOf('END:VTODO'));
|
||||||
|
return /COMPLETED:\d{8}/.test(body);
|
||||||
|
})());
|
||||||
|
|
||||||
|
// 3. 取消完成
|
||||||
|
const ics3 = 'BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nUID:todo-xyz\r\nSTATUS:COMPLETED\r\nCOMPLETED:20260101T000000Z\r\nPERCENT-COMPLETE:100\r\nSUMMARY:写报告\r\nEND:VTODO\r\nEND:VCALENDAR\r\n';
|
||||||
|
const r3 = rewrite(ics3, 'todo-xyz', false);
|
||||||
|
assert('取消完成 → NEEDS-ACTION', r3.includes('STATUS:NEEDS-ACTION'));
|
||||||
|
assert('PERCENT 回 0', r3.includes('PERCENT-COMPLETE:0'));
|
||||||
|
assert('COMPLETED 行被移除', !/COMPLETED:\d{8}/.test(r3));
|
||||||
|
assert('⭐ 结构完整', structureIntact(r3));
|
||||||
|
|
||||||
|
// 4. uid 不匹配 → 原文不动
|
||||||
|
assert('uid 不匹配 → 原文不变', rewrite(ics1, 'nope', true) === ics1);
|
||||||
|
|
||||||
|
// 5. 多 VTODO 只改目标
|
||||||
|
const ics5 = 'BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nUID:a1\r\nSUMMARY:第一个\r\nSTATUS:NEEDS-ACTION\r\nEND:VTODO\r\nBEGIN:VTODO\r\nUID:a2\r\nSUMMARY:第二个\r\nSTATUS:NEEDS-ACTION\r\nEND:VTODO\r\nEND:VCALENDAR\r\n';
|
||||||
|
const r5 = rewrite(ics5, 'a2', true);
|
||||||
|
assert('多 VTODO:a1 未动', r5.split('UID:a1')[1].split('END:VTODO')[0].includes('STATUS:NEEDS-ACTION'));
|
||||||
|
assert('多 VTODO:a2 已改', r5.split('UID:a2')[1].split('END:VTODO')[0].includes('STATUS:COMPLETED'));
|
||||||
|
assert('⭐ 多 VTODO 结构完整', structureIntact(r5));
|
||||||
|
assert('两个 VTODO 都配对', balanced(r5, 'VTODO'));
|
||||||
|
|
||||||
|
// 6. 目标 VTODO 缺 STATUS(走"补字段"最极端路径)
|
||||||
|
const ics6 = 'BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nUID:bare\r\nSUMMARY:没有状态字段\r\nEND:VTODO\r\nEND:VCALENDAR\r\n';
|
||||||
|
const r6 = rewrite(ics6, 'bare', true);
|
||||||
|
assert('缺 STATUS 时能补上', r6.includes('STATUS:COMPLETED'));
|
||||||
|
assert('⭐ 补在 VTODO 内而非 VCALENDAR 后', structureIntact(r6) && (() => {
|
||||||
|
const body = r6.substring(r6.indexOf('BEGIN:VTODO'), r6.indexOf('END:VTODO'));
|
||||||
|
return body.includes('STATUS:COMPLETED');
|
||||||
|
})());
|
||||||
|
|
||||||
|
// 7. 折行保留
|
||||||
|
const ics7 = 'BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nUID:long\r\nSUMMARY:很长的标题\r\n 需要折行\r\nSTATUS:NEEDS-ACTION\r\nEND:VTODO\r\nEND:VCALENDAR\r\n';
|
||||||
|
assert('折行被还原保留', rewrite(ics7, 'long', true).includes('很长的标题需要折行'));
|
||||||
|
|
||||||
|
// 8. 末尾多个空行也不应让结构崩
|
||||||
|
const ics8 = ics1 + '\r\n\r\n';
|
||||||
|
assert('⭐ 尾部空行场景结构完整', structureIntact(rewrite(ics8, 'todo-abc-123', true)));
|
||||||
|
|
||||||
|
console.log(`\n结果:通过 ${pass},失败 ${fail}`);
|
||||||
|
console.log('\n--- 测试1 输出 ---');
|
||||||
|
console.log(r1.replace(/\r\n/g, '\n'));
|
||||||
|
console.log('--- 测试6 输出(最极端:无 STATUS)---');
|
||||||
|
console.log(r6.replace(/\r\n/g, '\n'));
|
||||||
|
process.exit(fail === 0 ? 0 : 1);
|
||||||
Reference in New Issue
Block a user