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

styled #50

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
16 changes: 5 additions & 11 deletions app/components/CodeEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,13 @@ export default function CodeEditor({
onChange: OnChange;
state: Record<string, any>;
}) {
const {
name,
defaultValue,
height,
label,
help,
tooltipPlacement,
...restProps
} = props;
const { name, defaultValue, height, label, help, tooltipPlacement, ...args } =
props;
const [inputRef, value, setValue] = useGooeyStringInput<HTMLTextAreaElement>({
state,
name,
defaultValue,
args,
});
const handleChange = (val: string) => {
setValue(val);
Expand All @@ -73,7 +67,7 @@ export default function CodeEditor({
};

return (
<div className="mb-4 code-editor-wrapper position-relative">
<div className="gui-input code-editor-wrapper position-relative">
<InputLabel
label={label}
help={help}
Expand All @@ -98,7 +92,7 @@ export default function CodeEditor({
value={value}
onChange={handleChange}
extensions={[javascript(), lintGutter(), jsLinter(lintOptions)]}
{...restProps}
{...args}
/>
</div>
);
Expand Down
1 change: 1 addition & 0 deletions app/components/GooeySelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export default function GooeySelect({
defaultValue,
name,
onChange,
args,
});

// if the state value is changed by the server code, then update the value
Expand Down
23 changes: 23 additions & 0 deletions app/gooeyInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export function GooeyTextarea({
state,
name,
defaultValue,
args,
});
return (
<div className="gui-input gui-input-textarea">
Expand Down Expand Up @@ -74,6 +75,7 @@ export function GooeyInput({
state,
name,
defaultValue,
args,
});
return (
<div className={className}>
Expand All @@ -100,10 +102,12 @@ export function useGooeyStringInput<
state,
name,
defaultValue,
args,
}: {
state: Record<string, any>;
name: string;
defaultValue: string;
args?: Record<string, any>;
}): [
inputRef: React.RefObject<E>,
value: string,
Expand All @@ -117,6 +121,8 @@ export function useGooeyStringInput<
// but to avoid reloading the page on every change with onChange (gets very annoying when typing), we need to use this extra state variable with a useEffect
const [value, setValue] = useState<string>(state[name] || defaultValue);

loadEventHandlers(value, setValue, args);

useEffect(() => {
const element = inputRef.current;
if (
Expand Down Expand Up @@ -234,3 +240,20 @@ export function useGooeyCheckedInput({

return inputRef;
}

export function loadEventHandlers<T>(
value: T,
setValue: (value: T) => void,
args?: Record<string, any>
) {
if (!args) return;
for (const [attr, body] of Object.entries(args)) {
if (!attr.startsWith("on")) continue;
args[attr] = (event: React.SyntheticEvent) => {
// new Function(...args, body)
const fn = new Function("event", "value", "setValue", body);
// fn.call(thisArg, ...args)
return fn.call(event.currentTarget, event.nativeEvent, value, setValue);
};
}
}
5 changes: 5 additions & 0 deletions app/jsonFormInput.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
import React, { useEffect, useRef, useState } from "react";
import { loadEventHandlers } from "./gooeyInput";

export function useJsonFormInput<T>({
defaultValue,
name,
onChange,
encode = JSON.stringify,
decode = JSON.parse,
args,
}: {
defaultValue: T;
name: string;
onChange?: () => void;
encode?: (value: T) => string;
decode?: (value: string) => T;
args?: Record<string, any>;
}): [React.FunctionComponent, T, (value: T) => void] {
const [value, setValue] = useState(defaultValue);
const ref = useRef<HTMLInputElement>(null);

loadEventHandlers(value, setValue, args);

useEffect(() => {
if (!ref.current) return;
if (!ref.current.value) {
Expand Down
8 changes: 8 additions & 0 deletions app/renderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ function RenderedTreeNode({
children={children}
onChange={onChange}
state={state}
className={props.className}
/>
);
case "nav-tab-content":
Expand Down Expand Up @@ -526,10 +527,12 @@ export function RenderedChildren({
children,
onChange,
state,
className,
}: {
children: Array<TreeNode>;
onChange: OnChange;
state: Record<string, any>;
className?: string;
}) {
let elements = children.map((node, idx) => {
let key;
Expand All @@ -538,6 +541,10 @@ export function RenderedChildren({
} else {
key = `idx:${idx}`;
}
let prevClassName = node.props.className || "";
if (className && !prevClassName.includes(className)) {
node.props.className = `${className} ${prevClassName}`;
}
return (
<RenderedTreeNode
key={key}
Expand Down Expand Up @@ -621,6 +628,7 @@ export function GuiExpander({
defaultValue: open,
name,
onChange,
args: props,
});

return (
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 35 additions & 4 deletions py/gooey_gui/components/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,18 @@
BLANK_OPTION = "———"


StyleProp = typing.Optional[
typing.TypedDict(
"StyleProp",
{
"selector": dict[str, dict[str, str]],
"@media": dict[str, dict[str, str]],
},
total=False,
)
]


def _default_format(value: typing.Any) -> str:
if value is None:
return BLANK_OPTION
Expand Down Expand Up @@ -54,17 +66,17 @@ def nav_tab_content():
return _node("nav-tab-content")


def div(**props) -> core.NestingCtx:
return tag("div", **props)
def div(*, style: StyleProp = None, **props) -> core.NestingCtx:
return tag("div", style=style, **props)


def link(*, to: str, **props) -> core.NestingCtx:
return _node("Link", to=to, **props)


def tag(tag_name: str, **props) -> core.NestingCtx:
def tag(tag_name: str, *, style: StyleProp = None, **props) -> core.NestingCtx:
props["__reactjsxelement"] = tag_name
return _node("tag", **props)
return _node("tag", style=style, **props)


def html(body: str, **props):
Expand Down Expand Up @@ -115,11 +127,30 @@ def markdown(


def _node(nodename: str, **props):
if style := props.get("style"):
selector = style.pop("selector", None)
if selector:
identifier = "." + core.md5_values(selector)
for s, rules in selector.items():
_node("css-in-js", selector=s.replace("&", identifier), rules=rules)
props["className"] = " ".join(
filter(None, (props.get("className"), identifier))
)
# media = style.pop("@media", None)
node = core.RenderTreeNode(name=nodename, props=props)
node.mount()
return core.NestingCtx(node)


def styled(css: str) -> core.RenderTreeNode:
css = dedent(css).strip()
className = "gui-" + core.md5_values(css)
selector = "." + className
css = css.replace("&", selector)
core.add_styles(className, css)
return _node("", className=className)


def text(body: str, **props):
core.RenderTreeNode(
name="pre",
Expand Down
9 changes: 8 additions & 1 deletion py/gooey_gui/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@
realtime_clear_subs,
md5_values,
)
from .renderer import RenderTreeNode, NestingCtx, renderer, route, current_root_ctx
from .renderer import (
RenderTreeNode,
NestingCtx,
renderer,
route,
current_root_ctx,
add_styles,
)
from .state import (
get_session_state,
set_session_state,
Expand Down
14 changes: 14 additions & 0 deletions py/gooey_gui/core/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ def current_root_ctx() -> "NestingCtx":
return threadlocal.root_ctx


def add_styles(className: str, css: str):
threadlocal.styles[className] = css


class RenderTreeNode(BaseModel):
name: str
props: ReactHTMLProps = {}
Expand Down Expand Up @@ -108,17 +112,27 @@ def renderer(
set_query_params(query_params or {})
realtime_clear_subs()
threadlocal.use_state_count = 0
threadlocal.styles = {}
while True:
try:
root = RenderTreeNode(name="root")
threadlocal.root_ctx = NestingCtx(root)
with threadlocal.root_ctx:
styles_node = RenderTreeNode(
name="tag",
props=dict(__reactjsxelement="style"),
).mount()
try:
ret = render()
except StopException:
ret = None
except RedirectException as e:
return RedirectResponse(e.url, status_code=e.status_code)
if threadlocal.styles:
styles_node.props["dangerouslySetInnerHTML"] = {
"__html": "\n".join(threadlocal.styles.values())
}
print(get_subscriptions())
if isinstance(ret, Response):
return ret
return JSONResponse(
Expand Down
Loading