Skip to content

Commit

Permalink
feat(react): basic block and tour support
Browse files Browse the repository at this point in the history
  • Loading branch information
VojtechVidra committed Sep 20, 2024
1 parent f9b3005 commit 8c5ddfb
Show file tree
Hide file tree
Showing 20 changed files with 526 additions and 3 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"scripts": {
"e2e": "pnpm --filter e2e",
"js": "pnpm --filter js",
"react": "pnpm --filter react",
"tsc": "pnpm -r tsc",
"test": "pnpm -r test",
"lint": "pnpm -r lint",
Expand Down
50 changes: 47 additions & 3 deletions pnpm-lock.yaml

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

2 changes: 2 additions & 0 deletions workspaces/react/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
tsup.config.ts
dist
28 changes: 28 additions & 0 deletions workspaces/react/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const { resolve } = require("node:path");

const project = resolve(__dirname, "tsconfig.json");

module.exports = {
extends: [
require.resolve("@vercel/style-guide/eslint/browser"),
require.resolve("@vercel/style-guide/eslint/node"),
require.resolve("@vercel/style-guide/eslint/typescript"),
require.resolve("@vercel/style-guide/eslint/react"),
],
parserOptions: {
project,
},
settings: {
"import/resolver": {
typescript: {
project,
},
},
},
rules: {
"@typescript-eslint/naming-convention": 0,
"@typescript-eslint/restrict-template-expressions": 0,
"no-empty": "off",
"react/function-component-definition": "off",
},
};
1 change: 1 addition & 0 deletions workspaces/react/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
21 changes: 21 additions & 0 deletions workspaces/react/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Flows

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
33 changes: 33 additions & 0 deletions workspaces/react/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@flows/react",
"version": "0.0.1",
"description": "",
"scripts": {
"dev": "tsup --watch --env.NODE_ENV development",
"build": "tsup --env.NODE_ENV production && pnpm tsc -p tsconfig.dist.json",
"lint": "eslint src",
"tsc": "tsc -p tsconfig.json",
"version": "pnpm version"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/RBND-studio/flows-js.git"
},
"devDependencies": {
"@types/node": "^20.16.3",
"@types/react": "^18.3.7",
"tsup": "^8.2.4",
"typescript": "^5.5.4"
},
"peerDependencies": {
"react": ">=17.0.2"
},
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
}
}
}
48 changes: 48 additions & 0 deletions workspaces/react/src/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { type Block } from "./types";

const f = <T>(
url: string,
{ body, method }: { method?: string; body?: unknown } = {},
): Promise<T> =>
fetch(url, {
method,
headers: {
"Content-Type": "application/json",
},
body: body ? JSON.stringify(body) : undefined,
}).then(async (res) => {
const text = await res.text();
const resBody = (text ? JSON.parse(text) : undefined) as T;
if (!res.ok) {
const errorBody = resBody as undefined | { message?: string };
throw new Error(errorBody?.message ?? res.statusText);
}
return resBody;
});

interface GetBlocksRequest {
userId: string;
environment: string;
organizationId: string;
}

interface BlocksResponse {
blocks: Block[];
}

interface EventRequest {
userId: string;
environment: string;
organizationId: string;
name: string;
blockId: string;
propertyKey?: string;
properties?: Record<string, unknown>;
}

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type -- ignore
export const getApi = (apiUrl: string) => ({
getBlocks: (body: GetBlocksRequest) =>
f<BlocksResponse>(`${apiUrl}/v2/sdk/blocks`, { method: "POST", body }),
sendEvent: (body: EventRequest) => f(`${apiUrl}/v2/sdk/events`, { method: "POST", body }),
});
23 changes: 23 additions & 0 deletions workspaces/react/src/block.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { type FC } from "react";
import { type Block as IBlock } from "./types";
import { useFlowsContext } from "./flows-context";

interface Props {
block: IBlock;
}

export const Block: FC<Props> = ({ block }) => {
const { components, transition } = useFlowsContext();

const Component = components[block.type];
if (!Component) return null;
const methods = block.exitNodes.reduce(
(acc, exitNode) => ({
...acc,
[exitNode]: () => transition({ exitNode, blockId: block.id }),
}),
{},
);

return <Component key={block.id} {...block.data} {...methods} />;
};
28 changes: 28 additions & 0 deletions workspaces/react/src/flows-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { createContext, useContext } from "react";
import { type Block, type Components } from "./types";

export interface RunningTour {
block: Block;
currentBlockIndex: number;
setCurrentBlockIndex: (changeFn: (prevIndex: number) => number) => void;
activeStep?: Block;
}

export interface IFlowsContext {
blocks: Block[];
components: Components;
transition: (props: { exitNode: string; blockId: string }) => Promise<void>;
runningTours: RunningTour[];
}

// eslint-disable-next-line @typescript-eslint/no-empty-function -- ignore
const asyncNoop = async (): Promise<void> => {};
export const FlowsContext = createContext<IFlowsContext>({
blocks: [],
components: {},
transition: asyncNoop,
runningTours: [],
});

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type -- ignore
export const useFlowsContext = () => useContext(FlowsContext);
59 changes: 59 additions & 0 deletions workspaces/react/src/flows-provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { type FC, type ReactNode, useMemo } from "react";
import { getApi } from "./api";
import { type Components } from "./types";
import { Block } from "./block";
import { FlowsContext, type IFlowsContext } from "./flows-context";
import { useRunningTours } from "./use-running-tours";
import { useBlocks } from "./use-blocks";
import { getSlot } from "./selectors";
import { TourBlock } from "./tour-block";

interface Props {
children: ReactNode;
organizationId: string;
environment: string;
userId?: string;
apiUrl?: string;
components: Components;
}

export const FlowsProvider: FC<Props> = ({
children,
apiUrl = "https://api.flows-cloud.com",
environment,
organizationId,
userId,
components,
}) => {
const blocks = useBlocks({ apiUrl, environment, organizationId, userId });
const runningTours = useRunningTours(blocks);

const transition: IFlowsContext["transition"] = async ({ blockId, exitNode }) => {
await getApi(apiUrl).sendEvent({
userId: userId ?? "",
environment,
organizationId,
name: "transition",
blockId,
propertyKey: exitNode,
});
};

const floatingBlocks = useMemo(() => blocks.filter((b) => !getSlot(b)), [blocks]);
const floatingTourBlocks = useMemo(
() => runningTours.filter((b) => !getSlot(b.activeStep)),
[runningTours],
);

return (
<FlowsContext.Provider value={{ blocks, components, transition, runningTours }}>
{children}
{floatingBlocks.map((block) => {
return <Block block={block} key={block.id} />;
})}
{floatingTourBlocks.map((tour) => {
return <TourBlock key={tour.block.id} tour={tour} />;
})}
</FlowsContext.Provider>
);
};
Loading

0 comments on commit 8c5ddfb

Please sign in to comment.