Skip to content

Commit

Permalink
update use-design hooks to accept router, url and config to load the …
Browse files Browse the repository at this point in the history
…final design
  • Loading branch information
softmarshmallow committed Nov 2, 2021
1 parent 87f0dca commit 323f2db
Show file tree
Hide file tree
Showing 10 changed files with 159 additions and 79 deletions.
12 changes: 9 additions & 3 deletions editor/layout/loading-overlay/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,20 @@ import styled from "@emotion/styled";
* [design](https://www.figma.com/file/HSozKEVWhh8saZa2vr1Nxd/design-to-code?node-id=554%3A6162)
* @returns
*/
function LoadingLayout() {
function LoadingLayout({
title = "Loading",
content = "We are now loading design remotely..",
}: {
title?: string;
content?: string;
}) {
return (
<RootWrapperLoadingLayout>
<Frame61>
<Frame5>
<Loading>Loading</Loading>
<Loading>{title}</Loading>
<WeAreNowLoadingDesignRemotely>
We are now loading design remotely..
{content}
</WeAreNowLoadingDesignRemotely>
</Frame5>
</Frame61>
Expand Down
2 changes: 1 addition & 1 deletion editor/pages/figma/inspect-component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { make_instance_component_meta } from "@code-features/component";

export default function InspectComponent() {
//
const design = useDesign();
const design = useDesign({ type: "use-router" });
if (!design) {
return <LoadingLayout />;
}
Expand Down
2 changes: 1 addition & 1 deletion editor/pages/figma/inspect-frame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import LoadingLayout from "../../layout/loading-overlay";
*/
export default function InspectAutolayout() {
//
const design = useDesign();
const design = useDesign({ type: "use-router" });
if (!design) {
return <LoadingLayout />;
}
Expand Down
2 changes: 1 addition & 1 deletion editor/pages/figma/inspect-raw.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import LoadingLayout from "../../layout/loading-overlay";
*/
export default function InspectRaw() {
//
const design = useDesign();
const design = useDesign({ type: "use-router" });
if (!design) {
return <LoadingLayout />;
}
Expand Down
2 changes: 1 addition & 1 deletion editor/pages/figma/to-flutter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { CodeEditor, MonacoEditor } from "../../components/code-editor";
import LoadingLayout from "../../layout/loading-overlay";

export default function FigmaToFlutterPage() {
const design = useDesign();
const design = useDesign({ type: "use-router" });
const [result, setResult] = useState<output.ICodeOutput>();

useEffect(() => {
Expand Down
2 changes: 1 addition & 1 deletion editor/pages/figma/to-token.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { RemoteImageRepositories } from "@design-sdk/figma-remote/lib/asset-repo
import LoadingLayout from "../../layout/loading-overlay";

export default function FigmaToReflectWidgetTokenPage() {
const design = useDesign();
const design = useDesign({ type: "use-router" });

if (!design) {
return <LoadingLayout />;
Expand Down
15 changes: 14 additions & 1 deletion editor/pages/live/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import React from "react";
import Pusher from "pusher-js";
import { useState } from "react";
import { useEffect } from "react";
import LoadingLayout from "../../layout/loading-overlay";
import { useDesign } from "../../query-hooks";

const _base_url =
"https://ahzdf5x4q3.execute-api.us-west-1.amazonaws.com/production"; // "https://assistant-live-session.grida.cc";
Expand All @@ -15,6 +17,14 @@ const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY, {
export default function LiveSessionPage() {
// const [channel, setChannel] = useState<string>();
const [lastmessage, setLastmessage] = useState<string>();
const [filekey, setFilekey] = useState<string>();
const [nodeid, setNodeid] = useState<string>();

const design = useDesign({
type: "use-file-node-id",
file: filekey,
node: nodeid,
});

useEffect(() => {
// TODO: - add auth guard
Expand All @@ -34,7 +44,10 @@ export default function LiveSessionPage() {
</>
) : (
<>
<p>No session connection</p>
<LoadingLayout
title="Select design on figma"
content="Design selected on figma will be displayed here. On Assistant, Menu - Live - Connect"
/>
</>
)}
</div>
Expand Down
2 changes: 1 addition & 1 deletion editor/pages/to-code/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import { WidgetTree } from "../../components/visualization/json-visualization/js

export default function DesignToCodeUniversalPage() {
const router = useRouter();
const design = useDesign();
const design = useDesign({ type: "use-router", router: router });
const [result, setResult] = useState<Result>();
const [preview, setPreview] = useState<Result>();

Expand Down
180 changes: 115 additions & 65 deletions editor/query-hooks/use-design.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useRouter } from "next/router";
import { NextRouter, useRouter } from "next/router";
import { useEffect, useState } from "react";
import { DesignProvider, analyzeDesignUrl } from "@design-sdk/url-analysis";
import {
Expand All @@ -24,76 +24,126 @@ configure_auth_credentials({
*/
const P_DESIGN = "design";

export function useDesign(
options: { use_session_cache?: boolean } = { use_session_cache: true }
) {
type UseDesignProp =
| (UseDesignFromRouter & UseDesingOptions)
| (UseDesingFromUrl & UseDesingOptions)
| (UseDesignFromFileAndNode & UseDesingOptions);

interface UseDesingOptions {
use_session_cache?: boolean;
}

interface UseDesignFromRouter {
type: "use-router";
router?: NextRouter;
}

interface UseDesingFromUrl {
type: "use-url";
url: string;
}

interface UseDesignFromFileAndNode {
type: "use-file-node-id";
file: string;
node: string;
}

export function useDesign({
use_session_cache = true,
type,
...props
}: UseDesignProp) {
const [design, setDesign] = useState<TargetNodeConfig>(null);
const router = useRouter();
const router = (type === "use-router" && props["router"]) ?? useRouter();
useEffect(() => {
const designparam: string = router.query[P_DESIGN] as string;
let targetnodeconfig: FigmaTargetNodeConfig;
if (designparam) {
const _r = analyze(designparam);
switch (_r) {
case "id":
// todo
// load design from local storage
// setDesign(designparam);
break;
case "figma":
// load design from local storage or remote figma
targetnodeconfig = parseFileAndNodeId(designparam);
const cacheStore = new RemoteDesignSessionCacheStore({
url: targetnodeconfig.url,
});
// cache control
if (options.use_session_cache && cacheStore.exists) {
const last_response = cacheStore.get();
const _1_converted_to_figma = mapFigmaRemoteToFigma(
last_response.nodes[targetnodeconfig.node]
);
const _2_converted_to_reflect = convert.intoReflectNode(
_1_converted_to_figma
);
console.log("type", type);
switch (type) {
case "use-file-node-id": {
if (props["file"] && props["node"]) {
targetnodeconfig = {
file: props["file"],
node: props["node"],
url: `https://www.figma.com/file/${props["file"]}/${props["node"]}`, // only supports figma for now. improve this line
};
}
break;
}
case "use-router": {
const designparam: string = router.query[P_DESIGN] as string;
const _r = designparam && analyze(designparam);
switch (_r) {
case "figma": {
targetnodeconfig = parseFileAndNodeId(designparam);
break;
}
case undefined: {
break;
}
default: {
throw new Error(`unknown design provider: ${_r}`);
// not supported
}
}
break;
}
case "use-url": {
targetnodeconfig = parseFileAndNodeId((props as UseDesingFromUrl).url);
break;
}
}

if (targetnodeconfig) {
// load design from local storage or remote figma

const cacheStore = new RemoteDesignSessionCacheStore({
file: targetnodeconfig.file,
node: targetnodeconfig.node,
});
// cache control
if (use_session_cache && cacheStore.exists) {
const last_response = cacheStore.get();
const _1_converted_to_figma = mapFigmaRemoteToFigma(
last_response.nodes[targetnodeconfig.node]
);
const _2_converted_to_reflect = convert.intoReflectNode(
_1_converted_to_figma
);
setDesign(<TargetNodeConfig>{
...targetnodeconfig,
raw: last_response,
figma: _1_converted_to_figma,
reflect: _2_converted_to_reflect,
});
} else {
fetch
.fetchTargetAsReflect({
file: targetnodeconfig.file,
node: targetnodeconfig.node,
auth: {
personalAccessToken: personal.get_safe(),
},
})
.then((res) => {
cacheStore.set(res.raw); // setting cache does not need to be determined by `use_session_cache` option.
setDesign(<TargetNodeConfig>{
...res,
...targetnodeconfig,
raw: last_response,
figma: _1_converted_to_figma,
reflect: _2_converted_to_reflect,
});
} else {
fetch
.fetchTargetAsReflect({
file: targetnodeconfig.file,
node: targetnodeconfig.node,
auth: {
personalAccessToken: personal.get_safe(),
},
})
.then((res) => {
cacheStore.set(res.raw); // setting cache does not need to be determined by `use_session_cache` option.
setDesign(<TargetNodeConfig>{
...res,
...targetnodeconfig,
});
})
.catch((err: FigmaRemoteErrors) => {
switch (err.type) {
case "UnauthorizedError": {
// unauthorized
router.push("/preferences/access-tokens");
console.info(`(ignored) error while fetching design`, err);
break;
}
default:
throw err;
}
});
}

break;
default:
break;
})
.catch((err: FigmaRemoteErrors) => {
switch (err.type) {
case "UnauthorizedError": {
// unauthorized
router.push("/preferences/access-tokens");
console.info(`(ignored) error while fetching design`, err);
break;
}
default:
throw err;
}
});
}
}
}, [router]);
Expand Down
19 changes: 15 additions & 4 deletions editor/store/remote-design-session-cache-store/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import { RawNodeResponse } from "@design-sdk/figma-remote";
import { parseFileAndNodeId } from "@design-sdk/figma-url";

/**
* Session cache for remote design. it works based on target url.
*/
export class RemoteDesignSessionCacheStore {
readonly url: string;
constructor({ url }: { url: string }) {
this.url = url;
readonly config: {
file: string;
node: string;
};

constructor(props: { url: string } | { file: string; node: string }) {
if ("url" in props) {
this.config = parseFileAndNodeId(props.url);
} else {
this.config = props;
}
}

set(raw: RawNodeResponse) {
Expand All @@ -27,6 +36,8 @@ export class RemoteDesignSessionCacheStore {
}

private get key() {
return `remote-design-session-cache-${this.url}`;
return `remote-design-session-cache-${
this.config.file + "-" + this.config.node
}`;
}
}

0 comments on commit 323f2db

Please sign in to comment.