close #18 impl hidden trait

This commit is contained in:
Yanzhen Yu 2021-07-27 10:44:19 +08:00
parent 617784bdf2
commit 0f7825613a
2 changed files with 126 additions and 0 deletions

View File

@ -0,0 +1,79 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>meta-ui runtime example: hidden trait</title>
</head>
<body>
<div id="root"></div>
<script type="module">
import renderApp from "../../src/main.tsx";
renderApp({
version: "example/v1",
metadata: {
name: "hidden_trait",
description: "hidden trait example",
},
spec: {
components: [
{
id: "btn",
type: "chakra_ui/v1/button",
properties: {
text: {
raw: "toggle text",
format: "plain",
},
},
traits: [
{
type: "core/v1/state",
properties: {
key: "count",
initialValue: 0,
},
},
{
type: "core/v1/event",
properties: {
events: [
{
event: "click",
componentId: "btn",
method: {
name: "setValue",
parameters: "{{ btn.count + 1 }}",
},
wait: {},
disabled: false,
},
],
},
},
],
},
{
id: "text",
type: "core/v1/text",
properties: {
value: {
raw: "hidden with condition",
format: "plain",
},
},
traits: [
{
type: "core/v1/hidden",
properties: {
hidden: "{{ btn.count % 2 === 0 }}",
},
},
],
},
],
},
});
</script>
</body>
</html>

View File

@ -0,0 +1,47 @@
import React from "react";
import { createTrait } from "@meta-ui/core";
import { Static, Type } from "@sinclair/typebox";
import { TraitImplementation } from "../../registry";
import { useExpression } from "../../store";
type HiddenProps = {
hidden: Static<typeof HiddenPropertySchema>;
};
const Hidden: React.FC<HiddenProps> = ({ hidden: _hidden, children }) => {
const hidden = useExpression(_hidden.toString());
if (hidden) {
return null;
}
return <>{children}</>;
};
const useHiddenState: TraitImplementation<HiddenProps> = ({ hidden }) => {
return {
props: null,
component: (props) => <Hidden {...props} hidden={hidden} />,
};
};
const HiddenPropertySchema = Type.Union([Type.Boolean(), Type.String()]);
export default {
...createTrait({
version: "core/v1",
metadata: {
name: "hidden",
description: "render component with condition",
},
spec: {
properties: [
{
name: "hidden",
...HiddenPropertySchema,
},
],
state: {},
methods: [],
},
}),
impl: useHiddenState,
};