Skip to content

Commit

Permalink
Merge pull request #3723 from udecode/fix/insertMedia
Browse files Browse the repository at this point in the history
Fix/insert media
  • Loading branch information
felixfeng33 authored Nov 5, 2024
2 parents 807412f + d0720cf commit dd99fdc
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/tame-socks-admire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@udecode/plate-media': patch
---

Add `at` in `insertMedia` api.
35 changes: 27 additions & 8 deletions packages/media/src/react/placeholder/transforms/insertMedia.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { PlateEditor } from '@udecode/plate-common/react';

import { insertNodes, nanoid, withoutNormalizing } from '@udecode/plate-common';
import { Path } from 'slate';

import { type TPlaceholderElement, BasePlaceholderPlugin } from '../../../lib';
import { PlaceholderPlugin } from '../PlaceholderPlugin';
Expand All @@ -9,7 +10,11 @@ import { createUploadError, isUploadError } from '../utils/createUploadError';
import { getMediaType } from '../utils/getMediaType';
import { validateFiles } from '../utils/validateFiles';

export const insertMedia = (editor: PlateEditor, files: FileList): any => {
export const insertMedia = (
editor: PlateEditor,
files: FileList,
at?: Path
): any => {
const api = editor.getApi(PlaceholderPlugin);
const uploadConfig = editor.getOption(PlaceholderPlugin, 'uploadConfig');
const multiple = editor.getOption(PlaceholderPlugin, 'multiple');
Expand Down Expand Up @@ -48,16 +53,30 @@ export const insertMedia = (editor: PlateEditor, files: FileList): any => {
);
}

Array.from(files).forEach((file) => {
let currentAt: Path | undefined;

Array.from(files).forEach((file, index) => {
if (index === 0) {
if (at) {
currentAt = at;
}
} else {
currentAt = currentAt ? Path.next(currentAt) : undefined;
}

const id = nanoid();

withoutNormalizing(editor, () =>
insertNodes<TPlaceholderElement>(editor, {
id,
children: [{ text: '' }],
mediaType: getMediaType(file, uploadConfig)!,
type: editor.getType(BasePlaceholderPlugin),
})
insertNodes<TPlaceholderElement>(
editor,
{
id,
children: [{ text: '' }],
mediaType: getMediaType(file, uploadConfig)!,
type: editor.getType(BasePlaceholderPlugin),
},
{ at: currentAt, nextBlock: false }
)
);

api.placeholder.addUploadingFile(id, file);
Expand Down

0 comments on commit dd99fdc

Please sign in to comment.