Files
vibemake-pcb-studio/common/jsx-runtime.ts
T
likang 1fde96c05e
CI / typecheck + test + build (push) Has been cancelled
打通vibemake
2026-11-05 16:21:37 +08:00

113 lines
2.9 KiB
TypeScript

// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Modified by VibeMake to localize UI text at the React boundary.
import {
createElement,
Fragment,
isValidElement,
type ComponentProps,
type ElementType,
type JSX as ReactJSX,
type Key,
type ReactNode,
} from 'react';
import { translateText } from './i18n.js';
const TEXT_PROPS = new Set([
'alt',
'aria-label',
'ariaLabel',
'caption',
'choices',
'description',
'header',
'headers',
'helpText',
'hint',
'items',
'label',
'listLabel',
'menus',
'minWidthText',
'options',
'placeholder',
'text',
'texts',
'title',
'tooltip',
]);
function localize(value: unknown): unknown {
if (typeof value === 'string') return translateText(value);
if (Array.isArray(value)) return value.map(localize);
if (
value &&
typeof value === 'object' &&
!isValidElement(value) &&
Object.getPrototypeOf(value) === Object.prototype
) {
const out = { ...(value as Record<string, unknown>) };
for (const key of TEXT_PROPS) {
if (key in out) out[key] = localize(out[key]);
}
return out;
}
return value;
}
function createLocalizedElement(
type: ElementType,
props: Record<string, unknown> | null,
key?: Key,
isStaticChildren = false,
): ReactJSX.Element {
const localized = { ...(props ?? {}) };
if (typeof localized.children === 'string' || Array.isArray(localized.children)) {
localized.children = localize(localized.children) as ReactNode;
}
for (const name of TEXT_PROPS) {
if (name in localized) localized[name] = localize(localized[name]);
}
if (key !== undefined) localized.key = key;
// JSX's static siblings are positional arguments to createElement, not a
// dynamic list. Preserve that distinction so React does not demand keys for
// ordinary markup, while nested mapped lists still receive key validation.
if (isStaticChildren && Array.isArray(localized.children)) {
return createElement(type, localized as ComponentProps<typeof type>, ...localized.children);
}
return createElement(type, localized as ComponentProps<typeof type>);
}
export function jsx(
type: ElementType,
props: Record<string, unknown> | null,
key?: Key,
): ReactJSX.Element {
return createLocalizedElement(type, props, key);
}
export function jsxs(
type: ElementType,
props: Record<string, unknown> | null,
key?: Key,
): ReactJSX.Element {
return createLocalizedElement(type, props, key, true);
}
export { Fragment };
export function jsxDEV(
type: ElementType,
props: Record<string, unknown> | null,
key?: Key,
isStaticChildren = false,
): ReactJSX.Element {
return createLocalizedElement(type, props, key, isStaticChildren);
}
export namespace JSX {
export type Element = ReactJSX.Element;
export interface IntrinsicElements extends ReactJSX.IntrinsicElements {}
export interface IntrinsicAttributes extends ReactJSX.IntrinsicAttributes {}
}