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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ All notable changes to this project will be documented in this file. The format
### Added

- Add browser storage utilities: `createStorage`, `useLocalStorage`, `useSessionStorage`, `useUrlSearchParams`, `useUrlSearchParamsInHash` ([#671](https://github.com/studiometa/js-toolkit/pull/671))
- Add `logTree` helper to inspect the component tree from the console ([#654](https://github.com/studiometa/js-toolkit/pull/654))

## [v3.5.0](https://github.com/studiometa/js-toolkit/compare/3.4.3..3.5.0) (2026-03-25)

Expand Down
1 change: 1 addition & 0 deletions packages/docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ function getHelpersSidebar() {
{ text: 'importWhenPrefersMotion', link: '/api/helpers/importWhenPrefersMotion.html' },
{ text: 'importWhenVisible', link: '/api/helpers/importWhenVisible.html' },
{ text: 'isDirectChild', link: '/api/helpers/isDirectChild.html' },
{ text: 'logTree', link: '/api/helpers/logTree.html' },
{ text: 'registerComponent', link: '/api/helpers/registerComponent.html' },
];
}
Expand Down
42 changes: 42 additions & 0 deletions packages/docs/api/helpers/logTree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# logTree

Log the component tree to the browser console starting from a given instance. Uses the global instance registry and DOM containment to build the tree β€” does **not** rely on the deprecated `$children` API.

Components with children are displayed as collapsed groups. Each entry shows:
- **●** for mounted instances, **β—‹** for unmounted
- The instance `$id`
- A reference to the DOM element

## Usage

### From the console (zero config)

When using `createApp`, a `$logTree()` function is automatically registered on `globalThis` in development mode. Just open your browser console and type:

```js
$logTree()
```

### Programmatic usage

```js
import { logTree } from '@studiometa/js-toolkit';

// From any component
logTree(this);
```

```js
import { createApp, logTree } from '@studiometa/js-toolkit';

const useApp = createApp(App);
useApp().then((app) => logTree(app));
```

### Parameters

- `instance` (`Base`): The root component instance to log the tree from.

### Return value

- `void`: Logs to the console, does not return a value.
5 changes: 5 additions & 0 deletions packages/js-toolkit/helpers/createApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import type { Base, BaseConstructor, BaseProps } from '../Base/index.js';
import type { Features } from '../Base/features.js';
import { features } from '../Base/features.js';
import { defineFeatures } from './defineFeatures.js';
import { isDev } from '../utils/index.js';
import { logTree } from './logTree.js';

export type CreateAppOptions = Partial<Features> & {
root?: HTMLElement;
Expand All @@ -27,6 +29,9 @@ export function createApp<S extends BaseConstructor<Base>, T extends BaseProps =
async function init() {
app = new App(root) as S & Base<T>;
await app.$mount();
if (isDev) {
globalThis.$logTree = () => logTree(app);
}
return app;
}

Expand Down
1 change: 1 addition & 0 deletions packages/js-toolkit/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export * from './importOnMediaQuery.js';
export * from './importWhenIdle.js';
export * from './importWhenPrefersMotion.js';
export * from './importWhenVisible.js';
export * from './logTree.js';
export * from './registerComponent.js';
export {
type QueryOptions,
Expand Down
102 changes: 102 additions & 0 deletions packages/js-toolkit/helpers/logTree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import type { Base } from '../Base/Base.js';
import { getInstances } from '../Base/index.js';

/**
* Build a tree structure from a flat set of instances using DOM containment.
*/
function buildTree(root: Base): TreeNode {
const allInstances = getInstances();
const rootNode: TreeNode = { instance: root, children: [] };

// Collect all instances that are descendants of root (excluding root itself)
const descendants: Base[] = [];
for (const instance of allInstances) {
if (instance !== root && root.$el.contains(instance.$el)) {
descendants.push(instance);
}
}

// Sort by DOM order (depth-first)
descendants.sort((a, b) => {
const position = a.$el.compareDocumentPosition(b.$el);
if (position & Node.DOCUMENT_POSITION_FOLLOWING) return -1;
if (position & Node.DOCUMENT_POSITION_PRECEDING) return 1;
return 0;
});

// Build tree: assign each instance to its closest ancestor in the tree
const nodeMap = new Map<Base, TreeNode>();
nodeMap.set(root, rootNode);

for (const instance of descendants) {
const node: TreeNode = { instance, children: [] };
nodeMap.set(instance, node);

// Find the closest ancestor that is already in the tree
let parentNode = rootNode;
for (const [candidate, candidateNode] of nodeMap) {
if (
candidate !== instance &&
candidate.$el.contains(instance.$el) &&
// Pick the most specific (deepest) container
parentNode.instance.$el.contains(candidate.$el)
) {
parentNode = candidateNode;
}
}

parentNode.children.push(node);
}

return rootNode;
}

interface TreeNode {
instance: Base;
children: TreeNode[];
}

/**
* Log a tree node and its children using console groups.
*/
function logNode(node: TreeNode): void {
const { instance } = node;
const name = instance.$config.name;

Check warning on line 64 in packages/js-toolkit/helpers/logTree.ts

View workflow job for this annotation

GitHub Actions / code-quality

eslint(no-unused-vars)

Variable 'name' is declared but never used. Unused variables should start with a '_'.
const mounted = instance.$isMounted;
const status = mounted ? '●' : 'β—‹';
const label = `${status} ${instance.$id}`;

if (node.children.length > 0) {
console.groupCollapsed(label, instance.$el);
for (const child of node.children) {
logNode(child);
}
console.groupEnd();
} else {
console.log(label, instance.$el);
}
}

/**
* Log the component tree starting from the given instance.
*
* Uses the global instance registry and DOM containment to build the tree,
* without relying on the deprecated `$children` API.
*
* @param {Base} instance The root component instance.
* @example
* ```js
* import { createApp, logTree } from '@studiometa/js-toolkit';
*
* const useApp = createApp(App);
* useApp().then((app) => logTree(app));
* ```
*/
export function logTree(instance: Base): void {
const tree = buildTree(instance);
console.group(`🌳 ${instance.$config.name}`);
for (const child of tree.children) {
logNode(child);
}
console.groupEnd();
}
1 change: 1 addition & 0 deletions packages/tests/helpers/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ test('helpers exports', () => {
"importWhenPrefersMotion",
"importWhenVisible",
"isDirectChild",
"logTree",
"queryComponent",
"queryComponentAll",
"registerComponent",
Expand Down
Loading
Loading