diff --git a/README.md b/README.md index ab2aeca..a26ddd1 100644 --- a/README.md +++ b/README.md @@ -4,16 +4,16 @@ A Windows desktop app for building and maintaining Minecraft modpacks. It create projects and installs real mods from Modrinth, with every change reviewed before it is applied. Awake Launcher is not required. -> **What's new in 1.3.4:** see [docs/releases/v1.3.4.md](docs/releases/v1.3.4.md). +> **What's new in 1.4.0:** see [docs/releases/v1.4.0.md](docs/releases/v1.4.0.md). -**Version 1.3.4 · Windows x64 · English, ไทย, 简体中文, 繁體中文 · GPL-3.0-only** +**Version 1.4.0 · Windows x64 · English, ไทย, 简体中文, 繁體中文 · GPL-3.0-only** ## Install -1. Download `Awake-Modpack-Manager-v1.3.4-Windows-x64-Setup.exe` from the +1. Download `Awake-Modpack-Manager-v1.4.0-Windows-x64-Setup.exe` from the [latest release](https://github.com/awakenginexe/Awake-Modpack-Manager/releases/latest). 2. Optional: check it against `SHA256SUMS.txt` from the same release - (`Get-FileHash .\Awake-Modpack-Manager-v1.3.4-Windows-x64-Setup.exe`). + (`Get-FileHash .\Awake-Modpack-Manager-v1.4.0-Windows-x64-Setup.exe`). 3. Run the installer. It installs for your Windows user only (no administrator rights) into `%LOCALAPPDATA%\Awake Modpack Manager`. The installer is **not code-signed** yet, so Windows SmartScreen may warn that it is from an diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index cc5f55f..0b6e6e6 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,10 +1,10 @@ -# Development checkpoint: Manager 1.3.4 and Native Core 0.4.2 +# Development checkpoint: Manager 1.4.0 and Native Core 0.4.2 -Unreleased until the owner approves the pull request and tags `v1.3.4`. +Unreleased until the owner approves the pull request and tags `v1.4.0`. ## Where things are -- Manager: branch `release/1.3.4`. `npm ci`, then `npm test`, `npm run typecheck`, `cargo test --manifest-path src-tauri/Cargo.toml --lib`. +- Manager: branch `release/1.4.0`. `npm ci`, then `npm test`, `npm run typecheck`, `cargo test --manifest-path src-tauri/Cargo.toml --lib`. - Native Core: Awake Launcher branch `release/3.2.2`. `.github/workflows/native-core-package.yml` builds it with the recorded toolchain and commits a delivery under `native-core/redistribution//`. `scripts/helper-pin.json` pins that delivery. - Release: pushing a version tag runs `.github/workflows/awake-beta.yml`, which builds, verifies, assembles every asset and publishes the release. `SHA256SUMS.txt` is required by in-app updates. diff --git a/docs/releases/v1.4.0.md b/docs/releases/v1.4.0.md new file mode 100644 index 0000000..a0a274e --- /dev/null +++ b/docs/releases/v1.4.0.md @@ -0,0 +1,25 @@ +# Awake Modpack Manager 1.4.0 + +Works with **Awake Launcher 3.2.2** and newer. + +## New + +- **Turn a mod on or off with one click.** Every row on the Mods page has a switch. It is applied at once: no draft, no Review page. The change still goes through the same check, backup and rollback as a reviewed draft. If a switch would affect other mods (a conflict, or another mod pulled in), it is not applied silently: it is put in your draft and a message says so. A draft you were already building is kept. +- **A full project page when you click a mod, resource pack or shader.** Instead of the narrow panel on the right, a window opens with the project's own description and screenshots from Modrinth or CurseForge on the left, and the versions, the install or "Add to draft" button and "Open project page" on the right. + +## Changed + +- The mods table always shows the switch; on a narrow window it drops the Dependencies column instead. +- "Enable" and "Disable" in a mod's right-click menu and details panel are applied at once too. Enabling or disabling several selected mods still goes through the draft. + +## Fixed + +- **An instance managed here could show as "Read-only", and "Manage mods here" answered "This instance is already managed here."** This happened when the Manager's helper could not list its instances (for example after a jar saved from a browser was dropped into the mods folder). The Manager hid that error and treated the instance as unmanaged. It now shows the helper's message under the instance list and on "Manage mods here". The helper's own fix for browser-saved jars is separate and ships with a newer helper. + +## Safety + +Project descriptions are written by anyone on the two sites. They are never inserted as HTML: only plain formatting, https links and https images are rebuilt from them, and links open in your browser. Images in a description load from the address the author used. + +## Not verified on a real machine yet + +Checked with the automated tests and the built-in demo data. Still unverified in the desktop app against a real instance: the switch on a large pack, and real Modrinth and CurseForge project pages (descriptions, screenshots). diff --git a/package-lock.json b/package-lock.json index dd391b9..1cdcc6e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "awake-modpack-manager", - "version": "1.3.4", + "version": "1.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "awake-modpack-manager", - "version": "1.3.4", + "version": "1.4.0", "license": "GPL-3.0-only", "dependencies": { "@lucide/vue": "1.59.0", diff --git a/package.json b/package.json index bfd5d64..26bf0d1 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "awake-modpack-manager", "private": true, - "version": "1.3.4", + "version": "1.4.0", "license": "GPL-3.0-only", "type": "module", "engines": { diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 46b4eb2..af186b1 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -224,7 +224,7 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "awake-modpack-manager" -version = "1.3.4" +version = "1.4.0" dependencies = [ "md-5", "serde", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 5baa2fd..e4c6f7e 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "awake-modpack-manager" -version = "1.3.4" +version = "1.4.0" description = "Awake Modpack Manager desktop host" license = "GPL-3.0-only" repository = "https://github.com/awakenginexe/Awake-Modpack-Manager" diff --git a/src-tauri/src/providers.rs b/src-tauri/src/providers.rs index 43a1a46..078c142 100644 --- a/src-tauri/src/providers.rs +++ b/src-tauri/src/providers.rs @@ -1028,6 +1028,15 @@ pub struct ProjectDetail { license: Option, categories: Vec, page_url: Option, + /// The project's own long description, as the site stores it: Markdown (Modrinth) or HTML (CurseForge). + /// The window renders it through an allowlist; nothing here is trusted. + body: String, + body_format: &'static str, + gallery: Vec, +} +/// Screenshots, at most 12, and only from https. +fn gallery(list: &Value, key: &str) -> Vec { + list.as_array().map_or(vec![], |g| g.iter().filter_map(|x| x[key].as_str()).filter(|u| u.starts_with("https://")).take(12).map(String::from).collect()) } pub fn parse_modrinth_detail(p: &Value, members: &Value) -> ProjectDetail { @@ -1039,10 +1048,13 @@ pub fn parse_modrinth_detail(p: &Value, members: &Value) -> ProjectDetail { updated_at: p["updated"].as_str().map(Into::into), license: p["license"]["id"].as_str().filter(|l| !l.is_empty()).map(Into::into), categories: p["categories"].as_array().map_or(vec![], |c| c.iter().filter_map(|x| x.as_str().map(String::from)).collect()), - page_url: Some(format!("https://modrinth.com/mod/{}", s(p, "slug"))), + page_url: Some(format!("https://modrinth.com/{}/{}", p["project_type"].as_str().filter(|t| ["resourcepack", "shader"].contains(t)).unwrap_or("mod"), s(p, "slug"))), + body: s(p, "body").into(), + body_format: "markdown", + gallery: gallery(&p["gallery"], "url"), } } -pub fn parse_curseforge_detail(p: &Value) -> ProjectDetail { +pub fn parse_curseforge_detail(p: &Value, description: &str) -> ProjectDetail { ProjectDetail { author: p["authors"][0]["name"].as_str().unwrap_or("").into(), summary: s(p, "summary").into(), @@ -1051,6 +1063,9 @@ pub fn parse_curseforge_detail(p: &Value) -> ProjectDetail { license: None, categories: p["categories"].as_array().map_or(vec![], |c| c.iter().filter_map(|x| x["name"].as_str().map(String::from)).collect()), page_url: p["links"]["websiteUrl"].as_str().filter(|u| u.starts_with("https://")).map(Into::into), + body: description.into(), + body_format: "html", + gallery: gallery(&p["screenshots"], "url"), } } @@ -1064,7 +1079,12 @@ pub async fn project_detail(provider: String, project_id: String) -> HostResult< let members = get_json(&format!("{MODRINTH}/project/{}/members", encode(id))).unwrap_or(Value::Null); Ok(parse_modrinth_detail(&project, &members)) } - "curseforge" => Ok(parse_curseforge_detail(&cf_get(&format!("/mods/{}", encode(id)))?["data"])), + "curseforge" => { + let project = cf_get(&format!("/mods/{}", encode(id)))?; + // The long description is its own request; the rest of the page is still useful without it. + let description = cf_get(&format!("/mods/{}/description", encode(id))).unwrap_or(Value::Null); + Ok(parse_curseforge_detail(&project["data"], description["data"].as_str().unwrap_or(""))) + } _ => err("invalid", "Unknown mod provider."), } }) @@ -1169,9 +1189,11 @@ mod tests { #[test] fn project_details_read_both_providers() { - let m = parse_modrinth_detail(&json!({"slug": "sodium", "description": "Fast", "downloads": 5.0, "updated": "2026-01-01T00:00:00Z", "license": {"id": "LGPL-3.0"}, "categories": ["optimization"]}), &json!([{"role": "Member", "user": {"username": "b"}}, {"role": "Owner", "user": {"username": "jelly"}}])); - assert_eq!((m.author.as_str(), m.license.as_deref(), m.page_url.as_deref()), ("jelly", Some("LGPL-3.0"), Some("https://modrinth.com/mod/sodium"))); - let c = parse_curseforge_detail(&json!({"authors": [{"name": "mezz"}], "summary": "Items", "downloadCount": 9.0, "categories": [{"name": "API"}], "links": {"websiteUrl": "https://www.curseforge.com/minecraft/mc-mods/jei"}})); + let m = parse_modrinth_detail(&json!({"slug": "sodium", "description": "Fast", "downloads": 5.0, "updated": "2026-01-01T00:00:00Z", "license": {"id": "LGPL-3.0"}, "categories": ["optimization"], "project_type": "shader", "body": "# Hi", "gallery": [{"url": "https://cdn.modrinth.com/a.png"}, {"url": "http://plain/b.png"}]}), &json!([{"role": "Member", "user": {"username": "b"}}, {"role": "Owner", "user": {"username": "jelly"}}])); + assert_eq!((m.author.as_str(), m.license.as_deref(), m.page_url.as_deref()), ("jelly", Some("LGPL-3.0"), Some("https://modrinth.com/shader/sodium"))); + assert_eq!((m.body.as_str(), m.body_format, m.gallery), ("# Hi", "markdown", vec!["https://cdn.modrinth.com/a.png".to_string()])); + let c = parse_curseforge_detail(&json!({"authors": [{"name": "mezz"}], "summary": "Items", "downloadCount": 9.0, "categories": [{"name": "API"}], "links": {"websiteUrl": "https://www.curseforge.com/minecraft/mc-mods/jei"}, "screenshots": [{"url": "https://media.forgecdn.net/s.png"}]}), "

Items

"); + assert_eq!((c.body.as_str(), c.body_format, c.gallery.len()), ("

Items

", "html", 1)); assert_eq!((c.author.as_str(), c.categories.len(), c.downloads), ("mezz", 1, Some(9.0))); } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 62b033b..2a91def 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Awake Modpack Manager", - "version": "1.3.4", + "version": "1.4.0", "identifier": "io.github.awakenginexe.AwakeModpackManager", "build": { "frontendDist": "../dist", diff --git a/src/backend/composite.ts b/src/backend/composite.ts index 061a308..4afbaf9 100644 --- a/src/backend/composite.ts +++ b/src/backend/composite.ts @@ -20,6 +20,8 @@ export function createCompositeBackend(helper: ManagerBackend, launcher: Manager const launcherPaths = new Map(); const samePath = (p: string) => p.replace(/\\/g, '/').toLowerCase(); let retry: ReturnType | undefined; + /** Why the helper could not say which instances are connected; until it can, none may be connected again. */ + let sharedError: BackendError | null = null; const all = [parts.helper, parts.launcher]; const noHelper = (): Promise => Promise.reject(new BackendError('unsupported', 'Only Manager projects (the Manager helper) support this.')); @@ -59,7 +61,9 @@ export function createCompositeBackend(helper: ManagerBackend, launcher: Manager async function withShared(list: InstanceSummary[]): Promise { for (const i of list) if (i.path) launcherPaths.set(i.id, i.path); if (!parts.helper.handshake) return list; - const connected = new Map((await helper.listInstances('manager').catch(() => [] as InstanceSummary[])).filter((w) => w.sharedRoot).map((w) => [samePath(w.sharedRoot!), w])); + sharedError = null; + const mine = await helper.listInstances('manager').catch((e) => { sharedError = e instanceof BackendError ? e : new BackendError('protocol', String(e)); return [] as InstanceSummary[]; }); + const connected = new Map(mine.filter((w) => w.sharedRoot).map((w) => [samePath(w.sharedRoot!), w])); sharedOf.clear(); return list.map((i) => { const w = i.path ? connected.get(samePath(i.path)) : undefined; @@ -115,7 +119,7 @@ export function createCompositeBackend(helper: ManagerBackend, launcher: Manager startLauncher: async () => { await launcher.startLauncher?.(); scheduleLauncherRetry(); }, makeProfilePrivate: async () => { await launcher.makeProfilePrivate?.(); clearTimeout(retry); await connectPart(parts.launcher); emit(); scheduleLauncherRetry(); }, setPreferredProfile: (d) => launcher.setPreferredProfile?.(d), - instanceWarnings: () => current.backend.instanceWarnings?.() ?? [], + instanceWarnings: () => [...(current.backend.instanceWarnings?.() ?? []), ...(current === parts.launcher && sharedError ? [{ code: sharedError.code, path: sharedError.message }] : [])], async listInstances(installationId) { const p = backend.partFor(installationId); @@ -197,6 +201,8 @@ export function createCompositeBackend(helper: ManagerBackend, launcher: Manager }, canShareInstances: () => !!parts.helper.handshake && !!parts.launcher.handshake && !!helper.canAdopt?.() && !!launcher.canEnroll?.(), async shareInstance(id) { + // Without the helper's list an instance it already manages looks unconnected, and connecting it again is refused. + if (sharedError) throw sharedError; const path = launcherPaths.get(id); if (!path || !helper.adoptInstance || !launcher.enrollInstance) throw new BackendError('unsupported', 'Update Awake Launcher to 3.2.0 or newer to manage this instance here.'); // The Launcher refuses to start the game for this instance until it hears the outcome. diff --git a/src/backend/host.ts b/src/backend/host.ts index 2eb85b8..6d4793b 100644 --- a/src/backend/host.ts +++ b/src/backend/host.ts @@ -4,7 +4,7 @@ import { BackendError, type AddedContent, type ContentEntry, type ContentImage, export interface FetchedPack { token: string; format: 'mrpack' | 'curseforge'; size: number; sha256: string; notes: string[] } export interface ProjectMeta { provider: ProviderId; projectId: string; name: string; iconUrl?: string; restricted?: boolean; pageUrl?: string } export interface ModUpdate { provider: ProviderId; projectId: string; installedVersionId: string; candidate: { id: string; name: string; releaseType: 'release' | 'beta' | 'alpha' } | null } -export interface ProjectDetail { author: string; summary: string; downloads: number | null; updatedAt: string | null; license: string | null; categories: string[]; pageUrl: string | null } +export interface ProjectDetail { author: string; summary: string; downloads: number | null; updatedAt: string | null; license: string | null; categories: string[]; pageUrl: string | null; body?: string; bodyFormat?: 'markdown' | 'html'; gallery?: string[] } export interface ProjectRef { provider: ProviderId; projectId: string; versionId?: string } /** diff --git a/src/backend/mock/MockBackend.ts b/src/backend/mock/MockBackend.ts index 0996f38..40a9425 100644 --- a/src/backend/mock/MockBackend.ts +++ b/src/backend/mock/MockBackend.ts @@ -581,6 +581,21 @@ export class MockBackend implements ManagerBackend { /* ----- resource packs & shaders ----- */ + /** A made-up project page, so the details window has something to show in the demo. */ + async projectDetail(provider: ProviderId, projectId: string) { + await this.delay(this.opts.latencyMs); + const shot = (hue: number) => `data:image/svg+xml,${encodeURIComponent(``)}`; + const seed = [...projectId].reduce((n, c) => n + c.charCodeAt(0), 0); + return { + author: 'demo-author', summary: '', downloads: null, updatedAt: '2026-11-03T16:30:00Z', license: 'MIT', categories: ['library', 'utility'], pageUrl: null, + bodyFormat: provider === 'curseforge' ? 'html' as const : 'markdown' as const, + body: provider === 'curseforge' + ? '

About

A demo page written as HTML.

  • One thing
  • Another
' + : '# About\n\nA **demo** page written as Markdown, with a [link](https://example.com/).\n\n## Features\n\n- One thing\n- Another\n\n```\n/give @s demo\n```', + gallery: [shot(seed % 360), shot((seed + 120) % 360), shot((seed + 240) % 360)], + }; + } + async contentProviders(): Promise { return this.opts.providers ?? DEFAULT_PROVIDERS; } searchContent(q: ContentSearchQuery): Promise { return this.call(() => { diff --git a/src/components/ProjectDialog.vue b/src/components/ProjectDialog.vue new file mode 100644 index 0000000..5adb4b7 --- /dev/null +++ b/src/components/ProjectDialog.vue @@ -0,0 +1,134 @@ + + + + + diff --git a/src/components/SettingsDialog.vue b/src/components/SettingsDialog.vue index d9178ab..b59680d 100644 --- a/src/components/SettingsDialog.vue +++ b/src/components/SettingsDialog.vue @@ -315,11 +315,6 @@ async function removeFolder(folder: string) { .picker-option[aria-selected='true'] { color: #fff; font-weight: 600; } .tick { color: #60a5fa; } -/* Toggle switch built on a native checkbox (keeps keyboard + screen reader behaviour). */ -.switch { appearance: none; width: 42px !important; height: 24px !important; flex-shrink: 0; border-radius: 999px; background: rgba(255, 255, 255, 0.14); border: 1px solid rgba(255, 255, 255, 0.18); position: relative; cursor: pointer; transition: background-color var(--duration-fast) var(--ease); } -.switch::after { content: ''; position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #e2e8f0; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); transition: transform var(--duration-fast) var(--ease); } -.switch:checked { background: var(--accent); border-color: transparent; } -.switch:checked::after { transform: translateX(18px); background: #fff; } /* Connection */ .status-card { display: flex; align-items: center; gap: 12px; margin-top: 16px; padding: 14px 16px; border-radius: var(--radius-medium); border: 1px solid var(--border); background: rgba(255, 255, 255, 0.03); } diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 4e4bacf..e7e2e79 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -807,6 +807,12 @@ export const en = { contentNoVersions: "No version for Minecraft {version}. Untick the version filter to see every version.", contentShowInFiles: "Show installed", contentNeedManage: "To install resource packs and shaders, turn on “Manage mods here” for this instance on the Mods page.", + toggleEnable: "Turn on {name}", + toggleDisable: "Turn off {name}", + toggleNeedsReview: "{name} affects other mods, so this change is waiting in Review.", + detailGallery: "Screenshots", + detailShot: "Screenshot {n}", + detailNoBody: "This project has no description on its page.", } as const; export type MessageKey = keyof typeof en; diff --git a/src/i18n/th.ts b/src/i18n/th.ts index a5297a5..506a67a 100644 --- a/src/i18n/th.ts +++ b/src/i18n/th.ts @@ -809,4 +809,10 @@ export const th: Catalog = { contentNoVersions: "ไม่มีเวอร์ชันสำหรับ Minecraft {version} ยกเลิกตัวกรองเวอร์ชันเพื่อดูทุกเวอร์ชัน", contentShowInFiles: "ดูที่ติดตั้งแล้ว", contentNeedManage: "หากต้องการติดตั้งรีซอร์สแพ็กและเชดเดอร์ ให้เปิด “จัดการม็อดที่นี่” ของอินสแตนซ์นี้ที่หน้าม็อดก่อน", + toggleEnable: "เปิด {name}", + toggleDisable: "ปิด {name}", + toggleNeedsReview: "{name} มีผลกับม็อดอื่น การเปลี่ยนแปลงนี้จึงรออยู่ในหน้าตรวจสอบ", + detailGallery: "ภาพหน้าจอ", + detailShot: "ภาพหน้าจอ {n}", + detailNoBody: "โปรเจกต์นี้ไม่มีคำอธิบายบนหน้าเว็บ", }; diff --git a/src/i18n/zh-CN.ts b/src/i18n/zh-CN.ts index 47bbe91..32ee94c 100644 --- a/src/i18n/zh-CN.ts +++ b/src/i18n/zh-CN.ts @@ -809,4 +809,10 @@ export const zhCN: Catalog = { contentNoVersions: "没有适用于 Minecraft {version} 的版本。取消版本筛选即可查看全部版本。", contentShowInFiles: "查看已安装", contentNeedManage: "要安装资源包和光影,请先在“模组”页面为此版本开启“在此管理模组”。", + toggleEnable: "启用 {name}", + toggleDisable: "禁用 {name}", + toggleNeedsReview: "{name} 会影响其他模组,此更改已放入“检查”等待确认。", + detailGallery: "截图", + detailShot: "截图 {n}", + detailNoBody: "此项目的页面上没有说明。", }; diff --git a/src/i18n/zh-TW.ts b/src/i18n/zh-TW.ts index a3c36b5..e50ea03 100644 --- a/src/i18n/zh-TW.ts +++ b/src/i18n/zh-TW.ts @@ -809,4 +809,10 @@ export const zhTW: Catalog = { contentNoVersions: "沒有適用於 Minecraft {version} 的版本。取消版本篩選即可檢視所有版本。", contentShowInFiles: "檢視已安裝", contentNeedManage: "要安裝資源包和光影,請先在「模組」頁面為此實例開啟「在此管理模組」。", + toggleEnable: "啟用 {name}", + toggleDisable: "停用 {name}", + toggleNeedsReview: "{name} 會影響其他模組,此變更已放入「檢查」等待確認。", + detailGallery: "螢幕截圖", + detailShot: "螢幕截圖 {n}", + detailNoBody: "此專案的頁面上沒有說明。", }; diff --git a/src/state/session.ts b/src/state/session.ts index ad6e26d..7725151 100644 --- a/src/state/session.ts +++ b/src/state/session.ts @@ -8,7 +8,7 @@ import { export interface OpChange { action: PlanAction; name: string; from?: string; to?: string } import type { ConnectionState, ManagerBackend } from '../backend/ManagerBackend'; import { isComposite } from '../backend/composite'; -import { isStale, newDraft, rebase } from '../domain/draft'; +import { addChanges, isStale, newDraft, rebase } from '../domain/draft'; import { followOperation, isSettled } from '../domain/operation'; import { load, save } from '../domain/storage'; import { prune, emptySelection, type Selection } from '../domain/selection'; @@ -456,6 +456,62 @@ export function createSession(backend: ManagerBackend, { pollMs = 1500 } = {}) { } } + /* ----- instant enable / disable: one checked and applied change, without the Review page ----- */ + + /** Mods whose switch is being applied right now. */ + const toggling = ref>(new Set()); + let toggleQueue: Promise = Promise.resolve(); + const canQuickToggle = computed(() => can('plan.validate') && can('plan.prepare') && can('plan.apply')); + + /** + * Turn one mod on or off now. It goes through the same check, prepare and apply as a reviewed draft, so the + * coordinator's backup and rollback still cover it. Resolves 'done', or 'review' when the change was put in the + * draft instead because it is not a one-file change (a conflict, another mod pulled in) or cannot be applied here. + */ + function quickToggle(modKey: string, enabled: boolean): Promise<'done' | 'review'> { + toggling.value = new Set(toggling.value).add(modKey); + // One at a time: each apply changes the revision the next one is checked against. + const run = toggleQueue.then(() => toggleNow(modKey, enabled)).finally(() => { + const next = new Set(toggling.value); next.delete(modKey); toggling.value = next; + }); + toggleQueue = run.catch(() => undefined); + return run; + } + async function toggleNow(modKey: string, enabled: boolean, retried = false): Promise<'done' | 'review'> { + const id = state.instanceId; + if (!id || !inventory.value) throw new BackendError('rejected', 'No instance is open.'); + const change = { kind: enabled ? 'enable' as const : 'disable' as const, modKey }; + const toDraft = () => { if (draft.value) setDraft(addChanges(draft.value, [change])); return 'review' as const; }; + // A draft being checked or applied owns the coordinator's one waiting plan for this instance. + if (!canQuickToggle.value || ['resolving', 'preparing', 'applying', 'unconfirmed', 'changed'].includes(review.phase)) return toDraft(); + let plan: ResolvedPlan; + try { + plan = await backend.validateDraft({ ...newDraft(id, inventory.value.revision), changes: [change], pinnedKeys: [...pinned.value] }); + } catch (e) { + // Something else changed the instance (a game run, the Launcher): read it again and try once more. + if (asError(e).code !== 'stale-revision' || retried) throw e; + await loadInventory(); + return toggleNow(modKey, enabled, true); + } + const prepared = plan.blocked || plan.items.filter((i) => i.action !== 'keep').length !== 1 ? null : await backend.preparePlan(plan.planId); + if (!prepared || prepared.planHash !== plan.planHash) { + await backend.discardPlan?.(id).catch(() => undefined); + return toDraft(); + } + // shortcut: not saved as a pending apply, so a lost connection mid-switch is not resent; the list is re-read and shows what happened. + recordChanges([prepared.planId], prepared); + const { operationId } = await backend.applyPlan({ planId: prepared.planId, planHash: prepared.planHash, baseRevision: prepared.baseRevision, idempotencyKey: crypto.randomUUID() }); + if (operationId !== prepared.planId) recordChanges([operationId], prepared); + const final = await track(operationId); + await loadInventory(); + // The user's own draft was made for the list before this switch: carry it over instead of calling it out of date. + const mine = drafts.value[id]; + if (mine && inventory.value && isStale(mine, inventory.value.revision)) setDraft(rebase(mine, inventory.value.revision, inventory.value.mods).draft); + if (review.plan || review.phase !== 'idle') resetReview(); // a plan checked before the switch no longer matches + if (final && final.state !== 'completed') throw new BackendError('rejected', final.error?.message ?? 'The change was not applied.'); + return 'done'; + } + /** User confirmed the changed plan; it becomes the reviewed plan. */ function acceptChangedPlan() { if (review.phase === 'changed') review.phase = 'reviewed'; @@ -667,7 +723,7 @@ export function createSession(backend: ManagerBackend, { pollMs = 1500 } = {}) { backend, source, instanceSource, instanceHandshake, canShare, shareInstance, stopSharingInstance, state, inventory, selection, drafts, pins, exportIncludes, review, can, instance, draft, pinned, planOutdated, policies, policyOf, packHandshake, connect, refreshInstances, selectInstance, loadInventory, checkUpdates, deleteInstance, renameInstance, preparePackUpdate, - setDraft, discardDraft, rebaseDraft, setPinned, setExcluded, prepareImport, + setDraft, discardDraft, rebaseDraft, setPinned, setExcluded, prepareImport, quickToggle, toggling, canQuickToggle, validate, apply, acceptChangedPlan, resetReview, missingTracked, forgetMissingMods, modifiedMods, fixModifiedMods, opChanges, refreshOperations, cancelOperation, runRecovery, createInstance, installPack, startExport, launch, startLauncher, makeProfilePrivate, }; diff --git a/src/styles/base.css b/src/styles/base.css index 002ef97..c36d42f 100644 --- a/src/styles/base.css +++ b/src/styles/base.css @@ -214,3 +214,10 @@ button.card:hover .avatar, .card.interactive:hover .avatar { transform: scale(1. /* Reduced motion: honour the OS setting and the in-app preference. */ @media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition: none !important; animation: none !important; } } .reduced-motion *, .reduced-motion *::before, .reduced-motion *::after { transition: none !important; animation: none !important; } + +/* Toggle switch built on a native checkbox (keeps keyboard + screen reader behaviour). */ +.switch { appearance: none; width: 42px !important; height: 24px !important; flex-shrink: 0; border-radius: 999px; background: rgba(255, 255, 255, 0.14); border: 1px solid rgba(255, 255, 255, 0.18); position: relative; cursor: pointer; transition: background-color var(--duration-fast) var(--ease); } +.switch::after { content: ''; position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #e2e8f0; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); transition: transform var(--duration-fast) var(--ease); } +.switch:checked { background: var(--accent); border-color: transparent; } +.switch:checked::after { transform: translateX(18px); background: #fff; } +.switch:disabled { cursor: progress; opacity: 0.6; } diff --git a/src/ui/richText.ts b/src/ui/richText.ts new file mode 100644 index 0000000..e955ba6 --- /dev/null +++ b/src/ui/richText.ts @@ -0,0 +1,88 @@ +/** + * Project descriptions come from Modrinth (Markdown, often with HTML in it) and CurseForge (HTML), written by + * anyone. They are never inserted as HTML: the text is parsed into an inert document and rebuilt from an + * allowlist of plain formatting tags, https links and https images. Everything else is dropped or unwrapped. + */ + +const KEEP = new Set(['p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'strong', 'b', 'em', 'i', 'u', 's', 'del', 'code', 'pre', 'blockquote', + 'ul', 'ol', 'li', 'a', 'img', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'details', 'summary', 'center', 'sub', 'sup', 'kbd']); +/** Removed together with everything inside them. */ +const DROP = new Set(['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'button', 'textarea', 'select', 'svg', 'math', 'link', 'meta', 'base', 'template', 'noscript', 'video', 'audio', 'title', 'head']); +const web = (url: string | null) => (url && /^https:\/\/[^\s"'<>]+$/i.test(url.trim()) ? url.trim() : null); + +function copy(from: Node, to: Node, doc: Document) { + for (const node of Array.from(from.childNodes)) { + if (node.nodeType === 3) { to.appendChild(doc.createTextNode(node.textContent ?? '')); continue; } + if (node.nodeType !== 1) continue; + const el = node as Element, tag = el.tagName.toLowerCase(); + if (DROP.has(tag)) continue; + if (!KEEP.has(tag)) { copy(el, to, doc); continue; } // unknown wrapper (div, span, font): keep its text + const out = doc.createElement(tag); + if (tag === 'a') { + const href = web(el.getAttribute('href')); + if (!href) { copy(el, to, doc); continue; } + out.setAttribute('href', href); + out.setAttribute('rel', 'noreferrer noopener'); + } else if (tag === 'img') { + const src = web(el.getAttribute('src')); + if (!src) continue; + out.setAttribute('src', src); + out.setAttribute('alt', el.getAttribute('alt') ?? ''); + out.setAttribute('loading', 'lazy'); + out.setAttribute('referrerpolicy', 'no-referrer'); + } + copy(el, out, doc); + to.appendChild(out); + } +} + +const inline = (text: string) => text + .replace(/`([^`\n]+)`/g, (_m, code: string) => `${code.replace(/&/g, '&').replace(/`) + .replace(/!\[([^\]\n]*)\]\(\s*([^)\s]+)[^)\n]*\)/g, '$1') + .replace(/\[([^\]\n]+)\]\(\s*([^)\s]+)[^)\n]*\)/g, '$1') + .replace(/(^|[\s(>])(https:\/\/[^\s<)"]+)/g, '$1$2') + .replace(/\*\*([^*\n]+)\*\*|__([^_\n]+)__/g, (_m, a?: string, b?: string) => `${a ?? b}`) + .replace(/(^|[^*\w])\*([^*\n]+)\*/g, '$1$2') + .replace(/~~([^~\n]+)~~/g, '$1'); + +/** The common Markdown the sites use: headings, lists, quotes, rules, fenced code, emphasis, links, images. HTML passes through to the allowlist. */ +export function markdownToHtml(source: string): string { + const out: string[] = []; + let paragraph: string[] = [], list: 'ul' | 'ol' | null = null, fence: string[] | null = null; + const flush = () => { if (paragraph.length) out.push(`

${inline(paragraph.join('\n')).replace(/\n/g, '
')}

`); paragraph = []; }; + const endList = () => { if (list) out.push(``); list = null; }; + for (const raw of source.replace(/\r\n?/g, '\n').split('\n')) { + if (fence) { + if (/^\s*(```|~~~)/.test(raw)) { out.push(`
${fence.join('\n').replace(/&/g, '&').replace(/
`); fence = null; } else fence.push(raw); + continue; + } + const line = raw.trimEnd(); + if (/^\s*(```|~~~)/.test(line)) { flush(); endList(); fence = []; continue; } + const item = /^\s*(?:([-*+])|(\d+)[.)])\s+(.*)$/.exec(line); + if (item) { + flush(); + const kind = item[1] ? 'ul' : 'ol'; + if (list !== kind) { endList(); out.push(`<${kind}>`); list = kind; } + out.push(`
  • ${inline(item[3]!)}
  • `); + continue; + } + endList(); + const heading = /^(#{1,6})\s+(.*?)\s*#*$/.exec(line); + if (!line.trim()) flush(); + else if (heading) { flush(); out.push(`${inline(heading[2]!)}`); } + else if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { flush(); out.push('
    '); } + else if (/^\s*>/.test(line)) { flush(); out.push(`
    ${inline(line.replace(/^\s*>\s?/, ''))}
    `); } + else paragraph.push(line); + } + if (fence) out.push(`
    ${fence.join('\n').replace(/&/g, '&').replace(/
    `); + flush(); endList(); + return out.join('\n'); +} + +/** A description as safe nodes for `doc`, ready to append. */ +export function renderRich(source: string, format: 'markdown' | 'html', doc: Document = document): DocumentFragment { + const parsed = new DOMParser().parseFromString(format === 'markdown' ? markdownToHtml(source) : source, 'text/html'); + const fragment = doc.createDocumentFragment(); + copy(parsed.body, fragment, doc); + return fragment; +} diff --git a/src/views/BrowseView.vue b/src/views/BrowseView.vue index cc59750..998c9e9 100644 --- a/src/views/BrowseView.vue +++ b/src/views/BrowseView.vue @@ -1,17 +1,17 @@ ' + + '' + + 'badgood
    ', 'html'); + expect(out).toBe('

    Hi there

    badgood'); + }); + + it('treats HTML inside Markdown the same way', () => { + const out = html('
    \n\n\n\n[x](javascript:alert(1))'); + expect(out).toContain('
    '); + expect(out).not.toMatch(/script|javascript|alert/); + }); +}); diff --git a/tests/session.test.ts b/tests/session.test.ts index 2e380df..65ccd31 100644 --- a/tests/session.test.ts +++ b/tests/session.test.ts @@ -221,4 +221,34 @@ describe('session installPack', () => { expect(session.instance.value?.pack?.packId).toBe(hit.packId); expect(session.inventory.value?.instanceId).toBe(final?.result?.instanceId); }); + + it('switches a mod off and on at once, without the Review page', async () => { + const { session } = await ready(); + const mod = session.inventory.value!.mods.find((m) => m.enabled && !m.locallyModified && !(m.dependencies ?? []).length)!; + const other = session.inventory.value!.mods.find((m) => hasUpdate(m) && !m.locallyModified && m.key !== mod.key)!; + session.setDraft(addChanges(session.draft.value!, [{ kind: 'update', modKey: other.key, targetVersionId: other.available!.id }])); + + const run = session.quickToggle(mod.key, false); + expect(session.toggling.value.has(mod.key)).toBe(true); + expect(await run).toBe('done'); + expect(session.toggling.value.size).toBe(0); + expect(session.inventory.value!.mods.find((m) => m.key === mod.key)!.enabled).toBe(false); + // The draft the user was building is kept, moved onto the instance as it is now, and is not part of what was applied. + expect(session.draft.value!.changes).toEqual([{ kind: 'update', modKey: other.key, targetVersionId: other.available!.id }]); + expect(session.draft.value!.baseRevision).toBe(session.inventory.value!.revision); + expect(session.inventory.value!.mods.find((m) => m.key === other.key)!.installed?.id).toBe(other.installed?.id); + + expect(await session.quickToggle(mod.key, true)).toBe('done'); + expect(session.inventory.value!.mods.find((m) => m.key === mod.key)!.enabled).toBe(true); + }); + + it('leaves a switch for Review when it cannot be applied on its own', async () => { + const { session, backend } = await ready(); + const mod = session.inventory.value!.mods.find((m) => m.enabled && !m.locallyModified)!; + const real = backend.validateDraft.bind(backend); + vi.spyOn(backend, 'validateDraft').mockImplementation(async (d) => ({ ...(await real(d)), blocked: true })); + expect(await session.quickToggle(mod.key, false)).toBe('review'); + expect(session.inventory.value!.mods.find((m) => m.key === mod.key)!.enabled).toBe(true); + expect(session.draft.value!.changes).toContainEqual({ kind: 'disable', modKey: mod.key }); + }); }); diff --git a/tests/sharedInstances.test.ts b/tests/sharedInstances.test.ts index e1c2703..5501cae 100644 --- a/tests/sharedInstances.test.ts +++ b/tests/sharedInstances.test.ts @@ -102,6 +102,15 @@ describe('connected Launcher instances', () => { expect(bad.steps).toEqual(['begin', 'abort']); }); + it('says why when the helper cannot list its instances, instead of offering to connect one again', async () => { + const { composite, helper, steps } = await connected(); + helper.listInstances = async () => { throw new BackendError('recovery-required', 'Workspace inventory cannot be verified.'); }; + expect((await listOn(composite, 'launcher')).map((i) => i.id)).toEqual(['launcher-pack', 'launcher-other']); + expect(composite.instanceWarnings!()).toEqual([{ code: 'recovery-required', path: 'Workspace inventory cannot be verified.' }]); + await expect(composite.shareInstance!('launcher-pack')).rejects.toThrow('Workspace inventory cannot be verified.'); + expect(steps).toEqual([]); + }); + it('holds the Launcher around disconnecting', async () => { const { composite, steps } = await connected(); await listOn(composite, 'launcher');