diff --git a/settings/src/frame/AddPicker.test.tsx b/settings/src/frame/AddPicker.test.tsx new file mode 100644 index 00000000..077c2475 --- /dev/null +++ b/settings/src/frame/AddPicker.test.tsx @@ -0,0 +1,78 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { render } from "solid-js/web"; +import { AddPicker } from "./AddPicker"; + +const options = [ + { id: "comments", name: "Comments" }, + { id: "history", name: "History" }, + { id: "outline", name: "Outline" }, +]; + +let dispose: (() => void) | undefined; +afterEach(() => { + dispose?.(); + document.body.replaceChildren(); +}); + +function mount(list = options) { + const onPick = vi.fn(); + const root = document.createElement("div"); + document.body.append(root); + dispose = render(() => , root); + const menu = root.querySelector(".settings-picker")!; + // happy-dom has no popover api: stand in for it, toggle event and all + let open = false; + const set = (next: boolean) => { + open = next; + menu.dispatchEvent( + Object.assign(new Event("toggle"), { newState: next ? "open" : "closed" }) + ); + }; + menu.togglePopover = () => (set(!open), !open); + menu.hidePopover = () => set(false); + const input = root.querySelector("input")!; + const type = (value: string) => { + input.value = value; + input.dispatchEvent(new Event("input", { bubbles: true })); + }; + const key = (key: string) => + input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true })); + const items = () => + [...root.querySelectorAll(".settings-picker-item")].map((el) => + el.textContent?.trim() + ); + root.querySelector(".settings-button")!.click(); + return { onPick, type, key, items, isOpen: () => open }; +} + +describe("AddPicker", () => { + it("filters what's offered by what's typed, and enter adds the highlighted one", () => { + const { onPick, type, key, items, isOpen } = mount(); + expect(isOpen()).toBe(true); + expect(items()).toEqual(["Comments", "History", "Outline"]); + type("o"); + expect(items()).toEqual(["Comments", "History", "Outline"]); + type("out"); + expect(items()).toEqual(["Outline"]); + type(""); + key("ArrowDown"); + key("Enter"); + expect(onPick).toHaveBeenCalledWith("history"); + expect(isOpen()).toBe(false); + }); + + it("adds what was typed as a tool id when nothing matches", () => { + const { onPick, type, key, items } = mount(); + type(" my-tool "); + expect(items()).toEqual(["Add my-tool"]); + key("Enter"); + expect(onPick).toHaveBeenCalledWith("my-tool"); + }); + + it("says when there's nothing left to add", () => { + mount([]); + expect( + document.querySelector(".settings-picker-empty")?.textContent + ).toMatch(/already here/); + }); +}); diff --git a/settings/src/frame/AddPicker.tsx b/settings/src/frame/AddPicker.tsx new file mode 100644 index 00000000..ce7e0045 --- /dev/null +++ b/settings/src/frame/AddPicker.tsx @@ -0,0 +1,135 @@ +import { createMemo, createSignal, For, Show } from "solid-js"; +import { filterOptions, type LaneItem } from "./lanes"; +import { placePopover } from "./place"; + +// "Add…", and a search over `options` that pops out of it, like the title +// bar's "Open with…". type to filter, arrows to move, enter to add. enter on +// something that matches nothing adds what you typed, as a tool id +export function AddPicker(props: { + options: LaneItem[]; + onPick: (id: string) => void; +}) { + let button!: HTMLButtonElement; + let menu!: HTMLDivElement; + let input!: HTMLInputElement; + let list!: HTMLDivElement; + const [open, setOpen] = createSignal(false); + const [query, setQuery] = createSignal(""); + const [highlighted, setHighlighted] = createSignal(0); + const matches = createMemo(() => filterOptions(props.options, query())); + const typed = () => query().trim(); + + function pick(id: string) { + menu.hidePopover(); + props.onPick(id); + } + + function highlight(index: number) { + setHighlighted(index); + list.children[index]?.scrollIntoView({ block: "nearest" }); + } + + function place() { + placePopover(menu, button, { width: 220 }); + } + + return ( + <> + +
{ + setOpen(event.newState === "open"); + if (event.newState === "open") input.focus(); + }} + > + { + setQuery(event.currentTarget.value); + setHighlighted(0); + }} + onKeyDown={(event) => { + const count = matches().length; + if (event.key === "ArrowDown") { + event.preventDefault(); + highlight(Math.min(highlighted() + 1, count - 1)); + } else if (event.key === "ArrowUp") { + event.preventDefault(); + highlight(Math.max(highlighted() - 1, 0)); + } else if (event.key === "Enter") { + event.preventDefault(); + const match = matches()[highlighted()]; + if (match) pick(match.id); + else if (typed()) pick(typed()); + } + }} + /> +
+ + {(option, index) => ( + + )} + + + + {props.options.length + ? "Nothing matches" + : "Everything's already here. Type a tool id to add another."} +

+ } + > + +
+
+
+
+ + ); +} diff --git a/settings/src/frame/Frame.tsx b/settings/src/frame/Frame.tsx index d28112c1..fce89b75 100644 --- a/settings/src/frame/Frame.tsx +++ b/settings/src/frame/Frame.tsx @@ -1,15 +1,22 @@ -// what used to be the frame configurator: which frame the studio is, and -// which tools sit in a document's title bar. the frame's on the account doc -// (`frameToolId`); the title bar's in threepane's config doc -// (`account.tools.threepane`), as frame-configurator kept them +// what used to be the frame configurator: which frame the studio is, which +// tools sit in a document's title bar, and which tabs the context sidebar +// has. the frame's on the account doc (`frameToolId`); the title bar and the +// context sidebar are in threepane's config doc (`account.tools.threepane`) import { createMemo, createSignal, For, onCleanup, Show } from "solid-js"; import type { DocHandle } from "@automerge/automerge-repo/slim"; import { getRegistry } from "@inkandswitch/patchwork-plugins"; import { useDocument } from "solid-automerge"; import type { AccountDoc } from "../you/contact"; +import { AddPicker } from "./AddPicker"; +import { ItemMenu } from "./ItemMenu"; +import { + contextLane, + editContext, + editTitlebar, + slotId, + type ThreepaneConfigDoc, +} from "./lanes"; -type ToolSlot = [toolId: string, docId: string] | string; -type ThreepaneConfigDoc = { doctitle?: { tools?: ToolSlot[] } }; type Describable = { id: string; name?: string; @@ -32,14 +39,21 @@ function useRegistry(type: string) { return tools; } -const tagged = (tools: Describable[], tag: string): Option[] => +// `unlisted` ones too, for the context sidebar and the title bar, which show +// every tagged tool whether it's listed or not (every titlebar tool is +// unlisted, so it stays out of "Open with") +const tagged = ( + tools: Describable[], + tag: string, + { unlisted = false } = {} +): Option[] => tools - .filter((tool) => !tool.unlisted && (tool.tags ?? []).includes(tag)) + .filter( + (tool) => (unlisted || !tool.unlisted) && (tool.tags ?? []).includes(tag) + ) .map((tool) => ({ id: tool.id, name: tool.name || tool.id })) .sort((a, b) => a.name.localeCompare(b.name)); -const slotId = (slot: ToolSlot) => (typeof slot === "string" ? slot : slot[0]); - // the frame this page is in: the nearest patchwork-view around it that's one // of the frames. an account that's never chosen has no frameToolId, but it's // still in one @@ -77,12 +91,47 @@ export function Frame(props: { const frames = createMemo(() => tagged(tools(), "frame-tool")); const current = () => props.account()?.frameToolId ?? runningFrame(props.element, frames()); - const titlebar = createMemo(() => tagged(tools(), "titlebar-tool")); + const nameOf = (id: string) => names().get(id) ?? id; const [threepane, threepaneHandle] = useDocument( () => props.account()?.tools?.threepane ); - const doctitle = () => threepane()?.doctitle?.tools?.map(slotId); + + const titlebarItems = createMemo(() => { + const hidden = new Set((threepane()?.doctitle?.hidden ?? []).map(String)); + return (threepane()?.doctitle?.tools ?? []).map(slotId).map((id) => ({ + id, + name: nameOf(id), + hidden: hidden.has(id), + })); + }); + const titlebarOptions = createMemo(() => { + const present = new Set(titlebarItems().map((item) => item.id)); + return tagged(tools(), "titlebar-tool", { unlisted: true }).filter( + (option) => !present.has(option.id) + ); + }); + + // every component tagged "context-tool", with the person's edits on top. + // what's left to add is the tagged ones they took out + const contextTagged = createMemo(() => + tagged(components(), "context-tool", { unlisted: true }) + ); + const contextItems = createMemo(() => { + const config = threepane()?.context; + const hidden = new Set((config?.hidden ?? []).map(String)); + // in bar order, the hidden ones where they'd be if they weren't + const { shown } = contextLane( + contextTagged(), + { added: config?.added, removed: config?.removed }, + nameOf + ); + return shown.map((item) => ({ ...item, hidden: hidden.has(item.id) })); + }); + const contextOptions = createMemo(() => { + const present = new Set(contextItems().map((item) => item.id)); + return contextTagged().filter((option) => !present.has(option.id)); + }); function chooseFrame(id: string) { if (current() === id) return; @@ -129,55 +178,94 @@ export function Frame(props: { {(handle) => ( -
-

Title bar

-
-
- - handle().change((doc) => { - doc.doctitle ??= {}; - doc.doctitle.tools = next.slice(); - }) - } - /> + <> +
+

Title bar

+
+
+ + handle().change((doc) => + editTitlebar(doc, { action: "add", id }) + ) + } + onRemove={(id) => + handle().change((doc) => + editTitlebar(doc, { action: "remove", id }) + ) + } + onHidden={(id, hidden) => + handle().change((doc) => + editTitlebar(doc, { + action: hidden ? "hide" : "show", + id, + }) + ) + } + onMove={(from, to) => + handle().change((doc) => + editTitlebar(doc, { action: "move", from, to }) + ) + } + /> +
-
-
+ + +
+

Context sidebar

+
+
+ + handle().change((doc) => editContext(doc, "add", id)) + } + onRemove={(id) => + handle().change((doc) => editContext(doc, "remove", id)) + } + onHidden={(id, hidden) => + handle().change((doc) => + editContext(doc, hidden ? "hide" : "show", id) + ) + } + /> +
+
+
+ )}
); } -// an ordered row of tool ids: drag to reorder, × to take one out, + to add. +type StripItem = Option & { hidden?: boolean }; + +// a row of tools: each one's × has a menu to hide it (still there, just not +// shown) or take it out, and "Add…" puts one in. drag to reorder, when the lane has an order to keep. // ids are kept as they are, even ones whose plugin hasn't registered yet // (they're shown by id), so a slow plugin isn't dropped by a rewrite function Strip(props: { - values: string[]; + items: StripItem[]; options: Option[]; - names: Map; - setValues: (next: string[]) => void; + onAdd: (id: string) => void; + onRemove: (id: string) => void; + onHidden: (id: string, hidden: boolean) => void; + onMove?: (from: number, to: number) => void; }) { - const [adding, setAdding] = createSignal(false); - const [custom, setCustom] = createSignal(""); const [from, setFrom] = createSignal(null); const [to, setTo] = createSignal(null); - const nameOf = (id: string) => props.names.get(id) ?? id; - const available = createMemo(() => - props.options.filter((option) => !props.values.includes(option.id)) - ); - - const add = (id: string) => { - const clean = id.trim(); - if (clean && !props.values.includes(clean)) - props.setValues([...props.values, clean]); - }; - // `dropped` is false when the drag was called off: Escape, or let go // somewhere that isn't the strip. Then nothing moves. function drop(dropped: boolean) { @@ -186,10 +274,7 @@ function Strip(props: { setFrom(null); setTo(null); if (!dropped || a == null || b == null || a === b) return; - const next = props.values.slice(); - const [moved] = next.splice(a, 1); - next.splice(b, 0, moved); - props.setValues(next); + props.onMove?.(a, b); } return ( @@ -202,21 +287,25 @@ function Strip(props: { if (from() !== null) event.preventDefault(); }} > - - {(id, index) => ( + + {(item, index) => (
  • { + if (!props.onMove) return; event.dataTransfer!.effectAllowed = "move"; setFrom(index()); setTo(index()); }} onDragOver={(event) => { + if (from() === null) return; event.preventDefault(); event.dataTransfer!.dropEffect = "move"; setTo(index()); @@ -225,82 +314,18 @@ function Strip(props: { drop(event.dataTransfer?.dropEffect !== "none") } > - {nameOf(id)} - + {item.name} +
  • )}
    - setAdding(true)} - > - Add… - - } - > -
    event.key === "Escape" && setAdding(false)} - > - - {(option) => ( - - )} - -
    { - event.preventDefault(); - add(custom()); - setCustom(""); - }} - > - setCustom(event.currentTarget.value)} - /> - - -
    -
    -
    + ); } diff --git a/settings/src/frame/ItemMenu.tsx b/settings/src/frame/ItemMenu.tsx new file mode 100644 index 00000000..b8fed07a --- /dev/null +++ b/settings/src/frame/ItemMenu.tsx @@ -0,0 +1,78 @@ +import { createSignal } from "solid-js"; +import { placePopover } from "./place"; + +// a strip item's ×: a little menu off it, to hide (or show) the tool or take +// it out. arrows move between the two, Escape closes it +export function ItemMenu(props: { + name: string; + hidden?: boolean; + onHidden: (hidden: boolean) => void; + onRemove: () => void; +}) { + let button!: HTMLButtonElement; + let menu!: HTMLDivElement; + const [open, setOpen] = createSignal(false); + + function choose(fn: () => void) { + menu.hidePopover(); + fn(); + } + + return ( + <> + + + + ); +} diff --git a/settings/src/frame/lanes.test.ts b/settings/src/frame/lanes.test.ts new file mode 100644 index 00000000..dcfb972f --- /dev/null +++ b/settings/src/frame/lanes.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from "vitest"; +import * as Automerge from "@automerge/automerge"; +import { + contextLane, + editContext, + editTitlebar, + filterOptions, + slotId, + type ThreepaneConfigDoc, +} from "./lanes"; + +const tagged = [ + { id: "comments", name: "Comments" }, + { id: "history", name: "History" }, +]; + +describe("contextLane", () => { + it("is the tagged components when nothing's been edited", () => { + expect(contextLane(tagged, undefined)).toEqual({ + shown: tagged, + hidden: [], + }); + }); + + it("drops removed ones, puts added ones after, and splits out hidden", () => { + const lane = contextLane( + tagged, + { + removed: ["history"], + added: ["outline", "comments"], + hidden: ["comments"], + }, + (id) => id.toUpperCase() + ); + expect(lane.shown).toEqual([{ id: "outline", name: "OUTLINE" }]); + expect(lane.hidden).toEqual([{ id: "comments", name: "Comments" }]); + }); +}); + +describe("editContext", () => { + it("removing then adding brings a tab back, unhidden", () => { + const doc: ThreepaneConfigDoc = {}; + editContext(doc, "hide", "history"); + editContext(doc, "remove", "history"); + expect(contextLane(tagged, doc.context).shown.map((i) => i.id)).toEqual([ + "comments", + ]); + editContext(doc, "add", "history"); + expect(contextLane(tagged, doc.context)).toEqual({ + shown: tagged, + hidden: [], + }); + }); + + it("hide and show don't add anything twice", () => { + const doc: ThreepaneConfigDoc = {}; + editContext(doc, "hide", "comments"); + editContext(doc, "hide", "comments"); + expect(doc.context?.hidden).toEqual(["comments"]); + editContext(doc, "show", "comments"); + expect(doc.context?.hidden).toEqual([]); + }); +}); + +describe("editTitlebar", () => { + it("adds once, removes every copy, and forgets a removed one was hidden", () => { + const doc: ThreepaneConfigDoc = { doctitle: { tools: ["a"] } }; + editTitlebar(doc, { action: "add", id: " b " }); + editTitlebar(doc, { action: "add", id: "b" }); + editTitlebar(doc, { action: "hide", id: "b" }); + expect(doc.doctitle).toEqual({ tools: ["a", "b"], hidden: ["b"] }); + editTitlebar(doc, { action: "remove", id: "b" }); + expect(doc.doctitle).toEqual({ tools: ["a"], hidden: [] }); + }); + + it("moves a pinned slot in a real doc and keeps it a pin", () => { + let doc = Automerge.from({ + doctitle: { tools: ["a", ["pinned", "automerge:xyz"], "c"] }, + }); + doc = Automerge.change(doc, (d) => + editTitlebar(d, { action: "move", from: 1, to: 0 }) + ); + expect(doc.doctitle?.tools).toEqual([ + ["pinned", "automerge:xyz"], + "a", + "c", + ]); + doc = Automerge.change(doc, (d) => + editTitlebar(d, { action: "move", from: 0, to: 2 }) + ); + expect(doc.doctitle?.tools).toEqual([ + "a", + "c", + ["pinned", "automerge:xyz"], + ]); + }); +}); + +describe("editTitlebar with immutable string slots", () => { + it("removes, hides and moves a slot automerge hands back as an object", () => { + let doc = Automerge.from({ + doctitle: { + tools: [ + new Automerge.ImmutableString("open-with") as unknown as string, + "branches", + ], + }, + }); + const first = doc.doctitle!.tools![0]; + expect(typeof first).not.toBe("string"); + expect(slotId(first)).toBe("open-with"); + + doc = Automerge.change(doc, (d) => + editTitlebar(d, { action: "move", from: 0, to: 1 }) + ); + expect(doc.doctitle?.tools?.map(slotId)).toEqual(["branches", "open-with"]); + + doc = Automerge.change(doc, (d) => + editTitlebar(d, { action: "remove", id: "open-with" }) + ); + expect(doc.doctitle?.tools?.map(slotId)).toEqual(["branches"]); + }); +}); + +describe("filterOptions", () => { + it("matches name or id, ignoring case", () => { + const options = [ + { id: "doc-openwith", name: "Open With" }, + { id: "branches", name: "Branch picker" }, + ]; + expect(filterOptions(options, "OPEN").map((o) => o.id)).toEqual([ + "doc-openwith", + ]); + expect(filterOptions(options, "branches").map((o) => o.id)).toEqual([ + "branches", + ]); + expect(filterOptions(options, " ")).toBe(options); + }); +}); diff --git a/settings/src/frame/lanes.ts b/settings/src/frame/lanes.ts new file mode 100644 index 00000000..e7838ada --- /dev/null +++ b/settings/src/frame/lanes.ts @@ -0,0 +1,165 @@ +// the shape of threepane's config doc, as much of it as settings edits, and +// the rules for its lanes. these are threepane's (threepane/src/layoutEdits.ts) +// copied, not imported: a package doesn't reach into another one's source + +export type ToolSlot = [toolId: string, docId: string] | string; + +/** + * the context tabs are every `patchwork:component` tagged "context-tool"; + * this is the person's edits on top of that, as component ids. `added`: + * untagged ones added by hand, in order, after the tagged ones. `removed`: + * tagged ones taken out. `hidden`: still in the list, but not shown + */ +export type ContextLaneConfig = { + added?: string[]; + removed?: string[]; + hidden?: string[]; +}; + +export type ThreepaneConfigDoc = { + doctitle?: { tools?: ToolSlot[]; hidden?: string[] }; + context?: ContextLaneConfig; +}; + +export type LaneItem = { id: string; name: string }; + +// a string slot can come back from automerge as an object (a RawString), so +// it's the tuples that get told apart, not the strings +export const slotId = (slot: ToolSlot) => + Array.isArray(slot) ? String(slot[0]) : String(slot); + +function drop(list: string[] | undefined, id: string) { + if (!list) return; + for (let i = list.length - 1; i >= 0; i--) { + if (String(list[i]) === id) list.splice(i, 1); + } +} + +function include(list: string[], id: string) { + if (!list.some((existing) => String(existing) === id)) list.push(id); +} + +/** + * the context tabs in bar order: tagged first (in the order given), then the + * hand-added ones in the order they were added. `name` names an added id + * that isn't one of the tagged components + */ +export function contextLane( + tagged: LaneItem[], + config: ContextLaneConfig | undefined, + name: (id: string) => string = (id) => id +): { shown: LaneItem[]; hidden: LaneItem[] } { + const removed = new Set((config?.removed ?? []).map(String)); + const hidden = new Set((config?.hidden ?? []).map(String)); + const seen = new Set(); + const all: LaneItem[] = []; + for (const item of tagged) { + if (removed.has(item.id) || seen.has(item.id)) continue; + seen.add(item.id); + all.push(item); + } + for (const raw of config?.added ?? []) { + const id = String(raw); + if (removed.has(id) || seen.has(id)) continue; + seen.add(id); + all.push({ id, name: name(id) }); + } + return { + shown: all.filter((item) => !hidden.has(item.id)), + hidden: all.filter((item) => hidden.has(item.id)), + }; +} + +export type ContextEdit = "add" | "remove" | "hide" | "show"; + +/** one edit to the context tabs, inside a `change` */ +export function editContext( + doc: ThreepaneConfigDoc, + action: ContextEdit, + id: string +) { + if (!id) return; + doc.context ??= {}; + const lane = doc.context; + switch (action) { + case "add": + drop(lane.removed, id); + drop(lane.hidden, id); + lane.added ??= []; + include(lane.added, id); + return; + case "remove": + drop(lane.added, id); + drop(lane.hidden, id); + lane.removed ??= []; + include(lane.removed, id); + return; + case "hide": + lane.hidden ??= []; + include(lane.hidden, id); + return; + case "show": + drop(lane.hidden, id); + return; + } +} + +export type TitlebarEdit = + | { action: "add" | "remove" | "hide" | "show"; id: string } + | { action: "move"; from: number; to: number }; + +/** + * one edit to the title bar's tools, inside a `change`. a slot keeps its + * shape when it moves: a `[toolId, docId]` pin stays a pin + */ +export function editTitlebar(doc: ThreepaneConfigDoc, edit: TitlebarEdit) { + doc.doctitle ??= {}; + const doctitle = doc.doctitle; + doctitle.tools ??= []; + const tools = doctitle.tools; + + if (edit.action === "move") { + const { from, to } = edit; + if (from === to || !tools[from] || to < 0 || to >= tools.length) return; + const slot = tools[from]; + const copy: ToolSlot = Array.isArray(slot) + ? [String(slot[0]), String(slot[1])] + : String(slot); + tools.splice(from, 1); + tools.splice(to, 0, copy); + return; + } + + const id = edit.id.trim(); + if (!id) return; + switch (edit.action) { + case "add": + if (!tools.some((slot) => slotId(slot) === id)) tools.push(id); + drop(doctitle.hidden, id); + return; + case "remove": + for (let i = tools.length - 1; i >= 0; i--) { + if (slotId(tools[i]) === id) tools.splice(i, 1); + } + drop(doctitle.hidden, id); + return; + case "hide": + doctitle.hidden ??= []; + include(doctitle.hidden, id); + return; + case "show": + drop(doctitle.hidden, id); + return; + } +} + +/** options whose name or id has `query` in it, case-insensitively */ +export function filterOptions(options: T[], query: string) { + const q = query.trim().toLowerCase(); + if (!q) return options; + return options.filter( + (option) => + option.name.toLowerCase().includes(q) || + option.id.toLowerCase().includes(q) + ); +} diff --git a/settings/src/frame/place.ts b/settings/src/frame/place.ts new file mode 100644 index 00000000..ffdc330b --- /dev/null +++ b/settings/src/frame/place.ts @@ -0,0 +1,37 @@ +// put a popover next to the button that opens it: under it, or over it when +// there's more room there and not enough under, and no taller than the room +// it gets. lined up with the button's left edge, or its right edge when that +// would run off the page +export function placePopover( + menu: HTMLElement, + button: HTMLElement, + { width = 0, height = 260 } = {} +) { + const rect = button.getBoundingClientRect(); + const w = Math.max(rect.width, width); + const gap = 2; + const margin = 8; + const below = window.innerHeight - rect.bottom - gap - margin; + const above = rect.top - gap - margin; + const up = below < height && above > below; + + if (up) { + menu.style.top = ""; + menu.style.bottom = `${window.innerHeight - rect.top + gap}px`; + } else { + menu.style.bottom = ""; + menu.style.top = `${rect.bottom + gap}px`; + } + menu.style.maxHeight = `${Math.max(0, up ? above : below)}px`; + menu.style.minWidth = `${w}px`; + + const right = rect.left + w > window.innerWidth - margin; + if (right) { + menu.style.left = ""; + menu.style.right = `${window.innerWidth - rect.right}px`; + } else { + menu.style.right = ""; + menu.style.left = `${rect.left}px`; + } + menu.style.transformOrigin = `${up ? "bottom" : "top"} ${right ? "right" : "left"}`; +} diff --git a/settings/src/styles.css b/settings/src/styles.css index 05d808a4..4f6df1e1 100644 --- a/settings/src/styles.css +++ b/settings/src/styles.css @@ -1020,7 +1020,17 @@ } } -.settings-strip-remove { +.settings-strip-item { + &[data-fixed] { + cursor: default; + } + &[data-hidden] .settings-strip-name { + color: var(--settings-muted); + text-decoration: line-through; + } +} + +.settings-strip-icon { display: grid; place-items: center; width: 16px; @@ -1036,16 +1046,143 @@ @media (hover: hover) and (pointer: fine) { &:hover { background: var(--settings-hover); - color: var(--settings-danger); + color: var(--settings-fg); } } + &[data-open] { + background: var(--settings-hover); + color: var(--settings-fg); + } +} + +.settings-button[data-open] { + background: var(--settings-hover); + box-shadow: none; } -.settings-strip-add { +/* "Add…"'s search, like the title bar's "Open with…" */ +.settings-picker[popover] { + position: fixed; + inset: unset; + margin: 0; + padding: 0; + border: var(--studio-border-width, 1px) solid var(--settings-rule); + border-radius: var(--studio-radius-sm, 4px); + background: var(--settings-fill); + box-shadow: var(--studio-shadow-sm, 0 2px 8px rgb(0 0 0 / 8%)); + color: var(--settings-fg); + font: 400 13px/1.4 var(--settings-family); + overflow: hidden; + /* grows out of the button; closing is instant */ + transition: + opacity var(--settings-quick) var(--settings-ease-out), + scale var(--settings-quick) var(--settings-ease-out); +} + +/* a column, so the list is what gives when it's capped to the room on + screen (placePopover sets its max-height) */ +.settings-picker[popover]:popover-open { display: flex; - flex-wrap: wrap; - align-items: center; - gap: 6px; + flex-direction: column; +} + +@starting-style { + .settings-picker[popover]:popover-open, + .settings-menu[popover]:popover-open { + opacity: 0; + scale: 0.97; + } +} + +/* a strip item's ×: Hide / Remove */ +.settings-menu[popover] { + position: fixed; + inset: unset; + margin: 0; + padding: 4px; + border: var(--studio-border-width, 1px) solid var(--settings-rule); + border-radius: var(--studio-radius-sm, 4px); + background: var(--settings-fill); + box-shadow: var(--studio-shadow-sm, 0 2px 8px rgb(0 0 0 / 8%)); + color: var(--settings-fg); + font: 400 13px/1.4 var(--settings-family); + transition: + opacity var(--settings-quick) var(--settings-ease-out), + scale var(--settings-quick) var(--settings-ease-out); +} + +.settings-menu-item { + display: block; + box-sizing: border-box; + width: 100%; + padding: 4px 8px; + border: none; + border-radius: var(--studio-radius-xs, 2px); + background: none; + color: inherit; + font: inherit; + text-align: left; + white-space: nowrap; + cursor: var(--studio-cursor-pointer, pointer); + + &:focus-visible { + outline: none; + } + &:focus-visible, + &:hover { + background: var(--settings-hover); + } + &[data-danger] { + color: var(--settings-danger); + } +} + +.settings-picker-input { + display: block; + flex: none; + box-sizing: border-box; + width: 100%; + padding: 6px 8px; + border: none; + border-bottom: var(--studio-border-width, 1px) solid var(--settings-rule); + background: none; + color: inherit; + font: inherit; + outline: none; +} + +.settings-picker-list { + min-height: 0; + max-height: 220px; + overflow-y: auto; + padding: 4px; +} + +.settings-picker-item { + display: flex; + align-items: baseline; + gap: 4px; + box-sizing: border-box; + width: 100%; + padding: 4px 8px; + border: none; + border-radius: var(--studio-radius-xs, 2px); + background: none; + color: inherit; + font: inherit; + text-align: left; + white-space: nowrap; + cursor: var(--studio-cursor-pointer, pointer); + + &[data-highlight] { + background: var(--settings-hover); + } +} + +.settings-picker-empty { + margin: 0; + padding: 4px 8px; + color: var(--settings-muted); } /* ── contributed ───────────────────────────────────────────────────── */ diff --git a/threepane/src/PatchworkFrame.tsx b/threepane/src/PatchworkFrame.tsx index 3375ad76..1c4f1c89 100644 --- a/threepane/src/PatchworkFrame.tsx +++ b/threepane/src/PatchworkFrame.tsx @@ -43,6 +43,7 @@ import type { ToolImplementation } from "@inkandswitch/patchwork-plugins"; import { ensureThreepaneConfig } from "./account/ensureThreepaneConfig"; import { seedExampleDocuments } from "./account/seedExampleDocuments"; import { handleAddToSidebar } from "./account/addToSidebar"; +import { handleLayoutEdits } from "./layoutEdits"; import { ensureFrameStyles } from "./ensureFrameStyles"; import { useHandleDoc } from "./hooks/useHandleDoc"; import { CALL_PROVIDER } from "./datatypes"; @@ -237,6 +238,8 @@ function PatchworkFrameInner(props: { // to render each. `tray` is the system tray's explicit ordered list of tools, // rendered by the one stable host-owned instance below. const doctitleSlots = () => threepaneConfig()?.doctitle?.tools; + const doctitleHidden = () => threepaneConfig()?.doctitle?.hidden; + const contextLane = () => threepaneConfig()?.context; const sidebarWidgets = (): ToolSlot[] => threepaneConfig()?.sidebar?.widgets ?? []; const traySlots = (): ToolSlot[] => threepaneConfig()?.tray ?? []; @@ -282,6 +285,10 @@ function PatchworkFrameInner(props: { onCleanup(unsubscribeSelectedView); onCleanup(handleAddToSidebar(element, props.repo, props.handle)); + // The tab bar's and top bar's add / remove / hide / show. + onCleanup( + handleLayoutEdits(element, (fn) => threepaneConfigHandle()?.change(fn)) + ); }); const selectedDocUrl = () => selectedView()?.url; @@ -368,6 +375,8 @@ function PatchworkFrameInner(props: { selectedDocUrl={selectedDocUrl} selectedToolId={selectedToolId} doctitleSlots={doctitleSlots} + doctitleHidden={doctitleHidden} + contextLane={contextLane} isLeftCollapsed={sidebarState.isSidebarCollapsed} initialRightWidth={initialRightWidth} initialRightCollapsed={initialRightCollapsed} @@ -381,6 +390,8 @@ function PatchworkFrameInner(props: { selectedDocUrl={selectedDocUrl} selectedToolId={selectedToolId} doctitleSlots={doctitleSlots} + doctitleHidden={doctitleHidden} + contextLane={contextLane} isLeftCollapsed={sidebarState.isSidebarCollapsed} initialRightWidth={initialRightWidth} initialRightCollapsed={initialRightCollapsed} diff --git a/threepane/src/components/ContextMenu.tsx b/threepane/src/components/ContextMenu.tsx new file mode 100644 index 00000000..84535a22 --- /dev/null +++ b/threepane/src/components/ContextMenu.tsx @@ -0,0 +1,117 @@ +import { For, Match, onCleanup, onMount, Switch } from "solid-js"; +import { Portal } from "solid-js/web"; + +export type MenuEntry = + | { label: string; onSelect: () => void } + | { heading: string } + | "separator"; + +export type MenuAt = { x: number; y: number }; + +/** + * A right-click menu at a point, portalled to the body so no scroll container + * clips it. Closes on a pick, a click outside, Escape, or the window losing + * focus; arrow keys move between items. + */ +export function ContextMenu(props: { + at: MenuAt; + label: string; + entries: MenuEntry[]; + onClose: () => void; +}) { + let menu!: HTMLDivElement; + + onMount(() => { + // Kept on screen: flipped back from the right and bottom edges once its + // size is known. + const rect = menu.getBoundingClientRect(); + menu.style.left = `${Math.max(4, Math.min(props.at.x, innerWidth - rect.width - 4))}px`; + menu.style.top = `${Math.max(4, Math.min(props.at.y, innerHeight - rect.height - 4))}px`; + menu.querySelector('[role="menuitem"]')?.focus(); + + const onPointerDown = (event: PointerEvent) => { + if (!menu.contains(event.target as Node)) props.onClose(); + }; + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") props.onClose(); + }; + const onBlur = () => props.onClose(); + document.addEventListener("pointerdown", onPointerDown, true); + document.addEventListener("keydown", onKeyDown); + window.addEventListener("blur", onBlur); + onCleanup(() => { + document.removeEventListener("pointerdown", onPointerDown, true); + document.removeEventListener("keydown", onKeyDown); + window.removeEventListener("blur", onBlur); + }); + }); + + return ( + + + + ); +} + +/** Copy `text`, quietly: a refused clipboard isn't worth an error. */ +export function copyText(text: string) { + navigator.clipboard?.writeText(text).catch((error) => { + console.warn("threepane: couldn't copy", error); + }); +} diff --git a/threepane/src/components/ContextSidebar.tsx b/threepane/src/components/ContextSidebar.tsx index 3be032f2..7fdd180a 100644 --- a/threepane/src/components/ContextSidebar.tsx +++ b/threepane/src/components/ContextSidebar.tsx @@ -1,6 +1,7 @@ import { Show } from "solid-js"; import type { Accessor } from "solid-js"; -import { useTaggedComponents } from "../hooks"; +import type { ContextLaneConfig } from "../types"; +import { useContextLane } from "../hooks/useContextLane"; import { Sidebar } from "./Sidebar"; import { ContextTabs } from "./ContextTabs"; @@ -11,6 +12,8 @@ type ContextSidebarProps = { */ selectedToolId: Accessor; setSelectedToolId: (id: string) => void; + /** The person's edits to the tab list, from the threepane config doc. */ + config: Accessor; isCollapsed: Accessor; width: Accessor; onMouseDown: (e: MouseEvent) => void; @@ -25,12 +28,13 @@ type ContextSidebarProps = { * (the tabs that select the active tool, plus a collapse button), and the * active context tool's content. * - * The tab list is every `patchwork:component` tagged `"context-tool"` — - * registry-driven, not configured — so it's always rendered as a bare - * component with no document. + * The tab list is every `patchwork:component` tagged `"context-tool"`, with + * the person's adds, removes and hides from the config doc applied (see + * `useContextLane`). Each is rendered as a bare component with no document. */ export function ContextSidebar(props: ContextSidebarProps) { - const items = useTaggedComponents("context-tool"); + const lane = useContextLane(props.config); + const items = lane.shown; // The selection may name a tool that isn't in the current list (or be unset); // fall back to the first tab so there's always a valid active tool. @@ -51,26 +55,26 @@ export function ContextSidebar(props: ContextSidebarProps) { >
    {/* Tab header: selects the active tool, with a collapse button at the - end. Only when there are tabs — a tray-only sidebar has no header - and is collapsed via the resize handle. */} - -
    - - -
    -
    + end. There even with every tab hidden or removed, so its "+" and + right-click menu can bring them back. */} +
    +
    {/* `Sidebar` unmounts all of this once it has finished closing. */}
    diff --git a/threepane/src/components/ContextTabs.tsx b/threepane/src/components/ContextTabs.tsx index 1b95d336..de42f8ff 100644 --- a/threepane/src/components/ContextTabs.tsx +++ b/threepane/src/components/ContextTabs.tsx @@ -1,40 +1,171 @@ -import { For } from "solid-js"; +import { createSignal, For, Show } from "solid-js"; import type { Accessor } from "solid-js"; -import type { TaggedComponent } from "../hooks"; +import { dispatchLayoutEdit, type LaneItem } from "../layoutEdits"; +import { ContextMenu, copyText, type MenuAt, type MenuEntry } from "./ContextMenu"; +import { ToolPicker } from "./ToolPicker"; type ContextTabsProps = { - items: Accessor; + /** The tabs in the bar, and the ones hidden from it. */ + items: Accessor; + hidden: Accessor; + /** What the "+" offers. */ + addable: Accessor; selectedToolId: Accessor; setSelectedToolId: (id: string) => void; }; /** - * The context sidebar's tab bar, lifted out of the sidebar and into the top - * toolbar (it sits above the right sidebar). Horizontally scrollable when the - * tabs overflow. Selection is owned by the frame so it survives branch switches. + * The context sidebar's tab bar. Horizontally scrollable when the tabs + * overflow, with a "+" at the very end to add a tab. Selection is owned by the + * frame so it survives branch switches. + * + * Right-click a tab to copy its id, hide it or remove it; right-click anywhere + * on the bar to add a tab or show a hidden one again. Edits are sent up as + * `threepane:edit-layout` events for the frame to write to its config doc. */ export function ContextTabs(props: ContextTabsProps) { + let tablist!: HTMLDivElement; + const [menu, setMenu] = createSignal<{ at: MenuAt; entries: MenuEntry[] }>(); + const [picker, setPicker] = createSignal(); + const activeToolId = () => { const ids = props.items().map((item) => item.id); const selected = props.selectedToolId(); return selected && ids.includes(selected) ? selected : ids[0]; }; + function onContextMenu(event: MouseEvent) { + const tab = (event.target as Element).closest("[data-tool-id]"); + const id = tab?.dataset.toolId; + const entries: MenuEntry[] = []; + if (id) { + entries.push( + { label: "Copy tool id", onSelect: () => copyText(id) }, + { + label: "Hide", + onSelect: () => + dispatchLayoutEdit(tablist, { lane: "context", action: "hide", id }), + }, + { + label: "Remove", + onSelect: () => + dispatchLayoutEdit(tablist, { lane: "context", action: "remove", id }), + } + ); + } + if (entries.length) entries.push("separator"); + const at = { x: event.clientX, y: event.clientY }; + entries.push({ + label: "Add tab…", + onSelect: () => setPicker(new DOMRect(at.x, at.y, 0, 0)), + }); + const hidden = props.hidden(); + if (hidden.length) { + entries.push("separator"); + entries.push({ heading: "Hidden" }); + for (const item of hidden) { + entries.push({ + label: `Show ${item.name}`, + onSelect: () => { + dispatchLayoutEdit(tablist, { + lane: "context", + action: "show", + id: item.id, + }); + props.setSelectedToolId(item.id); + }, + }); + } + } + event.preventDefault(); + setMenu({ at, entries }); + } + + function add(id: string) { + dispatchLayoutEdit(tablist, { lane: "context", action: "add", id }); + props.setSelectedToolId(id); + } + return ( -
    +
    {(item) => ( )} + {/* last in the scrolling list, so it's there once you reach the end */} + + + + {(open) => ( + setMenu(undefined)} + /> + )} + + + {(anchor) => ( + setPicker(undefined)} + /> + )} +
    ); } + +// lucide `plus` +function PlusIcon() { + return ( + + + + + ); +} diff --git a/threepane/src/components/DocumentAreaRoot.tsx b/threepane/src/components/DocumentAreaRoot.tsx index 3fc2fe4e..eed773f1 100644 --- a/threepane/src/components/DocumentAreaRoot.tsx +++ b/threepane/src/components/DocumentAreaRoot.tsx @@ -27,7 +27,8 @@ import { type Accessor, type JSX, } from "solid-js"; -import type { ToolSlot } from "../types"; +import type { ContextLaneConfig, ToolSlot } from "../types"; +import { useContextLane } from "../hooks/useContextLane"; import { useProviderReady, useTaggedComponents, @@ -52,6 +53,10 @@ export interface DocumentAreaInputs { selectedDocUrl: Accessor; selectedToolId: Accessor; doctitleSlots: Accessor; + /** Doctitle tool ids hidden from the top bar. */ + doctitleHidden: Accessor; + /** The person's edits to the context tabs. */ + contextLane: Accessor; /** The host-side left sidebar's collapsed state, for top-bar layout only. */ isLeftCollapsed: Accessor; /** Seed values for the document-area-local right-sidebar state. */ @@ -174,6 +179,8 @@ export function DocumentAreaRoot(props: DocumentAreaRootProps) { selectedDocUrl={props.selectedDocUrl} selectedToolId={props.selectedToolId} doctitleSlots={props.doctitleSlots} + doctitleHidden={props.doctitleHidden} + contextLane={props.contextLane} isLeftCollapsed={props.isLeftCollapsed} isRightSidebarCollapsed={isRightSidebarCollapsed} setIsRightSidebarCollapsed={setIsRightSidebarCollapsed} @@ -210,6 +217,8 @@ function DraftDocumentArea(props: { selectedDocUrl: Accessor; selectedToolId: Accessor; doctitleSlots: Accessor; + doctitleHidden: Accessor; + contextLane: Accessor; isLeftCollapsed: Accessor; isRightSidebarCollapsed: Accessor; setIsRightSidebarCollapsed: ( @@ -221,9 +230,9 @@ function DraftDocumentArea(props: { selectedContextToolId: Accessor; setSelectedContextToolId: (id: string) => void; }) { - // The context sidebar exists only if something is tagged `context-tool`. - const contextItems = useTaggedComponents("context-tool"); - const hasContext = () => contextItems().length > 0; + // The context sidebar exists only if something is tagged `context-tool`, or + // was added to it by hand. + const hasContext = useContextLane(props.contextLane).exists; // Remount key for the main view: just the selected doc. Checkpoint pins are // streamed by the overlay provider on the descriptors' *backing* urls and @@ -304,6 +313,7 @@ function DraftDocumentArea(props: { ; toolSlots: Accessor; + /** Ids of configured doctitle tools hidden from the bar. */ + hiddenTools: Accessor; isLeftCollapsed: Accessor; @@ -25,14 +35,86 @@ type FrameTopBarProps = { * corner. When the left sidebar is collapsed the bar reserves a matching slot at * its start so the title slides up against (not under) that toggle. When the * context sidebar is collapsed a reopen toggle appears at the bar's right end. + * + * Right-click a doctitle tool to copy its id, hide it or remove it; right-click + * the bar's empty space (or any tool) to add a tool or show a hidden one again. Edits are + * sent up as `threepane:edit-layout` events for the frame to write to its + * config doc. */ export function FrameTopBar(props: FrameTopBarProps) { + let bar!: HTMLDivElement; + const [menu, setMenu] = createSignal<{ at: MenuAt; entries: MenuEntry[] }>(); + const [picker, setPicker] = createSignal(); + // Title + spacer are intrinsic to the bar and never in the config (the - // migration drops them), so the configured doctitle tools render as-is. - const docToolSlots = () => props.toolSlots() ?? []; + // migration drops them), so the configured doctitle tools render as-is, + // less the hidden ones. + const hidden = () => new Set((props.hiddenTools() ?? []).map(String)); + const docToolSlots = () => + (props.toolSlots() ?? []).filter((slot) => !hidden().has(slotId(slot))); + + // What "Add tool…" offers: every tool tagged `titlebar-tool` that isn't + // showing (a hidden one is shown again by adding it). + const titlebarTools = useTaggedComponents("titlebar-tool", "patchwork:tool"); + const addable = createMemo(() => { + const showing = new Set(docToolSlots().map(slotId)); + return titlebarTools().filter((tool) => !showing.has(tool.id)); + }); + + function onContextMenu(event: MouseEvent) { + // The title keeps the browser's own menu (it's an input when renaming). + const path = event.composedPath() as Element[]; + if (path.some((el) => el.classList?.contains("threepane__title"))) return; + const id = path + .find((el) => el instanceof HTMLElement && el.dataset.toolId) + ?.getAttribute("data-tool-id"); + + const entries: MenuEntry[] = []; + if (id) { + entries.push( + { label: "Copy tool id", onSelect: () => copyText(id) }, + { + label: "Hide", + onSelect: () => + dispatchLayoutEdit(bar, { lane: "doctitle", action: "hide", id }), + }, + { + label: "Remove", + onSelect: () => + dispatchLayoutEdit(bar, { lane: "doctitle", action: "remove", id }), + } + ); + } + if (entries.length) entries.push("separator"); + const at = { x: event.clientX, y: event.clientY }; + entries.push({ + label: "Add tool…", + onSelect: () => setPicker(new DOMRect(at.x, at.y, 0, 0)), + }); + + // Only hidden ids still configured: a stale one has nothing to show. + const configured = new Set((props.toolSlots() ?? []).map(slotId)); + const hiddenIds = [...hidden()].filter((hid) => configured.has(hid)); + if (hiddenIds.length) { + entries.push("separator"); + entries.push({ heading: "Hidden" }); + const tools = getRegistry("patchwork:tool"); + for (const hid of hiddenIds) { + entries.push({ + label: `Show ${tools.get(hid)?.name || hid}`, + onSelect: () => + dispatchLayoutEdit(bar, { lane: "doctitle", action: "show", id: hid }), + }); + } + } + event.preventDefault(); + setMenu({ at, entries }); + } return (
    @@ -56,7 +138,11 @@ export function FrameTopBar(props: FrameTopBarProps) {
    {(slot) => ( - + )}
    @@ -77,6 +163,30 @@ export function FrameTopBar(props: FrameTopBarProps) { + + + {(open) => ( + setMenu(undefined)} + /> + )} + + + {(anchor) => ( + + dispatchLayoutEdit(bar, { lane: "doctitle", action: "add", id }) + } + onClose={() => setPicker(undefined)} + /> + )} +
    ); } diff --git a/threepane/src/components/HostedDocumentArea.tsx b/threepane/src/components/HostedDocumentArea.tsx index 2d070861..0050799e 100644 --- a/threepane/src/components/HostedDocumentArea.tsx +++ b/threepane/src/components/HostedDocumentArea.tsx @@ -21,7 +21,7 @@ import type { AutomergeUrl } from "@automerge/automerge-repo/slim"; import { createMemo } from "solid-js"; import { createStore, reconcile } from "solid-js/store"; -import type { ToolSlot } from "../types"; +import type { ContextLaneConfig, ToolSlot } from "../types"; import { render } from "solid-js/web"; import type { DocumentAreaInputs } from "./DocumentAreaRoot"; import { DocumentAreaRoot } from "./DocumentAreaRoot"; @@ -54,6 +54,8 @@ export function HostedDocumentArea(props: HostedDocumentAreaProps) { selectedDocUrl: props.selectedDocUrl(), selectedToolId: props.selectedToolId(), doctitleSlots: props.doctitleSlots(), + doctitleHidden: props.doctitleHidden(), + contextLane: props.contextLane(), isLeftCollapsed: props.isLeftCollapsed(), initialRightWidth: props.initialRightWidth(), initialRightCollapsed: props.initialRightCollapsed(), @@ -78,6 +80,8 @@ interface DocumentAreaProps { selectedDocUrl?: AutomergeUrl; selectedToolId?: string; doctitleSlots?: ToolSlot[]; + doctitleHidden?: string[]; + contextLane?: ContextLaneConfig; isLeftCollapsed?: boolean; initialRightWidth?: number; initialRightCollapsed?: boolean; @@ -131,6 +135,8 @@ export function mountDocumentArea(element: HTMLElement): () => void { selectedDocUrl={() => p.selectedDocUrl} selectedToolId={() => p.selectedToolId} doctitleSlots={() => p.doctitleSlots} + doctitleHidden={() => p.doctitleHidden} + contextLane={() => p.contextLane} isLeftCollapsed={() => p.isLeftCollapsed ?? false} initialRightWidth={() => p.initialRightWidth ?? DEFAULT_SIDEBAR_WIDTH} initialRightCollapsed={() => p.initialRightCollapsed ?? false} diff --git a/threepane/src/components/LayoutMenus.test.tsx b/threepane/src/components/LayoutMenus.test.tsx new file mode 100644 index 00000000..b7dbe9df --- /dev/null +++ b/threepane/src/components/LayoutMenus.test.tsx @@ -0,0 +1,151 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { render } from "solid-js/web"; +import { ContextTabs } from "./ContextTabs"; +import { FrameTopBar } from "./FrameTopBar"; +import { EDIT_LAYOUT_EVENT, type LayoutEdit } from "../layoutEdits"; +import type { ToolSlot } from "../types"; + +vi.mock("@inkandswitch/patchwork-elements", () => ({})); +vi.mock("@inkandswitch/patchwork-plugins", () => ({ + getRegistry: () => ({ get: () => undefined, on: () => () => {} }), +})); +vi.mock("./DocumentTitle", () => ({ DocumentTitle: () => null })); + +let host: HTMLElement; +let dispose: () => void; +let edits: LayoutEdit[]; +afterEach(() => { + dispose?.(); + host?.remove(); + document + .querySelectorAll(".threepane-menu, .threepane-picker") + .forEach((m) => m.remove()); +}); + +function mount(ui: () => any) { + edits = []; + host = document.body.appendChild(document.createElement("div")); + host.addEventListener(EDIT_LAYOUT_EVENT, (e) => + edits.push((e as CustomEvent).detail) + ); + dispose = render(ui, host); +} + +function rightClick(target: Element) { + target.dispatchEvent( + new MouseEvent("contextmenu", { bubbles: true, cancelable: true, composed: true }) + ); +} + +const menuItems = () => + [...document.querySelectorAll('.threepane-menu [role="menuitem"]')]; + +describe("the context tab bar's menu", () => { + const tabs = (hidden: { id: string; name: string }[] = []) => + mount(() => ( + [ + { id: "comments", name: "Comments" }, + { id: "drafts", name: "Drafts" }, + ]} + hidden={() => hidden} + addable={() => []} + selectedToolId={() => undefined} + setSelectedToolId={() => {}} + /> + )); + + it("copies, hides and removes a tab", () => { + tabs(); + rightClick(host.querySelector('[data-tool-id="drafts"]')!); + expect(menuItems().map((b) => b.textContent)).toEqual([ + "Copy tool id", + "Hide", + "Remove", + "Add tab…", + ]); + menuItems()[2].click(); + expect(edits).toEqual([{ lane: "context", action: "remove", id: "drafts" }]); + }); + + it("shows a hidden tab again", () => { + tabs([{ id: "notes", name: "Notes" }]); + rightClick(host.querySelector(".context-sidebar__add")!); + expect(menuItems().map((b) => b.textContent)).toEqual([ + "Add tab…", + "Show Notes", + ]); + menuItems()[1].click(); + expect(edits).toEqual([{ lane: "context", action: "show", id: "notes" }]); + }); + + it("adds a tab from the search it opens", () => { + tabs(); + rightClick(host.querySelector(".context-sidebar__add")!); + menuItems()[0].click(); + const input = document.querySelector( + ".threepane-picker__input" + )!; + input.value = "my-thing"; + input.dispatchEvent(new InputEvent("input", { bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); + expect(edits).toEqual([{ lane: "context", action: "add", id: "my-thing" }]); + }); +}); + +describe("the top bar's doctitle tools", () => { + it("can be added from the bar's menu", () => { + bar([], []); + rightClick(host.querySelector(".threepane__spacer")!); + menuItems()[0].click(); + const input = document.querySelector( + ".threepane-picker__input" + )!; + input.value = "doc-presence"; + input.dispatchEvent(new InputEvent("input", { bubbles: true })); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); + expect(edits).toEqual([ + { lane: "doctitle", action: "add", id: "doc-presence" }, + ]); + }); + + const bar = (tools: ToolSlot[], hidden: string[]) => + mount(() => ( + "automerge:doc" as any} + toolSlots={() => tools} + hiddenTools={() => hidden} + isLeftCollapsed={() => false} + hasContext={() => false} + isRightCollapsed={() => false} + onToggleRight={() => {}} + /> + )); + + it("leave out the hidden ones, which the bar's menu can show", () => { + bar(["doc-openwith", "sync-indicator"], ["sync-indicator"]); + const ids = [...host.querySelectorAll("[data-tool-id]")].map((el) => + el.getAttribute("data-tool-id") + ); + expect(ids).toEqual(["doc-openwith"]); + + rightClick(host.querySelector(".threepane__spacer")!); + expect(menuItems().map((b) => b.textContent)).toEqual([ + "Add tool…", + "Show sync-indicator", + ]); + }); + + it("can each be removed", () => { + bar(["doc-openwith"], []); + rightClick(host.querySelector('[data-tool-id="doc-openwith"]')!); + menuItems().find((b) => b.textContent === "Remove")!.click(); + expect(edits).toEqual([ + { lane: "doctitle", action: "remove", id: "doc-openwith" }, + ]); + }); +}); diff --git a/threepane/src/components/ToolPicker.tsx b/threepane/src/components/ToolPicker.tsx new file mode 100644 index 00000000..6b2e9cdb --- /dev/null +++ b/threepane/src/components/ToolPicker.tsx @@ -0,0 +1,145 @@ +import { + createMemo, + createSignal, + For, + onCleanup, + onMount, + Show, +} from "solid-js"; +import { Portal } from "solid-js/web"; +import type { LaneItem } from "../layoutEdits"; + +const WIDTH = 220; + +/** + * A search box over a list of components, opened under `anchor`. Picks one of + * the listed items, or, when what's typed isn't one of them, the typed text as + * an id ("Add “…”", last). Closes on a pick, a click outside or Escape. + */ +export function ToolPicker(props: { + anchor: DOMRect; + items: LaneItem[]; + placeholder: string; + onPick: (id: string) => void; + onClose: () => void; +}) { + let root!: HTMLDivElement; + let input!: HTMLInputElement; + let list!: HTMLDivElement; + const [query, setQuery] = createSignal(""); + const [highlighted, setHighlighted] = createSignal(0); + + const rows = createMemo<(LaneItem & { typed?: true })[]>(() => { + const q = query().trim(); + const lower = q.toLowerCase(); + const matches = props.items.filter( + (item) => + !lower || + item.name.toLowerCase().includes(lower) || + item.id.toLowerCase().includes(lower) + ); + const exact = props.items.some((item) => item.id === q); + return q && !exact ? [...matches, { id: q, name: q, typed: true }] : matches; + }); + + function pick(id: string) { + props.onClose(); + props.onPick(id); + } + + function move(by: number) { + const count = rows().length; + if (!count) return; + const next = (highlighted() + by + count) % count; + setHighlighted(next); + list.children[next]?.scrollIntoView({ block: "nearest" }); + } + + // Under the anchor, its right edge lined up with the anchor's if it would + // otherwise run off the right of the screen. + const left = () => + Math.max( + 4, + props.anchor.left + WIDTH > innerWidth - 4 + ? props.anchor.right - WIDTH + : props.anchor.left + ); + + onMount(() => { + input.focus(); + const onPointerDown = (event: PointerEvent) => { + if (!root.contains(event.target as Node)) props.onClose(); + }; + document.addEventListener("pointerdown", onPointerDown, true); + onCleanup(() => + document.removeEventListener("pointerdown", onPointerDown, true) + ); + }); + + return ( + +
    event.stopPropagation()} + style={{ + left: `${left()}px`, + top: `${props.anchor.bottom + 2}px`, + width: `${WIDTH}px`, + }} + > + { + setQuery(event.currentTarget.value); + setHighlighted(0); + }} + onKeyDown={(event) => { + if (event.key === "ArrowDown") move(1); + else if (event.key === "ArrowUp") move(-1); + else if (event.key === "Enter") { + const row = rows()[highlighted()]; + if (row) pick(row.id); + } else if (event.key === "Escape") props.onClose(); + else return; + event.preventDefault(); + }} + /> +
    + + {(row, index) => ( + + )} + +
    +
    +
    + ); +} diff --git a/threepane/src/hooks/index.ts b/threepane/src/hooks/index.ts index 2953d451..104f081d 100644 --- a/threepane/src/hooks/index.ts +++ b/threepane/src/hooks/index.ts @@ -12,4 +12,8 @@ export { } from "./useSidebarResize"; export { useProviderReady } from "./useProviderReady"; export { useMainDocMounted } from "./useMainDocMounted"; -export { useTaggedComponents, type TaggedComponent } from "./useTaggedComponents"; +export { + useTaggedComponents, + useComponentName, + type TaggedComponent, +} from "./useTaggedComponents"; diff --git a/threepane/src/hooks/useContextLane.ts b/threepane/src/hooks/useContextLane.ts new file mode 100644 index 00000000..405e98b8 --- /dev/null +++ b/threepane/src/hooks/useContextLane.ts @@ -0,0 +1,31 @@ +import { createMemo, type Accessor } from "solid-js"; +import type { ContextLaneConfig } from "../types"; +import { contextLane, type LaneItem } from "../layoutEdits"; +import { useComponentName, useTaggedComponents } from "./useTaggedComponents"; + +/** + * The context tabs: every component tagged `"context-tool"`, with the person's + * edits from the config doc applied (see ContextLaneConfig). + * + * - `shown` / `hidden`: the tabs in the bar, and the ones hidden from it. + * - `addable`: the tagged components the "+" offers, i.e. every one that isn't + * showing (hidden and removed ones included). + * - `exists`: whether there's a context sidebar at all — anything tagged, or + * anything added by hand. It stays when every tab has been hidden or + * removed, so the "+" is still there to bring one back. + */ +export function useContextLane(config: Accessor) { + const tagged = useTaggedComponents("context-tool"); + const name = useComponentName(); + + const lane = createMemo(() => contextLane(tagged(), config(), name)); + const shown = () => lane().shown; + const hidden = () => lane().hidden; + const addable = createMemo(() => { + const showing = new Set(shown().map((item) => item.id)); + return tagged().filter((item) => !showing.has(item.id)); + }); + const exists = () => tagged().length > 0 || !!config()?.added?.length; + + return { shown, hidden, addable, exists }; +} diff --git a/threepane/src/hooks/useTaggedComponents.ts b/threepane/src/hooks/useTaggedComponents.ts index 8251803d..27b0cbe7 100644 --- a/threepane/src/hooks/useTaggedComponents.ts +++ b/threepane/src/hooks/useTaggedComponents.ts @@ -11,16 +11,20 @@ export type TaggedComponent = { }; /** - * Live, registry-driven list of every `patchwork:component` carrying `tag` - * (e.g. `"context-tool"` or `"system-tray"`), sorted by name. A component just + * Live, registry-driven list of every `patchwork:component` (or, given + * `registryType`, every plugin of that type) carrying `tag` (e.g. + * `"context-tool"` or `"system-tray"`), sorted by name. A component just * declares its tag and shows up everywhere that tag is rendered. * * Reactive to the registry's `"changed"` event, so a late-registering or * hot-reloaded plugin appears without a remount. When a host mounts the document * area in another realm, this resolves against that realm's registry. */ -export function useTaggedComponents(tag: string): Accessor { - const registry = getRegistry("patchwork:component"); +export function useTaggedComponents( + tag: string, + registryType = "patchwork:component" +): Accessor { + const registry = getRegistry(registryType); const [version, setVersion] = createSignal(0); const off = registry.on("changed", () => setVersion((v) => v + 1)); @@ -38,3 +42,22 @@ export function useTaggedComponents(tag: string): Accessor { .sort((a, b) => a.name.localeCompare(b.name)); }); } + +/** + * The registered name of a `patchwork:component` (its id if it has none, or + * isn't registered), live like `useTaggedComponents`. + */ +export function useComponentName(): (id: string) => string { + const registry = getRegistry("patchwork:component"); + + const [version, setVersion] = createSignal(0); + const off = registry.on("changed", () => { + setVersion((v) => v + 1); + }); + onCleanup(off); + + return (id) => { + version(); + return registry.get(id)?.name || id; + }; +} diff --git a/threepane/src/layoutEdits.test.ts b/threepane/src/layoutEdits.test.ts new file mode 100644 index 00000000..3216e59a --- /dev/null +++ b/threepane/src/layoutEdits.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from "vitest"; +import { applyLayoutEdit, contextLane } from "./layoutEdits"; +import type { ThreepaneConfigDoc } from "./types"; + +const config = (): ThreepaneConfigDoc => ({ + sidebar: { widgets: [] }, + doctitle: { tools: ["doc-openwith", ["sync-indicator", "automerge:x" as any]] }, + tray: [], +}); + +const tagged = [ + { id: "comments", name: "Comments" }, + { id: "drafts", name: "Drafts" }, +]; + +describe("context tabs", () => { + it("are the tagged components, untouched", () => { + expect(contextLane(tagged, undefined).shown.map((t) => t.id)).toEqual([ + "comments", + "drafts", + ]); + }); + + it("can be removed, and come back by adding", () => { + const doc = config(); + applyLayoutEdit(doc, { lane: "context", action: "remove", id: "drafts" }); + expect(contextLane(tagged, doc.context).shown.map((t) => t.id)).toEqual([ + "comments", + ]); + applyLayoutEdit(doc, { lane: "context", action: "add", id: "drafts" }); + expect(contextLane(tagged, doc.context).shown.map((t) => t.id)).toEqual([ + "comments", + "drafts", + ]); + }); + + it("can be hidden and shown", () => { + const doc = config(); + applyLayoutEdit(doc, { lane: "context", action: "hide", id: "comments" }); + const lane = contextLane(tagged, doc.context); + expect(lane.shown.map((t) => t.id)).toEqual(["drafts"]); + expect(lane.hidden.map((t) => t.id)).toEqual(["comments"]); + applyLayoutEdit(doc, { lane: "context", action: "show", id: "comments" }); + expect(contextLane(tagged, doc.context).hidden).toEqual([]); + }); + + it("take any component id by hand, after the tagged ones, once", () => { + const doc = config(); + applyLayoutEdit(doc, { lane: "context", action: "add", id: "my-thing" }); + applyLayoutEdit(doc, { lane: "context", action: "add", id: "my-thing" }); + applyLayoutEdit(doc, { lane: "context", action: "add", id: "comments" }); + const lane = contextLane(tagged, doc.context, (id) => id.toUpperCase()); + expect(lane.shown).toEqual([ + { id: "comments", name: "Comments" }, + { id: "drafts", name: "Drafts" }, + { id: "my-thing", name: "MY-THING" }, + ]); + }); + + it("forget a hidden state when removed", () => { + const doc = config(); + applyLayoutEdit(doc, { lane: "context", action: "hide", id: "my-thing" }); + applyLayoutEdit(doc, { lane: "context", action: "remove", id: "my-thing" }); + expect(doc.context?.hidden).toEqual([]); + }); +}); + +describe("doctitle tools", () => { + it("are removed whichever form their slot is", () => { + const doc = config(); + applyLayoutEdit(doc, { lane: "doctitle", action: "remove", id: "sync-indicator" }); + expect(doc.doctitle.tools).toEqual(["doc-openwith"]); + }); + + it("are added once, at the end, and a hidden one is shown", () => { + const doc = config(); + applyLayoutEdit(doc, { lane: "doctitle", action: "hide", id: "doc-openwith" }); + applyLayoutEdit(doc, { lane: "doctitle", action: "add", id: "doc-openwith" }); + applyLayoutEdit(doc, { lane: "doctitle", action: "add", id: "doc-presence" }); + applyLayoutEdit(doc, { lane: "doctitle", action: "add", id: "sync-indicator" }); + expect(doc.doctitle.hidden).toEqual([]); + expect(doc.doctitle.tools.map(String)).toEqual([ + "doc-openwith", + "sync-indicator,automerge:x", + "doc-presence", + ]); + }); + + it("can be hidden and shown", () => { + const doc = config(); + applyLayoutEdit(doc, { lane: "doctitle", action: "hide", id: "doc-openwith" }); + applyLayoutEdit(doc, { lane: "doctitle", action: "hide", id: "doc-openwith" }); + expect(doc.doctitle.hidden).toEqual(["doc-openwith"]); + applyLayoutEdit(doc, { lane: "doctitle", action: "show", id: "doc-openwith" }); + expect(doc.doctitle.hidden).toEqual([]); + }); +}); diff --git a/threepane/src/layoutEdits.ts b/threepane/src/layoutEdits.ts new file mode 100644 index 00000000..c63a6d03 --- /dev/null +++ b/threepane/src/layoutEdits.ts @@ -0,0 +1,150 @@ +import type { ContextLaneConfig, ThreepaneConfigDoc } from "./types"; +import { slotId } from "./components/SlotView"; + +/** + * Asked for by the tab bar and the top bar when someone adds, removes, hides + * or shows one of their tools. It bubbles and is composed, so the frame that + * owns the threepane config doc answers it wherever the document area is + * mounted (inline, or by a host). See `handleLayoutEdits`. + */ +export const EDIT_LAYOUT_EVENT = "threepane:edit-layout"; + +export type LayoutEdit = + | { lane: "context"; action: "add" | "remove" | "hide" | "show"; id: string } + | { + lane: "doctitle"; + action: "add" | "remove" | "hide" | "show"; + id: string; + }; + +export function dispatchLayoutEdit(from: Element, edit: LayoutEdit) { + from.dispatchEvent( + new CustomEvent(EDIT_LAYOUT_EVENT, { + detail: edit, + bubbles: true, + composed: true, + }) + ); +} + +/** Splice every `id` out of `list`, in place. */ +function drop(list: string[] | undefined, id: string) { + if (!list) return; + for (let i = list.length - 1; i >= 0; i--) { + if (String(list[i]) === id) list.splice(i, 1); + } +} + +function include(list: string[], id: string) { + if (!list.some((existing) => String(existing) === id)) list.push(id); +} + +/** Apply one edit to the config doc, inside a `change`. */ +export function applyLayoutEdit(doc: ThreepaneConfigDoc, edit: LayoutEdit) { + const { id } = edit; + if (!id) return; + + if (edit.lane === "context") { + if (!doc.context) doc.context = {}; + const lane = doc.context; + switch (edit.action) { + case "add": + drop(lane.removed, id); + drop(lane.hidden, id); + if (!lane.added) lane.added = []; + include(lane.added, id); + return; + case "remove": + drop(lane.added, id); + drop(lane.hidden, id); + if (!lane.removed) lane.removed = []; + include(lane.removed, id); + return; + case "hide": + if (!lane.hidden) lane.hidden = []; + include(lane.hidden, id); + return; + case "show": + drop(lane.hidden, id); + return; + } + } + + if (!doc.doctitle) doc.doctitle = { tools: [] }; + const doctitle = doc.doctitle; + switch (edit.action) { + case "add": + if (!doctitle.tools) doctitle.tools = []; + if (!doctitle.tools.some((slot) => slotId(slot) === id)) + doctitle.tools.push(id); + drop(doctitle.hidden, id); + return; + case "remove": { + const tools = doctitle.tools ?? []; + for (let i = tools.length - 1; i >= 0; i--) { + if (slotId(tools[i]) === id) tools.splice(i, 1); + } + drop(doctitle.hidden, id); + return; + } + case "hide": + if (!doctitle.hidden) doctitle.hidden = []; + include(doctitle.hidden, id); + return; + case "show": + drop(doctitle.hidden, id); + return; + } +} + +export type LaneItem = { id: string; name: string }; + +/** + * The context tabs, from the registry's tagged components and the person's + * edits: `shown` in the bar, `hidden` from it, in bar order (tagged first, by + * name, then the hand-added ones in the order they were added). `name` names a + * hand-added id that isn't a tagged component. + */ +export function contextLane( + tagged: LaneItem[], + config: ContextLaneConfig | undefined, + name: (id: string) => string = (id) => id +): { shown: LaneItem[]; hidden: LaneItem[] } { + const removed = new Set((config?.removed ?? []).map(String)); + const hidden = new Set((config?.hidden ?? []).map(String)); + const seen = new Set(); + const all: LaneItem[] = []; + for (const item of tagged) { + if (removed.has(item.id) || seen.has(item.id)) continue; + seen.add(item.id); + all.push(item); + } + for (const raw of config?.added ?? []) { + const id = String(raw); + if (removed.has(id) || seen.has(id)) continue; + seen.add(id); + all.push({ id, name: name(id) }); + } + return { + shown: all.filter((item) => !hidden.has(item.id)), + hidden: all.filter((item) => hidden.has(item.id)), + }; +} + +/** + * Answer `threepane:edit-layout` events from inside `element` by applying them + * to the config doc through `change`. + */ +export function handleLayoutEdits( + element: HTMLElement, + change: (fn: (doc: ThreepaneConfigDoc) => void) => void +) { + const onEdit = (event: Event) => { + const edit = (event as CustomEvent).detail; + if (!edit?.id) return; + event.stopPropagation(); + change((doc) => applyLayoutEdit(doc, edit)); + }; + element.addEventListener(EDIT_LAYOUT_EVENT, onEdit); + return () => element.removeEventListener(EDIT_LAYOUT_EVENT, onEdit); +} diff --git a/threepane/src/styles.css b/threepane/src/styles.css index 181aab04..3568098d 100644 --- a/threepane/src/styles.css +++ b/threepane/src/styles.css @@ -470,6 +470,31 @@ box-shadow: inset 0 1px 0 0 var(--context-sidebar-tab-active-accent); } +/* The "+" at the end of the tab list, to add a tab. Last in the scrolling + list, so it's only in reach once the tabs are scrolled to their end. */ +.context-sidebar__add { + display: flex; + align-items: center; + justify-content: center; + align-self: center; + flex-shrink: 0; + padding: var(--threepane-space-2xs); + border: none; + border-radius: var(--threepane-radius-xs); + background: transparent; + color: var(--context-sidebar-tab-fg); + cursor: var(--studio-cursor-pointer, pointer); + opacity: 0.6; + transition: opacity var(--studio-transition-fast, 0.1s ease), + background var(--studio-transition-fast, 0.1s ease); +} + +.context-sidebar__add:hover, +.context-sidebar__add[aria-expanded="true"] { + opacity: 1; + background: var(--studio-chrome-hover-fill, var(--context-sidebar-tab-hover)); +} + /* The close (collapse) button. Centred vertically in the tab header (the header is otherwise flex-end for the tabs) so it lands at the same height as the reopen toggle in the top bar when the sidebar is collapsed. */ @@ -629,7 +654,8 @@ text-overflow: ellipsis; } -.threepane-account-menu { +.threepane-account-menu, +.threepane-menu { position: fixed; z-index: 20; display: flex; @@ -645,7 +671,8 @@ box-shadow: var(--studio-shadow-menu, 0 4px 12px rgb(0 0 0 / 20%)); } -.threepane-account-menu button { +.threepane-account-menu button, +.threepane-menu button { padding: var(--threepane-space-xs) var(--threepane-space-sm); border: none; border-radius: var(--threepane-radius-xs); @@ -657,11 +684,109 @@ } .threepane-account-menu button:hover, -.threepane-account-menu button:focus-visible { +.threepane-account-menu button:focus-visible, +.threepane-menu button:hover, +.threepane-menu button:focus-visible { + outline: none; + background: var(--threepane-sidebar-hover); +} + +/* The tab bar's and top bar's right-click menu: wider than the account menu, + for "Show ". */ +.threepane-menu { + width: auto; + min-width: 160px; + max-width: min(280px, calc(100vw - 8px)); +} + +.threepane-menu button { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.threepane-menu__heading { + padding: var(--threepane-space-2xs) var(--threepane-space-sm) 0; + font-size: 0.75rem; + color: var(--threepane-muted); +} + +.threepane-menu__separator { + width: 100%; + margin: var(--threepane-space-3xs) 0; + border: none; + border-top: var(--studio-border-width, 1px) var(--studio-border-style, solid) var(--threepane-sidebar-divider); +} + +/* The "+" tab picker: a search box over the components it can add. */ +.threepane-picker { + position: fixed; + z-index: 20; + display: flex; + box-sizing: border-box; + max-width: calc(100vw - 8px); + flex-direction: column; + overflow: hidden; + border: var(--studio-border-width, 1px) var(--studio-border-style, solid) var(--threepane-sidebar-divider); + border-radius: var(--threepane-radius-sm); + background: var(--threepane-bg); + color: var(--threepane-fg); + box-shadow: var(--studio-shadow-menu, 0 4px 12px rgb(0 0 0 / 20%)); + font-family: var(--threepane-family); + font-size: 0.875rem; +} + +.threepane-picker__input { + box-sizing: border-box; + width: 100%; + padding: var(--threepane-space-xs) var(--threepane-space-sm); + border: none; + border-bottom: var(--studio-border-width, 1px) var(--studio-border-style, solid) var(--threepane-sidebar-divider); outline: none; + background: none; + color: inherit; + font: inherit; +} + +.threepane-picker__list { + max-height: 240px; + overflow-y: auto; + padding: var(--threepane-space-3xs); +} + +.threepane-picker__list:empty { + display: none; +} + +.threepane-picker__item { + display: flex; + width: 100%; + align-items: baseline; + gap: var(--threepane-space-sm); + padding: var(--threepane-space-xs) var(--threepane-space-sm); + border: none; + border-radius: var(--threepane-radius-xs); + background: transparent; + color: inherit; + font: inherit; + text-align: left; + white-space: nowrap; + cursor: var(--studio-cursor-pointer, pointer); +} + +.threepane-picker__item[data-highlight] { background: var(--threepane-sidebar-hover); } +.threepane-picker__id { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + font-family: var(--threepane-family-code); + font-size: 0.75rem; + color: var(--threepane-muted); +} + /* Left sidebar: a stack of configured widgets. The widgets start below the frame's top strip (the empty space matching the top bar), so the frame owns that spacing rather than each widget reserving its own top margin. */ diff --git a/threepane/src/types.ts b/threepane/src/types.ts index 0d4578a9..4c5b4468 100644 --- a/threepane/src/types.ts +++ b/threepane/src/types.ts @@ -47,6 +47,23 @@ export type ToolRef = [toolId: string, docId: AutomergeUrl]; */ export type ToolSlot = ToolRef | string; +/** + * The context tabs are every `patchwork:component` tagged `"context-tool"`, so + * a newly installed one shows up by itself. This records the person's edits on + * top of that list, all as component ids: + * + * - `added`: components that aren't tagged but were added by hand (the tab + * bar's "+"), in the order they were added, after the tagged ones. + * - `removed`: tagged components taken out of the bar. + * - `hidden`: tabs still in the bar's list but not shown (unhide from the + * tab bar's context menu). + */ +export type ContextLaneConfig = { + added?: string[]; + removed?: string[]; + hidden?: string[]; +}; + /** * The threepane layout config (its own document, referenced from * `AccountDoc.tools["threepane"]`). The context sidebar is host chrome and @@ -56,7 +73,11 @@ export type ToolSlot = ToolRef | string; */ export type ThreepaneConfigDoc = { sidebar: { widgets: ToolSlot[] }; - doctitle: { tools: ToolSlot[] }; + /** `hidden`: tool ids still in `tools` but not shown (unhide from the bar's + * context menu). */ + doctitle: { tools: ToolSlot[]; hidden?: string[] }; + /** Edits to the registry-driven context tabs. See ContextLaneConfig. */ + context?: ContextLaneConfig; /** The system-tray tools, docked at the frame's bottom-left, in order. */ tray: ToolSlot[]; /**