Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: disclaimer embed refactor + disclaimer in article #2812

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"@babel/core": "^7.26.0",
"@ndla/preset-panda": "^0.0.48",
"@ndla/scripts": "^2.1.3",
"@ndla/types-backend": "^1.0.1",
"@ndla/types-backend": "^1.0.4",
"@ndla/types-embed": "^5.0.6-alpha.0",
"@ndla/types-taxonomy": "^1.0.30",
"@pandacss/dev": "^0.48.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ const SlateBlockPicker = ({
break;
}
case TYPE_DISCLAIMER: {
onInsertBlock(defaultDisclaimerBlock(t("form.disclaimer.default")));
onInsertBlock(defaultDisclaimerBlock());
break;
}
case TYPE_COMMENT_BLOCK: {
Expand Down
6 changes: 3 additions & 3 deletions src/components/SlateEditor/plugins/link/Link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const StyledPopoverContent = styled(PopoverContent, {
base: {
flexDirection: "row",
gap: "xsmall",
zIndex: "dropdown",
zIndex: "modal",
},
});

Expand Down Expand Up @@ -142,9 +142,9 @@ const Link = ({ attributes, editor, element, children }: Props) => {
};

return (
<DialogRoot open={editMode} onOpenChange={(details) => toggleEditMode(details.open)}>
<DialogRoot open={editMode} onOpenChange={(details) => toggleEditMode(details.open)} context="alert">
<PopoverRoot
modal={false}
modal
// eslint-disable-next-line jsx-a11y/no-autofocus
autoFocus={false}
onOpenChange={(details) => {
Expand Down
126 changes: 126 additions & 0 deletions src/components/SlateEditor/plugins/uuDisclaimer/DisclaimerField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/**
* Copyright (c) 2024-present, NDLA.
*
* This source code is licensed under the GPLv3 license found in the
* LICENSE file in the root directory of this source tree.
*
*/

import { TextArea, Text, FieldRoot, FieldHelper, FieldErrorMessage } from "@ndla/primitives";
import { styled } from "@ndla/styled-system/jsx";
import { ContentEditableFieldLabel } from "../../../Form/ContentEditableFieldLabel";
import { FormField } from "../../../FormField";
import { SlatePlugin } from "../../interfaces";
import RichTextEditor from "../../RichTextEditor";
import { RichTextIndicator } from "../../RichTextIndicator";
import { breakPlugin } from "../break";
import { breakRenderer } from "../break/render";
import { linkPlugin } from "../link";
import { linkRenderer } from "../link/render";
import { markPlugin } from "../mark";
import { markRenderer } from "../mark/render";
import { noopPlugin } from "../noop";
import { noopRenderer } from "../noop/render";
import { paragraphPlugin } from "../paragraph";
import { paragraphRenderer } from "../paragraph/render";
import saveHotkeyPlugin from "../saveHotkey";
import { spanPlugin } from "../span";
import { spanRenderer } from "../span/render";
import { textTransformPlugin } from "../textTransform";
import { toolbarPlugin } from "../toolbar";
import { createToolbarAreaOptions, createToolbarDefaultValues } from "../toolbar/toolbarState";

const toolbarOptions = createToolbarDefaultValues({
text: {
hidden: true,
},
mark: {
code: {
hidden: true,
},
},
block: { hidden: true },
inline: {
hidden: true,
"content-link": { hidden: false },
},
});

export const toolbarAreaFilters = createToolbarAreaOptions();

export const disclaimerPlugins: SlatePlugin[] = [
spanPlugin,
paragraphPlugin,
toolbarPlugin(toolbarOptions, toolbarAreaFilters),
textTransformPlugin,
breakPlugin,
saveHotkeyPlugin,
markPlugin,
noopPlugin,
linkPlugin,
];

const renderers: SlatePlugin[] = [
noopRenderer,
paragraphRenderer,
markRenderer,
breakRenderer,
spanRenderer,
linkRenderer,
];

const plugins = disclaimerPlugins.concat(renderers);

const StyledTextArea = styled(TextArea, {
base: {
minHeight: "surface.3xsmall",
height: "unset",
},
});

const StyledText = styled(Text, {
base: {
width: "unset!",
top: "xsmall!",
},
});

interface Props {
submitted: boolean;
title: string;
description: string;
}

export const DisclaimerField = ({ submitted, title, description }: Props) => {
return (
<FormField name="disclaimer">
{({ field, meta, helpers }) => (
<FieldRoot invalid={!!meta.error}>
<ContentEditableFieldLabel>
{title}
<RichTextIndicator />
</ContentEditableFieldLabel>
<FieldHelper textStyle="body.medium">{description}</FieldHelper>
<StyledTextArea asChild>
<RichTextEditor
{...field}
submitted={submitted}
onChange={helpers.setValue}
hideBlockPicker
plugins={plugins}
toolbarOptions={toolbarOptions}
toolbarAreaFilters={toolbarAreaFilters}
noArticleStyling
renderPlaceholder={(placeholder) => (
<StyledText {...placeholder.attributes} textStyle="body.article" asChild consumeCss>
<span>{placeholder.children}</span>
</StyledText>
)}
/>
</StyledTextArea>
<FieldErrorMessage>{meta.error}</FieldErrorMessage>
</FieldRoot>
)}
</FormField>
);
};
156 changes: 13 additions & 143 deletions src/components/SlateEditor/plugins/uuDisclaimer/DisclaimerForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,42 +7,15 @@
*/

import { Formik, FormikValues } from "formik";
import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useState } from "react";
import { Dispatch, SetStateAction, useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Descendant } from "slate";
import { DeleteBinLine } from "@ndla/icons";
import {
Button,
ComboboxLabel,
DialogBody,
FieldErrorMessage,
FieldLabel,
FieldRoot,
IconButton,
ListItemContent,
ListItemHeading,
ListItemRoot,
Text,
TextArea,
} from "@ndla/primitives";
import { SafeLink } from "@ndla/safelink";
import { styled } from "@ndla/styled-system/jsx";
import { IArticleSummaryV2DTO, IArticleV2DTO } from "@ndla/types-backend/article-api";
import { Button, DialogBody } from "@ndla/primitives";
import { UuDisclaimerEmbedData } from "@ndla/types-embed";
import { getArticle } from "../../../../modules/article/articleApi";
import { useArticleSearch } from "../../../../modules/article/articleQueries";
import { plainTextToEditorValue, editorValueToPlainText } from "../../../../util/articleContentConverter";
import { routes } from "../../../../util/routeHelpers";
import { usePaginatedQuery } from "../../../../util/usePaginatedQuery";
import { GenericComboboxInput, GenericComboboxItemContent } from "../../../abstractions/Combobox";
import { GenericSearchCombobox } from "../../../Form/GenericSearchCombobox";
import { FormField } from "../../../FormField";
import { DisclaimerField } from "./DisclaimerField";
import { inlineContentToEditorValue, inlineContentToHTML } from "../../../../util/articleContentConverter";
import { FormActionsContainer, FormikForm } from "../../../FormikForm";
import validateFormik, { RulesType } from "../../../formikValidationSchema";
import PlainTextEditor from "../../PlainTextEditor";

const DISCLAIMER_EXAMPLES_LINK =
"https://docs.google.com/spreadsheets/d/1g8cCqgS4BvaChHX4R6VR5V5Q83fvYcMrgneBJMkLWYs/edit?usp=sharing";

interface DisclaimerFormProps {
initialData?: UuDisclaimerEmbedData;
Expand All @@ -52,7 +25,6 @@ interface DisclaimerFormProps {

interface DisclaimerFormValues {
resource: "uu-disclaimer";
articleId?: string;
disclaimer: Descendant[];
}

Expand All @@ -65,44 +37,20 @@ const rules: RulesType<DisclaimerFormValues> = {
const toInitialValues = (data?: UuDisclaimerEmbedData): DisclaimerFormValues => {
return {
resource: "uu-disclaimer",
disclaimer: plainTextToEditorValue(data?.disclaimer ?? ""),
articleId: data?.articleId,
disclaimer: inlineContentToEditorValue(data?.disclaimer ?? "", true),
};
};

const StyledTextArea = styled(TextArea, {
base: {
minHeight: "unset",
height: "unset",
},
});

const DisclaimerForm = ({ initialData, onOpenChange, onSave }: DisclaimerFormProps) => {
const { t, i18n } = useTranslation();
const { t } = useTranslation();
const initialValues = useMemo(() => toInitialValues(initialData), [initialData]);
const initialErrors = useMemo(() => validateFormik(initialValues, rules, t), [initialValues, t]);
const [selectedArticle, setSelectedArticle] = useState<IArticleV2DTO | IArticleSummaryV2DTO | undefined>(undefined);
const { query, delayedQuery, setQuery, page, setPage } = usePaginatedQuery();

const searchQuery = useArticleSearch({ query: delayedQuery, page: page }, { placeholderData: (prev) => prev });

useEffect(() => {
const initSelectedArticle = async () => {
let response: IArticleV2DTO | undefined = undefined;
if (initialValues.articleId) {
response = await getArticle(Number(initialValues.articleId));
}
setSelectedArticle(response ?? undefined);
};
initSelectedArticle();
}, [initialValues.articleId]);

const handleSubmit = useCallback(
(values: FormikValues) => {
onSave({
resource: "uu-disclaimer",
disclaimer: editorValueToPlainText(values.disclaimer),
articleId: values.articleId,
disclaimer: inlineContentToHTML(values.disclaimer),
});
onOpenChange(false);
},
Expand All @@ -117,92 +65,14 @@ const DisclaimerForm = ({ initialData, onOpenChange, onSave }: DisclaimerFormPro
validateOnMount
validate={(values) => validateFormik(values, rules, t)}
>
{() => (
{({ isSubmitting }) => (
<DialogBody>
<FormikForm>
<Text>{t("form.disclaimer.exampleHeader")}</Text>
<Text>{t("form.disclaimer.exampleText")}</Text>
<SafeLink to={DISCLAIMER_EXAMPLES_LINK}>{t("form.disclaimer.exampleLinkText")}</SafeLink>
<FormField name="disclaimer">
{({ field, meta }) => (
<FieldRoot>
<FieldLabel>{t("form.disclaimer.editorHeader")}</FieldLabel>
<StyledTextArea asChild>
<PlainTextEditor
data-testid="disclaimer-editor"
id={field.name}
{...field}
value={initialValues.disclaimer}
/>
</StyledTextArea>
<FieldErrorMessage>{meta.error}</FieldErrorMessage>
</FieldRoot>
)}
</FormField>
<FormField name="articleId">
{({ field, helpers }) => {
const handleChange = (selected: IArticleSummaryV2DTO | undefined) => {
helpers.setValue(selected?.id.toString() ?? "");
setSelectedArticle(selected);
};
return (
<FieldRoot>
<GenericSearchCombobox
items={searchQuery.data?.results ?? []}
itemToString={(item) => item.title.title}
itemToValue={(item) => item.id.toString()}
inputValue={query}
isSuccess={searchQuery.isSuccess}
paginationData={searchQuery.data}
onInputValueChange={(details) => setQuery(details.inputValue)}
onPageChange={(details) => setPage(details.page)}
value={[field.value?.toString()]}
onValueChange={(details) => handleChange(details.items[0])}
renderItem={(item) => (
<GenericComboboxItemContent
title={item.title.title}
description={item.metaDescription?.metaDescription}
image={item.metaImage}
useFallbackImage
/>
)}
>
<ComboboxLabel>{t("form.disclaimer.articleId")}</ComboboxLabel>
<GenericComboboxInput
placeholder={t("form.content.relatedArticle.placeholder")}
isFetching={searchQuery.isFetching}
/>
</GenericSearchCombobox>
{!!selectedArticle && (
<ListItemRoot variant="subtle">
<ListItemContent>
<ListItemHeading asChild>
<SafeLink
to={routes.editArticle(selectedArticle.id, selectedArticle.articleType, i18n.language)}
unstyled
>
{selectedArticle.title.title}
</SafeLink>
</ListItemHeading>
<IconButton
aria-label={t("form.disclaimer.removeArticle")}
variant="danger"
title={t("form.disclaimer.removeArticle")}
data-testid="disclaimerArticleDeleteButton"
onClick={() => {
helpers.setValue("");
setSelectedArticle(undefined);
}}
>
<DeleteBinLine />
</IconButton>
</ListItemContent>
</ListItemRoot>
)}
</FieldRoot>
);
}}
</FormField>
<DisclaimerField
submitted={isSubmitting}
title={t("form.disclaimer.editorHeader")}
description={t("form.disclaimer.description")}
/>
<FormActionsContainer>
<Button onClick={() => onOpenChange(false)} variant="secondary">
{t("form.abort")}
Expand Down
Loading
Loading