@limetech/lime-elements 38.11.1 → 38.12.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 (53) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/cjs/index.cjs.js +0 -9
  3. package/dist/cjs/index.cjs.js.map +1 -1
  4. package/dist/cjs/limel-prosemirror-adapter.cjs.entry.js +209 -111
  5. package/dist/cjs/limel-prosemirror-adapter.cjs.entry.js.map +1 -1
  6. package/dist/cjs/limel-text-editor.cjs.entry.js +7 -1
  7. package/dist/cjs/limel-text-editor.cjs.entry.js.map +1 -1
  8. package/dist/collection/components/text-editor/prosemirror-adapter/plugins/image/inserter.js +15 -54
  9. package/dist/collection/components/text-editor/prosemirror-adapter/plugins/image/inserter.js.map +1 -1
  10. package/dist/collection/components/text-editor/prosemirror-adapter/plugins/image/node.js +51 -43
  11. package/dist/collection/components/text-editor/prosemirror-adapter/plugins/image/node.js.map +1 -1
  12. package/dist/collection/components/text-editor/prosemirror-adapter/plugins/image/view.js +10 -12
  13. package/dist/collection/components/text-editor/prosemirror-adapter/plugins/image/view.js.map +1 -1
  14. package/dist/collection/components/text-editor/prosemirror-adapter/plugins/link-plugin.js.map +1 -1
  15. package/dist/collection/components/text-editor/prosemirror-adapter/prosemirror-adapter.js +51 -5
  16. package/dist/collection/components/text-editor/prosemirror-adapter/prosemirror-adapter.js.map +1 -1
  17. package/dist/collection/components/text-editor/text-editor.js +38 -4
  18. package/dist/collection/components/text-editor/text-editor.js.map +1 -1
  19. package/dist/collection/components/text-editor/text-editor.types.js +1 -9
  20. package/dist/collection/components/text-editor/text-editor.types.js.map +1 -1
  21. package/dist/collection/components/text-editor/utils/metadata-utils.js +108 -0
  22. package/dist/collection/components/text-editor/utils/metadata-utils.js.map +1 -0
  23. package/dist/esm/index.js +0 -2
  24. package/dist/esm/index.js.map +1 -1
  25. package/dist/esm/limel-prosemirror-adapter.entry.js +209 -111
  26. package/dist/esm/limel-prosemirror-adapter.entry.js.map +1 -1
  27. package/dist/esm/limel-text-editor.entry.js +7 -1
  28. package/dist/esm/limel-text-editor.entry.js.map +1 -1
  29. package/dist/lime-elements/index.esm.js +1 -1
  30. package/dist/lime-elements/index.esm.js.map +1 -1
  31. package/dist/lime-elements/lime-elements.esm.js +1 -1
  32. package/dist/lime-elements/p-7b039dab.entry.js +2 -0
  33. package/dist/lime-elements/p-7b039dab.entry.js.map +1 -0
  34. package/dist/lime-elements/{p-033fa919.entry.js → p-7f3045bd.entry.js} +2 -2
  35. package/dist/lime-elements/p-7f3045bd.entry.js.map +1 -0
  36. package/dist/types/components/text-editor/prosemirror-adapter/plugins/image/inserter.d.ts +2 -7
  37. package/dist/types/components/text-editor/prosemirror-adapter/plugins/image/node.d.ts +9 -0
  38. package/dist/types/components/text-editor/prosemirror-adapter/plugins/link-plugin.d.ts +0 -4
  39. package/dist/types/components/text-editor/prosemirror-adapter/prosemirror-adapter.d.ts +10 -0
  40. package/dist/types/components/text-editor/text-editor.d.ts +10 -0
  41. package/dist/types/components/text-editor/text-editor.types.d.ts +32 -7
  42. package/dist/types/components/text-editor/utils/metadata-utils.d.ts +22 -0
  43. package/dist/types/components.d.ts +17 -4
  44. package/package.json +1 -1
  45. package/dist/cjs/text-editor.types-5e5567e2.js +0 -13
  46. package/dist/cjs/text-editor.types-5e5567e2.js.map +0 -1
  47. package/dist/esm/text-editor.types-e82469d1.js +0 -13
  48. package/dist/esm/text-editor.types-e82469d1.js.map +0 -1
  49. package/dist/lime-elements/p-033fa919.entry.js.map +0 -1
  50. package/dist/lime-elements/p-7006fafe.entry.js +0 -2
  51. package/dist/lime-elements/p-7006fafe.entry.js.map +0 -1
  52. package/dist/lime-elements/p-9ca516ed.js +0 -2
  53. package/dist/lime-elements/p-9ca516ed.js.map +0 -1
@@ -13,6 +13,7 @@ const TextEditor = class {
13
13
  this.change = index.createEvent(this, "change", 7);
14
14
  this.imagePasted = index.createEvent(this, "imagePasted", 7);
15
15
  this.imageRemoved = index.createEvent(this, "imageRemoved", 7);
16
+ this.metadataChange = index.createEvent(this, "metadataChange", 7);
16
17
  this.triggerStart = index.createEvent(this, "triggerStart", 7);
17
18
  this.triggerStop = index.createEvent(this, "triggerStop", 7);
18
19
  this.triggerChange = index.createEvent(this, "triggerChange", 7);
@@ -39,8 +40,13 @@ const TextEditor = class {
39
40
  event.stopPropagation();
40
41
  this.imagePasted.emit(event.detail);
41
42
  };
43
+ this.handleMetadataChange = (event) => {
44
+ event.stopPropagation();
45
+ this.metadataChange.emit(event.detail);
46
+ };
42
47
  this.handleImageRemoved = (event) => {
43
48
  event.stopPropagation();
49
+ // eslint-disable-next-line sonarjs/deprecation
44
50
  this.imageRemoved.emit(event.detail);
45
51
  };
46
52
  this.contentType = 'markdown';
@@ -67,7 +73,7 @@ const TextEditor = class {
67
73
  if (this.readonly) {
68
74
  return (index.h("limel-markdown", { slot: "content", value: this.value, "aria-controls": this.helperTextId, id: this.editorId }));
69
75
  }
70
- return (index.h("limel-prosemirror-adapter", { slot: "content", "aria-placeholder": this.placeholder, contentType: this.contentType, onChange: this.handleChange, onImagePasted: this.handleImagePasted, onImageRemoved: this.handleImageRemoved, customElements: this.customElements, value: this.value, "aria-controls": this.helperTextId, id: this.editorId, "aria-disabled": this.disabled, "aria-invalid": this.invalid, "aria-required": this.required, language: this.language, triggerCharacters: this.triggers, disabled: this.disabled, ui: this.ui }));
76
+ return (index.h("limel-prosemirror-adapter", { slot: "content", "aria-placeholder": this.placeholder, contentType: this.contentType, onChange: this.handleChange, onImagePasted: this.handleImagePasted, onImageRemoved: this.handleImageRemoved, onMetadataChange: this.handleMetadataChange, customElements: this.customElements, value: this.value, "aria-controls": this.helperTextId, id: this.editorId, "aria-disabled": this.disabled, "aria-invalid": this.invalid, "aria-required": this.required, language: this.language, triggerCharacters: this.triggers, disabled: this.disabled, ui: this.ui }));
71
77
  }
72
78
  renderPlaceholder() {
73
79
  if (!this.placeholder || this.value) {
@@ -1 +1 @@
1
- {"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EAEO,iBAAiB;IACrB,IAAI,CAAC,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,KAAK,EAAE;MACjC,OAAO;KACV;IAED,QACIA,kBAAM,KAAK,EAAC,aAAa,iBAAa,MAAM,EAAC,IAAI,EAAC,SAAS,IACtD,IAAI,CAAC,WAAW,CACd,EACT;GACL;;;;;;;","names":["h","createRandomString","Host"],"sources":["./src/components/text-editor/text-editor.scss?tag=limel-text-editor&encapsulation=shadow","./src/components/text-editor/text-editor.tsx"],"sourcesContent":["@use '../../style/internal/shared_input-select-picker';\n@use '../../style/mixins.scss';\n\n/**\n * @prop --text-editor-max-height: the tallest height the text editor can become when auto-resizing itself. Defaults to `calc(100vh - (env(safe-area-inset-top) + env(safe-area-inset-bottom)) - 4rem)`.\n * @prop --text-editor-fade-out-background-color: the color of the fade-out effect at the top and bottom of the text editor, when the text-editor is in readonly state. Defaults to rgb(var(--contrast-100)).\n */\n\n* {\n box-sizing: border-box;\n}\n\n$min-height: 5rem;\n$min-height-condensed: calc($min-height / 2);\n\n:host(limel-text-editor) {\n --limel-notched-outline-z-index: 2; // since `div.toolbar` has `z-index: 1;`\n --limel-prosemirror-adapter-toolbar-opacity: 0.6;\n --limel-text-editor-padding: 0.25rem 1rem 0.75rem 1rem;\n --limel-prosemirror-adapter-toolbar-grid-template-rows: 1fr;\n --limel-prosemirror-adapter-toolbar-grid-template-rows-transition-duration: 0.3s;\n --limel-prosemirror-adapter-toolbar-transition-timing-function: cubic-bezier(\n 0.19,\n 0.23,\n 0.26,\n 0.89\n );\n\n position: relative;\n isolation: isolate;\n display: flex;\n flex-direction: column;\n\n width: 100%;\n min-width: 5rem;\n min-height: $min-height;\n height: 100%;\n max-height: var(\n --text-editor-max-height,\n calc(\n 100vh - (env(safe-area-inset-top) + env(safe-area-inset-bottom)) -\n 4rem\n )\n );\n padding: 1px; // prevents visual defects that can appear due to the backdrop-filter and closeness to borders\n}\n\n:host(limel-text-editor:focus-within),\n:host(limel-text-editor:not([ui='minimal']):hover) {\n --limel-prosemirror-adapter-toolbar-opacity: 1;\n}\n\n:host(limel-text-editor[ui='minimal']:not(:focus-within)) {\n --limel-prosemirror-adapter-toolbar-grid-template-rows: 0fr;\n --limel-prosemirror-adapter-toolbar-grid-template-rows-transition-duration: 0.46s;\n --limel-prosemirror-adapter-action-bar-padding-top-bottom: 0;\n --limel-prosemirror-adapter-toolbar-opacity: 0;\n}\n\n:host(limel-text-editor[ui='minimal']:not(:focus-within)),\n:host(limel-text-editor[ui='no-toolbar']) {\n --limel-text-editor-padding: 0.75rem 1rem 0.75rem 1rem;\n --limel-text-editor-placeholder-top: 0;\n\n min-height: $min-height-condensed;\n limel-prosemirror-adapter {\n min-height: $min-height-condensed;\n }\n}\n\n:host(limel-text-editor:focus-within),\n:host(limel-text-editor:focus) {\n .placeholder {\n opacity: 0;\n }\n}\n\n:host(limel-text-editor[disabled]:not([disabled='false'])) {\n limel-prosemirror-adapter {\n @include shared_input-select-picker.looks-disabled;\n pointer-events: none;\n }\n}\n\n:host(limel-text-editor[readonly]:not([readonly='false'])) {\n --limel-text-editor-padding: 0.75rem 1rem 0.75rem 1rem;\n --limel-text-editor-placeholder-top: 0;\n\n limel-markdown {\n // displayed when `readonly` instead of the adapter\n display: block;\n padding: var(--limel-text-editor-padding);\n\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n height: 100%;\n\n &:before,\n &:after {\n z-index: 1;\n pointer-events: none;\n content: '';\n display: block;\n position: absolute;\n width: 100%;\n }\n &:after {\n height: 1.75rem;\n top: 0;\n background: linear-gradient(\n var(\n --text-editor-fade-out-background-color,\n rgb(var(--contrast-100))\n ),\n transparent\n );\n }\n\n &:before {\n height: 2rem;\n bottom: -0.25rem;\n background: linear-gradient(\n transparent,\n var(\n --text-editor-fade-out-background-color,\n rgb(var(--contrast-100))\n )\n );\n }\n }\n}\n\n.placeholder {\n transition-property: top;\n transition-duration: var(\n --limel-prosemirror-adapter-toolbar-grid-template-rows-transition-duration\n );\n transition-timing-function: var(\n --limel-prosemirror-adapter-toolbar-transition-timing-function\n );\n @include mixins.truncate-text;\n pointer-events: none;\n position: absolute;\n top: var(--limel-text-editor-placeholder-top, 2.25rem);\n left: 0;\n right: 0;\n\n padding: var(--limel-text-editor-padding);\n font-style: italic;\n font-size: 0.875rem;\n color: shared_input-select-picker.$input-placeholder-color;\n}\n\nlimel-prosemirror-adapter {\n flex-grow: 1;\n\n min-width: 0;\n min-height: $min-height;\n height: 100%;\n overflow: hidden auto;\n -webkit-overflow-scrolling: touch;\n}\n\n@include mixins.hide-helper-line-when-not-needed(limel-text-editor);\n\n:host(limel-text-editor[allow-resize]) {\n limel-prosemirror-adapter {\n resize: vertical;\n }\n}\n","import { Component, Event, EventEmitter, Host, Prop, h } from '@stencil/core';\nimport { FormComponent } from '../form/form.types';\nimport { Languages } from '../date-picker/date.types';\nimport { createRandomString } from '../../util/random-string';\nimport { CustomElementDefinition } from '../../global/shared-types/custom-element.types';\nimport {\n TriggerCharacter,\n TriggerEventDetail,\n ImageInserter,\n ImageInfo,\n} from './text-editor.types';\nimport { EditorUiType } from './types';\n\n/**\n * A rich text editor that offers a rich text editing experience with markdown support,\n * in the sense that you can easily type markdown syntax and see the rendered\n * result as rich text in real-time. For instance, you can type `# Hello, world!`\n * and see it directly turning to a heading 1 (an `<h1>` HTML element).\n *\n * Naturally, you can use standard keyboard hotkeys such as <kbd>Ctrl</kbd> + <kbd>B</kbd>\n * to toggle bold text, <kbd>Ctrl</kbd> + <kbd>I</kbd> to toggle italic text, and so on.\n *\n * @exampleComponent limel-example-text-editor-basic\n * @exampleComponent limel-example-text-editor-as-form-component\n * @exampleComponent limel-example-text-editor-with-markdown\n * @exampleComponent limel-example-text-editor-with-html\n * @exampleComponent limel-example-text-editor-with-tables\n * @exampleComponent limel-example-text-editor-with-inline-images-file-storage\n * @exampleComponent limel-example-text-editor-with-inline-images-base64\n * @exampleComponent limel-example-text-editor-allow-resize\n * @exampleComponent limel-example-text-editor-size\n * @exampleComponent limel-example-text-editor-ui\n * @exampleComponent limel-example-text-editor-custom-element\n * @exampleComponent limel-example-text-editor-triggers\n * @exampleComponent limel-example-text-editor-composite\n * @beta\n */\n@Component({\n tag: 'limel-text-editor',\n shadow: { delegatesFocus: true },\n styleUrl: 'text-editor.scss',\n})\nexport class TextEditor implements FormComponent<string> {\n /** The type of content that the editor should handle and emit, defaults to `markdown`\n *\n * Assumed to be set only once, so not reactive to changes\n */\n @Prop()\n public contentType: 'markdown' | 'html' = 'markdown';\n\n /**\n * Defines the language for translations.\n */\n @Prop({ reflect: true })\n public language: Languages = 'en';\n\n /**\n * Set to `true` to disable the field.\n * Use `disabled` to indicate that the field can normally be interacted\n * with, but is currently disabled. This tells the user that if certain\n * requirements are met, the field may become enabled again.\n */\n @Prop({ reflect: true })\n public disabled?: boolean = false;\n\n /**\n * Set to `true` to make the component read-only.\n * Use `readonly` when the field is only there to present the data it holds,\n * and will not become possible for the current user to edit.\n * :::note\n * Consider that it might be better to use `limel-markdown`\n * instead of `limel-text-editor` when the goal is visualizing data.\n * :::\n */\n @Prop({ reflect: true })\n public readonly?: boolean = false;\n\n /**\n * Optional helper text to display below the input field when it has focus\n */\n @Prop({ reflect: true })\n public helperText?: string;\n\n /**\n * The placeholder text shown inside the input field,\n * when the field is empty.\n */\n @Prop({ reflect: true })\n public placeholder?: string;\n\n /**\n * The label of the editor\n */\n @Prop({ reflect: true })\n public label?: string;\n\n /**\n * Set to `true` to indicate that the current value of the editor is\n * invalid.\n */\n @Prop({ reflect: true })\n public invalid?: boolean = false;\n\n /**\n * Description of the text inside the editor as markdown\n */\n @Prop({ reflect: true })\n public value: string;\n\n /**\n * A list of custom elements\n *\n * Any `CustomElement` that should be used inside the text editor needs\n * to be defined here.\n *\n * @private\n * @alpha\n */\n @Prop()\n public customElements: CustomElementDefinition[] = [];\n\n /**\n * A set of trigger characters\n *\n * Defining a character here will enable trigger events to be sent if the\n * character is detected in the editor.\n *\n * @private\n * @alpha\n */\n @Prop()\n public triggers: TriggerCharacter[] = [];\n\n /**\n * Set to `true` to indicate that the field is required.\n *\n * :::important\n * An empty but required field is not automatically considered invalid.\n * You must make sure to check the validity of the field on your own,\n * and properly handle the `invalid` state.\n * :::\n */\n @Prop({ reflect: true })\n public required?: boolean = false;\n\n /**\n * Set to `true` to allow the user to vertically resize the editor.\n * Set to `false` to disable the resize functionality.\n */\n @Prop({ reflect: true })\n public allowResize: boolean = true;\n\n /**\n * Specifies the visual appearance of the editor.\n *\n * - `standard`: The default editor appearance with a full toolbar and\n * standard layout.\n * - `minimal`: A compact editor appearance, ideal for limited space\n * scenarios such as mobile devices. In this mode, the toolbar is hidden\n * until the editor is focused.\n * - `no-toolbar`: A basic textarea appearance without any text styling toolbar.\n * This mode is suitable for scenarios where you want to provide a simple\n * text input without any visible formatting options; but still provide\n * support for markdown syntax and rich text, using hotkeys or when pasting.\n */\n @Prop({ reflect: true })\n public ui?: EditorUiType = 'standard';\n\n /**\n * Dispatched when a change is made to the editor\n */\n @Event()\n public change: EventEmitter<string>;\n\n /**\n * Dispatched when a image is pasted into the editor\n *\n * @private\n * @alpha\n */\n @Event()\n private readonly imagePasted: EventEmitter<ImageInserter>;\n\n /**\n * Dispatched when a image is removed from the editor\n *\n * @private\n * @alpha\n */\n @Event()\n private readonly imageRemoved: EventEmitter<ImageInfo>;\n\n /**\n * Dispatched if a trigger character is detected.\n *\n * @private\n * @alpha\n */\n @Event()\n public triggerStart: EventEmitter<TriggerEventDetail>;\n\n /**\n * Dispatched if a trigger session is ended. That is if the selection\n * goes outside the trigger input or if something is inserted using the\n * supplied `TextEditor` insert function.\n *\n * @private\n * @alpha\n */\n @Event()\n public triggerStop: EventEmitter<TriggerEventDetail>;\n\n /**\n * Dispatched if a input is changed during an active trigger.\n *\n * @private\n * @alpha\n */\n @Event()\n public triggerChange: EventEmitter<TriggerEventDetail>;\n\n private readonly helperTextId: string;\n private readonly editorId: string;\n\n public constructor() {\n this.helperTextId = createRandomString();\n this.editorId = createRandomString();\n }\n\n public render() {\n return (\n <Host>\n <limel-notched-outline\n labelId={this.editorId}\n label={this.label}\n required={this.required}\n invalid={this.invalid}\n disabled={this.disabled}\n readonly={this.readonly}\n hasValue={!!this.value}\n hasFloatingLabel={true}\n >\n {this.renderEditor()}\n {this.renderPlaceholder()}\n </limel-notched-outline>\n {this.renderHelperLine()}\n </Host>\n );\n }\n\n private renderEditor() {\n if (this.readonly) {\n return (\n <limel-markdown\n slot=\"content\"\n value={this.value}\n aria-controls={this.helperTextId}\n id={this.editorId}\n />\n );\n }\n\n return (\n <limel-prosemirror-adapter\n slot=\"content\"\n aria-placeholder={this.placeholder}\n contentType={this.contentType}\n onChange={this.handleChange}\n onImagePasted={this.handleImagePasted}\n onImageRemoved={this.handleImageRemoved}\n customElements={this.customElements}\n value={this.value}\n aria-controls={this.helperTextId}\n id={this.editorId}\n aria-disabled={this.disabled}\n aria-invalid={this.invalid}\n aria-required={this.required}\n language={this.language}\n triggerCharacters={this.triggers}\n disabled={this.disabled}\n ui={this.ui}\n />\n );\n }\n\n private renderPlaceholder() {\n if (!this.placeholder || this.value) {\n return;\n }\n\n return (\n <span class=\"placeholder\" aria-hidden=\"true\" slot=\"content\">\n {this.placeholder}\n </span>\n );\n }\n\n private renderHelperLine = () => {\n if (!this.helperText) {\n return;\n }\n\n return (\n <limel-helper-line\n helperText={this.helperText}\n helperTextId={this.helperTextId}\n invalid={this.isInvalid()}\n />\n );\n };\n\n private isInvalid = () => {\n if (this.readonly) {\n // A readonly field can never be invalid.\n return false;\n }\n\n if (this.invalid) {\n return true;\n }\n };\n\n private handleChange = (event: CustomEvent<string>) => {\n event.stopPropagation();\n this.change.emit(event.detail);\n };\n\n private handleImagePasted = (event: CustomEvent<ImageInserter>) => {\n event.stopPropagation();\n this.imagePasted.emit(event.detail);\n };\n\n private handleImageRemoved = (event: CustomEvent<ImageInfo>) => {\n event.stopPropagation();\n this.imageRemoved.emit(event.detail);\n };\n}\n"],"version":3}
1
+ {"file":"limel-text-editor.entry.c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CAAC,QAAQ,EAC5B,QAAQ,EAAE,IAAI,CAAC,QAAQ,EACvB,iBAAiB,EAAE,IAAI,CAAC,QAAQ,EAChC,QAAQ,EAAE,IAAI,CAAC,QAAQ,EACvB,EAAE,EAAE,IAAI,CAAC,EAAE,GACb,EACJ;GACL;EAEO,iBAAiB;IACrB,IAAI,CAAC,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,KAAK,EAAE;MACjC,OAAO;KACV;IAED,QACIA,kBAAM,KAAK,EAAC,aAAa,iBAAa,MAAM,EAAC,IAAI,EAAC,SAAS,IACtD,IAAI,CAAC,WAAW,CACd,EACT;GACL;;;;;;;","names":["h","createRandomString","Host"],"sources":["./src/components/text-editor/text-editor.scss?tag=limel-text-editor&encapsulation=shadow","./src/components/text-editor/text-editor.tsx"],"sourcesContent":["@use '../../style/internal/shared_input-select-picker';\n@use '../../style/mixins.scss';\n\n/**\n * @prop --text-editor-max-height: the tallest height the text editor can become when auto-resizing itself. Defaults to `calc(100vh - (env(safe-area-inset-top) + env(safe-area-inset-bottom)) - 4rem)`.\n * @prop --text-editor-fade-out-background-color: the color of the fade-out effect at the top and bottom of the text editor, when the text-editor is in readonly state. Defaults to rgb(var(--contrast-100)).\n */\n\n* {\n box-sizing: border-box;\n}\n\n$min-height: 5rem;\n$min-height-condensed: calc($min-height / 2);\n\n:host(limel-text-editor) {\n --limel-notched-outline-z-index: 2; // since `div.toolbar` has `z-index: 1;`\n --limel-prosemirror-adapter-toolbar-opacity: 0.6;\n --limel-text-editor-padding: 0.25rem 1rem 0.75rem 1rem;\n --limel-prosemirror-adapter-toolbar-grid-template-rows: 1fr;\n --limel-prosemirror-adapter-toolbar-grid-template-rows-transition-duration: 0.3s;\n --limel-prosemirror-adapter-toolbar-transition-timing-function: cubic-bezier(\n 0.19,\n 0.23,\n 0.26,\n 0.89\n );\n\n position: relative;\n isolation: isolate;\n display: flex;\n flex-direction: column;\n\n width: 100%;\n min-width: 5rem;\n min-height: $min-height;\n height: 100%;\n max-height: var(\n --text-editor-max-height,\n calc(\n 100vh - (env(safe-area-inset-top) + env(safe-area-inset-bottom)) -\n 4rem\n )\n );\n padding: 1px; // prevents visual defects that can appear due to the backdrop-filter and closeness to borders\n}\n\n:host(limel-text-editor:focus-within),\n:host(limel-text-editor:not([ui='minimal']):hover) {\n --limel-prosemirror-adapter-toolbar-opacity: 1;\n}\n\n:host(limel-text-editor[ui='minimal']:not(:focus-within)) {\n --limel-prosemirror-adapter-toolbar-grid-template-rows: 0fr;\n --limel-prosemirror-adapter-toolbar-grid-template-rows-transition-duration: 0.46s;\n --limel-prosemirror-adapter-action-bar-padding-top-bottom: 0;\n --limel-prosemirror-adapter-toolbar-opacity: 0;\n}\n\n:host(limel-text-editor[ui='minimal']:not(:focus-within)),\n:host(limel-text-editor[ui='no-toolbar']) {\n --limel-text-editor-padding: 0.75rem 1rem 0.75rem 1rem;\n --limel-text-editor-placeholder-top: 0;\n\n min-height: $min-height-condensed;\n limel-prosemirror-adapter {\n min-height: $min-height-condensed;\n }\n}\n\n:host(limel-text-editor:focus-within),\n:host(limel-text-editor:focus) {\n .placeholder {\n opacity: 0;\n }\n}\n\n:host(limel-text-editor[disabled]:not([disabled='false'])) {\n limel-prosemirror-adapter {\n @include shared_input-select-picker.looks-disabled;\n pointer-events: none;\n }\n}\n\n:host(limel-text-editor[readonly]:not([readonly='false'])) {\n --limel-text-editor-padding: 0.75rem 1rem 0.75rem 1rem;\n --limel-text-editor-placeholder-top: 0;\n\n limel-markdown {\n // displayed when `readonly` instead of the adapter\n display: block;\n padding: var(--limel-text-editor-padding);\n\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n height: 100%;\n\n &:before,\n &:after {\n z-index: 1;\n pointer-events: none;\n content: '';\n display: block;\n position: absolute;\n width: 100%;\n }\n &:after {\n height: 1.75rem;\n top: 0;\n background: linear-gradient(\n var(\n --text-editor-fade-out-background-color,\n rgb(var(--contrast-100))\n ),\n transparent\n );\n }\n\n &:before {\n height: 2rem;\n bottom: -0.25rem;\n background: linear-gradient(\n transparent,\n var(\n --text-editor-fade-out-background-color,\n rgb(var(--contrast-100))\n )\n );\n }\n }\n}\n\n.placeholder {\n transition-property: top;\n transition-duration: var(\n --limel-prosemirror-adapter-toolbar-grid-template-rows-transition-duration\n );\n transition-timing-function: var(\n --limel-prosemirror-adapter-toolbar-transition-timing-function\n );\n @include mixins.truncate-text;\n pointer-events: none;\n position: absolute;\n top: var(--limel-text-editor-placeholder-top, 2.25rem);\n left: 0;\n right: 0;\n\n padding: var(--limel-text-editor-padding);\n font-style: italic;\n font-size: 0.875rem;\n color: shared_input-select-picker.$input-placeholder-color;\n}\n\nlimel-prosemirror-adapter {\n flex-grow: 1;\n\n min-width: 0;\n min-height: $min-height;\n height: 100%;\n overflow: hidden auto;\n -webkit-overflow-scrolling: touch;\n}\n\n@include mixins.hide-helper-line-when-not-needed(limel-text-editor);\n\n:host(limel-text-editor[allow-resize]) {\n limel-prosemirror-adapter {\n resize: vertical;\n }\n}\n","import { Component, Event, EventEmitter, Host, Prop, h } from '@stencil/core';\nimport { FormComponent } from '../form/form.types';\nimport { Languages } from '../date-picker/date.types';\nimport { createRandomString } from '../../util/random-string';\nimport { CustomElementDefinition } from '../../global/shared-types/custom-element.types';\nimport {\n TriggerCharacter,\n TriggerEventDetail,\n ImageInserter,\n EditorImage,\n EditorMetadata,\n} from './text-editor.types';\nimport { EditorUiType } from './types';\n\n/**\n * A rich text editor that offers a rich text editing experience with markdown support,\n * in the sense that you can easily type markdown syntax and see the rendered\n * result as rich text in real-time. For instance, you can type `# Hello, world!`\n * and see it directly turning to a heading 1 (an `<h1>` HTML element).\n *\n * Naturally, you can use standard keyboard hotkeys such as <kbd>Ctrl</kbd> + <kbd>B</kbd>\n * to toggle bold text, <kbd>Ctrl</kbd> + <kbd>I</kbd> to toggle italic text, and so on.\n *\n * @exampleComponent limel-example-text-editor-basic\n * @exampleComponent limel-example-text-editor-as-form-component\n * @exampleComponent limel-example-text-editor-with-markdown\n * @exampleComponent limel-example-text-editor-with-html\n * @exampleComponent limel-example-text-editor-with-tables\n * @exampleComponent limel-example-text-editor-with-inline-images-file-storage\n * @exampleComponent limel-example-text-editor-with-inline-images-base64\n * @exampleComponent limel-example-text-editor-allow-resize\n * @exampleComponent limel-example-text-editor-size\n * @exampleComponent limel-example-text-editor-ui\n * @exampleComponent limel-example-text-editor-custom-element\n * @exampleComponent limel-example-text-editor-triggers\n * @exampleComponent limel-example-text-editor-composite\n * @beta\n */\n@Component({\n tag: 'limel-text-editor',\n shadow: { delegatesFocus: true },\n styleUrl: 'text-editor.scss',\n})\nexport class TextEditor implements FormComponent<string> {\n /** The type of content that the editor should handle and emit, defaults to `markdown`\n *\n * Assumed to be set only once, so not reactive to changes\n */\n @Prop()\n public contentType: 'markdown' | 'html' = 'markdown';\n\n /**\n * Defines the language for translations.\n */\n @Prop({ reflect: true })\n public language: Languages = 'en';\n\n /**\n * Set to `true` to disable the field.\n * Use `disabled` to indicate that the field can normally be interacted\n * with, but is currently disabled. This tells the user that if certain\n * requirements are met, the field may become enabled again.\n */\n @Prop({ reflect: true })\n public disabled?: boolean = false;\n\n /**\n * Set to `true` to make the component read-only.\n * Use `readonly` when the field is only there to present the data it holds,\n * and will not become possible for the current user to edit.\n * :::note\n * Consider that it might be better to use `limel-markdown`\n * instead of `limel-text-editor` when the goal is visualizing data.\n * :::\n */\n @Prop({ reflect: true })\n public readonly?: boolean = false;\n\n /**\n * Optional helper text to display below the input field when it has focus\n */\n @Prop({ reflect: true })\n public helperText?: string;\n\n /**\n * The placeholder text shown inside the input field,\n * when the field is empty.\n */\n @Prop({ reflect: true })\n public placeholder?: string;\n\n /**\n * The label of the editor\n */\n @Prop({ reflect: true })\n public label?: string;\n\n /**\n * Set to `true` to indicate that the current value of the editor is\n * invalid.\n */\n @Prop({ reflect: true })\n public invalid?: boolean = false;\n\n /**\n * Description of the text inside the editor as markdown\n */\n @Prop({ reflect: true })\n public value: string;\n\n /**\n * A list of custom elements\n *\n * Any `CustomElement` that should be used inside the text editor needs\n * to be defined here.\n *\n * @private\n * @alpha\n */\n @Prop()\n public customElements: CustomElementDefinition[] = [];\n\n /**\n * A set of trigger characters\n *\n * Defining a character here will enable trigger events to be sent if the\n * character is detected in the editor.\n *\n * @private\n * @alpha\n */\n @Prop()\n public triggers: TriggerCharacter[] = [];\n\n /**\n * Set to `true` to indicate that the field is required.\n *\n * :::important\n * An empty but required field is not automatically considered invalid.\n * You must make sure to check the validity of the field on your own,\n * and properly handle the `invalid` state.\n * :::\n */\n @Prop({ reflect: true })\n public required?: boolean = false;\n\n /**\n * Set to `true` to allow the user to vertically resize the editor.\n * Set to `false` to disable the resize functionality.\n */\n @Prop({ reflect: true })\n public allowResize: boolean = true;\n\n /**\n * Specifies the visual appearance of the editor.\n *\n * - `standard`: The default editor appearance with a full toolbar and\n * standard layout.\n * - `minimal`: A compact editor appearance, ideal for limited space\n * scenarios such as mobile devices. In this mode, the toolbar is hidden\n * until the editor is focused.\n * - `no-toolbar`: A basic textarea appearance without any text styling toolbar.\n * This mode is suitable for scenarios where you want to provide a simple\n * text input without any visible formatting options; but still provide\n * support for markdown syntax and rich text, using hotkeys or when pasting.\n */\n @Prop({ reflect: true })\n public ui?: EditorUiType = 'standard';\n\n /**\n * Dispatched when a change is made to the editor\n */\n @Event()\n public change: EventEmitter<string>;\n\n /**\n * Dispatched when a image is pasted into the editor\n *\n * @private\n * @alpha\n */\n @Event()\n private readonly imagePasted: EventEmitter<ImageInserter>;\n\n /**\n * Dispatched when a image is removed from the editor\n *\n * @private\n * @alpha\n * @deprecated - This event is deprecated and will be removed in a future version.\n * Use the `metadataChange` event instead to track image removals.\n */\n @Event()\n private readonly imageRemoved: EventEmitter<EditorImage>;\n\n /**\n * Dispatched when the metadata of the editor changes\n *\n * @private\n * @alpha\n */\n @Event()\n private readonly metadataChange: EventEmitter<EditorMetadata>;\n\n /**\n * Dispatched if a trigger character is detected.\n *\n * @private\n * @alpha\n */\n @Event()\n public triggerStart: EventEmitter<TriggerEventDetail>;\n\n /**\n * Dispatched if a trigger session is ended. That is if the selection\n * goes outside the trigger input or if something is inserted using the\n * supplied `TextEditor` insert function.\n *\n * @private\n * @alpha\n */\n @Event()\n public triggerStop: EventEmitter<TriggerEventDetail>;\n\n /**\n * Dispatched if a input is changed during an active trigger.\n *\n * @private\n * @alpha\n */\n @Event()\n public triggerChange: EventEmitter<TriggerEventDetail>;\n\n private readonly helperTextId: string;\n private readonly editorId: string;\n\n public constructor() {\n this.helperTextId = createRandomString();\n this.editorId = createRandomString();\n }\n\n public render() {\n return (\n <Host>\n <limel-notched-outline\n labelId={this.editorId}\n label={this.label}\n required={this.required}\n invalid={this.invalid}\n disabled={this.disabled}\n readonly={this.readonly}\n hasValue={!!this.value}\n hasFloatingLabel={true}\n >\n {this.renderEditor()}\n {this.renderPlaceholder()}\n </limel-notched-outline>\n {this.renderHelperLine()}\n </Host>\n );\n }\n\n private renderEditor() {\n if (this.readonly) {\n return (\n <limel-markdown\n slot=\"content\"\n value={this.value}\n aria-controls={this.helperTextId}\n id={this.editorId}\n />\n );\n }\n\n return (\n <limel-prosemirror-adapter\n slot=\"content\"\n aria-placeholder={this.placeholder}\n contentType={this.contentType}\n onChange={this.handleChange}\n onImagePasted={this.handleImagePasted}\n onImageRemoved={this.handleImageRemoved}\n onMetadataChange={this.handleMetadataChange}\n customElements={this.customElements}\n value={this.value}\n aria-controls={this.helperTextId}\n id={this.editorId}\n aria-disabled={this.disabled}\n aria-invalid={this.invalid}\n aria-required={this.required}\n language={this.language}\n triggerCharacters={this.triggers}\n disabled={this.disabled}\n ui={this.ui}\n />\n );\n }\n\n private renderPlaceholder() {\n if (!this.placeholder || this.value) {\n return;\n }\n\n return (\n <span class=\"placeholder\" aria-hidden=\"true\" slot=\"content\">\n {this.placeholder}\n </span>\n );\n }\n\n private renderHelperLine = () => {\n if (!this.helperText) {\n return;\n }\n\n return (\n <limel-helper-line\n helperText={this.helperText}\n helperTextId={this.helperTextId}\n invalid={this.isInvalid()}\n />\n );\n };\n\n private isInvalid = () => {\n if (this.readonly) {\n // A readonly field can never be invalid.\n return false;\n }\n\n if (this.invalid) {\n return true;\n }\n };\n\n private handleChange = (event: CustomEvent<string>) => {\n event.stopPropagation();\n this.change.emit(event.detail);\n };\n\n private handleImagePasted = (event: CustomEvent<ImageInserter>) => {\n event.stopPropagation();\n this.imagePasted.emit(event.detail);\n };\n\n private handleMetadataChange = (event: CustomEvent<EditorMetadata>) => {\n event.stopPropagation();\n this.metadataChange.emit(event.detail);\n };\n\n private handleImageRemoved = (event: CustomEvent<EditorImage>) => {\n event.stopPropagation();\n // eslint-disable-next-line sonarjs/deprecation\n this.imageRemoved.emit(event.detail);\n };\n}\n"],"version":3}
@@ -1,10 +1,8 @@
1
1
  import { Plugin, PluginKey } from 'prosemirror-state';
2
2
  import { createFileInfo } from '../../../../../util/files';
3
- import { ImageState, } from '../../../text-editor.types';
4
3
  import { Node, Slice, Fragment } from 'prosemirror-model';
5
- import { imageCache } from './node';
6
4
  export const pluginKey = new PluginKey('imageInserterPlugin');
7
- export const createImageInserterPlugin = (imagePastedCallback, imageRemovedCallback) => {
5
+ export const createImageInserterPlugin = (imagePastedCallback) => {
8
6
  return new Plugin({
9
7
  key: pluginKey,
10
8
  props: {
@@ -17,40 +15,7 @@ export const createImageInserterPlugin = (imagePastedCallback, imageRemovedCallb
17
15
  },
18
16
  },
19
17
  },
20
- state: {
21
- init: () => {
22
- return { insertedImages: {} };
23
- },
24
- apply: (tr, pluginState) => {
25
- const newState = Object.assign({}, pluginState);
26
- newState.insertedImages = getImagesFromTransaction(tr);
27
- findAndHandleRemovedImages(imageRemovedCallback, pluginState.insertedImages, newState.insertedImages);
28
- return newState;
29
- },
30
- },
31
- });
32
- };
33
- const getImagesFromTransaction = (tr) => {
34
- const images = {};
35
- tr.doc.descendants((node) => {
36
- if (node.type.name === 'image') {
37
- images[node.attrs.fileInfoId] = node;
38
- }
39
18
  });
40
- return images;
41
- };
42
- const findAndHandleRemovedImages = (imageRemovedCallback, previousImages, newImages) => {
43
- const removedKeys = Object.keys(previousImages).filter((key) => !(key in newImages));
44
- for (const removedKey of removedKeys) {
45
- const removedImage = previousImages[removedKey];
46
- const imageInfo = {
47
- fileInfoId: removedImage.attrs.fileInfoId,
48
- src: removedImage.attrs.src,
49
- state: removedImage.attrs.state,
50
- };
51
- imageRemovedCallback(imageInfo);
52
- imageCache.delete(removedImage.attrs.fileInfoId);
53
- }
54
19
  };
55
20
  export const imageInserterFactory = (view, base64Data, fileInfo) => {
56
21
  return {
@@ -63,12 +28,8 @@ export const imageInserterFactory = (view, base64Data, fileInfo) => {
63
28
  const createThumbnailInserter = (view, base64Data, fileInfo) => () => {
64
29
  const { state, dispatch } = view;
65
30
  const { schema } = state;
66
- const placeholderNode = schema.nodes.image.create({
67
- src: base64Data,
68
- alt: fileInfo.filename,
69
- fileInfoId: fileInfo.id,
70
- state: ImageState.LOADING,
71
- });
31
+ const imageNodeAttrs = createImageNodeAttrs(base64Data, fileInfo, 'loading');
32
+ const placeholderNode = schema.nodes.image.create(imageNodeAttrs);
72
33
  const transaction = state.tr.replaceSelectionWith(placeholderNode);
73
34
  dispatch(transaction);
74
35
  };
@@ -78,12 +39,8 @@ const createImageInserter = (view, fileInfo) => (src) => {
78
39
  const tr = state.tr;
79
40
  state.doc.descendants((node, pos) => {
80
41
  if (node.attrs.fileInfoId === fileInfo.id) {
81
- const imageNode = schema.nodes.image.create({
82
- src: src ? src : node.attrs.src,
83
- alt: fileInfo.filename,
84
- fileInfoId: fileInfo.id,
85
- state: ImageState.SUCCESS,
86
- });
42
+ const imageNodeAttrs = createImageNodeAttrs(src ? src : node.attrs.src, fileInfo, 'success');
43
+ const imageNode = schema.nodes.image.create(imageNodeAttrs);
87
44
  tr.replaceWith(pos, pos + node.nodeSize, imageNode);
88
45
  return false;
89
46
  }
@@ -96,18 +53,22 @@ const createFailedThumbnailInserter = (view, fileInfo) => () => {
96
53
  const tr = state.tr;
97
54
  state.doc.descendants((node, pos) => {
98
55
  if (node.attrs.fileInfoId === fileInfo.id) {
99
- const errorPlaceholderNode = schema.nodes.image.create({
100
- src: node.attrs.src,
101
- alt: fileInfo.filename,
102
- fileInfoId: fileInfo.id,
103
- state: ImageState.FAILED,
104
- });
56
+ const imageNodeAttrs = createImageNodeAttrs(node.attrs.src, fileInfo, 'failed');
57
+ const errorPlaceholderNode = schema.nodes.image.create(imageNodeAttrs);
105
58
  tr.replaceWith(pos, pos + node.nodeSize, errorPlaceholderNode);
106
59
  return false;
107
60
  }
108
61
  });
109
62
  dispatch(tr);
110
63
  };
64
+ function createImageNodeAttrs(src, fileInfo, state) {
65
+ return {
66
+ src: src,
67
+ alt: fileInfo.filename,
68
+ fileInfoId: fileInfo.id,
69
+ state: state,
70
+ };
71
+ }
111
72
  /**
112
73
  * Check if a given ProseMirror node or fragment contains any image nodes.
113
74
  * @param node - The ProseMirror node or fragment to check.
@@ -1 +1 @@
1
- {"version":3,"file":"inserter.js","sourceRoot":"","sources":["../../../../../../src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAA2B,MAAM,mBAAmB,CAAC;AAE/E,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAGH,UAAU,GACb,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAC;AAU9D,MAAM,CAAC,MAAM,yBAAyB,GAAG,CACrC,mBAAwC,EACxC,oBAA0C,EAC5C,EAAE;EACA,OAAO,IAAI,MAAM,CAAC;IACd,GAAG,EAAE,SAAS;IACd,KAAK,EAAE;MACH,WAAW,EAAE,CAAC,IAAI,EAAE,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AAM,GAAG,IAAI,UAAU,EAAE,CAAC;MAChC,MAAM,CAAC,SAAS,GAAG,GAAG,EAAE;QACpB,IAAI,CAAC,GAAG,CAAC,aAAa,CAClB,IAAI,WAAW,CAAC,aAAa,EAAE;UAC3B,MAAM,EAAE,oBAAoB,CACxB,IAAI,EACJ,MAAM,CAAC,MAAgB,EACvB,cAAc,CAAC,IAAI,CAAC,CACvB;SACJ,CAAC,CACL,CAAC;MACN,CAAC,CAAC;MAEF,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;KAC9B;GACJ;EAED,MAAM,aAAa,GAAG,IAAI,KAAK,CAC3B,gBAAgB,CAAC,KAAK,CAAC,OAAO,CAAC,EAC/B,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,OAAO,CAChB,CAAC;EAEF,IAAI,aAAa,CAAC,OAAO,CAAC,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE;IAC7D,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;IACjC,MAAM,EAAE,GAAG,KAAK,CAAC,EAAE,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;IACpD,QAAQ,CAAC,EAAE,CAAC,CAAC;IAEb,OAAO,IAAI,CAAC;GACf;EAED,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AAC5B,CAAC,CAAC","sourcesContent":["import { Plugin, PluginKey, Transaction, StateField } from 'prosemirror-state';\nimport { EditorView } from 'prosemirror-view';\nimport { createFileInfo } from '../../../../../util/files';\nimport { FileInfo } from '../../../../../global/shared-types/file.types';\nimport {\n ImageInserter,\n ImageInfo,\n ImageState,\n} from '../../../text-editor.types';\nimport { Node, Slice, Fragment } from 'prosemirror-model';\nimport { imageCache } from './node';\n\nexport const pluginKey = new PluginKey('imageInserterPlugin');\n\ntype ImagePastedCallback = (data: ImageInserter) => CustomEvent<ImageInserter>;\n\ntype ImageRemovedCallback = (data: ImageInfo) => CustomEvent<ImageInfo>;\n\ntype PluginState = {\n insertedImages: Record<string, Node>;\n};\n\nexport const createImageInserterPlugin = (\n imagePastedCallback: ImagePastedCallback,\n imageRemovedCallback: ImageRemovedCallback,\n) => {\n return new Plugin({\n key: pluginKey,\n props: {\n handlePaste: (view, event, slice) => {\n return processPasteEvent(view, event, slice);\n },\n handleDOMEvents: {\n imagePasted: (_, event) => {\n imagePastedCallback(event.detail);\n },\n },\n },\n state: {\n init: (): PluginState => {\n return { insertedImages: {} };\n },\n apply: (tr, pluginState): PluginState => {\n const newState = { ...pluginState };\n\n newState.insertedImages = getImagesFromTransaction(tr);\n findAndHandleRemovedImages(\n imageRemovedCallback,\n pluginState.insertedImages,\n newState.insertedImages,\n );\n\n return newState;\n },\n } as StateField<PluginState>,\n });\n};\n\nconst getImagesFromTransaction = (tr: Transaction): Record<string, Node> => {\n const images: Record<string, Node> = {};\n tr.doc.descendants((node) => {\n if (node.type.name === 'image') {\n images[node.attrs.fileInfoId] = node;\n }\n });\n\n return images;\n};\n\nconst findAndHandleRemovedImages = (\n imageRemovedCallback: ImageRemovedCallback,\n previousImages: Record<string, Node>,\n newImages: Record<string, Node>,\n) => {\n const removedKeys = Object.keys(previousImages).filter(\n (key) => !(key in newImages),\n );\n\n for (const removedKey of removedKeys) {\n const removedImage = previousImages[removedKey];\n const imageInfo: ImageInfo = {\n fileInfoId: removedImage.attrs.fileInfoId,\n src: removedImage.attrs.src,\n state: removedImage.attrs.state,\n };\n imageRemovedCallback(imageInfo);\n\n imageCache.delete(removedImage.attrs.fileInfoId);\n }\n};\n\nexport const imageInserterFactory = (\n view: EditorView,\n base64Data: string,\n fileInfo: FileInfo,\n): ImageInserter => {\n return {\n fileInfo: fileInfo,\n insertThumbnail: createThumbnailInserter(view, base64Data, fileInfo),\n insertImage: createImageInserter(view, fileInfo),\n insertFailedThumbnail: createFailedThumbnailInserter(view, fileInfo),\n };\n};\n\nconst createThumbnailInserter =\n (view: EditorView, base64Data: string, fileInfo: FileInfo) => () => {\n const { state, dispatch } = view;\n const { schema } = state;\n\n const placeholderNode = schema.nodes.image.create({\n src: base64Data,\n alt: fileInfo.filename,\n fileInfoId: fileInfo.id,\n state: ImageState.LOADING,\n });\n\n const transaction = state.tr.replaceSelectionWith(placeholderNode);\n\n dispatch(transaction);\n };\n\nconst createImageInserter =\n (view: EditorView, fileInfo: FileInfo) => (src?: string) => {\n const { state, dispatch } = view;\n const { schema } = state;\n\n const tr = state.tr;\n state.doc.descendants((node, pos) => {\n if (node.attrs.fileInfoId === fileInfo.id) {\n const imageNode = schema.nodes.image.create({\n src: src ? src : node.attrs.src,\n alt: fileInfo.filename,\n fileInfoId: fileInfo.id,\n state: ImageState.SUCCESS,\n });\n\n tr.replaceWith(pos, pos + node.nodeSize, imageNode);\n\n return false;\n }\n });\n\n dispatch(tr);\n };\n\nconst createFailedThumbnailInserter =\n (view: EditorView, fileInfo: FileInfo) => () => {\n const { state, dispatch } = view;\n const { schema } = state;\n\n const tr = state.tr;\n state.doc.descendants((node, pos) => {\n if (node.attrs.fileInfoId === fileInfo.id) {\n const errorPlaceholderNode = schema.nodes.image.create({\n src: node.attrs.src,\n alt: fileInfo.filename,\n fileInfoId: fileInfo.id,\n state: ImageState.FAILED,\n });\n\n tr.replaceWith(pos, pos + node.nodeSize, errorPlaceholderNode);\n\n return false;\n }\n });\n\n dispatch(tr);\n };\n\n/**\n * Check if a given ProseMirror node or fragment contains any image nodes.\n * @param node - The ProseMirror node or fragment to check.\n * @returns A boolean indicating whether the node contains any image nodes.\n */\nconst isImageNode = (node: Node | Fragment): boolean => {\n if (node instanceof Node) {\n if (node.type.name === 'image') {\n return true;\n }\n\n let found = false;\n node.content.forEach((child) => {\n if (isImageNode(child)) {\n found = true;\n }\n });\n\n return found;\n } else if (node instanceof Fragment) {\n let found = false;\n node.forEach((child) => {\n if (isImageNode(child)) {\n found = true;\n }\n });\n\n return found;\n }\n\n return false;\n};\n\n/**\n * Filter out image nodes from a ProseMirror fragment.\n * @param fragment - The ProseMirror fragment to filter.\n * @returns A new fragment with image nodes removed.\n */\nconst filterImageNodes = (fragment: Fragment): Fragment => {\n const filteredChildren: Node[] = [];\n\n fragment.forEach((child) => {\n if (!isImageNode(child)) {\n if (child.content.size > 0) {\n const filteredContent = filterImageNodes(child.content);\n const newNode = child.copy(filteredContent);\n filteredChildren.push(newNode);\n } else {\n filteredChildren.push(child);\n }\n }\n });\n\n return Fragment.fromArray(filteredChildren);\n};\n\n/**\n * Process a paste event and trigger an imagePasted event if an image file is pasted.\n * If an HTML image element is pasted, this image is filtered out from the slice content.\n *\n * @param view - The ProseMirror editor view.\n * @param event - The paste event.\n * @returns A boolean; True if an image file was pasted to prevent default paste behavior, otherwise false.\n */\nconst processPasteEvent = (\n view: EditorView,\n event: ClipboardEvent,\n slice: Slice,\n): boolean => {\n const clipboardData = event.clipboardData;\n if (!clipboardData) {\n return false;\n }\n\n const files = Array.from(clipboardData.files || []);\n for (const file of files) {\n if (file.type.startsWith('image/')) {\n const reader = new FileReader();\n reader.onloadend = () => {\n view.dom.dispatchEvent(\n new CustomEvent('imagePasted', {\n detail: imageInserterFactory(\n view,\n reader.result as string,\n createFileInfo(file),\n ),\n }),\n );\n };\n\n reader.readAsDataURL(file);\n }\n }\n\n const filteredSlice = new Slice(\n filterImageNodes(slice.content),\n slice.openStart,\n slice.openEnd,\n );\n\n if (filteredSlice.content.childCount < slice.content.childCount) {\n const { state, dispatch } = view;\n const tr = state.tr.replaceSelection(filteredSlice);\n dispatch(tr);\n\n return true;\n }\n\n return files.length > 0;\n};\n"]}
1
+ {"version":3,"file":"inserter.js","sourceRoot":"","sources":["../../../../../../src/components/text-editor/prosemirror-adapter/plugins/image/inserter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEtD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAG3D,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,mB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K,MAAM,IAAI,IAAI,KAAK,EAAE;IACtB,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;MAChC,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;MAChC,MAAM,CAAC,SAAS,GAAG,GAAG,EAAE;QACpB,IAAI,CAAC,GAAG,CAAC,aAAa,CAClB,IAAI,WAAW,CAAC,aAAa,EAAE;UAC3B,MAAM,EAAE,oBAAoB,CACxB,IAAI,EACJ,MAAM,CAAC,MAAgB,EACvB,cAAc,CAAC,IAAI,CAAC,CACvB;SACJ,CAAC,CACL,CAAC;MACN,CAAC,CAAC;MAEF,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;KAC9B;GACJ;EAED,MAAM,aAAa,GAAG,IAAI,KAAK,CAC3B,gBAAgB,CAAC,KAAK,CAAC,OAAO,CAAC,EAC/B,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,OAAO,CAChB,CAAC;EAEF,IAAI,aAAa,CAAC,OAAO,CAAC,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE;IAC7D,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;IACjC,MAAM,EAAE,GAAG,KAAK,CAAC,EAAE,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;IACpD,QAAQ,CAAC,EAAE,CAAC,CAAC;IAEb,OAAO,IAAI,CAAC;GACf;EAED,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AAC5B,CAAC,CAAC","sourcesContent":["import { Plugin, PluginKey } from 'prosemirror-state';\nimport { EditorView } from 'prosemirror-view';\nimport { createFileInfo } from '../../../../../util/files';\nimport { FileInfo } from '../../../../../global/shared-types/file.types';\nimport { ImageInserter, EditorImageState } from '../../../text-editor.types';\nimport { Node, Slice, Fragment } from 'prosemirror-model';\nimport { ImageNodeAttrs } from './node';\n\nexport const pluginKey = new PluginKey('imageInserterPlugin');\n\ntype ImagePastedCallback = (data: ImageInserter) => CustomEvent<ImageInserter>;\n\nexport const createImageInserterPlugin = (\n imagePastedCallback: ImagePastedCallback,\n) => {\n return new Plugin({\n key: pluginKey,\n props: {\n handlePaste: (view, event, slice) => {\n return processPasteEvent(view, event, slice);\n },\n handleDOMEvents: {\n imagePasted: (_, event) => {\n imagePastedCallback(event.detail);\n },\n },\n },\n });\n};\n\nexport const imageInserterFactory = (\n view: EditorView,\n base64Data: string,\n fileInfo: FileInfo,\n): ImageInserter => {\n return {\n fileInfo: fileInfo,\n insertThumbnail: createThumbnailInserter(view, base64Data, fileInfo),\n insertImage: createImageInserter(view, fileInfo),\n insertFailedThumbnail: createFailedThumbnailInserter(view, fileInfo),\n };\n};\n\nconst createThumbnailInserter =\n (view: EditorView, base64Data: string, fileInfo: FileInfo) => () => {\n const { state, dispatch } = view;\n const { schema } = state;\n\n const imageNodeAttrs = createImageNodeAttrs(\n base64Data,\n fileInfo,\n 'loading',\n );\n const placeholderNode = schema.nodes.image.create(imageNodeAttrs);\n\n const transaction = state.tr.replaceSelectionWith(placeholderNode);\n\n dispatch(transaction);\n };\n\nconst createImageInserter =\n (view: EditorView, fileInfo: FileInfo) => (src?: string) => {\n const { state, dispatch } = view;\n const { schema } = state;\n\n const tr = state.tr;\n state.doc.descendants((node, pos) => {\n if (node.attrs.fileInfoId === fileInfo.id) {\n const imageNodeAttrs = createImageNodeAttrs(\n src ? src : node.attrs.src,\n fileInfo,\n 'success',\n );\n const imageNode = schema.nodes.image.create(imageNodeAttrs);\n\n tr.replaceWith(pos, pos + node.nodeSize, imageNode);\n\n return false;\n }\n });\n\n dispatch(tr);\n };\n\nconst createFailedThumbnailInserter =\n (view: EditorView, fileInfo: FileInfo) => () => {\n const { state, dispatch } = view;\n const { schema } = state;\n\n const tr = state.tr;\n state.doc.descendants((node, pos) => {\n if (node.attrs.fileInfoId === fileInfo.id) {\n const imageNodeAttrs = createImageNodeAttrs(\n node.attrs.src,\n fileInfo,\n 'failed',\n );\n const errorPlaceholderNode =\n schema.nodes.image.create(imageNodeAttrs);\n\n tr.replaceWith(pos, pos + node.nodeSize, errorPlaceholderNode);\n\n return false;\n }\n });\n\n dispatch(tr);\n };\n\nfunction createImageNodeAttrs(\n src: string,\n fileInfo: FileInfo,\n state: EditorImageState,\n): ImageNodeAttrs {\n return {\n src: src,\n alt: fileInfo.filename,\n fileInfoId: fileInfo.id,\n state: state,\n };\n}\n\n/**\n * Check if a given ProseMirror node or fragment contains any image nodes.\n * @param node - The ProseMirror node or fragment to check.\n * @returns A boolean indicating whether the node contains any image nodes.\n */\nconst isImageNode = (node: Node | Fragment): boolean => {\n if (node instanceof Node) {\n if (node.type.name === 'image') {\n return true;\n }\n\n let found = false;\n node.content.forEach((child) => {\n if (isImageNode(child)) {\n found = true;\n }\n });\n\n return found;\n } else if (node instanceof Fragment) {\n let found = false;\n node.forEach((child) => {\n if (isImageNode(child)) {\n found = true;\n }\n });\n\n return found;\n }\n\n return false;\n};\n\n/**\n * Filter out image nodes from a ProseMirror fragment.\n * @param fragment - The ProseMirror fragment to filter.\n * @returns A new fragment with image nodes removed.\n */\nconst filterImageNodes = (fragment: Fragment): Fragment => {\n const filteredChildren: Node[] = [];\n\n fragment.forEach((child) => {\n if (!isImageNode(child)) {\n if (child.content.size > 0) {\n const filteredContent = filterImageNodes(child.content);\n const newNode = child.copy(filteredContent);\n filteredChildren.push(newNode);\n } else {\n filteredChildren.push(child);\n }\n }\n });\n\n return Fragment.fromArray(filteredChildren);\n};\n\n/**\n * Process a paste event and trigger an imagePasted event if an image file is pasted.\n * If an HTML image element is pasted, this image is filtered out from the slice content.\n *\n * @param view - The ProseMirror editor view.\n * @param event - The paste event.\n * @returns A boolean; True if an image file was pasted to prevent default paste behavior, otherwise false.\n */\nconst processPasteEvent = (\n view: EditorView,\n event: ClipboardEvent,\n slice: Slice,\n): boolean => {\n const clipboardData = event.clipboardData;\n if (!clipboardData) {\n return false;\n }\n\n const files = Array.from(clipboardData.files || []);\n for (const file of files) {\n if (file.type.startsWith('image/')) {\n const reader = new FileReader();\n reader.onloadend = () => {\n view.dom.dispatchEvent(\n new CustomEvent('imagePasted', {\n detail: imageInserterFactory(\n view,\n reader.result as string,\n createFileInfo(file),\n ),\n }),\n );\n };\n\n reader.readAsDataURL(file);\n }\n }\n\n const filteredSlice = new Slice(\n filterImageNodes(slice.content),\n slice.openStart,\n slice.openEnd,\n );\n\n if (filteredSlice.content.childCount < slice.content.childCount) {\n const { state, dispatch } = view;\n const tr = state.tr.replaceSelection(filteredSlice);\n dispatch(tr);\n\n return true;\n }\n\n return files.length > 0;\n};\n"]}
@@ -1,4 +1,3 @@
1
- import { ImageState } from '../../../text-editor.types';
2
1
  import translate from '../../../../../global/translations';
3
2
  export const imageCache = new Map();
4
3
  export function getImageNode(language) {
@@ -24,39 +23,38 @@ export function hasImageNode(node) {
24
23
  return false;
25
24
  }
26
25
  function createImageNodeMarkdownSerializer(language) {
27
- return (state, node) => {
28
- if (node.attrs.state === ImageState.FAILED) {
29
- const text = translate.get('editor-image-view.failed', language, {
30
- filename: node.attrs.alt || 'file',
31
- });
32
- state.write(`<span>${text}</span>`);
26
+ return (markdownSerializerState, node) => {
27
+ const { state, alt, src, width, maxWidth } = node.attrs;
28
+ if (!isEditorImageState(state)) {
33
29
  return;
34
30
  }
35
- else if (node.attrs.state === ImageState.LOADING) {
36
- const text = translate.get('editor-image-view.loading', language, {
37
- filename: node.attrs.alt || 'file',
38
- });
39
- state.write(`<span>${text}</span>`);
31
+ if (state === 'success') {
32
+ const imageHTML = getImageHTML(src, alt, width, maxWidth);
33
+ markdownSerializerState.write(imageHTML);
40
34
  return;
41
35
  }
42
- let imageHTML = `<img src="${node.attrs.src}"`;
43
- if (node.attrs.alt) {
44
- imageHTML += ` alt="${node.attrs.alt}"`;
45
- }
46
- const style = [];
47
- if (node.attrs.width) {
48
- style.push(`width: ${node.attrs.width};`);
49
- }
50
- if (node.attrs.maxWidth) {
51
- style.push(`max-width: ${node.attrs.maxWidth};`);
52
- }
53
- if (style.length > 0) {
54
- imageHTML += ` style="${style.join(' ')}"`;
55
- }
56
- imageHTML += ' />';
57
- state.write(imageHTML);
36
+ const statusHTML = getStatusHTML(state, alt, language);
37
+ markdownSerializerState.write(statusHTML);
58
38
  };
59
39
  }
40
+ function getStatusHTML(state, alt, language) {
41
+ const key = state === 'failed' ? 'failed' : 'loading';
42
+ const text = translate.get(`editor-image-view.${key}`, language, {
43
+ filename: alt || 'file',
44
+ });
45
+ return `<span>${text}</span>`;
46
+ }
47
+ function getImageHTML(src, alt, width, maxWidth) {
48
+ const style = [];
49
+ if (width) {
50
+ style.push(`width: ${width};`);
51
+ }
52
+ if (maxWidth) {
53
+ style.push(`max-width: ${maxWidth};`);
54
+ }
55
+ const styleAttribute = style.length > 0 ? ` style="${style.join(' ')}"` : '';
56
+ return `<img src="${src}" alt="${alt}"${styleAttribute} />`;
57
+ }
60
58
  function createImageNodeSpec(language) {
61
59
  return {
62
60
  group: 'inline',
@@ -67,24 +65,16 @@ function createImageNodeSpec(language) {
67
65
  fileInfoId: { default: '' },
68
66
  width: { default: '' },
69
67
  maxWidth: { default: '100%' },
70
- state: { default: '' },
68
+ state: { default: 'success' },
71
69
  },
72
70
  toDOM: (node) => {
73
- if (node.attrs.state === ImageState.FAILED) {
74
- return createStatusSpan('failed', node, language);
75
- }
76
- else if (node.attrs.state === ImageState.LOADING) {
77
- return createStatusSpan('loading', node, language);
78
- }
79
- let img = imageCache.get(node.attrs.fileInfoId);
80
- if (img) {
81
- updateImageElement(img, node);
71
+ if (!isEditorImageState(node.attrs.state)) {
72
+ return;
82
73
  }
83
- else {
84
- img = createImageElement(node);
85
- imageCache.set(node.attrs.fileInfoId, img);
74
+ if (node.attrs.state === 'success') {
75
+ return getOrCreateImageElement(node.attrs.fileInfoId, node);
86
76
  }
87
- return img;
77
+ return createStatusSpanForState(node.attrs.state, node, language);
88
78
  },
89
79
  parseDOM: [
90
80
  {
@@ -95,7 +85,7 @@ function createImageNodeSpec(language) {
95
85
  alt: dom.getAttribute('alt') || 'file',
96
86
  width: dom.style.width || '',
97
87
  maxWidth: '100%',
98
- state: ImageState.SUCCESS,
88
+ state: 'success',
99
89
  fileInfoId: crypto.randomUUID(),
100
90
  };
101
91
  },
@@ -103,6 +93,24 @@ function createImageNodeSpec(language) {
103
93
  ],
104
94
  };
105
95
  }
96
+ function isEditorImageState(state) {
97
+ return state === 'loading' || state === 'failed' || state === 'success';
98
+ }
99
+ function getOrCreateImageElement(fileInfoId, node) {
100
+ let img = imageCache.get(fileInfoId);
101
+ if (img) {
102
+ updateImageElement(img, node);
103
+ }
104
+ else {
105
+ img = createImageElement(node);
106
+ imageCache.set(fileInfoId, img);
107
+ }
108
+ return img;
109
+ }
110
+ function createStatusSpanForState(state, node, language) {
111
+ const statusKey = state === 'failed' ? 'failed' : 'loading';
112
+ return createStatusSpan(statusKey, node, language);
113
+ }
106
114
  function createStatusSpan(key, node, language) {
107
115
  const text = translate.get(`editor-image-view.${key}`, language, {
108
116
  filename: node.attrs.alt || 'file',
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","sourceRoot":"","sources":["../../../../../../src/components/text-editor/prosemirror-adapter/plugins/image/node.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AAGxD,OAAO,SAAS,MAAM,oCAAoC,CAAC;AAE3D,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,GAAG,EAA4B,CAAC;AAO9D,MAAM,UAAU,YAAY,CAAC,QAAmB;EAC5C,OAAO,EAAE,KAAK,EAAE,mBAAmB,CAAC,QAAQ,CAAC,EAAE,CAAC;AACpD,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC1C,QAAmB;EAEnB,OAAO,EAAE,KAAK,EAAE,iCAAiC,CAAC,QAAQ,CAAC,EAAE,CAAC;AAClE,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,IAAU;EACnC,IAAI,IAAI,CAAC,IAAI,CAA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AAS,kBAAkB,CACvB,GAAqB,EACrB,IAAU;EAEV,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;EACzB,GAAG,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;EACzC,GAAG,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;EAEnC,OAAO,GAAG,CAAC;AACf,CAAC;AAED,SAAS,kBAAkB,CAAC,IAAU;EAClC,MAAM,GAAG,GAAG,QAAQ,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;EAC1C,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;EACzB,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;EACzB,GAAG,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;EACzC,GAAG,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;EAEnC,OAAO,GAAG,CAAC;AACf,CAAC","sourcesContent":["import { NodeSpec, Node, Attrs, DOMOutputSpec } from 'prosemirror-model';\nimport { ImageState } from '../../../text-editor.types';\nimport { MarkdownSerializerState } from 'prosemirror-markdown';\nimport { Languages } from '../../../../date-picker/date.types';\nimport translate from '../../../../../global/translations';\n\nexport const imageCache = new Map<string, HTMLImageElement>();\n\ntype MarkdownSerializerFunction = (\n state: MarkdownSerializerState,\n node: Node,\n) => void;\n\nexport function getImageNode(language: Languages): Record<string, NodeSpec> {\n return { image: createImageNodeSpec(language) };\n}\n\nexport function getImageNodeMarkdownSerializer(\n language: Languages,\n): Record<string, MarkdownSerializerFunction> {\n return { image: createImageNodeMarkdownSerializer(language) };\n}\n\n/**\n * Recursively checks if a ProseMirror node or\n * any of its child nodes is an image node.\n */\nexport function hasImageNode(node: Node): boolean {\n if (node.type.name === 'image') {\n return true;\n }\n\n for (let i = 0; i < node.childCount; i++) {\n const childNode = node.child(i);\n if (hasImageNode(childNode)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction createImageNodeMarkdownSerializer(\n language: Languages,\n): MarkdownSerializerFunction {\n return (state: MarkdownSerializerState, node: Node) => {\n if (node.attrs.state === ImageState.FAILED) {\n const text = translate.get('editor-image-view.failed', language, {\n filename: node.attrs.alt || 'file',\n });\n state.write(`<span>${text}</span>`);\n\n return;\n } else if (node.attrs.state === ImageState.LOADING) {\n const text = translate.get('editor-image-view.loading', language, {\n filename: node.attrs.alt || 'file',\n });\n state.write(`<span>${text}</span>`);\n\n return;\n }\n\n let imageHTML = `<img src=\"${node.attrs.src}\"`;\n\n if (node.attrs.alt) {\n imageHTML += ` alt=\"${node.attrs.alt}\"`;\n }\n\n const style = [];\n\n if (node.attrs.width) {\n style.push(`width: ${node.attrs.width};`);\n }\n\n if (node.attrs.maxWidth) {\n style.push(`max-width: ${node.attrs.maxWidth};`);\n }\n\n if (style.length > 0) {\n imageHTML += ` style=\"${style.join(' ')}\"`;\n }\n\n imageHTML += ' />';\n\n state.write(imageHTML);\n };\n}\n\nfunction createImageNodeSpec(language: Languages): NodeSpec {\n return {\n group: 'inline',\n inline: true,\n attrs: {\n src: { default: '' },\n alt: { default: '' },\n fileInfoId: { default: '' },\n width: { default: '' },\n maxWidth: { default: '100%' },\n state: { default: '' },\n },\n toDOM: (node): DOMOutputSpec => {\n if (node.attrs.state === ImageState.FAILED) {\n return createStatusSpan('failed', node, language);\n } else if (node.attrs.state === ImageState.LOADING) {\n return createStatusSpan('loading', node, language);\n }\n\n let img = imageCache.get(node.attrs.fileInfoId);\n if (img) {\n updateImageElement(img, node);\n } else {\n img = createImageElement(node);\n imageCache.set(node.attrs.fileInfoId, img);\n }\n\n return img;\n },\n parseDOM: [\n {\n tag: 'img',\n getAttrs: (dom: HTMLElement): Attrs => {\n return {\n src: dom.getAttribute('src') || '',\n alt: dom.getAttribute('alt') || 'file',\n width: dom.style.width || '',\n maxWidth: '100%',\n state: ImageState.SUCCESS,\n fileInfoId: crypto.randomUUID(),\n };\n },\n },\n ],\n };\n}\n\nfunction createStatusSpan(\n key: string,\n node: Node,\n language: Languages,\n): HTMLSpanElement {\n const text = translate.get(`editor-image-view.${key}`, language, {\n filename: node.attrs.alt || 'file',\n });\n const span = document.createElement('span');\n span.textContent = text;\n\n return span;\n}\n\nfunction updateImageElement(\n img: HTMLImageElement,\n node: Node,\n): HTMLImageElement {\n img.alt = node.attrs.alt;\n img.style.maxWidth = node.attrs.maxWidth;\n img.style.width = node.attrs.width;\n\n return img;\n}\n\nfunction createImageElement(node: Node): HTMLImageElement {\n const img = document.createElement('img');\n img.src = node.attrs.src;\n img.alt = node.attrs.alt;\n img.style.maxWidth = node.attrs.maxWidth;\n img.style.width = node.attrs.width;\n\n return img;\n}\n"]}
1
+ {"version":3,"file":"node.js","sourceRoot":"","sources":["../../../../../../src/components/text-editor/prosemirror-adapter/plugins/image/node.ts"],"names":[],"mappings":"AAIA,OAAO,SAAS,MAAM,oCAAoC,CAAC;AAE3D,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,GAAG,EAA4B,CAAC;AAO9D,MAAM,UAAU,YAAY,CAAC,QAAmB;EAC5C,OAAO,EAAE,KAAK,EAAE,mBAAmB,CAAC,QAAQ,CAAC,EAAE,CAAC;AACpD,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC1C,QAAmB;EAEnB,OAAO,EAAE,KAAK,EAAE,iCAAiC,CAAC,QAAQ,CAAC,EAAE,CAAC;AAClE,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,IAAU;EACnC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE;IAC5B,OAAO,IAAI,CAAC;GACf;EAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC,EAAE,EAAE;IACtC,M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AAC,qBAAqB,GAAG,EAAE,EAAE,QAAQ,EAAE;IAC7D,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,MAAM;GACrC,CAAC,CAAC;EACH,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;EAC5C,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;EAExB,OAAO,IAAI,CAAC;AAChB,CAAC;AAED,SAAS,kBAAkB,CACvB,GAAqB,EACrB,IAAU;EAEV,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;EACzB,GAAG,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;EACzC,GAAG,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;EAEnC,OAAO,GAAG,CAAC;AACf,CAAC;AAED,SAAS,kBAAkB,CAAC,IAAU;EAClC,MAAM,GAAG,GAAG,QAAQ,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;EAC1C,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;EACzB,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;EACzB,GAAG,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;EACzC,GAAG,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;EAEnC,OAAO,GAAG,CAAC;AACf,CAAC","sourcesContent":["import { NodeSpec, Node, DOMOutputSpec } from 'prosemirror-model';\nimport { EditorImageState } from '../../../text-editor.types';\nimport { MarkdownSerializerState } from 'prosemirror-markdown';\nimport { Languages } from '../../../../date-picker/date.types';\nimport translate from '../../../../../global/translations';\n\nexport const imageCache = new Map<string, HTMLImageElement>();\n\ntype MarkdownSerializerFunction = (\n state: MarkdownSerializerState,\n node: Node,\n) => void;\n\nexport function getImageNode(language: Languages): Record<string, NodeSpec> {\n return { image: createImageNodeSpec(language) };\n}\n\nexport function getImageNodeMarkdownSerializer(\n language: Languages,\n): Record<string, MarkdownSerializerFunction> {\n return { image: createImageNodeMarkdownSerializer(language) };\n}\n\n/**\n * Recursively checks if a ProseMirror node or\n * any of its child nodes is an image node.\n */\nexport function hasImageNode(node: Node): boolean {\n if (node.type.name === 'image') {\n return true;\n }\n\n for (let i = 0; i < node.childCount; i++) {\n const childNode = node.child(i);\n if (hasImageNode(childNode)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction createImageNodeMarkdownSerializer(\n language: Languages,\n): MarkdownSerializerFunction {\n return (markdownSerializerState: MarkdownSerializerState, node: Node) => {\n const { state, alt, src, width, maxWidth } = node.attrs;\n\n if (!isEditorImageState(state)) {\n return;\n }\n\n if (state === 'success') {\n const imageHTML = getImageHTML(src, alt, width, maxWidth);\n markdownSerializerState.write(imageHTML);\n\n return;\n }\n\n const statusHTML = getStatusHTML(state, alt, language);\n markdownSerializerState.write(statusHTML);\n };\n}\n\nfunction getStatusHTML(\n state: EditorImageState,\n alt: string,\n language: Languages,\n): string {\n const key = state === 'failed' ? 'failed' : 'loading';\n const text = translate.get(`editor-image-view.${key}`, language, {\n filename: alt || 'file',\n });\n\n return `<span>${text}</span>`;\n}\n\nfunction getImageHTML(\n src: string,\n alt: string,\n width: string,\n maxWidth: string,\n): string {\n const style = [];\n\n if (width) {\n style.push(`width: ${width};`);\n }\n\n if (maxWidth) {\n style.push(`max-width: ${maxWidth};`);\n }\n\n const styleAttribute =\n style.length > 0 ? ` style=\"${style.join(' ')}\"` : '';\n\n return `<img src=\"${src}\" alt=\"${alt}\"${styleAttribute} />`;\n}\n\nexport interface ImageNodeAttrs {\n src: string;\n alt: string;\n state: EditorImageState;\n fileInfoId: string | number;\n width?: string;\n maxWidth?: string;\n}\n\nfunction createImageNodeSpec(language: Languages): NodeSpec {\n return {\n group: 'inline',\n inline: true,\n attrs: {\n src: { default: '' },\n alt: { default: '' },\n fileInfoId: { default: '' },\n width: { default: '' },\n maxWidth: { default: '100%' },\n state: { default: 'success' },\n },\n toDOM: (node): DOMOutputSpec => {\n if (!isEditorImageState(node.attrs.state)) {\n return;\n }\n\n if (node.attrs.state === 'success') {\n return getOrCreateImageElement(node.attrs.fileInfoId, node);\n }\n\n return createStatusSpanForState(node.attrs.state, node, language);\n },\n parseDOM: [\n {\n tag: 'img',\n getAttrs: (dom: HTMLElement): ImageNodeAttrs => {\n return {\n src: dom.getAttribute('src') || '',\n alt: dom.getAttribute('alt') || 'file',\n width: dom.style.width || '',\n maxWidth: '100%',\n state: 'success',\n fileInfoId: crypto.randomUUID(),\n };\n },\n },\n ],\n };\n}\n\nfunction isEditorImageState(state: unknown): state is EditorImageState {\n return state === 'loading' || state === 'failed' || state === 'success';\n}\n\nfunction getOrCreateImageElement(\n fileInfoId: string,\n node: Node,\n): HTMLImageElement {\n let img = imageCache.get(fileInfoId);\n\n if (img) {\n updateImageElement(img, node);\n } else {\n img = createImageElement(node);\n imageCache.set(fileInfoId, img);\n }\n\n return img;\n}\n\nfunction createStatusSpanForState(\n state: EditorImageState,\n node: Node,\n language: Languages,\n): HTMLSpanElement {\n const statusKey = state === 'failed' ? 'failed' : 'loading';\n\n return createStatusSpan(statusKey, node, language);\n}\n\nfunction createStatusSpan(\n key: string,\n node: Node,\n language: Languages,\n): HTMLSpanElement {\n const text = translate.get(`editor-image-view.${key}`, language, {\n filename: node.attrs.alt || 'file',\n });\n const span = document.createElement('span');\n span.textContent = text;\n\n return span;\n}\n\nfunction updateImageElement(\n img: HTMLImageElement,\n node: Node,\n): HTMLImageElement {\n img.alt = node.attrs.alt;\n img.style.maxWidth = node.attrs.maxWidth;\n img.style.width = node.attrs.width;\n\n return img;\n}\n\nfunction createImageElement(node: Node): HTMLImageElement {\n const img = document.createElement('img');\n img.src = node.attrs.src;\n img.alt = node.attrs.alt;\n img.style.maxWidth = node.attrs.maxWidth;\n img.style.width = node.attrs.width;\n\n return img;\n}\n"]}
@@ -1,5 +1,4 @@
1
1
  import { Plugin } from 'prosemirror-state';
2
- import { ImageState } from '../../../text-editor.types';
3
2
  import translate from '../../../../../global/translations';
4
3
  const MIN_WIDTH = 10;
5
4
  export const createImageViewPlugin = (language) => {
@@ -92,21 +91,20 @@ class ImageView {
92
91
  });
93
92
  };
94
93
  this.transitionBetweenStates = () => {
94
+ var _a;
95
95
  this.cleanUpPreviousState();
96
96
  this.dom.className = `image-wrapper state-${this.node.attrs.state}`;
97
- if (this.node.attrs.state === ImageState.LOADING) {
98
- this.createLoadingState();
99
- }
100
- else if (this.node.attrs.state === ImageState.SUCCESS) {
101
- this.createSuccessState();
102
- }
103
- else if (this.node.attrs.state === ImageState.FAILED) {
104
- this.createFailedState();
105
- }
97
+ const stateHandlers = {
98
+ loading: this.createLoadingState,
99
+ success: this.createSuccessState,
100
+ failed: this.createFailedState,
101
+ };
102
+ const state = this.node.attrs.state;
103
+ (_a = stateHandlers[state]) === null || _a === void 0 ? void 0 : _a.call(stateHandlers);
106
104
  };
107
105
  this.transitioningBetweenSuccessStates = (newNode) => {
108
- return (this.node.attrs.state === ImageState.SUCCESS &&
109
- newNode.attrs.state === ImageState.SUCCESS);
106
+ return (this.node.attrs.state === 'success' &&
107
+ newNode.attrs.state === 'success');
110
108
  };
111
109
  this.node = node;
112
110
  this.view = view;
@@ -1 +1 @@
1
- {"version":3,"file":"view.js","sourceRoot":"","sources":["../../../../../../src/components/text-editor/prosemirror-adapter/plugins/image/view.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AACxD,OAAO,SAAS,MAAM,oCAAoC,CAAC;AAG3D,MAAM,SAAS,GAAG,EAAE,CAAC;AAErB,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,QAAmB,EAAE,EAAE;EACzD,O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AC,GAAG,GAAG,QAAQ,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IACzC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;IAC9B,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;IAC9B,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;IAC9C,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;IAExC,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAE/B,IAAI,CAAC,uBAAuB,EAAE,CAAC;EACnC,CAAC;EA4ID,qEAAqE;EACrE,gEAAgE;EACzD,MAAM,CAAC,IAAU;IACpB,IAAI,CAAC,IAAI,CAAC,iCAAiC,CAAC,IAAI,CAAC,EAAE;MAC/C,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;MAC9B,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;MAC9B,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;MAC9C,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;KAC3C;IAED,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACjB,IAAI,CAAC,uBAAuB,EAAE,CAAC;IAE/B,OAAO,IAAI,CAAC;EAChB,CAAC;CACJ","sourcesContent":["import { EditorView, NodeView } from 'prosemirror-view';\nimport { Node } from 'prosemirror-model';\nimport { Plugin } from 'prosemirror-state';\nimport { ImageState } from '../../../text-editor.types';\nimport translate from '../../../../../global/translations';\nimport { Languages } from '../../../../date-picker/date.types';\n\nconst MIN_WIDTH = 10;\n\nexport const createImageViewPlugin = (language: Languages) => {\n return new Plugin({\n props: {\n nodeViews: {\n image: (node, view, getPos) => {\n return new ImageView(node, view, getPos, language);\n },\n },\n },\n });\n};\n\nclass ImageView implements NodeView {\n node: Node;\n view: EditorView;\n getPos: () => number;\n dom: HTMLDivElement;\n img: HTMLImageElement;\n language: Languages;\n\n public constructor(\n node: Node,\n view: EditorView,\n getPos: () => number,\n language: Languages,\n ) {\n this.node = node;\n this.view = view;\n this.getPos = getPos;\n this.language = language;\n\n this.dom = document.createElement('div');\n this.dom.className = `image-wrapper state-${node.attrs.state}`;\n\n this.img = document.createElement('img');\n this.img.src = node.attrs.src;\n this.img.alt = node.attrs.alt;\n this.img.style.maxWidth = node.attrs.maxWidth;\n this.img.style.width = node.attrs.width;\n\n this.dom.appendChild(this.img);\n\n this.transitionBetweenStates();\n }\n\n private createResizeHandle = (position: 'bottom-right' | 'top-left') => {\n const handle = document.createElement('div');\n handle.className = `resize-handle ${position}`;\n handle.setAttribute('role', 'slider');\n handle.setAttribute(\n 'aria-label',\n translate.get('editor-image-view.resize-handle', this.language),\n );\n handle.setAttribute('tabindex', '0');\n handle.setAttribute('aria-valuemin', MIN_WIDTH.toString());\n handle.setAttribute('aria-valuenow', this.img.offsetWidth.toString());\n handle.setAttribute('aria-valuetext', `${this.img.offsetWidth} pixels`);\n handle.setAttribute('aria-grabbed', 'false');\n\n handle.addEventListener('pointerdown', (e: PointerEvent) => {\n handle.setAttribute('aria-grabbed', 'true');\n this.onResizeStart(e, position);\n });\n\n return handle;\n };\n\n private onResizeStart = (\n event: PointerEvent,\n position: 'bottom-right' | 'top-left',\n ) => {\n event.preventDefault();\n const handle = event.target as HTMLElement;\n\n const startX = event.clientX;\n const startWidth = this.img.offsetWidth;\n\n const onPointerMove = (e: PointerEvent) => {\n const delta = e.clientX - startX;\n const widthDelta = position === 'top-left' ? -delta : delta;\n const newWidth = Math.max(MIN_WIDTH, startWidth + widthDelta);\n\n this.img.style.width = `${newWidth}px`;\n\n const handles = this.dom.querySelectorAll('.resize-handle');\n handles.forEach((resizeHandle) => {\n resizeHandle.setAttribute('aria-valuenow', newWidth.toString());\n resizeHandle.setAttribute(\n 'aria-valuetext',\n `${newWidth} pixels`,\n );\n });\n };\n\n const onPointerUp = () => {\n window.removeEventListener('pointermove', onPointerMove);\n window.removeEventListener('pointerup', onPointerUp);\n handle.setAttribute('aria-grabbed', 'false');\n\n this.view.dispatch(\n this.view.state.tr.setNodeMarkup(this.getPos(), undefined, {\n ...this.node.attrs,\n width: this.img.style.width,\n height: this.node.attrs.height,\n }),\n );\n };\n\n window.addEventListener('pointermove', onPointerMove);\n window.addEventListener('pointerup', onPointerUp);\n };\n\n private createLoadingState = () => {\n this.dom.setAttribute('aria-live', 'polite');\n this.dom.setAttribute('aria-busy', 'true');\n this.dom.setAttribute(\n 'aria-label',\n translate.get('editor-image-view.loading', this.language, {\n filename: this.node.attrs.alt || 'file',\n }),\n );\n\n const spinnerElement = document.createElement('limel-linear-progress');\n spinnerElement.setAttribute('indeterminate', 'true');\n this.dom.appendChild(spinnerElement);\n };\n\n private createSuccessState = () => {\n this.dom.setAttribute('aria-live', 'polite');\n this.dom.setAttribute('aria-busy', 'false');\n this.dom.setAttribute(\n 'aria-label',\n translate.get('editor-image-view.success', this.language, {\n filename: this.node.attrs.alt || 'file',\n }),\n );\n\n const bottomRightHandle = this.createResizeHandle('bottom-right');\n const topLeftHandle = this.createResizeHandle('top-left');\n\n this.dom.appendChild(bottomRightHandle);\n this.dom.appendChild(topLeftHandle);\n };\n\n private createFailedState = () => {\n this.dom.setAttribute('aria-live', 'assertive');\n this.dom.setAttribute('aria-busy', 'false');\n this.dom.setAttribute(\n 'aria-label',\n translate.get('editor-image-view.failed', this.language, {\n filename: this.node.attrs.alt || 'file',\n }),\n );\n };\n\n private cleanUpPreviousState = () => {\n Array.from(this.dom.childNodes).forEach((child) => {\n if (!(child instanceof HTMLImageElement)) {\n child.remove();\n }\n });\n };\n\n private transitionBetweenStates = () => {\n this.cleanUpPreviousState();\n this.dom.className = `image-wrapper state-${this.node.attrs.state}`;\n\n if (this.node.attrs.state === ImageState.LOADING) {\n this.createLoadingState();\n } else if (this.node.attrs.state === ImageState.SUCCESS) {\n this.createSuccessState();\n } else if (this.node.attrs.state === ImageState.FAILED) {\n this.createFailedState();\n }\n };\n\n private transitioningBetweenSuccessStates = (newNode: Node): boolean => {\n return (\n this.node.attrs.state === ImageState.SUCCESS &&\n newNode.attrs.state === ImageState.SUCCESS\n );\n };\n\n // Ensure that the existing NodeView is reused rather than recreated.\n // Recreating the NodeView will cause flickering between states.\n public update(node: Node): boolean {\n if (!this.transitioningBetweenSuccessStates(node)) {\n this.img.src = node.attrs.src;\n this.img.alt = node.attrs.alt;\n this.img.style.maxWidth = node.attrs.maxWidth;\n this.img.style.width = node.attrs.width;\n }\n\n this.node = node;\n this.transitionBetweenStates();\n\n return true;\n }\n}\n"]}
1
+ {"version":3,"file":"view.js","sourceRoot":"","sources":["../../../../../../src/components/text-editor/prosemirror-adapter/plugins/image/view.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C,OAAO,SAAS,MAAM,oCAAoC,CAAC;AAG3D,MAAM,SAAS,GAAG,EAAE,CAAC;AAErB,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,QAAmB,EAAE,EAAE;EACzD,OAAO,IAAI,MAAM,CAAC;IACd,KAAK,EAAE;MACH,SAAS,EAAE;QACP,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE;UAC1B,OAAO,IAAI,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;QACvD,CAAC;OACJ;KACJ;GACJ,CAAC,CAAC;AACP,CAAC,CAAC;AAEF,MAAM,SAAS;EAQX,YACI,IAA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CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAE/B,IAAI,CAAC,uBAAuB,EAAE,CAAC;EACnC,CAAC;EA6ID,qEAAqE;EACrE,gEAAgE;EACzD,MAAM,CAAC,IAAU;IACpB,IAAI,CAAC,IAAI,CAAC,iCAAiC,CAAC,IAAI,CAAC,EAAE;MAC/C,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;MAC9B,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;MAC9B,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;MAC9C,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;KAC3C;IAED,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACjB,IAAI,CAAC,uBAAuB,EAAE,CAAC;IAE/B,OAAO,IAAI,CAAC;EAChB,CAAC;CACJ","sourcesContent":["import { EditorView, NodeView } from 'prosemirror-view';\nimport { Node } from 'prosemirror-model';\nimport { Plugin } from 'prosemirror-state';\nimport { EditorImageState } from '../../../text-editor.types';\nimport translate from '../../../../../global/translations';\nimport { Languages } from '../../../../date-picker/date.types';\n\nconst MIN_WIDTH = 10;\n\nexport const createImageViewPlugin = (language: Languages) => {\n return new Plugin({\n props: {\n nodeViews: {\n image: (node, view, getPos) => {\n return new ImageView(node, view, getPos, language);\n },\n },\n },\n });\n};\n\nclass ImageView implements NodeView {\n node: Node;\n view: EditorView;\n getPos: () => number;\n dom: HTMLDivElement;\n img: HTMLImageElement;\n language: Languages;\n\n public constructor(\n node: Node,\n view: EditorView,\n getPos: () => number,\n language: Languages,\n ) {\n this.node = node;\n this.view = view;\n this.getPos = getPos;\n this.language = language;\n\n this.dom = document.createElement('div');\n this.dom.className = `image-wrapper state-${node.attrs.state}`;\n\n this.img = document.createElement('img');\n this.img.src = node.attrs.src;\n this.img.alt = node.attrs.alt;\n this.img.style.maxWidth = node.attrs.maxWidth;\n this.img.style.width = node.attrs.width;\n\n this.dom.appendChild(this.img);\n\n this.transitionBetweenStates();\n }\n\n private createResizeHandle = (position: 'bottom-right' | 'top-left') => {\n const handle = document.createElement('div');\n handle.className = `resize-handle ${position}`;\n handle.setAttribute('role', 'slider');\n handle.setAttribute(\n 'aria-label',\n translate.get('editor-image-view.resize-handle', this.language),\n );\n handle.setAttribute('tabindex', '0');\n handle.setAttribute('aria-valuemin', MIN_WIDTH.toString());\n handle.setAttribute('aria-valuenow', this.img.offsetWidth.toString());\n handle.setAttribute('aria-valuetext', `${this.img.offsetWidth} pixels`);\n handle.setAttribute('aria-grabbed', 'false');\n\n handle.addEventListener('pointerdown', (e: PointerEvent) => {\n handle.setAttribute('aria-grabbed', 'true');\n this.onResizeStart(e, position);\n });\n\n return handle;\n };\n\n private onResizeStart = (\n event: PointerEvent,\n position: 'bottom-right' | 'top-left',\n ) => {\n event.preventDefault();\n const handle = event.target as HTMLElement;\n\n const startX = event.clientX;\n const startWidth = this.img.offsetWidth;\n\n const onPointerMove = (e: PointerEvent) => {\n const delta = e.clientX - startX;\n const widthDelta = position === 'top-left' ? -delta : delta;\n const newWidth = Math.max(MIN_WIDTH, startWidth + widthDelta);\n\n this.img.style.width = `${newWidth}px`;\n\n const handles = this.dom.querySelectorAll('.resize-handle');\n handles.forEach((resizeHandle) => {\n resizeHandle.setAttribute('aria-valuenow', newWidth.toString());\n resizeHandle.setAttribute(\n 'aria-valuetext',\n `${newWidth} pixels`,\n );\n });\n };\n\n const onPointerUp = () => {\n window.removeEventListener('pointermove', onPointerMove);\n window.removeEventListener('pointerup', onPointerUp);\n handle.setAttribute('aria-grabbed', 'false');\n\n this.view.dispatch(\n this.view.state.tr.setNodeMarkup(this.getPos(), undefined, {\n ...this.node.attrs,\n width: this.img.style.width,\n height: this.node.attrs.height,\n }),\n );\n };\n\n window.addEventListener('pointermove', onPointerMove);\n window.addEventListener('pointerup', onPointerUp);\n };\n\n private createLoadingState = () => {\n this.dom.setAttribute('aria-live', 'polite');\n this.dom.setAttribute('aria-busy', 'true');\n this.dom.setAttribute(\n 'aria-label',\n translate.get('editor-image-view.loading', this.language, {\n filename: this.node.attrs.alt || 'file',\n }),\n );\n\n const spinnerElement = document.createElement('limel-linear-progress');\n spinnerElement.setAttribute('indeterminate', 'true');\n this.dom.appendChild(spinnerElement);\n };\n\n private createSuccessState = () => {\n this.dom.setAttribute('aria-live', 'polite');\n this.dom.setAttribute('aria-busy', 'false');\n this.dom.setAttribute(\n 'aria-label',\n translate.get('editor-image-view.success', this.language, {\n filename: this.node.attrs.alt || 'file',\n }),\n );\n\n const bottomRightHandle = this.createResizeHandle('bottom-right');\n const topLeftHandle = this.createResizeHandle('top-left');\n\n this.dom.appendChild(bottomRightHandle);\n this.dom.appendChild(topLeftHandle);\n };\n\n private createFailedState = () => {\n this.dom.setAttribute('aria-live', 'assertive');\n this.dom.setAttribute('aria-busy', 'false');\n this.dom.setAttribute(\n 'aria-label',\n translate.get('editor-image-view.failed', this.language, {\n filename: this.node.attrs.alt || 'file',\n }),\n );\n };\n\n private cleanUpPreviousState = () => {\n Array.from(this.dom.childNodes).forEach((child) => {\n if (!(child instanceof HTMLImageElement)) {\n child.remove();\n }\n });\n };\n\n private transitionBetweenStates = () => {\n this.cleanUpPreviousState();\n this.dom.className = `image-wrapper state-${this.node.attrs.state}`;\n\n const stateHandlers: Record<EditorImageState, () => void> = {\n loading: this.createLoadingState,\n success: this.createSuccessState,\n failed: this.createFailedState,\n };\n\n const state: EditorImageState = this.node.attrs.state;\n stateHandlers[state]?.();\n };\n\n private transitioningBetweenSuccessStates = (newNode: Node): boolean => {\n return (\n this.node.attrs.state === 'success' &&\n newNode.attrs.state === 'success'\n );\n };\n\n // Ensure that the existing NodeView is reused rather than recreated.\n // Recreating the NodeView will cause flickering between states.\n public update(node: Node): boolean {\n if (!this.transitioningBetweenSuccessStates(node)) {\n this.img.src = node.attrs.src;\n this.img.alt = node.attrs.alt;\n this.img.style.maxWidth = node.attrs.maxWidth;\n this.img.style.width = node.attrs.width;\n }\n\n this.node = node;\n this.transitionBetweenStates();\n\n return true;\n }\n}\n"]}