Files
webstudio/packages/react-sdk/src/hook.ts
T
Bogdan Chadkin bdf4463098 fix: set proper default value in radix with content block (#4937)
User reported in discord.

Radix components like accordion does not open first item by default when
use with content block. The reason was in our default detection.

We used indexes within ancestor and when put item inside of content
block template it gets 0 but not rendered.

Here improved the logic to reset index when render inside of block
template.

<img width="837" alt="Screenshot 2025-03-01 at 21 14 09"
src="https://github.com/user-attachments/assets/788df39a-b7c5-466b-a80e-09cc40de9e3f"
/>
2025-03-04 18:26:29 +07:00

58 lines
1.4 KiB
TypeScript

import type { IndexesWithinAncestors, Instance, Prop } from "@webstudio-is/sdk";
export type InstanceData = {
id: Instance["id"];
instanceKey: string;
component: Instance["component"];
};
/**
* Hooks are subscriptions to builder events
* with limited way to interact with it.
* Called independently from components.
*/
export type HookContext = {
indexesWithinAncestors: IndexesWithinAncestors;
getPropValue: (instanceData: InstanceData, propName: Prop["name"]) => unknown;
setMemoryProp: (
instanceData: InstanceData,
propName: Prop["name"],
value: unknown
) => void;
};
export type InstancePath = InstanceData[];
type NavigatorEvent = {
/**
* List of instances from selected to the root
*/
instancePath: InstancePath;
};
export type Hook = {
onNavigatorSelect?: (context: HookContext, event: NavigatorEvent) => void;
onNavigatorUnselect?: (context: HookContext, event: NavigatorEvent) => void;
};
/**
* Find closest matching instance by component name
* by lookup in instance path
*/
export const getClosestInstance = (
instancePath: InstancePath,
currentInstance: InstanceData,
closestComponent: InstanceData["component"]
) => {
let matched = false;
for (const instance of instancePath) {
if (currentInstance === instance) {
matched = true;
}
if (matched && instance.component === closestComponent) {
return instance;
}
}
};