Theme Extensions
Using Theme Color Presets
A color preset is what identifies a website or a group or content-related websites.
A preset usually includes a:
- primary color: the color that visually identifies the website. It will be applied to heading H1 elements and the website title in the left navigation.
- hero banner: a background image with certain visual patterns to be used in the website's landing page. The banner should have the same or similar colors to the primary color.
Here is the list of the available presets:
base
merchantCenterDeveloperDocs
merchantCenterUserDocs
platformDeveloperDocs
Usage
In your gatsby-config.js
:
const colorPresets = require('@commercetools-docs/gatsby-theme-docs/color-presets');module.exports = {// ... other site configplugins: [...configureThemeWithAddOns({// ... other theme configcolorPreset: colorPresets.platformDeveloperDocs.key,}),],};
Using Theme with Add-Ons
A theme add-on is a Gatsby Theme that exposes React components to be injected into the MDX provider of the core theme.
Gatsby enables a child theme to use component shadowing (see Theme overrides). However, with multiple themes, the shadowed components are only loaded from the last theme in the Gatsby configuration. To solve this problem, a commercetools-docs Gatsby Theme can be used as an add-on, allowing multiple add-ons to provide additional components to be available in MDX without having to manually import them into every page.
When using add-on themes, a proxy export file will be generated in the websites src/@commercetools-docs/gatsby-theme-docs/overrides
folder to leverage Gatsby's component shadowing (see Theme overrides). This file provides all the exported components from the add-on packages. For a component to be exported by an add-on package it has to be exported from shortcodes.js
in the add-on package root.
To safely configure theme add-ons, use the configureThemeWithAddOns
function in the websites's gatsby-config.js
:
const {configureThemeWithAddOns,} = require('@commercetools-docs/gatsby-theme-docs/configure-theme');module.exports = {plugins: [...configureThemeWithAddOns({// Pass the normal theme optionswebsiteKey: 'my-website-key',// Define and configure the add-on plugins instead of configuring them in the main plugins array.addOns: ['@commercetools-docs/gatsby-theme-foo',{resolve: '@commercetools-docs/gatsby-theme-bar',options: {// ...},},],}),],};
Theme Overrides
Overrides files using Gatsby theme shadowing, to inject functionalities to specific parts of the theme.
Usage
To use this feature, the website must mimic the folder structure of the Gatsby theme and list the files in the overrides
folder that should be overridden.
src└── @commercetools-docs└── gatsby-theme-docs└── overrides├── markdown-components.js├── page-header-side.js└── use-additional-site-data.js
Note that Gatsby shadowing works with any file in the theme. However, the theme provides an explicit stable extension point that is the
overrides
folder. Users of the theme should use this extension point only instead of relying on theme-internal file system paths that can potentially change any time.
Available overrides
markdown-components
: allows to pass React components to be injected in the content pages.import MyCustomComponent from '../../../components/my-custom-component';const markdownComponents = {MyCustomComponent,};export default markdownComponents;With this, in the
*.mdx
content pages the<MyCustomComponent>
is available to use.page-header-side
: allows to render something in the top-right corner of a content page. Any valid React component should be default exported.use-additional-site-data
: allows to return custom site metadata using React hooks. The data is merged with the defaultsiteMetadata
of the Gatsby theme and can be accessed using theuseSiteData
hook.import { useStaticQuery, graphql } from 'gatsby';// This website defines the `repositoryUrl` value in the `siteMetadata` config.// Therefore, we query those extra values and return them.const useAdditionalSiteData = () => {const data = useStaticQuery(graphql`query GetAdditionalSiteData {site {siteMetadata {repositoryUrl}}}`);return data.site.siteMetadata;};export default useAdditionalSiteData;
Helpful Components & Functions
The theme additionally exports some React components and functions that are useful to build custom views in your website. Two hooks allow to build components that can be placed into MDX files while still having access to all necessary data:
usePageData
provides frontmatter values or their defaults and other page-level metadata like the table of contents.useSiteData
provides site wide metadata.
import {Markdown,Spacings,useSiteData,usePageData,} from '@commercetools-docs/gatsby-theme-docs';const MyComponent = () => {const siteData = useSiteData();const pageData = usePageData();return (<Spacings.Stack><Markdown.H1>{siteData.siteMetadata.title}</Markdown.H1><Markdown.Paragraph>{'Hello, world!'}</Markdown.Paragraph>{usePageData.beta ? (<Warning>Beta!</Warning>) : (<Info>Generally available</Info>)}</Spacings.Stack>);};export default MyComponent;
Gatsby Theme Add-On for API docs
This theme provides components in MDX to render API info from RAML spec files.
It is a feature add-on to @commercetools-docs/gatsby-theme-docs
and is not usable standalone.
Installation
npx install-peerdeps --dev @commercetools-docs/gatsby-theme-api-docs
Usage
In your gatsby-config.js
:
const {configureThemeWithAddOns,} = require('@commercetools-docs/gatsby-theme-docs/configure-theme');module.exports = {// ... other site configplugins: [...configureThemeWithAddOns({// ... other theme configaddOns: [{resolve: '@commercetools-docs/gatsby-theme-api-docs',options: {transformerRaml: {includeApis: ['example'],moveTypePropertiesToTop: ['id'],moveTypePropertiesToBottom: ['custom'],},},},],}),],};
Plugin Options
transformerRaml
: See gatsby-transformer-raml Plugin Options
Generating the required canonical RAML form
Use the @commercetools-docs/rmf-codegen RAML_DOC
target output to generate RAML API specifications in the canonical file layout required by this plugin. It does an (any valid) RAML to (canonical flattened) RAML conversion allowing the gatsbyJS plugin to handle the RAML without semantic parsing or resolving.
Example call:
npx rmf-codegen generate ./websites/api-docs-smoke-test/source-raml/test/api.raml --output-folder ./websites/api-docs-smoke-test/src/api-specs/test --target RAML_DOC
In gatsby develop mode, add the --watch
option to the rmf-codegen command to continuously regenerate the canonical output while editing the original RAML.
Path Convention ./src/api-specs/
RAML spec files have to be added in the ./src/api-specs/
folder of the website. This directory is required and is automatically generated when the plugin runs.
The file location determines the apiKey
through which it can be addressed:
src/api-specs/foo.raml
-> apiKeyfoo
src/api-specs/bar/api.raml
-> apiKeybar
src/api-specs/baz/baz.raml
-> apiKeybaz
Soft Links
Soft links are autogenerated for types and endpoints that are used on MDX pages. They are generated using our custom Uniform Resource Locator (URN), for types the custom URN is ctp:<api-key>:type:<type-name>
, and for endpoints the custom URN is ctp:<api-key>:endpoint:<endpoint>:<method>
.
Soft links can be taken advantage of in a couple of ways:
If the type of a field is used on an MDX page, the type would be automatically rendered as a link, instead of a text, to where the type is rendered/defined on the MDX page.
Our custom URN can be used in markdown links of description fields of types and resources. For example, to use an autogenerated soft link for a type, the markdown link would be written as
[Text](ctp:<api-key>:type:<type-name>)
.
Overriding the location of certain API types
If you want to override the location to link to for certain API data types, create a file called type-locations.yaml
under the src/data
folder of the website. This can be useful to choose manual markdown based documentation for certain types or to link ot shared types used on other websites like public standards. Use the following format to override the type locations:
- api: importlocations:- type: AssetDimensionshref: /product-variant#assetdimensions- type: DiscountedPricehref: /../other-microsite/order#discountedprice- api: historylocations:- type: LocalizedLabelhref: https://example.com/some/other/location/on/the/web
api
-> Name of the api where the types are located.locations
-> List of type locations you want to override.type
-> Name of the type to override.href
-> Your custom link.
Using UI components in MDX
Because the API documentation components load the complete API specification data, they are not automatically injected into the MDX provider but have to be imported explicitly.
By convention it's recommended that websites define a /shortcodes.js
module that can then be addressed in the MDX pages:
export {ApiType,ApiEndpoint,ApiEndpointsForResource,} from '@commercetools-docs/gatsby-theme-api-docs';
The package exposes the following components:
<ApiType>
: Renders an API type.
import { ApiType } from '/shortcodes';{/*apiKey - name of the specs directorytype - name of the api typehideInheritedProperties - optional prop that hides properties inherited from parent type except discriminator*/}<ApiType apiKey="test" type="ExamplesTestType" hideInheritedProperties />;
<ApiEndpoint>
: Renders an API endpoint.
import { ApiEndpoint } from '/shortcodes';{/*apiKey - name of the specs directoryresource - path of the endpointmethod - endpoint method e.g. get, post, delete.title - optional title to render*/}<ApiEndpointapiKey="test"resource="/{projectKey}/resource/artificially-complex/path/uri-parameter-one={uriParameterOne}/{uriParameterTwo}"method="POST"title="<optional>"/>;
<ApiEndpointsForResource>
: Renders all endpoints of an API resource.
import { ApiEndpointsForResource } from '/shortcodes';{/*apiKey - name of the specs directoryresource - path of the resource*/}<ApiEndpointsForResource apiKey="test" resource="/{projectKey}/resource" />;
Resource Query Paramesters of Array Type
All query parameters of array type are not rendered as arrays. Only the type (for example String
) of the array items is rendered along with additional text in the description that reads The parameter can be passed multiple times.
.
Gatsby Theme Add-On for Code Examples
This theme provides components in MDX to render code examples from files, optionally in multiple programming languages.
It is a feature add-on to @commercetools-docs/gatsby-theme-docs
and is not usable standalone.
Installation
npx install-peerdeps --dev @commercetools-docs/gatsby-theme-code-examples
Usage
In your gatsby-config.js
:
const {configureThemeWithAddOns,} = require('@commercetools-docs/gatsby-theme-docs/configure-theme');module.exports = {// ... other site configplugins: [...configureThemeWithAddOns({// ... other theme configaddOns: ['@commercetools-docs/gatsby-theme-code-examples'],}),],};
Example files must be added in the ./src/code-examples/
folder of the website. That folder is automatically generated when the plugin runs.
Supported MIME Types
application/javascript
(JavaScript)text/x-java-source
(Java)application/json
(JSON)application/x-httpd-php
(PHP)application/x-sh
(Shell / Bash)video/mp2t
(not actually TypeScript, but gatsbyJS represents .ts files as this mime type)text/yaml
(YAML)text/vnd.curl
(cURL)
In addition the following are included to cover languages with no explicit mime type (for example C#)
application/octet-stream
text/plain
Using UI components in Markdown
The package exposes the following components in the MDX context:
<CodeExample>
<MultiCodeExample>
Then in your MDX files:
<MultiCodeExample title="Multilanguage Code Samples"><CodeExample path="example.js" highlightLines={[3]} /><CodeExample path="example.java"/><CodeExample path="example.console" noPromptLines={[3, 4]} /></MultiCodeExample><CodeExample path="example.js" title="JavaScript Code Sample" />
In addition to path
, the <CodeExample>
component supports all custom parameters that can be passed to fenced code blocks in the base theme
Gatsby Theme Add-On for Constants
This theme exposes components in MDX to render constant values centrally defined in data files. Use cases include centrally managing limits and defaults of the documented product.
It is a feature add-on to @commercetools-docs/gatsby-theme-docs
and is not usable standalone.
Installation
npx install-peerdeps --dev @commercetools-docs/gatsby-theme-constants
Usage
In your gatsby-config.js
:
const {configureThemeWithAddOns,} = require('@commercetools-docs/gatsby-theme-docs/configure-theme');module.exports = {// ... other site configplugins: [...configureThemeWithAddOns({// ... other theme configaddOns: ['@commercetools-docs/gatsby-theme-constants'],}),],};
The YAML data files containing the constant data points must be added to the ./src/constants
folder of the website. This folder is automatically generated when the plugin runs.
YAML file format
For example, to centrally manage limits of your product, add a file src/constants/limits.yaml
with content in the following format:
- name: jsonSizenumber: 64text: megabytes- name: slugLengthnumber: 256- name: slugPatterntext: "[a-zA-Z0-9_\\-]{2,256}"
The filename without extension becomes the "type" of the constant when addressing it. Multiple files are supported.
Using the UI component in content
The package exposes the following components in the MDX context:
<Constant>
Then in your MDX files include the constant value in arbitrary places:
<Constant type="limits" name="slugLength"/>
If both a text and a number value are provided, the text is rendered after the number, separated by a non-breaking space to allow using the text as a unit of measure for the number.