portable-text-serialization

Renderize e serialize Portable Text para React, Svelte, Vue, Astro, HTML, Markdown e texto simples. Use ao implementar a renderização de Portable Text em qualquer frontend…

npx skills add https://github.com/sanity-io/agent-toolkit --skill portable-text-serialization

Portable Text Serialization

Render Portable Text content across frameworks using the @portabletext/* library family. Each library follows the same component-mapping pattern: you provide a components object that maps PT node types to framework-specific renderers.

Portable Text Structure (Quick Reference)

PT is an array of blocks. Each block has _type, optional style, children (spans), markDefs, listItem, and level.

Root array
├── block (_type: "block")
│   ├── style: "normal" | "h1" | "h2" | "blockquote" | ...
│   ├── children: [span, span, ...]
│   │   └── span: { _type: "span", text: "...", marks: ["strong", "<markDefKey>"] }
│   ├── markDefs: [{ _key, _type: "link", href: "..." }, ...]
│   ├── listItem: "bullet" | "number" (optional)
│   └── level: 1, 2, 3... (optional, for nested lists)
├── custom block (_type: "image" | "code" | any custom type)
└── ...more blocks

Marks come in two forms:

  • Decorators: string values in marks[] like "strong", "em", "underline", "code"
  • Annotations: keys in marks[] referencing entries in markDefs[] (e.g., links, internal references)

Component Mapping Pattern (All Frameworks)

Every @portabletext/* library accepts a components object with these keys:

KeyRendersProps/Data
typesCustom block/inline types (image, code, CTA)value (the block data)
marksDecorators + annotationschildren + value (mark data)
blockBlock styles (h1, normal, blockquote)children
listList wrappers (ul, ol)children
listItemList itemschildren
hardBreakLine breaks within a block

Framework-Specific Rules

Read the rule file matching your framework:

  • React / Next.js: rules/react.md@portabletext/react or next-sanity
  • Svelte / SvelteKit: rules/svelte.md@portabletext/svelte
  • Vue / Nuxt: rules/vue.md@portabletext/vue
  • Astro: rules/astro.mdastro-portabletext
  • HTML (server-side): rules/html.md@portabletext/to-html
  • Markdown: rules/markdown.md@portabletext/markdown
  • Plain text extraction: rules/plain-text.md@portabletext/toolkit

Additional Community Serializers

These are listed on portabletext.org but don't have dedicated rule files:

TargetPackage
React Native@portabletext/react-native-portabletext
React PDF@portabletext/react-pdf-portabletext
Solidsolid-portabletext
Qwikportabletext-qwik
Shopify Liquidportable-text-to-liquid
PHPsanity-php (SanityBlockContent class)
Pythonportabletext-html
C# / .NETdotnet-portable-text
Dart / Flutterflutter_sanity_portable_text

Common Patterns (All Frameworks)

Custom Types Need Explicit Components

PT renderers only handle standard blocks by default. Custom types (image, code, callToAction, etc.) require explicit component mappings — they won't render otherwise.

Keep Components Object Stable

In React/Vue, define components outside the render function or memoize it. Recreating on every render causes unnecessary re-renders.

Handle Missing Components Gracefully

All libraries accept onMissingComponent to control behavior when encountering unknown types:

  • false — suppress warnings
  • Custom function — log or report

Querying PT with GROQ

Always expand references inside custom blocks:

body[]{
  ...,
  _type == "image" => {
    ...,
    asset->
  },
  markDefs[]{
    ...,
    _type == "internalLink" => {
      ...,
      "slug": @.reference->slug.current
    }
  }
}

Mais skills de sanity-io

sanity-migration
sanity-io
Planeja, implementa e revisa migrações de outros CMSs e sistemas de conteúdo para o Sanity. Use ao migrar ou replataformar para o Sanity a partir de AEM, Adobe Experience Manager, Contentful, Strapi, Webflow, WordPress, Payload, Drupal, arquivos Markdown/MDX/frontmatter, exportações WXR/XML, APIs de CMS, dumps de banco de dados, HTML estático, ou ao projetar fluxos de extração, transformação, conversão de Portable Text, migração de ativos, redirecionamentos, validação e cutover.
officialdevelopmentdatabase
create-agent-with-sanity-context
sanity-io
Construa agentes de IA com acesso estruturado ao conteúdo do Sanity via Agent Context. Use ao configurar um chatbot com Sanity, conectando um assistente de IA ao Sanity…
official
dial-your-context
sanity-io
Sessão interativa para criar conteúdo do campo Instruções para um Context MCP do Sanity Agent. Use esta habilidade sempre que usuários mencionarem ajuste de contexto do agente, melhoria…
official
optimize-agent-prompt
sanity-io
Ajuste seu agente de contexto do Sanity Agent por meio de conversa guiada. Transforma dados de exploração em instruções prontas para produção e cria um prompt de sistema…
official
shape-your-agent
sanity-io
Sessão interativa para criar um prompt de sistema para um agente de IA alimentado pelo Sanity Agent Context MCP. Use esta habilidade quando os usuários quiserem definir a personalidade do agente,…
official
content-experimentation-best-practices
sanity-io
Orientação estruturada para projetar, executar e analisar experimentos de conteúdo visando melhorar conversão e engajamento. Abrange frameworks de hipóteses, seleção de métricas, cálculo de tamanho amostral e testes de significância estatística em experimentos A/B e multivariados. Inclui recursos detalhados sobre valores-p, intervalos de confiança, análise de poder e métodos bayesianos para interpretação de resultados. Fornece padrões de integração com CMS para gerenciar variantes no nível de campo e conectar sistemas externos...
official
content-modeling-best-practices
sanity-io
Orientação para modelagem de conteúdo estruturado voltada ao design de esquemas, reutilização e entrega multicanal. Aborda princípios fundamentais: tratar conteúdo como dados, e não como páginas; manter fontes únicas de verdade; projetar para canais futuros; e otimizar fluxos de trabalho editoriais. Inclui estruturas de decisão para referências versus objetos incorporados, separação de responsabilidades e padrões de reutilização de conteúdo. Oferece orientação sobre taxonomia e classificação para abordagens planas, hierárquicas e facetadas. Aplica-se a...
official
portable-text-conversion
sanity-io
Converta conteúdo HTML e Markdown em blocos Portable Text para Sanity. Use ao migrar conteúdo de CMSs legados, importando HTML ou Markdown para o Sanity,…
official