Skip to content

Commit

Permalink
feat: useDocument for SSR
Browse files Browse the repository at this point in the history
  • Loading branch information
righ committed Nov 13, 2024
1 parent 8587d38 commit 2888928
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/components/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ import { useSheetContext } from './SheetProvider';
import { Lexer } from '../formula/evaluator';
import { REF_PALETTE } from '../lib/palette';
import { Mode } from '../types';
import { useDocument } from './hooks';

type Props = {
mode?: Mode;
};

export const Editor: React.FC<Props> = ({ mode }: Props) => {
const { store, dispatch } = React.useContext(Context);

const {
showAddress,
editorRect,
Expand All @@ -56,7 +56,6 @@ export const Editor: React.FC<Props> = ({ mode }: Props) => {
} = store;

const [, sheetContext] = useSheetContext();

React.useEffect(() => {
editorRef?.current?.focus?.({ preventScroll: true });
}, [editorRef]);
Expand Down Expand Up @@ -101,8 +100,11 @@ export const Editor: React.FC<Props> = ({ mode }: Props) => {
};

const numLines = valueString.split('\n').length;

const [isKeyDown, setIsKeyDown] = React.useState(false);
const document = useDocument();
if (document == null) {
return null;
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (isKeyDown) {
return;
Expand Down Expand Up @@ -386,10 +388,6 @@ export const Editor: React.FC<Props> = ({ mode }: Props) => {
return false;
};

if (typeof window === 'undefined') {
return null;
}

return createPortal(
<div
className={`gs-editor ${editing ? 'gs-editing' : ''}`}
Expand All @@ -410,6 +408,7 @@ export const Editor: React.FC<Props> = ({ mode }: Props) => {
{editorStyle(inputting)}
</pre>
<textarea
autoFocus={true}
spellCheck={false}
draggable={false}
ref={editorRef}
Expand Down
12 changes: 12 additions & 0 deletions src/components/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import React from 'react';

// Return the document object with SSR.
export const useDocument = () => {
const [ok, setOk] = React.useState(false);
React.useEffect(() => {
setOk(true);
});
if (ok && typeof document !== 'undefined') {
return document;
}
};
Empty file removed src/lib/hooks.ts
Empty file.

0 comments on commit 2888928

Please sign in to comment.