Skip to content

Commit

Permalink
chore: refactor import and block structure
Browse files Browse the repository at this point in the history
  • Loading branch information
itsjoeoui committed Nov 27, 2023
1 parent e241a2d commit c4e0d7b
Show file tree
Hide file tree
Showing 14 changed files with 62 additions and 41 deletions.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
6 changes: 0 additions & 6 deletions captain/blocks/button.py

This file was deleted.

6 changes: 0 additions & 6 deletions captain/blocks/gamepad.py

This file was deleted.

4 changes: 3 additions & 1 deletion captain/controllers/reactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from captain.types.flowchart import BlockID, FCBlock, FlowChart
from captain.utils.blocks import import_blocks, is_ui_input

BLOCKS_DIR = os.path.join("captain", "blocks")
BLOCKS_DIR = os.path.join("blocks")

ZIPPED_BLOCKS = [] # TODO: I (sasha) am anti zip in all cases.

Expand Down Expand Up @@ -183,6 +183,8 @@ def __init__(

funcs = import_blocks(BLOCKS_DIR)

print(funcs, flush=True)

for block in flowchart.blocks:
if is_ui_input(funcs[block.block_type]):
logger.debug(f"Creating UI input for {block.id}")
Expand Down
6 changes: 5 additions & 1 deletion captain/types/flowchart.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@

# TODO: This is hardcoded for now
BlockType = Literal[
"slider", "gamepad", "button", "bignum", "add", "subtract", "constant"
"flojoy.control.slider",
"flojoy.visualization.bignum",
"flojoy.math.arithmetic.add",
"flojoy.math.arithmetic.subtract",
"flojoy.math.constant",
]

BlockID: TypeAlias = str
Expand Down
45 changes: 31 additions & 14 deletions captain/utils/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,47 @@
import os
from typing import Callable, Mapping

from captain.logging import logger


def import_blocks(blocks_dir: str) -> Mapping[str, Callable]:
# example key: "flojoy.math.arithmetic.add"
functions = {}
for file in os.listdir(blocks_dir):
full_path = os.path.join(blocks_dir, file)
if not os.path.isfile(full_path) or not file.endswith(".py"):
continue

block_name = file.strip(".py")
spec = importlib.util.spec_from_file_location(block_name, full_path)
for root, _, files in os.walk(blocks_dir):
for file in files:
if not file.endswith(".py"):
continue

block_name = file.strip(".py")

block_path = os.path.join(root, file)

# block_type is something like "flojoy.math.arithmetic.add"
block_type = os.path.relpath(
os.path.splitext(block_path)[0], blocks_dir
).replace("/", ".")

if not spec:
raise ValueError(f"Invalid block spec from {full_path}")
spec = importlib.util.spec_from_file_location(block_name, block_path)

module = importlib.util.module_from_spec(spec)
if not spec.loader:
raise ValueError(f"Could not get loader from {full_path}")
if not spec:
raise ValueError(f"Invalid block spec from {block_path}")

spec.loader.exec_module(module)
func = getattr(module, block_name)
functions[block_name] = func
module = importlib.util.module_from_spec(spec)
if not spec.loader:
raise ValueError(f"Could not get loader from {block_path}")

spec.loader.exec_module(module)
func = getattr(module, block_name)

logger.info(f"importing {block_type}")
functions[block_type] = func

return functions


def is_ui_input(func: Callable) -> bool:
return getattr(func, "ui_input", False)


import_blocks("blocks")
6 changes: 3 additions & 3 deletions src/renderer/src/components/flow/BlockCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/

type Props = {
name: string;
block_id: string;
block_type: string;
desc: string;
};

const BlockCard = ({ name, desc, block_id }: Props): JSX.Element => {
const BlockCard = ({ name, desc, block_type }: Props): JSX.Element => {
const onDragStart = (event, nodeType) => {
event.dataTransfer.setData('application/reactflow', nodeType);
event.dataTransfer.effectAllowed = 'move';
Expand All @@ -24,7 +24,7 @@ const BlockCard = ({ name, desc, block_id }: Props): JSX.Element => {
className=""
variant="secondary"
draggable
onDragStart={(event) => onDragStart(event, block_id)}
onDragStart={(event) => onDragStart(event, block_type)}
>
<div>{name}</div>
</Button>
Expand Down
10 changes: 7 additions & 3 deletions src/renderer/src/components/flow/BlocksLibrary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,13 @@ const BlocksLibrary = () => {
</div>
<div className="py-2"></div>
<div className="flex flex-col gap-2">
<BlockCard name="Add" desc="Add a bunch of stuff together" block_id="add" />
<BlockCard name="Slider" desc="it slides" block_id="slider" />
<BlockCard name="Big Number" desc="Big number" block_id="bignum" />
<BlockCard
name="Add"
desc="Add a bunch of stuff together"
block_type="flojoy.math.arithmetic.add"
/>
<BlockCard name="Slider" desc="it slides" block_type="flojoy.control.slider" />
<BlockCard name="Big Number" desc="Big number" block_type="flojoy.visualization.bignum" />
</div>
</div>
);
Expand Down
12 changes: 6 additions & 6 deletions src/renderer/src/components/flow/FlowCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ import useUndoRedo from '@/hooks/useUndoRedo';
// import useUndoRedo from '@/hooks/useUndoRedo';

const nodeTypes = {
slider: SliderBlock,
bignum: BigNumberBlock,
add: AddBlock
'flojoy.control.slider': SliderBlock,
'flojoy.visualization.bignum': BigNumberBlock,
'flojoy.math.arithmetic.add': AddBlock
};

const edgeTypes = {
Expand Down Expand Up @@ -84,10 +84,10 @@ const FlowCanvas = () => {
return;
}

const block_id = event.dataTransfer.getData('application/reactflow');
const block_type = event.dataTransfer.getData('application/reactflow');

// check if the dropped element is valid
if (typeof block_id === 'undefined' || !block_id) {
if (typeof block_type === 'undefined' || !block_type) {
return;
}

Expand All @@ -99,7 +99,7 @@ const FlowCanvas = () => {
y: event.clientY
});

addNode(block_id, position);
addNode(block_type, position);
},
[reactFlowInstance]
);
Expand Down
8 changes: 7 additions & 1 deletion src/renderer/src/types/block.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { NodeProps } from 'reactflow';

export type BlockType = 'slider' | 'gamepad' | 'button' | 'bignum' | 'add' | 'subtract';
// TODO: This should not be hardcoded
export type BlockType =
| 'flojoy.control.slider'
| 'flojoy.visualization.bignum'
| 'flojoy.math.arithmetic.add'
| 'flojoy.math.arithmetic.subtract'
| 'flojoy.math.constant';

export type BlockData = {
block_type: BlockType;
Expand Down

0 comments on commit c4e0d7b

Please sign in to comment.