Skip to content

Commit

Permalink
Fix SSR
Browse files Browse the repository at this point in the history
  • Loading branch information
MattiasBuelens committed Mar 6, 2024
1 parent aa28dfa commit a2444dd
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions src/components/CodeInput/index.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,36 @@
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
import React, { type DetailedHTMLProps, type HTMLAttributes } from 'react';
import Prism from 'prismjs';
import * as codeInput from '@webcoder49/code-input/code-input';
import '@webcoder49/code-input/plugins/indent';
import React, { type DetailedHTMLProps, type HTMLAttributes, useEffect } from 'react';
import type * as CodeInputNamespace from '@webcoder49/code-input/code-input';
import type * as PrismNamespace from 'prismjs';
import 'prismjs/themes/prism-okaidia.min.css';
import '@webcoder49/code-input/code-input.min.css';

let codeInput: typeof CodeInputNamespace;
let Prism: typeof PrismNamespace;
if (ExecutionEnvironment.canUseDOM) {
// <code-input> can only be loaded inside the browser
codeInput = require('@webcoder49/code-input/code-input');
Prism = require('prismjs');
require('@webcoder49/code-input/plugins/indent');
// HACK: <code-input> doesn't handle being loaded lazily (after window load)
(codeInput as any).windowLoaded = true;
}

let codeInputInitialized = false;

function initializeCodeInput() {
if (codeInputInitialized) return;
// Register our template
codeInput.registerTemplate('syntax-highlighted', codeInput.templates.prism(Prism, [new codeInput.plugins.Indent(true, 4)]));
codeInputInitialized = true;
}

export interface CodeInputElement extends codeInput.CodeInput {
export interface CodeInputElement extends CodeInputNamespace.CodeInput {
value: string;
}

export interface Props extends DetailedHTMLProps<HTMLAttributes<CodeInputElement>, CodeInputElement> {
template?: string;
value?: string;
}

declare module 'react' {
Expand All @@ -28,5 +42,8 @@ declare module 'react' {
}

export function CodeInput(props: Props) {
useEffect(() => {
initializeCodeInput();
}, []);
return <code-input template="syntax-highlighted" {...props}></code-input>;
}

0 comments on commit a2444dd

Please sign in to comment.