Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions docs/common/CELL_CONTEXT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
`<ct-cell-context>` designates a region of the page as pertaining to a particular cell. This creates a tree of cells annotating the entire interaction—like an accessibility tree, but for data. Currently used for debugging and inspection; future features will build on this structure.

# Automatic Injection

Every `[UI]` render is automatically wrapped in `ct-cell-context`. You get top-level charm debugging for free without any code changes.

# When to Use Manually

Add `ct-cell-context` sparingly—typically 1-2 per pattern at most. Use it for values that are:

- Important but otherwise difficult to access
- Intermediate calculations or API responses
- Values you'd otherwise debug with `console.log`

This is better than adding a `derive` with `console.log` because inspection is conditional—users can watch and unwatch values on demand rather than flooding the console.

```tsx
<ct-cell-context $cell={result} label="Calculation Result">
<div>{result.value}</div>
</ct-cell-context>
```

# API

- `$cell` - The Cell to associate with this region
- `label` - Human-readable name shown in the toolbar (optional)
- `inline` - Display as inline-block instead of block (optional)

# Debugging

Hold **Alt** and hover over a cell context region to see the debugging toolbar:

- **val** - Log the cell value to console and set `globalThis.$cell` to the cell, making it accessible via the console for inspection (similar to Chrome's `$0` for elements)
- **id** - Log the cell's full address
- **watch/unwatch** - Subscribe to value changes; updates appear in the debugger's Watch List

# When NOT to Use

- Don't wrap every cell—reserve for important values
- Don't use for trivial or obviously-accessible values
- If a value is already easy to inspect via the UI, you probably don't need this
129 changes: 129 additions & 0 deletions packages/shell/src/components/FavoriteButton.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { css, html, LitElement, PropertyValues } from "lit";
import { property, state } from "lit/decorators.js";
import { RuntimeInternals } from "../lib/runtime.ts";
import { Task } from "@lit/task";

export class XFavoriteButtonElement extends LitElement {
static override styles = css`
x-button.emoji-button {
opacity: 0.7;
transition: opacity 0.2s;
font-size: 1rem;
}

x-button.emoji-button:hover {
opacity: 1;
}

x-button.auth-button {
font-size: 1rem;
}
`;

@property()
rt?: RuntimeInternals;

@property({ attribute: false })
charmId?: string;

// Local state for favoriting, used when
// modifying state inbetween server syncs.
@state()
isFavorite: boolean | undefined = undefined;

private async handleFavoriteClick(e: Event) {
e.preventDefault();
e.stopPropagation();
if (!this.rt || !this.charmId) return;
const manager = this.rt.cc().manager();

const isFavorite = this.deriveIsFavorite();

// Update local state, and use until overridden by
// syncing state, or another click.
this.isFavorite = !isFavorite;

try {
const charmCell = (await this.rt.cc().get(this.charmId, true)).getCell();
if (isFavorite) {
await manager.removeFavorite(charmCell);
} else {
await manager.addFavorite(charmCell);
}
} finally {
this.isFavoriteSync.run();
}
}

protected override willUpdate(changedProperties: PropertyValues): void {
if (changedProperties.has("charmId")) {
this.isFavorite = undefined;
}
}

private deriveIsFavorite(): boolean {
// If `isFavorite` is defined, we have local state that is not
// yet synced. Prefer local state if defined, otherwise use server state.
return this.isFavorite ?? this.isFavoriteSync.value ?? false;
}

isFavoriteSync = new Task(this, {
task: async (
[charmId, rt],
{ signal },
): Promise<boolean> => {
const isFavorite = await isFavoriteSync(rt, charmId);

// If another favorite request was initiated, store
// the sync status, but don't overwrite the local state.
if (signal.aborted) return isFavorite;

// We update `this.isFavorite` here to `undefined`,
// indicating that the synced state should be preferred
// now that it's fresh.
this.isFavorite = undefined;
return isFavorite;
},
args: () => [this.charmId, this.rt],
});

override render() {
const isFavorite = this.deriveIsFavorite();

return html`
<x-button
class="emoji-button"
size="small"
@click="${this.handleFavoriteClick}"
title="${isFavorite ? "Remove from Favorites" : "Add to Favorites"}"
>
${isFavorite ? "⭐" : "☆"}
</x-button>
`;
}
}

globalThis.customElements.define("x-favorite-button", XFavoriteButtonElement);

async function isFavoriteSync(
rt?: RuntimeInternals,
charmId?: string,
): Promise<boolean> {
if (!charmId || !rt) {
return false;
}
const manager = rt.cc().manager();
try {
const charm = await manager.get(charmId, true);
if (charm) {
const favorites = manager.getFavorites();
await favorites.sync();
return manager.isFavorite(charm);
} else {
return false;
}
} catch (_) {
//
}
return false;
}
1 change: 1 addition & 0 deletions packages/shell/src/components/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from "./Button.ts";
export * from "./CharmLink.ts";
export * from "./CTLogo.ts";
export * from "./FavoriteButton.ts";
export * from "./Flex.ts";
export * from "./Spinner.ts";
33 changes: 8 additions & 25 deletions packages/shell/src/lib/app/commands.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import { Identity } from "@commontools/identity";
import { AppView, isAppView } from "./view.ts";
import { AppStateConfigKey, isAppStateConfigKey } from "./state.ts";

export type Command =
| { type: "set-view"; view: AppView }
| { type: "set-identity"; identity: Identity }
| { type: "clear-authentication" }
| { type: "set-show-charm-list-view"; show: boolean }
| { type: "set-show-debugger-view"; show: boolean }
| { type: "set-show-quick-jump-view"; show: boolean }
| { type: "set-show-sidebar"; show: boolean }
| { type: "toggle-favorite"; charmId: string };
| { type: "set-identity"; identity: Identity | undefined }
| { type: "set-config"; key: AppStateConfigKey; value: boolean };

export function isCommand(value: unknown): value is Command {
if (
Expand All @@ -20,28 +16,15 @@ export function isCommand(value: unknown): value is Command {
}
switch (value.type) {
case "set-identity": {
return "identity" in value && value.identity instanceof Identity;
return "identity" in value &&
(value.identity === undefined || value.identity instanceof Identity);
}
case "set-view": {
return "view" in value && isAppView(value.view);
}
case "clear-authentication": {
return true;
}
case "set-show-charm-list-view": {
return "show" in value && typeof value.show === "boolean";
}
case "set-show-debugger-view": {
return "show" in value && typeof value.show === "boolean";
}
case "set-show-quick-jump-view": {
return "show" in value && typeof value.show === "boolean";
}
case "set-show-sidebar": {
return "show" in value && typeof value.show === "boolean";
}
case "toggle-favorite": {
return "charmId" in value && typeof value.charmId === "string";
case "set-config": {
return "key" in value && isAppStateConfigKey(value.key) &&
"value" in value && typeof value.value === "boolean";
}
}
return false;
Expand Down
65 changes: 40 additions & 25 deletions packages/shell/src/lib/app/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,52 @@ export interface AppState {
identity?: Identity;
view: AppView;
apiUrl: URL;
config: AppStateConfig;
}

export interface AppStateConfig {
showShellCharmListView?: boolean;
showDebuggerView?: boolean;
showQuickJumpView?: boolean;
showSidebar?: boolean;
}

export type AppStateConfigKey = keyof AppStateConfig;

export type AppStateSerialized = Omit<AppState, "identity" | "apiUrl"> & {
identity?: TransferrableInsecureCryptoKeyPair | null;
apiUrl: string;
};

export function isAppStateConfigKey(
value: unknown,
): value is AppStateConfigKey {
if (typeof value !== "string") return false;
switch (value) {
case "showShellCharmListView":
case "showDebuggerView":
case "showQuickJumpView":
case "showSidebar":
return true;
}
return false;
}

export function createAppState(
initial: Pick<AppState, "view" | "apiUrl" | "identity"> & {
config?: AppStateConfig;
},
): AppState {
return Object.assign({}, initial, { config: initial.config ?? {} });
}

export function clone(state: AppState): AppState {
const view = typeof state.view === "object"
? Object.assign({}, state.view)
: state.view;
const cloned = Object.assign({}, state);
cloned.view = view;
return cloned;
return Object.assign({}, state, {
config: Object.assign({}, state.config),
view: typeof state.view === "object"
? Object.assign({}, state.view)
: state.view,
});
}

export function applyCommand(
Expand All @@ -45,28 +73,15 @@ export function applyCommand(
case "set-view": {
next.view = command.view;
if ("charmId" in command.view && command.view.charmId) {
next.showShellCharmListView = false;
next.config.showShellCharmListView = false;
}
break;
}
case "clear-authentication": {
next.identity = undefined;
break;
}
case "set-show-charm-list-view": {
next.showShellCharmListView = command.show;
break;
}
case "set-show-debugger-view": {
next.showDebuggerView = command.show;
break;
}
case "set-show-quick-jump-view": {
next.showQuickJumpView = command.show;
break;
}
case "set-show-sidebar": {
next.showSidebar = command.show;
case "set-config": {
if (!isAppStateConfigKey(command.key)) {
throw new Error(`Invalid config key: ${command.key}`);
}
next.config[command.key] = command.value;
break;
}
}
Expand Down
38 changes: 35 additions & 3 deletions packages/shell/src/lib/debugger-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@ export interface WatchedCell {
* - Watched cell subscriptions with console logging
*/
export class DebuggerController implements ReactiveController {
private host: ReactiveControllerHost;
private host: ReactiveControllerHost & HTMLElement;
private runtime?: RuntimeInternals;
private visible = false;
private telemetryMarkers: RuntimeTelemetryMarkerResult[] = [];
private updateVersion = 0;
private watchedCells = new Map<string, WatchedCell>();

constructor(host: ReactiveControllerHost) {
constructor(host: ReactiveControllerHost & HTMLElement) {
this.host = host;
this.host.addController(this);
}
Expand All @@ -61,12 +61,17 @@ export class DebuggerController implements ReactiveController {
this.visible = savedVisible === "true";
}

// Listen for storage events (cross-tab sync)
globalThis.addEventListener("storage", this.handleStorageChange);
this.host.addEventListener("ct-cell-watch", this.handleCellWatch);
this.host.addEventListener("ct-cell-unwatch", this.handleCellUnwatch);
this.host.addEventListener("clear-telemetry", this.handleClearTelemetry);
}

hostDisconnected() {
globalThis.removeEventListener("storage", this.handleStorageChange);
this.host.removeEventListener("ct-cell-watch", this.handleCellWatch);
this.host.removeEventListener("ct-cell-unwatch", this.handleCellUnwatch);
this.host.removeEventListener("clear-telemetry", this.handleClearTelemetry);
// Clean up all watched cell subscriptions to prevent memory leaks
this.unwatchAll();
}
Expand Down Expand Up @@ -340,4 +345,31 @@ export class DebuggerController implements ReactiveController {
const shortId = id.split(":").pop()?.slice(-6) ?? "???";
return `#${shortId}`;
}

private handleCellWatch = (e: Event) => {
const event = e as CustomEvent<{ cell: unknown; label?: string }>;
const { cell, label } = event.detail;
// Cell type from @commontools/runner
if (cell && typeof (cell as any).sink === "function") {
this.watchCell(cell as any, label);
}
};

private handleCellUnwatch = (e: Event) => {
const event = e as CustomEvent<{ cell: unknown; label?: string }>;
const { cell } = event.detail;
// Find and remove the watch by matching the cell
if (cell && typeof (cell as any).getAsNormalizedFullLink === "function") {
const link = (cell as any).getAsNormalizedFullLink();
const watches = this.getWatchedCells();
const watch = watches.find((w) => w.cellLink.id === link.id);
if (watch) {
this.unwatchCell(watch.id);
}
}
};

private handleClearTelemetry = () => {
this.clearTelemetry();
};
}
Loading
Loading