@jpmorganchase/mosaic-content-editor-plugin 0.1.0-beta.72 → 0.1.0-beta.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/package.json +6 -3
  2. package/.turbo/turbo-build.log +0 -4
  3. package/CHANGELOG.md +0 -687
  4. package/src/components/ActionMenu/ActionMenu.css.ts +0 -9
  5. package/src/components/ActionMenu/ActionMenu.tsx +0 -26
  6. package/src/components/BaseToolbar/BaseToolbar.css.ts +0 -21
  7. package/src/components/BaseToolbar/BaseToolbar.tsx +0 -13
  8. package/src/components/BaseTooltray/BaseTooltray.css.ts +0 -31
  9. package/src/components/BaseTooltray/BaseTooltray.tsx +0 -22
  10. package/src/components/ContentEditor.tsx +0 -14
  11. package/src/components/Dialog.css.ts +0 -7
  12. package/src/components/Dialog.tsx +0 -12
  13. package/src/components/Editor.css.ts +0 -64
  14. package/src/components/Editor.tsx +0 -145
  15. package/src/components/EditorControls.css.ts +0 -6
  16. package/src/components/EditorControls.tsx +0 -37
  17. package/src/components/LinkEditor/EditLinkButton.tsx +0 -9
  18. package/src/components/LinkEditor/LinkEditor.css.ts +0 -15
  19. package/src/components/LinkEditor/LinkEditor.tsx +0 -136
  20. package/src/components/LinkEditor/SaveAdornment.tsx +0 -17
  21. package/src/components/PersistEditDialog/PersistStatus.css.ts +0 -21
  22. package/src/components/PersistEditDialog/PersistStatus.tsx +0 -57
  23. package/src/components/PersistEditDialog/__tests__/index.test.tsx +0 -90
  24. package/src/components/PersistEditDialog/index.css.ts +0 -14
  25. package/src/components/PersistEditDialog/index.tsx +0 -152
  26. package/src/components/Popper/Popper.css.ts +0 -12
  27. package/src/components/Popper/Popper.tsx +0 -36
  28. package/src/components/SaveButton.tsx +0 -23
  29. package/src/components/ScrollableSection/ScrollableSection.css.ts +0 -10
  30. package/src/components/ScrollableSection/ScrollableSection.tsx +0 -20
  31. package/src/components/StatusBanner.tsx +0 -16
  32. package/src/components/Toolbar/InsertBlockDropdown.tsx +0 -134
  33. package/src/components/Toolbar/InsertHorizontalRule.tsx +0 -18
  34. package/src/components/Toolbar/InsertImage.css.ts +0 -7
  35. package/src/components/Toolbar/InsertImage.tsx +0 -138
  36. package/src/components/Toolbar/InsertLink.css.ts +0 -7
  37. package/src/components/Toolbar/InsertLink.tsx +0 -148
  38. package/src/components/Toolbar/InsertTable.css.ts +0 -52
  39. package/src/components/Toolbar/InsertTable.tsx +0 -196
  40. package/src/components/Toolbar/TextFormatTooltray.css.ts +0 -22
  41. package/src/components/Toolbar/TextFormatTooltray.tsx +0 -113
  42. package/src/components/Toolbar/Toolbar.tsx +0 -52
  43. package/src/components/Toolbar/ToolbarButton.css.ts +0 -11
  44. package/src/components/Toolbar/ToolbarButton.tsx +0 -41
  45. package/src/components/Toolbar/ToolbarSeparator.css.ts +0 -28
  46. package/src/components/Toolbar/ToolbarSepartor.tsx +0 -13
  47. package/src/components/__tests__/EditorControls.test.tsx +0 -69
  48. package/src/components/__tests__/StatusBanner.test.tsx +0 -33
  49. package/src/hooks/useEditHistory.ts +0 -49
  50. package/src/hooks/useWorkflowFeed.ts +0 -69
  51. package/src/index.ts +0 -5
  52. package/src/nodes/index.ts +0 -23
  53. package/src/plugins/FloatingToolbarPlugin.css.ts +0 -14
  54. package/src/plugins/FloatingToolbarPlugin.tsx +0 -101
  55. package/src/plugins/HorizontalRulePlugin.tsx +0 -39
  56. package/src/plugins/MarkdownImagePlugin.tsx +0 -58
  57. package/src/plugins/MarkdownLinkPlugin.tsx +0 -69
  58. package/src/plugins/PreviewPlugin.tsx +0 -71
  59. package/src/plugins/TableActionMenuPlugin.css.ts +0 -29
  60. package/src/plugins/TableActionMenuPlugin.tsx +0 -274
  61. package/src/store/__tests__/index.test.ts +0 -171
  62. package/src/store/index.ts +0 -84
  63. package/src/theme/index.css.ts +0 -39
  64. package/src/theme/index.ts +0 -22
  65. package/src/transformers/horizontalRule.ts +0 -25
  66. package/src/transformers/index.ts +0 -6
  67. package/src/transformers/link.ts +0 -3
  68. package/src/transformers/tableRule.ts +0 -193
  69. package/src/utils/getSelectedNode.ts +0 -16
  70. package/tsconfig.json +0 -8
@@ -1,90 +0,0 @@
1
- import React from 'react';
2
- import { render, screen, waitFor } from '@testing-library/react';
3
- import userEvent from '@testing-library/user-event';
4
- import { LexicalComposer } from '@lexical/react/LexicalComposer';
5
-
6
- import { PersistDialog } from '../index';
7
- import { usePageState } from '../../../store';
8
- import { nodes } from '../../../nodes';
9
- import useWorkflowFeed from '../../../hooks/useWorkflowFeed';
10
-
11
- jest.mock('../../../store', () => ({
12
- ...jest.requireActual('../../../store'),
13
- __esModule: true,
14
- usePageState: jest.fn()
15
- }));
16
-
17
- const mockSendWorkflowProgressMessage = jest.fn();
18
- jest.mock('../../../hooks/useWorkflowFeed');
19
- jest
20
- .mocked(useWorkflowFeed)
21
- .mockReturnValue({ sendWorkflowProgressMessage: mockSendWorkflowProgressMessage });
22
-
23
- const setPageStateSpy = jest.fn();
24
- const setErrorMessageSpy = jest.fn();
25
- const mockMeta = { sourceId: 'source-1', route: 'route' };
26
-
27
- jest.mock('@lexical/markdown', () => ({
28
- ...jest.requireActual('@lexical/markdown'),
29
- $convertToMarkdownString: jest.fn().mockReturnValue('## Test Markdown')
30
- }));
31
-
32
- const renderPersistDialog = (props = { meta: mockMeta }) => {
33
- render(
34
- <LexicalComposer
35
- initialConfig={{ namespace: 'persist-dialog-test', nodes, onError: jest.fn() }}
36
- >
37
- <PersistDialog {...props} />
38
- </LexicalComposer>
39
- );
40
- };
41
-
42
- describe('GIVEN a PersistEditDialog', () => {
43
- beforeAll(() => {
44
- jest.mocked(usePageState).mockReturnValue({
45
- pageState: 'SAVING',
46
- setErrorMessage: setErrorMessageSpy,
47
- setPageState: setPageStateSpy,
48
- errorMessage: undefined
49
- });
50
- });
51
-
52
- test('THEN the dialog is open when SAVING', () => {
53
- // arrange
54
- renderPersistDialog();
55
- // assert
56
- expect(
57
- screen.getByText(
58
- 'The content of this page resides in a Git repository and to update it requires a Pull Request which will be reviewed by the content owners.'
59
- )
60
- ).toBeDefined();
61
- });
62
-
63
- test('THEN cancelling returns the page to edit mode', async () => {
64
- // arrange
65
- renderPersistDialog();
66
- // act
67
- const cancelButton = screen.getByText('Cancel');
68
- await userEvent.click(cancelButton);
69
- // assert
70
- expect(setPageStateSpy).toBeCalledTimes(1);
71
- expect(setPageStateSpy.mock.calls[0][0]).toEqual('EDIT');
72
- });
73
-
74
- describe.skip('AND WHEN we can create a Pull Request', () => {
75
- beforeAll(() => {
76
- server.use(postSaveContentSuccessHandler);
77
- });
78
- test('THEN raising a PR provides a link to the PR', async () => {
79
- // arrange
80
- renderPersistDialog();
81
- // act
82
- const raisePrButton = screen.getByText('Raise Pull Request');
83
- userEvent.click(raisePrButton);
84
- // assert
85
- await waitFor(() => {
86
- expect(screen.getByText('A Pull Request for your changes has been created.'));
87
- });
88
- });
89
- });
90
- });
@@ -1,14 +0,0 @@
1
- import { globalStyle, style } from '@vanilla-extract/css';
2
- import { vars } from '@jpmorganchase/mosaic-theme';
3
-
4
- const title = style({
5
- alignItems: 'center'
6
- });
7
-
8
- export default {
9
- title
10
- };
11
-
12
- globalStyle(`${title} [role=heading] `, {
13
- paddingLeft: vars.space.horizontal.x2
14
- });
@@ -1,152 +0,0 @@
1
- import React, { FC, useState } from 'react';
2
- import md5 from 'md5';
3
- import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
4
- import { $convertToMarkdownString } from '@lexical/markdown';
5
- import { Link, P2, Button } from '@jpmorganchase/mosaic-components';
6
- import { DialogHeader, DialogContent, DialogActions } from '@salt-ds/core';
7
- import { ButtonBar } from '@salt-ds/lab';
8
- import { SourceWorkflowMessageEvent } from '@jpmorganchase/mosaic-types';
9
-
10
- import { useEditorUser, usePageState } from '../../store';
11
- import transformers from '../../transformers';
12
- import { PersistStatus } from './PersistStatus';
13
- import { Dialog } from '../Dialog';
14
- import style from './index.css';
15
- import useWorkflowFeed from '../../hooks/useWorkflowFeed';
16
-
17
- interface InfoProps {
18
- isRaising: boolean;
19
- prHref: string | null;
20
- error: string | null;
21
- }
22
-
23
- const Info: FC<InfoProps> = ({ isRaising, prHref, error }) =>
24
- !isRaising && !prHref && !error ? (
25
- <>
26
- <P2>
27
- The content of this page resides in a Git repository and to update it requires a Pull
28
- Request which will be reviewed by the content owners.
29
- </P2>
30
- <br />
31
- <P2>
32
- Should you decide to stop editing before creating the Pull Request then all changes will be
33
- lost.
34
- </P2>
35
- </>
36
- ) : null;
37
-
38
- interface PersistDialogProps {
39
- meta: any;
40
- persistUrl?: string;
41
- }
42
-
43
- export const PersistDialog = ({ meta, persistUrl }: PersistDialogProps) => {
44
- const { pageState, setPageState } = usePageState();
45
- const { user } = useEditorUser();
46
- const [editor] = useLexicalComposerContext();
47
- const [isRaising, setIsRaising] = useState(false);
48
- const [prHref, setPrHref] = useState<string | null>(null);
49
- const [error, setError] = useState<string | null>(null);
50
- const [progress, setProgress] = useState<SourceWorkflowMessageEvent[]>([]);
51
-
52
- const open = pageState === 'SAVING';
53
- const state = prHref !== null ? 'success' : 'info';
54
-
55
- const handleOpenChange = (newOpen: boolean) => {
56
- setIsRaising(newOpen);
57
- if (!newOpen) {
58
- setPageState('EDIT');
59
- setPrHref(null);
60
- setProgress([]);
61
- }
62
- };
63
-
64
- const handleClose = () => {
65
- handleOpenChange(false);
66
- };
67
-
68
- const handleErrorMessage = (errorMessage: string) => {
69
- setError(errorMessage ? errorMessage : 'Sorry - an unexpected error has occurred');
70
- setPrHref(null);
71
- setProgress([]);
72
- setIsRaising(false);
73
- };
74
-
75
- const handleCompleteMessage = message => {
76
- setPrHref(message.message?.links?.self[0]?.href);
77
- setIsRaising(false);
78
- };
79
-
80
- const handleSuccessMessage = message => {
81
- setProgress(prevState => [...prevState, message]);
82
- };
83
-
84
- const { sendWorkflowProgressMessage } = useWorkflowFeed(
85
- open,
86
- handleErrorMessage,
87
- handleSuccessMessage,
88
- handleCompleteMessage
89
- );
90
-
91
- const handleRaisePr = () => {
92
- setIsRaising(true);
93
- setPrHref(null);
94
- setError(null);
95
-
96
- try {
97
- editor.update(() => {
98
- const markdown = $convertToMarkdownString(transformers);
99
- if (markdown && user && persistUrl) {
100
- const { sid, displayName, email } = user;
101
-
102
- sendWorkflowProgressMessage(
103
- JSON.stringify({
104
- user: { sid, name: displayName, email },
105
- route: meta.route,
106
- markdown,
107
- name: 'save'
108
- }),
109
- md5(`${sid.toLowerCase()} - save`)
110
- );
111
- }
112
- });
113
- } catch (e) {
114
- setError('Sorry - an unexpected error has occurred');
115
- setPrHref(null);
116
- setIsRaising(false);
117
- setProgress([]);
118
- }
119
- };
120
-
121
- return (
122
- <Dialog onOpenChange={handleOpenChange} open={open} status={error ? 'error' : state}>
123
- <DialogHeader
124
- className={style.title}
125
- header={!prHref ? 'Save Changes' : 'Pull Request Created Successfully'}
126
- />
127
- <DialogContent>
128
- {(isRaising || error) && !prHref && <PersistStatus error={error} progress={progress} />}
129
- <Info isRaising={isRaising} prHref={prHref} error={error} />
130
- {!isRaising && prHref && (
131
- <Link href={prHref} target="_blank">
132
- A Pull Request for your changes has been created
133
- </Link>
134
- )}
135
- </DialogContent>
136
- <DialogActions>
137
- <ButtonBar>
138
- <Button disabled={isRaising} onClick={handleClose}>
139
- {!prHref ? 'Cancel' : 'Done'}
140
- </Button>
141
- <Button
142
- disabled={persistUrl === undefined || isRaising || prHref !== null}
143
- onClick={handleRaisePr}
144
- variant="cta"
145
- >
146
- Raise Pull Request
147
- </Button>
148
- </ButtonBar>
149
- </DialogActions>
150
- </Dialog>
151
- );
152
- };
@@ -1,12 +0,0 @@
1
- import { style } from '@vanilla-extract/css';
2
- import { backgroundColor, shadow } from '@jpmorganchase/mosaic-theme';
3
-
4
- export const POPPER_Z_INDEX = 10;
5
-
6
- export default {
7
- root: style([
8
- style({ zIndex: POPPER_Z_INDEX }),
9
- backgroundColor({ variant: 'regular' }),
10
- shadow({ variant: 'elevation3' })
11
- ])
12
- };
@@ -1,36 +0,0 @@
1
- import React, { forwardRef, HTMLAttributes, ReactNode } from 'react';
2
- import { Portal, useWindow } from '@salt-ds/lab';
3
- import { themeClassName } from '@jpmorganchase/mosaic-theme';
4
- import classnames from 'clsx';
5
-
6
- import styles from './Popper.css';
7
-
8
- interface PopperProps extends HTMLAttributes<HTMLDivElement> {
9
- /** Floating contents */
10
- children?: ReactNode;
11
- /** Class name */
12
- className?: string;
13
- /** Flag indicating whether the floating content is visible */
14
- open?: boolean;
15
- }
16
-
17
- export const Popper = forwardRef<HTMLDivElement, PopperProps>(function Popper(props, forwardedRef) {
18
- const { children, className, ...rest } = props;
19
- const Window = useWindow();
20
-
21
- if (!rest.open) {
22
- return null;
23
- }
24
-
25
- return (
26
- <Portal>
27
- <Window
28
- className={classnames(className, themeClassName, styles.root)}
29
- ref={forwardedRef}
30
- {...rest}
31
- >
32
- {children}
33
- </Window>
34
- </Portal>
35
- );
36
- });
@@ -1,23 +0,0 @@
1
- import React, { useState } from 'react';
2
- import { Button, Icon } from '@jpmorganchase/mosaic-components';
3
- import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
4
-
5
- import { usePageState } from '../store';
6
-
7
- export const SaveButton = () => {
8
- const { setPageState } = usePageState();
9
- const [isDisabled, setIsDisabled] = useState(true);
10
-
11
- const onChange = () => {
12
- setIsDisabled(false);
13
- };
14
-
15
- return (
16
- <>
17
- <OnChangePlugin onChange={onChange} ignoreSelectionChange />
18
- <Button disabled={isDisabled} variant="cta" onClick={() => setPageState('SAVING')}>
19
- <Icon name="save" /> &nbsp; Save
20
- </Button>
21
- </>
22
- );
23
- };
@@ -1,10 +0,0 @@
1
- import { style } from '@vanilla-extract/css';
2
- import { vars } from '@jpmorganchase/mosaic-theme';
3
-
4
- export default {
5
- root: style({
6
- padding: vars.space.horizontal.x3,
7
- maxHeight: '100vh',
8
- overflow: 'scroll'
9
- })
10
- };
@@ -1,20 +0,0 @@
1
- import React, { Ref, forwardRef } from 'react';
2
- import classnames from 'clsx';
3
-
4
- import styles from './ScrollableSection.css';
5
-
6
- interface ScrollableSectionProps {
7
- className?: string;
8
- children: React.ReactNode;
9
- }
10
-
11
- export const ScrollableSection = forwardRef(function ScrollableSection(
12
- { className, children }: ScrollableSectionProps,
13
- ref: Ref<HTMLDivElement>
14
- ) {
15
- return (
16
- <section ref={ref} className={classnames(styles.root, className)}>
17
- {children}
18
- </section>
19
- );
20
- });
@@ -1,16 +0,0 @@
1
- import React from 'react';
2
- import { Banner, BannerContent } from '@salt-ds/core';
3
-
4
- import { usePageState } from '../store';
5
-
6
- const StatusBanner = () => {
7
- const { pageState, errorMessage } = usePageState();
8
- const isError = pageState === 'ERROR';
9
- return isError ? (
10
- <Banner status="error">
11
- <BannerContent role="status">{errorMessage}</BannerContent>
12
- </Banner>
13
- ) : null;
14
- };
15
-
16
- export default StatusBanner;
@@ -1,134 +0,0 @@
1
- import React from 'react';
2
- import { Dropdown, SelectionChangeHandler } from '@salt-ds/lab';
3
- import { $createCodeNode } from '@lexical/code';
4
- import { INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDERED_LIST_COMMAND } from '@lexical/list';
5
- import { $createHeadingNode, $createQuoteNode, HeadingTagType } from '@lexical/rich-text';
6
- import { $wrapNodes } from '@lexical/selection';
7
- import { $createParagraphNode, $getSelection, $isRangeSelection, LexicalEditor } from 'lexical';
8
-
9
- interface BlockSourceType {
10
- name: string;
11
- type: string;
12
- }
13
-
14
- const itemToString = (item?: BlockSourceType | null) => (item ? item.name : '');
15
-
16
- const headings = [
17
- { name: 'Heading 1', type: 'h1' },
18
- { name: 'Heading 2', type: 'h2' },
19
- { name: 'Heading 3', type: 'h3' },
20
- { name: 'Heading 4', type: 'h4' },
21
- { name: 'Heading 5', type: 'h5' },
22
- { name: 'Heading 6', type: 'h6' }
23
- ];
24
-
25
- const source = [
26
- { name: 'Bulleted List', type: 'bullet' },
27
- { name: 'Code Block', type: 'code' },
28
- ...headings,
29
- { name: 'Numbered List', type: 'number' },
30
- { name: 'Paragraph', type: 'paragraph' },
31
- { name: 'Quote', type: 'quote' }
32
- ];
33
-
34
- export function InsertBlockDropdown({
35
- editor,
36
- type: blockSourceType
37
- }: {
38
- editor: LexicalEditor;
39
- type: string;
40
- }): JSX.Element {
41
- const formatParagraph = (item: BlockSourceType) => {
42
- if (item.type === 'paragraph') {
43
- editor.update(() => {
44
- const selection = $getSelection();
45
-
46
- if ($isRangeSelection(selection)) {
47
- $wrapNodes(selection, () => $createParagraphNode());
48
- }
49
- });
50
- }
51
- };
52
-
53
- const formatHeading = (item: BlockSourceType) => {
54
- if (headings.findIndex(heading => heading.type === item.type) >= 0) {
55
- editor.update(() => {
56
- const selection = $getSelection();
57
-
58
- if ($isRangeSelection(selection)) {
59
- $wrapNodes(selection, () => $createHeadingNode(item.type as HeadingTagType));
60
- }
61
- });
62
- }
63
- };
64
-
65
- const formatBulletList = (item: BlockSourceType) => {
66
- if (item.type === 'bullet') {
67
- editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined);
68
- }
69
- };
70
-
71
- const formatNumberedList = (item: BlockSourceType) => {
72
- if (item.type === 'number') {
73
- editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
74
- }
75
- };
76
-
77
- const formatQuote = (item: BlockSourceType) => {
78
- if (item.type === 'quote') {
79
- editor.update(() => {
80
- const selection = $getSelection();
81
-
82
- if ($isRangeSelection(selection)) {
83
- $wrapNodes(selection, () => $createQuoteNode());
84
- }
85
- });
86
- }
87
- };
88
-
89
- const formatCode = (item: BlockSourceType) => {
90
- if (item.type === 'code') {
91
- editor.update(() => {
92
- const selection = $getSelection();
93
-
94
- if ($isRangeSelection(selection)) {
95
- if (selection.isCollapsed()) {
96
- $wrapNodes(selection, () => $createCodeNode());
97
- } else {
98
- const textContent = selection.getTextContent();
99
- const codeNode = $createCodeNode();
100
- selection.removeText();
101
- selection.insertNodes([codeNode]);
102
- selection.insertRawText(textContent);
103
- }
104
- }
105
- });
106
- }
107
- };
108
-
109
- const handleSelect: SelectionChangeHandler<BlockSourceType, 'default'> = (_event, item) => {
110
- if (!item) {
111
- return;
112
- }
113
- formatParagraph(item);
114
- formatHeading(item);
115
- formatBulletList(item);
116
- formatNumberedList(item);
117
- formatQuote(item);
118
- formatCode(item);
119
- };
120
-
121
- const selectedBlockSourceIndex = source.findIndex(item => item.type === blockSourceType);
122
- return (
123
- <Dropdown
124
- ListProps={{
125
- width: 200
126
- }}
127
- defaultSelected={source[selectedBlockSourceIndex]}
128
- itemToString={itemToString}
129
- onSelectionChange={handleSelect}
130
- source={source}
131
- width={132}
132
- />
133
- );
134
- }
@@ -1,18 +0,0 @@
1
- import React from 'react';
2
- import { Icon } from '@jpmorganchase/mosaic-components';
3
- import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
4
- import { INSERT_HORIZONTAL_RULE_COMMAND } from '@lexical/react/LexicalHorizontalRuleNode';
5
- import { ToolbarButton } from './ToolbarButton';
6
-
7
- export const InsertHorizontalRule = () => {
8
- const [editor] = useLexicalComposerContext();
9
-
10
- const handleClick = () => {
11
- editor.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND, undefined);
12
- };
13
- return (
14
- <ToolbarButton onClick={handleClick} label="Insert Divider">
15
- <Icon name="minimize" />
16
- </ToolbarButton>
17
- );
18
- };
@@ -1,7 +0,0 @@
1
- import { style } from '@vanilla-extract/css';
2
-
3
- export default {
4
- fullWidth: style({
5
- width: '100%'
6
- })
7
- };
@@ -1,138 +0,0 @@
1
- import React, { useState } from 'react';
2
- import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
3
- import { Button, Icon } from '@jpmorganchase/mosaic-components';
4
- import { string, object } from 'yup';
5
- import {
6
- Input,
7
- FormField,
8
- FormFieldLabel,
9
- FormFieldHelperText,
10
- DialogHeader,
11
- DialogContent,
12
- DialogActions
13
- } from '@salt-ds/core';
14
- import { ButtonBar } from '@salt-ds/lab';
15
-
16
- import { ToolbarButton } from './ToolbarButton';
17
- import { Dialog } from '../Dialog';
18
- import {
19
- INSERT_MARKDOWN_IMAGE_COMMAND,
20
- InsertImagePayload
21
- } from '../../plugins/MarkdownImagePlugin';
22
- import styles from './InsertImage.css';
23
-
24
- const validationSchema = object({
25
- alt: string()
26
- .required('Alternative Information is a required field')
27
- .max(100, 'Alternative Information must be fewer than 100 characters'),
28
- url: string().required('Url is required').url('Must be a valid Url')
29
- });
30
-
31
- const initialState = {
32
- url: 'https://'
33
- };
34
-
35
- type FormValueState =
36
- | {
37
- alt?: string;
38
- url?: string;
39
- }
40
- | undefined;
41
-
42
- type FormErrorState =
43
- | {
44
- alt?: string;
45
- url?: string;
46
- }
47
- | undefined;
48
-
49
- export const InsertImage = () => {
50
- const [editor] = useLexicalComposerContext();
51
- const [isOpen, setIsOpen] = useState(false);
52
- const [values, setValues] = useState<FormValueState>(initialState);
53
- const [errors, setErrors] = useState<FormErrorState>();
54
-
55
- const handleOpenChange = (open: boolean) => {
56
- setIsOpen(open);
57
- if (!open) {
58
- setValues(initialState);
59
- }
60
- };
61
-
62
- const handleOpen = () => setIsOpen(true);
63
-
64
- const handleClose = () => {
65
- handleOpenChange(false);
66
- };
67
-
68
- const processErrors = validationErrors => {
69
- const newErrors = validationErrors.inner.reduce(
70
- (acc, { path, message }) => ({
71
- ...acc,
72
- [path]: message
73
- }),
74
- {}
75
- );
76
- setErrors(newErrors);
77
- };
78
-
79
- const handleChange = event => {
80
- const { name, value } = event.target;
81
- const newValues = { ...values, [name]: value };
82
- validationSchema.validateAt(name, newValues, { abortEarly: false }).then(() => {
83
- setErrors({ ...errors, [name]: undefined });
84
- }, processErrors);
85
- setValues(newValues);
86
- };
87
-
88
- const handleSubmit = async event => {
89
- event.preventDefault();
90
- validationSchema.validate(values, { abortEarly: false }).then(() => {
91
- const payload: InsertImagePayload = {
92
- alt: values && values.alt !== undefined ? values.alt : null,
93
- url: values && values.url !== undefined ? values.url : null
94
- };
95
- editor.dispatchCommand(INSERT_MARKDOWN_IMAGE_COMMAND, payload);
96
- handleClose();
97
- }, processErrors);
98
- };
99
-
100
- return (
101
- <>
102
- <ToolbarButton active={isOpen} onClick={handleOpen} label="Insert Image">
103
- <Icon name="addDocument" />
104
- </ToolbarButton>
105
-
106
- <Dialog onOpenChange={handleOpenChange} open={isOpen}>
107
- <form onSubmit={handleSubmit} noValidate>
108
- <DialogHeader header="Insert Image" />
109
- <DialogContent>
110
- <div className={styles.fullWidth}>
111
- <FormField validationStatus={errors?.url ? 'error' : undefined}>
112
- <FormFieldLabel>Url for image</FormFieldLabel>
113
- <Input value={values?.url} inputProps={{ name: 'url' }} onChange={handleChange} />
114
- <FormFieldHelperText>{errors?.url}</FormFieldHelperText>
115
- </FormField>
116
- <FormField validationStatus={errors?.alt ? 'error' : undefined}>
117
- <FormFieldLabel>Alternative Information (alt)</FormFieldLabel>
118
- <Input value={values?.alt} inputProps={{ name: 'alt' }} onChange={handleChange} />
119
- <FormFieldHelperText>
120
- {errors?.alt ||
121
- 'Provides alternative information for the image if for some reason it cannot be viewed'}
122
- </FormFieldHelperText>
123
- </FormField>
124
- </div>
125
- </DialogContent>
126
- <DialogActions>
127
- <ButtonBar>
128
- <Button onClick={handleClose}>Cancel</Button>
129
- <Button variant="cta" type="submit">
130
- Insert
131
- </Button>
132
- </ButtonBar>
133
- </DialogActions>
134
- </form>
135
- </Dialog>
136
- </>
137
- );
138
- };
@@ -1,7 +0,0 @@
1
- import { style } from '@vanilla-extract/css';
2
-
3
- export default {
4
- fullWidth: style({
5
- width: '100%'
6
- })
7
- };