@squiz/formatted-text-editor 1.21.1-alpha.9 → 1.22.0

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 (123) hide show
  1. package/demo/App.tsx +38 -10
  2. package/demo/index.scss +2 -7
  3. package/jest.config.ts +0 -2
  4. package/lib/Editor/Editor.js +45 -7
  5. package/lib/Editor/EditorContext.d.ts +15 -0
  6. package/lib/Editor/EditorContext.js +15 -0
  7. package/lib/EditorToolbar/FloatingToolbar.js +11 -5
  8. package/lib/EditorToolbar/Tools/Image/Form/ImageForm.d.ts +9 -8
  9. package/lib/EditorToolbar/Tools/Image/Form/ImageForm.js +91 -23
  10. package/lib/EditorToolbar/Tools/Image/ImageButton.d.ts +4 -1
  11. package/lib/EditorToolbar/Tools/Image/ImageButton.js +22 -14
  12. package/lib/EditorToolbar/Tools/Image/ImageModal.js +9 -5
  13. package/lib/EditorToolbar/Tools/Link/Form/LinkForm.d.ts +14 -5
  14. package/lib/EditorToolbar/Tools/Link/Form/LinkForm.js +66 -14
  15. package/lib/EditorToolbar/Tools/Link/LinkButton.js +21 -13
  16. package/lib/EditorToolbar/Tools/Link/LinkModal.js +12 -5
  17. package/lib/EditorToolbar/Tools/Link/RemoveLinkButton.js +1 -8
  18. package/lib/Extensions/CommandsExtension/CommandsExtension.d.ts +20 -0
  19. package/lib/Extensions/CommandsExtension/CommandsExtension.js +52 -0
  20. package/lib/Extensions/Extensions.d.ts +11 -1
  21. package/lib/Extensions/Extensions.js +42 -20
  22. package/lib/Extensions/ImageExtension/AssetImageExtension.d.ts +17 -0
  23. package/lib/Extensions/ImageExtension/AssetImageExtension.js +92 -0
  24. package/lib/Extensions/ImageExtension/ImageExtension.d.ts +4 -0
  25. package/lib/Extensions/ImageExtension/ImageExtension.js +11 -0
  26. package/lib/Extensions/LinkExtension/AssetLinkExtension.d.ts +26 -0
  27. package/lib/Extensions/LinkExtension/AssetLinkExtension.js +102 -0
  28. package/lib/Extensions/LinkExtension/LinkExtension.d.ts +19 -12
  29. package/lib/Extensions/LinkExtension/LinkExtension.js +56 -66
  30. package/lib/Extensions/LinkExtension/common.d.ts +7 -0
  31. package/lib/Extensions/LinkExtension/common.js +14 -0
  32. package/lib/Extensions/PreformattedExtension/PreformattedExtension.js +6 -2
  33. package/lib/hooks/index.d.ts +1 -0
  34. package/lib/hooks/index.js +1 -0
  35. package/lib/hooks/useExpandedSelection.d.ts +23 -0
  36. package/lib/hooks/useExpandedSelection.js +37 -0
  37. package/lib/index.css +58 -26
  38. package/lib/index.d.ts +3 -2
  39. package/lib/index.js +5 -3
  40. package/lib/types.d.ts +3 -0
  41. package/lib/types.js +2 -0
  42. package/lib/ui/Button/Button.d.ts +2 -1
  43. package/lib/ui/Button/Button.js +4 -5
  44. package/lib/ui/Fields/Input/Input.d.ts +1 -0
  45. package/lib/ui/Fields/Input/Input.js +9 -3
  46. package/lib/ui/Modal/Modal.js +5 -3
  47. package/lib/utils/converters/remirrorNodeToSquizNode/remirrorNodeToSquizNode.d.ts +1 -2
  48. package/lib/utils/converters/remirrorNodeToSquizNode/remirrorNodeToSquizNode.js +118 -104
  49. package/lib/utils/converters/squizNodeToRemirrorNode/squizNodeToRemirrorNode.js +102 -69
  50. package/lib/utils/resolveMatrixAssetUrl.d.ts +1 -0
  51. package/lib/utils/resolveMatrixAssetUrl.js +10 -0
  52. package/lib/utils/undefinedIfEmpty.d.ts +1 -0
  53. package/lib/utils/undefinedIfEmpty.js +7 -0
  54. package/package.json +8 -4
  55. package/src/Editor/Editor.spec.tsx +78 -18
  56. package/src/Editor/Editor.tsx +28 -9
  57. package/src/Editor/EditorContext.spec.tsx +26 -0
  58. package/src/Editor/EditorContext.ts +26 -0
  59. package/src/Editor/_editor.scss +20 -4
  60. package/src/EditorToolbar/FloatingToolbar.spec.tsx +26 -7
  61. package/src/EditorToolbar/FloatingToolbar.tsx +15 -6
  62. package/src/EditorToolbar/Tools/Image/Form/ImageForm.spec.tsx +81 -6
  63. package/src/EditorToolbar/Tools/Image/Form/ImageForm.tsx +167 -47
  64. package/src/EditorToolbar/Tools/Image/ImageButton.spec.tsx +250 -2
  65. package/src/EditorToolbar/Tools/Image/ImageButton.tsx +29 -16
  66. package/src/EditorToolbar/Tools/Image/ImageModal.spec.tsx +59 -20
  67. package/src/EditorToolbar/Tools/Image/ImageModal.tsx +12 -10
  68. package/src/EditorToolbar/Tools/Link/Form/LinkForm.spec.tsx +37 -9
  69. package/src/EditorToolbar/Tools/Link/Form/LinkForm.tsx +96 -26
  70. package/src/EditorToolbar/Tools/Link/LinkButton.spec.tsx +137 -26
  71. package/src/EditorToolbar/Tools/Link/LinkButton.tsx +28 -19
  72. package/src/EditorToolbar/Tools/Link/LinkModal.tsx +13 -6
  73. package/src/EditorToolbar/Tools/Link/RemoveLinkButton.spec.tsx +27 -26
  74. package/src/EditorToolbar/Tools/Link/RemoveLinkButton.tsx +2 -10
  75. package/src/EditorToolbar/Tools/Undo/UndoButton.spec.tsx +22 -1
  76. package/src/EditorToolbar/_floating-toolbar.scss +4 -5
  77. package/src/EditorToolbar/_toolbar.scss +1 -1
  78. package/src/Extensions/CommandsExtension/CommandsExtension.ts +54 -0
  79. package/src/Extensions/Extensions.ts +42 -19
  80. package/src/Extensions/ImageExtension/AssetImageExtension.spec.ts +76 -0
  81. package/src/Extensions/ImageExtension/AssetImageExtension.ts +111 -0
  82. package/src/Extensions/ImageExtension/ImageExtension.ts +17 -1
  83. package/src/Extensions/LinkExtension/AssetLinkExtension.spec.ts +104 -0
  84. package/src/Extensions/LinkExtension/AssetLinkExtension.ts +128 -0
  85. package/src/Extensions/LinkExtension/LinkExtension.spec.ts +68 -0
  86. package/src/Extensions/LinkExtension/LinkExtension.ts +71 -85
  87. package/src/Extensions/LinkExtension/common.ts +10 -0
  88. package/src/Extensions/PreformattedExtension/PreformattedExtension.spec.ts +41 -0
  89. package/src/Extensions/PreformattedExtension/PreformattedExtension.ts +6 -2
  90. package/src/hooks/index.ts +1 -0
  91. package/src/hooks/useExpandedSelection.ts +44 -0
  92. package/src/index.ts +3 -2
  93. package/src/types.ts +5 -0
  94. package/src/ui/Button/Button.tsx +10 -6
  95. package/src/ui/Button/_button.scss +1 -1
  96. package/src/ui/Fields/Input/Input.spec.tsx +7 -1
  97. package/src/ui/Fields/Input/Input.tsx +23 -4
  98. package/src/ui/Modal/Modal.spec.tsx +15 -0
  99. package/src/ui/Modal/Modal.tsx +8 -4
  100. package/src/ui/ToolbarDropdown/_toolbar-dropdown.scss +1 -1
  101. package/src/ui/_forms.scss +14 -0
  102. package/src/utils/converters/mocks/squizNodeJson.mock.ts +196 -0
  103. package/src/utils/converters/remirrorNodeToSquizNode/remirrorNodeToSquizNode.spec.ts +41 -6
  104. package/src/utils/converters/remirrorNodeToSquizNode/remirrorNodeToSquizNode.ts +132 -111
  105. package/src/utils/converters/squizNodeToRemirrorNode/squizNodeToRemirrorNode.spec.ts +68 -34
  106. package/src/utils/converters/squizNodeToRemirrorNode/squizNodeToRemirrorNode.ts +115 -79
  107. package/src/utils/resolveMatrixAssetUrl.spec.ts +26 -0
  108. package/src/utils/resolveMatrixAssetUrl.ts +7 -0
  109. package/src/utils/undefinedIfEmpty.spec.ts +12 -0
  110. package/src/utils/undefinedIfEmpty.ts +3 -0
  111. package/tailwind.config.cjs +3 -0
  112. package/tests/renderWithEditor.tsx +26 -13
  113. package/tsconfig.json +1 -1
  114. package/lib/FormattedTextEditor.d.ts +0 -2
  115. package/lib/FormattedTextEditor.js +0 -7
  116. package/lib/utils/converters/validNodeTypes.d.ts +0 -2
  117. package/lib/utils/converters/validNodeTypes.js +0 -21
  118. package/src/Editor/Editor.mock.tsx +0 -43
  119. package/src/FormattedTextEditor.spec.tsx +0 -10
  120. package/src/FormattedTextEditor.tsx +0 -3
  121. package/src/utils/converters/validNodeTypes.spec.ts +0 -33
  122. package/src/utils/converters/validNodeTypes.ts +0 -21
  123. /package/tests/{select.tsx → select.ts} +0 -0
@@ -1,8 +1,11 @@
1
- import React from 'react';
2
- import { EditorComponent, Remirror, useRemirror } from '@remirror/react';
1
+ import React, { useContext, useCallback } from 'react';
2
+ import { EditorComponent, Remirror, useRemirror, useEditorEvent } from '@remirror/react';
3
3
  import { RemirrorContentType, RemirrorEventListener, Extension } from '@remirror/core';
4
4
  import { Toolbar, FloatingToolbar } from '../EditorToolbar';
5
- import { Extensions } from '../Extensions/Extensions';
5
+ import { EditorContext } from './EditorContext';
6
+ import { createExtensions } from '../Extensions/Extensions';
7
+ import clsx from 'clsx';
8
+ import { ClipboardEventHandler } from '@remirror/extension-events/dist-types/events-extension';
6
9
 
7
10
  type EditorProps = {
8
11
  content?: RemirrorContentType;
@@ -10,9 +13,25 @@ type EditorProps = {
10
13
  editable?: boolean;
11
14
  };
12
15
 
13
- const Editor = ({ content, editable, onChange }: EditorProps) => {
16
+ const WrappedEditor = () => {
17
+ const preventImagePaste = useCallback((event) => {
18
+ const { clipboardData } = event;
19
+ const pastedData = clipboardData?.files[0];
20
+ if (pastedData?.type && pastedData?.type.startsWith('image/')) {
21
+ event.preventDefault();
22
+ }
23
+
24
+ // Allow other paste event handlers to be run.
25
+ return false;
26
+ }, []) as ClipboardEventHandler;
27
+
28
+ useEditorEvent('paste', preventImagePaste);
29
+ return <EditorComponent />;
30
+ };
31
+
32
+ const Editor = ({ content, editable = true, onChange }: EditorProps) => {
14
33
  const { manager, state, setState } = useRemirror({
15
- extensions: Extensions,
34
+ extensions: createExtensions(useContext(EditorContext)),
16
35
  content,
17
36
  selection: 'start',
18
37
  stringHandler: 'html',
@@ -25,7 +44,7 @@ const Editor = ({ content, editable, onChange }: EditorProps) => {
25
44
 
26
45
  return (
27
46
  <div className="squiz-fte-scope">
28
- <div className="remirror-theme formatted-text-editor editor-wrapper">
47
+ <div className={clsx('remirror-theme formatted-text-editor', !editable && 'formatted-text-editor--is-disabled')}>
29
48
  <Remirror
30
49
  manager={manager}
31
50
  state={state}
@@ -34,9 +53,9 @@ const Editor = ({ content, editable, onChange }: EditorProps) => {
34
53
  placeholder="Write something"
35
54
  label="Text editor"
36
55
  >
37
- <Toolbar />
38
- <EditorComponent />
39
- <FloatingToolbar />
56
+ {editable && <Toolbar />}
57
+ <WrappedEditor />
58
+ {editable && <FloatingToolbar />}
40
59
  </Remirror>
41
60
  </div>
42
61
  </div>
@@ -0,0 +1,26 @@
1
+ import React, { useContext } from 'react';
2
+ import { EditorContext } from './EditorContext';
3
+ import { render } from '@testing-library/react';
4
+
5
+ describe('EditorContext', () => {
6
+ const defaultContextFn = jest.fn();
7
+ const Component = () => {
8
+ defaultContextFn(useContext(EditorContext));
9
+ return null;
10
+ };
11
+
12
+ it('Has expected defaults', async () => {
13
+ render(<Component />);
14
+
15
+ const defaultContext = defaultContextFn.mock.calls[0][0];
16
+
17
+ expect(defaultContext).toEqual({
18
+ matrix: {
19
+ resolveMatrixAsset: expect.any(Function),
20
+ matrixDomain: '',
21
+ matrixIdentifier: '',
22
+ },
23
+ });
24
+ expect(await defaultContext.matrix.resolveMatrixAsset('fake-asset-id')).toBeNull();
25
+ });
26
+ });
@@ -0,0 +1,26 @@
1
+ import React from 'react';
2
+
3
+ export type MatrixAsset = {
4
+ id: string;
5
+ type: string | 'image';
6
+ };
7
+
8
+ export type MatrixAssetResolver = (assetId: string) => Promise<MatrixAsset | null>;
9
+
10
+ export type EditorContextOptions = {
11
+ matrix: {
12
+ matrixIdentifier: string;
13
+ matrixDomain: string;
14
+ resolveMatrixAsset: MatrixAssetResolver;
15
+ };
16
+ };
17
+
18
+ export const defaultEditorContext: EditorContextOptions = {
19
+ matrix: {
20
+ matrixIdentifier: '',
21
+ matrixDomain: '',
22
+ resolveMatrixAsset: () => Promise.resolve(null),
23
+ },
24
+ };
25
+
26
+ export const EditorContext = React.createContext(defaultEditorContext);
@@ -1,9 +1,6 @@
1
1
  .formatted-text-editor {
2
2
  font-family: 'Open Sans' !important;
3
-
4
- &.editor-wrapper {
5
- @apply bg-white rounded border-gray-300 border-2 border-solid;
6
- }
3
+ @apply bg-white rounded border-gray-300 border-2 border-solid;
7
4
 
8
5
  .remirror-editor-wrapper {
9
6
  @apply text-gray-800 pt-0;
@@ -12,6 +9,7 @@
12
9
  .remirror-editor {
13
10
  @apply bg-white shadow-none rounded-b p-3;
14
11
  overflow: auto;
12
+ min-height: 15vh;
15
13
 
16
14
  &:active,
17
15
  &:focus {
@@ -24,6 +22,15 @@
24
22
  }
25
23
  }
26
24
 
25
+ &--is-disabled {
26
+ .remirror-editor {
27
+ @apply bg-gray-300 cursor-not-allowed;
28
+ }
29
+ .remirror-is-empty:first-of-type::before {
30
+ display: none;
31
+ }
32
+ }
33
+
27
34
  .remirror-is-empty:first-of-type::before {
28
35
  position: absolute;
29
36
  pointer-events: none;
@@ -32,4 +39,13 @@
32
39
  content: attr(data-placeholder);
33
40
  @apply text-gray-500;
34
41
  }
42
+
43
+ .ProseMirror-selectednode {
44
+ @apply border-blue-300 border-2 border-solid;
45
+ }
46
+
47
+ // match the Remirror node
48
+ img {
49
+ display: inline;
50
+ }
35
51
  }
@@ -1,9 +1,12 @@
1
- import React from 'react';
2
1
  import { act, screen } from '@testing-library/react';
2
+ import { NodeSelection } from 'prosemirror-state';
3
3
  import { renderWithEditor } from '../../tests';
4
- import { FloatingToolbar } from './FloatingToolbar';
5
4
 
6
5
  describe('FloatingToolbar', () => {
6
+ const getFloatingButtonNames = () => {
7
+ return screen.queryAllByRole('button').map((button) => button.getAttribute('title'));
8
+ };
9
+
7
10
  it.each([
8
11
  ['Nothing selected', 3, 3, []],
9
12
  ['Regular text selected', 3, 4, ['Bold (cmd+B)', 'Italic (cmd+I)', 'Underline (cmd+U)', 'Link (cmd+K)']],
@@ -11,20 +14,36 @@ describe('FloatingToolbar', () => {
11
14
  ['Nothing selected, positioned directly on the left of a link', 12, 12, []],
12
15
  ['Nothing selected, positioned directly on the right of a link', 19, 19, []],
13
16
  ['Nothing selected, positioned within a link', 13, 13, ['Link (cmd+K)', 'Remove link']],
14
- ['Link partially selected', 15, 17, ['Link (cmd+K)', 'Remove link']],
15
17
  ])(
16
18
  'Renders formatting buttons when text is selected - %s',
17
19
  async (description: string, from: number, to: number, expectedButtons: string[]) => {
18
- const { editor } = await renderWithEditor(<FloatingToolbar />, {
20
+ const { editor } = await renderWithEditor(null, {
19
21
  content: 'My awesome <a href="https://example.org">example</a> content.',
22
+ editable: true,
20
23
  });
21
24
 
22
25
  await act(() => editor.selectText({ from, to }));
23
26
 
24
- const buttons = screen.queryAllByRole('button');
25
- const buttonLabels = buttons.map((button) => button.getAttribute('title'));
27
+ expect(getFloatingButtonNames()).toEqual(expectedButtons);
28
+ },
29
+ );
30
+
31
+ it.each([
32
+ ['Image selected', 1, ['Image (cmd+L)']],
33
+ ['Asset image selected', 2, ['Image (cmd+L)']],
34
+ ])(
35
+ 'Renders formatting buttons when node is selected - %s',
36
+ async (description: string, pos: number, expectedButtons: string[]) => {
37
+ const { editor } = await renderWithEditor(null, {
38
+ content:
39
+ '<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />' +
40
+ '<img data-matrix-asset-id="100" data-matrix-identifier="key" data-matrix-domain="my-matrix.squiz.net" />',
41
+ editable: true,
42
+ });
43
+
44
+ await act(() => editor.selectText(new NodeSelection(editor.state.doc.resolve(pos))));
26
45
 
27
- expect(buttonLabels).toEqual(expectedButtons);
46
+ expect(getFloatingButtonNames()).toEqual(expectedButtons);
28
47
  },
29
48
  );
30
49
  });
@@ -5,26 +5,35 @@ import BoldButton from './Tools/Bold/BoldButton';
5
5
  import { useExtensionNames } from '../hooks';
6
6
  import RemoveLinkButton from './Tools/Link/RemoveLinkButton';
7
7
  import LinkButton from './Tools/Link/LinkButton';
8
- import { FloatingToolbar as RemirrorFloatingToolbar, usePositioner } from '@remirror/react';
8
+ import { FloatingToolbar as RemirrorFloatingToolbar, useActive, usePositioner } from '@remirror/react';
9
9
  import { VerticalDivider } from '@remirror/react-components';
10
10
  import { createToolbarPositioner, ToolbarPositionerRange } from '../utils/createToolbarPositioner';
11
+ import ImageButton from './Tools/Image/ImageButton';
12
+ import { MarkName } from '../Extensions/Extensions';
13
+ import { ImageExtension } from '../Extensions/ImageExtension/ImageExtension';
11
14
 
12
- // The editor main toolbar
13
15
  export const FloatingToolbar = () => {
16
+ const watchedMarks = [MarkName.Link, MarkName.AssetLink];
14
17
  const extensionNames = useExtensionNames();
15
- const positioner = useMemo(() => createToolbarPositioner({ types: ['link'] }), []);
16
- const { data } = usePositioner<Partial<ToolbarPositionerRange>>(positioner, []);
18
+ const positioner = useMemo(() => createToolbarPositioner({ types: watchedMarks }), []);
19
+ const active = useActive<ImageExtension>();
20
+ const {
21
+ data: { marks },
22
+ } = usePositioner<Partial<ToolbarPositionerRange>>(positioner, []);
23
+
17
24
  let buttons = [
18
25
  extensionNames.bold && <BoldButton key="bold" />,
19
26
  extensionNames.italic && <ItalicButton key="italic" />,
20
27
  extensionNames.underline && <UnderlineButton key="underline" />,
21
28
  ];
22
29
 
23
- if (data.marks?.link.isExclusivelyActive) {
30
+ if (active.image() || active.assetImage()) {
31
+ buttons = [<ImageButton key="add-image" inPopover={true} />];
32
+ } else if (marks?.[MarkName.Link].isExclusivelyActive || marks?.[MarkName.AssetLink].isExclusivelyActive) {
24
33
  // if all of the selected text is a link show the options to update/remove the link instead of the regular
25
34
  // formatting options.
26
35
  buttons = [<LinkButton key="update-link" inPopover={true} />, <RemoveLinkButton key="remove-link" />];
27
- } else if (!data.marks?.link.isActive) {
36
+ } else if (!marks?.[MarkName.Link].isActive && !marks?.[MarkName.AssetLink].isActive) {
28
37
  // if none of the selected text is a link show the option to create a link.
29
38
  buttons.push(
30
39
  <VerticalDivider key="link-divider" className="editor-divider" />,
@@ -1,23 +1,98 @@
1
1
  import '@testing-library/jest-dom';
2
- import { render, screen } from '@testing-library/react';
2
+ import { render, screen, act, fireEvent } from '@testing-library/react';
3
3
  import React from 'react';
4
4
  import ImageForm from './ImageForm';
5
+ import { NodeName } from '../../../../Extensions/Extensions';
5
6
 
6
7
  describe('Image Form', () => {
7
8
  const handleSubmit = jest.fn();
8
9
  const data = {
9
- src: 'https://httpcats.com/302.jpg',
10
- alt: 'Cat with mouse in mouth',
11
- width: 1600,
12
- height: 1400,
10
+ imageType: NodeName.Image,
11
+ image: {
12
+ src: 'https://httpcats.com/302.jpg',
13
+ alt: 'Cat with mouse in mouth',
14
+ width: 1600,
15
+ height: 1400,
16
+ },
13
17
  };
14
18
 
15
- it('Renders the form with the relevant fields', () => {
19
+ it('Renders the form with the relevant fields for arbitrary images', () => {
16
20
  render(<ImageForm data={data} onSubmit={handleSubmit} />);
17
21
 
22
+ expect(screen.getByLabelText('Type')).toHaveTextContent('External image');
18
23
  expect(screen.getByLabelText('Source')).toHaveValue('https://httpcats.com/302.jpg');
19
24
  expect(screen.getByLabelText('Alternative description')).toHaveValue('Cat with mouse in mouth');
20
25
  expect(screen.getByLabelText('Width')).toHaveValue(1600);
21
26
  expect(screen.getByLabelText('Height')).toHaveValue(1400);
22
27
  });
28
+
29
+ it('Renders the form with the relevant fields for asset images', () => {
30
+ render(
31
+ <ImageForm
32
+ data={{
33
+ ...data,
34
+ imageType: NodeName.AssetImage,
35
+ assetImage: { matrixAssetId: '100' },
36
+ }}
37
+ onSubmit={handleSubmit}
38
+ />,
39
+ );
40
+
41
+ expect(screen.getByLabelText('Type')).toHaveTextContent('Asset image');
42
+ expect(screen.getByLabelText('Asset ID')).toHaveValue('100');
43
+ });
44
+
45
+ it('calculates the height when width changes and aspect ratio is locked', () => {
46
+ render(<ImageForm data={data} onSubmit={handleSubmit} />);
47
+ const widthInput = screen.getByLabelText('Width');
48
+ const heightInput = screen.getByLabelText('Height');
49
+
50
+ // change the width value
51
+ act(() => {
52
+ fireEvent.change(widthInput, { target: { value: 800 } });
53
+ });
54
+
55
+ // check that the height value has been calculated correctly
56
+ expect(heightInput).toHaveValue(450);
57
+ });
58
+
59
+ it('calculates the width when height changes and aspect ratio is locked', () => {
60
+ render(<ImageForm data={data} onSubmit={handleSubmit} />);
61
+ const widthInput = screen.getByLabelText('Width');
62
+ const heightInput = screen.getByLabelText('Height');
63
+
64
+ // change the height value
65
+ act(() => {
66
+ fireEvent.change(heightInput, { target: { value: 800 } });
67
+ });
68
+
69
+ // check that the width value has been calculated correctly
70
+ expect(widthInput).toHaveValue(1422.22);
71
+ });
72
+
73
+ it('does not calculate dimensions when aspect ratio is unlocked', () => {
74
+ render(<ImageForm data={data} onSubmit={handleSubmit} />);
75
+ const widthInput = screen.getByLabelText('Width');
76
+ const heightInput = screen.getByLabelText('Height');
77
+ const toggleButton = screen.getByRole('button', { name: 'Constrain properties' });
78
+
79
+ // unlock the aspect ratio
80
+ fireEvent.click(toggleButton);
81
+
82
+ // change the width value
83
+ act(() => {
84
+ fireEvent.change(widthInput, { target: { value: 800 } });
85
+ });
86
+
87
+ // check that the height value has not been calculated
88
+ expect(heightInput).toHaveValue(1400);
89
+
90
+ // change the height value
91
+ act(() => {
92
+ fireEvent.change(heightInput, { target: { value: 800 } });
93
+ });
94
+
95
+ // check that the width value has not been calculated
96
+ expect(widthInput).toHaveValue(800);
97
+ });
23
98
  });
@@ -1,4 +1,4 @@
1
- import React, { ReactElement, useState } from 'react';
1
+ import React, { ReactElement, useContext, useState } from 'react';
2
2
  import { Input } from '../../../../ui/Fields/Input/Input';
3
3
  import { SubmitHandler, useForm } from 'react-hook-form';
4
4
  import { getImageSize } from 'react-image-size';
@@ -6,51 +6,79 @@ import { ImageAttributes } from '@remirror/extension-image/dist-types/image-exte
6
6
  import Button from '../../../../ui/Button/Button';
7
7
  import LinkOffIcon from '@mui/icons-material/LinkOff';
8
8
  import InsertLinkRoundedIcon from '@mui/icons-material/InsertLinkRounded';
9
+ import clsx from 'clsx';
10
+ import { NodeName } from '../../../../Extensions/Extensions';
11
+ import { AssetImageAttributes } from '../../../../Extensions/ImageExtension/AssetImageExtension';
12
+ import { DeepPartial } from '../../../../types';
13
+ import { Select, SelectOptions } from '../../../../ui/Fields/Select/Select';
14
+ import { EditorContext } from '../../../../Editor/EditorContext';
9
15
 
10
- export type UpdateImageOptions = ImageAttributes & {
11
- src: string;
12
- alt: string;
13
- width: number;
14
- height: number;
16
+ export type ImageFormData = {
17
+ imageType: NodeName;
18
+ image: Pick<ImageAttributes, 'src' | 'alt' | 'width' | 'height'>;
19
+ assetImage: AssetImageAttributes;
20
+ };
21
+
22
+ const imageTypeOptions: SelectOptions = {
23
+ [NodeName.Image]: { label: 'External image' },
24
+ [NodeName.AssetImage]: { label: 'Asset image' },
15
25
  };
16
- export type ImageFormData = Pick<UpdateImageOptions, 'src' | 'alt' | 'width' | 'height'>;
17
26
 
18
27
  export type FormProps = {
19
- data: Partial<ImageFormData>;
28
+ data: DeepPartial<ImageFormData>;
20
29
  onSubmit: SubmitHandler<ImageFormData>;
21
30
  };
22
- export type Dimensions = 'width' | 'height';
31
+ export type Dimensions = 'image.width' | 'image.height';
32
+
33
+ const regexDataURI =
34
+ /^data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@/?%\s]*)$/i;
23
35
 
24
36
  const ImageForm = ({ data, onSubmit }: FormProps): ReactElement => {
25
- const { register, handleSubmit, setValue } = useForm<ImageFormData>({
37
+ const {
38
+ register,
39
+ handleSubmit,
40
+ setValue,
41
+ watch,
42
+ formState: { errors },
43
+ } = useForm<ImageFormData>({
26
44
  defaultValues: data,
27
45
  });
46
+ const imageType = watch('imageType') || NodeName.Image;
47
+ const context = useContext(EditorContext);
28
48
  const [aspectRatioFromWidth, setAspectRatioFromWidth] = useState(9 / 16);
29
49
  const [aspectRatioFromHeight, setAspectRatioFromHeight] = useState(16 / 9);
30
50
  const [aspectRatioLocked, setAspectRatioLocked] = useState(true);
31
51
 
32
- const setDimensionsFromURL = (e: { target: { value: string } }) => {
33
- // get the new url, calculate the width and height and set those fields
34
- getImageSize(e.target.value)
35
- .then(({ width, height }) => {
36
- setValue('width', width);
37
- setValue('height', height);
38
- setAspectRatioFromWidth(height / width);
39
- setAspectRatioFromHeight(width / height);
40
- })
41
- .catch((errorMessage) => {
42
- // TODO: we will use this when we add validation in a follow-up ticket
43
- console.log(errorMessage);
44
- });
52
+ const setDimensionsFromURL = async (e: React.ChangeEvent<HTMLInputElement>) => {
53
+ try {
54
+ const { width, height } = await getImageSize(e.target.value);
55
+
56
+ setValue('image.width', width);
57
+ setValue('image.height', height);
58
+ setAspectRatioFromWidth(height / width);
59
+ setAspectRatioFromHeight(width / height);
60
+ } catch (error) {
61
+ // swallow the error for fetching the image size, will occur if the URL does not point to an image.
62
+ // will be handled by validation when attempting to add the image.
63
+ }
64
+ };
65
+
66
+ const validateIsNotImage = async (src: string) => {
67
+ try {
68
+ await getImageSize(src);
69
+ return false;
70
+ } catch (error) {
71
+ return true;
72
+ }
45
73
  };
46
74
 
47
- const calculateDimensions = () => {
75
+ const calculateDimensions = (event: Event) => {
48
76
  if (aspectRatioLocked) {
49
77
  const currentTarget = event?.target as HTMLInputElement;
50
78
  const type = currentTarget.name as Dimensions;
51
79
  const currentValue = currentTarget.value as string;
52
- const otherValue = type === 'width' ? 'height' : 'width';
53
- const aspectRatio = type === 'width' ? aspectRatioFromWidth : aspectRatioFromHeight;
80
+ const otherValue = type === 'image.width' ? 'image.height' : 'image.width';
81
+ const aspectRatio = type === 'image.width' ? aspectRatioFromWidth : aspectRatioFromHeight;
54
82
  const newValue = Math.round(aspectRatio * Number(currentValue) * 100) / 100;
55
83
  setValue(otherValue, newValue);
56
84
  }
@@ -63,28 +91,120 @@ const ImageForm = ({ data, onSubmit }: FormProps): ReactElement => {
63
91
  return (
64
92
  <form className="squiz-fte-form" onSubmit={handleSubmit(onSubmit)}>
65
93
  <div className="squiz-fte-form-group mb-2">
66
- <Input label="Source" {...register('src')} onBlur={setDimensionsFromURL} />
67
- </div>
68
- <div className="squiz-fte-form-group mb-2">
69
- <Input label="Alternative description" {...register('alt')} />
70
- </div>
71
- <div className="flex flex-row items-end">
72
- <div className="squiz-fte-form-group mb-2">
73
- <Input label="Width" {...register('width')} type="number" name="width" onChange={calculateDimensions} />
74
- </div>
75
- <div className="flex mx-1 mb-2">
76
- <Button
77
- handleOnClick={toggleAspectRatio}
78
- isActive={false}
79
- icon={aspectRatioLocked ? <InsertLinkRoundedIcon /> : <LinkOffIcon />}
80
- label="Constrain properties"
81
- isDisabled={false}
82
- />
83
- </div>
84
- <div className="squiz-fte-form-group mb-2">
85
- <Input label="Height" {...register('height')} type="number" name="height" onChange={calculateDimensions} />
86
- </div>
94
+ <Select
95
+ name="imageType"
96
+ label="Type"
97
+ value={imageType}
98
+ options={imageTypeOptions}
99
+ onChange={(value) => setValue('imageType', value as NodeName)}
100
+ />
87
101
  </div>
102
+ {imageType === NodeName.Image && (
103
+ <>
104
+ <div className="squiz-fte-form-group mb-2">
105
+ <Input
106
+ label="Source"
107
+ required
108
+ error={errors?.image?.src?.message}
109
+ {...register('image.src', {
110
+ onChange: setDimensionsFromURL,
111
+ required: 'Source is required',
112
+ validate: {
113
+ isValidImage: async (value: string | undefined) => {
114
+ if (value && regexDataURI.test(value)) {
115
+ return 'Must not be a data URI';
116
+ }
117
+ if (value && (await validateIsNotImage(value))) {
118
+ return 'Must be a valid image URL';
119
+ }
120
+ },
121
+ },
122
+ })}
123
+ />
124
+ </div>
125
+ <div className="squiz-fte-form-group mb-2">
126
+ <Input
127
+ label="Alternative description"
128
+ required
129
+ error={errors?.image?.alt?.message}
130
+ {...register('image.alt', { required: 'Alternative description is required' })}
131
+ />
132
+ </div>
133
+ <div className="flex flex-row">
134
+ <div className="squiz-fte-form-group mb-2">
135
+ <Input
136
+ label="Width"
137
+ type="number"
138
+ required
139
+ error={errors?.image?.width?.message}
140
+ {...register('image.width', {
141
+ onChange: calculateDimensions,
142
+ required: 'Width is required',
143
+ validate: {
144
+ isValidWidth: (value) => {
145
+ if (value && !(value > 0)) {
146
+ return 'Must be higher than 0';
147
+ }
148
+ },
149
+ },
150
+ })}
151
+ />
152
+ </div>
153
+ <div className="flex mx-1 mb-2">
154
+ <Button
155
+ handleOnClick={toggleAspectRatio}
156
+ isActive={false}
157
+ icon={aspectRatioLocked ? <InsertLinkRoundedIcon /> : <LinkOffIcon />}
158
+ label="Constrain properties"
159
+ isDisabled={false}
160
+ className={clsx('my-auto', !errors?.image?.height && !errors?.image?.width && 'mb-0')}
161
+ />
162
+ </div>
163
+ <div className="squiz-fte-form-group mb-2">
164
+ <Input
165
+ label="Height"
166
+ type="number"
167
+ required
168
+ error={errors?.image?.height?.message}
169
+ {...register('image.height', {
170
+ onChange: calculateDimensions,
171
+ required: 'Height is required',
172
+ validate: {
173
+ isValidHeight: (value) => {
174
+ if (value && !(value > 0)) {
175
+ return 'Must be higher than 0';
176
+ }
177
+ },
178
+ },
179
+ })}
180
+ />
181
+ </div>
182
+ </div>
183
+ </>
184
+ )}
185
+ {imageType === NodeName.AssetImage && (
186
+ <>
187
+ <div className="squiz-fte-form-group mb-2">
188
+ <Input
189
+ label="Asset ID"
190
+ required
191
+ error={errors?.assetImage?.matrixAssetId?.message}
192
+ {...register('assetImage.matrixAssetId', {
193
+ required: 'Asset ID is required',
194
+ validate: {
195
+ isImage: async (assetId) => {
196
+ const asset = await context.matrix.resolveMatrixAsset(assetId);
197
+
198
+ if (asset?.type !== 'image') {
199
+ return 'Asset ID is invalid or not an image';
200
+ }
201
+ },
202
+ },
203
+ })}
204
+ />
205
+ </div>
206
+ </>
207
+ )}
88
208
  </form>
89
209
  );
90
210
  };