This commit is contained in:
Tom Moor committed 2024-07-24 21:48:54 -04:00
1 parent c636c4e5df
commit 36682574c6
16 files changed
+294 -41

No files matched your search

+2 -1
View File
@@ -1,6 +1,7 @@
import { PlusIcon } from "outline-icons";
import * as React from "react";
import stores from "~/stores";
import { DataAttributeNew } from "~/components/DataAttribute/DataAttributeNew";
import { createAction } from "..";
import { SettingsSection } from "../sections";
@@ -18,7 +19,7 @@ export const createDataAttribute = createAction({
stores.dialogs.openModal({
title: t("New attribute"),
// content: TODO
content: <DataAttributeNew onSubmit={stores.dialogs.closeAllModals} />,
});
},
});
@@ -0,0 +1,161 @@
import capitalize from "lodash/capitalize";
import { observer } from "mobx-react";
import { PlusIcon } from "outline-icons";
import * as React from "react";
import { Controller, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import {
DataAttributeDataType,
type DataAttributeOptions,
} from "@shared/models/types";
import { DataAttributeValidation } from "@shared/validations";
import DataAttribute from "~/models/DataAttribute";
import Button from "~/components/Button";
import Flex from "~/components/Flex";
import Input from "~/components/Input";
import InputSelect from "../InputSelect";
import NudeButton from "../NudeButton";
import Switch from "../Switch";
export interface FormData {
name: string;
description?: string;
dataType: DataAttributeDataType;
options?: DataAttributeOptions;
pinned: boolean;
}
export const DataAttributeForm = observer(function DataAttributeForm_({
handleSubmit,
dataAttribute,
}: {
handleSubmit: (data: FormData) => void;
dataAttribute?: DataAttribute;
}) {
const { t } = useTranslation();
const {
register,
handleSubmit: formHandleSubmit,
formState,
watch,
control,
setFocus,
setValue,
} = useForm<FormData>({
mode: "all",
defaultValues: {
name: dataAttribute?.name,
description: dataAttribute?.description ?? undefined,
dataType: dataAttribute?.dataType ?? DataAttributeDataType.String,
options: dataAttribute?.options ?? undefined,
pinned: dataAttribute?.pinned ?? false,
},
});
React.useEffect(() => {
setTimeout(() => setFocus("name", { shouldSelect: true }), 100);
}, [setFocus]);
const values = watch();
return (
<form onSubmit={formHandleSubmit(handleSubmit)}>
<Controller
control={control}
name="dataType"
render={({ field }) => (
<InputSelect
ref={field.ref}
value={field.value}
onChange={(value: DataAttributeDataType) => {
field.onChange(value);
if (value === DataAttributeDataType.List) {
setValue("options", { options: [""] });
}
}}
ariaLabel={t("Format")}
label={t("Format")}
options={Object.values(DataAttributeDataType).map((dataType) => ({
value: dataType,
label: t(capitalize(dataType)),
}))}
/>
)}
/>
{values.dataType === DataAttributeDataType.List && (
<Flex column gap={8}>
{values.options?.options?.map((option, index) => (
<div key={index}>
<Input
value={option}
type="text"
autoComplete="off"
autoFocus
flex
/>
</div>
))}
<Controller
control={control}
name="options"
render={({ field }) => (
<NudeButton
disabled={
(values.options?.options?.length ?? 0) >=
DataAttributeValidation.maxOptions
}
onClick={() => {
field.onChange({
options: [...(field.value?.options ?? []), ""],
});
}}
>
<PlusIcon />
</NudeButton>
)}
/>
</Flex>
)}
<Input
type="text"
label={t("Name")}
{...register("name", {
required: true,
maxLength: DataAttributeValidation.maxNameLength,
})}
autoComplete="off"
autoFocus
flex
/>
<Input
type="text"
label={t("Description")}
{...register("description", {
maxLength: DataAttributeValidation.maxDescriptionLength,
})}
autoComplete="off"
flex
/>
<Switch
id="pinned"
label={t("Pinned")}
note={t("Pinned attributes are shown at the top of documents.")}
{...register("pinned")}
/>
<Flex justify="flex-end">
<Button
type="submit"
disabled={formState.isSubmitting || !formState.isValid}
>
{dataAttribute
? formState.isSubmitting
? `${t("Saving")}…`
: t("Save")
: formState.isSubmitting
? `${t("Creating")}…`
: t("Create")}
</Button>
</Flex>
</form>
);
});
@@ -0,0 +1,30 @@
import { observer } from "mobx-react";
import * as React from "react";
import { toast } from "sonner";
import DataAttribute from "~/models/DataAttribute";
import useStores from "~/hooks/useStores";
import { DataAttributeForm, FormData } from "./DataAttributeForm";
type Props = {
onSubmit: () => void;
};
export const DataAttributeNew = observer(function DataAttributeNew_({
onSubmit,
}: Props) {
const { dataAttributes } = useStores();
const handleSubmit = React.useCallback(
async (data: FormData) => {
try {
const dataAttribute = new DataAttribute(data, dataAttributes);
await dataAttribute.save();
onSubmit?.();
} catch (error) {
toast.error(error.message);
}
},
[dataAttributes, onSubmit]
);
return <DataAttributeForm handleSubmit={handleSubmit} />;
});
+4 -1
View File
@@ -21,6 +21,7 @@ import { useTranslation } from "react-i18next";
import { integrationSettingsPath } from "@shared/utils/routeHelpers";
import ZapierIcon from "~/components/Icons/ZapierIcon";
import { Hook, PluginManager } from "~/utils/PluginManager";
import { Feature, FeatureFlags } from "~/utils/FeatureFlags";
import isCloudHosted from "~/utils/isCloudHosted";
import lazy from "~/utils/lazyWithRetry";
import { settingsPath } from "~/utils/routeHelpers";
@@ -125,7 +126,9 @@ const useSettingsConfig = () => {
name: t("Attributes"),
path: settingsPath("attributes"),
component: DataAttributes,
enabled: can.createDataAttribute,
enabled:
can.createDataAttribute &&
FeatureFlags.isEnabled(Feature.dataAttributes),
group: t("Workspace"),
icon: DatabaseIcon,
},
+6
View File
@@ -62,6 +62,12 @@ export default class Document extends ParanoidModel {
@observable
lastViewedAt: string | undefined;
@observable
dataAttributes: {
dataAttributeId: string;
value: string;
}[];
store: DocumentsStore;
@Field
View File
Whitespace-only changes.
+26 -1
View File
@@ -20,11 +20,12 @@ import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import useTextSelection from "~/hooks/useTextSelection";
import InsightsMenu from "~/menus/InsightsMenu";
import { Feature, FeatureFlags } from "~/utils/FeatureFlags";
import { documentPath } from "~/utils/routeHelpers";
import Sidebar from "./SidebarLayout";
function Insights() {
const { views, documents } = useStores();
const { views, dataAttributes, documents } = useStores();
const { t } = useTranslation();
const match = useRouteMatch<{ documentSlug: string }>();
const history = useHistory();
@@ -44,6 +45,9 @@ function Insights() {
useKeyDown("Escape", onCloseInsights);
// Temporarily here, insights will be removed / renamed.
const hasDataAttributes = FeatureFlags.isEnabled(Feature.dataAttributes);
return (
<Sidebar title={t("Insights")} onClose={onCloseInsights}>
{document ? (
@@ -54,6 +58,27 @@ function Insights() {
justify="space-between"
>
<div>
{hasDataAttributes && (
<Content column>
<Heading>{t("Data attributes")}</Heading>
{dataAttributes.orderedData.map((dataAttribute) => (
<Text
as="p"
type="secondary"
size="small"
key={dataAttribute.id}
>
{dataAttribute.name}:{" "}
{
document.dataAttributes?.find(
(da) => da.dataAttributeId === dataAttribute.id
)?.value
}
</Text>
))}
</Content>
)}
<Content column>
{document.sourceMetadata && (
<>
+3
View File
@@ -4,11 +4,14 @@ import Storage from "@shared/utils/Storage";
export enum Feature {
/** New collection permissions UI */
newCollectionSharing = "newCollectionSharing",
/** Document data attributes */
dataAttributes = "dataAttributes",
}
/** Default values for feature flags */
const FeatureDefaults: Record<Feature, boolean> = {
[Feature.newCollectionSharing]: true,
[Feature.dataAttributes]: false,
};
/**
@@ -109,7 +109,15 @@ module.exports = {
value: {
type: Sequelize.STRING,
allowNull: false,
}
},
createdAt: {
type: Sequelize.DATE,
allowNull: false,
},
updatedAt: {
type: Sequelize.DATE,
allowNull: false,
},
}, {
transaction
});
+1 -1
View File
@@ -69,7 +69,7 @@ class DataAttribute extends ParanoidModel<
// hooks
@BeforeCreate
static async checkMaximumAttributes(model: DataAttribute) {
const count = await DataAttribute.count({
const count = await this.count({
where: {
teamId: model.teamId,
},
+2 -2
View File
@@ -9,7 +9,7 @@ import {
import DataAttribute from "./DataAttribute";
import Document from "./Document";
import User from "./User";
import Model from "./base/Model";
import IdModel from "./base/IdModel";
import Fix from "./decorators/Fix";
@Table({
@@ -17,7 +17,7 @@ import Fix from "./decorators/Fix";
modelName: "document_data_attribute",
})
@Fix
class DocumentDataAttribute extends Model<
class DocumentDataAttribute extends IdModel<
InferAttributes<DocumentDataAttribute>,
Partial<InferCreationAttributes<DocumentDataAttribute>>
> {
+8 -7
View File
@@ -1,14 +1,15 @@
import DocumentDataAttribute from "@server/models/DocumentDataAttribute";
import DataAttribute from "@server/models/DataAttribute";
export default function presentDocumentDataAttribute(
dataAttribute: DocumentDataAttribute
) {
export default function presentDataAttribute(dataAttribute: DataAttribute) {
return {
id: dataAttribute.id,
value: dataAttribute.value,
dataAttributeId: dataAttribute.dataAttributeId,
documentId: dataAttribute.documentId,
name: dataAttribute.name,
description: dataAttribute.description,
dataType: dataAttribute.dataType,
options: dataAttribute.options,
pinned: dataAttribute.pinned,
createdAt: dataAttribute.createdAt,
updatedAt: dataAttribute.updatedAt,
deletedAt: dataAttribute.deletedAt,
};
}
+3 -4
View File
@@ -3,7 +3,7 @@ import { Document } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
import { TextHelper } from "@server/models/helpers/TextHelper";
import { APIContext } from "@server/types";
import presentDocumentDataAttribute from "./dataAttribute";
import presentDocumentDataAttribute from "./documentDataAttribute";
import presentUser from "./user";
type Options = {
@@ -77,9 +77,8 @@ async function presentDocument(
if (!options.isPublic) {
const source = await document.$get("import");
data.dataAttributes = document.dataAttributes?.map(
presentDocumentDataAttribute(dataAttribute)
) ?? [];
data.dataAttributes =
document.dataAttributes?.map(presentDocumentDataAttribute) ?? [];
data.isCollectionDeleted = await document.isCollectionDeleted();
data.collectionId = document.collectionId;
data.parentDocumentId = document.parentDocumentId;
+7 -8
View File
@@ -1,15 +1,14 @@
import DataAttribute from "@server/models/DataAttribute";
import type DocumentDataAttribute from "@server/models/DocumentDataAttribute";
export default function presentDataAttribute(dataAttribute: DataAttribute) {
export default function presentDocumentDataAttribute(
dataAttribute: DocumentDataAttribute
) {
return {
id: dataAttribute.id,
name: dataAttribute.name,
description: dataAttribute.description,
dataType: dataAttribute.dataType,
options: dataAttribute.options,
pinned: dataAttribute.pinned,
value: dataAttribute.value,
dataAttributeId: dataAttribute.dataAttributeId,
documentId: dataAttribute.documentId,
createdAt: dataAttribute.createdAt,
updatedAt: dataAttribute.updatedAt,
deletedAt: dataAttribute.deletedAt,
};
}
+23 -15
View File
@@ -1,5 +1,5 @@
import z from "zod";
import { DataAttributeDataType } from "@server/models/DataAttribute";
import { DataAttributeDataType } from "@shared/models/types";
import { BaseSchema } from "../schema";
const BaseIdSchema = z.object({
@@ -34,24 +34,32 @@ export const DataAttributesListSchema = BaseSchema.extend({
export type DataAttributesListReq = z.infer<typeof DataAttributesListSchema>;
export const DataAttributesCreateSchema = BaseSchema.extend({
body: z.object({
/** Name of the data attribute */
name: z.string(),
body: z
.object({
/** Name of the data attribute */
name: z.string(),
/** Description of the data attribute */
description: z.string().optional(),
/** Description of the data attribute */
description: z.string().optional(),
/** Type of the data attribute */
dataType: z.nativeEnum(DataAttributeDataType),
/** Type of the data attribute */
dataType: z.nativeEnum(DataAttributeDataType),
/** Options for the data attribute (if list type) */
options: z.object({
options: z.array(z.string()),
}),
/** Options for the data attribute (if list type) */
options: z
.object({
options: z.array(z.string()),
})
.optional(),
/** Whether the data attribute is pinned to the top of document */
pinned: z.boolean().optional(),
}),
/** Whether the data attribute is pinned to the top of document */
pinned: z.boolean().optional(),
})
.refine(
(val) =>
val.dataType !== DataAttributeDataType.List ||
(val.dataType === DataAttributeDataType.List && val.options)
),
});
export type DataAttributesCreateReq = z.infer<
+9
View File
@@ -34,8 +34,17 @@ export const DataAttributeValidation = {
/** The maximum length of the name */
maxNameLength: 255,
/** The maximum length of the description */
maxDescriptionLength: 1000,
/** The maximum number of data attributes */
max: 25,
/** The maximum number of data attributes that can be pinned */
maxPinned: 3,
/** The maximum number of options for a single attribute */
maxOptions: 10,
};
export const CollectionValidation = {