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

fix(docz-theme-default): force codemirror to refresh (#637) #638

Merged
merged 1 commit into from
Feb 17, 2019
Merged
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
88 changes: 74 additions & 14 deletions packages/docz-theme-default/src/components/ui/CodeMirror/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { jsx } from '@emotion/core'
import { SFC } from 'react'
import { Component, ReactNode } from 'react'
import { ThemeConfig } from 'docz'
import { Controlled as BaseCodeMirror } from 'react-codemirror2'
import PerfectScrollbar from 'react-perfect-scrollbar'
Expand Down Expand Up @@ -70,16 +70,76 @@ const scrollbarOpts = {
suppressScrollX: true,
}

export const CodeMirror: SFC<any> = props => (
<ThemeConfig>
{({ themeConfig }) => (
<Scrollbar
option={scrollbarOpts}
linesToScroll={themeConfig.linesToScrollEditor || 14}
>
{global}
<EditorStyled {...props} />
</Scrollbar>
)}
</ThemeConfig>
)
export class CodeMirror extends Component {
private codeMirrorInstance: any;
private forceUpdateCodeMirrorTimeout = 0;
private previousCodeMirrorHeight = 0;

public componentWillUnmount(): void {
this.clearForceUpdateCodeMirror();
}

public render(): ReactNode {
this.forceUpdateCodeMirror();

const props = {
...this.props,
editorDidMount: (editor: any) => {
this.codeMirrorInstance = editor;
},
}

return (
<ThemeConfig>
{({ themeConfig }) => (
<Scrollbar
option={scrollbarOpts}
linesToScroll={themeConfig.linesToScrollEditor || 14}
>
{global}
<EditorStyled {...props} />
</Scrollbar>
)}
</ThemeConfig>
)
}

private refreshCodeMirror = () => {
if (!this.codeMirrorInstance) {
return;
}

this.codeMirrorInstance.refresh();
}

private clearForceUpdateCodeMirror = () => {
if (!this.forceUpdateCodeMirrorTimeout) {
return;
}
clearTimeout(this.forceUpdateCodeMirrorTimeout);
}

private forceUpdateCodeMirror = () => {
if (!this.codeMirrorInstance) {
return;
}

this.clearForceUpdateCodeMirror();

this.forceUpdateCodeMirrorTimeout = setTimeout(() => {
const currentHeight = this.codeMirrorInstance.getScrollInfo().height || 0;

if (
// Don't refresh if no height (CodeMirror is not visible)
currentHeight <= 0
// Don't refresh if same height
|| this.previousCodeMirrorHeight === currentHeight
) {
return;
}

this.refreshCodeMirror();
this.previousCodeMirrorHeight = this.codeMirrorInstance.getScrollInfo().height || 0;
});
}
}