Skip to content
Draft
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
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.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "roamjs-components",
"description": "Expansive toolset, utilities, & components for developing RoamJS extensions.",
"version": "0.85.1",
"version": "1.0.0-beta.2",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
Expand Down
21 changes: 17 additions & 4 deletions src/components/BlockInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ import {
MenuItem,
InputGroup,
} from "@blueprintjs/core";
import React, { useCallback, useMemo, useRef, useState } from "react";
import React, {
useCallback,
useMemo,
useRef,
useState,
useEffect,
} from "react";
import getAllBlockUidsAndTexts from "../queries/getAllBlockUidsAndTexts";
import useArrowKeyDown from "../hooks/useArrowKeyDown";

Expand All @@ -29,16 +35,23 @@ const BlockInput = ({
setValue: (q: string, uid?: string) => void;
onBlur?: (v: string) => void;
onConfirm?: () => void;
getAllBlocks?: () => { text: string; uid: string }[];
getAllBlocks?: () => Promise<{ text: string; uid: string }[]>;
autoFocus?: boolean;
}): React.ReactElement => {
const [isOpen, setIsOpen] = useState(false);
const [allBlocks, setAllBlocks] = useState<{ text: string; uid: string }[]>(
[]
);
const open = useCallback(() => setIsOpen(true), [setIsOpen]);
const close = useCallback(() => setIsOpen(false), [setIsOpen]);
const allBlocks = useMemo(getAllBlocks, []);

useEffect(() => {
getAllBlocks().then(setAllBlocks);
}, [getAllBlocks]);
Comment on lines +48 to +50
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Error handling recommended for useEffect

While the implementation correctly uses useEffect to fetch data asynchronously when the component mounts or when getAllBlocks changes, it lacks error handling for the Promise.

- useEffect(() => {
-   getAllBlocks().then(setAllBlocks);
- }, [getAllBlocks]);
+ useEffect(() => {
+   getAllBlocks()
+     .then(setAllBlocks)
+     .catch(error => {
+       console.error("Failed to load blocks:", error);
+       // Consider setting an error state or providing a fallback
+     });
+ }, [getAllBlocks]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
getAllBlocks().then(setAllBlocks);
}, [getAllBlocks]);
useEffect(() => {
getAllBlocks()
.then(setAllBlocks)
.catch(error => {
console.error("Failed to load blocks:", error);
// Consider setting an error state or providing a fallback
});
}, [getAllBlocks]);


const items = useMemo(
() => (value && isOpen ? searchBlocksByString(value, allBlocks) : []),
[value, allBlocks]
[value, allBlocks, isOpen]
);
const menuRef = useRef<HTMLUListElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
Expand Down
30 changes: 16 additions & 14 deletions src/components/ComponentContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,22 @@ export const createComponentRender =
(b: HTMLButtonElement, args?: OnloadArgs): void => {
if (b.parentElement) {
b.parentElement.onmousedown = (e: MouseEvent) => e.stopPropagation();
const blockUid = getBlockUidFromTarget(b);
const possibleBlockId = b.closest(".roam-block")?.id;
const blockId = possibleBlockId?.endsWith?.(blockUid)
? possibleBlockId
: undefined;
if (blockUid) {
renderWithUnmount(
<ComponentContainer blockId={blockId} className={className}>
<Fc blockUid={blockUid} />
</ComponentContainer>,
b.parentElement,
args
);
}
getBlockUidFromTarget(b).then((blockUid) => {
if (!b.parentElement) return;
const possibleBlockId = b.closest(".roam-block")?.id;
const blockId = possibleBlockId?.endsWith?.(blockUid)
? possibleBlockId
: undefined;
if (blockUid) {
renderWithUnmount(
<ComponentContainer blockId={blockId} className={className}>
<Fc blockUid={blockUid} />
</ComponentContainer>,
b.parentElement,
args
);
}
});
}
};

Expand Down
62 changes: 41 additions & 21 deletions src/components/ConfigPage.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { Card, Tab, Tabs } from "@blueprintjs/core";
import React, { useCallback, useMemo, useRef, useState } from "react";
import React, {
useCallback,
useMemo,
useRef,
useState,
useEffect,
} from "react";
import ReactDOM from "react-dom";
import createHTMLObserver from "../dom/createHTMLObserver";
import createBlock from "../writes/createBlock";
Expand All @@ -11,7 +17,7 @@ import localStorageGet from "../util/localStorageGet";
import idToTitle from "../util/idToTitle";
import type { Field, UnionField } from "./ConfigPanels/types";
import { Brand } from "./ConfigPanels/getBrandColors";
import { InputTextNode } from "../types";
import { InputTextNode, RoamBasicNode } from "../types";

export type ConfigTab = {
id: string;
Expand Down Expand Up @@ -61,12 +67,25 @@ const FieldTabs = ({
});
return newUid;
}, [pageUid, uid, id, toggleable]);
const childUids = Object.fromEntries(
getShallowTreeByParentUid(parentUid).map(({ text, uid }) => [
text.toLowerCase().trim(),
uid,
])
);

const [childUids, setChildUids] = useState<Record<string, string>>({});

useEffect(() => {
const loadChildUids = async () => {
try {
const tree = await getShallowTreeByParentUid(parentUid);
setChildUids(
Object.fromEntries(
tree.map(({ text, uid }) => [text.toLowerCase().trim(), uid])
)
);
} catch (error) {
console.error("Failed to load child UIDs:", error);
}
};
loadChildUids();
}, [parentUid]);

const [selectedTabId, setSelectedTabId] = useState(
fields.length && typeof toggleable !== "string"
? fields[0].title
Expand Down Expand Up @@ -121,11 +140,16 @@ const ConfigPage = ({
? config.tabs.filter((t) => t.fields.length || t.toggleable)
: [{ fields: config, id: "home" }];
const [selectedTabId, setSelectedTabId] = useState(userTabs[0]?.id);
const [tree, setTree] = useState<RoamBasicNode[]>([]);

useEffect(() => {
getBasicTreeByParentUid(pageUid).then(setTree);
}, [pageUid]);

const onTabsChange = useCallback(
(tabId: string) => setSelectedTabId(tabId),
[setSelectedTabId]
);
const tree = getBasicTreeByParentUid(pageUid);

// first character trimmed intentionally for the `v` below
const titleRef = useRef<HTMLDivElement>(null);
Expand Down Expand Up @@ -248,18 +272,18 @@ const createConfigPage = ({
});
};

export const render = ({
export const render = async ({
h,
title,
pageUid = getPageUidByPageTitle(title),
pageUid,
config,
}: {
h: HTMLHeadingElement;
title: string;
pageUid?: string;
config: Config;
}) => {
const uid = getPageUidByPageTitle(title);
const uid = pageUid || (await getPageUidByPageTitle(title));
const attribute = `data-roamjs-${uid}`;
const containerParent = h.parentElement?.parentElement;
if (containerParent && !containerParent.hasAttribute(attribute)) {
Expand All @@ -272,7 +296,7 @@ export const render = ({
h.parentElement?.nextElementSibling || null
);
ReactDOM.render(
<ConfigPage id={configPageId} config={config} pageUid={pageUid} />,
<ConfigPage id={configPageId} config={config} pageUid={uid} />,
parent
);
}
Expand All @@ -286,11 +310,12 @@ export const createConfigObserver = async ({
config: Config;
}): Promise<{ pageUid: string; observer?: MutationObserver }> => {
const pageUid =
getPageUidByPageTitle(title) ||
(await getPageUidByPageTitle(title)) ||
(await createConfigPage({
title,
config,
}));

if ("tabs" in config ? !!config.tabs.length : !!config.length) {
const observer = createHTMLObserver({
className: "rm-title-display",
Expand All @@ -307,14 +332,9 @@ export const createConfigObserver = async ({
}
},
});
return {
pageUid,
observer,
};
return { pageUid, observer };
}
return {
pageUid,
};
return { pageUid };
};

export default ConfigPage;
34 changes: 18 additions & 16 deletions src/components/ConfigPanels/BlocksPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,23 +28,25 @@ const BlocksPanel: FieldPanel<BlocksField> = ({
)
)
.then((formatUid) =>
getFirstChildUidByBlockUid(formatUid)
? formatUid
: (defaultValue?.length
? Promise.all(
defaultValue.map((node, order) =>
createBlock({
node,
parentUid: formatUid,
order,
})
getFirstChildUidByBlockUid(formatUid).then((childUid) =>
childUid
? formatUid
: (defaultValue?.length
? Promise.all(
defaultValue.map((node, order) =>
createBlock({
node,
parentUid: formatUid,
order,
})
)
)
)
: createBlock({
node: { text: " " },
parentUid: formatUid,
})
).then(() => formatUid)
: createBlock({
node: { text: " " },
parentUid: formatUid,
})
).then(() => formatUid)
)
)
.then((uid) => {
window.roamAlphaAPI.ui.components.renderBlock({
Expand Down
17 changes: 13 additions & 4 deletions src/components/ConfigPanels/MultiChildPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Button, Label } from "@blueprintjs/core";
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import getShallowTreeByParentUid from "../../queries/getShallowTreeByParentUid";
import idToTitle from "../../util/idToTitle";
import Description from "../Description";
Expand All @@ -22,10 +22,19 @@ const MultiChildPanel: FieldPanel<
InputComponent,
}) => {
const [uid, setUid] = useState(initialUid);
const [texts, setTexts] = useState(() =>
uid ? getShallowTreeByParentUid(uid) : []
);
const [texts, setTexts] = useState<{ text: string; uid: string }[]>([]);
const [value, setValue] = useState("");

useEffect(() => {
const loadTexts = async () => {
if (uid) {
const items = await getShallowTreeByParentUid(uid);
setTexts(items);
}
};
loadTexts();
}, [uid]);

return (
<>
<Label>
Expand Down
39 changes: 23 additions & 16 deletions src/components/ConfigPanels/OauthPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Button, Checkbox } from "@blueprintjs/core";
import React, { useCallback, useState } from "react";
import React, { useCallback, useState, useEffect } from "react";
import getBasicTreeByParentUid from "../../queries/getBasicTreeByParentUid";
import getShallowTreeByParentUid from "../../queries/getShallowTreeByParentUid";
import localStorageGet from "../../util/localStorageGet";
Expand All @@ -10,31 +10,38 @@ import Description from "../Description";
import ExternalLogin from "../ExternalLogin";
import type { OauthField, FieldPanel } from "./types";

type Accounts = { text: string; uid: string; data: string };

const OauthPanel: FieldPanel<OauthField> = ({ uid, parentUid, options }) => {
const key = `oauth-${options.service}`;
const [useLocal, setUseLocal] = useState(!!localStorageGet(key));
const [accounts, setAccounts] = useState<
{ text: string; uid: string; data: string }[]
>(() =>
useLocal
? JSON.parse(localStorageGet(key) as string)
: uid
? getBasicTreeByParentUid(uid).map((v) => ({
text: v.children[0]?.text ? v.text : "Default Account",
uid: v.uid,
data: v.children[0]?.text || v.text,
}))
: []
const [accounts, setAccounts] = useState<Accounts[]>(() =>
useLocal ? JSON.parse(localStorageGet(key) as string) : []
);

useEffect(() => {
if (!useLocal && uid) {
getBasicTreeByParentUid(uid).then((items) => {
setAccounts(
items.map((v) => ({
text: v.children[0]?.text ? v.text : "Default Account",
uid: v.uid,
data: v.children[0]?.text || v.text,
}))
);
});
}
}, [uid, useLocal]);

const onCheck = useCallback(
(e) => {
const checked = (e.target as HTMLInputElement).checked;
setUseLocal(checked);
if (checked) {
if (uid) {
getShallowTreeByParentUid(uid).forEach(({ uid: u }) =>
deleteBlock(u)
);
getShallowTreeByParentUid(uid).then((items) => {
items.forEach(({ uid: u }) => deleteBlock(u));
});
}
localStorageSet(key, JSON.stringify(accounts));
} else {
Expand Down
Loading