From c0dcc3c559be45a80ab03b4380ea9ab7c7691ff2 Mon Sep 17 00:00:00 2001
From: Wiktor Walc <w.walc@cksource.com>
Date: Fri, 2 Mar 2012 21:39:24 +0100
Subject: [PATCH] Integration with CKEditor via WYSIWYG

---
 caption_filter.module |   14 +++-
 js/caption-filter.js  |   14 +--
 js/ckeditor/plugin.js |  249 +++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 267 insertions(+), 10 deletions(-)
 create mode 100644 js/ckeditor/plugin.js

diff --git a/caption_filter.module b/caption_filter.module
index 2ca7d0d..2dc112f 100644
--- a/caption_filter.module
+++ b/caption_filter.module
@@ -55,7 +55,7 @@ function caption_filter_tips($filter, $format, $long = FALSE) {
 function caption_filter_process_filter($text, $filter) {
   // Prevent useless processing if there are no caption tags at all.
   if (stristr($text, '[caption') !== FALSE) {
-    $pattern = "/(\[caption([^\]]*)\])(.*?)(\[\/caption\])/";
+    $pattern = "/(\[caption([^\]]*)\])(.*?)(\[\/caption\])/s";
     $text = preg_replace_callback($pattern, '_caption_filter_replace', $text);
   }
   return $text;
@@ -191,6 +191,18 @@ function caption_filter_wysiwyg_plugin($editor, $version) {
       'load' => TRUE,
     );
   }
+  if ($editor == 'ckeditor') {
+    $plugins['captionfilter'] = array(
+      'path' => drupal_get_path('module', 'caption_filter') .'/js/ckeditor',
+      'load' => TRUE,
+      'buttons' => array(
+        'captionfilter' => t('Caption Filter'),
+      ),
+    'options' => array(
+        'captionfilter_css' => base_path() . drupal_get_path('module', 'caption_filter') . '/caption-filter.css',
+      ),
+    );
+  }
   return $plugins;
 }
 
diff --git a/js/caption-filter.js b/js/caption-filter.js
index 5e1bc8b..d2c812d 100644
--- a/js/caption-filter.js
+++ b/js/caption-filter.js
@@ -16,31 +16,27 @@ Drupal.captionFilter = Drupal.captionFilter || {};
 
 Drupal.captionFilter.toHTML = function(co, editor) {
   return co.replace(/(?:<p>)?\[caption([^\]]*)\]([\s\S]+?)\[\/caption\](?:<\/p>)?[\s\u00a0]*/g, function(a,b,c){
-    var id, cls, w, tempClass;
+    var cls, w, tempClass;
 
     b = b.replace(/\\'|\\&#39;|\\&#039;/g, '&#39;').replace(/\\"|\\&quot;/g, '&quot;');
     c = c.replace(/\\&#39;|\\&#039;/g, '&#39;').replace(/\\&quot;/g, '&quot;');
-    id = b.match(/id=['"]([^'"]+)/i);
     cls = b.match(/align=['"]([^'"]+)/i);
-    w = c.match(/width=['"]([0-9]+)/);
+    w = c.match(/width=['"]([0-9]+)/i);
 
-    id = ( id && id[1] ) ? id[1] : '';
     cls = ( cls && cls[1] ) ? 'caption-' + cls[1] : '';
     w = ( w && w[1] ) ? w[1] : '';
 
     if (editor == 'tinymce')
-      tempClass = (cls == 'caption-center') ? 'mceTemp mceIEcenter' : 'mceTemp';
-    else if (editor == 'ckeditor')
-      tempClass = (cls == 'caption-center') ? 'mceTemp mceIEcenter' : 'mceTemp';
+      tempClass = (cls == 'caption-center') ? 'mceTemp mceIEcenter draggable' : 'mceTemp draggable';
     else
       tempClass = '';
 
-    return '<div class="caption ' + cls + ' ' + tempClass + ' draggable"><div class="caption-inner" style="width: '+(parseInt(w))+'px">' + c + '</div></div>';
+    return '<div class="caption' + ( cls ? ' ' + cls : '' ) + ( tempClass ? ' ' + tempClass : '' ) + '"><div class="caption-inner"' + ( w ? ' style="width: '+(parseInt(w))+'px"' : '' ) + '>' + c + '</div></div>';
   });
 };
 
 Drupal.captionFilter.toTag = function(co) {
-  return co.replace(/(<div class="caption [^"]*">)\s*<div[^>]+>(.+?)<\/div>\s*<\/div>\s*/gi, function(match, captionWrapper, contents) {
+  return co.replace(/(<div class="caption(?:\s+[^"]*)?">)\s*<div[^>]+>((?:\s|.)+?)<\/div>\s*<\/div>\s*/gi, function(match, captionWrapper, contents) {
     var align;
     align = captionWrapper.match(/class=.*?caption-(left|center|right)/i);
     align = (align && align[1]) ? align[1] : '';
diff --git a/js/ckeditor/plugin.js b/js/ckeditor/plugin.js
new file mode 100644
index 0000000..1922ee8
--- /dev/null
+++ b/js/ckeditor/plugin.js
@@ -0,0 +1,249 @@
+/*
+Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
+For licensing, see LICENSE.html or http://ckeditor.com/license
+*/
+
+CKEDITOR.plugins.add( 'captionfilter', 
+{
+	beforeInit : function( editor )
+	{
+		if ( editor.config.contentsCss )
+		{
+			if ( !CKEDITOR.tools.isArray( editor.config.contentsCss ) )
+				editor.config.contentsCss = [ editor.config.contentsCss ];
+
+			editor.config.contentsCss.push( editor.config.captionfilter_css );
+		}
+	},
+	init : function( editor )
+	{
+		CKEDITOR.on( 'dialogDefinition', function( e )
+		{
+			if ( e.data.name == 'image' && !e.data.definition.getContents( 'caption' ) )
+			{
+				e.data.definition.addContents( {
+					id : 'caption',
+					label : 'Caption',
+					title : 'Caption',
+					elements : 
+					[
+						{
+							type : 'text',
+							id : 'captionText',
+							label : 'Caption',
+							onHide : function()
+							{
+								this.enable();
+							},
+							setup : function( type, element )
+							{
+								if ( type == 1 )
+								{
+									var el = this.getDialog().cleanImageElement,
+										parent = el && el.getAscendant( 'div' ),
+										caption;
+									if ( parent && ( caption = parent.getParent() ) && caption.is( 'div' ) && caption.hasClass( 'caption' ) )
+									{
+										var next = el.getNext(),
+											bogus = el.getParent().getBogus();
+										if ( next )
+										{
+											this.setValue( next.getText() );
+											if ( ( next = next.getNext() ) && !next.equals( bogus ) )
+												this.disable();
+										}
+										
+										var select = this.getDialog().getContentElement( 'caption', 'captionStyle' );
+										select && select.setValue( caption.hasClass( 'caption-right' ) ? 'right' :
+													caption.hasClass( 'caption-left' ) ? 'left' :
+														caption.hasClass( 'caption-center' ) ? 'center' : '' );
+
+										this.captionElement = caption;
+									}
+								}
+							},
+							commit : function( type, element )
+							{
+								if ( type == 1 )
+								{
+									var caption = this.captionElement,
+										sel = editor.getSelection(),
+										selected = sel && sel.getSelectedElement();
+
+									if ( selected && !selected.is( 'img' ) )
+										selected = null;
+
+									if ( !caption )
+									{
+										if ( !this.getValue() )
+											return null;
+
+										caption = CKEDITOR.dom.element.createFromHtml( '<div class="caption"><div class="caption-inner"></div></div>', element.getDocument() );
+										if ( this.linkElement )
+										{
+											caption.insertBefore( this.linkElement );
+											this.linkElement.appendTo( caption.getFirst() );
+										}
+										else
+										{
+											if ( selected )
+											{
+												caption.insertBefore( selected );
+												selected.move( caption.getFirst(), true );
+											}
+											else
+											{
+												editor.insertElement( caption );
+												var imageElement = this.getDialog().imageElement;
+												setTimeout( function(){ imageElement.move( caption.getFirst(), true ); }, 0 );
+											}
+										}
+									}
+
+									if ( this.isEnabled() )
+									{
+										if ( !this.getValue() )
+										{
+											if ( this.linkElement )
+												this.linkElement.insertAfter( caption );
+											else
+												selected.insertAfter( caption );
+											caption.remove();
+										}
+										else if ( this.isChanged() )
+										{
+											var inner = caption.getFirst(),
+												bogus = inner.getBogus();
+											bogus && bogus.remove();
+											if ( inner.getLast() && inner.getLast().type == CKEDITOR.NODE_TEXT )
+												inner.getLast().remove();
+											if ( CKEDITOR.env.ie && CKEDITOR.env.version < 8 )
+											{
+												var dummy = new CKEDITOR.dom.element( 'span', element.getDocument() );
+												dummy.setText( this.getValue() );
+												dummy.moveChildren( inner );
+												dummy.remove();
+											}
+											else
+												inner.appendText( this.getValue() );
+										}
+									}
+
+									var select = this.getDialog().getContentElement( 'caption', 'captionStyle' );
+									if ( select && ( !select.getValue() || !caption.hasClass( 'caption-' + select.getValue() ) ) )
+									{
+										caption.removeClass( 'caption-right' );
+										caption.removeClass( 'caption-left' );
+										caption.removeClass( 'caption-center' );
+										select.getValue() && caption.addClass( 'caption-' + select.getValue() );
+									}
+								}
+							}
+						},
+						{
+							type : 'select',
+							id : 'captionStyle',
+							label : 'Style',
+							'default' : '',
+							items : [ [ '' ], [ 'Right', 'right' ], [ 'Left', 'left' ], [ 'Center', 'center' ] ]
+						}
+					]
+				});
+			}
+		});
+
+		var findCaption = function( element )
+		{
+			var elementPath = new CKEDITOR.dom.elementPath( element ),
+				asc = elementPath.blockLimit && elementPath.blockLimit.getAscendant( 'div', true );
+			while ( asc && !asc.hasClass( 'caption' ) )
+				asc = asc.getAscendant( 'div' );
+			return asc;
+		};
+
+		if ( editor.addMenuItem )
+		{
+			editor.addCommand( 'removecaption',
+			{
+				modes : { wysiwyg : 1 },
+				exec : function( editor )
+				{
+					var sel = editor.getSelection(),
+						caption = sel && sel.getStartElement();
+					if ( !caption || !( caption = findCaption( caption ) ) )
+						return null;
+					var inner = caption.getFirst( function( node )
+					{
+						return node.type == CKEDITOR.NODE_ELEMENT && node.is( 'div' ) && node.hasClass( 'caption-inner' );
+					});
+					caption.remove( true );
+					inner.getFirst( function( node )
+					{
+						return node.type == CKEDITOR.NODE_ELEMENT && node.is( 'img' );
+					}).clone().insertAfter( inner );
+					inner.remove();
+				}
+			});
+			editor.addMenuItem( 'removeCaption',
+			{
+				label : 'Remove Caption',
+				command : 'removecaption',
+				group : 'div',
+				order : 1
+			});
+			editor.contextMenu.addListener( function( element, selection )
+			{
+				if ( !element || element.isReadOnly() )
+					return null;
+
+				if ( findCaption( element ) )
+					return { removeCaption : CKEDITOR.TRISTATE_OFF };
+			});
+		}
+
+		if ( editor.keystrokeHandler )
+		{
+			var ks = editor.keystrokeHandler.keystrokes,
+				handler = ks[ 13 ];
+			editor.addCommand( 'captionEnter',
+			{
+				modes : { wysiwyg : 1 },
+				editorFocus : false,
+				exec : function( editor )
+				{
+					var sel = editor.getSelection(),
+						caption = sel && sel.getStartElement(),
+						range = sel && sel.getRanges()[ 0 ];
+					if ( caption && ( caption = findCaption( caption ) ) )
+					{
+						CKEDITOR.env.ie && ( CKEDITOR.env.version < 9 ) && caption.getParent().focus();
+						range.moveToPosition( caption, CKEDITOR.POSITION_AFTER_END );
+						range.select();
+					}
+					return editor.execCommand( handler );
+				}
+			});
+			ks[ 13 ] = 'captionEnter';
+		}
+	},
+	afterInit : function( editor )
+	{
+		var proto = CKEDITOR.htmlDataProcessor.prototype;
+		proto.toHtml = CKEDITOR.tools.override( proto.toHtml, function( org )
+		{
+			return function( data )
+			{
+				data = Drupal.captionFilter.toHTML( data, 'ckeditor' );
+				return org.apply( this, arguments );
+			};
+		});
+		proto.toDataFormat = CKEDITOR.tools.override( proto.toDataFormat, function( org )
+		{
+			return function( data )
+			{
+				data = org.apply( this, arguments );
+				return Drupal.captionFilter.toTag( data );
+			};
+		});
+	}
+});
\ No newline at end of file
-- 
1.7.3.1.msysgit.0

