51 lines
1.4 KiB
TypeScript
51 lines
1.4 KiB
TypeScript
import "../core/metadata.ts";
|
|
import { defineMetadata, getMetadata } from "../core/metadata.ts";
|
|
|
|
export const COMPONENT_METADATA_KEY = "muddle:component";
|
|
|
|
export interface ComponentOptions {
|
|
/** Name used inside the templates, defaults to the class name. */
|
|
name?: string;
|
|
/**
|
|
* Renders the component after the page, the response is streamed.
|
|
*/
|
|
deferred?: boolean;
|
|
description?: string;
|
|
params?: Record<string, string>;
|
|
}
|
|
|
|
/** Runtime description of a server component. */
|
|
export interface ComponentMetadata {
|
|
name: string;
|
|
deferred: boolean;
|
|
description?: string;
|
|
params?: Record<string, string>;
|
|
}
|
|
|
|
/** Declares a server component. */
|
|
export function Component(options: ComponentOptions = {}): ClassDecorator {
|
|
return (target) => {
|
|
const metadata: ComponentMetadata = {
|
|
name: options.name ?? target.name,
|
|
deferred: options.deferred === true,
|
|
description: options.description,
|
|
params: options.params,
|
|
};
|
|
defineMetadata(COMPONENT_METADATA_KEY, metadata, target as object);
|
|
return target;
|
|
};
|
|
}
|
|
|
|
/** Reads the metadata of a server component. */
|
|
export function getComponentMetadata(
|
|
target: object,
|
|
): ComponentMetadata | undefined {
|
|
return getMetadata(COMPONENT_METADATA_KEY, target) as
|
|
| ComponentMetadata
|
|
| undefined;
|
|
}
|
|
|
|
/** `true` when the class is a server component. */
|
|
export function isComponent(target: object): boolean {
|
|
return getComponentMetadata(target) !== undefined;
|
|
}
|