Composables

Vue composables for collections, UI resolution, navigation, and content

In addition to the collection of utilities, DocLayer offers a set of composables that encapsulate reusable logic and state management across the application. These composables provide type-safe, reactive interfaces for common operations such as data fetching, UI resolution, navigation handling, and content manipulation.

Global Context

All of these composables are auto-imported, globally accessible and can be used with application-based or content-related components without needing to import them. Remember, outside of the components context (setup function), composables can't be used, as they may contains Vue/Nuxt-specific APIs.

Bellow you'll find a comprehensive list of these utilities with a brief descriptions of their functionality. Where applicable, with examples that illustrate on how to use each effectively.


useAdapterData

Collects and provides global configuration for all registered adapters.

Example:

<script setup lang="ts">// Retrieve Newsletter adapter dataconst { newsletter } = useAdapterData();// Retrieve Newsletter adapter data within the server contextconst { newsletter } = useAdapterData(event);// ... or assign/overwrite Newsletter adapter datauseAdapterData({  newsletter: { key: 'value' },});</script>
import type { GlobalInstance, Prettify } from '@vuehouse/dl/types';import type { H3Event } from 'h3';type AdapterData = Prettify<GlobalInstance['__DL__']['adapterData']>;declare function setData(instance: GlobalInstance, data: AdapterData): () => void;declare function useAdapterData(): AdapterData;declare function useAdapterData(data: AdapterData): ReturnType<typeof setData>;declare function useAdapterData(event: H3Event): AdapterData;declare function useAdapterData(adapterData?: AdapterData): AdapterData | ReturnType<typeof setData>;

When creating custom adapters, you can define global configurations for them, such as public API keys or external API endpoints. This configuration is useful when invoking an adapter within components or creating dedicated server handlers. With this composable, you can easily access these configuration values as they are shared between the client and server. However, in some isolated contexts (such as serverless functions), you may need to pass the event object to the composable because the global instance might not be available or shared in that environment.

On how to build custom adapters and use its data you can read more here.


useComponentUi

Resolves component UI variants for custom styling configurations.

Example:

<script setup lang="ts">const { resolveUi } = useComponentUi();// Resolve custom UI with defaultsconst finalUi = await resolveUi(customUi, defaultUi);</script>
<script setup lang="ts">const { resolvePropsUi } = useComponentUi();</script><template>  <DlWrapper :ui="resolvePropsUi(props)">    <!-- component body -->  </DlWrapper></template>
type UiCallback = (classes?: string) => string;type UiRecord<Key extends string, Variant> = { [key in Key]-?: Variant };type UiResolvedRecord<Variant extends UiRecord<string, string>> = {  [key in keyof Variant]: key extends 'base' ? Variant[key] : { base: Variant[key] };};declare function useComponentUi(): {  resolveUi: <UI extends UiRecord<string, string>, Defaults extends UiRecord<string, string> = UI>(    ui: UI,    defaults: Defaults,  ) => Promise<UiResolvedRecord<typeof defaults>>;  resolvePropsUi: <Props extends UiProps<any>>(props: Props) => ReturnType<Props['ui']>;};

Composable provides two key functions:

  • resolveUi - Merges custom UI classes (Markdown-added) with component's default ones. It's used by the UiWrapper component to apply consistent theming and UI resolving.
  • resolvePropsUi - Merges UI props: inline UI (iui) with default block UI (ui), enabling flexible components theming.

If you're using DlWrapper for your components, UI resolving is integrated by default, so you may not need to add it manually. To learn more about managing UI with Tailwind classes inside components, see the component building guide.


useContentGuard

Guards content-driven components and pages.

Example:

<script setup lang="ts">const props = defineProps<{ type: string }>();useContentGuard(!['info', 'note', 'warning'].includes(props.type), {  source: 'DlCallout',  message: 'Invalid callout type. Accepted values are: info, note, warning.',});</script>
import type { Function } from '@vuehouse/dl/types';type Config = {  source: string;  message: string;  statusCode?: number;  context?: 'client' | 'server';  severity?: 'error' | 'warn' | 'info' | 'debug';  fallbackOnCondition?: boolean;};type FallbackCondition<T> = T extends Function<infer U> ? U : T;declare function useContentGuard<FallbackReturn extends unknown = undefined>(  condition: boolean,  config: Config,  fallback?: Function<FallbackReturn>,): typeof fallback extends undefined  ? typeof condition extends boolean    ? void    : boolean  : FallbackCondition<FallbackReturn>;

Utility can be very helpful when components or pages logic fails custom validation. It replaces ad-hoc showError() calls with environment-aware behavior so authors catch mistakes early, builds fail before deploy, and production visitors are not exposed to validation noise. It can be also a great way to handle errors across the DocLayer-based application, when extending.

Pass true as the condition when validation fails (invalid props, missing required data, etc.). When the condition is false, the guard will proceed and call the optional fallback function instead.

Behavior by environment:

EnvironmentRespectively
Development

Throws via showError - loud feedback for content authors.

Build / Prerender

Throws via createError - fails the deploy (failOnError is enabled in DocLayer).

Production runtime

Logs using utilLogger (default severity: warn) and does not throw - code continues to run. We recommend to use template guards (placeholders) to hide broken content.

Note: DocLayer's security setup disables logs in production by default.

The default HTTP status code is 422 (Unprocessable Entity). Override it with statusCode when needed. To limit logging to the selected context (client or server) set context to client or server within the configuration object; leave it undefined to log in both contexts.

Intended usage

Use useContentGuard in components and pages that render Markdown content. Prefer it over raw showError() for author-facing validation.

Utility was designed to catch content-related errors early during the writing stage and prevent them from reaching the production runtime. Using it close to the content minimizes unintended side effects.

Avoid using it inside low-level utilities or composables unless the failure is truly content-scoped. For fatal route-level failures (missing collection, auth), use page or middleware-level createError() instead.

Example with custom status code and log severity:

useContentGuard(true, {  source: 'MyPage',  message: 'Something went wrong',  statusCode: 404,  severity: 'error',});

Example with fallback function:

By default fallback function runs when the condition resolves to false (e.g. when internal component-based validation passed).

useContentGuard(  false,  {    source: 'MyComponent',    message: 'Something went wrong',  },  () => console.log('Run function if everything is fine'),);

You can also run the fallback function as a consequence of the condition and showing/logging error (e.g. when the condition resolves to true, but you want to run something before the error is thrown). To do so, pass fallbackOnCondition within the configuration object.

useContentGuard(  true,  {    source: 'MyComponent',    message: 'Something went wrong',    fallbackOnCondition: true,  },  () => console.log('Run function before something went wrong'),);

Additionally, as the utility on production runs in silent mode, this approach can be very useful for hiding broken content blocks, preventing errors from appearing and avoiding potential application crashes. To achieve this, simply update a custom UI flag defined within the component.

Messages are formatted through utilLogMessage with the doclayer tag, so logs stay consistent with the rest of the application.

Build pipeline

Invalid content on any prerendered route causes the build to fail. Ensure nuxt build is not wrapped with || true (which's added to prevent Nitro from failing the build on hang) in CI if you rely on this gate. console.warn alone does not fail the build - only a thrown error during prerender does.


useContentTransformer

Transforms content using configured content transformer.

Example:

// with simple objectconst transformedContent = useContentTransformer(pageData.value);// or with a custom transformerconst transformedContent = useContentTransformer(pageData.value, (code) => `/* transformed */\n${code}`);
import type { PageCollectionItemBase } from '@nuxt/content';import type { DeepNonNullable, InitialAppConfig } from '@vuehouse/dl/types';type Code = string | PageCollectionItemBase;declare function useContentTransformer<T extends Code>(  code: T,  transformer?: InitialAppConfig['dl']['transformers']['code'],): T;

Composable is used to transform the content data of dynamic pages before rendering, starting from an AST string. It uses the dl.transformers.content.post transformer. You can pass either a string or an object; objects are first stringified, transformed, and then parsed back into JSON if possible. If you provide a custom transformer, it will take priority over the built-in transformer.

If you want to transform content globally, use the dl.transformers.content within the dl.transformers object in your app.config.ts file.


useCurrentInstance

Returns a safe Vue Component Instance for the current context.

Example:

const { $instance, utility: $useAppConfig } = useCurrentInstance(useAppConfig);
import type { Nullable, Prettify } from '@vuehouse/dl/types';import type { ComponentInternalInstance } from 'vue';type StrippedInstance = Prettify<Pick<ComponentInternalInstance, 'type' | 'slots' | 'props'>>;declare function useCurrentInstance<Utility extends Function>(  utility?: Utility,): {  $instance: Nullable<    StrippedInstance & {      parent: Nullable<StrippedInstance>;    }  >;  utility?: Utility | null;};

Composable helps you safely determine if the current component's instance is available in the current context - it will return a safe shape of it, or undefined if called outside of a component. It's also useful for securely accessing specific utilities (from Vue or Nuxt) inside a setup function, or in situations where the application context might be uncertain, such as when using them within external utilities.

Caveat

Composable relies on Vue's getCurrentInstance method. While this method is primarily meant for internal APIs and may expose private data, it is still accessible in Vue. To ensure sensitive information is not leaked, DocLayer implementation returns a cleaned and parsed version of the instance, exposing only the safe, component-related APIs, removing any private details. Instance is never exposed globally.

Composable will expose only the following properties from the Vue Component Instance: type, props, slots, parent.type, parent.props, parent.slots.


useDynamicHead

Generates dynamic head data.

Example:

<script setup lang="ts">useDynamicHead({  title: 'Getting Started', // or dynamic: `${pageData.value.title}`  description: 'Learn how to get started with DocLayer',  seo: {    keywords: 'documentation, guide, getting started',    robots: 'index, follow',    // or dynamic: ...pageData.value._seo  },});</script>
import type { PageCollectionItemBase } from '@nuxt/content';import type { MetaKeys } from '@vuehouse/dl/types';type MetaExtend = Pick<PageCollectionItemBase, 'title' | 'description'> & {  seo?: Record<MetaKeys, string>;  schemaOrg?: ReturnType<typeof defineWebPage>;};declare function useDynamicHead<Meta extends MetaExtend>(pageMetadata: Meta): void;

Composable automatically sets up SEO meta tags, Open Graph tags, and Schema.org structured data for pages. It merges page-specific metadata with global app configuration, ensuring consistent SEO across all pages while allowing per-page customization.

Composable can be helpful when building custom pages or layouts that need dynamic head management. More about defining metadata for content pages, you can read here.


useInDocData

Creates an injectable data object for content documents.

Example:

<script setup lang="ts">// Use with global static dataconst { data: inDocData } = useInDocData();// ... or with additional local dataconst { data: inDocData } = useInDocData({ customKey: 'customValue' });// ... or with props dataconst { data: inDocData } = useInDocData(props.data);</script><template>  <ContentRenderer :data="inDocData" /></template>
import type { AppConfig, Primitive } from '@vuehouse/dl/types';import type { Ref } from 'vue';type LocalData = Record<string, Primitive | Record<string, Primitive>>;declare function useInDocData(localData?: LocalData): {  data: Ref<AppConfig['dl']['inDocData'] & AppConfig['dl']['_meta'] & LocalData>;};

Composable is essential for passing reactive data into Markdown content files. The data can be accessed within .md files using the $doc['key'] syntax, enabling dynamic content generation. By default, it provides any values defined in the dl.inDocData global object. You can also provide local, component-specific data, which will be merged with the global one - if there are overlapping keys, the local data will take precedence.


useLocalDB

Creates a typed local database instance backed by IndexedDB (Dexie).

Requires dexie to be installed

In most cases, this composable may not be needed. Because Dexie is a first-class dependency and it's loaded dynamically during the initialization process, it requires the dexie package to be installed. You can do it by running:

# add it to your projectpnpm add dexie
{  // rest of the package.json file  "dependencies": {    "dexie": "latest"  }}

Dexie is a browser-only database and must be initialized only on the client side, outside of the server context. Otherwise, it will throw an error if loaded server-side. To ensure proper setup, you can use Nuxt's ssrContext to detect client-side execution:

<script setup lang="ts">import { useNuxtApp, useLocalDB } from '#imports';import type { DatabaseInitialSchema } from '@vuehouse/dl/types';type User = { name: string; email: string };type LocalDBSchema = {  /** Users entity. */  users: DatabaseInitialSchema<User>;};let localDB: Awaited<ReturnType<typeof useLocalDB<LocalDBSchema>>> | undefined;if (!useNuxtApp().ssrContext) {  localDB = await useLocalDB<{ users: User }>('database-name', {    users: 'id, created_at, updated_at, name, email',  });}</script>

Example:

<script setup lang="ts">// Add / Update / Deleteawait db.addEntity('users', { id: '1', name: 'John', email: 'john@example.com', created_at: new Date().toISOString() });await db.updateEntity('users', '1', {  name: 'John Doe',  email: 'johndoe@example.com',});await db.upsertEntity('users', '1', {  name: 'John Smith',  email: 'johnsmith@example.com',});await db.deleteEntity('users', '1');// Queryconst user = await db.getEntity('users', '1');// Sort by created_at in descending orderconst users = await db.getEntities('users', { order: 'created_at', reverse: true });// Sort by name in ascending orderconst users = await db.getEntities('users', { sort: 'name' });// Limit to 20 entitiesconst users = await db.getEntities('users', { limit: 20 });</script>
import type { Primitive } from '@vuehouse/dl/types';import type { EntityTable, IDType } from 'dexie';type IsoDate = ReturnType<typeof Date.prototype.toISOString>;type SchemaExtension = { [key: string]: Record<string, unknown>[] | Exclude<Primitive, symbol> };type DatabaseInitialSchema<T extends SchemaExtension = SchemaExtension> = {  id: string;  created_at: IsoDate;  updated_at?: IsoDate;} & T;type InitialSchema = Record<string, DatabaseInitialSchema>;type GetEntitiesConfig = Partial<{  sort: string;  limit: number;  order: 'created_at' | 'updated_at';  reverse: boolean;}>;type UpdateEntityData<Schema extends InitialSchema, TableId extends keyof Schema> = Omit<  Schema[TableId],  'id' | 'created_at'> &  Partial<Pick<DatabaseInitialSchema, 'updated_at'>>;declare async function useLocalDB<Schema extends InitialSchema>(  name: string,  schema: Record<string, `id, created_at, updated_at, ${string}`>,): Promise<{  getDatabase: (tableId: keyof Schema) => Promise<EntityTable<Schema[keyof Schema], keyof Schema[keyof Schema]>>;  getEntity: (tableId: keyof Schema, entityId: IDType<Schema[keyof Schema], any>) => Promise<Schema[keyof Schema]>;  getEntities: (tableId: keyof Schema, config?: GetEntitiesConfig) => Promise<Array<Schema[keyof Schema]>>;  updateEntity: (tableId: keyof Schema, entityId: IDType<Schema[keyof Schema], any>, data: UpdateEntityData<Schema, typeof tableId>) => Promise<unknown>;  upsertEntity: (    tableId: keyof Schema,    entityId: IDType<Schema[keyof Schema], any>,    data: UpdateEntityData<Schema, typeof tableId>,  ) => Promise<unknown>;  addEntity: (tableId: keyof Schema, entity: Schema[keyof Schema]) => Promise<unknown>;  deleteEntity: (tableId: keyof Schema, entityId: IDType<Schema[keyof Schema], any>) => Promise<unknown>;  rollVersion: (version?: number) => Promise<void>;}>;

Composable initializes a Dexie database for storing application data locally. Each table schema must include id, created_at, and updated_at - these fields are required by the CRUD and helper methods.

CRUD methods:

methoddescription
addEntity

Creates a new entity in the table.

updateEntity

Updates (puts) an entity by id.

upsertEntity

Inserts or updates an entity by id.

deleteEntity

Deletes an entity by id.

getEntity

Reads a single entity by id.

getEntities

Reads up to 10 entities.

Sorting & Ordering:

The getEntities method supports sorting and ordering of entities. The sort parameter is a string that represents the field to sort by. The order parameter is a string that represents the order to sort by; use created_at or updated_at. The reverse parameter is a boolean that represents the order to sort by.

To limit the number of entities returned, you can use the limit parameter. It's a number that represents the number of entities to return; defaults to 10.

Helper methods:

methoddescription
getDatabase

Returns the Dexie database instance for the table.

rollVersion

Bumps the schema version.


useNavigationData

Provides structured and flat content navigation data.

Example:

<script setup lang="ts">const { getNavigationData, getFlatNavigationData } = useNavigationData('docs');// Get tree structureconst { data: navigation } = await getNavigationData();// Get flattened arrayconst { data: flatNavigation } = await getFlatNavigationData();</script>
import type { ContentNavigationItem } from '@nuxt/content';import type { Nullable, CollectionName, QueryCollectionNavigation } from '@vuehouse/dl/types';import type { Ref } from 'vue';type NavigationBlockExtends = { icon?: string; title?: string };type NavigationData = { data: Ref<Nullable<NavigationBlock['pages']>> };interface NavigationBlock extends AccordionItem {  id?: string;  pages: (ContentNavigationItem & NavigationBlockExtends)[];}declare function useNavigationData<CollectionName extends keyof PageCollections>(  collection: CollectionName,): {  // getNavigationData: typeof getNavigationData  getNavigationData: () => Promise<AsyncData<NavigationBlock['pages'], any>>;  // getFlatNavigationData: typeof getFlatNavigationData  getFlatNavigationData: () => Promise<{ data: Ref<NavigationBlock['pages']> }>;};

Composable handles content navigation hierarchies. Use getNavigationData to retrieve the full tree structure, or getFlatNavigationData to get a flat array of all pages. The flattened version is useful for search functionality or simplified navigation UIs.

Use with utilCollectionName

Consider using utilCollectionName to determine the current collection context, allowing to fetch the appropriate navigation data based on the active route.

<script setup lang="ts">const route = useRoute();const collectionName = await utilCollectionName(route);const { getNavigationData } = useNavigationData(collectionName);</script>

usePropsExtender

Automatically extends component props with values provided via the #props slot in Markdown files.

Example:

<script setup lang="ts">// Props are automatically extended with values from the #props slotusePropsExtender();</script>
declare function usePropsExtender(): Record<string, any>;

Composable handles dynamic props transfer to rendered components from Markdown files. It reads the #props slot - defined inside the .md file - and merges those values into the component's props, enabling flexible component configuration from content files.

By default, this composable is used by the DlWrapper component, so you typically don't need to add it manually. However, when using with newly created components make sure the props data is properly passed to the rendered content components - for example, by using useInDocData(props.data). More about overwriting component props from Markdown, you can read here.


useSlotsParser

Parses component slots and extracts their values as / to strings.

Example:

const output = ref({ default: undefined });useSlotsParser(slots, output);// output.value.default contains parsed slot content// if any other slots are defined, they will be available as well// Get code from slot, defined in Markdownconst codeOutput = ref({ default: undefined });useSlotsParser(slots, codeOutput, true);// codeOutput.value.code contains extracted code blocks
import type { Nullable } from '@vuehouse/dl/types';import type { Ref } from 'vue';type CodeOutlet = { code: string; language: string };type CodeOutletRecord<Keys extends string, ExtractCode extends boolean = false> = Record<  Keys,  Nullable<ExtractCode extends true ? CodeOutlet[] : string>>;declare function useSlotsParser<Keys extends string>(  slots: ReturnType<typeof useSlots>,  output: Ref<CodeOutletRecord<Keys, typeof extractCode>>,  extractCode?: boolean,): void;

Composable gathers slot content into an object, using slot names as keys and their stringified content values. It can also extract code blocks - such as those defined in Markdown with triple backticks - along with related metadata like the code language.


usePathMarker

Resolves a $path-marker against the global dl.pathMap registry.

Example:

<script setup lang="ts">const { resolvePath, resolvePathData } = usePathMarker();const linkDataFromPathMarker = resolvePathData('$docs-getting-started', {  source: 'MyComponent',  label: 'Getting Started', // or false for custom markers});// Results in: { url: '/docs/getting-started', label: 'Getting Started' }const linkDataFromLiteral = resolvePath('/docs/components' /* or a $path-marker */, {  source: 'MyComponent',  label: 'Link to the Component', // or false for custom markers  literal: true,});// Results in: { url: '/docs/components', label: 'Link to the Component' }</script>
type PathMarkerOptions = {  source: string;  label?: string | false;  path?: string;  hash?: string | '$current' | '$unset';  local?: boolean | string;  literal?: boolean;};declare function usePathMarker(): {  resolvePath: (identifier: string, options: PathMarkerOptions) => ResolvedPathMarkerLink | undefined;  resolvePathData: (marker: string, options: PathMarkerOptions) => ResolvedPathMarker | undefined;};

Composable useful when you need to resolve a path marker against the global path registry. Use resolvePath if you're providing either a path marker or a literal URL (unknown); we use it for links defined within the DlFeaturesGrid component. Use resolvePathData if you're providing a path map key; we use it for links defined within the DlLink component.


usePathResolver

Resolves relative paths and/or external URLs.

Example:

usePathResolver('docs/getting-started');// results in: https://your.base/docs/getting-startedusePathResolver('/docs');// results in: /docsusePathResolver('https://example.com');// results in: https://example.comusePathResolver('docs', 'section');// results in: https://your.base/docs/sectionusePathResolver('docs', 'section', 'hash');// results in: https://your.base/docs/section#hash
declare function usePathResolver<T extends string | undefined = string>(url: T, path?: string, hash?: string): T;

Composable is useful when you need to resolve proper linking from different places in the application, whether it’s a local path or an external one. It leaves absolute paths (/...) and full URLs (https://...) unchanged. Additionally, it supports an optional paths and hashes. If path will be undefined or empty string, it will return just the runtimeConfig.public.baseUrl.