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.
Collects and provides global configuration for all registered adapters.
Example:
Component.vue
signature.d.ts
<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.
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.
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.
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:
Environment
Respectively
Development
Throws via showError - loud feedback for content authors.
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 setupdisables 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.
By default fallback function runs when the condition resolves to false (e.g. when internal component-based validation passed).
Component.vue
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.
Component.vue
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.
Transforms content using configured content transformer.
Example:
example.ts
signature.d.ts
// 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.
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.
<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.
Creates an injectable data object for content documents.
Example:
Component.vue
signature.d.ts
<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.
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:
bash.sh
package.json
# 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:
Composable initializes a Dexie database for storing application data locally. Each table schema must includeid, created_at, and updated_at - these fields are required by the CRUD and helper methods.
CRUD methods:
method
description
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:
method
description
getDatabase
Returns the Dexie database instance for the table.
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.
Automatically extends component props with values provided via the #props slot in Markdown files.
Example:
Component.vue
signature.d.ts
<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 theDlWrapper 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.
Parses component slots and extracts their values as / to strings.
Example:
Component.vue
signature.d.ts
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
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.
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.
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.