Saltearse al contenido

Haciendo complementos útiles

Crear un complemento para StudioCMS es una forma poderosa de extender la funcionalidad de StudioCMS. Los complementos proporcionan una manera simple y flexible de agregar nuevas características a tu proyecto StudioCMS. A continuación se muestra un ejemplo básico de cómo crear un complemento de StudioCMS y cómo funciona.

Para comenzar, necesitarás crear un nuevo complemento de StudioCMS. A continuación se muestra un ejemplo básico de la estructura de archivos para un complemento de StudioCMS:

  • package.json
  • Directorysrc
    • index.ts
    • Directoryroutes
      • […slug].astro
    • Directorydashboard-grid-items
      • MyPluginGridItem.astro

En el archivo principal src/index.ts, definirás el complemento de StudioCMS. A continuación se muestra un ejemplo de cómo definir un complemento de StudioCMS que incluye una Integración Astro para crear un ejemplo simple de blog:

index.ts
import {
function definePlugin(options: StudioCMSPluginOptions): StudioCMSPlugin

Defines a plugin for StudioCMS.

@paramoptions - The configuration options for the plugin.

@returnsThe plugin configuration.

definePlugin
} from 'studiocms/plugins';
import {
(alias) interface AstroIntegration
import AstroIntegration
AstroIntegration
} from 'astro';
import {
const addVirtualImports: HookUtility<"astro:config:setup", [{
name: string;
imports: Imports;
__enableCorePowerDoNotUseOrYouWillBeFired?: boolean;
}], void>

Creates a Vite virtual module and updates the Astro config. Virtual imports are useful for passing things like config options, or data computed within the integration.

@paramparams

@paramoptions

@paramoptions.name

@paramoptions.imports

@seehttps://astro-integration-kit.netlify.app/utilities/add-virtual-imports/

@example

// my-integration/index.ts
import { addVirtualImports } from "astro-integration-kit";
addVirtualImports(params, {
name: 'my-integration',
imports: {
'virtual:my-integration/config': `export default ${ JSON.stringify({foo: "bar"}) }`,
},
});

This is then readable anywhere else in your integration:

// myIntegration/src/component/layout.astro
import config from "virtual:my-integration/config";
console.log(config.foo) // "bar"

addVirtualImports
,
const createResolver: (_base: string) => {
resolve: (...path: Array<string>) => string;
}

Allows resolving paths relatively to the integration folder easily. Call it like this:

@param_base - The location you want to create relative references from. import.meta.url is usually what you'll want.

@seehttps://astro-integration-kit.netlify.app/core/create-resolver/

@example

const { resolve } = createResolver(import.meta.url);
const pluginPath = resolve("./plugin.ts");

This way, you do not have to add your plugin to your package.json exports.

createResolver
} from 'astro-integration-kit';
// Define the options for the complemento and integration
interface
interface Options
Options
{
Options.route: string
route
: string;
}
export function
function studioCMSPageInjector(options: Options): StudioCMSPlugin
studioCMSPageInjector
(
options: Options
options
:
interface Options
Options
) {
// Resuelve la ruta al archivo actual
const {
const resolve: (...path: Array<string>) => string
resolve
} =
function createResolver(_base: string): {
resolve: (...path: Array<string>) => string;
}

Allows resolving paths relatively to the integration folder easily. Call it like this:

@param_base - The location you want to create relative references from. import.meta.url is usually what you'll want.

@seehttps://astro-integration-kit.netlify.app/core/create-resolver/

@example

const { resolve } = createResolver(import.meta.url);
const pluginPath = resolve("./plugin.ts");

This way, you do not have to add your plugin to your package.json exports.

createResolver
(import.

The type of import.meta.

If you need to declare that a given property exists on import.meta, this type may be augmented via interface merging.

meta
.
ImportMeta.url: string

The absolute file: URL of the module.

url
);
// Define la Integración Astro
function
function (local function) myIntegration(options: Options): AstroIntegration
myIntegration
(
options: Options
options
:
interface Options
Options
):
(alias) interface AstroIntegration
import AstroIntegration
AstroIntegration
{
const
const route: string
route
= `/${
options: Options
options
?.
Options.route: string
route
|| 'my-plugin'}`;
return {
AstroIntegration.name: string

The name of the integration.

name
: 'my-astro-integration',
AstroIntegration.hooks: {
'astro:config:setup'?: (options: {
config: AstroConfig;
command: "dev" | "build" | "preview" | "sync";
isRestart: boolean;
updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig;
addRenderer: (renderer: AstroRenderer) => void;
addWatchFile: (path: URL | string) => void;
injectScript: (stage: InjectedScriptStage, content: string) => void;
injectRoute: (injectRoute: InjectedRoute) => void;
addClientDirective: (directive: ClientDirectiveConfig) => void;
addDevToolbarApp: (entrypoint: DevToolbarAppEntry) => void;
addMiddleware: (mid: AstroIntegrationMiddleware) => void;
createCodegenDir: () => URL;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
... 10 more ...;
'astro:routes:resolved'?: (options: {
routes: IntegrationResolvedRoute[];
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
} & Partial<...>

The different hooks available to extend.

hooks
: {
"astro:config:setup": (
params: {
config: AstroConfig;
command: "dev" | "build" | "preview" | "sync";
isRestart: boolean;
updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig;
... 8 more ...;
logger: AstroIntegrationLogger;
}
params
) => {
const {
const injectRoute: (injectRoute: InjectedRoute) => void
injectRoute
} =
params: {
config: AstroConfig;
command: "dev" | "build" | "preview" | "sync";
isRestart: boolean;
updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig;
... 8 more ...;
logger: AstroIntegrationLogger;
}
params
;
// Inyecta la ruta para el complemento
const injectRoute: (injectRoute: InjectedRoute) => void
injectRoute
({
entrypoint: string | URL
entrypoint
:
const resolve: (...path: Array<string>) => string
resolve
('./routes/[...slug].astro'),
pattern: string
pattern
: `/${
const route: string
route
}/[...slug]`,
prerender?: boolean
prerender
: false,
})
function addVirtualImports(params: {
config: AstroConfig;
command: "dev" | "build" | "preview" | "sync";
isRestart: boolean;
updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig;
... 8 more ...;
logger: AstroIntegrationLogger;
}, args_0: {
...;
}): void

Creates a Vite virtual module and updates the Astro config. Virtual imports are useful for passing things like config options, or data computed within the integration.

@paramparams

@paramoptions

@paramoptions.name

@paramoptions.imports

@seehttps://astro-integration-kit.netlify.app/utilities/add-virtual-imports/

@example

// my-integration/index.ts
import { addVirtualImports } from "astro-integration-kit";
addVirtualImports(params, {
name: 'my-integration',
imports: {
'virtual:my-integration/config': `export default ${ JSON.stringify({foo: "bar"}) }`,
},
});

This is then readable anywhere else in your integration:

// myIntegration/src/component/layout.astro
import config from "virtual:my-integration/config";
console.log(config.foo) // "bar"

addVirtualImports
(
params: {
config: AstroConfig;
command: "dev" | "build" | "preview" | "sync";
isRestart: boolean;
updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig;
... 8 more ...;
logger: AstroIntegrationLogger;
}
params
, {
name: string
name
: 'my-astro-integration',
imports: Imports
imports
: {
'myplugin:config': `
export const options = ${
var JSON: JSON

An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.

JSON
.
JSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)

Converts a JavaScript value to a JavaScript Object Notation (JSON) string.

@paramvalue A JavaScript value, usually an object or array, to be converted.

@paramreplacer A function that transforms the results.

@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.

stringify
({
route: string
route
})};
export default options;
`,
}
})
}
}
}
}
// Define el complemento de StudioCMS
return
function definePlugin(options: StudioCMSPluginOptions): StudioCMSPlugin

Defines a plugin for StudioCMS.

@paramoptions - The configuration options for the plugin.

@returnsThe plugin configuration.

definePlugin
({
identifier: string
identifier
: 'my-plugin',
name: string
name
: 'My Plugin',
studiocmsMinimumVersion: string
studiocmsMinimumVersion
: '0.1.0-beta.8',
integration?: AstroIntegration | AstroIntegration[] | undefined
integration
:
function (local function) myIntegration(options: Options): AstroIntegration
myIntegration
(
options: Options
options
), // Opcional, pero recomendado
// Define los enlaces de navegación del frontend para el complemento (opcional)
// Esto es útil si estás usando los ayudantes de navegación de StudioCMS incorporados en tu diseño,
// como cuando usas el complemento `@studiocms/blog`.
frontendNavigationLinks?: {
label: string;
href: string;
}[] | undefined
frontendNavigationLinks
: [{
label: string
label
: 'Title here',
href: string
href
:
options: Options
options
?.
Options.route: string
route
|| 'my-plugin' }],
// Cuando estes creando pageTypes, también puedes definir un `pageContentComponent` si tu complemento requiere un editor de contenido personalizado.
// pageTypes: [{ identifier: 'my-plugin', label: 'Blog Post (My plugin)', pageContentComponent: resolve('./components/MyContentEditor.astro') }],
// In this example we are okay using the default content editor (markdown).
pageTypes?: {
label: string;
identifier: string;
description?: string | undefined;
fields?: ({
input: "checkbox";
label: string;
name: string;
required?: boolean | undefined;
readOnly?: boolean | undefined;
color?: "danger" | "success" | "warning" | "info" | "primary" | "mono" | undefined;
defaultChecked?: boolean | undefined;
size?: "sm" | "md" | "lg" | undefined;
} | {
input: "input";
label: string;
name: string;
type?: "number" | "search" | "email" | "tel" | "text" | "url" | "password" | undefined;
required?: boolean | undefined;
readOnly?: boolean | undefined;
placeholder?: string | undefined;
defaultValue?: string | undefined;
} | {
input: "textarea";
label: string;
name: string;
required?: boolean | undefined;
readOnly?: boolean | undefined;
placeholder?: string | undefined;
defaultValue?: string | undefined;
} | {
input: "radio";
label: string;
name: string;
options: {
label: string;
value: string;
disabled?: boolean | undefined;
}[];
required?: boolean | undefined;
readOnly?: boolean | undefined;
color?: "danger" | "success" | "warning" | "info" | "primary" | "mono" | undefined;
defaultValue?: string | undefined;
direction?: "horizontal" | "vertical" | undefined;
} | {
input: "select";
label: string;
name: string;
options ...
pageTypes
: [{
identifier: string
identifier
: 'my-plugin',
label: string
label
: 'Blog Post (My plugin)' }],
// Definir los elementos de la cuadrícula para el panel
// Estos son los elementos que serán mostrados en el panel de StudioCMS
// Puedes definir tantos elementos como desees
// En este ejemplo, estamos definiendo un solo elemento, que tiene un span de 2 y requiere el permiso 'editor' e inyecta un componente Astro que reemplaza el elemento personalizado de html plano.
dashboardGridItems?: GridItemInput[] | undefined
dashboardGridItems
: [
{
GridItemInput.name: string

The name of the grid item.

name
: 'example',
GridItemInput.span: 1 | 2 | 3

The span of the grid item, which can be 1, 2, or 3.

span
: 2,
GridItemInput.variant: "default" | "filled"

The variant of the grid item, which can be 'default' or 'filled'.

variant
: 'default',
GridItemInput.requiresPermission?: "editor" | "owner" | "admin" | "visitor"

The required permission level to view the grid item. Optional. Can be 'owner', 'admin', 'editor', or 'visitor'.

requiresPermission
: 'editor',
GridItemInput.header?: {
title: string;
icon?: HeroIconName;
}

The header of the grid item. Optional.

header
: {
title: string

The title of the header.

title
: 'Example',
icon?: "bolt" | "code-bracket-solid" | "code-bracket-square-solid" | "exclamation-circle" | "exclamation-circle-solid" | "exclamation-triangle" | "exclamation-triangle-solid" | ... 1280 more ... | "x-mark-solid"

The icon of the header. Optional.

icon
: 'bolt' },
GridItemInput.body?: {
html: string;
components?: Record<string, string>;
sanitizeOpts?: SanitizeOptions;
}

The body of the grid item. Optional.

body
: {
// Siempre usa html plano sin `-` o caracteres especiales en las etiquetas, se reemplazarán con el componente Astro y este HTML nunca se renderizará
html: string

The HTML content of the body.

html
: '<examplegriditem></examplegriditem>',
components?: Record<string, string>

The components within the body. Optional.

components
: {
// Inyecta el componente de Astro para reemplazar el elemento personalizado en html plano
examplegriditem: string
examplegriditem
:
const resolve: (...path: Array<string>) => string
resolve
('./dashboard-grid-items/MycomplementoGridItem.astro')
}
}
}
],
});
}

El ejemplo anterior define un complemento de StudioCMS que incluye una Integración Astro para crear un ejemplo simple de blog. El complemento incluye una ruta que se inyecta en el proyecto StudioCMS y un elemento de cuadrícula que se muestra en el Panel de Control de StudioCMS.

Para más información sobre cómo crear una Integración Astro, consulta el Kit de Integración Astro^ y la documentación de Integraciones de Astro^.

En el archivo src/routes/[...slug].astro, definirás la ruta para el complemento. A continuación se muestra un ejemplo de cómo definir una ruta para el complemento, lo dividiremos en dos partes, la primera parte es el frontmatter (entre las marcas ---), y la segunda parte es la plantilla HTML que se coloca debajo del segundo ---.

Frontmatter
import {
const StudioCMSRenderer: any
StudioCMSRenderer
} from 'studiocms:renderer';
import
const sdk: {
addPageToFolderTree: (tree: FolderNode[], folderId: string, newPage: FolderNode) => FolderNode[];
... 28 more ...;
REST_API: {
tokens: {
get: (userId: string) => Promise<{
description: string | null;
userId: string;
id: string;
key: string;
creationDate: Date;
}[]>;
new: (userId: string, description: string) => Promise<{
description: string | null;
userId: string;
id: string;
key: string;
creationDate: Date;
}>;
delete: (userId: string, tokenId: string) => Promise<void>;
verify: (key: string) => Promise<false | {
userId: string;
key: string;
rank: string;
}>;
};
};
}
sdk
from 'studiocms:sdk';
import
const config: {
route: string;
}
config
from 'myplugin:config';
const
const makeRoute: (slug: string) => string
makeRoute
= (
slug: string
slug
: string) => {
return `/${
const config: {
route: string;
}
config
.
route: string
route
}/${
slug: string
slug
}`;
}
// 'my-plugin' aquí se usa como identificador para
// el pageType de la definición del complemento
const
const pages: CombinedPageData[]
pages
= await
const sdk: {
addPageToFolderTree: (tree: FolderNode[], folderId: string, newPage: FolderNode) => FolderNode[];
... 28 more ...;
REST_API: {
tokens: {
get: (userId: string) => Promise<{
description: string | null;
userId: string;
id: string;
key: string;
creationDate: Date;
}[]>;
new: (userId: string, description: string) => Promise<{
description: string | null;
userId: string;
id: string;
key: string;
creationDate: Date;
}>;
delete: (userId: string, tokenId: string) => Promise<void>;
verify: (key: string) => Promise<false | {
userId: string;
key: string;
rank: string;
}>;
};
};
}
sdk
.
type GET: {
database: {
users: () => Promise<CombinedUserData[]>;
pages: (includeDrafts?: boolean, tree?: FolderNode[]) => Promise<CombinedPageData[]>;
config: () => Promise<{
id: number;
title: string;
description: string;
defaultOgImage: string | null;
... 5 more ...;
gridItems: unknown;
} | undefined>;
folders: () => Promise<{
...;
}[]>;
};
databaseEntry: {
users: {
byId: (id: string) => Promise<CombinedUserData | undefined>;
byUsername: (username: string) => Promise<CombinedUserData | undefined>;
byEmail: (email: string) => Promise<CombinedUserData | undefined>;
};
pages: {
byId: (id: string, tree?: FolderNode[]) => Promise<CombinedPageData | undefined>;
bySlug: (slug: string, tree?: FolderNode[]) => Promise<CombinedPageData | undefined>;
};
folder: (id: string) => Promise<{
...;
} | undefined>;
};
databaseTable: {
users: () => Promise<{
name: string;
username: string;
email: string | null;
id: string;
url: string | null;
avatar: string | null;
password: string | null;
updatedAt: Date | null;
createdAt: Date | null;
}[]>;
oAuthAccounts: () => Promise<{
provider: string;
providerUserId: string;
userId: string;
}[]>;
sessionTable: () => ...
GET
.
packagePages: (packageName: string, tree?: FolderNode[]) => Promise<CombinedPageData[]>
packagePages
('my-complemento');
const {
const slug: string | undefined
slug
} =
const Astro: AstroGlobal<Record<string, any>, AstroComponentFactory, Record<string, string | undefined>>
Astro
.
AstroGlobal<Record<string, any>, AstroComponentFactory, Record<string, string | undefined>>.params: Record<string, string | undefined>

Parameters passed to a dynamic page generated using getStaticPaths

Example usage:

---
export async function getStaticPaths() {
return [
{ params: { id: '1' } },
];
}
const { id } = Astro.params;
---
<h1>{id}</h1>

Astro reference

params
;
const
const page: CombinedPageData | undefined
page
=
const pages: CombinedPageData[]
pages
.
Array<CombinedPageData>.find(predicate: (value: CombinedPageData, index: number, obj: CombinedPageData[]) => unknown, thisArg?: any): CombinedPageData | undefined (+1 overload)

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

@parampredicate find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.

@paramthisArg If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

find
((
page: CombinedPageData
page
) =>
page: CombinedPageData
page
.
slug: string
slug
===
const slug: string | undefined
slug
|| '');
Template
{
slug && page ? (
<div>
<h1>{page.title}</h1>
<StudioCMSRenderer content={page.defaultContent?.content || ''} />
</div>
) : (
<div>
<h1>Mi complemento</h1>
<ul>
{pages.length > 0 && pages.map((page) => (
<li>
<a href={makeRoute(page.slug)}>{page.title}</a>
</li>
))}
</ul>
</div>
)
}

El ejemplo anterior define una ruta dinámica^ para el complemento que muestra una lista de entradas de blog cuando no se proporciona un slug y muestra el contenido de una entrada de blog cuando se proporciona un slug.

En el archivo src/dashboard-grid-items/MyPluginGridItem.astro, definirás el elemento de cuadrícula para el complemento. A continuación se muestra un ejemplo de cómo definir un elemento de cuadrícula para el complemento:

MyPluginGridItem.astro
---
import { StudioCMSRoutes } from 'studiocms:lib';
import sdk from 'studiocms:sdk';
// 'my-plugin' aqui es usado como el identificador para
// el pageType de la definición del complemento
const pages = await sdk.GET.packagePages('my-complemento');
// Consigue las últimas 5 páginas actualizadas en los últimos 30 días
const recentlyUpdatedPages = pages
.filter((page) => {
const now = new Date();
const thirtyDaysAgo = new Date(now.setDate(now.getDate() - 30));
return new Date(page.updatedAt) > thirtyDaysAgo;
})
.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
.slice(0, 5);
---
<div>
<h2>Páginas Actualizadas Recientemente</h2>
<ul>
{recentlyUpdatedPages.length > 0 && recentlyUpdatedPages.map((page) => (
<li>
<a href={StudioCMSRoutes.mainLinks.contentManagementEdit + `?edit=${page.id}`}>{page.title}</a>
</li>
))}
</ul>
</div>

El ejemplo anterior define un elemento de cuadrícula para el complemento que muestra las 5 páginas actualizadas más recientemente de los últimos 30 días. El elemento de cuadrícula incluye una lista de enlaces a la página de edición de gestión de contenido para cada página.

Si deseas usar los ayudantes de navegación incorporados de StudioCMS en tu proyecto, similar a como lo hace el complemento @studiocms/blog, puedes crear un componente personalizado Navigation.astro:

Navigation.astro
---
import { StudioCMSRoutes } from 'studiocms:lib';
import studioCMS_SDK from 'studiocms:sdk/cache';
import { frontendNavigation } from 'studiocms:complemento-helpers';
// Define las props para el componente de navegación
interface Props {
topLevelLinkCount?: number;
};
// Consigue el enlace de nivel superior de las props
const { topLevelLinkCount = 3 } = Astro.props;
// Consigue la configuración del sitio y la lista de páginas
const config = (await studioCMS_SDK.GET.siteConfig()).data;
// Consigue el título del sitio de la configuración
const { title } = config || { title: 'StudioCMS' };
// Consigue la URL principal del sitio
const {
mainLinks: { baseSiteURL },
} = StudioCMSRoutes;
// Define las props de enlace para la navegación
type LinkProps = {
text: string;
href: string;
};
// Define los enlaces para la navegación
const links: LinkProps[] = await frontendNavigation();
---
{/* Si no hay elementos dropdown */}
{ ( links.length < topLevelLinkCount || links.length === topLevelLinkCount ) && (
<div class="navigation">
<div class="title"><a href={baseSiteURL}>{title}</a></div>
<div class="mini-nav">
<button>Menu</button>
<div class="mini-nav-content">
{
links.map(({ text, href }) => (
<a {href}>{text}</a>
))
}
</div>
</div>
{
links.map(({ text, href }) => (
<a class="links" {href}>{text}</a>
))
}
</div>
) }
{/* Si hay elementos dropdown */}
{ links.length > topLevelLinkCount && (
<div class="navigation">
<div class="title"><a href={baseSiteURL}>{title}</a></div>
<div class="mini-nav">
<button>Menu</button>
<div class="mini-nav-content">
{
links.map(({ text, href }) => (
<a {href}>{text}</a>
))
}
</div>
</div>
{
links.slice(0, topLevelLinkCount).map(({ text, href }) => (
<a class="links" {href}>{text}</a>
))
}
<div class="dropdown">
<button>More ▼</button>
<div class="dropdown-content">
{ links.slice(topLevelLinkCount).map(({ text, href }) => (
<a {href}>{text}</a>
)) }
</div>
</div>
</div>
) }

El ejemplo anterior define un componente personalizado Navigation.astro que utiliza los ayudantes de navegación incorporados de StudioCMS para crear un menú de navegación para el proyecto. El componente incluye enlaces a la URL principal del sitio, la página de índice y cualquier otra página que esté configurada para mostrarse en la navegación.

Todo lo que necesitas hacer es agregar algunos estilos, y tendrás un menú de navegación completamente funcional que funciona con los ayudantes de navegación incorporados de StudioCMS.