Skip to content

Commit 577da8f

Browse files
authored
Drag'n'drop support (codex-team#445)
* moving caret initial * small improvements * last changes, added docs * requested changes * implement getters instead of functions in block cursors * last requested changes * caret module docs and last improvements * update docs * upgrade request * update docs * upd * todo on delays * Sanitizer docs * split func upd * split blocks update * up docs * Listeners Module: initial * listener module updates * split is ready * update * start to make merge * upd * split general upd split is ready * ups * keyboard module update * BlockManager removed keyboard handler * commit before merging rewriting2.0 * general upd split * Documentation upd * document + listener upd * upd doc * documentation upd * doc upd * listener upd * update algh extract fragm * upd extractRangeContent * upd dom.js * keyboard upd (shift + enter & enableLineBreaks) * upd enter pressed * keyboard.js upd * enter pressed upd * documenation added * documentation upd * Toolbar: settings zone added. (codex-team#252) * Toolbar: settings zone added. * update some comments * Making a Toolbar * delete block * dom improvements and merging blocks * merge and split improvements * fix merging * do not remove block if block contains media * optimize code * caret behaviour improved * up * up * merging blocks. Now plugins handles this cases * mergeable getter * save * up * dom getdeepestnode improvements * improve getDeepest node method one more time * upd * Deal with it * improve isAtStart * improve docs * use smart isAtStart and isAtEnt method in navigateNext/navigatePrevious * improve docs * fix bug in $.isEmpty, improve keydown * fix isAtEnd * rollback setCaret code duplication * improve backspace * Debug tree walker * fix tree walker * small caret fix * queue ordering * update bundle * improve first letter checkup * doc upd * update current block index setter * TypeScript support, Webpack 4, Inline Toolbar beginning (codex-team#257) * Create UI * Support TypeScript Modules * remove tmp files * migrate to 2-spaced tabs * Add TS Linter * Inline Toolbar moving (codex-team#258) * Inline Toolbar moving * simplify code * Check is need to show Inline Toolbar * remove duplicate from doc * fix doc * open/close IT * Close IT by clicks on Redactor * @GurYN going strange Co-Authored-By: Taly <vitalik7tv@yandex.ru> * default settings initial * add move up button to default tunes area * need to figure out with assets * Inline Toolbar Tools base example (codex-team#260) * Inline Toolbar Tools base example * texts fixed * imrpove texts * little fixes * save * tunes with interface * add tool settings * initial api methods * api is ready * started writing docs * Create svg sprite (codex-team#261) * API * requested changes * fix conflicts * add docs * doc fixes and interface improvements * update * API scopes improved * Deleting block: Initial * Delete block with confirmation * Event subscription&unsubscription * deletion trigger improvements * small improvements * Link Inline Tool (codex-team#264) * Link Inline Tool * api injected * text improved * Clear input on the reselection * little improvements * Delete tune fixes * UI: Block Settings, show Plus after Enter keydown (codex-team#265) * Some UI improvements: icons settigns * Show plus button after split * decrease autoprefixer * rename variable * Revert "Merge branch 'delete-tune-fixes' into rewriting-version2.0" This reverts commit 779bf5d, reversing changes made to 972eb87. * Delete Tune improvements * upd * upd comments * actualize API docs * Allow to connect external Inline Tools (codex-team#269) * Allow to connect external Inline Tools * unhardcode tool's api settings * Italic inline tool * update icon size * upgrade findParentTag function * add interface selection * fix cs * save marker * bundles * add todo * removing wrapper * update styles * market -> term * add comments * improve code * descrease margin * add text block to example * add line brakes * remove space * fix bugs * fix bug * umd as a library target * background -> background-color if `background` has only `color` then use `background-color` * Clear API (codex-team#274) * blockManager.clear * upd * api bez ebanoj knopki api * fix assignment * insert empty block with clear method * clear and render methods improved * open saver.save() * add comments * update comments * fix data returned by editor * rename plugin name field in data object (codex-team#276) * Text tool refactored (codex-team#277) Now it returns strict data format. * do not add block if tool is not exist (codex-team#278) * do not add block if tool is not exist * show warning * add todo * update warning message * put message into variable * Revert "put message into variable" This reverts commit c1f6389. * update comment * Module Keyboard rewrited to BlockEvents (codex-team#279) * Module Keydown rewrited to BlockEvents * move keyup and mouseup to the Block Events * Move-up tune (codex-team#268) Co-authored-by: khaydarov <murod.haydarov@gmail.com> * Move up tune initial * move up tune initial behaviour * moving up formula, docs and code cleaned * do not close the toolbar if moving block up * move nagivate methods to Caret Module * navigations returns boolean if caret is set * code improved * update comments * disable tune when block index is zero * provide API with listener module methods * caret improvements * add to docs * update docs and blocks api methods * docs changes * small improvements * swap instead of moves * update * fix swap * remove unused method * remove useless return value from setToBlock * improve caret isAtEnd and isAtStart * improve swap, fix listeners api@off method * Eslint --fix for project files (codex-team#280) * Header plugin (codex-team#281) * header initial * fix styles * eslint fix * add appendCallback * add comments * update styles * add svgs * highlight settings buttons * do not show text plugin in the toolbar * remove svg * Fixing caret behaviour. (codex-team#282) Plugins can change their state so that affect on Block's pluginsContent property which is in memory. * remove useless code * fix merge * "MoveDown" tune (codex-team#283) * move down initial Swap current block with next block and scroll window screen * check if block is last added new method to the blocks API that returns blocks count * fix comments * animate tune * add animation when tune is disabled * requested changes * remove unused css * Fix merge function and rename Block's wrapper (codex-team#284) * Fix merge function and rename wrapper * update * renew condition * update * upd * Merging blocks: Restore caret position 🤟🤟💪 (codex-team#286) * Merging blocks: Restore caret position 🤟🤟💪 * requested changes * update removing shadow caret * hide toolbar and selection on typing (codex-team#289) closes codex-team#288 * Editor Instance config Interface (codex-team#285) * create interface for editor config * use IEditorConfig * create some interfaces * add comments * editor interface * updates * update editor interface (codex-team#293) * При перемещении по стрелочкам убирать выделение блока (codex-team#296) * При перемещении по стрелочкам убирать выделение блока * Add comments * update comments * update comment * update toolbar design (codex-team#301) * Set caret at the end if clicked outsite the block (codex-team#305) * Set caret at last block or create new block at end * update comment * fix comments * Insert new Block when enter pressed on editor area (codex-team#307) * insert new block when enter pressed on editor zone * extra conditions. Enter must be handled on editors area * move at editor condition to the Selection method * closes can return null * fixing editor area * do not create new block * clean example * updates due to the requested changes * Add placeholder to contentEditable elements (codex-team#306) * add placeholder to contentEditable elements * store selection color in a variable * add placeholder to header block * Add placeholder to contenteditable only if attribute data-placeholder exists * remove tool config * Close toolbar after block is removed (codex-team#314) * makeSettings -> renderSettings (codex-team#315) * Term: new icon, new style. + margin between settings buttons (codex-team#316) Resolves codex-team#309 * Tool's renderToolboxIcon function (codex-team#318) * create renderToolboxIcon issue was not done * remove useless span wrapper * update linters * update styles * process click on svg by closest * remove commented code * rename function: svgIcon -> toolboxIcon * add toolboxIcon to docs * Paste (codex-team#259) * Paste module * Rewrite paste logic * Update due comments * Docs * Add all block elements * Sanitize content on paste * Remove logs and add header handler * Add comment to dom.js * Add comment to tools.js * Split block if paste not at the end * Update docs * Update docs * pidr * Take Tool name from config * Update docs * Label onPaste handler as private * Resolve conflict * Replace current block if it is empty (codex-team#320) * Improve Header line-height (codex-team#321) * Fix typo (codex-team#324) * CodeX Editor 2.0 Co-authored-by: Murod Khaydarov <murod.haydarov@gmail.com> Co-authored-by: Petr Savchenko <specc.dev@gmail.com> Co-authored-by: George Berezhnoy <gohabereg@gmail.com> Co-authored-by: Taly Guryn <vitalik7tv@yandex.ru> * Fix typo * Installation docs (codex-team#325) close codex-team#310 * Module Shortcuts (codex-team#317) * import shortcuts * node modules works * enable shortcut for inline tools * check shortcut existance * enable shortcuts to Block tools * set caret to block if block replaced * enable shortcuts on inline-tools * improve code * last changes * update * fix * insert returns block so we can set caret * use Map instead own structure * disable shortcut if iniline-toolbar disabled * update code styles * remove todo * upd * update * remove settings from insert function * create interface * code improvements * use const instead of let * upd * Simple Image Tool (codex-team#326) * Simple Image * fix pattern * show tunes` state * update code * update code * upd * Fix toolbox appearance, tools boxed are clickable (codex-team#331) * Remove toolsConfig from Editor's config (codex-team#327) * fix linters * remove toolsConfig * update tool's interfaces * add comments * bundles * remove test headers * restore commented code * update tool's interface * toolConfig -> toolSetting * fix typos toolSetting -> toolSettings toolsSettings -> toolSettings toolClasses -> toolsClasses * update code comments * update installation doc * update docs * update dev dep packages (codex-team#333) * Check is paste handler a function only if it exists (codex-team#328) * Toolbar with tab (codex-team#330) * toolbar tabs initial * leaf initial * save state * flip back toolbox items * enter on toolbox item * update * requested changes * new condfition * update * improve animation on leaf * fix shift+tab flip * up * update * updates * Consecutive blank lines are forbidden * Correct choosing next toolbox item * update * update comment * Validate editor's config before initing (codex-team#341) * validate editor's config before initing * update readme * @ * update comments * add function _.isClass * Styles API (codex-team#343) * StylesAPI * use styles api in plugins * add inline styles * List Tool [new] (codex-team#344) * list tool initial * list class with settings * make tool reactive * final List improvements * reorder * tmp update * unhadrcode enter handler * updates * enableLineBreaks also checks * skip empty items * select LI by CMD+A, fix backspace in the last item * improve check for emptiness * Example page improved (codex-team#347) * Update new example * imrpove example.html * updates * improve code * Header plugin (codex-team#348) * isFunction function * use header from cdn * Improve paste behaviour (codex-team#346) * Improve paste behaviour * Done * Don't pass empty items * Update comment * move public up * Remove disallow paste option * Quote Tool (codex-team#329) * Quote Tool * Add icon * Upd * fix ENTER on quote * Remove useless code * items -> blocks (codex-team#351) * use SimpleImage from cdn (codex-team#355) * use simpleimage from cdn * add comments * fix spaces * fix comments * remove comments * update simple-image script * Update text on the example.html (codex-team#356) * use Paragraph Tool from CDN (codex-team#357) * use Paragraph Tool from CDN * add line brakes * rename block: paragraph -> text * Remove _callbacks.js (codex-team#358) * Clear unused files (codex-team#359) * TOOLBAR_ICON_CLASS -> TOOLBAR_ICON (codex-team#360) * TOOLBAR_ICON_CLASS -> TOOLBAR_ICON * remove defaultConfig * Delimiter tool (codex-team#362) * Delimiter added * ашч * use delimiter from cdn * Enter on editor (codex-team#363) * Enterpress on editor * use additional property * check enter on body * update * fix toolbar behaviour * upd * update bundle * remove useless ui property * update comment * add Element.prepend() function (codex-team#365) * add Element.prepend() function * allow to pass element of array to prepend() polyfill * use List Tool from cdn (codex-team#366) * use List Tool from cdn * add missing </div> in example.html * Pass "config" from Tool's settings to Tool's constructor (codex-team#367) * pass config from Tool's settings to Tool's constructor * reorder elements * add apiSettings.CONFIG property * use string as a object's key 😔 (codex-team#368) * update placeholder's styles (codex-team#369) * Add shortcuts for internal tools (codex-team#370) * Add shortcuts for internal tools * upd doc * remove articles * ☹️ guryn asked * use quote from cdn (codex-team#371) * Add cache to the inline tools (codex-team#372) * use Inline Code Tool from cdn (codex-team#375) * Issue 354 inline tools filter (codex-team#376) * Allow to filter inline tools. * update example * update header * fix endless cycle (codex-team#378) * Destructured options for Inline Tools (codex-team#379) * add destructured options for inline-tools * temporary disable inlineCode * remove term sources * Fix toolbar moving after arrow navigation (codex-team#380) * Fix toolbar moving after arrow navigation Resolves codex-team#361 * move before open * fix error on Enter after block removing * add example Tools as submodules (codex-team#381) * add destructured options for inline-tools * temporary disable inlineCode * remove term sources * add inline code Tool as a submodule * update version of inline-code package * add Tools as submodules * update Tools and use destructured params object * Add constructor() docs * update package Paragraph Tool * update installation docs * Input navigation (codex-team#339) * Quote Tool * Add icon * Upd * Initial setup * Save changes * Add scroll and fix input focus * Add comments * Rebuild bundle * fix ENTER on quote * Fix split behaviour * Fix * Navigate only to contentful blocks * add comments * Fix backspace on last block * Remove log * It works * Resolve comments * Use constants * New readme 🦅 (codex-team#386) * New readme 🦅 * upd text * Issue 374 (codex-team#385) * Fix issue codex-team#374 * Set current block index to -1 if there is no blocks left * Insert new block if first one was removed by default * Paragraph as a default Tool in editor; Zero-conf (codex-team#389) * git commit -m "Removed submodule Paragraph" * add paragraph to core + zero-config * update bundle * update comment * remove log * enable minifying (codex-team#390) * Drop current block index only if there is no selection at the Editor (codex-team#388) * Drop current block index only if there is no selection at the Editor * Set current node if click ended out of editor * Small backspace behaviour improvement (codex-team#391) * Small backspace behaviour improvement * fix caret position * update from base branch * Update webpack config * Migrate to Yarn (codex-team#393) * Migrate to yarn * Update scripts * Rewrite helpers classes to TypeScript (codex-team#396) * Add docs and isReady promise (codex-team#394) * set default holderId value (codex-team#404) * Destroyer (codex-team#392) * Initial destroy method * Add destroy method to api docs * Export isReady promise in CodexEditor constructor * Add drag'n'drop support * Add docs * Small fix * Continue merging master :| * Fixes after merge * Add styles and improve behavior * Close inline toolbar and remove dragged content * Some improvements of paste data processing * Delete selection content only if drag has been started at editor * Add comments * Support of pasting from copy-buffer * Change header level * Improvements * Use isDraNDrop flag * Update example * Improve d'n'd behaviour * git pull for simple-image tool
1 parent cdf6d97 commit 577da8f

12 files changed

Lines changed: 775 additions & 319 deletions

File tree

‎build/codex-editor.js‎

Lines changed: 155 additions & 151 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎build/codex-editor.js.map‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎docs/tools.md‎

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ CodeX Editor is a block-oriented editor. It means that entry composed with the l
44

55
`Tool` — is a class that provide custom `Block` type. All Tools represented by `Plugins`.
66

7-
Each Tool should have an installation guide.
7+
Each Tool should have an installation guide.
88

99
## Tool class structure
1010

1111
### constructor()
1212

1313
Each Tool's instance called with an params object.
14-
14+
1515
| Param | Type | Description |
1616
| ------ | ------------------- | ----------------------------------------------- |
1717
| api | [`IAPI`][iapi-link] | CodeX Editor's API methods |
@@ -62,7 +62,7 @@ Options that Tool can specify. All settings should be passed as static propertie
6262

6363
### User configuration
6464

65-
All Tools can be configured by users. You can set up some of available settings along with Tool's class
65+
All Tools can be configured by users. You can set up some of available settings along with Tool's class
6666
to the `tools` property of Editor Config.
6767

6868
```javascript
@@ -103,7 +103,7 @@ To provide paste handling for your Tool you need to define static getter `onPast
103103

104104
##### HTML tags handling
105105

106-
To handle pasted HTML elements object returned from `onPaste` getter should contain following fields:
106+
To handle pasted HTML elements object returned from `onPaste` getter should contain following fields:
107107

108108
| Name | Type | Description |
109109
| -- | -- | -- |
@@ -140,7 +140,7 @@ Your Tool can analyze text by RegExp patterns to substitute pasted string with d
140140
| `patterns` | `Object` | _Optional_. `patterns` object contains RegExp patterns with their names as object's keys |
141141
| `patternHandler(text: string, key: string)` | `Function` | _Optional_. Gets pasted string and pattern name. Should return the same object as Tool `save` method |
142142

143-
**Note** Editor will check pattern's full match, so don't forget to handle all available chars in there.
143+
**Note** Editor will check pattern's full match, so don't forget to handle all available chars in there.
144144

145145
Pattern will be processed only if paste was on `initialBlock` Tool and pasted string length is less than 450 characters.
146146

@@ -156,7 +156,7 @@ static get onPaste() {
156156
},
157157
patternHandler: (text, key) => {
158158
const urlData = Youtube.onPaste.patterns[key].exec(text);
159-
159+
160160
return {
161161
iframe: Youtube.makeEmbededFromURL(urlData)
162162
};
@@ -167,4 +167,41 @@ static get onPaste() {
167167

168168
> Both `onPaste.handler` and `onPaste.patternHandler` can be `async` or return a `Promise`.
169169
170+
##### Files
171+
172+
Your Tool can handle files pasted or dropped into the Editor.
173+
174+
To handle file you should provide `files` and `fileHandler` properties in your `onPaste` configuration object.
175+
176+
`fileHandler` property should be a function which takes File object as an argument and returns the same object as Tool\`s `save` method.
177+
178+
`file` property is an object with the following fields:
179+
180+
| Name | Type | Description |
181+
| ---- | ---- | ----------- |
182+
| `extensions` | `string[]` | _Optional_ Array of extensions your Tool can handle |
183+
| `mimeTypes` | `sring[]` | _Optional_ Array of MIME types your Tool can handle |
184+
185+
186+
187+
Example
188+
189+
```javascript
190+
static get onPaste() {
191+
return {
192+
files: {
193+
mimeTypes: ['image/png'],
194+
extensions: ['json']
195+
},
196+
fileHandler: (file) => {
197+
/* do smth with the file */
198+
199+
return {
200+
data // Some extracted content
201+
}
202+
}
203+
}
204+
}
205+
```
206+
170207
### Sanitize

‎example/tools/simple-image‎

‎src/components/block.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,13 @@ export default class Block {
3232
* CSS classes for the Block
3333
* @return {{wrapper: string, content: string}}
3434
*/
35-
static get CSS(): {wrapper: string, wrapperStretched: string, content: string, selected: string} {
35+
static get CSS(): {wrapper: string, wrapperStretched: string, content: string, selected: string, dropTarget: string} {
3636
return {
3737
wrapper: 'ce-block',
3838
wrapperStretched: 'ce-block--stretched',
3939
content: 'ce-block__content',
4040
selected: 'ce-block--selected',
41+
dropTarget: 'ce-block--drop-target',
4142
};
4243
}
4344

@@ -363,6 +364,14 @@ export default class Block {
363364
return tunesElement;
364365
}
365366

367+
/**
368+
* Toggle drop target state
369+
* @param {boolean} state
370+
*/
371+
public set dropTarget(state) {
372+
this.holder.classList.toggle(Block.CSS.dropTarget, state);
373+
}
374+
366375
/**
367376
* Make default Block wrappers and put Tool`s content there
368377
* @returns {HTMLDivElement}

‎src/components/core.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ export default class Core {
262262
* @return {Promise}
263263
*/
264264
async start() {
265-
const modulesToPrepare = ['Tools', 'UI', 'BlockManager', 'Paste', 'ModificationsObserver'];
265+
const modulesToPrepare = ['Tools', 'UI', 'BlockManager', 'Paste', 'DragNDrop', 'ModificationsObserver'];
266266

267267
await modulesToPrepare.reduce(
268268
(promise, module) => promise.then(async () => {

‎src/components/modules/block-events.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,28 @@ export default class BlockEvents extends Module {
120120
}
121121
}
122122

123+
/**
124+
* Add drop target styles
125+
*
126+
* @param {DragEvent} e
127+
*/
128+
public dragOver(e: DragEvent) {
129+
const block = this.Editor.BlockManager.getBlockByChildNode(e.target);
130+
131+
block.dropTarget = true;
132+
}
133+
134+
/**
135+
* Remove drop target style
136+
*
137+
* @param {DragEvent} e
138+
*/
139+
public dragLeave(e: DragEvent) {
140+
const block = this.Editor.BlockManager.getBlockByChildNode(e.target);
141+
142+
block.dropTarget = false;
143+
}
144+
123145
/**
124146
* ENTER pressed on block
125147
* @param {KeyboardEvent} event - keydown

‎src/components/modules/blockManager.js‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,8 @@ export default class BlockManager extends Module {
103103
this.Editor.Listeners.on(block.holder, 'keydown', (event) => this.Editor.BlockEvents.keydown(event), true);
104104
this.Editor.Listeners.on(block.holder, 'mouseup', (event) => this.Editor.BlockEvents.mouseUp(event));
105105
this.Editor.Listeners.on(block.holder, 'keyup', (event) => this.Editor.BlockEvents.keyup(event));
106+
this.Editor.Listeners.on(block.holder, 'dragover', (event) => this.Editor.BlockEvents.dragOver(event));
107+
this.Editor.Listeners.on(block.holder, 'dragleave', (event) => this.Editor.BlockEvents.dragLeave(event));
106108
}
107109

108110
/**
@@ -362,17 +364,18 @@ export default class BlockManager extends Module {
362364
* 2) Mark it as current
363365
*
364366
* @param {Element|Text} childNode - look ahead from this node.
367+
* @param {string} caretPosition - position where to set caret
365368
* @throws Error - when passed Node is not included at the Block
366369
*/
367-
setCurrentBlockByChildNode(childNode) {
370+
setCurrentBlockByChildNode(childNode, caretPosition = 'default') {
368371
/**
369372
* If node is Text TextNode
370373
*/
371374
if (!$.isElement(childNode)) {
372375
childNode = childNode.parentNode;
373376
}
374377

375-
let parentFirstLevelBlock = childNode.closest(`.${Block.CSS.wrapper}`);
378+
const parentFirstLevelBlock = childNode.closest(`.${Block.CSS.wrapper}`);
376379

377380
if (parentFirstLevelBlock) {
378381
/**
@@ -381,12 +384,31 @@ export default class BlockManager extends Module {
381384
*/
382385
this.currentBlockIndex = this._blocks.nodes.indexOf(parentFirstLevelBlock);
383386

384-
this.Editor.Caret.setToInput(childNode);
387+
this.Editor.Caret.setToInput(childNode, caretPosition);
385388
} else {
386389
throw new Error('Can not find a Block from this child Node');
387390
}
388391
}
389392

393+
/**
394+
* Return block which contents passed node
395+
*
396+
* @param {Node} childNode
397+
* @return {Block}
398+
*/
399+
getBlockByChildNode(childNode) {
400+
/**
401+
* If node is Text TextNode
402+
*/
403+
if (!$.isElement(childNode)) {
404+
childNode = childNode.parentNode;
405+
}
406+
407+
const firstLevelBlock = childNode.closest(`.${Block.CSS.wrapper}`);
408+
409+
return this.blocks.find(block => block.holder === firstLevelBlock);
410+
}
411+
390412
/**
391413
* Swap Blocks Position
392414
* @param {Number} fromIndex
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import SelectionUtils from '../selection';
2+
3+
declare var Module: any;
4+
5+
export default class DragNDrop extends Module {
6+
7+
/**
8+
* If drag has been started at editor, we save it
9+
*
10+
* @type Boolean
11+
* @private
12+
*/
13+
private isStartedAtEditor = false;
14+
15+
/**
16+
* Bind events
17+
*
18+
* @private
19+
*/
20+
public prepare(): void {
21+
this.bindEvents();
22+
}
23+
24+
/**
25+
* Add drag events listeners to editor zone
26+
* @private
27+
*/
28+
private bindEvents(): void {
29+
this.Editor.Listeners.on(this.Editor.UI.nodes.holder, 'drop', this.processDrop, true);
30+
31+
this.Editor.Listeners.on(this.Editor.UI.nodes.holder, 'dragstart', (dragEvent: DragEvent) => {
32+
33+
if (SelectionUtils.isAtEditor && !SelectionUtils.isCollapsed) {
34+
this.isStartedAtEditor = true;
35+
}
36+
37+
this.Editor.InlineToolbar.close();
38+
});
39+
40+
/* Prevent default browser behavior to allow drop on non-contenteditable elements */
41+
this.Editor.Listeners.on(this.Editor.UI.nodes.holder, 'dragover', (e) => e.preventDefault(), true);
42+
}
43+
44+
/**
45+
* Handle drop event
46+
*
47+
* @param {DragEvent} dropEvent
48+
*/
49+
private processDrop = async (dropEvent: DragEvent): Promise<void> => {
50+
const {
51+
BlockManager,
52+
Paste,
53+
} = this.Editor;
54+
55+
dropEvent.preventDefault();
56+
57+
BlockManager.blocks.forEach((block) => block.dropTarget = false);
58+
59+
if (SelectionUtils.isAtEditor && !SelectionUtils.isCollapsed && this.isStartedAtEditor) {
60+
document.execCommand('delete');
61+
}
62+
63+
this.isStartedAtEditor = false;
64+
65+
/**
66+
* Try to set current block by drop target.
67+
* If drop target (error will be thrown) is not part of the Block, set last Block as current.
68+
*/
69+
try {
70+
BlockManager.setCurrentBlockByChildNode(dropEvent.target, 'end');
71+
} catch (e) {
72+
BlockManager.setCurrentBlockByChildNode(BlockManager.lastBlock.holder, 'end');
73+
}
74+
75+
Paste.processDataTransfer(dropEvent.dataTransfer, true);
76+
}
77+
}

0 commit comments

Comments
 (0)