Files
webstudio/packages/sdk-components-react/src/code-text.tsx
T
Oleg Isonen 8b998662a4 fix: add backwards compatibility for children in code text (#3270)
## Description

Initially we allowed using any component inside code text and now we
need to keep backwards compatibility because its not easy to migrate
that to pure text.

## Steps for reproduction

1. would need to find any old instance with code text that has other
instances inside
2. see that it still works
3. override it with new code property

## Code Review

- [ ] hi @istarkov , I need you to do
  - conceptual review (architecture, feature-correctness)
  - detailed review (read every line)
  - test it on preview

## Before requesting a review

- [ ] made a self-review
- [ ] added inline comments where things may be not obvious (the "why",
not "what")

## Before merging

- [ ] tested locally and on preview environment (preview dev login:
5de6)
- [ ] updated [test
cases](https://github.com/webstudio-is/webstudio/blob/main/apps/builder/docs/test-cases.md)
document
- [ ] added tests
- [ ] if any new env variables are added, added them to `.env.example`
and the `builder/env-check.js` if mandatory
2024-05-01 11:33:17 +02:00

44 lines
1.1 KiB
TypeScript

import {
type ElementRef,
type ComponentProps,
forwardRef,
type ForwardedRef,
} from "react";
export const defaultTag = "code";
const Placeholder = ({
innerRef,
...rest
}: {
innerRef: ForwardedRef<HTMLElement>;
}) => {
return (
<code {...rest} style={{ padding: 20 }} ref={innerRef}>
{`Open the "Settings" panel to edit the code.`}
</code>
);
};
export const CodeText = forwardRef<
ElementRef<typeof defaultTag>,
ComponentProps<typeof defaultTag> & { code?: string }
>(({ code, children, ...props }, ref) => {
// We are supporting children here for historical reasons, because
// the first version of this component allowed using any components inside the CodeText
// and we didn't want to migrate them to use code, also it's not entirely possible.
if (
(children === undefined && code === undefined) ||
String(code).trim().length === 0
) {
return <Placeholder innerRef={ref} {...props} />;
}
return (
<code {...props} ref={ref}>
{code ?? children}
</code>
);
});
CodeText.displayName = "CodeText";