Compare commits

..

53 Commits

Author SHA1 Message Date
fish 1a525c763e 归档笔记保留 Note 格式化操作
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-17 22:33:41 +08:00
fish a0dffdc715 增大收集箱列表文案与时间间距 2026-07-16 21:46:43 +08:00
fish 4765d48021 收集箱列表展示完整文案 2026-07-16 21:44:51 +08:00
fish f888e28d15 添加简体中文本地化支持 2026-07-16 21:38:07 +08:00
fish c934dbad84 调整完成按钮与键盘的间距 2026-07-16 21:35:40 +08:00
fish 4088db8ec0 编辑页完成按钮改为玻璃浮动效果 2026-07-16 21:26:36 +08:00
fish 255f171aa8 编辑页键盘增加完成按钮 2026-07-16 21:19:29 +08:00
fish 70870e1ec2 编辑页增加键盘遮挡处理 2026-07-16 21:13:52 +08:00
fish f1a380d105 保存失败时返回具体错误信息 2026-07-15 23:55:36 +08:00
fish 01ad237af3 修复 TextFormatter actor 隔离警告 2026-07-15 23:47:47 +08:00
fish 7d49f7d5a4 预置快捷指令自动读取剪贴板 2026-07-15 23:43:22 +08:00
fish 87eb958869 添加预置快捷指令 2026-07-15 23:39:15 +08:00
fish 4340fd3635 修复编译警告 2026-07-15 23:33:33 +08:00
fish ac2eac5fcd 修复收集箱后台返回不刷新 2026-07-15 23:22:37 +08:00
fish a386802a55 快捷指令预处理去掉标题前缀 2026-07-15 23:19:32 +08:00
fish 1f94b9884c 快捷指令保存文案前使用 iCloud 格式化预处理 2026-07-15 23:15:55 +08:00
fish 58a8d27315 归档增加标题并统一分隔符 2026-07-15 23:11:05 +08:00
fish 7f4fc34dbf 收集箱增加归档功能 2026-07-15 23:04:20 +08:00
fish 5af8038ec0 收集箱使用独立编辑页 2026-07-15 22:57:00 +08:00
fish 1ff250fa17 过滤剪贴板无效占位符 2026-07-15 22:51:42 +08:00
fish 42e647c932 修复后台返回首页收集箱数量不刷新 2026-07-15 22:49:26 +08:00
fish 080c7f00ce 首页菜单支持自定义排序 2026-07-15 22:46:56 +08:00
fish 545e023ffc 修复收集箱有内容时无法进入 2026-07-15 22:43:45 +08:00
fish 10ba84e349 修复快捷指令运行时崩溃 2026-07-15 22:40:19 +08:00
fish adf13ae47c 重置按钮增加确认弹窗 2026-07-15 22:31:16 +08:00
fish 6c62d4bce4 修复清空按钮在暗夜模式下显示为灰色 2026-07-15 22:26:20 +08:00
fish 000a56295f 添加项目说明与编译命令 2026-07-15 22:22:30 +08:00
fish bbd4f0e266 添加收集箱与快捷指令保存功能 2026-07-15 22:19:36 +08:00
fish 423132699e 调整分享扩展配置 2026-07-14 22:50:29 +08:00
fish 505777a40e 修改分享扩展 Bundle ID 2026-07-14 22:38:35 +08:00
fish 3dccd16757 增加 Markdown 文件分享支持 2026-07-14 22:29:58 +08:00
fish e19dba594c 优化 Markdown 文件打开方式注册 2026-07-13 22:37:13 +08:00
fish 73154aad08 修复 Markdown 文件打开方式中未显示 App 的问题 2026-07-13 22:29:55 +08:00
fish 28ec64f8e6 更新应用图标 2026-07-13 22:18:23 +08:00
fish 99b014190d 支持外部 Markdown 文件预览与格式化分发 2026-07-13 22:17:12 +08:00
fish df7e74b10e 添加键盘上方浮动完成按钮 2026-07-13 22:01:16 +08:00
fish 51fb757143 修复键盘弹起时遮挡底部文本的问题 2026-07-13 21:30:10 +08:00
fish d4783d7438 Note格式化去除末尾空白并确保标题后两行间距 2026-07-12 22:49:05 +08:00
fish 195483b3e1 Note格式化按---分段并移除句间空行 2026-07-12 22:41:36 +08:00
fish e01404f18e 恢复iCloud格式化原始逻辑 2026-07-12 22:38:44 +08:00
fish 8d117f7f97 iCloud格式化保留段落结构以配合Note格式化 2026-07-12 22:35:50 +08:00
fish 0c14b89125 修复Note格式化段落结构失真 2026-07-12 22:32:09 +08:00
fish d2aa860bc3 Note格式化后按钮变为复制并打开备忘录 2026-07-12 22:29:17 +08:00
fish e86c5e183c Note格式化段落之间改为两行间距 2026-07-12 22:27:35 +08:00
fish 2553894db4 打开文件改为跳转系统文件应用 2026-07-12 22:13:03 +08:00
fish 87deb5d9f2 格式化文本框背景浅色固定白色深色使用次级背景 2026-07-12 22:07:55 +08:00
fish b31ffc1c83 格式化页面文本框添加系统分隔线边框 2026-07-12 21:57:24 +08:00
fish e55f84dd97 格式化文本框使用系统背景色适配深色模式 2026-07-12 21:53:33 +08:00
fish 657442249a 设置应用显示名称 2026-07-12 21:48:55 +08:00
fish 24b69cf72f 声明应用不使用非豁免加密以消除出口合规警告 2026-07-12 21:48:32 +08:00
fish a76be6e871 首页新增打开文件入口 2026-07-12 21:41:02 +08:00
fish 4c7d063a94 同步 Xcode 版本号格式 2026-07-12 21:38:26 +08:00
fish 401a6dafc8 格式化操作增加空内容拦截和 Alert 提示 2026-07-12 21:36:41 +08:00
28 changed files with 2004 additions and 128 deletions
+16
View File
@@ -0,0 +1,16 @@
# 项目说明
## 构建与测试环境
- 开发设备:macOS
- Xcode 版本:26.3
- 主 App Deployment TargetiOS 26.0
- 可用的 iOS 模拟器:**iPhone 17 Pro**
## 常用命令
### 编译主 AppiPhone 17 Pro 模拟器)
```bash
xcodebuild -scheme Note -destination 'platform=iOS Simulator,name=iPhone 17 Pro' build
```
+181 -2
View File
@@ -6,8 +6,37 @@
objectVersion = 77; objectVersion = 77;
objects = { objects = {
/* Begin PBXBuildFile section */
CFD40B353003C283009C9F2A /* NoteShareExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = CFD40B283003C283009C9F2A /* NoteShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
CFD40B313003C283009C9F2A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = CFD40B083003C283009C9F2A /* Project object */;
proxyType = 1;
remoteGlobalIDString = CFD40B293003C283009C9F2A;
remoteInfo = NoteShareExtension;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
CFD40B2F3003C283009C9F2A /* Embed Foundation Extensions */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 16;
files = (
CFD40B353003C283009C9F2A /* NoteShareExtension.appex in Embed Foundation Extensions */,
);
name = "Embed Foundation Extensions";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
CFD40B103003C283009C9F2A /* Note.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Note.app; sourceTree = BUILT_PRODUCTS_DIR; }; CFD40B103003C283009C9F2A /* Note.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Note.app; sourceTree = BUILT_PRODUCTS_DIR; };
CFD40B283003C283009C9F2A /* NoteShareExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = NoteShareExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */ /* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ /* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
@@ -18,6 +47,13 @@
); );
target = CFD40B0F3003C283009C9F2A /* Note */; target = CFD40B0F3003C283009C9F2A /* Note */;
}; };
CFD40B2E3003C283009C9F2A /* Exceptions for "NoteShareExtension" folder in "NoteShareExtension" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
);
target = CFD40B293003C283009C9F2A /* NoteShareExtension */;
};
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ /* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */ /* Begin PBXFileSystemSynchronizedRootGroup section */
@@ -29,6 +65,14 @@
path = Note; path = Note;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
CFD40B2D3003C283009C9F2A /* NoteShareExtension */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
CFD40B2E3003C283009C9F2A /* Exceptions for "NoteShareExtension" folder in "NoteShareExtension" target */,
);
path = NoteShareExtension;
sourceTree = "<group>";
};
/* End PBXFileSystemSynchronizedRootGroup section */ /* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */ /* Begin PBXFrameworksBuildPhase section */
@@ -39,6 +83,13 @@
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
CFD40B323003C283009C9F2A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */ /* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */ /* Begin PBXGroup section */
@@ -46,6 +97,7 @@
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
CFD40B123003C283009C9F2A /* Note */, CFD40B123003C283009C9F2A /* Note */,
CFD40B2D3003C283009C9F2A /* NoteShareExtension */,
CFD40B113003C283009C9F2A /* Products */, CFD40B113003C283009C9F2A /* Products */,
); );
sourceTree = "<group>"; sourceTree = "<group>";
@@ -54,6 +106,7 @@
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
CFD40B103003C283009C9F2A /* Note.app */, CFD40B103003C283009C9F2A /* Note.app */,
CFD40B283003C283009C9F2A /* NoteShareExtension.appex */,
); );
name = Products; name = Products;
sourceTree = "<group>"; sourceTree = "<group>";
@@ -68,10 +121,12 @@
CFD40B0C3003C283009C9F2A /* Sources */, CFD40B0C3003C283009C9F2A /* Sources */,
CFD40B0D3003C283009C9F2A /* Frameworks */, CFD40B0D3003C283009C9F2A /* Frameworks */,
CFD40B0E3003C283009C9F2A /* Resources */, CFD40B0E3003C283009C9F2A /* Resources */,
CFD40B2F3003C283009C9F2A /* Embed Foundation Extensions */,
); );
buildRules = ( buildRules = (
); );
dependencies = ( dependencies = (
CFD40B303003C283009C9F2A /* PBXTargetDependency */,
); );
fileSystemSynchronizedGroups = ( fileSystemSynchronizedGroups = (
CFD40B123003C283009C9F2A /* Note */, CFD40B123003C283009C9F2A /* Note */,
@@ -83,6 +138,28 @@
productReference = CFD40B103003C283009C9F2A /* Note.app */; productReference = CFD40B103003C283009C9F2A /* Note.app */;
productType = "com.apple.product-type.application"; productType = "com.apple.product-type.application";
}; };
CFD40B293003C283009C9F2A /* NoteShareExtension */ = {
isa = PBXNativeTarget;
buildConfigurationList = CFD40B2A3003C283009C9F2A /* Build configuration list for PBXNativeTarget "NoteShareExtension" */;
buildPhases = (
CFD40B333003C283009C9F2A /* Sources */,
CFD40B343003C283009C9F2A /* Resources */,
CFD40B323003C283009C9F2A /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
fileSystemSynchronizedGroups = (
CFD40B2D3003C283009C9F2A /* NoteShareExtension */,
);
name = NoteShareExtension;
packageProductDependencies = (
);
productName = NoteShareExtension;
productReference = CFD40B283003C283009C9F2A /* NoteShareExtension.appex */;
productType = "com.apple.product-type.app-extension";
};
/* End PBXNativeTarget section */ /* End PBXNativeTarget section */
/* Begin PBXProject section */ /* Begin PBXProject section */
@@ -96,6 +173,9 @@
CFD40B0F3003C283009C9F2A = { CFD40B0F3003C283009C9F2A = {
CreatedOnToolsVersion = 26.3; CreatedOnToolsVersion = 26.3;
}; };
CFD40B293003C283009C9F2A = {
CreatedOnToolsVersion = 26.3;
};
}; };
}; };
buildConfigurationList = CFD40B0B3003C283009C9F2A /* Build configuration list for PBXProject "Note" */; buildConfigurationList = CFD40B0B3003C283009C9F2A /* Build configuration list for PBXProject "Note" */;
@@ -104,6 +184,7 @@
knownRegions = ( knownRegions = (
en, en,
Base, Base,
"zh-Hans",
); );
mainGroup = CFD40B073003C283009C9F2A; mainGroup = CFD40B073003C283009C9F2A;
minimizedProjectReferenceProxies = 1; minimizedProjectReferenceProxies = 1;
@@ -113,6 +194,7 @@
projectRoot = ""; projectRoot = "";
targets = ( targets = (
CFD40B0F3003C283009C9F2A /* Note */, CFD40B0F3003C283009C9F2A /* Note */,
CFD40B293003C283009C9F2A /* NoteShareExtension */,
); );
}; };
/* End PBXProject section */ /* End PBXProject section */
@@ -125,6 +207,13 @@
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
CFD40B343003C283009C9F2A /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */ /* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */
@@ -135,19 +224,36 @@
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
CFD40B333003C283009C9F2A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */ /* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
CFD40B303003C283009C9F2A /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = CFD40B293003C283009C9F2A /* NoteShareExtension */;
targetProxy = CFD40B313003C283009C9F2A /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */ /* Begin XCBuildConfiguration section */
CFD40B243003C284009C9F2A /* Debug */ = { CFD40B243003C284009C9F2A /* Debug */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = Note/Note.entitlements;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1; CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 37HGUEC495; DEVELOPMENT_TEAM = 37HGUEC495;
GENERATE_INFOPLIST_FILE = YES; GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = Note/Info.plist; INFOPLIST_FILE = Note/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "备忘录格式化助手";
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen;
INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait; INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait;
@@ -157,7 +263,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 1.0; MARKETING_VERSION = 1.0.0;
PRODUCT_BUNDLE_IDENTIFIER = com.fishestlife.note; PRODUCT_BUNDLE_IDENTIFIER = com.fishestlife.note;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = YES; STRING_CATALOG_GENERATE_SYMBOLS = YES;
@@ -175,11 +281,13 @@
buildSettings = { buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = Note/Note.entitlements;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1; CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 37HGUEC495; DEVELOPMENT_TEAM = 37HGUEC495;
GENERATE_INFOPLIST_FILE = YES; GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = Note/Info.plist; INFOPLIST_FILE = Note/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "备忘录格式化助手";
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen;
INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait; INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait;
@@ -189,7 +297,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 1.0; MARKETING_VERSION = 1.0.0;
PRODUCT_BUNDLE_IDENTIFIER = com.fishestlife.note; PRODUCT_BUNDLE_IDENTIFIER = com.fishestlife.note;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
STRING_CATALOG_GENERATE_SYMBOLS = YES; STRING_CATALOG_GENERATE_SYMBOLS = YES;
@@ -323,6 +431,68 @@
}; };
name = Release; name = Release;
}; };
CFD40B2B3003C283009C9F2A /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_OBJC_WEAK = YES;
CODE_SIGN_ENTITLEMENTS = NoteShareExtension/NoteShareExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 37HGUEC495;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = NoteShareExtension/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "备忘录格式化助手";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
IPHONEOS_DEPLOYMENT_TARGET = 26.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.0.0;
PRODUCT_BUNDLE_IDENTIFIER = com.fishestlife.note.share;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
CFD40B2C3003C283009C9F2A /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_OBJC_WEAK = YES;
CODE_SIGN_ENTITLEMENTS = NoteShareExtension/NoteShareExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 37HGUEC495;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = NoteShareExtension/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "备忘录格式化助手";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
IPHONEOS_DEPLOYMENT_TARGET = 26.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.0.0;
PRODUCT_BUNDLE_IDENTIFIER = com.fishestlife.note.share;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */ /* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */ /* Begin XCConfigurationList section */
@@ -344,6 +514,15 @@
defaultConfigurationIsVisible = 0; defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release; defaultConfigurationName = Release;
}; };
CFD40B2A3003C283009C9F2A /* Build configuration list for PBXNativeTarget "NoteShareExtension" */ = {
isa = XCConfigurationList;
buildConfigurations = (
CFD40B2B3003C283009C9F2A /* Debug */,
CFD40B2C3003C283009C9F2A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */ /* End XCConfigurationList section */
}; };
rootObject = CFD40B083003C283009C9F2A /* Project object */; rootObject = CFD40B083003C283009C9F2A /* Project object */;
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CFD40B0F3003C283009C9F2A"
BuildableName = "Note.app"
BlueprintName = "Note"
ReferencedContainer = "container:Note.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CFD40B0F3003C283009C9F2A"
BuildableName = "Note.app"
BlueprintName = "Note"
ReferencedContainer = "container:Note.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CFD40B0F3003C283009C9F2A"
BuildableName = "Note.app"
BlueprintName = "Note"
ReferencedContainer = "container:Note.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,97 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2630"
wasCreatedForAppExtension = "YES"
version = "2.0">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CFD40B293003C283009C9F2A"
BuildableName = "NoteShareExtension.appex"
BlueprintName = "NoteShareExtension"
ReferencedContainer = "container:Note.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CFD40B0F3003C283009C9F2A"
BuildableName = "Note.app"
BlueprintName = "Note"
ReferencedContainer = "container:Note.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = ""
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
launchStyle = "0"
askForAppToLaunch = "Yes"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES"
launchAutomaticallySubstyle = "2">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CFD40B0F3003C283009C9F2A"
BuildableName = "Note.app"
BlueprintName = "Note"
ReferencedContainer = "container:Note.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES"
askForAppToLaunch = "Yes"
launchAutomaticallySubstyle = "2">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CFD40B0F3003C283009C9F2A"
BuildableName = "Note.app"
BlueprintName = "Note"
ReferencedContainer = "container:Note.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -1,7 +1,7 @@
{ {
"images" : [ "images" : [
{ {
"filename" : "note_app_logo_appstore 1.png", "filename" : "note_app_logo_full.png",
"idiom" : "universal", "idiom" : "universal",
"platform" : "ios", "platform" : "ios",
"size" : "1024x1024" "size" : "1024x1024"
@@ -13,7 +13,7 @@
"value" : "dark" "value" : "dark"
} }
], ],
"filename" : "note_app_logo_appstore 2.png", "filename" : "note_app_logo_full 1.png",
"idiom" : "universal", "idiom" : "universal",
"platform" : "ios", "platform" : "ios",
"size" : "1024x1024" "size" : "1024x1024"
@@ -25,7 +25,7 @@
"value" : "tinted" "value" : "tinted"
} }
], ],
"filename" : "note_app_logo_appstore.png", "filename" : "note_app_logo_full 2.png",
"idiom" : "universal", "idiom" : "universal",
"platform" : "ios", "platform" : "ios",
"size" : "1024x1024" "size" : "1024x1024"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

+167
View File
@@ -0,0 +1,167 @@
//
// ClipEditViewController.swift
// Note
//
// Created by Kimi Code CLI on 2026/7/15.
//
import UIKit
class ClipEditViewController: UIViewController {
private var textView: UITextView!
private var floatingDoneButton: UIButton!
private var floatingDoneButtonBottomConstraint: NSLayoutConstraint!
private var clip: Clip
init(clip: Clip) {
self.clip = clip
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "编辑文案"
navigationItem.largeTitleDisplayMode = .never
view.backgroundColor = .systemGroupedBackground
setupNavigationBar()
setupTextView()
setupKeyboardObservers()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func setupKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc private func keyboardWillShow(_ notification: Notification) {
guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
let keyboardFrameInView = view.convert(keyboardFrame, from: nil)
let intersection = keyboardFrameInView.intersection(view.bounds)
let keyboardHeight = intersection.height
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState) {
self.textView.contentInset.bottom = keyboardHeight
self.textView.verticalScrollIndicatorInsets.bottom = keyboardHeight
self.floatingDoneButtonBottomConstraint.constant = -(keyboardHeight + 8)
self.floatingDoneButton.alpha = 1
self.view.layoutIfNeeded()
}
}
@objc private func keyboardWillHide(_ notification: Notification) {
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState) {
self.textView.contentInset.bottom = 0
self.textView.verticalScrollIndicatorInsets.bottom = 0
self.floatingDoneButtonBottomConstraint.constant = -16
self.floatingDoneButton.alpha = 0
self.view.layoutIfNeeded()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textView.becomeFirstResponder()
}
private func setupNavigationBar() {
let saveButton = UIBarButtonItem(
title: "保存",
style: .prominent,
target: self,
action: #selector(didTapSaveButton)
)
navigationItem.rightBarButtonItem = saveButton
}
private func setupTextView() {
textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.backgroundColor = UIColor { traitCollection in
traitCollection.userInterfaceStyle == .dark ? .secondarySystemBackground : .white
}
textView.layer.cornerRadius = 12
textView.layer.borderWidth = 0.5
textView.layer.borderColor = UIColor.separator.cgColor
textView.layer.masksToBounds = true
textView.font = UIFont.preferredFont(forTextStyle: .body)
textView.textContainerInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
textView.text = clip.text
view.addSubview(textView)
var doneConfig = UIButton.Configuration.glass()
doneConfig.title = "完成"
doneConfig.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
return outgoing
}
doneConfig.baseForegroundColor = .label
doneConfig.cornerStyle = .capsule
doneConfig.contentInsets = NSDirectionalEdgeInsets(top: 15, leading: 22, bottom: 15, trailing: 22)
floatingDoneButton = UIButton(configuration: doneConfig)
floatingDoneButton.translatesAutoresizingMaskIntoConstraints = false
floatingDoneButton.alpha = 0
floatingDoneButton.addTarget(self, action: #selector(didTapFloatingDoneButton), for: .touchUpInside)
view.addSubview(floatingDoneButton)
let safeArea = view.safeAreaLayoutGuide
floatingDoneButtonBottomConstraint = floatingDoneButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16)
NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: safeArea.topAnchor, constant: 16),
textView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor, constant: 16),
textView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -16),
textView.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor, constant: -16),
floatingDoneButton.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -16),
floatingDoneButtonBottomConstraint
])
}
@objc private func didTapFloatingDoneButton() {
textView.resignFirstResponder()
}
@objc private func didTapSaveButton() {
let updatedText = textView.text ?? ""
guard !updatedText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
let alert = UIAlertController(title: "提示", message: "文案不能为空。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
present(alert, animated: true)
return
}
var updatedClip = clip
updatedClip.text = updatedText
Task {
do {
try await ClipStore.shared.update(updatedClip)
_ = await MainActor.run {
self.navigationController?.popViewController(animated: true)
return ()
}
} catch {
await MainActor.run {
let alert = UIAlertController(title: "提示", message: "保存失败: \(error.localizedDescription)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
self.present(alert, animated: true)
}
}
}
}
}
+290
View File
@@ -0,0 +1,290 @@
//
// ClipInboxViewController.swift
// Note
//
// Created by Kimi Code CLI on 2026/7/15.
//
import UIKit
class ClipInboxViewController: UIViewController {
private var tableView: UITableView!
private var emptyLabel: UILabel!
private var archiveButton: UIButton!
private var clips: [Clip] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "收集箱"
navigationItem.largeTitleDisplayMode = .never
view.backgroundColor = .systemGroupedBackground
setupNavigationBar()
setupArchiveButton()
setupTableView()
setupEmptyLabel()
setupAppStateObserver()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadClips()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func setupAppStateObserver() {
NotificationCenter.default.addObserver(
self,
selector: #selector(appDidBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil
)
}
@objc private func appDidBecomeActive() {
loadClips()
}
private func setupNavigationBar() {
let clearButton = UIBarButtonItem(
title: "清空",
style: .plain,
target: self,
action: #selector(didTapClearButton)
)
clearButton.tintColor = .systemRed
navigationItem.rightBarButtonItem = clearButton
}
private func setupTableView() {
tableView = UITableView(frame: .zero, style: .insetGrouped)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "clipCell")
tableView.backgroundColor = .systemGroupedBackground
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: archiveButton.topAnchor, constant: -16)
])
}
private func setupArchiveButton() {
var config = UIButton.Configuration.filled()
config.title = "归档"
config.baseBackgroundColor = .systemBlue
config.baseForegroundColor = .white
config.cornerStyle = .medium
config.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
archiveButton = UIButton(configuration: config)
archiveButton.translatesAutoresizingMaskIntoConstraints = false
archiveButton.addTarget(self, action: #selector(didTapArchiveButton), for: .touchUpInside)
view.addSubview(archiveButton)
NSLayoutConstraint.activate([
archiveButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16),
archiveButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
archiveButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -16),
archiveButton.heightAnchor.constraint(equalToConstant: 52)
])
}
@objc private func didTapArchiveButton() {
guard clips.count >= 2 else {
let alert = UIAlertController(title: "提示", message: "至少需要两条文案才能归档。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
present(alert, animated: true)
return
}
let title = self.archiveTitle()
let itemsText = clips.map { "\($0.text)\n\n---" }.joined(separator: "\n\n")
let archivedText = "\(title)\n\n\(itemsText)"
let viewController = FormatNoteViewController()
viewController.initialText = archivedText
navigationController?.pushViewController(viewController, animated: true)
}
private func archiveTitle() -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "zh_CN")
dateFormatter.dateFormat = "yyyy年MM月dd日"
let dateString = dateFormatter.string(from: Date())
let weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
let weekdayIndex = Calendar.current.component(.weekday, from: Date()) - 1
let weekday = (weekdayIndex >= 0 && weekdayIndex < weekdays.count) ? weekdays[weekdayIndex] : ""
return "【读书摘抄】\(dateString) \(weekday)"
}
private func setupEmptyLabel() {
emptyLabel = UILabel()
emptyLabel.translatesAutoresizingMaskIntoConstraints = false
emptyLabel.text = "还没有保存的文案\n复制内容后运行快捷指令即可收藏"
emptyLabel.numberOfLines = 0
emptyLabel.textAlignment = .center
emptyLabel.textColor = .secondaryLabel
emptyLabel.font = UIFont.preferredFont(forTextStyle: .body)
emptyLabel.isHidden = true
view.addSubview(emptyLabel)
NSLayoutConstraint.activate([
emptyLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
emptyLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
emptyLabel.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor),
emptyLabel.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor)
])
}
private func loadClips() {
Task {
do {
clips = try await ClipStore.shared.loadAll()
await MainActor.run {
tableView.reloadData()
updateEmptyState()
}
} catch {
await MainActor.run {
showError(message: "加载失败: \(error.localizedDescription)")
}
}
}
}
private func updateEmptyState() {
let isEmpty = clips.isEmpty
emptyLabel.isHidden = !isEmpty
tableView.isHidden = isEmpty
archiveButton.isHidden = isEmpty
}
@objc private func didTapClearButton() {
guard !clips.isEmpty else {
let alert = UIAlertController(title: "提示", message: "收集箱为空,没有可清空的内容。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
present(alert, animated: true)
return
}
let alert = UIAlertController(
title: "清空收集箱",
message: "确定要删除所有保存的文案吗?此操作不可撤销。",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "清空", style: .destructive) { [weak self] _ in
self?.clearAllClips()
})
present(alert, animated: true)
}
private func clearAllClips() {
Task {
do {
try await ClipStore.shared.clearAll()
clips = []
await MainActor.run {
tableView.reloadData()
updateEmptyState()
}
} catch {
await MainActor.run {
showError(message: "清空失败: \(error.localizedDescription)")
}
}
}
}
private func deleteClip(at indexPath: IndexPath) {
let clip = clips[indexPath.row]
Task {
do {
try await ClipStore.shared.delete(id: clip.id)
clips.remove(at: indexPath.row)
await MainActor.run {
tableView.deleteRows(at: [indexPath], with: .automatic)
updateEmptyState()
}
} catch {
await MainActor.run {
showError(message: "删除失败: \(error.localizedDescription)")
}
}
}
}
private func openClip(_ clip: Clip) {
let viewController = ClipEditViewController(clip: clip)
navigationController?.pushViewController(viewController, animated: true)
}
private func showError(message: String) {
let alert = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
present(alert, animated: true)
}
}
extension ClipInboxViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return clips.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "clipCell", for: indexPath)
let clip = clips[indexPath.row]
var config = cell.defaultContentConfiguration()
config.text = previewText(for: clip.text)
config.textProperties.numberOfLines = 0
config.secondaryText = formattedDate(clip.createdAt)
config.secondaryTextProperties.color = .secondaryLabel
config.textToSecondaryTextVerticalPadding = 12
cell.contentConfiguration = config
cell.accessoryType = .disclosureIndicator
return cell
}
private func previewText(for text: String) -> String {
let preview = text.trimmingCharacters(in: .whitespacesAndNewlines)
if preview.isEmpty {
return "(无内容)"
}
return preview
}
private func formattedDate(_ date: Date) -> String {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .short
return formatter.localizedString(for: date, relativeTo: Date())
}
}
extension ClipInboxViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let clip = clips[indexPath.row]
openClip(clip)
}
func tableView(_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .destructive, title: "删除") { [weak self] _, _, completion in
self?.deleteClip(at: indexPath)
completion(true)
}
return UISwipeActionsConfiguration(actions: [deleteAction])
}
}
+112
View File
@@ -0,0 +1,112 @@
//
// ClipStore.swift
// Note
//
// Created by Kimi Code CLI on 2026/7/15.
//
import Foundation
struct Clip: Codable, Identifiable, Equatable, Sendable {
let id: UUID
var text: String
let createdAt: Date
var source: String?
nonisolated init(id: UUID = UUID(), text: String, createdAt: Date = Date(), source: String? = nil) {
self.id = id
self.text = text
self.createdAt = createdAt
self.source = source
}
}
enum ClipStoreError: Error, LocalizedError {
case appGroupUnavailable
var errorDescription: String? {
switch self {
case .appGroupUnavailable:
return "无法访问 App Group 容器,请检查签名和 entitlements 配置。"
}
}
}
actor ClipStore {
static let shared = ClipStore()
private let appGroupIdentifier = "group.com.fishestlife.note"
private let fileName = "clips.json"
private let subdirectory = "SharedFiles/Clips"
private var cachedClips: [Clip]?
private func fileURL() throws -> URL {
let fileManager = FileManager.default
guard let containerURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier) else {
throw ClipStoreError.appGroupUnavailable
}
let directoryURL = containerURL.appendingPathComponent(subdirectory, isDirectory: true)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
return directoryURL.appendingPathComponent(fileName)
}
private init() {}
func save(text: String, source: String? = nil) async throws {
var clips = try await loadAll()
let clip = Clip(text: text, source: source)
clips.insert(clip, at: 0)
try await persist(clips)
}
func loadAll() async throws -> [Clip] {
if let cached = cachedClips {
return cached
}
let url = try fileURL()
let fileManager = FileManager.default
guard fileManager.fileExists(atPath: url.path) else {
cachedClips = []
return []
}
let data = try Data(contentsOf: url)
let clips = try JSONDecoder().decode([Clip].self, from: data)
cachedClips = clips
return clips
}
func update(_ clip: Clip) async throws {
var clips = try await loadAll()
guard let index = clips.firstIndex(where: { $0.id == clip.id }) else {
return
}
clips[index] = clip
try await persist(clips)
}
func delete(id: UUID) async throws {
var clips = try await loadAll()
clips.removeAll { $0.id == id }
try await persist(clips)
}
func clearAll() async throws {
try await persist([])
}
func count() async throws -> Int {
let clips = try await loadAll()
return clips.count
}
private func persist(_ clips: [Clip]) async throws {
let url = try fileURL()
let data = try JSONEncoder().encode(clips)
try data.write(to: url, options: .atomic)
cachedClips = clips
}
}
+107 -24
View File
@@ -11,11 +11,14 @@ class FormatLogViewController: UIViewController {
private var textView: UITextView! private var textView: UITextView!
private var formatButton: UIButton! private var formatButton: UIButton!
private var floatingDoneButton: UIButton!
private var floatingDoneButtonBottomConstraint: NSLayoutConstraint!
private var doneButton: UIBarButtonItem! private var doneButton: UIBarButtonItem!
private var pasteButton: UIBarButtonItem! private var pasteButton: UIBarButtonItem!
private var resetButton: UIBarButtonItem! private var resetButton: UIBarButtonItem!
private var isFormatted = false private var isFormatted = false
private var rightBarButtonMode: RightBarButtonMode = .paste private var rightBarButtonMode: RightBarButtonMode = .paste
var initialText: String?
private enum RightBarButtonMode { private enum RightBarButtonMode {
case paste case paste
@@ -28,14 +31,30 @@ class FormatLogViewController: UIViewController {
navigationItem.largeTitleDisplayMode = .never navigationItem.largeTitleDisplayMode = .never
view.backgroundColor = .systemGroupedBackground view.backgroundColor = .systemGroupedBackground
setupUI() setupUI()
if let initialText = initialText {
textView.text = initialText
isFormatted = true
formatButton.setTitle("保存到 iCloud", for: .normal)
rightBarButtonMode = .reset
updateRightBarButtonItem()
}
setupKeyboardObservers()
}
deinit {
NotificationCenter.default.removeObserver(self)
} }
private func setupUI() { private func setupUI() {
textView = UITextView() textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false textView.translatesAutoresizingMaskIntoConstraints = false
textView.font = UIFont.systemFont(ofSize: 16) textView.font = UIFont.systemFont(ofSize: 16)
textView.backgroundColor = .white textView.backgroundColor = UIColor { traitCollection in
traitCollection.userInterfaceStyle == .dark ? .secondarySystemBackground : .white
}
textView.layer.cornerRadius = 12 textView.layer.cornerRadius = 12
textView.layer.borderWidth = 0.5
textView.layer.borderColor = UIColor.separator.cgColor
textView.textContainerInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) textView.textContainerInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
textView.delegate = self textView.delegate = self
view.addSubview(textView) view.addSubview(textView)
@@ -56,7 +75,28 @@ class FormatLogViewController: UIViewController {
formatButton.addTarget(self, action: #selector(didTapFormatButton), for: .touchUpInside) formatButton.addTarget(self, action: #selector(didTapFormatButton), for: .touchUpInside)
view.addSubview(formatButton) view.addSubview(formatButton)
var doneConfig = UIButton.Configuration.glass()
doneConfig.title = "完成"
doneConfig.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
return outgoing
}
doneConfig.baseForegroundColor = .label
doneConfig.cornerStyle = .capsule
doneConfig.contentInsets = NSDirectionalEdgeInsets(top: 15, leading: 22, bottom: 15, trailing: 22)
floatingDoneButton = UIButton(configuration: doneConfig)
floatingDoneButton.translatesAutoresizingMaskIntoConstraints = false
floatingDoneButton.alpha = 0
floatingDoneButton.addTarget(self, action: #selector(didTapFloatingDoneButton), for: .touchUpInside)
view.addSubview(floatingDoneButton)
floatingDoneButtonBottomConstraint = floatingDoneButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16)
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
floatingDoneButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
floatingDoneButtonBottomConstraint,
textView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16), textView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16), textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16), textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
@@ -73,11 +113,53 @@ class FormatLogViewController: UIViewController {
textView.resignFirstResponder() textView.resignFirstResponder()
} }
@objc private func didTapFloatingDoneButton() {
textView.resignFirstResponder()
}
private func setupKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc private func keyboardWillShow(_ notification: Notification) {
guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
let keyboardFrameInView = view.convert(keyboardFrame, from: nil)
let intersection = keyboardFrameInView.intersection(view.bounds)
let keyboardHeight = intersection.height
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState) {
self.textView.contentInset.bottom = keyboardHeight
self.textView.verticalScrollIndicatorInsets.bottom = keyboardHeight
self.floatingDoneButtonBottomConstraint.constant = -(keyboardHeight + 8)
self.floatingDoneButton.alpha = 1
self.view.layoutIfNeeded()
}
}
@objc private func keyboardWillHide(_ notification: Notification) {
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState) {
self.textView.contentInset.bottom = 0
self.textView.verticalScrollIndicatorInsets.bottom = 0
self.floatingDoneButtonBottomConstraint.constant = -16
self.floatingDoneButton.alpha = 0
self.view.layoutIfNeeded()
}
}
@objc private func didTapFormatButton() { @objc private func didTapFormatButton() {
guard !trimmedText().isEmpty else {
showEmptyAlert()
return
}
if isFormatted { if isFormatted {
saveToFiles() saveToFiles()
} else { } else {
textView.text = formatLog(textView.text) textView.text = TextFormatter.formatLog(textView.text)
isFormatted = true isFormatted = true
formatButton.setTitle("保存到 iCloud", for: .normal) formatButton.setTitle("保存到 iCloud", for: .normal)
rightBarButtonMode = .reset rightBarButtonMode = .reset
@@ -91,7 +173,30 @@ class FormatLogViewController: UIViewController {
} }
} }
private func trimmedText() -> String {
return textView.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
}
private func showEmptyAlert() {
let alert = UIAlertController(title: "提示", message: "请输入内容后再进行格式化", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
present(alert, animated: true)
}
@objc private func didTapResetButton() { @objc private func didTapResetButton() {
let alert = UIAlertController(
title: "确认重置",
message: "确定要清空当前内容吗?",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "重置", style: .destructive) { [weak self] _ in
self?.performReset()
})
present(alert, animated: true)
}
private func performReset() {
textView.text = "" textView.text = ""
isFormatted = false isFormatted = false
formatButton.setTitle("格式化", for: .normal) formatButton.setTitle("格式化", for: .normal)
@@ -138,28 +243,6 @@ class FormatLogViewController: UIViewController {
} }
return cleanName + ".md" return cleanName + ".md"
} }
private func formatLog(_ text: String) -> String {
var content = text
content = content.replacingOccurrences(of: "# ", with: "")
content = content.replacingOccurrences(of: "#", with: "")
content = content.replacingOccurrences(of: ";", with: "")
content = content.replacingOccurrences(of: "", with: "")
content = content.replacingOccurrences(of: ".", with: "")
content = content.replacingOccurrences(of: "", with: "(")
content = content.replacingOccurrences(of: "", with: ")")
content = content.replacingOccurrences(of: "?", with: "")
content = content.replacingOccurrences(of: ",", with: "")
content = content.replacingOccurrences(of: ":", with: "")
content = content.replacingOccurrences(of: "日星期", with: "日 星期")
content = "# " + content
content = content.replacingOccurrences(of: "一、生活方面", with: "## 一、生活方面")
content = content.replacingOccurrences(of: "二、交易方面", with: "## 二、交易方面")
content = content.replacingOccurrences(of: "三、工作方面", with: "## 三、工作方面")
return content
}
} }
extension FormatLogViewController: UITextViewDelegate { extension FormatLogViewController: UITextViewDelegate {
+122 -84
View File
@@ -12,11 +12,15 @@ class FormatNoteViewController: UIViewController {
private var textView: UITextView! private var textView: UITextView!
private var iCloudButton: UIButton! private var iCloudButton: UIButton!
private var noteButton: UIButton! private var noteButton: UIButton!
private var floatingDoneButton: UIButton!
private var floatingDoneButtonBottomConstraint: NSLayoutConstraint!
private var doneButton: UIBarButtonItem! private var doneButton: UIBarButtonItem!
private var pasteButton: UIBarButtonItem! private var pasteButton: UIBarButtonItem!
private var resetButton: UIBarButtonItem! private var resetButton: UIBarButtonItem!
private var rightBarButtonMode: RightBarButtonMode = .paste private var rightBarButtonMode: RightBarButtonMode = .paste
private var isCloudFormatted = false private var isCloudFormatted = false
private var isNoteFormatted = false
var initialText: String?
private enum RightBarButtonMode { private enum RightBarButtonMode {
case paste case paste
@@ -29,13 +33,25 @@ class FormatNoteViewController: UIViewController {
navigationItem.largeTitleDisplayMode = .never navigationItem.largeTitleDisplayMode = .never
view.backgroundColor = .systemGroupedBackground view.backgroundColor = .systemGroupedBackground
setupUI() setupUI()
if let initialText = initialText {
textView.text = initialText
}
setupKeyboardObservers()
}
deinit {
NotificationCenter.default.removeObserver(self)
} }
private func setupUI() { private func setupUI() {
textView = UITextView() textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false textView.translatesAutoresizingMaskIntoConstraints = false
textView.backgroundColor = .systemBackground textView.backgroundColor = UIColor { traitCollection in
traitCollection.userInterfaceStyle == .dark ? .secondarySystemBackground : .white
}
textView.layer.cornerRadius = 12 textView.layer.cornerRadius = 12
textView.layer.borderWidth = 0.5
textView.layer.borderColor = UIColor.separator.cgColor
textView.layer.masksToBounds = true textView.layer.masksToBounds = true
textView.font = UIFont.preferredFont(forTextStyle: .body) textView.font = UIFont.preferredFont(forTextStyle: .body)
textView.textContainerInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) textView.textContainerInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
@@ -56,10 +72,28 @@ class FormatNoteViewController: UIViewController {
noteButton.addTarget(self, action: #selector(didTapNoteButton), for: .touchUpInside) noteButton.addTarget(self, action: #selector(didTapNoteButton), for: .touchUpInside)
view.addSubview(noteButton) view.addSubview(noteButton)
var doneConfig = UIButton.Configuration.glass()
doneConfig.title = "完成"
doneConfig.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
return outgoing
}
doneConfig.baseForegroundColor = .label
doneConfig.cornerStyle = .capsule
doneConfig.contentInsets = NSDirectionalEdgeInsets(top: 15, leading: 22, bottom: 15, trailing: 22)
floatingDoneButton = UIButton(configuration: doneConfig)
floatingDoneButton.translatesAutoresizingMaskIntoConstraints = false
floatingDoneButton.alpha = 0
floatingDoneButton.addTarget(self, action: #selector(didTapFloatingDoneButton), for: .touchUpInside)
view.addSubview(floatingDoneButton)
let safeArea = view.safeAreaLayoutGuide let safeArea = view.safeAreaLayoutGuide
let buttonHeight: CGFloat = 52 let buttonHeight: CGFloat = 52
let spacing: CGFloat = 16 let spacing: CGFloat = 16
floatingDoneButtonBottomConstraint = floatingDoneButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -spacing)
NSLayoutConstraint.activate([ NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: safeArea.topAnchor, constant: spacing), textView.topAnchor.constraint(equalTo: safeArea.topAnchor, constant: spacing),
textView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor, constant: spacing), textView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor, constant: spacing),
@@ -75,7 +109,10 @@ class FormatNoteViewController: UIViewController {
noteButton.leadingAnchor.constraint(equalTo: safeArea.centerXAnchor, constant: spacing / 2), noteButton.leadingAnchor.constraint(equalTo: safeArea.centerXAnchor, constant: spacing / 2),
noteButton.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -spacing), noteButton.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -spacing),
noteButton.heightAnchor.constraint(equalToConstant: buttonHeight), noteButton.heightAnchor.constraint(equalToConstant: buttonHeight),
noteButton.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor, constant: -spacing) noteButton.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor, constant: -spacing),
floatingDoneButton.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -spacing),
floatingDoneButtonBottomConstraint
]) ])
} }
@@ -96,17 +133,80 @@ class FormatNoteViewController: UIViewController {
textView.resignFirstResponder() textView.resignFirstResponder()
} }
@objc private func didTapFloatingDoneButton() {
textView.resignFirstResponder()
}
private func setupKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc private func keyboardWillShow(_ notification: Notification) {
guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
let keyboardFrameInView = view.convert(keyboardFrame, from: nil)
let intersection = keyboardFrameInView.intersection(view.bounds)
let keyboardHeight = intersection.height
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState) {
self.textView.contentInset.bottom = keyboardHeight
self.textView.verticalScrollIndicatorInsets.bottom = keyboardHeight
self.floatingDoneButtonBottomConstraint.constant = -(keyboardHeight + 8)
self.floatingDoneButton.alpha = 1
self.view.layoutIfNeeded()
}
}
@objc private func keyboardWillHide(_ notification: Notification) {
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState) {
self.textView.contentInset.bottom = 0
self.textView.verticalScrollIndicatorInsets.bottom = 0
self.floatingDoneButtonBottomConstraint.constant = -16
self.floatingDoneButton.alpha = 0
self.view.layoutIfNeeded()
}
}
@objc private func didTapPasteButton() { @objc private func didTapPasteButton() {
if let string = UIPasteboard.general.string { if let string = UIPasteboard.general.string {
textView.text = string textView.text = string
} }
} }
private func trimmedText() -> String {
return textView.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
}
private func showEmptyAlert() {
let alert = UIAlertController(title: "提示", message: "请输入内容后再进行格式化", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
present(alert, animated: true)
}
@objc private func didTapResetButton() { @objc private func didTapResetButton() {
let alert = UIAlertController(
title: "确认重置",
message: "确定要清空当前内容吗?",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "重置", style: .destructive) { [weak self] _ in
self?.performReset()
})
present(alert, animated: true)
}
private func performReset() {
textView.text = "" textView.text = ""
rightBarButtonMode = .paste rightBarButtonMode = .paste
isCloudFormatted = false isCloudFormatted = false
isNoteFormatted = false
iCloudButton.setTitle("iCloud 格式化", for: .normal) iCloudButton.setTitle("iCloud 格式化", for: .normal)
noteButton.setTitle("Note 格式化", for: .normal)
updateRightBarButtonItem() updateRightBarButtonItem()
} }
@@ -124,10 +224,14 @@ class FormatNoteViewController: UIViewController {
} }
@objc private func didTapiCloudButton() { @objc private func didTapiCloudButton() {
guard !trimmedText().isEmpty else {
showEmptyAlert()
return
}
if isCloudFormatted { if isCloudFormatted {
saveToFiles() saveToFiles()
} else { } else {
textView.text = formatForCloud(textView.text) textView.text = TextFormatter.formatForCloud(textView.text)
isCloudFormatted = true isCloudFormatted = true
iCloudButton.setTitle("保存到 iCloud", for: .normal) iCloudButton.setTitle("保存到 iCloud", for: .normal)
rightBarButtonMode = .reset rightBarButtonMode = .reset
@@ -136,78 +240,26 @@ class FormatNoteViewController: UIViewController {
} }
@objc private func didTapNoteButton() { @objc private func didTapNoteButton() {
textView.text = formatForNote(textView.text) guard !trimmedText().isEmpty else {
showEmptyAlert()
return
}
if isNoteFormatted {
copyAndOpenNotes()
} else {
textView.text = TextFormatter.formatForNote(textView.text)
isNoteFormatted = true
noteButton.setTitle("复制并打开备忘录", for: .normal)
rightBarButtonMode = .reset rightBarButtonMode = .reset
updateRightBarButtonItem() updateRightBarButtonItem()
} }
private func formatForCloud(_ text: String) -> String {
var content = text
content = content.replacingOccurrences(of: " ", with: "")
content = content.replacingOccurrences(of: " ", with: "")
content = content.replacingOccurrences(of: "\u{00A0}", with: "")
content = content.replacingOccurrences(of: "# ", with: "")
content = content.replacingOccurrences(of: "#", with: "")
content = content.replacingOccurrences(of: "", with: "")
content = content.replacingOccurrences(of: "!", with: "")
content = content.replacingOccurrences(of: ";", with: "")
content = content.replacingOccurrences(of: "", with: "")
content = content.replacingOccurrences(of: ".", with: "")
content = content.replacingOccurrences(of: "", with: "(")
content = content.replacingOccurrences(of: "", with: ")")
content = content.replacingOccurrences(of: "?", with: "")
content = content.replacingOccurrences(of: ",", with: "")
content = content.replacingOccurrences(of: ":", with: "")
let numberReplacements: [(String, String)] = [
("20、", "二十、"), ("19、", "十九、"), ("18、", "十八、"), ("17、", "十七、"),
("16、", "十六、"), ("15、", "十五、"), ("14、", "十四、"), ("13、", "十三、"),
("12、", "十二、"), ("11、", "十一、"), ("10、", "十、"),
("9、", "九、"), ("8、", "八、"), ("7、", "七、"), ("6、", "六、"),
("5、", "五、"), ("4、", "四、"), ("3、", "三、"), ("2、", "二、"), ("1、", "一、")
]
for (old, new) in numberReplacements {
content = content.replacingOccurrences(of: old, with: new)
} }
content = content.replacingOccurrences(of: "", with: "\n") private func copyAndOpenNotes() {
content = content.replacingOccurrences(of: "", with: "\n") UIPasteboard.general.string = textView.text
content = removeEmptyLines(content) guard let url = URL(string: "mobilenotes://") else { return }
content = content.replacingOccurrences(of: "\\s*", with: "\n\n", options: .regularExpression) guard UIApplication.shared.canOpenURL(url) else { return }
content = content.replacingOccurrences(of: "", with: "\n") UIApplication.shared.open(url, options: [:], completionHandler: nil)
content = content.replacingOccurrences(of: "", with: "\n")
content = content.replacingOccurrences(of: "\n\n", with: "")
content = content.replacingOccurrences(of: ":一、", with: "\n\n一、")
content = content.replacingOccurrences(of: " ", with: "")
content = content.replacingOccurrences(of: "---", with: "---\n")
content = content.replacingOccurrences(of: "日星期", with: "日 星期")
content = "# " + content
content = insertEmptyLineAfterFirstLine(content)
return content
}
private func formatForNote(_ text: String) -> String {
var content = text
content = content.replacingOccurrences(of: " ", with: "")
content = content.replacingOccurrences(of: "# ", with: "")
content = content.replacingOccurrences(of: "#", with: "")
content = content.replacingOccurrences(of: "", with: "")
content = content.replacingOccurrences(of: "!", with: "")
content = content.replacingOccurrences(of: ";", with: "")
content = content.replacingOccurrences(of: "", with: "")
content = content.replacingOccurrences(of: ".", with: "")
content = content.replacingOccurrences(of: "", with: "(")
content = content.replacingOccurrences(of: "", with: ")")
content = content.replacingOccurrences(of: "?", with: "")
content = content.replacingOccurrences(of: ",", with: "")
content = content.replacingOccurrences(of: ":", with: "")
content = content.replacingOccurrences(of: "", with: "\n")
content = content.replacingOccurrences(of: "", with: "\n")
content = removeEmptyLines(content)
content = content.replacingOccurrences(of: "---", with: "")
content = content.replacingOccurrences(of: "日星期", with: "日 星期")
content = insertEmptyLineAfterFirstLine(content)
return content
} }
private func saveToFiles() { private func saveToFiles() {
@@ -236,20 +288,6 @@ class FormatNoteViewController: UIViewController {
} }
return cleanName + ".md" return cleanName + ".md"
} }
private func removeEmptyLines(_ text: String) -> String {
let lines = text.components(separatedBy: .newlines)
let nonEmptyLines = lines.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
return nonEmptyLines.joined(separator: "\n")
}
private func insertEmptyLineAfterFirstLine(_ text: String) -> String {
var lines = text.components(separatedBy: .newlines)
if !lines.isEmpty {
lines.insert("", at: 1)
}
return lines.joined(separator: "\n")
}
} }
extension FormatNoteViewController: UIDocumentPickerDelegate { extension FormatNoteViewController: UIDocumentPickerDelegate {
+154 -1
View File
@@ -2,6 +2,160 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"> <plist version="1.0">
<dict> <dict>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>mobilenotes</string>
<string>shareddocuments</string>
<string>noteapp</string>
</array>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.fishestlife.note</string>
<key>CFBundleURLSchemes</key>
<array>
<string>noteapp</string>
</array>
</dict>
</array>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>Markdown File</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>net.daringfireball.markdown</string>
<string>public.markdown</string>
<string>public.text</string>
<string>public.plain-text</string>
<string>public.utf8-plain-text</string>
</array>
<key>CFBundleTypeExtensions</key>
<array>
<string>md</string>
<string>markdown</string>
<string>mdown</string>
<string>mkd</string>
<string>mkdn</string>
</array>
<key>CFBundleTypeMIMETypes</key>
<array>
<string>text/markdown</string>
<string>text/x-markdown</string>
</array>
</dict>
<dict>
<key>CFBundleTypeName</key>
<string>Plain Text File</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Alternate</string>
<key>LSItemContentTypes</key>
<array>
<string>public.plain-text</string>
<string>public.utf8-plain-text</string>
<string>public.text</string>
</array>
<key>CFBundleTypeExtensions</key>
<array>
<string>txt</string>
<string>text</string>
</array>
</dict>
<dict>
<key>CFBundleTypeName</key>
<string>Any Text or Data File</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSHandlerRank</key>
<string>Alternate</string>
<key>LSItemContentTypes</key>
<array>
<string>public.data</string>
<string>public.content</string>
<string>public.item</string>
</array>
<key>CFBundleTypeExtensions</key>
<array>
<string>md</string>
<string>markdown</string>
<string>txt</string>
<string>*</string>
</array>
</dict>
</array>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.text</string>
<string>public.plain-text</string>
</array>
<key>UTTypeDescription</key>
<string>Markdown File</string>
<key>UTTypeIdentifier</key>
<string>net.daringfireball.markdown</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>md</string>
<string>markdown</string>
<string>mdown</string>
<string>mkd</string>
<string>mkdn</string>
</array>
<key>public.mime-type</key>
<array>
<string>text/markdown</string>
<string>text/x-markdown</string>
</array>
</dict>
</dict>
</array>
<key>UTImportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.text</string>
<string>public.plain-text</string>
<string>public.data</string>
</array>
<key>UTTypeDescription</key>
<string>Markdown File</string>
<key>UTTypeIdentifier</key>
<string>net.daringfireball.markdown</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>md</string>
<string>markdown</string>
<string>mdown</string>
<string>mkd</string>
<string>mkdn</string>
</array>
<key>public.mime-type</key>
<array>
<string>text/markdown</string>
<string>text/x-markdown</string>
</array>
</dict>
</dict>
</array>
<key>UIApplicationSceneManifest</key> <key>UIApplicationSceneManifest</key>
<dict> <dict>
<key>UIApplicationSupportsMultipleScenes</key> <key>UIApplicationSupportsMultipleScenes</key>
@@ -15,7 +169,6 @@
<string>Default Configuration</string> <string>Default Configuration</string>
<key>UISceneDelegateClassName</key> <key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string> <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
</dict> </dict>
</array> </array>
</dict> </dict>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.application-groups</key>
<array>
<string>group.com.fishestlife.note</string>
</array>
</dict>
</plist>
+20
View File
@@ -0,0 +1,20 @@
//
// NoteAppShortcuts.swift
// Note
//
// Created by Kimi Code CLI on 2026/7/15.
//
import AppIntents
struct NoteAppShortcuts: AppShortcutsProvider {
static var appShortcuts: [AppShortcut] {
AppShortcut(
intent: SaveClipIntent(),
phrases: ["保存剪贴板到 ${applicationName}"],
shortTitle: "保存剪贴板",
systemImageName: "doc.text"
)
}
}
+99
View File
@@ -0,0 +1,99 @@
//
// PreviewViewController.swift
// Note
//
// Created by fish on 2026/7/13.
//
import UIKit
class PreviewViewController: UIViewController {
private var textView: UITextView!
private var logButton: UIButton!
private var noteButton: UIButton!
var initialText: String?
var fileName: String?
override func viewDidLoad() {
super.viewDidLoad()
title = "预览"
navigationItem.largeTitleDisplayMode = .never
view.backgroundColor = .systemGroupedBackground
setupUI()
}
private func setupUI() {
textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.backgroundColor = UIColor { traitCollection in
traitCollection.userInterfaceStyle == .dark ? .secondarySystemBackground : .white
}
textView.layer.cornerRadius = 12
textView.layer.borderWidth = 0.5
textView.layer.borderColor = UIColor.separator.cgColor
textView.layer.masksToBounds = true
textView.font = UIFont.preferredFont(forTextStyle: .body)
textView.textContainerInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
textView.isEditable = false
textView.isSelectable = true
textView.text = initialText
view.addSubview(textView)
logButton = createBottomButton(title: "处理日志", color: .systemBlue)
logButton.addTarget(self, action: #selector(didTapLogButton), for: .touchUpInside)
view.addSubview(logButton)
noteButton = createBottomButton(title: "处理 Note", color: .systemGreen)
noteButton.addTarget(self, action: #selector(didTapNoteButton), for: .touchUpInside)
view.addSubview(noteButton)
let safeArea = view.safeAreaLayoutGuide
let buttonHeight: CGFloat = 52
let spacing: CGFloat = 16
NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: safeArea.topAnchor, constant: spacing),
textView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor, constant: spacing),
textView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -spacing),
logButton.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: spacing),
logButton.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor, constant: spacing),
logButton.trailingAnchor.constraint(equalTo: safeArea.centerXAnchor, constant: -spacing / 2),
logButton.heightAnchor.constraint(equalToConstant: buttonHeight),
logButton.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor, constant: -spacing),
noteButton.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: spacing),
noteButton.leadingAnchor.constraint(equalTo: safeArea.centerXAnchor, constant: spacing / 2),
noteButton.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -spacing),
noteButton.heightAnchor.constraint(equalToConstant: buttonHeight),
noteButton.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor, constant: -spacing)
])
}
private func createBottomButton(title: String, color: UIColor) -> UIButton {
var config = UIButton.Configuration.filled()
config.title = title
config.baseBackgroundColor = color
config.baseForegroundColor = .white
config.cornerStyle = .medium
config.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
let button = UIButton(configuration: config)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}
@objc private func didTapLogButton() {
let viewController = FormatLogViewController()
viewController.initialText = TextFormatter.formatLog(initialText ?? "")
navigationController?.pushViewController(viewController, animated: true)
}
@objc private func didTapNoteButton() {
let viewController = FormatNoteViewController()
viewController.initialText = TextFormatter.formatForNote(initialText ?? "")
navigationController?.pushViewController(viewController, animated: true)
}
}
+61
View File
@@ -0,0 +1,61 @@
//
// SaveClipIntent.swift
// Note
//
// Created by Kimi Code CLI on 2026/7/15.
//
import AppIntents
import UIKit
struct SaveClipIntent: AppIntent {
static var title: LocalizedStringResource = "保存剪贴板到 Note"
static var description: IntentDescription? = "将一段文本保存到 Note App 的收集箱,稍后统一处理。"
@Parameter(title: "文案", description: "要保存的文本内容", default: "")
var text: String
@Parameter(title: "来源", description: "文案来源,例如应用名称", default: "快捷指令")
var source: String?
init() {}
init(text: String, source: String? = nil) {
self.text = text
self.source = source
}
func perform() async throws -> some IntentResult & ReturnsValue<String> {
var inputText = text
if inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
inputText = await MainActor.run {
UIPasteboard.general.string ?? ""
}
}
let trimmed = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
return .result(value: "文案为空,未保存。")
}
guard !isSystemClipboardPlaceholder(trimmed) else {
return .result(value: "剪贴板没有有效文本,未保存。")
}
let formattedText = TextFormatter.formatForShortcut(trimmed)
try await ClipStore.shared.save(text: formattedText, source: source)
return .result(value: "已保存到收集箱。")
}
private func isSystemClipboardPlaceholder(_ text: String) -> Bool {
let lowercased = text.lowercased()
if lowercased.hasPrefix("clipboard ") && lowercased.contains(" at ") {
return true
}
if text == "获取剪贴板" {
return true
}
return false
}
}
+76
View File
@@ -20,6 +20,10 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
let navigationController = UINavigationController(rootViewController: rootViewController) let navigationController = UINavigationController(rootViewController: rootViewController)
window?.rootViewController = navigationController window?.rootViewController = navigationController
window?.makeKeyAndVisible() window?.makeKeyAndVisible()
if let url = connectionOptions.urlContexts.first?.url {
handleSharedFile(url)
}
} }
func sceneDidDisconnect(_ scene: UIScene) { func sceneDidDisconnect(_ scene: UIScene) {
@@ -50,6 +54,78 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
// to restore the scene back to its current state. // to restore the scene back to its current state.
} }
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let url = URLContexts.first?.url else { return }
handleSharedFile(url)
}
private func handleSharedFile(_ url: URL) {
guard let navigationController = window?.rootViewController as? UINavigationController else {
return
}
if url.scheme == "noteapp", url.host == "share" {
handleShareURL(url, navigationController: navigationController)
return
}
guard url.isFileURL else { return }
let shouldStopAccessing = url.startAccessingSecurityScopedResource()
defer {
if shouldStopAccessing {
url.stopAccessingSecurityScopedResource()
}
}
do {
let content = try String(contentsOf: url, encoding: .utf8)
DispatchQueue.main.async {
let viewController = PreviewViewController()
viewController.initialText = content
viewController.fileName = url.lastPathComponent
viewController.title = url.lastPathComponent
navigationController.pushViewController(viewController, animated: true)
}
} catch {
print("Failed to read shared file: \(error)")
}
}
private func handleShareURL(_ url: URL, navigationController: UINavigationController) {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let queryItems = components.queryItems else { return }
let fileManager = FileManager.default
let containerURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.fishestlife.note")
let sharedDir = containerURL?.appendingPathComponent("SharedFiles", isDirectory: true)
var contents: [(text: String, fileName: String)] = []
for item in queryItems {
if item.name.hasPrefix("text"), let text = item.value, !text.isEmpty {
contents.append((text: text, fileName: "shared.md"))
} else if item.name.hasPrefix("file"), let fileName = item.value, !fileName.isEmpty {
if let sharedDir = sharedDir {
let fileURL = sharedDir.appendingPathComponent(fileName)
if let text = try? String(contentsOf: fileURL, encoding: .utf8) {
contents.append((text: text, fileName: fileName))
}
}
}
}
guard let first = contents.first else { return }
DispatchQueue.main.async {
let viewController = PreviewViewController()
viewController.initialText = first.text
viewController.fileName = first.fileName
viewController.title = first.fileName
navigationController.pushViewController(viewController, animated: true)
}
}
} }
+132
View File
@@ -0,0 +1,132 @@
//
// TextFormatter.swift
// Note
//
// Created by fish on 2026/7/13.
//
import Foundation
enum TextFormatter {
static nonisolated func formatLog(_ text: String) -> String {
var content = text
content = content.replacingOccurrences(of: "# ", with: "")
content = content.replacingOccurrences(of: "#", with: "")
content = content.replacingOccurrences(of: ";", with: "")
content = content.replacingOccurrences(of: "", with: "")
content = content.replacingOccurrences(of: ".", with: "")
content = content.replacingOccurrences(of: "", with: "(")
content = content.replacingOccurrences(of: "", with: ")")
content = content.replacingOccurrences(of: "?", with: "")
content = content.replacingOccurrences(of: ",", with: "")
content = content.replacingOccurrences(of: ":", with: "")
content = content.replacingOccurrences(of: "日星期", with: "日 星期")
content = "# " + content
content = content.replacingOccurrences(of: "一、生活方面", with: "## 一、生活方面")
content = content.replacingOccurrences(of: "二、交易方面", with: "## 二、交易方面")
content = content.replacingOccurrences(of: "三、工作方面", with: "## 三、工作方面")
return content
}
static nonisolated func formatForCloud(_ text: String) -> String {
var content = formatForShortcut(text)
content = "# " + content
content = insertEmptyLineAfterFirstLine(content)
return content
}
static nonisolated func formatForShortcut(_ text: String) -> String {
var content = text
content = content.replacingOccurrences(of: " ", with: "")
content = content.replacingOccurrences(of: " ", with: "")
content = content.replacingOccurrences(of: "\u{00A0}", with: "")
content = content.replacingOccurrences(of: "# ", with: "")
content = content.replacingOccurrences(of: "#", with: "")
content = content.replacingOccurrences(of: "", with: "")
content = content.replacingOccurrences(of: "!", with: "")
content = content.replacingOccurrences(of: ";", with: "")
content = content.replacingOccurrences(of: "", with: "")
content = content.replacingOccurrences(of: ".", with: "")
content = content.replacingOccurrences(of: "", with: "(")
content = content.replacingOccurrences(of: "", with: ")")
content = content.replacingOccurrences(of: "?", with: "")
content = content.replacingOccurrences(of: ",", with: "")
content = content.replacingOccurrences(of: ":", with: "")
let numberReplacements: [(String, String)] = [
("20、", "二十、"), ("19、", "十九、"), ("18、", "十八、"), ("17、", "十七、"),
("16、", "十六、"), ("15、", "十五、"), ("14、", "十四、"), ("13、", "十三、"),
("12、", "十二、"), ("11、", "十一、"), ("10、", "十、"),
("9、", "九、"), ("8、", "八、"), ("7、", "七、"), ("6、", "六、"),
("5、", "五、"), ("4、", "四、"), ("3、", "三、"), ("2、", "二、"), ("1、", "一、")
]
for (old, new) in numberReplacements {
content = content.replacingOccurrences(of: old, with: new)
}
content = content.replacingOccurrences(of: "", with: "\n")
content = content.replacingOccurrences(of: "", with: "\n")
content = removeEmptyLines(content)
content = content.replacingOccurrences(of: "\\s*", with: "\n\n", options: .regularExpression)
content = content.replacingOccurrences(of: "", with: "\n")
content = content.replacingOccurrences(of: "", with: "\n")
content = content.replacingOccurrences(of: "\n\n", with: "")
content = content.replacingOccurrences(of: ":一、", with: "\n\n一、")
content = content.replacingOccurrences(of: " ", with: "")
content = content.replacingOccurrences(of: "---", with: "---\n")
content = content.replacingOccurrences(of: "日星期", with: "日 星期")
return content
}
static nonisolated func formatForNote(_ text: String) -> String {
var content = text
content = content.replacingOccurrences(of: "# ", with: "")
content = content.replacingOccurrences(of: "#", with: "")
content = content.replacingOccurrences(of: "日星期", with: "日 星期")
//
let allLines = removeEmptyLines(content).components(separatedBy: .newlines)
guard let title = allLines.first else { return content }
// ---
let bodyLines = Array(allLines.dropFirst())
var groups: [[String]] = []
var currentGroup: [String] = []
for line in bodyLines {
if line == "---" {
if !currentGroup.isEmpty {
groups.append(currentGroup)
currentGroup = []
}
} else {
currentGroup.append(line)
}
}
if !currentGroup.isEmpty {
groups.append(currentGroup)
}
var result = title
for group in groups {
result += "\n\n\n" + group.joined(separator: "\n")
}
return result.trimmingCharacters(in: .whitespacesAndNewlines)
}
static nonisolated func removeEmptyLines(_ text: String) -> String {
let lines = text.components(separatedBy: .newlines)
let nonEmptyLines = lines.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
return nonEmptyLines.joined(separator: "\n")
}
static nonisolated func insertEmptyLineAfterFirstLine(_ text: String) -> String {
var lines = text.components(separatedBy: .newlines)
if !lines.isEmpty {
lines.insert("", at: 1)
}
return lines.joined(separator: "\n")
}
}
+140 -12
View File
@@ -10,24 +10,54 @@ import UIKit
class ViewController: UIViewController { class ViewController: UIViewController {
private var tableView: UITableView! private var tableView: UITableView!
private var editButton: UIBarButtonItem!
private let menuOrderKey = "homeMenuOrder"
private struct MenuItem { private struct MenuItem {
let icon: String let icon: String
let iconColor: UIColor let iconColor: UIColor
let title: String let title: String
let identifier: String
} }
private let menuItems: [[MenuItem]] = [ private let defaultMenuItems: [MenuItem] = [
[ MenuItem(icon: "tray.full", iconColor: .systemIndigo, title: "收集箱", identifier: "inbox"),
MenuItem(icon: "note.text", iconColor: .systemYellow, title: "打开备忘录"), MenuItem(icon: "note.text", iconColor: .systemYellow, title: "打开备忘录", identifier: "notes"),
MenuItem(icon: "doc.text", iconColor: .systemBlue, title: "格式化日志"), MenuItem(icon: "doc.text", iconColor: .systemBlue, title: "格式化日志", identifier: "formatLog"),
MenuItem(icon: "text.alignleft", iconColor: .systemGreen, title: "格式化笔记") MenuItem(icon: "text.alignleft", iconColor: .systemGreen, title: "格式化笔记", identifier: "formatNote"),
] MenuItem(icon: "folder", iconColor: .systemOrange, title: "打开文件", identifier: "files")
] ]
private var menuItems: [[MenuItem]] = []
override func viewDidLoad() { override func viewDidLoad() {
super.viewDidLoad() super.viewDidLoad()
menuItems = [loadMenuOrder()]
setupUI() setupUI()
setupAppStateObserver()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateInboxBadge()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func setupAppStateObserver() {
NotificationCenter.default.addObserver(
self,
selector: #selector(appDidBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil
)
}
@objc private func appDidBecomeActive() {
updateInboxBadge()
} }
private func setupUI() { private func setupUI() {
@@ -36,6 +66,9 @@ class ViewController: UIViewController {
navigationItem.largeTitleDisplayMode = .always navigationItem.largeTitleDisplayMode = .always
view.backgroundColor = .systemGroupedBackground view.backgroundColor = .systemGroupedBackground
editButton = UIBarButtonItem(title: "编辑", style: .plain, target: self, action: #selector(didTapEditButton))
navigationItem.rightBarButtonItem = editButton
tableView = UITableView(frame: .zero, style: .insetGrouped) tableView = UITableView(frame: .zero, style: .insetGrouped)
tableView.translatesAutoresizingMaskIntoConstraints = false tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self tableView.delegate = self
@@ -51,6 +84,34 @@ class ViewController: UIViewController {
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
]) ])
} }
@objc private func didTapEditButton() {
tableView.setEditing(!tableView.isEditing, animated: true)
editButton.title = tableView.isEditing ? "完成" : "编辑"
}
private func loadMenuOrder() -> [MenuItem] {
guard let savedOrder = UserDefaults.standard.array(forKey: menuOrderKey) as? [String] else {
return defaultMenuItems
}
var orderedItems: [MenuItem] = []
for identifier in savedOrder {
if let item = defaultMenuItems.first(where: { $0.identifier == identifier }) {
orderedItems.append(item)
}
}
let remaining = defaultMenuItems.filter { item in
!orderedItems.contains { $0.identifier == item.identifier }
}
return orderedItems + remaining
}
private func saveMenuOrder() {
let identifiers = menuItems.flatMap { $0.map(\.identifier) }
UserDefaults.standard.set(identifiers, forKey: menuOrderKey)
}
} }
extension ViewController: UITableViewDataSource { extension ViewController: UITableViewDataSource {
@@ -73,34 +134,101 @@ extension ViewController: UITableViewDataSource {
config.imageProperties.tintColor = item.iconColor config.imageProperties.tintColor = item.iconColor
config.imageToTextPadding = 12 config.imageToTextPadding = 12
cell.contentConfiguration = config cell.contentConfiguration = config
cell.accessoryType = .disclosureIndicator cell.accessoryType = tableView.isEditing ? .none : .disclosureIndicator
cell.selectionStyle = tableView.isEditing ? .none : .default
return cell return cell
} }
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard sourceIndexPath != destinationIndexPath else { return }
let item = menuItems[sourceIndexPath.section].remove(at: sourceIndexPath.row)
menuItems[destinationIndexPath.section].insert(item, at: destinationIndexPath.row)
saveMenuOrder()
}
} }
extension ViewController: UITableViewDelegate { extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true) tableView.deselectRow(at: indexPath, animated: true)
guard !tableView.isEditing else { return }
let item = menuItems[indexPath.section][indexPath.row] let item = menuItems[indexPath.section][indexPath.row]
switch item.title { switch item.identifier {
case "打开备忘录": case "inbox":
let viewController = ClipInboxViewController()
navigationController?.pushViewController(viewController, animated: true)
case "notes":
openSystemNotesApp() openSystemNotesApp()
case "格式化日志": case "formatLog":
let viewController = FormatLogViewController() let viewController = FormatLogViewController()
navigationController?.pushViewController(viewController, animated: true) navigationController?.pushViewController(viewController, animated: true)
case "格式化笔记": case "formatNote":
let viewController = FormatNoteViewController() let viewController = FormatNoteViewController()
navigationController?.pushViewController(viewController, animated: true) navigationController?.pushViewController(viewController, animated: true)
case "files":
openFilesApp()
default: default:
break break
} }
} }
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
private func updateInboxBadge() {
Task {
guard let count = try? await ClipStore.shared.count(), count > 0 else {
await MainActor.run {
self.updateInboxTitle("收集箱")
}
return
}
await MainActor.run {
self.updateInboxTitle("收集箱(\(count)")
}
}
}
private func updateInboxTitle(_ title: String) {
for (sectionIndex, section) in menuItems.enumerated() {
for (rowIndex, item) in section.enumerated() {
if item.identifier == "inbox" {
menuItems[sectionIndex][rowIndex] = MenuItem(
icon: item.icon,
iconColor: item.iconColor,
title: title,
identifier: item.identifier
)
let indexPath = IndexPath(row: rowIndex, section: sectionIndex)
tableView.reloadRows(at: [indexPath], with: .none)
return
}
}
}
}
private func openSystemNotesApp() { private func openSystemNotesApp() {
guard let url = URL(string: "mobilenotes://") else { return } openURLIfPossible("mobilenotes://")
}
private func openFilesApp() {
openURLIfPossible("shareddocuments://")
}
private func openURLIfPossible(_ string: String) {
guard let url = URL(string: string) else { return }
guard UIApplication.shared.canOpenURL(url) else { return } guard UIApplication.shared.canOpenURL(url) else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil) UIApplication.shared.open(url, options: [:], completionHandler: nil)
} }
+1
View File
@@ -0,0 +1 @@
/* Simplified Chinese localization */
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSExtension</key>
<dict>
<key>NSExtensionAttributes</key>
<dict>
<key>NSExtensionActivationRule</key>
<dict>
<key>NSExtensionActivationSupportsFileWithMaxCount</key>
<integer>10</integer>
<key>NSExtensionActivationSupportsText</key>
<true/>
</dict>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.share-services</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).ShareViewController</string>
</dict>
</dict>
</plist>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.application-groups</key>
<array>
<string>group.com.fishestlife.note</string>
</array>
</dict>
</plist>
@@ -0,0 +1,103 @@
import UIKit
import UniformTypeIdentifiers
class ShareViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
handleSharedItems()
}
private func handleSharedItems() {
guard let items = extensionContext?.inputItems as? [NSExtensionItem] else {
closeExtension()
return
}
let fileManager = FileManager.default
guard let containerURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.fishestlife.note") else {
closeExtension()
return
}
let sharedDir = containerURL.appendingPathComponent("SharedFiles", isDirectory: true)
try? fileManager.createDirectory(at: sharedDir, withIntermediateDirectories: true)
var sharedTexts: [String] = []
var sharedFileNames: [String] = []
let group = DispatchGroup()
for item in items {
guard let attachments = item.attachments else { continue }
for attachment in attachments {
group.enter()
if attachment.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) {
attachment.loadItem(forTypeIdentifier: UTType.plainText.identifier, options: nil) { data, _ in
defer { group.leave() }
if let text = data as? String {
sharedTexts.append(text)
} else if let url = data as? URL, let text = try? String(contentsOf: url, encoding: .utf8) {
sharedTexts.append(text)
}
}
} else if attachment.hasItemConformingToTypeIdentifier(UTType.url.identifier) {
attachment.loadItem(forTypeIdentifier: UTType.url.identifier, options: nil) { data, _ in
defer { group.leave() }
if let url = data as? URL, let text = try? String(contentsOf: url, encoding: .utf8) {
sharedTexts.append(text)
}
}
} else {
attachment.loadItem(forTypeIdentifier: UTType.data.identifier, options: nil) { data, _ in
defer { group.leave() }
if let url = data as? URL {
let destURL = sharedDir.appendingPathComponent(url.lastPathComponent)
try? fileManager.removeItem(at: destURL)
if (try? fileManager.copyItem(at: url, to: destURL)) != nil {
sharedFileNames.append(url.lastPathComponent)
}
} else if let fileData = data as? Data {
let fileName = "shared-\(UUID().uuidString).md"
let destURL = sharedDir.appendingPathComponent(fileName)
if (try? fileData.write(to: destURL)) != nil {
sharedFileNames.append(fileName)
}
}
}
}
}
}
group.notify(queue: .main) { [weak self] in
self?.openMainApp(texts: sharedTexts, fileNames: sharedFileNames)
}
}
private func openMainApp(texts: [String], fileNames: [String]) {
var components = URLComponents(string: "noteapp://share")!
var queryItems: [URLQueryItem] = []
for (index, text) in texts.prefix(5).enumerated() {
queryItems.append(URLQueryItem(name: "text\(index)", value: text))
}
for (index, fileName) in fileNames.prefix(5).enumerated() {
queryItems.append(URLQueryItem(name: "file\(index)", value: fileName))
}
components.queryItems = queryItems.isEmpty ? nil : queryItems
guard let url = components.url else {
closeExtension()
return
}
extensionContext?.open(url) { [weak self] _ in
self?.closeExtension()
}
}
private func closeExtension() {
extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
}
}