Skip to content

Commit fbb9629

Browse files
committed
feat(react): extract common runtime code into reusable components
1 parent 17e964e commit fbb9629

3 files changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
export type ReplexicaBaseChunkProps = ReplexicaChunkSelector & {
2+
data: any;
3+
};
4+
5+
export function ReplexicaBaseChunk(props: ReplexicaBaseChunkProps) {
6+
return resolveChunkValue(props.data, {
7+
fileId: props.fileId,
8+
scopeId: props.scopeId,
9+
chunkId: props.chunkId,
10+
});
11+
}
12+
13+
export type ReplexicaChunkSelector = {
14+
fileId: string;
15+
scopeId: string;
16+
chunkId: string;
17+
};
18+
19+
export function resolveChunkValue(data: any, selector: ReplexicaChunkSelector) {
20+
const { fileId, scopeId, chunkId } = selector;
21+
const text = data?.[fileId]?.[scopeId]?.[chunkId];
22+
const fallback = `${fileId}.${scopeId}.${chunkId}`;
23+
return text || fallback;
24+
}

packages/react/src/shared/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export * from './chunk';
2+
export * from './proxy';
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { createElement } from "react";
2+
import { ReplexicaBaseChunkProps, resolveChunkValue } from "./chunk";
3+
4+
export type ReplexicaBaseProxyProps<P extends {}> = P & {
5+
data: any;
6+
_ReplexicaComponent: string | React.ComponentType<P>;
7+
_ReplexicaAttributes: Record<keyof P, Omit<ReplexicaBaseChunkProps, 'data'>>;
8+
};
9+
10+
export function ReplexicaBaseProxy<P extends {}>(props: ReplexicaBaseProxyProps<P>) {
11+
const { _ReplexicaAttributes, _ReplexicaComponent, data, ...originalProps } = props;
12+
let propsPatch: Partial<P> = {};
13+
14+
for (const [key, value] of Object.entries(_ReplexicaAttributes || {})) {
15+
const selector = value as Omit<ReplexicaBaseChunkProps, 'data'>;
16+
const result = resolveChunkValue(data, selector);
17+
18+
propsPatch = {
19+
...propsPatch,
20+
[key]: result,
21+
};
22+
}
23+
24+
const modifiedProps: P = {
25+
...originalProps,
26+
...propsPatch,
27+
} as any;
28+
29+
return createElement(
30+
_ReplexicaComponent,
31+
modifiedProps,
32+
);
33+
}

0 commit comments

Comments
 (0)