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(editor): prefer useId when available #461

Merged
merged 2 commits into from
May 25, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
isolate generate id
  • Loading branch information
danilowoz committed May 16, 2022
commit 76fc29a67f63d11360e47b423680aeb82de38d35
16 changes: 4 additions & 12 deletions sandpack-react/src/components/CodeEditor/CodeMirror.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { getFileName } from "../../utils/stringUtils";

import { highlightDecorators } from "./highlightDecorators";
import { highlightInlineError } from "./highlightInlineError";
import { useGeneratedId } from "./useGeneratedId";
import {
getCodeMirrorLanguage,
getLanguageFromFile,
Expand Down Expand Up @@ -125,10 +126,7 @@ export const CodeMirror = React.forwardRef<CodeMirrorRef, CodeMirrorProps>(

const c = useClasser("sp");
const { listen } = useSandpack();
const generatedId = typeof React.useId === 'function' ?
React.useId() :
React.useRef<string>(generateRandomId()).current;
const ariaId = id ?? generatedId;
const ariaId = useGeneratedId(id);

const { isIntersecting } = useIntersectionObserver(wrapper, {
rootMargin: "600px 0px",
Expand Down Expand Up @@ -427,17 +425,11 @@ export const CodeMirror = React.forwardRef<CodeMirrorRef, CodeMirrorProps>(
</pre>

<>
<p
id={`enter-instructions-${ariaId}`}
style={{ display: "none" }}
>
<p id={`enter-instructions-${ariaId}`} style={{ display: "none" }}>
To enter the code editing mode, press Enter. To exit the edit mode,
press Escape
</p>
<p
id={`exit-instructions-${ariaId}`}
style={{ display: "none" }}
>
<p id={`exit-instructions-${ariaId}`} style={{ display: "none" }}>
You are editing the code. To exit the edit mode, press Escape
</p>
</>
Expand Down
13 changes: 13 additions & 0 deletions sandpack-react/src/components/CodeEditor/useGeneratedId.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable @typescript-eslint/ban-ts-comment */
import * as React from "react";

import { generateRandomId } from "../../utils/stringUtils";

export const useGeneratedId = (id?: string): string =>
id ??
// @ts-ignore
typeof React.useId === "function"
? // @ts-ignore
React.useId()
: React.useRef<string>(generateRandomId()).current;