diff --git a/ASSETS.md b/ASSETS.md index 6c16a92..a422fc2 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -9,6 +9,7 @@ - 城市高速路牌的[正式母版与制作说明](docs/design/city-wayposts/v2/README.md)记录了两色预烘焙流程和投影标定。外环组织广告牌复用[铜绿铸铁牌架原画与标定](docs/design/city-wayposts/organization-billboard/README.md),各组织的图标来自当前主页。 - `public/assets/city-runtime/`:由设计源素材及标定流程生成的 107 张运行 PNG,发行时复制到 `assets/city/`。城郊地纹、山脊、雪山和草场的原画、来源与尺寸见[城郊素材记录](docs/design/city-outskirts/v3/SOURCES.md)。 - SVG 投影模板、标定 JSON 与程序绘制道路属于项目代码;运行时只使用本地资源。 +- `public/assets/calendar/`:微缩城市的十二张 WebP 复用 1×1 运行素材 `garden-butterfly`、`cottage-gable`、`courtyard-flat`、`low-terrace`、`res-mansard-stucco`、`civic-clinic`、`res-limestone-bay`、`apartment-h2-b`、`res-sawtooth-duplex`、`office-h3-b`、`office-h3-a`、`tower-h4-b`。裁掉透明留边并缩至长边不超过 184 像素。十二项合计 121,642 字节,发行时复制到 `assets/calendar/`。 生成提示、来源和标定分别保留在 `docs/design/city-buildings/`、`docs/design/city-units/v2/` 至 `v4/`、`docs/design/city-outskirts/`、`docs/design/city-transport/` 和 `docs/design/city-model-expansion/`。部分提示使用城市建造游戏作为质感参考,并要求不复制游戏素材、标志或受保护的特色建筑;没有将游戏图片打包。不能仅凭提示就宣称已完成第三方权利核查。 diff --git a/PRIVACY.md b/PRIVACY.md index 265f568..21ba440 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,12 +1,14 @@ # CodeYears 隐私说明 -更新于 2026-11-19。本说明适用于随附此文件的扩展构建。 +更新于 2026-11-20。本说明适用于随附此文件的扩展构建。 CodeYears 在 GitHub 个人页把每日贡献绘成城市。扩展免费,无需 GitHub Token、独立账号或后台服务。 ## 什么时候读取数据 -普通个人页默认显示 GitHub 原生贡献图。轻量入口只识别 URL、贡献区和年份入口。点击“城市”、使用工具栏快捷入口或打开带 `#codeyears-city` 的城市链接时,才载入城市并读取贡献。旧的 `#codeyears-town` 链接也会打开城市。 +默认的「大规模城市」模式在个人页先显示 GitHub 原生贡献图。点击「城市」页签、弹窗里的打开城市按钮或带 `#codeyears-city` 的链接后,才载入城市并读取历史贡献。旧的 `#codeyears-town` 链接也能在该模式下打开城市。 + +「微缩城市」使用当前日历已经显示的日期和颜色档位。档位用于决定建筑样式,精确数量仍由 GitHub 原生日期提示提供。扩展在此模式下不会请求历史或活动,也不把这张日历写入缓存。 - **查看自己的主页。** 扩展核对当前 GitHub 登录身份,以该会话读取 GitHub 实际提供的年度日历和建筑活动。合计可包含你本人有权看到的私有贡献。组织的访问和 SSO 设置仍由 GitHub 决定。 - **查看其他人的主页、退出登录或身份不明。** 年度和活动请求均不携带登录凭据。城市只呈现匿名访客可以看到的内容,其中可能包含对方主动公开的匿名私有贡献数。公开日历不可用时会提示。 @@ -18,7 +20,7 @@ CodeYears 在 GitHub 个人页把每日贡献绘成城市。扩展免费,无 年度日期、数量、抓取时间和格式版本保存在当前设备的扩展本地存储中,按访问者、主页和年份隔离。身份未知时不读写年度缓存。新构建不复用旧版按登录访客抓取的缓存。完整 HTML 不进入缓存。 -当年快照最多复用一小时,跨本地日期失效;重新读取的历史年度最多复用三十天。过期记录可能留在存储中,直到覆盖或清除。选“更多 → 清除年度贡献缓存”可删除当前访问者在当前主页的新旧年度记录。“刷新所选年份”会重新请求数据。语言偏好单独保存在本机。 +当年快照最多复用一小时,跨本地日期失效;重新读取的历史年度最多复用三十天。过期记录可能留在存储中,直到覆盖或清除。选“更多 → 清除年度贡献缓存”可删除当前访问者在当前主页的新旧年度记录。“刷新所选年份”会重新请求数据。语言、城市页签显隐和贡献图样式偏好单独保存在本机。 建筑活动详情在页面内存中最多复用五分钟。切回原图会隐藏城市和摘要。切换浏览器标签页时,公开城市保留画面,本人城市暂时隐藏。恢复本人城市之前会重新核对会话,暂时无法核对时保持隐藏,确认换号时丢弃旧画面。离开页面会释放场景及详情。部分详情查询失败时本地控制台可能记录失败原因和处理条数,不记录访问者、仓库名、完整响应或凭据。 @@ -36,7 +38,7 @@ CodeYears 在 GitHub 个人页把每日贡献绘成城市。扩展免费,无 ## 权限与图片 -- `storage` 用于本地年度贡献缓存和语言偏好。 +- `storage` 用于本地年度贡献缓存、界面语言、城市页签显隐和贡献图样式。 - `activeTab` 和 `scripting` 用于从工具栏快捷打开当前标签的扩展入口。自动入口仅声明 `https://github.com/*`。 - 脚本及城市素材随包提供。原生右键菜单可以保存或复制画布,图片可能反映你本人可见的贡献。若浏览器限制将某个跨域组织头像导出,保存的城市图片在对应牌面使用组织账号缩写。扩展不自动上传图片。 diff --git a/README.md b/README.md index 0996cf3..bdaa586 100644 --- a/README.md +++ b/README.md @@ -10,16 +10,24 @@ CodeYears 是免费的 Manifest V3 浏览器扩展,将 GitHub 个人主页中 ## 使用方式 -允许扩展在 GitHub 运行后,个人贡献区出现文件夹式“城市 / 贡献图”标签,默认仍显示 GitHub 原图。点击城市、使用工具栏快捷入口或经城市直达链接抵达后加载面板并读取历史,默认最近三年。先显示完整空场地与道路,再随已校验年度数据填入地块;未知、未返回和未来日期不补零。读取、取消、警告和失败在画布浮层内显示,正常完成后隐藏。 +个人贡献区默认提供「城市」和「贡献图」两个页签。在 GitHub 个人主页的贡献区打开浏览器工具栏的 CodeYears 弹窗,可显示或隐藏「城市」页签、直接打开城市,以及调整贡献图样式和界面语言。在其他页面打开弹窗时,设置项置灰,并显示切换到个人主页的提示。显示设置和语言偏好保存在本机。弹窗页脚提供版本信息及「官网」「关于作者」「源代码」「问题反馈」四个入口。产品官网提供隐私说明。「关于作者」在弹窗中展示作者简介、官网及其他四款扩展的 Chrome 商店链接。 + +「贡献图样式」可选择「GitHub 原图」或「微缩城市」。同时显示两个页签时,也可点「贡献图」里的「微缩城市」按钮切换样式。 + +**大规模城市。** 点击「城市」页签、弹窗里的「打开城市」或城市直达链接后,会加载城市并读取历史,默认最近三年。 + +**微缩城市。** 在 GitHub 原贡献图的尺寸内,把原生日格的圆角设为 50%,沿用其浅灰实线边框。建筑叠在有贡献的日格上。底色跟随 GitHub 主题。五档图例由一个圆点和四档建筑组成,年份切换、日期点选与提示继续由 GitHub 提供。 + +### 浏览大规模城市 + +城市先显示空场地与道路,再随已校验年度数据填入地块。读取、取消、警告和失败在画布浮层内显示,正常完成后隐藏。 修改起止年份后城市自动更新。两端交叉时,另一端跟随你刚选的年份,形成单年范围。合计旁显示实际覆盖的起止日期。滚轮或按钮缩放、拖动平移,聚焦城市画布后用方向键平移,“全景”让城区、已命名的出城路牌和返程牌完整入画。可在当前页面内展开同一画布,按 Esc、点击遮罩或“收起”返回。初始 100% 对应旧版 150% 的取景,最大不超过 2000%,较小城市也受素材细节上限约束。缩放不改变数量和建筑合并。 -切回 GitHub 原图时,原生贡献图和活动概览一起恢复,完整城市留在页内内存。切换浏览器标签页时,公开城市保留画布、展开状态和取景,回到前台即可续看。本人城市在后台暂时隐藏,在回到前台时静默核对身份,再复用仍有效的画布。身份暂时无法核实时可重试,确认换号、刷新、清除缓存或离开主页会释放旧城市。 +切回「贡献图」页签时,按已选样式显示日历,同时恢复活动概览,完整城市留在页内内存。切换浏览器标签页时,公开城市保留画布、展开状态和取景,回到前台即可续看。本人城市在后台暂时隐藏,在回到前台时静默核对身份,再复用仍有效的画布。身份暂时无法核实时可重试,确认换号、刷新、清除缓存或离开主页会释放旧城市。 “更多”按主页操作与帮助分组,可刷新或清除当前主页缓存;帮助与图例可折叠。打开「更多 → 路牌和出口从哪里来?」可查看出口、返程牌和外环组织牌的来源。也可以直接点地图上的空白出口牌,查看如何在自己的 GitHub 简介中用 `@用户名` 连接朋友。点击菜单外部或按Esc关闭菜单。可在其中选择英文、简体中文或跟随浏览器。界面双语不表示所有GitHub网页语言都能解析:当前贡献来源主要验证英文页面。GitHub页面结构或访问权限变化可能导致读取停止,失败不会当作零贡献。 -扩展图标左键仍快捷打开当前GitHub主页的城市;在扩展图标上使用浏览器原生右键菜单的“选项”,可设置全局界面语言,并查看版本、帮助、隐私与反馈入口。语言保存后会联动GitHub页内入口,刷新后仍保留偏好。 - 调整取景后,在画布上右键使用浏览器原生保存或复制图片菜单。没有独立导出或分享服务;正式入口不提供暂停、继续、跳过或重播。 ## 城市与数据 diff --git a/docs/DATA_AND_PRIVACY.md b/docs/DATA_AND_PRIVACY.md index 7df3bd5..01dcf31 100644 --- a/docs/DATA_AND_PRIVACY.md +++ b/docs/DATA_AND_PRIVACY.md @@ -1,5 +1,7 @@ # 数据与隐私 +2026-11-20 贡献图样式 `codeyears:ui:appearance` 和城市页签显隐 `codeyears:ui:show-city` 分别保存在本机。样式可选 `native` 或 `miniature`,默认 `native`。城市页签默认显示。旧样式值 `city` 和 `off` 都按原图处理,旧微缩偏好继续适用。微缩视图读取 GitHub 当前日历的日期和显示档位,档位只用于选造型。日期提示继续由 GitHub 提供。微缩视图不推算数量、不请求历史、活动或访问者信息,也不读写年度缓存。 + 2026-11-19,城市静态车流使用当前主页资料栏可直接读取的粉丝数和关注数。计数缺省时采用基础密度。数字只在当前页面用于布车,转化为装饰强度并随道路规模封顶。 当前城市链接的浏览器片段可保存已选起止年份,例如 `#codeyears-city?from=2018&to=2026`。年份从页面已有年度入口校验,片段随当前历史项更新。 diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index 826932a..c24c04a 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -1,5 +1,7 @@ # 性能约束与验证 +2026-11-20 显示微缩贡献图时按需加载 `calendar.js`(6.39 kB,gzip 2.64 kB)和 121,642 字节的本地 WebP。圆格样式直接作用于原生日格。建筑画布定位在原生日格范围。尺寸和日历数据变化合并到下一次单帧重绘。切回原图、进入大规模城市或离开主页时拆下微缩图层和监听,同页可复用已解码的素材。关闭城市页签时释放大规模城市视图。Chrome 公开主页与发行结构实测见[本轮报告](reports/CONTRIBUTION-CALENDAR-APPEARANCE.md)。 + 2026-11-11 全部路牌右置:默认、分岔、已有返回出口及独立临时返程,均位于离城右侧。创建路牌时对安装处的可见出城路面做横切,支架包络置于右侧车行面外,避免重新压到分岔。临时返程与普通目的地共路时,右半幅按靠城/靠外分段;字宽和命中区共用段范围。新增计算仅在路牌准备时执行,没有新资源、请求、帧循环或缓存框架。修改按钮用独立CSS translate定位,保留按压scale,避免按下跳位。验证见[本轮报告](reports/RIGHT-HAND-WAYPOSTS-AND-EDIT-CLICK.md)。 2026-11-11 路牌精度与交通修正:四张运行图从正式原图按2048上限重烘焙,合计5,619,299 bytes,前版400,665 bytes;每种地图仍仅加载两张,解码驻留像素也增加。低饱和配色在离线完成,没有帧内滤色;脚点/分岔位置及视觉字高校准仍在场景准备时计算。车辆仅翻转侧向偏移,桥曲线和车型不变,沿用原缓存及静止停绘。实际最大缩放、128个脚点与浏览器交通检查见[本轮报告](reports/ROAD-SUPPORTS-TRAFFIC-AND-STORAGE.md),不宣称硬件性能预算通过。 diff --git a/docs/PRODUCT.md b/docs/PRODUCT.md index a68d955..ecd3831 100644 --- a/docs/PRODUCT.md +++ b/docs/PRODUCT.md @@ -1,5 +1,9 @@ # 产品定义 +2026-11-20 贡献区默认显示「城市」和「贡献图」页签。点击「城市」按需加载多年场景。工具栏弹窗顶部的「城市」分组提供页签显隐与快捷打开入口。贡献图样式独立设置,默认显示 GitHub 原图,同时显示两个页签时也可用页内按钮切换微缩城市。微缩城市通过 CSS 把原生日格的圆角设为 50%,沿用 GitHub 的细实线边框。建筑在原日期区内错列绘制并叠在日格上方。背景沿原日期区的矩形范围填色,底色跟随 GitHub 主题。五档图例用圆点和四级建筑示意。房型从原有 1×1 运行素材中按 GitHub 档位随机选取,顶部建筑缩小以适应边界。日期操作和提示继续由 GitHub 提供。两项设置同步到已打开的个人主页。 + +工具栏弹窗在当前标签为有贡献图的 GitHub 个人主页时开放设置与城市快捷打开。「打开城市」是主要操作,保存反馈出现在对应设置组下。在其他页面显示说明,城市、贡献图样式和语言控件置灰。页脚提供版本信息、对应界面语言的产品官网、关于作者、GitHub 仓库和问题反馈页。「关于作者」进入弹窗内的二级页面,介绍作者并列出其他四款 Chrome 扩展。各外部链接由用户点击后在新标签页打开。 + 0.1.3 远郊由成片的林木山脊和丘陵覆盖,城区和河谷之间保留开阔低地,较宽阔的远景可以看见雪山。野外地面由浅草、湿苔、碎石草地和偏干草地按地图坐标随机拼接,相邻纹理沿边缘逐渐混合。主河经过城区桥梁,城外沿不同方向转入河谷。支流沿途拓宽成小湖,河谷里还有独立的小湖。出城路牌靠近城区,公路过牌后依据山体轮廓与实际岸线找通路,优先沿岸,必须跨水时选择较窄的过河点,桥面和护栏随两岸位置接续。公路继续延伸到视野边缘。道路较宽时布车更密,当前资料栏的粉丝数与关注数温和调整整体密度。进入城市时随机生成静态车阵,查看期间缩放和平移复用原有车辆位置。 0.1.3 中,修改任一端年份立即更新城市。两端交叉时,另一端跟到所选年份。城市链接在当前历史项带上起止年份,例如 `#codeyears-city?from=2018&to=2026`,刷新或打开链接后恢复所选区间。所选范围跨过可用日期边界时,合计旁仍显示实际提供的日期。切换浏览器标签页时,公开城市保留画布、展开和取景,本人城市在确认会话后恢复。标签在后台时停止逐帧绘制。指针在地图内时,滚轮控制缩放,到上下限后停在原位。把指针移到地图外可继续滚动网页。 diff --git a/docs/STORE_LISTING.md b/docs/STORE_LISTING.md index 94faa90..d7d6094 100644 --- a/docs/STORE_LISTING.md +++ b/docs/STORE_LISTING.md @@ -1,5 +1,7 @@ # CodeYears 商店材料 +[0.1.4 上传交接](store/city-0.1.4/README.md)包含中英文文案、审核步骤与新增的微缩城市截图。每种语言保留 0.1.3 的前三张图。 + 0.1.3 候选构建从当前主页的 Bio 生成个人出口,从 Bio、资料栏与 Organizations 列表生成组织广告牌,仅使用页面已有的账号和图标。手动路牌和 Chrome 路牌同步已撤下。年度贡献缓存与语言偏好保存在本机,返程只属于当前标签页。候选构建的权限与数据用途见[随包隐私说明](../PRIVACY.md)。下方 0.1.2 材料描述此前提交的独立构建。 0.1.3 的起止年份在选定后自动更新,合计旁列出实际数据日期。切换浏览器标签页时,公开城市保留当前画面和取景,本人城市恢复前会核对会话。 diff --git a/docs/reports/CONTRIBUTION-CALENDAR-APPEARANCE.md b/docs/reports/CONTRIBUTION-CALENDAR-APPEARANCE.md new file mode 100644 index 0000000..90f5f5b --- /dev/null +++ b/docs/reports/CONTRIBUTION-CALENDAR-APPEARANCE.md @@ -0,0 +1,58 @@ +# 微缩贡献图与工具栏设置验收 + +日期 2026-11-20。PR #87 的反馈修订,基线 `6604565`。 + +## 复现 + +1. 安装锁定依赖后运行 `npm run build`。构建包含 `npm run check`。 +2. 使用新建、未登录的 Chrome 配置加载 `dist/`,打开公开 GitHub 个人主页 `https://github.com/torvalds`。 +3. 分别在站外页面、GitHub 仓库、GitHub 组织主页和有贡献图的个人主页打开弹窗。确认前三处有说明且所有设置控件禁用。个人主页的弹窗顶部应有独立「城市」分组,包含页签开关和打开按钮。用复选框隐藏城市,再切换贡献图样式。对照 `table.ContributionCalendar-grid`、`thead` 和微缩覆盖层的尺寸。 +4. 在 GitHub 明暗主题下检查微缩图、建筑与五档图例。对照两种样式下 `.ContributionCalendar-day` 和 `.ContributionCalendar-day[data-level="0"]` 的圆角与边框,确认微缩覆盖层的子元素只有建筑画布。悬停及点选有贡献的日格,观察 GitHub 原生日期提示和选中状态。 +5. 刷新验证设置保留。城市隐藏时打开城市直达链接,确认仍显示所选的贡献图。重新勾选复选框,从工具栏快捷按钮进入大规模城市,再取消勾选。用原生年份链接切换到 2024 年后切回原图。 +6. 将打包输出放到独立临时目录,运行 `python3 scripts/package-city.py --output-dir <临时目录>` 和 `python3 scripts/verify-city-package.py <临时目录>/codeyears-0.1.3-city.zip`。 + +## 实际结果 + +- macOS Chrome 158.0.8127.36 以全新未登录的无头配置加载实际 MV3 构建。通过 DevTools Protocol 触发工具栏动作、标签点击和原生鼠标事件。 +- 在 `https://example.com/`、`https://github.com/wxy/CodeYears` 和 `https://github.com/github` 打开弹窗,均显示个人主页提示。城市页签开关、打开城市按钮、两种贡献图样式及语言菜单均禁用。尝试点按未改变本机偏好,页脚帮助可见。返回 `https://github.com/torvalds` 后,控件启用并可保存设置。 +- 350 像素宽弹窗实看通过。顶部「城市」分组的标题字号大于下方「贡献图样式」,开关点击区约 50 像素高,快捷按钮位于同组。点击开关标签可以切换页签。 +- 原图与微缩模式均显示 370 个日期,表格同为 723 × 113 CSS 像素,月份标题行高 13 像素,图表高 143 像素。微缩覆盖层与原生日格范围同为 686 × 88 像素。 +- 明暗主题实看通过。370 个原生日期格在微缩模式为等宽等高的 50% 圆角,测试中的原图为 2 像素圆角。GitHub 源样式声明为 `.5px solid`,该 Chrome 会话在两个模式中都以 1 CSS 像素报告计算后的边框。建筑画布叠在日格上方,矩形底板圆角为 0,原生外框的上角在两种样式下都为 6 像素。GitHub 日期悬停提示和实际鼠标点选通过。 +- 城市显示和隐藏均可配合 GitHub 原图或微缩样式。隐藏后刷新或访问城市直达链接继续显示贡献图。开启时快捷按钮可打开大规模城市并绘制画布,关闭当前城市页签会释放大规模场景并恢复微缩图。切换年份和还原原图通过。 +- TypeScript、Vite 构建和发行包核验通过。测试 ZIP 137 项,33,436,091 字节。SHA-256 为 `f23e75816fda6c46ffd8b3e577ae5599030bc4044c16e0d6434820b4ffdd561e`。 + +这次覆盖匿名公开主页与本地 MV3 构建。登录会话、私有贡献、Edge、商店发行及整套硬件性能预算另行验收。 + +## 页脚入口 + +日期 2026-11-20,基线 `b68ec04`。运行 `npm run build` 后,在全新未登录的 macOS Chrome 158.0.8127.36 中加载 `dist/`。通过实际工具栏动作打开弹窗,在 GitHub 个人主页分别切换英文和简体中文,核对页脚顺序、文本、网址和版本号。放大页脚文字再检查换行。将活动标签切至站外页面,检查页脚是否仍能使用。 + +- 两种语言的四个入口在 350 像素宽弹窗内完整显示。模拟放大页脚文字到 17 像素后,导航换行且无横向溢出。四个链接的点击区域均至少为 24 × 24 CSS 像素。 +- 中文官网链接打开 `/zh/extensions/codeyears`,英文对应 `/extensions/codeyears`。官网、作者首页、仓库、Issue 列表四项均在独立标签页打开。作者首页和两种语言的产品页在线 HTTP 200,产品页均提供隐私说明链接。站外的设置控件置灰时,页脚链接仍可访问。 +- TypeScript、Vite 构建和发行包核验通过。测试 ZIP 137 项,33,436,370 字节。SHA-256 为 `439433980a1f4e6945f82cab398fb13879228a396ad44f870aa3da62249d8ef1`。 + +## 0.1.4 作者页与审核候选 + +日期 2026-11-20,基线 `60f9a51`。Chrome 商店公开详情当前显示 0.1.3,本轮候选版本为 0.1.4。运行 `npm run build`,然后执行 `python3 scripts/package-city.py --output-dir <候选目录>` 和 `python3 scripts/verify-city-package.py <候选目录>/codeyears-0.1.4-city.zip`。 + +- macOS Chrome 158.0.8127.36 以新建的未登录配置加载实际 MV3 构建。通过工具栏打开弹窗,在 GitHub 公开个人主页验证「打开城市」。在 350 像素宽的中英文弹窗核对页脚四个入口与版本号同行,所有链接的 HTML `title` 等于解析后的目标地址。明暗主题实看通过。 +- 实测键盘进入作者页、浏览器返回和「返回设置」键盘操作。返回后焦点回到「关于作者」,界面语言保留。站外页面的设置保持禁用,作者页仍可打开。 +- 实际点开 HiTable、Navigraph、Silent Feed 和 AI Pulse,四项均进入独立 Chrome 商店详情标签页。AI Pulse 使用当前可公开访问的商店条目,编号为 `dpacojibmleehcmmkcabnbgeadofkkpe`。这些链接由用户点击时打开。 +- 保存反馈紧邻对应设置。空闲状态零占位。受控存储写入失败时,贡献图回到已保存的选项并显示错误。恢复存储后重试,微缩图正常出现并显示「已保存」。 +- TypeScript、Vite、版本、资源引用、权限及发行包核验通过。候选 ZIP 137 项,33,438,140 字节,SHA-256 为 `0c5fdd93b8975ee53711f334330f33ec21d9fec90ae92d66cc926dc4b92bc9a8`。本机 `dist/` 与候选 ZIP 的 133 项运行文件逐字节一致。 + +该轮候选包保留在项目的 `release/codeyears-0.1.4-city.zip`。本次记录覆盖本地候选验证。 + +## 防止城市页签重复嵌套 + +日期 2026-11-20,修复前基线 `4ccba64`。在 macOS Chrome 158.0.8127.36 的临时未登录配置加载 MV3 构建,打开 `https://github.com/torvalds`。用 DevTools Protocol 加载两个路径下的构建以获得独立的扩展脚本上下文,并用 `Extensions.triggerAction` 触发对应工具栏弹窗。 + +- 修复前,单实例打开城市后切回贡献图只有一组页签。对同一主页触发第二份构建的弹窗后,页面出现两组嵌套页签和两个城市容器。打开城市再切回贡献图时,嵌套仍存在。用户报告在其浏览器刷新后恢复。复现验证了独立脚本重复接管贡献区的机制。 +- 在同一标签页用 `Extensions.uninstall` 卸载旧候选后,旧视图仍留在页面上。加载修复版,点「打开城市」会提示刷新,页面只保留原有的一组页签和一个城市容器。刷新后,修复版能从弹窗打开实际城市画布,切回贡献图仍只有一组页签。 +- 主页已加载修复版时打开第二份修复构建的工具栏弹窗,页面仍只有一组页签。移除第二份构建后,开启微缩城市,再从弹窗进入大规模城市和切回贡献图,恢复一张微缩画布。 +- 实际 Chrome 将脚本探测的缺失返回值序列化为 `null`。弹窗据此补载入口。已有脚本可直接处理打开城市的请求。 +- `npm run build`、`python3 scripts/package-city.py --output-dir <候选目录>` 和 `python3 scripts/verify-city-package.py <候选目录>/codeyears-0.1.4-city.zip` 通过。修复候选包位于 `release/review-0.1.4/codeyears-0.1.4-city.zip`,137 项,33,438,579 字节,SHA-256 为 `536d626ababf0ee3f5570c80dd9445a55e9d8d52335cc28490ad66f853529059`。 +- [0.1.4 商店材料](../store/city-0.1.4/README.md)使用修复版在未登录的 Chrome 打开 `https://github.com/wxy`,实拍英文及简体中文微缩贡献图。两张 RGB JPEG 均为 1280 × 800,保留 370 个原生日格的日期范围。全球截图组复用英文图。素材包核对前三张截图、宣传图块和商店图标与 0.1.3 素材包逐字节一致。 +- 素材包位于 `release/review-0.1.4/codeyears-store-media-0.1.4.zip`,内含 12 张分组截图、3 项沿用的宣传图块与图标、中英文文案、审核说明和素材清单。SHA-256 为 `a4b4695e4a7095522e4cec09e2dc4fadd90cdba877012cbd093ed5e37ccbcd50`。 + +本次未读取审核后台。上述运行验证覆盖公开主页上的本地扩展。 diff --git a/docs/store/city-0.1.4/README.md b/docs/store/city-0.1.4/README.md new file mode 100644 index 0000000..e1eb309 --- /dev/null +++ b/docs/store/city-0.1.4/README.md @@ -0,0 +1,27 @@ +# CodeYears 0.1.4 Chrome 商店交接 + +在 Chrome 应用商店后台的「软件包」上传修复版候选 `codeyears-0.1.4-city.zip`。安装包与这个素材包是两个文件。 + +- [商店文案](store-listing.md)提供英文和简体中文的完整可复制文本。这次需要更新详细说明。名称和简短说明沿用 0.1.3。 +- [审核说明](review-notes.md)说明新版可见变化、公开个人主页的复现步骤和作者页链接的行为。 +- 官网、支持页、隐私政策和已有宣传图块沿用现有商店配置。产品页提供对应语言的入口。 + +## 截图按语言放置 + +| 商店位置 | 素材包目录 | 新增文件 | +| --- | --- | --- | +| 全球截图 | `global/` | `04-miniature-calendar.jpg`,与英文图逐字节一致 | +| English 本地化 | `localized/en/` | `04-miniature-calendar.jpg` | +| 简体中文本地化 | `localized/zh_CN/` | `04-miniature-calendar.jpg` | + +每组保留 0.1.3 的三张图片和原来的顺序。第 4 张使用当前候选版在 Chrome 中实拍,展示 GitHub 公共个人主页的微缩城市。三组截图都是 1280 × 800 像素的 RGB JPEG。[Chrome 截图规格](https://developer.chrome.com/docs/webstore/images#screenshots) + +## 第 4 张截图配文 + +**简体中文** + +微缩城市就在贡献图里。每个有贡献的日子对应一栋小建筑,可以随时切回 GitHub 原图。 + +**English** + +See daily contributions as miniature buildings in GitHub’s contribution graph. Switch back to the original graph whenever you like. diff --git a/docs/store/city-0.1.4/localized/en/04-miniature-calendar.jpg b/docs/store/city-0.1.4/localized/en/04-miniature-calendar.jpg new file mode 100644 index 0000000..e602ea5 Binary files /dev/null and b/docs/store/city-0.1.4/localized/en/04-miniature-calendar.jpg differ diff --git a/docs/store/city-0.1.4/localized/zh_CN/04-miniature-calendar.jpg b/docs/store/city-0.1.4/localized/zh_CN/04-miniature-calendar.jpg new file mode 100644 index 0000000..a09fad3 Binary files /dev/null and b/docs/store/city-0.1.4/localized/zh_CN/04-miniature-calendar.jpg differ diff --git a/docs/store/city-0.1.4/review-notes.md b/docs/store/city-0.1.4/review-notes.md new file mode 100644 index 0000000..8d261df --- /dev/null +++ b/docs/store/city-0.1.4/review-notes.md @@ -0,0 +1,27 @@ +# CodeYears 0.1.4 审核说明 + +## English + +```text +CodeYears visualizes the contribution calendar on GitHub personal profiles. + +1. Open https://github.com/wxy/ in Chrome. The public contribution calendar can be used while signed out. +2. Open CodeYears from the browser toolbar. Set Contribution graph style to Miniature city. Miniature buildings appear within GitHub's contribution calendar. Hover over a date to see GitHub's date tooltip. Choose GitHub original to restore the original graph. +3. With Show City tab checked, click Open City to view multiple years. Use the Contributions tab on the page to return to the calendar. The toolbar setting also lets you hide the City tab. +4. Author in the popup footer opens an author information view. Its four project links open each extension's own Chrome Web Store listing in a new tab when clicked. Back to settings returns to the popup settings. + +The miniature view uses the contribution levels GitHub has already rendered, without making additional contribution requests. The full City view requests contribution data directly from GitHub. CodeYears stores interface preferences and the annual contribution cache locally. The extension uses the same permissions as 0.1.3. activeTab and scripting let the toolbar open City on the current GitHub profile, and storage saves preferences and the annual contribution cache. +``` + +## 简体中文 + +```text +CodeYears 在 GitHub 个人主页可视化贡献日历。 + +1. 在 Chrome 打开 https://github.com/wxy/。未登录时也可以用公开贡献图验证。 +2. 点击浏览器工具栏的 CodeYears 图标,把「贡献图样式」切换为「微缩城市」。建筑在原贡献图范围内显示,悬停日期可看到 GitHub 的提示。选择「GitHub 原图」可以恢复原图。 +3. 勾选「显示城市页签」,点「打开城市」查看多年贡献。点击页面中的「贡献图」页签可回到日历。也可在弹窗取消勾选来隐藏城市页签。 +4. 页脚「关于作者」进入作者介绍页。点击四个扩展链接中的任一项会在新标签页打开它各自的 Chrome 商店详情。「返回设置」回到弹窗设置。 + +微缩图直接使用 GitHub 已渲染的贡献档位,无需再请求贡献数据。大规模城市直接向 GitHub 请求贡献数据。权限沿用 0.1.3。activeTab 和 scripting 用于从工具栏打开当前 GitHub 个人主页的城市,storage 用于在本机保存界面偏好和年度贡献缓存。 +``` diff --git a/docs/store/city-0.1.4/store-listing.md b/docs/store/city-0.1.4/store-listing.md new file mode 100644 index 0000000..9262090 --- /dev/null +++ b/docs/store/city-0.1.4/store-listing.md @@ -0,0 +1,105 @@ +# CodeYears 0.1.4 · Chrome Web Store 文案 + +## English + +### Name + +CodeYears: GitHub Contribution City + +### Short description + +A free GitHub contribution visualizer. Turn real daily contributions into a city. + +### Detailed description + +```text +Your years of code, a city of their own. + +CodeYears turns daily GitHub contributions into a city you can explore. Smaller counts bring in houses, while higher counts can produce apartments, offices and towers. Days with zero contributions appear as greenery or paving, depending on the surroundings. Zoom out to see years of work together, or zoom in to see the dates and activity behind a building. + +A miniature city inside the contribution graph + +On a GitHub personal profile, select Miniature city in the Contributions tab or in the CodeYears toolbar settings. Small buildings appear within the original calendar area. The five-level legend follows GitHub’s contribution levels, and GitHub continues to provide date selection and tooltips. Choose GitHub original at any time to switch back. + +Open the city and choose your years + +Select City beside the contribution graph, or open CodeYears from Chrome’s toolbar and click Open City. The city starts with the most recent three available years. Changing either end of the range updates the map immediately. The URL remembers your selection so you can reopen it or share the same range with someone who has CodeYears installed. + +Terrain and roads appear first, then buildings fill in as yearly data arrives. The earliest year shown on the GitHub profile sets the starting point for fixed five-year districts. Contributions are grouped by complete ISO weeks, so a week around New Year can span two calendar years. The contribution total shows the dates it actually covers. + +Follow the highway signs + +Blue exit signs lead to contribution cities for personal accounts mentioned in the profile’s Bio. Add friends to your own Bio with @username mentions, and CodeYears places them at available exits in order. Click an empty sign for instructions. After following an exit, use the return sign to go back to the previous city in the same tab. + +Billboards along the ring road display organizations from the Bio, profile details and Organizations list. Click one to visit the organization on GitHub. If the ring road runs out of space, the remaining organizations are available from the map’s organization list. + +Explore districts and individual buildings + +Roads connect districts, curve around hills and riverbanks, and cross water on bridges. Beyond the streets are wooded ridges, branching rivers, lakes and distant snowy peaks. Highways continue to the edges of the view. + +Scroll to zoom and drag to pan. When the canvas is focused, use the arrow keys to pan and + or - to zoom. Fit view frames the city and its named road signs, while Maximum zoom brings you in for a closer look. Expand the city within the page, then press Esc or click the backdrop to return. + +Hover over or select a building to see the dates it represents and their actual contribution total. CodeYears loads available GitHub activity summaries on demand, including related repositories and approximate counts for commits, pull requests, reviews and issues. When GitHub activity confirms the date you joined and that day is in view, a distinctive tower marks it. + +Save your city + +Frame your view, then right-click the canvas to save or copy it using Chrome’s image menu. Right-clicking includes the City of Code plaque in the image, with the profile’s GitHub handle and a Made with CodeYears credit. While exploring, mouse activity reveals the plaque. It fades after five seconds of inactivity. + +Language, cache and privacy + +Open More for the legend, viewing instructions and an explanation of where the signs come from. You can also refresh the selected years, clear the profile’s yearly contribution cache, or choose English, Simplified Chinese or the browser language. The CodeYears toolbar popup on a GitHub personal profile lets you show or hide the City tab, choose the contribution graph style and set the interface language. Its footer links to the product website, source code and feedback. The product website provides the privacy policy. + +CodeYears is free. On your own profile, it verifies your current GitHub session and shows the contributions GitHub makes available to you, including private contributions you can see. Other profiles and signed-out or unverified sessions use GitHub’s signed-out view. That view may include anonymized private contribution counts the profile owner has chosen to show. Yearly contribution records are cached locally by viewer, profile and year. Your language preference is also stored on the device. +``` + +## 简体中文 + +### 名称 + +CodeYears:GitHub 贡献之城 + +### 简短说明 + +免费的 GitHub 贡献历史可视化扩展。选择年份,用真实每日贡献生成贡献之城。 + +### 详细说明 + +```text +代码岁月,自成风景。 + +CodeYears 把真实的 GitHub 每日贡献绘成一座可以探索的城市。贡献较少的日子对应小住宅,较高的贡献档位会出现公寓、办公楼和大厦。零贡献的地块则根据周围环境呈现为草地、植被或铺装。拉远可以看到多年的开发轨迹,拉近可以查看一栋建筑对应的日期和活动。 + +在贡献图里看微缩城市 + +打开 GitHub 个人主页后,默认显示原生贡献图。在「贡献图」页签或工具栏弹窗中选「微缩城市」,原日期范围里会出现小建筑。五档图例沿用 GitHub 的贡献档位,日期点选和悬停提示继续由 GitHub 提供。随时可以切回「GitHub 原图」。 + +打开城市,选择年份 + +点击贡献区的「城市」页签,或在 Chrome 工具栏的 CodeYears 弹窗点「打开城市」,即可在当前主页查看多年的贡献之城。默认展示最近三个可用年份。修改起始年或结束年,画面随即更新。城市网址会记住所选区间,刷新后可以继续查看,也可以把这段年份分享给同样安装了 CodeYears 的人。 + +地形和道路先出现,建筑随各年的贡献数据逐步填入。城区从 GitHub 主页列出的最早年份起,每五年划为一个固定城区。贡献日期按 ISO 完整周组织,年初年末的同一周可能包含相邻公历年的日期。贡献合计旁会标出实际覆盖的日期。 + +沿公路前往其他贡献城市 + +蓝色高速出口牌来自 GitHub 简介(Bio)中提及的个人账号。在自己的简介里写入朋友的 @用户名,CodeYears 会按出现顺序把这些账号放到可用的出口上。点击空白出口牌可查看设置方法。沿具名路牌进入另一座城市后,可以通过返程牌回到当前标签页里来时的城市。 + +外环路边的广告牌展示来自简介、资料栏和 Organizations 列表的组织图标。点击广告牌可打开相应的 GitHub 组织主页。外环放不下的组织仍可从地图上的组织名录打开。 + +从城区全景看到建筑细节 + +道路连接各个城区,沿着山丘和水岸转弯,在需要过河的地方架起桥梁。城郊有林木覆盖的山脊、分叉的河流、湖泊和远处的雪山,出城公路延伸到视野边缘。 + +滚动鼠标滚轮可缩放,拖动可平移。画布获得焦点后,也可用方向键移动,用 + 和 - 缩放。右下角的「全景」会把城区和已命名的路牌一同纳入取景,「最大倍率」可快速查看近景。可在当前页面展开城市,按 Esc 或点击遮罩返回。 + +悬停或选中一栋建筑,可以查看它涵盖的日期与真实贡献合计。CodeYears 会按需读取 GitHub 可见的活动摘要,包括相关仓库,以及提交、拉取请求、评审和 Issue 的可用汇总。查看最早年份时,如果 GitHub 的活动记录明确标出了加入日期,城市会用一座纪念塔标记那一天。 + +保存你的城市 + +调整好取景后,右键点击城市画布,即可通过 Chrome 原生菜单保存或复制图片。右键会把左下角的 City of Code 铭牌带入图片,为分享的画面保留当前主页的 GitHub 账号和 Made with CodeYears 署名。浏览时,鼠标在画布上活动会显示铭牌,静止五秒后收起。 + +语言、缓存和隐私 + +「更多」菜单提供图例、操作说明和路牌来源,也可以刷新所选年份或清除当前主页的年度贡献缓存。界面支持英文、简体中文及跟随浏览器语言。在 GitHub 个人主页打开 CodeYears 工具栏弹窗,也可以设置城市页签显隐、贡献图样式和界面语言。页脚提供官网、源代码和问题反馈入口,隐私说明可在产品官网查看。 + +CodeYears 免费使用。查看自己的主页时,扩展会核对当前 GitHub 会话,并显示 GitHub 向该会话提供的贡献,其中可以包含本人有权查看的私有贡献。访问其他人的主页、退出登录或身份未能确认时,城市使用匿名访客可见的数据,其中可能包含主页主人选择公开的匿名私有贡献数。年度贡献缓存在本机,按访问者、主页和年份隔离,语言偏好也保存在本机。 +``` diff --git a/options.html b/options.html deleted file mode 100644 index 6712a47..0000000 --- a/options.html +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - CodeYears - - - -
-

-

- - - -
-

-

- -
-
- - - diff --git a/package-lock.json b/package-lock.json index e94aad7..2a0b266 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "codeyears", - "version": "0.1.3", + "version": "0.1.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "codeyears", - "version": "0.1.3", + "version": "0.1.4", "dependencies": { "three": "0.186.1" }, diff --git a/package.json b/package.json index f96edd7..8925552 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "codeyears", - "version": "0.1.3", + "version": "0.1.4", "private": true, "license": "MIT", "description": "免费的 GitHub 贡献历史可视化浏览器扩展", diff --git a/popup.html b/popup.html index 63227e9..5dfc4da 100644 --- a/popup.html +++ b/popup.html @@ -1,15 +1,151 @@ - + + CodeYears -
+
+
+

+ +
+ +
+ + +
+
+
+ +
+ + +
+
+
+ + +
+ +
+ + +
+
+ +
diff --git a/public/_locales/en/messages.json b/public/_locales/en/messages.json index b2067f7..23de4b4 100644 --- a/public/_locales/en/messages.json +++ b/public/_locales/en/messages.json @@ -6,7 +6,7 @@ "message": "A free GitHub contribution visualizer. Turn real daily contributions into a city." }, "actionTitle": { - "message": "CodeYears · Contribution City" + "message": "CodeYears settings" }, "viewGroup": { "message": "Contribution view" @@ -198,11 +198,14 @@ "message": "Opening Contribution City…" }, "popupWrongPage": { - "message": "Open a GitHub profile first, then click CodeYears." + "message": "Open a GitHub personal profile with a contribution calendar to change these settings." }, "popupNotReady": { "message": "Retry after the contribution calendar has loaded on the GitHub profile." }, + "popupAlreadyMounted": { + "message": "CodeYears already has a view on this page. Refresh the profile after an extension reload, and keep one version enabled." + }, "popupOpened": { "message": "City opened." }, @@ -329,8 +332,26 @@ "settingsTitle": { "message": "CodeYears settings" }, - "settingsHelp": { - "message": "Preferences apply in this browser. Year and view controls stay on the GitHub profile." + "calendarAppearance": { + "message": "Contribution graph style" + }, + "appearanceNative": { + "message": "GitHub original" + }, + "appearanceMiniature": { + "message": "Miniature city" + }, + "appearanceSaveError": { + "message": "Could not save the graph style. Try again." + }, + "showCity": { + "message": "Show City tab" + }, + "cityVisibilitySaveError": { + "message": "Could not save City visibility. Try again." + }, + "openCityShortcut": { + "message": "Open City" }, "settingsAbout": { "message": "About CodeYears" @@ -341,8 +362,41 @@ "version": { "message": "Version $1" }, - "privacy": { - "message": "Privacy" + "officialWebsite": { + "message": "Website" + }, + "aboutAuthor": { + "message": "About the author" + }, + "authorLink": { + "message": "Author" + }, + "backToSettings": { + "message": "Back to settings" + }, + "authorDescription": { + "message": "Independent developer of native apps and browser extensions." + }, + "authorWebsite": { + "message": "Author website" + }, + "authorExtensions": { + "message": "Other extensions on the Chrome Web Store" + }, + "authorHitable": { + "message": "Explore, filter and export tabular data." + }, + "authorNavigraph": { + "message": "See and retrace your browsing paths." + }, + "authorSilentfeed": { + "message": "An RSS reader that learns your reading preferences." + }, + "authorAiPulse": { + "message": "Monitor AI service status, usage and balances." + }, + "sourceCode": { + "message": "Source code" }, "help": { "message": "Help" diff --git a/public/_locales/zh_CN/messages.json b/public/_locales/zh_CN/messages.json index 3464d1d..d1bf223 100644 --- a/public/_locales/zh_CN/messages.json +++ b/public/_locales/zh_CN/messages.json @@ -6,7 +6,7 @@ "message": "免费的 GitHub 贡献历史可视化扩展。选择年份,用真实每日贡献生成贡献之城。" }, "actionTitle": { - "message": "CodeYears · 贡献之城" + "message": "CodeYears 设置" }, "viewGroup": { "message": "贡献展示方式" @@ -198,11 +198,14 @@ "message": "正在打开贡献之城…" }, "popupWrongPage": { - "message": "请先打开 GitHub 个人主页,再点击扩展。" + "message": "请在 GitHub 个人主页的贡献区打开这些设置。" }, "popupNotReady": { "message": "请在 GitHub 个人主页的贡献日历加载完成后重试。" }, + "popupAlreadyMounted": { + "message": "当前主页已有 CodeYears 视图。重载扩展后请刷新主页,并确保只启用一个版本。" + }, "popupOpened": { "message": "已打开城市。" }, @@ -329,8 +332,26 @@ "settingsTitle": { "message": "CodeYears 设置" }, - "settingsHelp": { - "message": "偏好设置适用于当前浏览器;年份与画面操作仍在 GitHub 个人主页中使用。" + "calendarAppearance": { + "message": "贡献图样式" + }, + "appearanceNative": { + "message": "GitHub 原图" + }, + "appearanceMiniature": { + "message": "微缩城市" + }, + "appearanceSaveError": { + "message": "贡献图样式保存失败,请重试。" + }, + "showCity": { + "message": "显示城市页签" + }, + "cityVisibilitySaveError": { + "message": "城市显示设置保存失败,请重试。" + }, + "openCityShortcut": { + "message": "打开城市" }, "settingsAbout": { "message": "关于 CodeYears" @@ -341,8 +362,41 @@ "version": { "message": "版本 $1" }, - "privacy": { - "message": "隐私说明" + "officialWebsite": { + "message": "官网" + }, + "aboutAuthor": { + "message": "关于作者" + }, + "authorLink": { + "message": "关于作者" + }, + "backToSettings": { + "message": "返回设置" + }, + "authorDescription": { + "message": "独立开发者,开发原生应用和浏览器扩展。" + }, + "authorWebsite": { + "message": "作者官网" + }, + "authorExtensions": { + "message": "Chrome 商店中的其他扩展" + }, + "authorHitable": { + "message": "浏览、筛选和导出表格数据。" + }, + "authorNavigraph": { + "message": "查看并追溯浏览路径。" + }, + "authorSilentfeed": { + "message": "能学习阅读偏好的 RSS 阅读器。" + }, + "authorAiPulse": { + "message": "监控 AI 服务状态、用量和余额。" + }, + "sourceCode": { + "message": "源代码" }, "help": { "message": "使用帮助" diff --git a/public/assets/calendar/apartment.webp b/public/assets/calendar/apartment.webp new file mode 100644 index 0000000..a1a250d Binary files /dev/null and b/public/assets/calendar/apartment.webp differ diff --git a/public/assets/calendar/clinic.webp b/public/assets/calendar/clinic.webp new file mode 100644 index 0000000..85ea676 Binary files /dev/null and b/public/assets/calendar/clinic.webp differ diff --git a/public/assets/calendar/cottage.webp b/public/assets/calendar/cottage.webp new file mode 100644 index 0000000..6e68f4f Binary files /dev/null and b/public/assets/calendar/cottage.webp differ diff --git a/public/assets/calendar/courtyard.webp b/public/assets/calendar/courtyard.webp new file mode 100644 index 0000000..397e062 Binary files /dev/null and b/public/assets/calendar/courtyard.webp differ diff --git a/public/assets/calendar/duplex.webp b/public/assets/calendar/duplex.webp new file mode 100644 index 0000000..fb57983 Binary files /dev/null and b/public/assets/calendar/duplex.webp differ diff --git a/public/assets/calendar/garden.webp b/public/assets/calendar/garden.webp new file mode 100644 index 0000000..f3e31d6 Binary files /dev/null and b/public/assets/calendar/garden.webp differ diff --git a/public/assets/calendar/limestone.webp b/public/assets/calendar/limestone.webp new file mode 100644 index 0000000..b65840e Binary files /dev/null and b/public/assets/calendar/limestone.webp differ diff --git a/public/assets/calendar/mansard.webp b/public/assets/calendar/mansard.webp new file mode 100644 index 0000000..9e3052a Binary files /dev/null and b/public/assets/calendar/mansard.webp differ diff --git a/public/assets/calendar/office-amber.webp b/public/assets/calendar/office-amber.webp new file mode 100644 index 0000000..7c73977 Binary files /dev/null and b/public/assets/calendar/office-amber.webp differ diff --git a/public/assets/calendar/office-blue.webp b/public/assets/calendar/office-blue.webp new file mode 100644 index 0000000..1fad9fd Binary files /dev/null and b/public/assets/calendar/office-blue.webp differ diff --git a/public/assets/calendar/terrace.webp b/public/assets/calendar/terrace.webp new file mode 100644 index 0000000..9046b66 Binary files /dev/null and b/public/assets/calendar/terrace.webp differ diff --git a/public/assets/calendar/tower-green.webp b/public/assets/calendar/tower-green.webp new file mode 100644 index 0000000..5734a58 Binary files /dev/null and b/public/assets/calendar/tower-green.webp differ diff --git a/public/manifest.json b/public/manifest.json index b231d06..ae4bb18 100644 --- a/public/manifest.json +++ b/public/manifest.json @@ -1,12 +1,11 @@ { "manifest_version": 3, "name": "__MSG_extensionName__", - "version": "0.1.3", + "version": "0.1.4", "default_locale": "en", "description": "__MSG_extensionDescription__", "permissions": ["activeTab", "scripting", "storage"], "content_scripts": [{ "matches": ["https://github.com/*"], "js": ["entry.js"], "run_at": "document_idle" }], - "options_ui": { "page": "options.html", "open_in_tab": false }, "action": { "default_title": "__MSG_actionTitle__", "default_popup": "popup.html", @@ -23,7 +22,7 @@ "48": "icons/codeyears-48.png", "128": "icons/codeyears-128.png" }, - "web_accessible_resources": [{ "resources": ["content.js", "landscape.js", "chunks/*.js", "assets/city/*.png"], "matches": ["https://github.com/*"] }], + "web_accessible_resources": [{ "resources": ["content.js", "landscape.js", "calendar.js", "chunks/*.js", "assets/city/*.png", "assets/calendar/*.webp"], "matches": ["https://github.com/*"] }], "content_security_policy": { "extension_pages": "script-src 'self'; object-src 'none'" } diff --git a/scripts/build.mjs b/scripts/build.mjs index cf85a99..d4c1933 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -32,6 +32,14 @@ await build({ }, }, }); +await build({ + configFile: false, + publicDir: false, + build: { + target: "es2022", outDir: values.outDir, emptyOutDir: false, watch, + lib: { entry: "src/extension/miniature-calendar.ts", formats: ["es"], fileName: () => "calendar.js" }, + }, +}); await build({ configFile: false, publicDir: false, @@ -47,3 +55,4 @@ for (const name of ['manifest.json', '_locales', 'icons']) { await cp(resolve('public', name), resolve(values.outDir, name), { recursive: true }); } await cp(resolve('public/assets/city-runtime'), resolve(values.outDir, 'assets/city'), { recursive: true }); +await cp(resolve('public/assets/calendar'), resolve(values.outDir, 'assets/calendar'), { recursive: true }); diff --git a/scripts/package-city.py b/scripts/package-city.py index b999a37..4395f57 100644 --- a/scripts/package-city.py +++ b/scripts/package-city.py @@ -25,15 +25,15 @@ if manifest.get("content_scripts") != [{"matches": ["https://github.com/*"], "js": ["entry.js"], "run_at": "document_idle"}]: raise SystemExit("Review changed automatic entry scope before packaging") -if manifest.get("options_ui") != {"page": "options.html", "open_in_tab": False}: - raise SystemExit("Review changed options page before packaging") +if "options_ui" in manifest or manifest["action"].get("default_popup") != "popup.html": + raise SystemExit("Settings must be served by the toolbar popup") # An explicit distribution list excludes repository material, source maps and local data. -files = {name: dist / name for name in ("manifest.json", "popup.html", "options.html", "entry.js", "content.js", "landscape.js")} +files = {name: dist / name for name in ("manifest.json", "popup.html", "entry.js", "content.js", "landscape.js", "calendar.js")} for locale in ("en", "zh_CN"): name = f"_locales/{locale}/messages.json" files[name] = dist / name -for pattern in ("assets/popup-*.js", "assets/options-*.js", "assets/shared-*.js", "assets/city/*.png", "chunks/*.js"): +for pattern in ("assets/popup-*.js", "assets/shared-*.js", "assets/city/*.png", "assets/calendar/*.webp", "chunks/*.js"): files.update((path.relative_to(dist).as_posix(), path) for path in dist.glob(pattern)) for table in (manifest["icons"], manifest["action"]["default_icon"]): files.update((name, dist / name) for name in table.values()) diff --git a/scripts/verify-city-package.py b/scripts/verify-city-package.py index c0f3fa4..d599905 100644 --- a/scripts/verify-city-package.py +++ b/scripts/verify-city-package.py @@ -10,11 +10,15 @@ from zipfile import BadZipFile, ZipFile ROOT = Path(__file__).resolve().parents[1] -FIXED = {'manifest.json', 'popup.html', 'options.html', 'entry.js', 'content.js', 'landscape.js'} +FIXED = {'manifest.json', 'popup.html', 'entry.js', 'content.js', 'landscape.js', 'calendar.js'} +CALENDAR_ASSETS = {'cottage.webp', 'garden.webp', 'courtyard.webp', 'terrace.webp', 'mansard.webp', 'clinic.webp', + 'limestone.webp', 'apartment.webp', 'duplex.webp', 'office-blue.webp', 'office-amber.webp', + 'tower-green.webp'} NOTICES = {'LICENSE', 'THIRD_PARTY_NOTICES.md', 'ASSETS.md', 'PRIVACY.md'} SCOPE = ['https://github.com/*'] ENTRY = [{'matches': SCOPE, 'js': ['entry.js'], 'run_at': 'document_idle'}] -WAR = [{'resources': ['content.js', 'landscape.js', 'chunks/*.js', 'assets/city/*.png'], 'matches': SCOPE}] +WAR = [{'resources': ['content.js', 'landscape.js', 'calendar.js', 'chunks/*.js', 'assets/city/*.png', + 'assets/calendar/*.webp'], 'matches': SCOPE}] def require(condition, message): @@ -54,7 +58,8 @@ def verify(archive, build): require(manifest.get('content_scripts') == ENTRY, 'automatic entry scope changed') require(manifest.get('web_accessible_resources') == WAR, 'resource exposure changed') require(manifest.get('content_security_policy') == {'extension_pages': "script-src 'self'; object-src 'none'"}, 'CSP changed') - require(manifest.get('options_ui') == {'page': 'options.html', 'open_in_tab': False}, 'options page changed') + require('options_ui' not in manifest and manifest['action'].get('default_popup') == 'popup.html', + 'settings must be served by the toolbar popup') require(manifest == source, 'manifest differs from checkout; review new capabilities') require(manifest.get('default_locale') == 'en', 'expected English fallback locale') catalogs = [read_json(ROOT / f'public/_locales/{locale}/messages.json') for locale in ('en', 'zh_CN')] @@ -82,7 +87,10 @@ def verify(archive, build): for path in runtime.glob('*.png'): name = 'assets/city/' + path.name expected[name] = build / name - for pattern in ('assets/popup-*.js', 'assets/options-*.js', 'assets/shared-*.js', 'chunks/*.js'): + require({p.name for p in (ROOT / 'public/assets/calendar').iterdir()} == CALENDAR_ASSETS, + 'miniature calendar asset inventory mismatch') + expected.update((f'assets/calendar/{name}', build / 'assets/calendar' / name) for name in CALENDAR_ASSETS) + for pattern in ('assets/popup-*.js', 'assets/shared-*.js', 'chunks/*.js'): paths = list(build.glob(pattern)) require(paths or pattern == 'assets/shared-*.js', f'build missing {pattern}') expected.update((p.relative_to(build).as_posix(), p) for p in paths) @@ -94,7 +102,6 @@ def reference(owner, target, root=False): require(name in names, f'missing reference: {owner} -> {target}') reference('manifest.json', manifest['action']['default_popup'], True) - reference('manifest.json', manifest['options_ui']['page'], True) for group in manifest['content_scripts']: for name in group['js']: reference('manifest.json', name, True) @@ -111,10 +118,19 @@ def reference(owner, target, root=False): reference(name, target, not target.startswith('.')) for target in re.findall(r'''(?:src|href)=["']([^"']+)["']|url\(["']?([^\s)'";]+)''', text): target = target[0] or target[1] - if name == 'options.html' and target in { - 'https://github.com/wxy/CodeYears#readme', - 'https://github.com/wxy/CodeYears/blob/main/PRIVACY.md', + if name == 'popup.html' and target.startswith('#'): + require(f'id="{target[1:]}"' in text, f'missing popup section: {target}') + continue + if name == 'popup.html' and target in { + 'https://xingyu.wang/', + 'https://xingyu.wang/extensions/codeyears', + 'https://xingyu.wang/zh/extensions/codeyears', + 'https://github.com/wxy/CodeYears', 'https://github.com/wxy/CodeYears/issues', + 'https://chromewebstore.google.com/detail/hitable/gepfjnfkjimhdfemijfnnpefdpocldpc', + 'https://chromewebstore.google.com/detail/navigraph/jfjgdldpgmnhclffkkcnbhleijeopkhi', + 'https://chromewebstore.google.com/detail/silentfeed/pieiedlagbmcnooloibhigmidpakneca', + 'https://chromewebstore.google.com/detail/ai-pulse/dpacojibmleehcmmkcabnbgeadofkkpe', }: continue reference(name, target) diff --git a/src/extension/appearance.ts b/src/extension/appearance.ts new file mode 100644 index 0000000..e57bb5b --- /dev/null +++ b/src/extension/appearance.ts @@ -0,0 +1,22 @@ +export type Appearance = 'native' | 'miniature'; +export const APPEARANCE_KEY = 'codeyears:ui:appearance'; +export const CITY_VISIBILITY_KEY = 'codeyears:ui:show-city'; + +export function appearancePreference(value: unknown): Appearance { + return value === 'miniature' ? 'miniature' : 'native'; +} + +export const cityVisibilityPreference = (value: unknown) => value !== false; + +export async function readAppearanceSettings(): Promise<{ appearance: Appearance; showCity: boolean }> { + try { + const values = await chrome.storage.local.get([APPEARANCE_KEY, CITY_VISIBILITY_KEY]); + return { + appearance: appearancePreference(values[APPEARANCE_KEY]), + showCity: cityVisibilityPreference(values[CITY_VISIBILITY_KEY]), + }; + } catch { return { appearance: 'native', showCity: true }; } +} + +export const saveAppearance = (appearance: Appearance) => chrome.storage.local.set({ [APPEARANCE_KEY]: appearance }); +export const saveCityVisibility = (showCity: boolean) => chrome.storage.local.set({ [CITY_VISIBILITY_KEY]: showCity }); diff --git a/src/extension/entry-text.ts b/src/extension/entry-text.ts index a57bf84..d32d5ad 100644 --- a/src/extension/entry-text.ts +++ b/src/extension/entry-text.ts @@ -1,9 +1,19 @@ import type { Language } from './language'; import { viewGroup as enViewGroup, city as enCity, contributions as enContributions, retry as enRetry, prepareCity as enPrepareCity, cityOpenError as enCityOpenError } from '../../public/_locales/en/messages.json'; import { viewGroup as zhViewGroup, city as zhCity, contributions as zhContributions, retry as zhRetry, prepareCity as zhPrepareCity, cityOpenError as zhCityOpenError } from '../../public/_locales/zh_CN/messages.json'; +import { appearanceMiniature as enAppearanceMiniature, appearanceSaveError as enAppearanceSaveError } from '../../public/_locales/en/messages.json'; +import { appearanceMiniature as zhAppearanceMiniature, appearanceSaveError as zhAppearanceSaveError } from '../../public/_locales/zh_CN/messages.json'; const phrases = { - 'en': {viewGroup: enViewGroup.message, city: enCity.message, contributions: enContributions.message, retry: enRetry.message, prepareCity: enPrepareCity.message, cityOpenError: enCityOpenError.message}, - 'zh-CN': {viewGroup: zhViewGroup.message, city: zhCity.message, contributions: zhContributions.message, retry: zhRetry.message, prepareCity: zhPrepareCity.message, cityOpenError: zhCityOpenError.message}, + 'en': { + viewGroup: enViewGroup.message, city: enCity.message, contributions: enContributions.message, + retry: enRetry.message, prepareCity: enPrepareCity.message, cityOpenError: enCityOpenError.message, + appearanceMiniature: enAppearanceMiniature.message, appearanceSaveError: enAppearanceSaveError.message, + }, + 'zh-CN': { + viewGroup: zhViewGroup.message, city: zhCity.message, contributions: zhContributions.message, + retry: zhRetry.message, prepareCity: zhPrepareCity.message, cityOpenError: zhCityOpenError.message, + appearanceMiniature: zhAppearanceMiniature.message, appearanceSaveError: zhAppearanceSaveError.message, + }, }; -/** 入口只打包6条标题/失败文案,完整词库留给按需面板。 */ +/** 入口只打包页签和切换文案,完整词库留给按需面板。 */ export const entryText = (language: Language, key: keyof typeof phrases.en) => phrases[language][key]; diff --git a/src/extension/entry.ts b/src/extension/entry.ts index 9f9223a..80bb026 100644 --- a/src/extension/entry.ts +++ b/src/extension/entry.ts @@ -1,24 +1,74 @@ import type { CityPanel } from './content'; +import { APPEARANCE_KEY, CITY_VISIBILITY_KEY, appearancePreference, cityVisibilityPreference, readAppearanceSettings, saveAppearance, type Appearance } from './appearance'; import { entryText } from './entry-text'; import { LANGUAGE_KEY, languagePreference, readLanguagePreference, resolveLanguage, saveLanguagePreference, type LanguagePreference } from './language'; import { isCityUrl } from './city-url'; declare global { - interface Window { __codeyearsOpenCity?: () => boolean } + interface Window { + __codeyearsOpenCity?: () => Promise; + __codeyearsHasProfileCalendar?: () => boolean; + } } (() => { if (window.__codeyearsOpenCity) return; - let mounted: ReturnType | undefined; + const mountMarker = 'data-codeyears-mounted'; + let mounted: ReturnType | { + kind: 'miniature'; + root: HTMLElement; + grid: HTMLTableElement; + heading: HTMLElement; + profile: string; + dispose: () => void; + } | undefined; + let appearance: Appearance | undefined; + let showCity: boolean | undefined; let navigating = false, queued = false; let preference: LanguagePreference = 'auto'; const languageSettings = () => ({ language: resolveLanguage(preference), preference, change: async (next: LanguagePreference) => { await saveLanguagePreference(next); updateLanguage(next); } }); - const updateLanguage = (next: LanguagePreference) => { preference = next; mounted?.localize(); }; + const updateLanguage = (next: LanguagePreference) => { preference = next; if (mounted?.kind === 'city') mounted.localize(); }; void readLanguagePreference().then(updateLanguage); - chrome.storage.onChanged.addListener((changes, area) => { if (area === 'local' && changes[LANGUAGE_KEY]) updateLanguage(languagePreference(changes[LANGUAGE_KEY].newValue)); }); + function syncSettings() { + if (mounted?.kind === 'city' && showCity) { + mounted.syncAppearance(); + return; + } + if (mounted && (mounted.kind === 'city' || showCity || appearance === 'native')) { + if (mounted.kind === 'city') mounted.deactivate(); + disposeView(); + } + reconcile(); + } + const settingsReady = readAppearanceSettings().then(saved => { + appearance ??= saved.appearance; + showCity ??= saved.showCity; + syncSettings(); + }); + chrome.storage.onChanged.addListener((changes, area) => { + if (area !== 'local') return; + if (changes[LANGUAGE_KEY]) updateLanguage(languagePreference(changes[LANGUAGE_KEY].newValue)); + const appearanceChange = changes[APPEARANCE_KEY]; + const visibilityChange = changes[CITY_VISIBILITY_KEY]; + if (appearanceChange) appearance = appearancePreference(appearanceChange.newValue); + if (visibilityChange) showCity = cityVisibilityPreference(visibilityChange.newValue); + if (appearanceChange || visibilityChange) syncSettings(); + }); - function mount(root: HTMLElement, native: HTMLElement, grid: HTMLElement, heading: HTMLElement, profile: string) { + function mountMiniature(grid: HTMLTableElement) { + let view: ReturnType | undefined; + let disposed = false; + void import(/* @vite-ignore */ chrome.runtime.getURL('calendar.js')).then( + (module: typeof import('./miniature-calendar')) => { + if (!disposed && grid.isConnected) view = module.mountMiniatureCalendar(grid); + }, + () => { /* Keep the native calendar available if the optional module does not load. */ }, + ); + return () => { disposed = true; view?.dispose(); }; + } + + function mount(root: HTMLElement, native: HTMLElement, grid: HTMLTableElement, heading: HTMLElement, profile: string) { const host = document.createElement('span'); host.id = 'codeyears-profile-tabs'; const shadow = host.attachShadow({ mode: 'open' }); @@ -35,6 +85,10 @@ declare global { button { flex:none; white-space:nowrap; font:inherit; color:inherit; cursor:pointer; padding:4px 7px; border:0; border-radius:4px; background:transparent; } button[aria-pressed="true"] { font-weight:600; } button:focus-visible { outline:2px solid #268f80; outline-offset:2px; } + #miniature-toggle { border:1px solid var(--borderColor-default,#d1d9e0); border-radius:6px; background:var(--bgColor-muted,#f6f8fa); } + #miniature-toggle[aria-pressed="true"] { color:var(--fgColor-accent,#0969da); border-color:var(--borderColor-accent-muted,#54aeff); background:var(--bgColor-accent-muted,#ddf4ff); } + #appearance-status:empty { position:absolute; } + #appearance-status:not(:empty) { flex-basis:100%; color:var(--fgColor-danger,#cf222e); } slot[name="native-stat"] { flex:1 1 180px; } ::slotted(#codeyears-native-stat) { flex:1 1 180px; min-width:0; font-size:14px; } ::slotted(.js-contribution-settings-menu) { float:none!important; margin:0!important; } @@ -42,7 +96,15 @@ declare global {
-
+
+ +
+ + + + +
+
`; const bodyHost = document.createElement('div'); bodyHost.id = 'codeyears-city-content'; bodyHost.hidden = true; @@ -62,6 +124,8 @@ declare global { `; const nativeButton = shadow.querySelector('#tab-native')!; const cityButton = shadow.querySelector('#tab-city')!; + const miniatureButton = shadow.querySelector('#miniature-toggle')!; + const appearanceStatus = shadow.querySelector('#appearance-status')!; const nativeControls = shadow.querySelector('#native-controls')!; const cityControls = shadow.querySelector('#city-controls')!; const toolbarHost = document.createElement('div'); toolbarHost.slot = 'city-controls'; @@ -87,6 +151,7 @@ declare global { heading.append(host); heading.after(bodyHost); const hiddenNative = new Map(); let active = false, disposed = false, selection = 0, trafficSeed = 0, panel: CityPanel | undefined; + let disposeMiniature: (() => void) | undefined; if (location.hash === '#codeyears-town') { const url = new URL(location.href); url.hash = 'codeyears-city'; @@ -99,12 +164,31 @@ declare global { const language = resolveLanguage(preference); host.lang = bodyHost.lang = language; shadow.querySelector('.tabs')!.setAttribute('aria-label', entryText(language, 'viewGroup')); cityButton.textContent = entryText(language, 'city'); nativeButton.textContent = entryText(language, 'contributions'); + miniatureButton.textContent = entryText(language, 'appearanceMiniature'); + if (appearanceStatus.textContent) appearanceStatus.textContent = entryText(language, 'appearanceSaveError'); retry.textContent = entryText(language, 'retry'); status.textContent = entryText(language, entryState === 'error' ? 'cityOpenError' : 'prepareCity'); panel?.setLanguage(language, preference); }; localize(); + const syncAppearance = () => { + miniatureButton.setAttribute('aria-pressed', String(appearance === 'miniature')); + appearanceStatus.textContent = ''; + if (!showCity || active || appearance !== 'miniature') { + disposeMiniature?.(); + disposeMiniature = undefined; + } else { + disposeMiniature ??= mountMiniature(grid); + } + }; + miniatureButton.addEventListener('click', () => { + appearanceStatus.textContent = ''; + void saveAppearance(appearance === 'miniature' ? 'native' : 'miniature').catch(() => { + appearanceStatus.textContent = entryText(resolveLanguage(preference), 'appearanceSaveError'); + }); + }); + const sync = () => { if (!active) return; panel?.syncProfileCard(); @@ -135,10 +219,12 @@ declare global { bodyHost.hidden = panelHost.hidden = status.hidden = retry.hidden = true; feedback.hidden = true; host.dataset.view = 'native'; + syncAppearance(); }; const selectCity = async () => { if (active || disposed || document.hidden) return; active = true; const token = ++selection; + syncAppearance(); trafficSeed = Math.floor(Math.random() * 0x100000000); sync(); nativeControls.hidden = true; cityControls.hidden = false; nativeButton.parentElement!.dataset.active = 'false'; cityButton.parentElement!.dataset.active = 'true'; @@ -177,7 +263,7 @@ declare global { }; host.dataset.view = 'native'; return { - root, native, grid, heading, nativeStats, host, bodyHost, profile, sync, localize, + kind: 'city' as const, root, grid, heading, nativeStats, host, bodyHost, profile, sync, localize, syncAppearance, open() { roadArrivalPending=false; host.scrollIntoView({ block: 'nearest' }); void selectCity(); }, openRoadArrival, syncUrl() { @@ -194,7 +280,7 @@ declare global { if (hidden) panel?.suspendPrivateView(); else void panel?.activate(trafficSeed); }, dispose() { - disposed = true; selection++; panel?.dispose(); restoreNative(); + disposed = true; selection++; disposeMiniature?.(); panel?.dispose(); restoreNative(); if (nativeSettings) { if (settingsSlot == null) nativeSettings.removeAttribute('slot'); else nativeSettings.setAttribute('slot', settingsSlot); settingsHome.replaceWith(nativeSettings); @@ -206,22 +292,54 @@ declare global { }; } - function reconcile() { - const profile = location.origin === 'https://github.com' ? location.pathname.match(/^\/([a-zA-Z0-9-]{1,39})\/?$/)?.[1].toLowerCase() : undefined; - if (mounted && (profile !== mounted.profile || !mounted.grid.isConnected || !mounted.heading.isConnected || !mounted.bodyHost.isConnected || !mounted.heading.contains(mounted.nativeStats) || !mounted.heading.contains(mounted.host))) { - mounted.dispose(); mounted = undefined; - } - if (mounted) { mounted.sync(); return; } - if (navigating || !profile) return; + function profileLogin() { + if (location.origin === 'https://github.com') return location.pathname.match(/^\/([a-zA-Z0-9-]{1,39})\/?$/)?.[1].toLowerCase(); + } + + function findProfileCalendar() { const root = document.querySelector('.js-yearly-contributions'); - const grid = root?.querySelector('table.ContributionCalendar-grid'); + const grid = root?.querySelector('table.ContributionCalendar-grid'); const heading = root?.querySelector('#js-contribution-activity-description'); - if (!root || !grid || !heading || !document.querySelector('a[id^="year-link-"]')) return; - let native = grid; - while (native.parentElement !== root) native = native.parentElement!; - if (!native.contains(heading)) return; - mounted = mount(root, native, grid, heading, profile); - mounted.openRoadArrival(); + if (root && grid && heading) return { root, grid, heading }; + } + + function disposeView() { + if (!mounted) return; + mounted.dispose(); + mounted.root.removeAttribute(mountMarker); + mounted = undefined; + } + + function reconcile() { + const profile = profileLogin(); + if (mounted && (profile !== mounted.profile || !mounted.grid.isConnected || !mounted.heading.isConnected + || (mounted.kind === 'city' && (!mounted.bodyHost.isConnected || !mounted.heading.contains(mounted.nativeStats) || !mounted.heading.contains(mounted.host))))) { + disposeView(); + } + if (mounted) { if (mounted.kind === 'city') mounted.sync(); return; } + if (!appearance || showCity === undefined || navigating || !profile) return; + if (!showCity && appearance === 'native') return; + const calendar = findProfileCalendar(); + if (!calendar) return; + const { root, grid, heading } = calendar; + // 内容脚本的 JavaScript 上下文彼此隔离。重载前或其他版本的宿主仍可能留在同一页面。 + if (root.hasAttribute(mountMarker) || root.querySelector('#codeyears-profile-tabs, #codeyears-miniature-canvas')) { + return 'already-mounted'; + } + if (showCity) { + if (!document.querySelector('a[id^="year-link-"]')) return; + let native: HTMLElement = grid; + while (native.parentElement !== root) native = native.parentElement!; + if (!native.contains(heading)) return; + mounted = mount(root, native, grid, heading, profile); + } else { + mounted = { kind: 'miniature', root, grid, heading, profile, dispose: mountMiniature(grid) }; + } + root.setAttribute(mountMarker, ''); + if (mounted.kind === 'city') { + mounted.openRoadArrival(); + mounted.syncAppearance(); + } } const observer = new MutationObserver(() => { if (queued) return; @@ -229,18 +347,25 @@ declare global { queueMicrotask(() => { queued = false; reconcile(); }); }); const observe = () => observer.observe(document.documentElement, { childList: true, subtree: true }); - const beforeNavigate = () => { navigating = true; mounted?.dispose(); mounted = undefined; }; + observe(); + const beforeNavigate = () => { navigating = true; disposeView(); }; const afterNavigate = () => { navigating = false; reconcile(); }; document.addEventListener('turbo:before-cache', beforeNavigate); document.addEventListener('turbo:before-render', beforeNavigate); document.addEventListener('turbo:render', afterNavigate); document.addEventListener('turbo:load', afterNavigate); - document.addEventListener('visibilitychange', () => { mounted?.visibility(document.hidden); }); - const onUrlChange = () => { reconcile(); mounted?.syncUrl(); }; + document.addEventListener('visibilitychange', () => { if (mounted?.kind === 'city') mounted.visibility(document.hidden); }); + const onUrlChange = () => { reconcile(); if (mounted?.kind === 'city') mounted.syncUrl(); }; window.addEventListener('popstate', onUrlChange); window.addEventListener('hashchange', onUrlChange); window.addEventListener('pagehide', () => { beforeNavigate(); observer.disconnect(); }); window.addEventListener('pageshow', () => { observe(); afterNavigate(); }); - window.__codeyearsOpenCity = () => { reconcile(); if (!mounted) return false; mounted.open(); return true; }; - observe(); reconcile(); + window.__codeyearsHasProfileCalendar = () => Boolean(profileLogin() && findProfileCalendar()); + window.__codeyearsOpenCity = async () => { + await settingsReady; + if (reconcile() === 'already-mounted') return 'already-mounted'; + if (mounted?.kind !== 'city') return false; + mounted.open(); + return true; + }; })(); diff --git a/src/extension/miniature-calendar.ts b/src/extension/miniature-calendar.ts new file mode 100644 index 0000000..520d843 --- /dev/null +++ b/src/extension/miniature-calendar.ts @@ -0,0 +1,223 @@ +const sceneClass = 'codeyears-miniature-scene'; +const buildings = [ + [], + ['garden.webp', 'cottage.webp', 'courtyard.webp'], + ['terrace.webp', 'mansard.webp', 'clinic.webp'], + ['limestone.webp', 'apartment.webp', 'duplex.webp'], + ['office-blue.webp', 'office-amber.webp', 'tower-green.webp'], +] as const; +const lotScale = 0.7; +const modelSeed = Math.floor(Math.random() * 0x100000000); +type Level = 0 | 1 | 2 | 3 | 4; +interface Day { cell: HTMLTableCellElement; date: string; column: number; row: number; level: Level } + +let assetsPromise: Promise> | undefined; +function loadAssets() { + assetsPromise ??= Promise.all(buildings.flat().map(async file => { + const image = new Image(); + image.src = chrome.runtime.getURL('assets/calendar/' + file); + await image.decode(); + return [file, image] as const; + })).then(images => new Map(images)).catch(error => { + assetsPromise = undefined; + throw error; + }); + return assetsPromise; +} + +function readDays(grid: HTMLTableElement) { + const rows = Array.from(grid.tBodies[0]?.rows ?? []); + if (rows.length !== 7) return; + const days: Day[] = []; + const dates = new Set(); + for (const [row, tr] of rows.entries()) { + const columns = new Set(); + for (const cell of tr.querySelectorAll('td.ContributionCalendar-day[data-date]')) { + const { date = '', ix = '', level = '' } = cell.dataset; + const column = Number(ix); + if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || dates.has(date) + || !/^\d{1,2}$/.test(ix) || column > 53 || columns.has(column) || !/^[0-4]$/.test(level)) return; + dates.add(date); + columns.add(column); + days.push({ cell, date, column, row, level: Number(level) as Level }); + } + } + if (days.length) return { days, rows }; +} + +const sceneCss = ` + .${sceneClass} { position: relative; isolation: isolate; } + .codeyears-miniature-layer { position: absolute; pointer-events: none; } + .codeyears-miniature-layer::before { + content: ''; position: absolute; inset: 0; z-index: -1; + background-color: color-mix(in srgb, var(--bgColor-muted, #f6f8fa) 90%, var(--fgColor-muted, #59636e)); + } + #codeyears-miniature-canvas { display: block; position: relative; z-index: 1; width: 100%; height: 100%; } + .${sceneClass}[data-painted]:not([data-measuring]) .ContributionCalendar-day[data-date] { + translate: var(--codeyears-x, 0px) var(--codeyears-y, 0px); + background-color: transparent !important; + border-radius: 50%; + box-shadow: none !important; + } + .${sceneClass}[data-painted] .ContributionCalendar-day[data-date]:is([aria-selected="true"], :focus-visible) { + position: relative; z-index: 2; + outline: 2px solid var(--fgColor-accent, #0969da); outline-offset: -1px; + } + [data-codeyears-miniature-legend] { + position: relative; + background-color: transparent !important; box-shadow: none !important; + } + [data-codeyears-miniature-legend] > img { + position: absolute; inset-inline-start: -1px; inset-block-end: -1px; + width: 12px; height: 13px; object-fit: contain; object-position: center bottom; pointer-events: none; + } + [data-codeyears-miniature-legend="0"] { + background-color: var(--bgColor-neutral-muted, #d0d7de) !important; + border-radius: 50% !important; + } +`; + +export function mountMiniatureCalendar(grid: HTMLTableElement) { + const scroller = grid.parentElement!; + const graph = grid.closest('.js-calendar-graph'); + const style = document.createElement('style'); + style.textContent = sceneCss; + const layer = document.createElement('div'); + layer.className = 'codeyears-miniature-layer'; + layer.setAttribute('aria-hidden', 'true'); + layer.hidden = true; + const canvas = document.createElement('canvas'); + canvas.id = 'codeyears-miniature-canvas'; + layer.append(canvas); + const swatches = new Map(); + let snapshot: ReturnType; + let pictures: Map | undefined; + let frame = 0; + let disposed = false; + + function resetLegend() { + for (const [swatch, icon] of swatches) { + swatch.removeAttribute('data-codeyears-miniature-legend'); + icon?.remove(); + } + swatches.clear(); + } + + function paintLegend() { + for (const [level, options] of buildings.entries()) { + const swatch = graph?.querySelector('#contribution-graph-legend-level-' + level); + if (!swatch || swatches.has(swatch)) continue; + swatch.dataset.codeyearsMiniatureLegend = String(level); + let icon: HTMLImageElement | undefined; + if (options.length) { + icon = document.createElement('img'); + icon.src = pictures!.get(options[0])!.src; + icon.alt = ''; + swatch.append(icon); + } + swatches.set(swatch, icon); + } + } + + function updateDays() { + snapshot = readDays(grid); + schedule(); + } + + function hide() { + scroller.removeAttribute('data-painted'); + layer.hidden = true; + resetLegend(); + } + + function paint() { + frame = 0; + if (!pictures || !snapshot || !grid.isConnected) { hide(); return; } + scroller.setAttribute('data-measuring', ''); + const area = scroller.getBoundingClientRect(); + const { days, rows } = snapshot; + const positions = days.map(day => day.cell.getBoundingClientRect()); + const left = Math.min(...positions.map(rect => rect.left)); + const right = Math.max(...positions.map(rect => rect.right)); + const top = rows[0].getBoundingClientRect().top; + const bottom = rows[6].getBoundingClientRect().bottom; + scroller.removeAttribute('data-measuring'); + const width = right - left, height = bottom - top; + if (!width || !height || !area.width) { hide(); return; } + + // 以原生日格的矩形为画布边界,图层绝对定位,不给表格加行或留白。 + layer.style.left = `${left - area.left + scroller.scrollLeft - scroller.clientLeft}px`; + layer.style.top = `${top - area.top + scroller.scrollTop - scroller.clientTop}px`; + layer.style.width = `${width}px`; + layer.style.height = `${height}px`; + const columns = Math.max(...days.map(day => day.column)) + 1; + const columnStep = width / (columns + 1); + const rowStep = height / 7.5; + const pixelRatio = Math.min(window.devicePixelRatio, 3); + canvas.width = Math.ceil(width * pixelRatio); + canvas.height = Math.ceil(height * pixelRatio); + const ctx = canvas.getContext('2d')!; + ctx.setTransform(canvas.width / width, 0, 0, canvas.height / height, 0, 0); + const halfWidth = columnStep * lotScale; + const baseOffset = Math.min(columnStep, rowStep) * lotScale / 2; + const houses: { x: number; bottom: number; image: HTMLImageElement }[] = []; + for (const [index, day] of days.entries()) { + const { cell, row, column, level } = day; + const parity = column % 2; + const x = (column + 1) * columnStep; + const center = (row + parity / 2 + 0.5) * rowStep; + const rect = positions[index]; + cell.style.setProperty('--codeyears-x', `${x - (rect.left + rect.width / 2 - left)}px`); + cell.style.setProperty('--codeyears-y', `${center - (rect.top + rect.height / 2 - top)}px`); + if (!level) continue; + const options = buildings[level]; + const seed = Number(day.date.replaceAll('-', '')) ^ modelSeed; + const mixed = Math.imul(seed ^ (seed >>> 16), 0x45d9f3b); + const image = pictures.get(options[((mixed ^ (mixed >>> 16)) >>> 0) % options.length])!; + houses.push({ x, bottom: center + baseOffset, image }); + } + for (const house of houses.sort((a, b) => a.bottom - b.bottom)) { + const aspect = house.image.naturalWidth / house.image.naturalHeight; + const width = Math.min(2 * halfWidth, Math.min(house.bottom, rowStep * 2.45) * aspect); + const height = width / aspect; + ctx.drawImage(house.image, house.x - width / 2, house.bottom - height, width, height); + } + paintLegend(); + layer.hidden = false; + scroller.setAttribute('data-painted', ''); + } + + function schedule() { + if (!frame && !disposed) frame = requestAnimationFrame(paint); + } + + const updates = new MutationObserver(updateDays); + const resize = new ResizeObserver(schedule); + void loadAssets().then(loaded => { + if (disposed || !grid.isConnected) return; + pictures = loaded; + scroller.classList.add(sceneClass); + grid.before(style, layer); + updates.observe(grid, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-ix', 'data-level', 'data-date'] }); + resize.observe(grid); + updateDays(); + }, () => { /* Leave the native chart available if the local artwork did not load. */ }); + + return { + dispose() { + disposed = true; + cancelAnimationFrame(frame); + updates.disconnect(); + resize.disconnect(); + hide(); + scroller.classList.remove(sceneClass); + for (const cell of grid.querySelectorAll('td.ContributionCalendar-day')) { + cell.style.removeProperty('--codeyears-x'); + cell.style.removeProperty('--codeyears-y'); + } + style.remove(); + layer.remove(); + canvas.width = canvas.height = 0; + }, + }; +} diff --git a/src/extension/options.ts b/src/extension/options.ts deleted file mode 100644 index 98ee9b3..0000000 --- a/src/extension/options.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { localize, text } from './i18n'; -import { languagePreference, readLanguagePreference, resolveLanguage, saveLanguagePreference, type LanguagePreference } from './language'; - -const main = document.querySelector('main')!; -const select = document.querySelector('#language')!; -const status = document.querySelector('#save-status')!; -const version = chrome.runtime.getManifest().version; -let preference: LanguagePreference = 'auto'; - -function render() { - const language = resolveLanguage(preference); - document.documentElement.lang = language; - document.title = text(language, 'settingsTitle'); - localize(main, language); - document.querySelector('#version')!.textContent = text(language, 'version', [version]); - select.value = preference; -} - -async function initialize() { - preference = await readLanguagePreference(); - render(); - main.hidden = false; - select.disabled = false; -} - -select.addEventListener('change', async () => { - const next = languagePreference(select.value); - select.disabled = true; - status.textContent = ''; - delete status.dataset.error; - try { - await saveLanguagePreference(next); - preference = next; - render(); - status.textContent = text(resolveLanguage(preference), 'settingsSaved'); - } catch { - render(); - status.dataset.error = ''; - status.textContent = text(resolveLanguage(preference), 'languageSaveError'); - } finally { - select.disabled = false; - select.focus(); - } -}); - -void initialize(); diff --git a/src/extension/popup.ts b/src/extension/popup.ts index 90a3492..327f36c 100644 --- a/src/extension/popup.ts +++ b/src/extension/popup.ts @@ -1,31 +1,151 @@ -import { text, type MessageKey } from './i18n'; -import { readLanguagePreference, resolveLanguage } from './language'; - -const root = document.querySelector('#app')!; -const shadow = root.attachShadow({ mode: 'open' }); -shadow.innerHTML = ` - -

CodeYears

`; -const status = shadow.querySelector('output')!; - -async function openCity() { - const language = resolveLanguage(await readLanguagePreference()); - document.documentElement.lang = language; - const show = (key: MessageKey) => { status.textContent = text(language, key); }; - show('popupOpening'); +import { appearancePreference, readAppearanceSettings, saveAppearance, saveCityVisibility, type Appearance } from './appearance'; +import { localize, text, type MessageKey } from './i18n'; +import { languagePreference, readLanguagePreference, resolveLanguage, saveLanguagePreference, type LanguagePreference } from './language'; + +const main = document.querySelector('main')!; +const settings = document.querySelector('#settings')!; +const about = document.querySelector('#about')!; +const backToSettings = document.querySelector('#back-to-settings')!; +const authorLink = document.querySelector('#about-author-link')!; +const modes = document.querySelector('#appearance')!; +const citySettings = document.querySelector('#city-settings')!; +const cityVisibility = document.querySelector('#show-city')!; +const languageSelect = document.querySelector('#language')!; +const openButton = document.querySelector('#open-city')!; +const profileHint = document.querySelector('#profile-required')!; +const status = document.querySelector('#save-status')!; +const productSite = document.querySelector('#product-site')!; +const englishProductUrl = productSite.href; +const versionLabel = document.querySelector('#version')!; +const version = chrome.runtime.getManifest().version; +let appearance: Appearance = 'native'; +let showCity = true; +let preference: LanguagePreference = 'auto'; +let profileTarget: chrome.scripting.InjectionTarget | undefined; + +async function findActiveProfile() { try { const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); - if (!tab.id || !tab.url || new URL(tab.url).origin !== 'https://github.com') { show('popupWrongPage'); return; } - await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['entry.js'] }); - const [result] = await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => window.__codeyearsOpenCity?.() ?? false }); - if (!result.result) { show('popupNotReady'); return; } - show('popupOpened'); - window.close(); + if (tab?.id === undefined || !tab.url || new URL(tab.url).origin !== 'https://github.com') return; + const target = { tabId: tab.id }; + const hasProfileCalendar = async () => { + const [probe] = await chrome.scripting.executeScript({ + target, func: () => window.__codeyearsHasProfileCalendar?.() ?? null, + }); + return probe?.result; + }; + let profile = await hasProfileCalendar(); + if (profile == null) { + await chrome.scripting.executeScript({ target, files: ['entry.js'] }); + profile = await hasProfileCalendar(); + } + if (profile) return target; } catch { - show('popupFailed'); + // Chrome can restrict script access to the active page. } } -void openCity(); + +function render() { + const language = resolveLanguage(preference); + document.documentElement.lang = language; + localize(main, language); + productSite.href = language === 'zh-CN' ? productSite.dataset.zhHref! : englishProductUrl; + for (const link of main.querySelectorAll('a[href]')) link.title = link.href; + versionLabel.textContent = `v${version}`; + versionLabel.title = text(language, 'version', [version]); + languageSelect.value = preference; + cityVisibility.checked = showCity; + openButton.hidden = !showCity; + for (const input of modes.querySelectorAll('input')) input.checked = input.value === appearance; + renderPane(); +} + +function renderPane(focus = false) { + const showAbout = location.hash === '#about'; + settings.hidden = showAbout; + about.hidden = !showAbout; + document.title = text(resolveLanguage(preference), showAbout ? 'aboutAuthor' : 'settingsTitle'); + if (focus) (showAbout ? backToSettings : authorLink).focus({ preventScroll: true }); +} +window.addEventListener('hashchange', () => renderPane(true)); + +function show(key: MessageKey, control: HTMLElement, error = false) { + const group = control.closest('fieldset, .language')!; + if (status.previousElementSibling !== group) group.after(status); + status.toggleAttribute('data-error', error); + status.textContent = text(resolveLanguage(preference), key); +} + +function setBusy(busy: boolean) { + citySettings.disabled = modes.disabled = languageSelect.disabled = busy || !profileTarget; +} + +async function save(change: () => Promise, control: HTMLElement, error: MessageKey) { + setBusy(true); + try { + await change(); + render(); + show('settingsSaved', control); + } catch { + render(); + show(error, control, true); + } finally { + setBusy(false); + control.focus(); + } +} + +modes.addEventListener('change', event => { + const input = event.target; + if (!(input instanceof HTMLInputElement) || !input.checked) return; + void save(async () => { + const next = appearancePreference(input.value); + await saveAppearance(next); + appearance = next; + }, input, 'appearanceSaveError'); +}); + +cityVisibility.addEventListener('change', () => { + void save(async () => { + const next = cityVisibility.checked; + await saveCityVisibility(next); + showCity = next; + }, cityVisibility, 'cityVisibilitySaveError'); +}); + +languageSelect.addEventListener('change', () => { + void save(async () => { + const next = languagePreference(languageSelect.value); + await saveLanguagePreference(next); + preference = next; + }, languageSelect, 'languageSaveError'); +}); + +openButton.addEventListener('click', async () => { + if (!profileTarget) return; + setBusy(true); + show('popupOpening', openButton); + try { + const [result] = await chrome.scripting.executeScript({ target: profileTarget, func: () => window.__codeyearsOpenCity?.() ?? false }); + if (result.result === 'already-mounted') { show('popupAlreadyMounted', openButton, true); return; } + if (!result.result) { show('popupNotReady', openButton); return; } + show('popupOpened', openButton); + window.close(); + } catch { + show('popupFailed', openButton, true); + } finally { + setBusy(false); + } +}); + +void Promise.all([readAppearanceSettings(), readLanguagePreference(), findActiveProfile()]).then(([stored, savedLanguage, target]) => { + appearance = stored.appearance; + showCity = stored.showCity; + preference = savedLanguage; + profileTarget = target; + render(); + profileHint.hidden = Boolean(profileTarget); + settings.toggleAttribute('data-locked', !profileTarget); + main.hidden = false; + setBusy(false); +}); diff --git a/vite.config.ts b/vite.config.ts index afb8415..6851813 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -6,7 +6,7 @@ export default defineConfig({ build: { target: "es2022", rolldownOptions: { - input: { popup: "popup.html", options: "options.html" }, + input: "popup.html", output: { chunkFileNames: "assets/shared-[hash].js" }, }, },