Merge launcher folders and custom layout

This commit is contained in:
Blendman974 committed 2026-11-06 06:00:42 +01:00
commit c9151710dc
7 files changed
+505 -34

No files matched your search

+131 -20
View File
@@ -8,7 +8,11 @@ import { IconGrid, ICON_GRID_BAND_INSET_X, ICON_GRID_HIGHLIGHT_INSET_Y, ICON_GRI
import { Layer, LayerActions, LayerContext } from "../../ui/layers";
import { MenuLayer, type MenuItem } from "../../ui/menu";
import { WINDOW_MENU_LAYOUT } from "../../ui/window-menu";
import { onAnySettingChanged } from "../../ui/dashboard-settings";
import {
onAnySettingChanged, launcherLayoutSetting, enumSettingMenuItem,
ConfigSettingString, EditTextSettingLayer,
} from "../../ui/dashboard-settings";
import { getLauncherLayoutFingerprint, orderLauncherEntries, moveLauncherEntry } from "./launcher-layout";
import { createInProcessWindow } from "../../ui/shell/in-process-window";
import {
getFolderAssignments,
@@ -16,6 +20,7 @@ import {
getFolderStateFingerprint,
setAppFolder,
unusedNewFolderName,
getExplicitFolderNames, createFolder, renameFolder, folderNameError, disbandFolder,
} from "./launcher-folders";
import { shell, type ShellWindow } from "../../ui/shell/shell";
@@ -66,6 +71,14 @@ type LauncherGridEntry =
* and is re-read every paint, so assistant folder tools take effect without
* the layer holding any copy of the state.
*/
const entryKey = (entry: LauncherGridEntry) => entry.kind === "app" ? `app:${entry.appId}` : `folder:${entry.name}`;
/** Reuse the phone text editor; dismiss it if the glasses leave this page. */
class FolderNameEditorLayer extends EditTextSettingLayer {
constructor(setting: ConfigSettingString, private readonly actions: LayerActions) { super(setting); }
onRemoved(): void { void this.actions.endTextSettingEdit(); }
}
class LauncherGridLayer implements Layer {
// Watch swipes are spatial: up/down move between rows, left/right between
// columns. From the leftmost column, left keeps going out: it leaves the
@@ -74,6 +87,12 @@ class LauncherGridLayer implements Layer {
readonly acceptsDirectional = true;
/** Folder whose contents the grid is showing, or null for the top grid. */
private currentFolder: string | null = null;
private editingFolder = false;
private moving: { key: string; label: string; folder: string | null } | null = null;
private sortEntries(entries: LauncherGridEntry[]): LauncherGridEntry[] {
return orderLauncherEntries(entries, entryKey, this.currentFolder, launcherLayoutSetting.get() === "custom");
}
private readonly grid = new IconGrid<LauncherGridEntry>({
items: () => this.entries(),
describe: (entry) => ({
@@ -104,25 +123,23 @@ class LauncherGridLayer implements Layer {
const members = (getFolders().get(this.currentFolder) ?? [])
.map((appId) => byAppId.get(appId))
.filter(Boolean) as LauncherAppEntry[];
if (members.length > 0) {
return members
.map((app): LauncherGridEntry => ({
if (members.length > 0 || getExplicitFolderNames().includes(this.currentFolder)) {
return this.sortEntries(members.map((app): LauncherGridEntry => ({
kind: "app",
label: app.label,
icon: app.icon,
appId: app.appId,
renderIcon: app.renderIcon,
}))
.sort((a, b) => a.label.localeCompare(b.label));
})));
}
this.currentFolder = null;
}
const assignments = getFolderAssignments();
const entries: LauncherGridEntry[] = [];
// A folder cell appears only when it holds at least one known app; stale
// assignments to removed apps are ignored.
// Legacy folders need a known member; explicitly created folders may be empty.
const explicit = new Set(getExplicitFolderNames());
for (const [name, members] of getFolders()) {
if (members.some((appId) => byAppId.has(appId))) {
if (explicit.has(name) || members.some((appId) => byAppId.has(appId))) {
entries.push({ kind: "folder", label: name, name });
}
}
@@ -137,7 +154,7 @@ class LauncherGridLayer implements Layer {
});
}
}
return entries.sort((a, b) => a.label.localeCompare(b.label));
return this.sortEntries(entries);
}
/** Leave the current folder, putting the selection back on its cell. */
@@ -151,6 +168,16 @@ class LauncherGridLayer implements Layer {
/** Enter a folder or launch an app; true when that left the grid (a launch). */
private async openEntry(entry: LauncherGridEntry): Promise<boolean> {
if (this.moving) {
const moving = this.moving;
this.moving = null;
if (launcherLayoutSetting.get() === "custom" && moving.folder === this.currentFolder) {
moveLauncherEntry(this.currentFolder, this.entries().map(entryKey), moving.key, entryKey(entry));
const index = this.entries().findIndex(item => entryKey(item) === moving.key);
if (index >= 0) this.grid.selectIndex(index);
}
return false;
}
if (entry.kind === "folder") {
this.currentFolder = entry.name;
this.grid.resetSelection();
@@ -166,6 +193,13 @@ class LauncherGridLayer implements Layer {
/** Leave the open folder, else yield to the sidebar; true when that left the grid. */
private back(): boolean {
if (this.moving) {
const key = this.moving.key;
this.moving = null;
const index = this.entries().findIndex(entry => entryKey(entry) === key);
if (index >= 0) this.grid.selectIndex(index);
return false;
}
if (this.currentFolder !== null) {
this.exitFolder();
return false;
@@ -175,14 +209,54 @@ class LauncherGridLayer implements Layer {
}
/**
* App-specific entries for the window's context menu. Only item mode
* pins the selection to a single cell, and only apps can move to folders,
* so anywhere else the menu falls back to just the defaults.
* Layout and folder creation are always available. Per-icon actions need
* item mode so row navigation never edits an ambiguous selection.
*/
menuItems(): MenuItem[] {
if (this.editingFolder) return [];
const entry = this.grid.selectedItem;
if (!entry || entry.kind !== "app") return [];
return [
const items: MenuItem[] = [
enumSettingMenuItem(launcherLayoutSetting, { onChange: () => { this.moving = null; this.grid.resetSelection(); } }),
{
label: "New folder",
onSelect: ctx => {
const name = unusedNewFolderName();
if (createFolder(name)) {
this.currentFolder = null;
this.moving = null;
this.grid.resetSelection();
this.grid.selectIndex(this.entries().findIndex(item => item.kind === "folder" && item.name === name));
}
ctx.stack.pop();
},
},
];
const folder = entry?.kind === "folder" ? entry.name : this.currentFolder;
if (folder !== null) {
items.push({ label: "Rename folder", onSelect: ctx => this.editFolderName(folder, ctx) }, {
label: "Delete folder",
onSelect: ctx => {
ctx.stack.pop();
ctx.stack.push(new MenuLayer("Delete folder? Apps stay installed.", [
{ label: "Delete folder", onSelect: confirm => {
disbandFolder(folder);
if (this.currentFolder === folder) this.currentFolder = null;
this.moving = null;
this.grid.resetSelection();
confirm.stack.pop();
} },
{ label: "Cancel", onSelect: confirm => confirm.stack.pop() },
], WINDOW_MENU_LAYOUT));
},
});
}
if (this.moving) items.push({ label: "Cancel move", onSelect: ctx => { this.back(); ctx.stack.pop(); } });
else if (entry && launcherLayoutSetting.get() === "custom") items.push({
label: "Move icon",
onSelect: ctx => { this.moving = { key: entryKey(entry), label: entry.label, folder: this.currentFolder }; ctx.stack.pop(); },
});
if (!entry || entry.kind !== "app") return items;
return [...items,
{
label: "Move to folder",
onSelect: (ctx) => {
@@ -221,6 +295,32 @@ class LauncherGridLayer implements Layer {
];
}
private editFolderName(folder: string, ctx: LayerContext): void {
ctx.stack.pop();
const setting = new ConfigSettingString({
id: "launcher-folder-name", label: "Folder name", storageKey: "launcher.folderNameDraft",
defaultValue: folder, normalize: value => value ?? "",
validate: value => folderNameError(value, folder), reportInAnalytics: false,
});
setting.set(folder);
this.editingFolder = true;
const editor = new FolderNameEditorLayer(setting, ctx.actions);
ctx.stack.push(editor);
void ctx.actions.startTextSettingsEdit([setting], "Rename folder", () => {
this.editingFolder = false;
if (renameFolder(folder, setting.get())) {
if (this.currentFolder === folder) this.currentFolder = setting.get().trim();
this.moving = null;
}
ctx.stack.popIfTop(layer => layer === editor);
ctx.actions.requestRender();
}, undefined, () => {
this.editingFolder = false;
ctx.stack.popIfTop(layer => layer === editor);
ctx.actions.requestRender();
});
}
/**
* The folder-picker submenu: every existing folder except the app's own,
* plus a generated-name "New folder" (ring input has no text entry) and,
@@ -242,7 +342,9 @@ class LauncherGridLayer implements Layer {
items.push({
label: "New folder",
onSelect: (ctx) => {
setAppFolder(appId, unusedNewFolderName());
const name = unusedNewFolderName();
createFolder(name);
setAppFolder(appId, name);
ctx.stack.pop();
},
});
@@ -263,8 +365,16 @@ class LauncherGridLayer implements Layer {
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
// The folder-name header band scales with the font.
const gridTop = this.currentFolder !== null ? GRID_TOP + font.lineHeight + 4 : ROOT_GRID_TOP;
if (this.currentFolder !== null) {
const entries = this.entries();
if (this.moving && (launcherLayoutSetting.get() !== "custom" || this.moving.folder !== this.currentFolder ||
!entries.some(entry => entryKey(entry) === this.moving!.key))) this.moving = null;
const gridTop = this.moving ? GRID_TOP + 2 * (font.lineHeight + 2)
: this.currentFolder !== null ? GRID_TOP + font.lineHeight + 4 : ROOT_GRID_TOP;
if (this.moving) {
image.drawText(font, 8, GRID_TOP - 2, truncateText(font, `Move ${this.moving.label}`, width - 16), 220);
image.drawText(font, 8, GRID_TOP + font.lineHeight, "Select position; double tap cancels", 160);
}
if (this.currentFolder !== null && !this.moving) {
image.drawText(font, 8, GRID_TOP - 2, truncateText(font, this.currentFolder, width - 16), 160);
}
// The grid runs to the window's bottom edge, so a row cut off there for
@@ -274,6 +384,7 @@ class LauncherGridLayer implements Layer {
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
if (this.moving && event.type === "double-click") { this.back(); return; }
await this.grid.handleInput(event, ctx);
}
@@ -311,9 +422,9 @@ export function createLauncherWindow(options: LauncherOptions): ShellWindow {
// keeps every unrelated setting change from repainting the launcher. The
// launcher is pinned for the app's lifetime, so the subscription never needs
// tearing down.
let lastState = `${getFolderStateFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
let lastState = `${getFolderStateFingerprint()}\n${getLauncherLayoutFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
onAnySettingChanged(() => {
const state = `${getFolderStateFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
const state = `${getFolderStateFingerprint()}\n${getLauncherLayoutFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
if (state === lastState) return;
lastState = state;
created.requestRender();
+51 -11
View File
@@ -1,14 +1,50 @@
/**
* Launcher folder state: which apps are grouped into which named folder.
* Stored as one JSON string (appId -> folder name) in the settings store, so
* it persists and its changes broadcast to every isolate. An unset value means
* the default grouping; any edit persists the whole map, so clearing out the
* defaults sticks. Folders exist only while at least one app is assigned to
* them — there is no separate create/delete step.
*/
/** Launcher assignments keep their legacy format; explicitly created folders may be empty. */
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import { renameLauncherFolderOrder, removeLauncherFolderOrder } from "./launcher-layout";
const STORAGE_KEY = "launcher.folders";
const NAMES_KEY = "launcher.folderNames";
/** Only user-created/renamed folders persist after their last member leaves. */
export function getExplicitFolderNames(): string[] {
try {
const value = JSON.parse(getStringSetting(NAMES_KEY, "[]"));
return Array.isArray(value) ? [...new Set(value.filter((name): name is string =>
typeof name === "string" && !!name.trim()).map(name => name.trim()))] : [];
} catch { return []; }
}
export function folderNameError(input: string, previous?: string): string | null {
const name = input.trim();
if (!name) return "Enter a folder name.";
if (name.length > FOLDER_NAME_MAX_LENGTH) return `Use at most ${FOLDER_NAME_MAX_LENGTH} characters.`;
if (/[\u0000-\u001f\u007f]/.test(name)) return "Use a single-line folder name.";
if (previous !== undefined && !getFolders().has(previous)) return "This folder no longer exists.";
for (const existing of getFolders().keys()) {
if (existing !== previous && existing.toLowerCase() === name.toLowerCase()) return "A folder with this name already exists.";
}
return null;
}
export function createFolder(input: string): boolean {
if (folderNameError(input)) return false;
setStringSetting(NAMES_KEY, JSON.stringify([...getExplicitFolderNames(), input.trim()]));
return true;
}
export function renameFolder(previous: string, input: string): boolean {
if (folderNameError(input, previous)) return false;
const name = input.trim();
if (name === previous) return true;
const assignments = getFolderAssignments();
for (const appId of Object.keys(assignments)) if (assignments[appId] === previous) assignments[appId] = name;
// Preserve position and per-folder order when the visible name changes.
renameLauncherFolderOrder(previous, name);
setStringSetting(NAMES_KEY, JSON.stringify([...getExplicitFolderNames().filter(n => n !== previous), name]));
setStringSetting(STORAGE_KEY, JSON.stringify(assignments));
return true;
}
/** The out-of-the-box grouping, applied only while the setting is unset. */
const DEFAULT_ASSIGNMENTS: Record<string, string> = {
@@ -32,7 +68,7 @@ export function getFolderAssignments(): Record<string, string> {
try {
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
const assignments: Record<string, string> = {};
const assignments: Record<string, string> = Object.create(null);
for (const appId of Object.keys(parsed)) {
const folder = parsed[appId];
if (typeof folder === "string" && folder.trim()) {
@@ -58,6 +94,7 @@ export function getFolders(): Map<string, string[]> {
unsorted.set(folder, [appId]);
}
}
for (const name of getExplicitFolderNames()) if (!unsorted.has(name)) unsorted.set(name, []);
const folders = new Map<string, string[]>();
for (const name of Array.from(unsorted.keys()).sort((a, b) => a.localeCompare(b))) {
folders.set(name, unsorted.get(name)!);
@@ -86,6 +123,8 @@ export function disbandFolder(folder: string): number {
moved++;
}
}
setStringSetting(NAMES_KEY, JSON.stringify(getExplicitFolderNames().filter(name => name !== folder)));
removeLauncherFolderOrder(folder);
if (moved > 0) {
setStringSetting(STORAGE_KEY, JSON.stringify(assignments));
}
@@ -95,7 +134,7 @@ export function disbandFolder(folder: string): number {
/**
* An unused name for a ring-created folder ("New folder", "New folder 2", …).
* Ring input has no text entry, so new folders start with a generated name;
* the assistant's folder tools can regroup the apps under a better one.
* Rename folder uses the existing phone text editor for a custom name.
*/
export function unusedNewFolderName(): string {
const existing = new Set(Array.from(getFolders().keys()).map((name) => name.toLowerCase()));
@@ -119,5 +158,6 @@ export function resolveFolderName(input: string): string {
/** Raw stored value, for cheap change detection by the launcher window. */
export function getFolderStateFingerprint(): string {
return getStringSetting(STORAGE_KEY, "");
return JSON.stringify([getStringSetting(STORAGE_KEY, ""), getStringSetting(NAMES_KEY, ""),
getStringSetting("launcher.folderNameDraft", "")]);
}
+60
View File
@@ -0,0 +1,60 @@
import { getStringSetting, setStringSetting } from "../../native/settings-store";
const ORDER_KEY = "launcher.order";
const scopeKey = (folder: string | null) => folder === null ? "root" : `folder:${folder}`;
function readOrders(): Record<string, string[]> {
try {
const value = JSON.parse(getStringSetting(ORDER_KEY, "{}"));
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
return Object.fromEntries(Object.entries(value).filter(([, order]) => Array.isArray(order))
.map(([scope, order]) => [scope, [...new Set((order as unknown[]).filter((id): id is string => typeof id === "string"))]]));
} catch { return {}; }
}
export function setLauncherOrder(folder: string | null, ids: readonly string[]): void {
const orders = readOrders();
orders[scopeKey(folder)] = [...new Set(ids)];
setStringSetting(ORDER_KEY, JSON.stringify(orders));
}
/** Unseen apps append alphabetically; changing sort modes never destroys saved order. */
export function orderLauncherEntries<T extends { label: string }>(
entries: T[], key: (entry: T) => string, folder: string | null, custom: boolean,
): T[] {
const order = custom ? readOrders()[scopeKey(folder)] ?? [] : [];
const rank = new Map(order.map((id, index) => [id, index]));
return entries.sort((a, b) => (rank.get(key(a)) ?? Infinity) - (rank.get(key(b)) ?? Infinity) ||
a.label.localeCompare(b.label) || key(a).localeCompare(key(b)));
}
/** Move into the target's position, without moving apps across folders. */
export function moveLauncherEntry(folder: string | null, ids: string[], source: string, target: string): boolean {
const from = ids.indexOf(source), to = ids.indexOf(target);
if (from < 0 || to < 0) return false;
const next = ids.slice();
next.splice(from, 1);
next.splice(to, 0, source);
setLauncherOrder(folder, next);
return true;
}
export function renameLauncherFolderOrder(previous: string, next: string): void {
const orders = readOrders();
const oldScope = scopeKey(previous), newScope = scopeKey(next);
if (orders[oldScope]) orders[newScope] = orders[oldScope];
delete orders[oldScope];
if (orders.root) orders.root = orders.root.map(id => id === `folder:${previous}` ? `folder:${next}` : id);
setStringSetting(ORDER_KEY, JSON.stringify(orders));
}
export function removeLauncherFolderOrder(folder: string): void {
const orders = readOrders();
delete orders[scopeKey(folder)];
if (orders.root) orders.root = orders.root.filter(id => id !== `folder:${folder}`);
setStringSetting(ORDER_KEY, JSON.stringify(orders));
}
export function getLauncherLayoutFingerprint(): string {
return JSON.stringify([getStringSetting("launcher.layout", "alphabetical"), getStringSetting(ORDER_KEY, "")]);
}