Skip to content

Commit

Permalink
Add back complete logic
Browse files Browse the repository at this point in the history
  • Loading branch information
SamyPesse committed Feb 3, 2025
1 parent 35c01ec commit 669354a
Showing 1 changed file with 30 additions and 14 deletions.
44 changes: 30 additions & 14 deletions packages/runtime/src/components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,11 @@ export function createComponent<
*/
action?: RuntimeCallback<
[ComponentInstance<Props, State>, ComponentAction<Action>],
Promise<{ props?: Props; state?: State } | undefined>,
Promise<
| { type?: 'element'; props?: Props; state?: State }
| { type: 'complete'; returnValue?: PlainObject }
| undefined
>,
Context
>;

Expand Down Expand Up @@ -129,29 +133,41 @@ export function createComponent<
dynamicState: (key) => ({ $state: key }),
};

const respondWithOutput = (output: ContentKitRenderOutput) => {
return new Response(JSON.stringify(output), {
headers: {
'Content-Type': 'application/json',
...(cache
? {
// @ts-ignore - I'm not sure how to fix this one with TS
'Cache-Control': `max-age=${cache.maxAge}`,
}
: {}),
},
});
};

if (action && component.action) {
instance = { ...instance, ...(await component.action(instance, action, context)) };
const actionResult = await component.action(instance, action, context);

// If the action is complete, return the result directly. No need to render the component.
if (actionResult?.type === 'complete') {
return respondWithOutput(actionResult);
}

instance = { ...instance, ...actionResult };
}

const element = await component.render(instance, context);

const output: ContentKitRenderOutput = {
type: 'element',
state: instance.state,
props: instance.props,
element,
};

return new Response(JSON.stringify(output), {
headers: {
'Content-Type': 'application/json',
...(cache
? {
// @ts-ignore - I'm not sure how to fix this one with TS
'Cache-Control': `max-age=${cache.maxAge}`,
}
: {}),
},
});
return respondWithOutput(output);
},
};
}
}

0 comments on commit 669354a

Please sign in to comment.