Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: global vars #1039

Merged
merged 3 commits into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions __tests__/variables/index.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { render, screen } from '@testing-library/react';
import React from 'react';
import { execute } from '../helpers';

describe('variables', () => {
it('renders a variable', async () => {
const md = `{user.name}`;
const Content = await execute(md, {}, { variables: { user: { name: 'Testing' } } });

render(<Content />);

expect(screen.getByText('Testing')).toBeVisible();
});

it('renders a default value', async () => {
const md = `{user.name}`;
const Content = await execute(md);

render(<Content />);

expect(screen.getByText('NAME')).toBeVisible();
});

it('supports user variables in ESM', async () => {
const md = `
export const Hello = () => <p>{user.name}</p>;

<Hello />
`;
const Content = await execute(md, {}, { variables: { user: { name: 'Owlbert' } } });

render(<Content />);

expect(screen.getByText('Owlbert')).toBeVisible();
});
});
8 changes: 3 additions & 5 deletions lib/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,14 @@ const compile = (text: string, { components, copyButtons, ...opts }: CompileOpts
remarkGfm,
...Object.values(transforms),
[codeTabsTransformer, { copyButtons }],
variablesTransformer,
],
rehypePlugins: [...rehypePlugins, [rehypeToc, { components }]],
...opts,
});

return String(vfile).replace(
/await import\(_resolveDynamicMdxSpecifier\(('react'|"react")\)\)/,
'arguments[0].imports.React',
);
return String(vfile)
.replace(/await import\(_resolveDynamicMdxSpecifier\(('react'|"react")\)\)/, 'arguments[0].imports.React')
.replace('"use strict";', '"use strict";\nconst { user } = arguments[0].imports;');
} catch (error) {
throw error.line ? new MdxSyntaxError(error, text) : error;
}
Expand Down
10 changes: 3 additions & 7 deletions lib/run.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,7 @@ import { Depth } from '../components/Heading';
import { tocToMdx } from '../processor/plugin/toc';
import compile from './compile';
import { CustomComponents, RMDXModule } from '../types';

interface Variables {
user: Record<string, string>;
defaults: { name: string; default: string }[];
}
import User, { Variables } from '../utils/user';

export type RunOpts = Omit<RunOptions, 'Fragment'> & {
components?: CustomComponents;
Expand Down Expand Up @@ -63,7 +59,7 @@ const run = async (string: string, _opts: RunOpts = {}) => {
...runtime,
Fragment,
baseUrl: import.meta.url,
imports: { React },
imports: { React, user: User(variables) },
useMDXComponents,
...opts,
}) as Promise<RMDXModule>;
Expand All @@ -76,7 +72,7 @@ const run = async (string: string, _opts: RunOpts = {}) => {

return {
default: () => (
<Contexts terms={terms} variables={variables} baseUrl={baseUrl}>
<Contexts terms={terms} baseUrl={baseUrl} variables={variables}>
<Content />
</Contexts>
),
Expand Down
31 changes: 31 additions & 0 deletions utils/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
interface Default {
name: string;
default: string;
}

export interface Variables {
user: Record<string, string>;
defaults: Default[];
}

const User = (variables?: Variables) => {
const { user = {}, defaults = [] } = variables || {};

return new Proxy(user, {
get(target, attribute) {
if (typeof attribute === 'symbol') {
return '';
}

if (attribute in target) {
return target[attribute];
}

const def = defaults.find((d: Default) => d.name === attribute);

return def ? def.default : attribute.toUpperCase();
},
});
};

export default User;
Loading