diff --git a/Dockerfile b/Dockerfile
index 843c44ce4..b488b245b 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -13,6 +13,7 @@ RUN rm -r /usr/share/nginx/html && rm /etc/nginx/conf.d/default.conf
COPY --from=builder /frontend-shared/build /usr/share/nginx/html
COPY ./templates/index.html /usr/share/nginx/html/index.html
COPY ./images /usr/share/nginx/html/images
+COPY ./src/pattern-library/examples /usr/share/nginx/html/examples
COPY conf/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 5001
diff --git a/README.md b/README.md
index c19677abc..a581da48d 100644
--- a/README.md
+++ b/README.md
@@ -49,3 +49,4 @@ import { Link } from '@hypothesis/frontend-shared';
- [Development guide](docs/developing.md)
- [Release guide](docs/releases.md)
+- [Adding examples](docs/examples.md)
diff --git a/docs/examples.md b/docs/examples.md
new file mode 100644
index 000000000..ddcdfe237
--- /dev/null
+++ b/docs/examples.md
@@ -0,0 +1,28 @@
+# Adding code examples
+
+Component library documentation frequently needs to show interactive examples, along with the code for them.
+
+Manually writing those code snippets has some issues: they are not covered by your type checking and linting tasks, and they can accidentally get outdated.
+
+The web-based documentation included with this library allows to create example files which are both used as regular modules that can be imported for interactive examples, but also read as plain text to generate their corresponding code snippet.
+
+These files are type-checked, formatted and linted like any other source files, and the code snippet will always be in sync with the interactive example.
+
+## Using example files
+
+When you want to create a code example, add a file with the name of your choice inside `src/pattern-library/examples` directory.
+
+You can then reference this file from the web-based pattern library, passing the `exampleFile` prop to the `` component.
+
+```tsx
+
+```
+
+## Considerations
+
+There are some considerations and limitations when working with example files.
+
+- They all need to have the `tsx` extension.
+- Nested directories are not supported, so it's a good idea to add contextual prefixes to example files. For example, all files related with `SelectNext` can be prefixed with `select-next` to make sure they are all grouped together.
+- Example files need to have a Preact component as their default export.
+- When generating the source code snippet, import statements are stripped out, to avoid internal module references which are not relevant for the library consumers.
diff --git a/package.json b/package.json
index eba13bf8c..c68ce7027 100644
--- a/package.json
+++ b/package.json
@@ -14,6 +14,7 @@
"@hypothesis/frontend-testing": "^1.2.2",
"@rollup/plugin-babel": "^6.0.0",
"@rollup/plugin-commonjs": "^25.0.0",
+ "@rollup/plugin-dynamic-import-vars": "^2.1.2",
"@rollup/plugin-node-resolve": "^15.0.0",
"@rollup/plugin-virtual": "^3.0.0",
"@trivago/prettier-plugin-sort-imports": "^4.1.1",
diff --git a/rollup.config.js b/rollup.config.js
index d4a38b961..9b0a34936 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -1,5 +1,6 @@
import { babel } from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
+import dynamicImportVars from '@rollup/plugin-dynamic-import-vars';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import { string } from 'rollup-plugin-string';
@@ -27,6 +28,7 @@ function bundleConfig(name, entryFile) {
exclude: 'node_modules/**',
extensions: ['.js', '.ts', '.tsx'],
}),
+ dynamicImportVars(),
nodeResolve({ extensions: ['.js', '.ts', '.tsx'] }),
commonjs({ include: 'node_modules/**' }),
string({
diff --git a/scripts/serve-pattern-library.js b/scripts/serve-pattern-library.js
index dfc9dc477..b52218c8a 100644
--- a/scripts/serve-pattern-library.js
+++ b/scripts/serve-pattern-library.js
@@ -11,6 +11,10 @@ export function servePatternLibrary(port = 4001) {
app.use('/scripts', express.static(path.join(dirname, '../build/scripts')));
app.use('/styles', express.static(path.join(dirname, '../build/styles')));
app.use('/images', express.static(path.join(dirname, '../images')));
+ app.use(
+ '/examples',
+ express.static(path.join(dirname, '../src/pattern-library/examples')),
+ );
// For any other path, serve the index.html file to allow client-side routing
app.get('/:path?', (req, res) => {
diff --git a/src/pattern-library/components/Library.tsx b/src/pattern-library/components/Library.tsx
index 18a8b7766..d3ab59b44 100644
--- a/src/pattern-library/components/Library.tsx
+++ b/src/pattern-library/components/Library.tsx
@@ -1,7 +1,7 @@
import classnames from 'classnames';
import { toChildArray, createContext } from 'preact';
import type { ComponentChildren, JSX } from 'preact';
-import { useMemo, useState, useContext } from 'preact/hooks';
+import { useState, useContext, useEffect } from 'preact/hooks';
import { Link as RouteLink } from 'wouter-preact';
import {
@@ -11,7 +11,7 @@ import {
Scroll,
ScrollContainer,
} from '../../';
-import { jsxToHTML } from '../util/jsx-to-string';
+import { highlightCode, jsxToHTML } from '../util/jsx-to-string';
/**
* Components for rendering component documentation, examples and demos in the
@@ -165,8 +165,50 @@ function Example({ children, title, ...htmlAttributes }: LibraryExampleProps) {
);
}
+function SimpleError({ message }: { message: string }) {
+ return (
+
+ {message}
+
+ );
+}
+
+/**
+ * Fetches provided example file and returns its contents as text, excluding
+ * the import statements.
+ * An error is thrown if the file cannot be fetched for any reason.
+ */
+async function fetchCodeExample(
+ exampleFile: string,
+ signal: AbortSignal,
+): Promise {
+ const res = await fetch(`/examples/${exampleFile}.tsx`, { signal });
+ if (res.status >= 400) {
+ throw new Error(`Failed loading ${exampleFile} example file`);
+ }
+
+ const text = await res.text();
+
+ // Remove import statements and trim trailing empty lines
+ return text.replace(/^import .*;\n/gm, '').replace(/^\s*\n*/, '');
+}
+
export type LibraryDemoProps = {
- children: ComponentChildren;
+ children?: ComponentChildren;
+
+ /**
+ * Example file to read and use as content (to be rendered with syntax
+ * highlighting).
+ * It should be relative to the `pattern-library/examples` dir, and include no
+ * file extension: `exampleFile="some-example"`.
+ *
+ * The file needs to have a default export, which will be used to render the
+ * interactive example.
+ *
+ * If provided together with `children`, `children` will take precedence.
+ */
+ exampleFile?: string;
+
/** Extra CSS classes for the demo content's immediate parent container */
classes?: string | string[];
/** Inline styles to apply to the demo container */
@@ -179,6 +221,62 @@ export type LibraryDemoProps = {
withSource?: boolean;
};
+type DemoContentsResult =
+ | { children: ComponentChildren }
+ | {
+ code?: string;
+ example?: ComponentChildren;
+ codeError?: string;
+ exampleError?: string;
+ };
+
+function isStaticDemoContent(
+ contentResult: DemoContentsResult,
+): contentResult is { children: ComponentChildren } {
+ return 'children' in contentResult;
+}
+
+/**
+ * Determines what are the contents to be used for a Demo, which can be either
+ * an explicitly provided set of children, or the contents of an example file
+ * which is dynamically imported.
+ */
+function useDemoContents(
+ props: Pick,
+): DemoContentsResult {
+ const [code, setCode] = useState();
+ const [example, setExample] = useState();
+ const [codeError, setCodeError] = useState();
+ const [exampleError, setExampleError] = useState();
+
+ useEffect(() => {
+ if (!props.exampleFile) {
+ return () => {};
+ }
+
+ import(`../examples/${props.exampleFile}.tsx`)
+ .then(({ default: Example }) => setExample())
+ .catch(() =>
+ setExampleError(
+ `Failed loading ../examples/${props.exampleFile}.tsx module`,
+ ),
+ );
+
+ const controller = new AbortController();
+ fetchCodeExample(props.exampleFile, controller.signal)
+ .then(setCode)
+ .catch(e => setCodeError(e.message));
+
+ return () => controller.abort();
+ }, [props.exampleFile, props.children]);
+
+ if (props.children) {
+ return { children: props.children };
+ }
+
+ return { code, example, codeError, exampleError };
+}
+
/**
* Render a "Demo", with optional source. This will render the children as
* provided in a tabbed container. If `withSource` is `true`, the JSX source
@@ -186,25 +284,16 @@ export type LibraryDemoProps = {
* rendered Demo content.
*/
function Demo({
- children,
classes,
withSource = false,
style = {},
title,
+ ...rest
}: LibraryDemoProps) {
const [visibleTab, setVisibleTab] = useState('demo');
- const source = toChildArray(children).map((child, idx) => {
- return (
-