Skip to content
This repository has been archived by the owner on Jun 26, 2020. It is now read-only.

Commit

Permalink
Further refactor the _insertMissingModelCaptionElement() method.
Browse files Browse the repository at this point in the history
  • Loading branch information
jodator committed Feb 18, 2019
1 parent 87b90ba commit b5c3c16
Showing 1 changed file with 15 additions and 20 deletions.
35 changes: 15 additions & 20 deletions src/imagecaption/imagecaptionediting.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@

import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import { isImage } from '../image/utils';
import {
captionElementCreator,
getCaptionFromImage,
matchImageCaption
} from './utils';
import { captionElementCreator, getCaptionFromImage, matchImageCaption } from './utils';

/**
* The image caption engine plugin.
Expand Down Expand Up @@ -182,40 +178,39 @@ export default class ImageCaptionEditing extends Plugin {
const model = this.editor.model;
const changes = model.document.differ.getChanges();

let wasFixed = false;
const imagesWithoutCaption = [];

for ( const entry of changes ) {
const images = [];

if ( entry.type == 'insert' && entry.name != '$text' ) {
const item = entry.position.nodeAfter;

if ( item.is( 'image' ) ) {
images.push( item );
} else if ( item.childCount ) {
if ( item.is( 'image' ) && !getCaptionFromImage( item ) ) {
imagesWithoutCaption.push( item );
}

// Check elements with children for nested images.
if ( !item.is( 'image' ) && item.childCount ) {
// Use the walker to find all nested images despite of their nest level.
const walker = model.createRangeOn( item ).getWalker();

for ( const walkerValue of walker ) {
if ( walkerValue.type === 'elementStart' ) {
const walkerItem = walkerValue.item;

if ( walkerItem.is( 'image' ) ) {
images.push( walkerItem );
if ( walkerItem.is( 'image' ) && !getCaptionFromImage( walkerItem ) ) {
imagesWithoutCaption.push( walkerItem );
}
}
}
}
}
}

for ( const image of images.filter( image => !getCaptionFromImage( image ) ) ) {
writer.appendElement( 'caption', image );
}

// TODO: infinite loop :/
wasFixed = false;
for ( const image of imagesWithoutCaption ) {
writer.appendElement( 'caption', image );
}

return wasFixed;
return !!imagesWithoutCaption.length;
}
}

Expand Down

0 comments on commit b5c3c16

Please sign in to comment.