Files
outline/plugins/granola/client/Settings.tsx
T
Tom Moor 0c56aeeba2 Show Granola rules as source → destination (#14909)
* feat: Show Granola rules as source → destination with a row menu

* fix: Keep Granola rule destinations readable and mirror the arrow in RTL

* chore: Simplify Granola rule menu and drop orphan translation
2026-12-05 21:27:39 -05:00

389 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { observer } from "mobx-react";
import { ArrowIcon, DocumentIcon, PlusIcon } from "outline-icons";
import { useCallback, useMemo } from "react";
import { useTranslation, Trans } from "react-i18next";
import styled, { useTheme } from "styled-components";
import { toast } from "sonner";
import Icon from "@shared/components/Icon";
import { ellipsis, s } from "@shared/styles";
import { IntegrationService, IntegrationType } from "@shared/types";
import { errToString } from "@shared/utils/error";
import { Avatar, AvatarSize } from "~/components/Avatar";
import Button from "~/components/Button";
import Flex from "~/components/Flex";
import Heading from "~/components/Heading";
import { DropdownMenu } from "~/components/Menu/DropdownMenu";
import { OverflowMenuButton } from "~/components/Menu/OverflowMenuButton";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import List from "~/components/List";
import ListItem from "~/components/List/Item";
import Text from "~/components/Text";
import Time from "~/components/Time";
import env from "~/env";
import useCurrentUser from "~/hooks/useCurrentUser";
import { useMenuAction } from "~/hooks/useMenuAction";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import type Integration from "~/models/Integration";
import type Policy from "~/models/Policy";
import type User from "~/models/User";
import { ConnectedButton } from "~/scenes/Settings/components/ConnectedButton";
import { IntegrationScene } from "~/scenes/Settings/components/IntegrationScene";
import type { PartialExcept } from "~/types";
import { client } from "~/utils/ApiClient";
import { ActionSeparator, createAction } from "~/actions";
import { SettingsSection } from "~/actions/sections";
import type { GranolaRule } from "../shared/types";
import GranolaIcon from "./Icon";
import { GranolaConnectButton } from "./components/GranolaButton";
import RuleDialog from "./components/RuleDialog";
interface Connection {
id: string;
userId: string;
createdAt: string;
}
interface ListResponse {
data: Connection[];
users: PartialExcept<User, "id">[];
policies: Policy[];
}
function Granola() {
const { integrations, users } = useStores();
const user = useCurrentUser();
const { t } = useTranslation();
const appName = env.APP_NAME;
const integration = integrations.find({
type: IntegrationType.LinkedAccount,
service: IntegrationService.Granola,
userId: user.id,
}) as Integration<IntegrationType.LinkedAccount> | undefined;
const settings = integration?.settings?.granola;
const fetchConnections = useCallback(async () => {
const res = await client.post<ListResponse>("/granola.list");
res.users.forEach((item) => users.add(item));
// The rules come from the store, and another tab can change the connection.
res.data
.filter((item) => item.userId === user.id)
.forEach((item) => integrations.add(item));
integrations.addPolicies(res.policies);
return res.data;
}, [users, integrations, user.id]);
const { data: connections, request: refresh } = useRequest(
fetchConnections,
true
);
const handleDisconnect = useCallback(
async (id: string) => {
await client.post("/integrations.delete", { id });
if (integrations.get(id)) {
integrations.remove(id);
}
await refresh();
},
[integrations, refresh]
);
return (
<IntegrationScene title="Granola" icon={<GranolaIcon />}>
<Heading>Granola</Heading>
<Text as="p">
<Trans>
Link your Granola account to {{ appName }} and your meeting notes will
show up as documents as soon as they’re ready. Everyone connects their
own account and chooses where their notes go.
</Trans>
</Text>
{connections &&
(connections.length ? (
<>
<Heading as="h2">
<Flex justify="space-between" auto>
{t("Connected")}
{!integration && (
<GranolaConnectButton
icon={<PlusIcon />}
onConnect={refresh}
/>
)}
</Flex>
</Heading>
<List>
{connections.map((connection) => (
<ConnectionItem
key={connection.id}
connection={connection}
onDisconnect={handleDisconnect}
/>
))}
</List>
</>
) : (
<p>
<GranolaConnectButton icon={<GranolaIcon />} onConnect={refresh} />
</p>
))}
{integration && settings ? (
<Rules integration={integration} rules={settings.rules} />
) : null}
</IntegrationScene>
);
}
interface ConnectionItemProps {
connection: Connection;
onDisconnect: (id: string) => Promise<void>;
}
const ConnectionItem = observer(function ConnectionItem({
connection,
onDisconnect,
}: ConnectionItemProps) {
const { t } = useTranslation();
const { users, policies } = useStores();
const user = useCurrentUser();
const owner = users.get(connection.userId);
const canDelete = policies.abilities(connection.id).delete;
const isOwn = connection.userId === user.id;
return (
<ListItem
small
title={
isOwn
? t("{{ userName }} (you)", { userName: owner?.name })
: (owner?.name ?? t("Unknown user"))
}
subtitle={
<>
<Trans>Connected on</Trans>{" "}
<Time
dateTime={connection.createdAt}
relative={false}
format={{ en_US: "MMMM d, y" }}
/>
</>
}
image={owner ? <Avatar model={owner} size={AvatarSize.Large} /> : null}
actions={
canDelete ? (
<ConnectedButton
onClick={() => onDisconnect(connection.id)}
confirmationMessage={
isOwn
? t(
"Disconnecting will stop creating documents from your new meeting notes. Are you sure?"
)
: t(
"Disconnecting will stop creating documents from new meeting notes by {{ userName }}. Are you sure?",
{ userName: owner?.name }
)
}
/>
) : null
}
/>
);
});
interface RulesProps {
integration: Integration<IntegrationType.LinkedAccount>;
rules: GranolaRule[];
}
const Rules = observer(function Rules({ integration, rules }: RulesProps) {
const { t } = useTranslation();
const { collections, documents, dialogs, integrations } = useStores();
const theme = useTheme();
const save = useCallback(
async (next: GranolaRule[]) => {
try {
const res = await client.post("/granola.update", {
id: integration.id,
rules: next,
});
integrations.add(res.data);
} catch (err) {
toast.error(errToString(err));
throw err;
}
},
[integration.id, integrations]
);
const openDialog = (index?: number) => {
const rule = index === undefined ? undefined : rules[index];
dialogs.openModal({
title: rule ? t("Edit rule") : t("Add rule"),
content: (
<RuleDialog
integrationId={integration.id}
rule={rule}
usedFolderIds={rules
.filter((_, i) => i !== index)
.map((other) => other.folderId)}
onSubmit={async (updated) => {
await save(
index === undefined
? [...rules, updated]
: rules.map((other, i) => (i === index ? updated : other))
);
dialogs.closeAllModals();
}}
/>
),
});
};
const locationName = (rule: GranolaRule) =>
(rule.documentId && documents.get(rule.documentId)?.title) ||
(rule.collectionId && collections.get(rule.collectionId)?.name) ||
rule.locationName ||
t("Unknown location");
const locationIcon = (rule: GranolaRule) => {
const document = rule.documentId
? documents.get(rule.documentId)
: undefined;
if (document?.icon) {
return (
<Icon
value={document.icon}
initial={document.initial}
color={document.color ?? undefined}
/>
);
}
if (rule.documentId) {
return <DocumentIcon color={theme.textSecondary} />;
}
const collection = rule.collectionId
? collections.get(rule.collectionId)
: undefined;
return collection ? <CollectionIcon collection={collection} /> : null;
};
return (
<>
<Heading as="h2">
<Flex justify="space-between" auto>
{t("Rules")}
<Button icon={<PlusIcon />} onClick={() => openDialog()} neutral>
{t("Add rule")}
</Button>
</Flex>
</Heading>
{rules.length ? (
<List>
{rules.map((rule, index) => (
<ListItem
key={rule.folderId ?? "*"}
small
title={
<Flex align="center" gap={4}>
<Name>
{rule.folderId === null
? t("All other notes")
: (rule.folderName ?? rule.folderId)}
</Name>
<Arrow size={18} />
<LocationIcon>{locationIcon(rule)}</LocationIcon>
<Name>{locationName(rule)}</Name>
</Flex>
}
actions={
<RuleMenu
onEdit={() => openDialog(index)}
onDelete={() =>
save(rules.filter((_, i) => i !== index)).catch(
() => undefined
)
}
/>
}
/>
))}
</List>
) : (
<Text as="p" type="secondary">
<Trans>
Add a rule to choose where your notes are saved. Notes that don’t
match a rule won’t be added.
</Trans>
</Text>
)}
</>
);
});
const Name = styled.span`
${ellipsis()}
min-width: 0;
max-width: 50%;
`;
interface RuleMenuProps {
/** Called when the user chooses to edit the rule. */
onEdit: () => void;
/** Called when the user chooses to delete the rule. */
onDelete: () => void;
}
function RuleMenu({ onEdit, onDelete }: RuleMenuProps) {
const { t } = useTranslation();
const actions = useMemo(
() => [
createAction({
name: `${t("Edit")}…`,
section: SettingsSection,
perform: onEdit,
}),
ActionSeparator,
createAction({
name: t("Delete"),
section: SettingsSection,
dangerous: true,
perform: onDelete,
}),
],
[t, onEdit, onDelete]
);
const rootAction = useMenuAction(actions);
return (
<DropdownMenu action={rootAction} align="end" ariaLabel={t("Rule")}>
<OverflowMenuButton />
</DropdownMenu>
);
}
const LocationIcon = styled.span`
display: flex;
flex-shrink: 0;
&:empty {
display: none;
}
`;
const Arrow = styled(ArrowIcon)`
flex-shrink: 0;
color: ${s("textTertiary")};
[dir="rtl"] & {
transform: rotate(180deg);
}
`;
export default observer(Granola);