plugin.js 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or http://ckeditor.com/license
  4. */
  5. /**
  6. * @fileOverview [Widget](http://ckeditor.com/addon/widget) plugin.
  7. */
  8. 'use strict';
  9. ( function() {
  10. var DRAG_HANDLER_SIZE = 15;
  11. CKEDITOR.plugins.add( 'widget', {
  12. // jscs:disable maximumLineLength
  13. lang: 'af,ar,bg,ca,cs,cy,da,de,el,en,en-gb,eo,es,fa,fi,fr,gl,he,hr,hu,it,ja,km,ko,ku,lv,nb,nl,no,pl,pt,pt-br,ru,sk,sl,sq,sv,tr,tt,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
  14. // jscs:enable maximumLineLength
  15. requires: 'lineutils,clipboard',
  16. onLoad: function() {
  17. CKEDITOR.addCss(
  18. '.cke_widget_wrapper{' +
  19. 'position:relative;' +
  20. 'outline:none' +
  21. '}' +
  22. '.cke_widget_inline{' +
  23. 'display:inline-block' +
  24. '}' +
  25. '.cke_widget_wrapper:hover>.cke_widget_element{' +
  26. 'outline:2px solid yellow;' +
  27. 'cursor:default' +
  28. '}' +
  29. '.cke_widget_wrapper:hover .cke_widget_editable{' +
  30. 'outline:2px solid yellow' +
  31. '}' +
  32. '.cke_widget_wrapper.cke_widget_focused>.cke_widget_element,' +
  33. // We need higher specificity than hover style.
  34. '.cke_widget_wrapper .cke_widget_editable.cke_widget_editable_focused{' +
  35. 'outline:2px solid #ace' +
  36. '}' +
  37. '.cke_widget_editable{' +
  38. 'cursor:text' +
  39. '}' +
  40. '.cke_widget_drag_handler_container{' +
  41. 'position:absolute;' +
  42. 'width:' + DRAG_HANDLER_SIZE + 'px;' +
  43. 'height:0;' +
  44. // Initially drag handler should not be visible, until its position will be
  45. // calculated (#11177).
  46. // We need to hide unpositined handlers, so they don't extend
  47. // widget's outline far to the left (#12024).
  48. 'display:none;' +
  49. 'opacity:0.75;' +
  50. 'transition:height 0s 0.2s;' + // Delay hiding drag handler.
  51. // Prevent drag handler from being misplaced (#11198).
  52. 'line-height:0' +
  53. '}' +
  54. '.cke_widget_wrapper:hover>.cke_widget_drag_handler_container{' +
  55. 'height:' + DRAG_HANDLER_SIZE + 'px;' +
  56. 'transition:none' +
  57. '}' +
  58. '.cke_widget_drag_handler_container:hover{' +
  59. 'opacity:1' +
  60. '}' +
  61. 'img.cke_widget_drag_handler{' +
  62. 'cursor:move;' +
  63. 'width:' + DRAG_HANDLER_SIZE + 'px;' +
  64. 'height:' + DRAG_HANDLER_SIZE + 'px;' +
  65. 'display:inline-block' +
  66. '}' +
  67. '.cke_widget_mask{' +
  68. 'position:absolute;' +
  69. 'top:0;' +
  70. 'left:0;' +
  71. 'width:100%;' +
  72. 'height:100%;' +
  73. 'display:block' +
  74. '}' +
  75. '.cke_editable.cke_widget_dragging, .cke_editable.cke_widget_dragging *{' +
  76. 'cursor:move !important' +
  77. '}'
  78. );
  79. },
  80. beforeInit: function( editor ) {
  81. /**
  82. * An instance of widget repository. It contains all
  83. * {@link CKEDITOR.plugins.widget.repository#registered registered widget definitions} and
  84. * {@link CKEDITOR.plugins.widget.repository#instances initialized instances}.
  85. *
  86. * editor.widgets.add( 'someName', {
  87. * // Widget definition...
  88. * } );
  89. *
  90. * editor.widgets.registered.someName; // -> Widget definition
  91. *
  92. * @since 4.3
  93. * @readonly
  94. * @property {CKEDITOR.plugins.widget.repository} widgets
  95. * @member CKEDITOR.editor
  96. */
  97. editor.widgets = new Repository( editor );
  98. },
  99. afterInit: function( editor ) {
  100. addWidgetButtons( editor );
  101. setupContextMenu( editor );
  102. }
  103. } );
  104. /**
  105. * Widget repository. It keeps track of all {@link #registered registered widget definitions} and
  106. * {@link #instances initialized instances}. An instance of the repository is available under
  107. * the {@link CKEDITOR.editor#widgets} property.
  108. *
  109. * @class CKEDITOR.plugins.widget.repository
  110. * @mixins CKEDITOR.event
  111. * @constructor Creates a widget repository instance. Note that the widget plugin automatically
  112. * creates a repository instance which is available under the {@link CKEDITOR.editor#widgets} property.
  113. * @param {CKEDITOR.editor} editor The editor instance for which the repository will be created.
  114. */
  115. function Repository( editor ) {
  116. /**
  117. * The editor instance for which this repository was created.
  118. *
  119. * @readonly
  120. * @property {CKEDITOR.editor} editor
  121. */
  122. this.editor = editor;
  123. /**
  124. * A hash of registered widget definitions (definition name => {@link CKEDITOR.plugins.widget.definition}).
  125. *
  126. * To register a definition use the {@link #add} method.
  127. *
  128. * @readonly
  129. */
  130. this.registered = {};
  131. /**
  132. * An object containing initialized widget instances (widget id => {@link CKEDITOR.plugins.widget}).
  133. *
  134. * @readonly
  135. */
  136. this.instances = {};
  137. /**
  138. * An array of selected widget instances.
  139. *
  140. * @readonly
  141. * @property {CKEDITOR.plugins.widget[]} selected
  142. */
  143. this.selected = [];
  144. /**
  145. * The focused widget instance. See also {@link CKEDITOR.plugins.widget#event-focus}
  146. * and {@link CKEDITOR.plugins.widget#event-blur} events.
  147. *
  148. * editor.on( 'selectionChange', function() {
  149. * if ( editor.widgets.focused ) {
  150. * // Do something when a widget is focused...
  151. * }
  152. * } );
  153. *
  154. * @readonly
  155. * @property {CKEDITOR.plugins.widget} focused
  156. */
  157. this.focused = null;
  158. /**
  159. * The widget instance that contains the nested editable which is currently focused.
  160. *
  161. * @readonly
  162. * @property {CKEDITOR.plugins.widget} widgetHoldingFocusedEditable
  163. */
  164. this.widgetHoldingFocusedEditable = null;
  165. this._ = {
  166. nextId: 0,
  167. upcasts: [],
  168. upcastCallbacks: [],
  169. filters: {}
  170. };
  171. setupWidgetsLifecycle( this );
  172. setupSelectionObserver( this );
  173. setupMouseObserver( this );
  174. setupKeyboardObserver( this );
  175. setupDragAndDrop( this );
  176. setupNativeCutAndCopy( this );
  177. }
  178. Repository.prototype = {
  179. /**
  180. * Minimum interval between selection checks.
  181. *
  182. * @private
  183. */
  184. MIN_SELECTION_CHECK_INTERVAL: 500,
  185. /**
  186. * Adds a widget definition to the repository. Fires the {@link CKEDITOR.editor#widgetDefinition} event
  187. * which allows to modify the widget definition which is going to be registered.
  188. *
  189. * @param {String} name The name of the widget definition.
  190. * @param {CKEDITOR.plugins.widget.definition} widgetDef Widget definition.
  191. * @returns {CKEDITOR.plugins.widget.definition}
  192. */
  193. add: function( name, widgetDef ) {
  194. // Create prototyped copy of original widget definition, so we won't modify it.
  195. widgetDef = CKEDITOR.tools.prototypedCopy( widgetDef );
  196. widgetDef.name = name;
  197. widgetDef._ = widgetDef._ || {};
  198. this.editor.fire( 'widgetDefinition', widgetDef );
  199. if ( widgetDef.template )
  200. widgetDef.template = new CKEDITOR.template( widgetDef.template );
  201. addWidgetCommand( this.editor, widgetDef );
  202. addWidgetProcessors( this, widgetDef );
  203. this.registered[ name ] = widgetDef;
  204. return widgetDef;
  205. },
  206. /**
  207. * Adds a callback for element upcasting. Each callback will be executed
  208. * for every element which is later tested by upcast methods. If a callback
  209. * returns `false`, the element will not be upcasted.
  210. *
  211. * // Images with the "banner" class will not be upcasted (e.g. to the image widget).
  212. * editor.widgets.addUpcastCallback( function( element ) {
  213. * if ( element.name == 'img' && element.hasClass( 'banner' ) )
  214. * return false;
  215. * } );
  216. *
  217. * @param {Function} callback
  218. * @param {CKEDITOR.htmlParser.element} callback.element
  219. */
  220. addUpcastCallback: function( callback ) {
  221. this._.upcastCallbacks.push( callback );
  222. },
  223. /**
  224. * Checks the selection to update widget states (selection and focus).
  225. *
  226. * This method is triggered by the {@link #event-checkSelection} event.
  227. */
  228. checkSelection: function() {
  229. var sel = this.editor.getSelection(),
  230. selectedElement = sel.getSelectedElement(),
  231. updater = stateUpdater( this ),
  232. widget;
  233. // Widget is focused so commit and finish checking.
  234. if ( selectedElement && ( widget = this.getByElement( selectedElement, true ) ) )
  235. return updater.focus( widget ).select( widget ).commit();
  236. var range = sel.getRanges()[ 0 ];
  237. // No ranges or collapsed range mean that nothing is selected, so commit and finish checking.
  238. if ( !range || range.collapsed )
  239. return updater.commit();
  240. // Range is not empty, so create walker checking for wrappers.
  241. var walker = new CKEDITOR.dom.walker( range ),
  242. wrapper;
  243. walker.evaluator = Widget.isDomWidgetWrapper;
  244. while ( ( wrapper = walker.next() ) )
  245. updater.select( this.getByElement( wrapper ) );
  246. updater.commit();
  247. },
  248. /**
  249. * Checks if all widget instances are still present in the DOM.
  250. * Destroys those instances that are not present.
  251. * Reinitializes widgets on widget wrappers for which widget instances
  252. * cannot be found. Takes nested widgets into account, too.
  253. *
  254. * This method triggers the {@link #event-checkWidgets} event whose listeners
  255. * can cancel the method's execution or modify its options.
  256. *
  257. * @param [options] The options object.
  258. * @param {Boolean} [options.initOnlyNew] Initializes widgets only on newly wrapped
  259. * widget elements (those which still have the `cke_widget_new` class). When this option is
  260. * set to `true`, widgets which were invalidated (e.g. by replacing with a cloned DOM structure)
  261. * will not be reinitialized. This makes the check faster.
  262. * @param {Boolean} [options.focusInited] If only one widget is initialized by
  263. * the method, it will be focused.
  264. */
  265. checkWidgets: function( options ) {
  266. this.fire( 'checkWidgets', CKEDITOR.tools.copy( options || {} ) );
  267. },
  268. /**
  269. * Removes the widget from the editor and moves the selection to the closest
  270. * editable position if the widget was focused before.
  271. *
  272. * @param {CKEDITOR.plugins.widget} widget The widget instance to be deleted.
  273. */
  274. del: function( widget ) {
  275. if ( this.focused === widget ) {
  276. var editor = widget.editor,
  277. range = editor.createRange(),
  278. found;
  279. // If haven't found place for caret on the default side,
  280. // try to find it on the other side.
  281. if ( !( found = range.moveToClosestEditablePosition( widget.wrapper, true ) ) )
  282. found = range.moveToClosestEditablePosition( widget.wrapper, false );
  283. if ( found )
  284. editor.getSelection().selectRanges( [ range ] );
  285. }
  286. widget.wrapper.remove();
  287. this.destroy( widget, true );
  288. },
  289. /**
  290. * Destroys the widget instance and all its nested widgets (widgets inside its nested editables).
  291. *
  292. * @param {CKEDITOR.plugins.widget} widget The widget instance to be destroyed.
  293. * @param {Boolean} [offline] Whether the widget is offline (detached from the DOM tree) —
  294. * in this case the DOM (attributes, classes, etc.) will not be cleaned up.
  295. */
  296. destroy: function( widget, offline ) {
  297. if ( this.widgetHoldingFocusedEditable === widget )
  298. setFocusedEditable( this, widget, null, offline );
  299. widget.destroy( offline );
  300. delete this.instances[ widget.id ];
  301. this.fire( 'instanceDestroyed', widget );
  302. },
  303. /**
  304. * Destroys all widget instances.
  305. *
  306. * @param {Boolean} [offline] Whether the widgets are offline (detached from the DOM tree) —
  307. * in this case the DOM (attributes, classes, etc.) will not be cleaned up.
  308. * @param {CKEDITOR.dom.element} [container] The container within widgets will be destroyed.
  309. * This option will be ignored if the `offline` flag was set to `true`, because in such case
  310. * it is not possible to find widgets within the passed block.
  311. */
  312. destroyAll: function( offline, container ) {
  313. var widget,
  314. id,
  315. instances = this.instances;
  316. if ( container && !offline ) {
  317. var wrappers = container.find( '.cke_widget_wrapper' ),
  318. l = wrappers.count(),
  319. i = 0;
  320. // Length is constant, because this is not a live node list.
  321. // Note: since querySelectorAll returns nodes in document order,
  322. // outer widgets are always placed before their nested widgets and therefore
  323. // are destroyed before them.
  324. for ( ; i < l; ++i ) {
  325. widget = this.getByElement( wrappers.getItem( i ), true );
  326. // Widget might not be found, because it could be a nested widget,
  327. // which would be destroyed when destroying its parent.
  328. if ( widget )
  329. this.destroy( widget );
  330. }
  331. return;
  332. }
  333. for ( id in instances ) {
  334. widget = instances[ id ];
  335. this.destroy( widget, offline );
  336. }
  337. },
  338. /**
  339. * Finalizes a process of widget creation. This includes:
  340. *
  341. * * inserting widget element into editor,
  342. * * marking widget instance as ready (see {@link CKEDITOR.plugins.widget#event-ready}),
  343. * * focusing widget instance.
  344. *
  345. * This method is used by the default widget's command and is called
  346. * after widget's dialog (if set) is closed. It may also be used in a
  347. * customized process of widget creation and insertion.
  348. *
  349. * widget.once( 'edit', function() {
  350. * // Finalize creation only of not ready widgets.
  351. * if ( widget.isReady() )
  352. * return;
  353. *
  354. * // Cancel edit event to prevent automatic widget insertion.
  355. * evt.cancel();
  356. *
  357. * CustomDialog.open( widget.data, function saveCallback( savedData ) {
  358. * // Cache the container, because widget may be destroyed while saving data,
  359. * // if this process will require some deep transformations.
  360. * var container = widget.wrapper.getParent();
  361. *
  362. * widget.setData( savedData );
  363. *
  364. * // Widget will be retrieved from container and inserted into editor.
  365. * editor.widgets.finalizeCreation( container );
  366. * } );
  367. * } );
  368. *
  369. * @param {CKEDITOR.dom.element/CKEDITOR.dom.documentFragment} container The element
  370. * or document fragment which contains widget wrapper. The container is used, so before
  371. * finalizing creation the widget can be freely transformed (even destroyed and reinitialized).
  372. */
  373. finalizeCreation: function( container ) {
  374. var wrapper = container.getFirst();
  375. if ( wrapper && Widget.isDomWidgetWrapper( wrapper ) ) {
  376. this.editor.insertElement( wrapper );
  377. var widget = this.getByElement( wrapper );
  378. // Fire postponed #ready event.
  379. widget.ready = true;
  380. widget.fire( 'ready' );
  381. widget.focus();
  382. }
  383. },
  384. /**
  385. * Finds a widget instance which contains a given element. The element will be the {@link CKEDITOR.plugins.widget#wrapper wrapper}
  386. * of the returned widget or a descendant of this {@link CKEDITOR.plugins.widget#wrapper wrapper}.
  387. *
  388. * editor.widgets.getByElement( someWidget.wrapper ); // -> someWidget
  389. * editor.widgets.getByElement( someWidget.parts.caption ); // -> someWidget
  390. *
  391. * // Check wrapper only:
  392. * editor.widgets.getByElement( someWidget.wrapper, true ); // -> someWidget
  393. * editor.widgets.getByElement( someWidget.parts.caption, true ); // -> null
  394. *
  395. * @param {CKEDITOR.dom.element} element The element to be checked.
  396. * @param {Boolean} [checkWrapperOnly] If set to `true`, the method will not check wrappers' descendants.
  397. * @returns {CKEDITOR.plugins.widget} The widget instance or `null`.
  398. */
  399. getByElement: ( function() {
  400. var validWrapperElements = { div: 1, span: 1 };
  401. function getWidgetId( element ) {
  402. return element.is( validWrapperElements ) && element.data( 'cke-widget-id' );
  403. }
  404. return function( element, checkWrapperOnly ) {
  405. if ( !element )
  406. return null;
  407. var id = getWidgetId( element );
  408. // There's no need to check element parents if element is a wrapper.
  409. if ( !checkWrapperOnly && !id ) {
  410. var limit = this.editor.editable();
  411. // Try to find a closest ascendant which is a widget wrapper.
  412. do {
  413. element = element.getParent();
  414. } while ( element && !element.equals( limit ) && !( id = getWidgetId( element ) ) );
  415. }
  416. return this.instances[ id ] || null;
  417. };
  418. } )(),
  419. /**
  420. * Initializes a widget on a given element if the widget has not been initialized on it yet.
  421. *
  422. * @param {CKEDITOR.dom.element} element The future widget element.
  423. * @param {String/CKEDITOR.plugins.widget.definition} [widgetDef] Name of a widget or a widget definition.
  424. * The widget definition should be previously registered by using the
  425. * {@link CKEDITOR.plugins.widget.repository#add} method.
  426. * @param [startupData] Widget startup data (has precedence over default one).
  427. * @returns {CKEDITOR.plugins.widget} The widget instance or `null` if a widget could not be initialized on
  428. * a given element.
  429. */
  430. initOn: function( element, widgetDef, startupData ) {
  431. if ( !widgetDef )
  432. widgetDef = this.registered[ element.data( 'widget' ) ];
  433. else if ( typeof widgetDef == 'string' )
  434. widgetDef = this.registered[ widgetDef ];
  435. if ( !widgetDef )
  436. return null;
  437. // Wrap element if still wasn't wrapped (was added during runtime by method that skips dataProcessor).
  438. var wrapper = this.wrapElement( element, widgetDef.name );
  439. if ( wrapper ) {
  440. // Check if widget wrapper is new (widget hasn't been initialized on it yet).
  441. // This class will be removed by widget constructor to avoid locking snapshot twice.
  442. if ( wrapper.hasClass( 'cke_widget_new' ) ) {
  443. var widget = new Widget( this, this._.nextId++, element, widgetDef, startupData );
  444. // Widget could be destroyed when initializing it.
  445. if ( widget.isInited() ) {
  446. this.instances[ widget.id ] = widget;
  447. return widget;
  448. } else {
  449. return null;
  450. }
  451. }
  452. // Widget already has been initialized, so try to get widget by element.
  453. // Note - it may happen that other instance will returned than the one created above,
  454. // if for example widget was destroyed and reinitialized.
  455. return this.getByElement( element );
  456. }
  457. // No wrapper means that there's no widget for this element.
  458. return null;
  459. },
  460. /**
  461. * Initializes widgets on all elements which were wrapped by {@link #wrapElement} and
  462. * have not been initialized yet.
  463. *
  464. * @param {CKEDITOR.dom.element} [container=editor.editable()] The container which will be checked for not
  465. * initialized widgets. Defaults to editor's {@link CKEDITOR.editor#editable editable} element.
  466. * @returns {CKEDITOR.plugins.widget[]} Array of widget instances which have been initialized.
  467. * Note: Only first-level widgets are returned &mdash; without nested widgets.
  468. */
  469. initOnAll: function( container ) {
  470. var newWidgets = ( container || this.editor.editable() ).find( '.cke_widget_new' ),
  471. newInstances = [],
  472. instance;
  473. for ( var i = newWidgets.count(); i--; ) {
  474. instance = this.initOn( newWidgets.getItem( i ).getFirst( Widget.isDomWidgetElement ) );
  475. if ( instance )
  476. newInstances.push( instance );
  477. }
  478. return newInstances;
  479. },
  480. /**
  481. * Allows to listen to events on specific types of widgets, even if they are not created yet.
  482. *
  483. * Please note that this method inherits parameters from the {@link CKEDITOR.event#method-on} method with one
  484. * extra parameter at the beginning which is the widget name.
  485. *
  486. * editor.widgets.onWidget( 'image', 'action', function( evt ) {
  487. * // Event `action` occurs on `image` widget.
  488. * } );
  489. *
  490. * @since 4.5
  491. * @param {String} widgetName
  492. * @param {String} eventName
  493. * @param {Function} listenerFunction
  494. * @param {Object} [scopeObj]
  495. * @param {Object} [listenerData]
  496. * @param {Number} [priority=10]
  497. */
  498. onWidget: function( widgetName ) {
  499. var args = Array.prototype.slice.call( arguments );
  500. args.shift();
  501. for ( var i in this.instances ) {
  502. var instance = this.instances[ i ];
  503. if ( instance.name == widgetName ) {
  504. instance.on.apply( instance, args );
  505. }
  506. }
  507. this.on( 'instanceCreated', function( evt ) {
  508. var widget = evt.data;
  509. if ( widget.name == widgetName ) {
  510. widget.on.apply( widget, args );
  511. }
  512. } );
  513. },
  514. /**
  515. * Parses element classes string and returns an object
  516. * whose keys contain class names. Skips all `cke_*` classes.
  517. *
  518. * This method is used by the {@link CKEDITOR.plugins.widget#getClasses} method and
  519. * may be used when overriding that method.
  520. *
  521. * @since 4.4
  522. * @param {String} classes String (value of `class` attribute).
  523. * @returns {Object} Object containing classes or `null` if no classes found.
  524. */
  525. parseElementClasses: function( classes ) {
  526. if ( !classes )
  527. return null;
  528. classes = CKEDITOR.tools.trim( classes ).split( /\s+/ );
  529. var cl,
  530. obj = {},
  531. hasClasses = 0;
  532. while ( ( cl = classes.pop() ) ) {
  533. if ( cl.indexOf( 'cke_' ) == -1 )
  534. obj[ cl ] = hasClasses = 1;
  535. }
  536. return hasClasses ? obj : null;
  537. },
  538. /**
  539. * Wraps an element with a widget's non-editable container.
  540. *
  541. * If this method is called on an {@link CKEDITOR.htmlParser.element}, then it will
  542. * also take care of fixing the DOM after wrapping (the wrapper may not be allowed in element's parent).
  543. *
  544. * @param {CKEDITOR.dom.element/CKEDITOR.htmlParser.element} element The widget element to be wrapped.
  545. * @param {String} [widgetName] The name of the widget definition. Defaults to element's `data-widget`
  546. * attribute value.
  547. * @returns {CKEDITOR.dom.element/CKEDITOR.htmlParser.element} The wrapper element or `null` if
  548. * the widget definition of this name is not registered.
  549. */
  550. wrapElement: function( element, widgetName ) {
  551. var wrapper = null,
  552. widgetDef,
  553. isInline;
  554. if ( element instanceof CKEDITOR.dom.element ) {
  555. widgetDef = this.registered[ widgetName || element.data( 'widget' ) ];
  556. if ( !widgetDef )
  557. return null;
  558. // Do not wrap already wrapped element.
  559. wrapper = element.getParent();
  560. if ( wrapper && wrapper.type == CKEDITOR.NODE_ELEMENT && wrapper.data( 'cke-widget-wrapper' ) )
  561. return wrapper;
  562. // If attribute isn't already set (e.g. for pasted widget), set it.
  563. if ( !element.hasAttribute( 'data-cke-widget-keep-attr' ) )
  564. element.data( 'cke-widget-keep-attr', element.data( 'widget' ) ? 1 : 0 );
  565. if ( widgetName )
  566. element.data( 'widget', widgetName );
  567. isInline = isWidgetInline( widgetDef, element.getName() );
  568. wrapper = new CKEDITOR.dom.element( isInline ? 'span' : 'div' );
  569. wrapper.setAttributes( getWrapperAttributes( isInline ) );
  570. wrapper.data( 'cke-display-name', widgetDef.pathName ? widgetDef.pathName : element.getName() );
  571. // Replace element unless it is a detached one.
  572. if ( element.getParent( true ) )
  573. wrapper.replace( element );
  574. element.appendTo( wrapper );
  575. }
  576. else if ( element instanceof CKEDITOR.htmlParser.element ) {
  577. widgetDef = this.registered[ widgetName || element.attributes[ 'data-widget' ] ];
  578. if ( !widgetDef )
  579. return null;
  580. wrapper = element.parent;
  581. if ( wrapper && wrapper.type == CKEDITOR.NODE_ELEMENT && wrapper.attributes[ 'data-cke-widget-wrapper' ] )
  582. return wrapper;
  583. // If attribute isn't already set (e.g. for pasted widget), set it.
  584. if ( !( 'data-cke-widget-keep-attr' in element.attributes ) )
  585. element.attributes[ 'data-cke-widget-keep-attr' ] = element.attributes[ 'data-widget' ] ? 1 : 0;
  586. if ( widgetName )
  587. element.attributes[ 'data-widget' ] = widgetName;
  588. isInline = isWidgetInline( widgetDef, element.name );
  589. wrapper = new CKEDITOR.htmlParser.element( isInline ? 'span' : 'div', getWrapperAttributes( isInline ) );
  590. wrapper.attributes[ 'data-cke-display-name' ] = widgetDef.pathName ? widgetDef.pathName : element.name;
  591. var parent = element.parent,
  592. index;
  593. // Don't detach already detached element.
  594. if ( parent ) {
  595. index = element.getIndex();
  596. element.remove();
  597. }
  598. wrapper.add( element );
  599. // Insert wrapper fixing DOM (splitting parents if wrapper is not allowed inside them).
  600. parent && insertElement( parent, index, wrapper );
  601. }
  602. return wrapper;
  603. },
  604. // Expose for tests.
  605. _tests_createEditableFilter: createEditableFilter
  606. };
  607. CKEDITOR.event.implementOn( Repository.prototype );
  608. /**
  609. * An event fired when a widget instance is created, but before it is fully initialized.
  610. *
  611. * @event instanceCreated
  612. * @param {CKEDITOR.plugins.widget} data The widget instance.
  613. */
  614. /**
  615. * An event fired when a widget instance was destroyed.
  616. *
  617. * See also {@link CKEDITOR.plugins.widget#event-destroy}.
  618. *
  619. * @event instanceDestroyed
  620. * @param {CKEDITOR.plugins.widget} data The widget instance.
  621. */
  622. /**
  623. * An event fired to trigger the selection check.
  624. *
  625. * See the {@link #method-checkSelection} method.
  626. *
  627. * @event checkSelection
  628. */
  629. /**
  630. * An event fired by the the {@link #method-checkWidgets} method.
  631. *
  632. * It can be canceled in order to stop the {@link #method-checkWidgets}
  633. * method execution or the event listener can modify the method's options.
  634. *
  635. * @event checkWidgets
  636. * @param [data]
  637. * @param {Boolean} [data.initOnlyNew] Initialize widgets only on newly wrapped
  638. * widget elements (those which still have the `cke_widget_new` class). When this option is
  639. * set to `true`, widgets which were invalidated (e.g. by replacing with a cloned DOM structure)
  640. * will not be reinitialized. This makes the check faster.
  641. * @param {Boolean} [data.focusInited] If only one widget is initialized by
  642. * the method, it will be focused.
  643. */
  644. /**
  645. * An instance of a widget. Together with {@link CKEDITOR.plugins.widget.repository} these
  646. * two classes constitute the core of the Widget System.
  647. *
  648. * Note that neither the repository nor the widget instances can be created by using their constructors.
  649. * A repository instance is automatically set up by the Widget plugin and is accessible under
  650. * {@link CKEDITOR.editor#widgets}, while widget instances are created and destroyed by the repository.
  651. *
  652. * To create a widget, first you need to {@link CKEDITOR.plugins.widget.repository#add register} its
  653. * {@link CKEDITOR.plugins.widget.definition definition}:
  654. *
  655. * editor.widgets.add( 'simplebox', {
  656. * upcast: function( element ) {
  657. * // Defines which elements will become widgets.
  658. * if ( element.hasClass( 'simplebox' ) )
  659. * return true;
  660. * },
  661. * init: function() {
  662. * // ...
  663. * }
  664. * } );
  665. *
  666. * Once the widget definition is registered, widgets will be automatically
  667. * created when loading data:
  668. *
  669. * editor.setData( '<div class="simplebox">foo</div>', function() {
  670. * console.log( editor.widgets.instances ); // -> An object containing one instance.
  671. * } );
  672. *
  673. * It is also possible to create instances during runtime by using a command
  674. * (if a {@link CKEDITOR.plugins.widget.definition#template} property was defined):
  675. *
  676. * // You can execute an automatically defined command to
  677. * // insert a new simplebox widget or edit the one currently focused.
  678. * editor.execCommand( 'simplebox' );
  679. *
  680. * Note: Since CKEditor 4.5 widget's `startupData` can be passed as the command argument:
  681. *
  682. * editor.execCommand( 'simplebox', {
  683. * startupData: {
  684. * align: 'left'
  685. * }
  686. * } );
  687. *
  688. * A widget can also be created in a completely custom way:
  689. *
  690. * var element = editor.document.createElement( 'div' );
  691. * editor.insertElement( element );
  692. * var widget = editor.widgets.initOn( element, 'simplebox' );
  693. *
  694. * @since 4.3
  695. * @class CKEDITOR.plugins.widget
  696. * @mixins CKEDITOR.event
  697. * @extends CKEDITOR.plugins.widget.definition
  698. * @constructor Creates an instance of the widget class. Do not use it directly, but instead initialize widgets
  699. * by using the {@link CKEDITOR.plugins.widget.repository#initOn} method or by the upcasting system.
  700. * @param {CKEDITOR.plugins.widget.repository} widgetsRepo
  701. * @param {Number} id Unique ID of this widget instance.
  702. * @param {CKEDITOR.dom.element} element The widget element.
  703. * @param {CKEDITOR.plugins.widget.definition} widgetDef Widget's registered definition.
  704. * @param [startupData] Initial widget data. This data object will overwrite the default data and
  705. * the data loaded from the DOM.
  706. */
  707. function Widget( widgetsRepo, id, element, widgetDef, startupData ) {
  708. var editor = widgetsRepo.editor;
  709. // Extend this widget with widgetDef-specific methods and properties.
  710. CKEDITOR.tools.extend( this, widgetDef, {
  711. /**
  712. * The editor instance.
  713. *
  714. * @readonly
  715. * @property {CKEDITOR.editor}
  716. */
  717. editor: editor,
  718. /**
  719. * This widget's unique (per editor instance) ID.
  720. *
  721. * @readonly
  722. * @property {Number}
  723. */
  724. id: id,
  725. /**
  726. * Whether this widget is an inline widget (based on an inline element unless
  727. * forced otherwise by {@link CKEDITOR.plugins.widget.definition#inline}).
  728. *
  729. * **Note:** This option does not allow to turn a block element into an inline widget.
  730. * However, it makes it possible to turn an inline element into a block widget or to
  731. * force a correct type in case when automatic recognition fails.
  732. *
  733. * @readonly
  734. * @property {Boolean}
  735. */
  736. inline: element.getParent().getName() == 'span',
  737. /**
  738. * The widget element &mdash; the element on which the widget was initialized.
  739. *
  740. * @readonly
  741. * @property {CKEDITOR.dom.element} element
  742. */
  743. element: element,
  744. /**
  745. * Widget's data object.
  746. *
  747. * The data can only be set by using the {@link #setData} method.
  748. * Changes made to the data fire the {@link #event-data} event.
  749. *
  750. * @readonly
  751. */
  752. data: CKEDITOR.tools.extend( {}, typeof widgetDef.defaults == 'function' ? widgetDef.defaults() : widgetDef.defaults ),
  753. /**
  754. * Indicates if a widget is data-ready. Set to `true` when data from all sources
  755. * ({@link CKEDITOR.plugins.widget.definition#defaults}, set in the
  756. * {@link #init} method, loaded from the widget's element and startup data coming from the constructor)
  757. * are finally loaded. This is immediately followed by the first {@link #event-data}.
  758. *
  759. * @readonly
  760. */
  761. dataReady: false,
  762. /**
  763. * Whether a widget instance was initialized. This means that:
  764. *
  765. * * An instance was created,
  766. * * Its properties were set,
  767. * * The `init` method was executed.
  768. *
  769. * **Note**: The first {@link #event-data} event could not be fired yet which
  770. * means that the widget's DOM has not been set up yet. Wait for the {@link #event-ready}
  771. * event to be notified when a widget is fully initialized and ready.
  772. *
  773. * **Note**: Use the {@link #isInited} method to check whether a widget is initialized and
  774. * has not been destroyed.
  775. *
  776. * @readonly
  777. */
  778. inited: false,
  779. /**
  780. * Whether a widget instance is ready. This means that the widget is {@link #inited} and
  781. * that its DOM was finally set up.
  782. *
  783. * **Note:** Use the {@link #isReady} method to check whether a widget is ready and
  784. * has not been destroyed.
  785. *
  786. * @readonly
  787. */
  788. ready: false,
  789. // Revert what widgetDef could override (automatic #edit listener).
  790. edit: Widget.prototype.edit,
  791. /**
  792. * The nested editable element which is currently focused.
  793. *
  794. * @readonly
  795. * @property {CKEDITOR.plugins.widget.nestedEditable}
  796. */
  797. focusedEditable: null,
  798. /**
  799. * The widget definition from which this instance was created.
  800. *
  801. * @readonly
  802. * @property {CKEDITOR.plugins.widget.definition} definition
  803. */
  804. definition: widgetDef,
  805. /**
  806. * Link to the widget repository which created this instance.
  807. *
  808. * @readonly
  809. * @property {CKEDITOR.plugins.widget.repository} repository
  810. */
  811. repository: widgetsRepo,
  812. draggable: widgetDef.draggable !== false,
  813. // WAAARNING: Overwrite widgetDef's priv object, because otherwise violent unicorn's gonna visit you.
  814. _: {
  815. downcastFn: ( widgetDef.downcast && typeof widgetDef.downcast == 'string' ) ?
  816. widgetDef.downcasts[ widgetDef.downcast ] : widgetDef.downcast
  817. }
  818. }, true );
  819. /**
  820. * An object of widget component elements.
  821. *
  822. * For every `partName => selector` pair in {@link CKEDITOR.plugins.widget.definition#parts},
  823. * one `partName => element` pair is added to this object during the widget initialization.
  824. *
  825. * @readonly
  826. * @property {Object} parts
  827. */
  828. /**
  829. * The template which will be used to create a new widget element (when the widget's command is executed).
  830. * It will be populated with {@link #defaults default values}.
  831. *
  832. * @readonly
  833. * @property {CKEDITOR.template} template
  834. */
  835. /**
  836. * The widget wrapper &mdash; a non-editable `div` or `span` element (depending on {@link #inline})
  837. * which is a parent of the {@link #element} and widget compontents like the drag handler and the {@link #mask}.
  838. * It is the outermost widget element.
  839. *
  840. * @readonly
  841. * @property {CKEDITOR.dom.element} wrapper
  842. */
  843. widgetsRepo.fire( 'instanceCreated', this );
  844. setupWidget( this, widgetDef );
  845. this.init && this.init();
  846. // Finally mark widget as inited.
  847. this.inited = true;
  848. setupWidgetData( this, startupData );
  849. // If at some point (e.g. in #data listener) widget hasn't been destroyed
  850. // and widget is already attached to document then fire #ready.
  851. if ( this.isInited() && editor.editable().contains( this.wrapper ) ) {
  852. this.ready = true;
  853. this.fire( 'ready' );
  854. }
  855. }
  856. Widget.prototype = {
  857. /**
  858. * Adds a class to the widget element. This method is used by
  859. * the {@link #applyStyle} method and should be overriden by widgets
  860. * which should handle classes differently (e.g. add them to other elements).
  861. *
  862. * **Note**: This method should not be used directly. Use the {@link #setData} method to
  863. * set the `classes` property. Read more in the {@link #setData} documentation.
  864. *
  865. * See also: {@link #removeClass}, {@link #hasClass}, {@link #getClasses}.
  866. *
  867. * @since 4.4
  868. * @param {String} className The class name to be added.
  869. */
  870. addClass: function( className ) {
  871. this.element.addClass( className );
  872. },
  873. /**
  874. * Applies the specified style to the widget. It is highly recommended to use the
  875. * {@link CKEDITOR.editor#applyStyle} or {@link CKEDITOR.style#apply} methods instead of
  876. * using this method directly, because unlike editor's and style's methods, this one
  877. * does not perform any checks.
  878. *
  879. * By default this method handles only classes defined in the style. It clones existing
  880. * classes which are stored in the {@link #property-data widget data}'s `classes` property,
  881. * adds new classes, and calls the {@link #setData} method if at least one new class was added.
  882. * Then, using the {@link #event-data} event listener widget applies modifications passing
  883. * new classes to the {@link #addClass} method.
  884. *
  885. * If you need to handle classes differently than in the default way, you can override the
  886. * {@link #addClass} and related methods. You can also handle other style properties than `classes`
  887. * by overriding this method.
  888. *
  889. * See also: {@link #checkStyleActive}, {@link #removeStyle}.
  890. *
  891. * @since 4.4
  892. * @param {CKEDITOR.style} style The custom widget style to be applied.
  893. */
  894. applyStyle: function( style ) {
  895. applyRemoveStyle( this, style, 1 );
  896. },
  897. /**
  898. * Checks if the specified style is applied to this widget. It is highly recommended to use the
  899. * {@link CKEDITOR.style#checkActive} method instead of using this method directly,
  900. * because unlike style's method, this one does not perform any checks.
  901. *
  902. * By default this method handles only classes defined in the style and passes
  903. * them to the {@link #hasClass} method. You can override these methods to handle classes
  904. * differently or to handle more of the style properties.
  905. *
  906. * See also: {@link #applyStyle}, {@link #removeStyle}.
  907. *
  908. * @since 4.4
  909. * @param {CKEDITOR.style} style The custom widget style to be checked.
  910. * @returns {Boolean} Whether the style is applied to this widget.
  911. */
  912. checkStyleActive: function( style ) {
  913. var classes = getStyleClasses( style ),
  914. cl;
  915. if ( !classes )
  916. return false;
  917. while ( ( cl = classes.pop() ) ) {
  918. if ( !this.hasClass( cl ) )
  919. return false;
  920. }
  921. return true;
  922. },
  923. /**
  924. * Destroys this widget instance.
  925. *
  926. * Use {@link CKEDITOR.plugins.widget.repository#destroy} when possible instead of this method.
  927. *
  928. * This method fires the {#event-destroy} event.
  929. *
  930. * @param {Boolean} [offline] Whether a widget is offline (detached from the DOM tree) &mdash;
  931. * in this case the DOM (attributes, classes, etc.) will not be cleaned up.
  932. */
  933. destroy: function( offline ) {
  934. this.fire( 'destroy' );
  935. if ( this.editables ) {
  936. for ( var name in this.editables )
  937. this.destroyEditable( name, offline );
  938. }
  939. if ( !offline ) {
  940. if ( this.element.data( 'cke-widget-keep-attr' ) == '0' )
  941. this.element.removeAttribute( 'data-widget' );
  942. this.element.removeAttributes( [ 'data-cke-widget-data', 'data-cke-widget-keep-attr' ] );
  943. this.element.removeClass( 'cke_widget_element' );
  944. this.element.replace( this.wrapper );
  945. }
  946. this.wrapper = null;
  947. },
  948. /**
  949. * Destroys a nested editable and all nested widgets.
  950. *
  951. * @param {String} editableName Nested editable name.
  952. * @param {Boolean} [offline] See {@link #method-destroy} method.
  953. */
  954. destroyEditable: function( editableName, offline ) {
  955. var editable = this.editables[ editableName ];
  956. editable.removeListener( 'focus', onEditableFocus );
  957. editable.removeListener( 'blur', onEditableBlur );
  958. this.editor.focusManager.remove( editable );
  959. if ( !offline ) {
  960. this.repository.destroyAll( false, editable );
  961. editable.removeClass( 'cke_widget_editable' );
  962. editable.removeClass( 'cke_widget_editable_focused' );
  963. editable.removeAttributes( [ 'contenteditable', 'data-cke-widget-editable', 'data-cke-enter-mode' ] );
  964. }
  965. delete this.editables[ editableName ];
  966. },
  967. /**
  968. * Starts widget editing.
  969. *
  970. * This method fires the {@link CKEDITOR.plugins.widget#event-edit} event
  971. * which may be canceled in order to prevent it from opening a dialog window.
  972. *
  973. * The dialog window name is obtained from the event's data `dialog` property or
  974. * from {@link CKEDITOR.plugins.widget.definition#dialog}.
  975. *
  976. * @returns {Boolean} Returns `true` if a dialog window was opened.
  977. */
  978. edit: function() {
  979. var evtData = { dialog: this.dialog },
  980. that = this;
  981. // Edit event was blocked or there's no dialog to be automatically opened.
  982. if ( this.fire( 'edit', evtData ) === false || !evtData.dialog )
  983. return false;
  984. this.editor.openDialog( evtData.dialog, function( dialog ) {
  985. var showListener,
  986. okListener;
  987. // Allow to add a custom dialog handler.
  988. if ( that.fire( 'dialog', dialog ) === false )
  989. return;
  990. showListener = dialog.on( 'show', function() {
  991. dialog.setupContent( that );
  992. } );
  993. okListener = dialog.on( 'ok', function() {
  994. // Commit dialog's fields, but prevent from
  995. // firing data event for every field. Fire only one,
  996. // bulk event at the end.
  997. var dataChanged,
  998. dataListener = that.on( 'data', function( evt ) {
  999. dataChanged = 1;
  1000. evt.cancel();
  1001. }, null, null, 0 );
  1002. // Create snapshot preceeding snapshot with changed widget...
  1003. // TODO it should not be required, but it is and I found similar
  1004. // code in dialog#ok listener in dialog/plugin.js.
  1005. that.editor.fire( 'saveSnapshot' );
  1006. dialog.commitContent( that );
  1007. dataListener.removeListener();
  1008. if ( dataChanged ) {
  1009. that.fire( 'data', that.data );
  1010. that.editor.fire( 'saveSnapshot' );
  1011. }
  1012. } );
  1013. dialog.once( 'hide', function() {
  1014. showListener.removeListener();
  1015. okListener.removeListener();
  1016. } );
  1017. } );
  1018. return true;
  1019. },
  1020. /**
  1021. * Returns widget element classes parsed to an object. This method
  1022. * is used to populate the `classes` property of widget's {@link #property-data}.
  1023. *
  1024. * This method reuses {@link CKEDITOR.plugins.widget.repository#parseElementClasses}.
  1025. * It should be overriden if a widget should handle classes differently (e.g. on other elements).
  1026. *
  1027. * See also: {@link #removeClass}, {@link #addClass}, {@link #hasClass}.
  1028. *
  1029. * @since 4.4
  1030. * @returns {Object}
  1031. */
  1032. getClasses: function() {
  1033. return this.repository.parseElementClasses( this.element.getAttribute( 'class' ) );
  1034. },
  1035. /**
  1036. * Checks if the widget element has specified class. This method is used by
  1037. * the {@link #checkStyleActive} method and should be overriden by widgets
  1038. * which should handle classes differently (e.g. on other elements).
  1039. *
  1040. * See also: {@link #removeClass}, {@link #addClass}, {@link #getClasses}.
  1041. *
  1042. * @since 4.4
  1043. * @param {String} className The class to be checked.
  1044. * @param {Boolean} Whether a widget has specified class.
  1045. */
  1046. hasClass: function( className ) {
  1047. return this.element.hasClass( className );
  1048. },
  1049. /**
  1050. * Initializes a nested editable.
  1051. *
  1052. * **Note**: Only elements from {@link CKEDITOR.dtd#$editable} may become editables.
  1053. *
  1054. * @param {String} editableName The nested editable name.
  1055. * @param {CKEDITOR.plugins.widget.nestedEditable.definition} definition The definition of the nested editable.
  1056. * @returns {Boolean} Whether an editable was successfully initialized.
  1057. */
  1058. initEditable: function( editableName, definition ) {
  1059. // Don't fetch just first element which matched selector but look for a correct one. (#13334)
  1060. var editable = this._findOneNotNested( definition.selector );
  1061. if ( editable && editable.is( CKEDITOR.dtd.$editable ) ) {
  1062. editable = new NestedEditable( this.editor, editable, {
  1063. filter: createEditableFilter.call( this.repository, this.name, editableName, definition )
  1064. } );
  1065. this.editables[ editableName ] = editable;
  1066. editable.setAttributes( {
  1067. contenteditable: 'true',
  1068. 'data-cke-widget-editable': editableName,
  1069. 'data-cke-enter-mode': editable.enterMode
  1070. } );
  1071. if ( editable.filter )
  1072. editable.data( 'cke-filter', editable.filter.id );
  1073. editable.addClass( 'cke_widget_editable' );
  1074. // This class may be left when d&ding widget which
  1075. // had focused editable. Clean this class here, not in
  1076. // cleanUpWidgetElement for performance and code size reasons.
  1077. editable.removeClass( 'cke_widget_editable_focused' );
  1078. if ( definition.pathName )
  1079. editable.data( 'cke-display-name', definition.pathName );
  1080. this.editor.focusManager.add( editable );
  1081. editable.on( 'focus', onEditableFocus, this );
  1082. CKEDITOR.env.ie && editable.on( 'blur', onEditableBlur, this );
  1083. // Finally, process editable's data. This data wasn't processed when loading
  1084. // editor's data, becuase they need to be processed separately, with its own filters and settings.
  1085. editable._.initialSetData = true;
  1086. editable.setData( editable.getHtml() );
  1087. return true;
  1088. }
  1089. return false;
  1090. },
  1091. /**
  1092. * Looks inside wrapper element to find a node that
  1093. * matches given selector and is not nested in other widget. (#13334)
  1094. *
  1095. * @since 4.5
  1096. * @private
  1097. * @param {String} selector Selector to match.
  1098. * @returns {CKEDITOR.dom.element} Matched element or `null` if a node has not been found.
  1099. */
  1100. _findOneNotNested: function( selector ) {
  1101. var matchedElements = this.wrapper.find( selector ),
  1102. match,
  1103. closestWrapper;
  1104. for ( var i = 0; i < matchedElements.count(); i++ ) {
  1105. match = matchedElements.getItem( i );
  1106. closestWrapper = match.getAscendant( Widget.isDomWidgetWrapper );
  1107. // The closest ascendant-wrapper of this match defines to which widget
  1108. // this match belongs. If the ascendant is this widget's wrapper
  1109. // it means that the match is not nested in other widget.
  1110. if ( this.wrapper.equals( closestWrapper ) ) {
  1111. return match;
  1112. }
  1113. }
  1114. return null;
  1115. },
  1116. /**
  1117. * Checks if a widget has already been initialized and has not been destroyed yet.
  1118. *
  1119. * See {@link #inited} for more details.
  1120. *
  1121. * @returns {Boolean}
  1122. */
  1123. isInited: function() {
  1124. return !!( this.wrapper && this.inited );
  1125. },
  1126. /**
  1127. * Checks if a widget is ready and has not been destroyed yet.
  1128. *
  1129. * See {@link #property-ready} for more details.
  1130. *
  1131. * @returns {Boolean}
  1132. */
  1133. isReady: function() {
  1134. return this.isInited() && this.ready;
  1135. },
  1136. /**
  1137. * Focuses a widget by selecting it.
  1138. */
  1139. focus: function() {
  1140. var sel = this.editor.getSelection();
  1141. // Fake the selection before focusing editor, to avoid unpreventable viewports scrolling
  1142. // on Webkit/Blink/IE which is done because there's no selection or selection was somewhere else than widget.
  1143. if ( sel ) {
  1144. var isDirty = this.editor.checkDirty();
  1145. sel.fake( this.wrapper );
  1146. !isDirty && this.editor.resetDirty();
  1147. }
  1148. // Always focus editor (not only when focusManger.hasFocus is false) (because of #10483).
  1149. this.editor.focus();
  1150. },
  1151. /**
  1152. * Removes a class from the widget element. This method is used by
  1153. * the {@link #removeStyle} method and should be overriden by widgets
  1154. * which should handle classes differently (e.g. on other elements).
  1155. *
  1156. * **Note**: This method should not be used directly. Use the {@link #setData} method to
  1157. * set the `classes` property. Read more in the {@link #setData} documentation.
  1158. *
  1159. * See also: {@link #hasClass}, {@link #addClass}.
  1160. *
  1161. * @since 4.4
  1162. * @param {String} className The class to be removed.
  1163. */
  1164. removeClass: function( className ) {
  1165. this.element.removeClass( className );
  1166. },
  1167. /**
  1168. * Removes the specified style from the widget. It is highly recommended to use the
  1169. * {@link CKEDITOR.editor#removeStyle} or {@link CKEDITOR.style#remove} methods instead of
  1170. * using this method directly, because unlike editor's and style's methods, this one
  1171. * does not perform any checks.
  1172. *
  1173. * Read more about how applying/removing styles works in the {@link #applyStyle} method documentation.
  1174. *
  1175. * See also {@link #checkStyleActive}, {@link #applyStyle}, {@link #getClasses}.
  1176. *
  1177. * @since 4.4
  1178. * @param {CKEDITOR.style} style The custom widget style to be removed.
  1179. */
  1180. removeStyle: function( style ) {
  1181. applyRemoveStyle( this, style, 0 );
  1182. },
  1183. /**
  1184. * Sets widget value(s) in the {@link #property-data} object.
  1185. * If the given value(s) modifies current ones, the {@link #event-data} event is fired.
  1186. *
  1187. * this.setData( 'align', 'left' );
  1188. * this.data.align; // -> 'left'
  1189. *
  1190. * this.setData( { align: 'right', opened: false } );
  1191. * this.data.align; // -> 'right'
  1192. * this.data.opened; // -> false
  1193. *
  1194. * Set values are stored in {@link #element}'s attribute (`data-cke-widget-data`),
  1195. * in a JSON string, therefore {@link #property-data} should contain
  1196. * only serializable data.
  1197. *
  1198. * **Note:** A special data property, `classes`, exists. It contains an object with
  1199. * classes which were returned by the {@link #getClasses} method during the widget initialization.
  1200. * This property is then used by the {@link #applyStyle} and {@link #removeStyle} methods.
  1201. * When it is changed (the reference to object must be changed!), the widget updates its classes by
  1202. * using the {@link #addClass} and {@link #removeClass} methods.
  1203. *
  1204. * // Adding a new class.
  1205. * var classes = CKEDITOR.tools.clone( widget.data.classes );
  1206. * classes.newClass = 1;
  1207. * widget.setData( 'classes', classes );
  1208. *
  1209. * // Removing a class.
  1210. * var classes = CKEDITOR.tools.clone( widget.data.classes );
  1211. * delete classes.newClass;
  1212. * widget.setData( 'classes', classes );
  1213. *
  1214. * @param {String/Object} keyOrData
  1215. * @param {Object} value
  1216. * @chainable
  1217. */
  1218. setData: function( key, value ) {
  1219. var data = this.data,
  1220. modified = 0;
  1221. if ( typeof key == 'string' ) {
  1222. if ( data[ key ] !== value ) {
  1223. data[ key ] = value;
  1224. modified = 1;
  1225. }
  1226. }
  1227. else {
  1228. var newData = key;
  1229. for ( key in newData ) {
  1230. if ( data[ key ] !== newData[ key ] ) {
  1231. modified = 1;
  1232. data[ key ] = newData[ key ];
  1233. }
  1234. }
  1235. }
  1236. // Block firing data event and overwriting data element before setupWidgetData is executed.
  1237. if ( modified && this.dataReady ) {
  1238. writeDataToElement( this );
  1239. this.fire( 'data', data );
  1240. }
  1241. return this;
  1242. },
  1243. /**
  1244. * Changes the widget's focus state. This method is executed automatically after
  1245. * a widget was focused by the {@link #method-focus} method or the selection was moved
  1246. * out of the widget.
  1247. *
  1248. * This is a low-level method which is not integrated with e.g. the undo manager.
  1249. * Use the {@link #method-focus} method instead.
  1250. *
  1251. * @param {Boolean} selected Whether to select or deselect this widget.
  1252. * @chainable
  1253. */
  1254. setFocused: function( focused ) {
  1255. this.wrapper[ focused ? 'addClass' : 'removeClass' ]( 'cke_widget_focused' );
  1256. this.fire( focused ? 'focus' : 'blur' );
  1257. return this;
  1258. },
  1259. /**
  1260. * Changes the widget's select state. This method is executed automatically after
  1261. * a widget was selected by the {@link #method-focus} method or the selection
  1262. * was moved out of the widget.
  1263. *
  1264. * This is a low-level method which is not integrated with e.g. the undo manager.
  1265. * Use the {@link #method-focus} method instead or simply change the selection.
  1266. *
  1267. * @param {Boolean} selected Whether to select or deselect this widget.
  1268. * @chainable
  1269. */
  1270. setSelected: function( selected ) {
  1271. this.wrapper[ selected ? 'addClass' : 'removeClass' ]( 'cke_widget_selected' );
  1272. this.fire( selected ? 'select' : 'deselect' );
  1273. return this;
  1274. },
  1275. /**
  1276. * Repositions drag handler according to the widget's element position. Should be called from events, like mouseover.
  1277. */
  1278. updateDragHandlerPosition: function() {
  1279. var editor = this.editor,
  1280. domElement = this.element.$,
  1281. oldPos = this._.dragHandlerOffset,
  1282. newPos = {
  1283. x: domElement.offsetLeft,
  1284. y: domElement.offsetTop - DRAG_HANDLER_SIZE
  1285. };
  1286. if ( oldPos && newPos.x == oldPos.x && newPos.y == oldPos.y )
  1287. return;
  1288. // We need to make sure that dirty state is not changed (#11487).
  1289. var initialDirty = editor.checkDirty();
  1290. editor.fire( 'lockSnapshot' );
  1291. this.dragHandlerContainer.setStyles( {
  1292. top: newPos.y + 'px',
  1293. left: newPos.x + 'px',
  1294. display: 'block'
  1295. } );
  1296. editor.fire( 'unlockSnapshot' );
  1297. !initialDirty && editor.resetDirty();
  1298. this._.dragHandlerOffset = newPos;
  1299. }
  1300. };
  1301. CKEDITOR.event.implementOn( Widget.prototype );
  1302. /**
  1303. * Gets the {@link #isDomNestedEditable nested editable}
  1304. * (returned as a {@link CKEDITOR.dom.element}, not as a {@link CKEDITOR.plugins.widget.nestedEditable})
  1305. * closest to the `node` or the `node` if it is a nested editable itself.
  1306. *
  1307. * @since 4.5
  1308. * @static
  1309. * @param {CKEDITOR.dom.element} guard Stop ancestor search on this node (usually editor's editable).
  1310. * @param {CKEDITOR.dom.node} node Start the search from this node.
  1311. * @returns {CKEDITOR.dom.element/null} Element or `null` if not found.
  1312. */
  1313. Widget.getNestedEditable = function( guard, node ) {
  1314. if ( !node || node.equals( guard ) )
  1315. return null;
  1316. if ( Widget.isDomNestedEditable( node ) )
  1317. return node;
  1318. return Widget.getNestedEditable( guard, node.getParent() );
  1319. };
  1320. /**
  1321. * Checks whether the `node` is a widget's drag handle element.
  1322. *
  1323. * @since 4.5
  1324. * @static
  1325. * @param {CKEDITOR.dom.node} node
  1326. * @returns {Boolean}
  1327. */
  1328. Widget.isDomDragHandler = function( node ) {
  1329. return node.type == CKEDITOR.NODE_ELEMENT && node.hasAttribute( 'data-cke-widget-drag-handler' );
  1330. };
  1331. /**
  1332. * Checks whether the `node` is a container of the widget's drag handle element.
  1333. *
  1334. * @since 4.5
  1335. * @static
  1336. * @param {CKEDITOR.dom.node} node
  1337. * @returns {Boolean}
  1338. */
  1339. Widget.isDomDragHandlerContainer = function( node ) {
  1340. return node.type == CKEDITOR.NODE_ELEMENT && node.hasClass( 'cke_widget_drag_handler_container' );
  1341. };
  1342. /**
  1343. * Checks whether the `node` is a {@link CKEDITOR.plugins.widget#editables nested editable}.
  1344. * Note that this function only checks whether it is the right element, not whether
  1345. * the passed `node` is an instance of {@link CKEDITOR.plugins.widget.nestedEditable}.
  1346. *
  1347. * @since 4.5
  1348. * @static
  1349. * @param {CKEDITOR.dom.node} node
  1350. * @returns {Boolean}
  1351. */
  1352. Widget.isDomNestedEditable = function( node ) {
  1353. return node.type == CKEDITOR.NODE_ELEMENT && node.hasAttribute( 'data-cke-widget-editable' );
  1354. };
  1355. /**
  1356. * Checks whether the `node` is a {@link CKEDITOR.plugins.widget#element widget element}.
  1357. *
  1358. * @since 4.5
  1359. * @static
  1360. * @param {CKEDITOR.dom.node} node
  1361. * @returns {Boolean}
  1362. */
  1363. Widget.isDomWidgetElement = function( node ) {
  1364. return node.type == CKEDITOR.NODE_ELEMENT && node.hasAttribute( 'data-widget' );
  1365. };
  1366. /**
  1367. * Checks whether the `node` is a {@link CKEDITOR.plugins.widget#wrapper widget wrapper}.
  1368. *
  1369. * @since 4.5
  1370. * @static
  1371. * @param {CKEDITOR.dom.element} node
  1372. * @returns {Boolean}
  1373. */
  1374. Widget.isDomWidgetWrapper = function( node ) {
  1375. return node.type == CKEDITOR.NODE_ELEMENT && node.hasAttribute( 'data-cke-widget-wrapper' );
  1376. };
  1377. /**
  1378. * Checks whether the `node` is a {@link CKEDITOR.plugins.widget#element widget element}.
  1379. *
  1380. * @since 4.5
  1381. * @static
  1382. * @param {CKEDITOR.htmlParser.node} node
  1383. * @returns {Boolean}
  1384. */
  1385. Widget.isParserWidgetElement = function( node ) {
  1386. return node.type == CKEDITOR.NODE_ELEMENT && !!node.attributes[ 'data-widget' ];
  1387. };
  1388. /**
  1389. * Checks whether the `node` is a {@link CKEDITOR.plugins.widget#wrapper widget wrapper}.
  1390. *
  1391. * @since 4.5
  1392. * @static
  1393. * @param {CKEDITOR.htmlParser.element} node
  1394. * @returns {Boolean}
  1395. */
  1396. Widget.isParserWidgetWrapper = function( node ) {
  1397. return node.type == CKEDITOR.NODE_ELEMENT && !!node.attributes[ 'data-cke-widget-wrapper' ];
  1398. };
  1399. /**
  1400. * An event fired when a widget is ready (fully initialized). This event is fired after:
  1401. *
  1402. * * {@link #init} is called,
  1403. * * The first {@link #event-data} event is fired,
  1404. * * A widget is attached to the document.
  1405. *
  1406. * Therefore, in case of widget creation with a command which opens a dialog window, this event
  1407. * will be delayed after the dialog window is closed and the widget is finally inserted into the document.
  1408. *
  1409. * **Note**: If your widget does not use automatic dialog window binding (i.e. you open the dialog window manually)
  1410. * or another situation in which the widget wrapper is not attached to document at the time when it is
  1411. * initialized occurs, you need to take care of firing {@link #event-ready} yourself.
  1412. *
  1413. * See also {@link #property-ready} and {@link #property-inited} properties, and
  1414. * {@link #isReady} and {@link #isInited} methods.
  1415. *
  1416. * @event ready
  1417. */
  1418. /**
  1419. * An event fired when a widget is about to be destroyed, but before it is
  1420. * fully torn down.
  1421. *
  1422. * @event destroy
  1423. */
  1424. /**
  1425. * An event fired when a widget is focused.
  1426. *
  1427. * Widget can be focused by executing {@link #method-focus}.
  1428. *
  1429. * @event focus
  1430. */
  1431. /**
  1432. * An event fired when a widget is blurred.
  1433. *
  1434. * @event blur
  1435. */
  1436. /**
  1437. * An event fired when a widget is selected.
  1438. *
  1439. * @event select
  1440. */
  1441. /**
  1442. * An event fired when a widget is deselected.
  1443. *
  1444. * @event deselect
  1445. */
  1446. /**
  1447. * An event fired by the {@link #method-edit} method. It can be canceled
  1448. * in order to stop the default action (opening a dialog window and/or
  1449. * {@link CKEDITOR.plugins.widget.repository#finalizeCreation finalizing widget creation}).
  1450. *
  1451. * @event edit
  1452. * @param data
  1453. * @param {String} data.dialog Defaults to {@link CKEDITOR.plugins.widget.definition#dialog}
  1454. * and can be changed or set by the listener.
  1455. */
  1456. /**
  1457. * An event fired when a dialog window for widget editing is opened.
  1458. * This event can be canceled in order to handle the editing dialog in a custom manner.
  1459. *
  1460. * @event dialog
  1461. * @param {CKEDITOR.dialog} data The opened dialog window instance.
  1462. */
  1463. /**
  1464. * An event fired when a key is pressed on a focused widget.
  1465. * This event is forwarded from the {@link CKEDITOR.editor#key} event and
  1466. * has the ability to block editor keystrokes if it is canceled.
  1467. *
  1468. * @event key
  1469. * @param data
  1470. * @param {Number} data.keyCode A number representing the key code (or combination).
  1471. */
  1472. /**
  1473. * An event fired when a widget is double clicked.
  1474. *
  1475. * **Note:** If a default editing action is executed on double click (i.e. a widget has a
  1476. * {@link CKEDITOR.plugins.widget.definition#dialog dialog} defined and the {@link #event-doubleclick} event was not
  1477. * canceled), this event will be automatically canceled, so a listener added with the default priority (10)
  1478. * will not be executed. Use a listener with low priority (e.g. 5) to be sure that it will be executed.
  1479. *
  1480. * widget.on( 'doubleclick', function( evt ) {
  1481. * console.log( 'widget#doubleclick' );
  1482. * }, null, null, 5 );
  1483. *
  1484. * If your widget handles double click in a special way (so the default editing action is not executed),
  1485. * make sure you cancel this event, because otherwise it will be propagated to {@link CKEDITOR.editor#doubleclick}
  1486. * and another feature may step in (e.g. a Link dialog window may be opened if your widget was inside a link).
  1487. *
  1488. * @event doubleclick
  1489. * @param data
  1490. * @param {CKEDITOR.dom.element} data.element The double-clicked element.
  1491. */
  1492. /**
  1493. * An event fired when the context menu is opened for a widget.
  1494. *
  1495. * @event contextMenu
  1496. * @param data The object containing context menu options to be added
  1497. * for this widget. See {@link CKEDITOR.plugins.contextMenu#addListener}.
  1498. */
  1499. /**
  1500. * An event fired when the widget data changed. See the {@link #setData} method and the {@link #property-data} property.
  1501. *
  1502. * @event data
  1503. */
  1504. /**
  1505. * The wrapper class for editable elements inside widgets.
  1506. *
  1507. * Do not use directly. Use {@link CKEDITOR.plugins.widget.definition#editables} or
  1508. * {@link CKEDITOR.plugins.widget#initEditable}.
  1509. *
  1510. * @class CKEDITOR.plugins.widget.nestedEditable
  1511. * @extends CKEDITOR.dom.element
  1512. * @constructor
  1513. * @param {CKEDITOR.editor} editor
  1514. * @param {CKEDITOR.dom.element} element
  1515. * @param config
  1516. * @param {CKEDITOR.filter} [config.filter]
  1517. */
  1518. function NestedEditable( editor, element, config ) {
  1519. // Call the base constructor.
  1520. CKEDITOR.dom.element.call( this, element.$ );
  1521. this.editor = editor;
  1522. this._ = {};
  1523. var filter = this.filter = config.filter;
  1524. // If blockless editable - always use BR mode.
  1525. if ( !CKEDITOR.dtd[ this.getName() ].p )
  1526. this.enterMode = this.shiftEnterMode = CKEDITOR.ENTER_BR;
  1527. else {
  1528. this.enterMode = filter ? filter.getAllowedEnterMode( editor.enterMode ) : editor.enterMode;
  1529. this.shiftEnterMode = filter ? filter.getAllowedEnterMode( editor.shiftEnterMode, true ) : editor.shiftEnterMode;
  1530. }
  1531. }
  1532. NestedEditable.prototype = CKEDITOR.tools.extend( CKEDITOR.tools.prototypedCopy( CKEDITOR.dom.element.prototype ), {
  1533. /**
  1534. * Sets the editable data. The data will be passed through the {@link CKEDITOR.editor#dataProcessor}
  1535. * and the {@link CKEDITOR.editor#filter}. This ensures that the data was filtered and prepared to be
  1536. * edited like the {@link CKEDITOR.editor#method-setData editor data}.
  1537. *
  1538. * Before content is changed, all nested widgets are destroyed. Afterwards, after new content is loaded,
  1539. * all nested widgets are initialized.
  1540. *
  1541. * @param {String} data
  1542. */
  1543. setData: function( data ) {
  1544. // For performance reasons don't call destroyAll when initializing a nested editable,
  1545. // because there are no widgets inside.
  1546. if ( !this._.initialSetData ) {
  1547. // Destroy all nested widgets before setting data.
  1548. this.editor.widgets.destroyAll( false, this );
  1549. }
  1550. this._.initialSetData = false;
  1551. data = this.editor.dataProcessor.toHtml( data, {
  1552. context: this.getName(),
  1553. filter: this.filter,
  1554. enterMode: this.enterMode
  1555. } );
  1556. this.setHtml( data );
  1557. this.editor.widgets.initOnAll( this );
  1558. },
  1559. /**
  1560. * Gets the editable data. Like {@link #setData}, this method will process and filter the data.
  1561. *
  1562. * @returns {String}
  1563. */
  1564. getData: function() {
  1565. return this.editor.dataProcessor.toDataFormat( this.getHtml(), {
  1566. context: this.getName(),
  1567. filter: this.filter,
  1568. enterMode: this.enterMode
  1569. } );
  1570. }
  1571. } );
  1572. /**
  1573. * The editor instance.
  1574. *
  1575. * @readonly
  1576. * @property {CKEDITOR.editor} editor
  1577. */
  1578. /**
  1579. * The filter instance if allowed content rules were defined.
  1580. *
  1581. * @readonly
  1582. * @property {CKEDITOR.filter} filter
  1583. */
  1584. /**
  1585. * The enter mode active in this editable.
  1586. * It is determined from editable's name (whether it is a blockless editable),
  1587. * its allowed content rules (if defined) and the default editor's mode.
  1588. *
  1589. * @readonly
  1590. * @property {Number} enterMode
  1591. */
  1592. /**
  1593. * The shift enter move active in this editable.
  1594. *
  1595. * @readonly
  1596. * @property {Number} shiftEnterMode
  1597. */
  1598. //
  1599. // REPOSITORY helpers -----------------------------------------------------
  1600. //
  1601. function addWidgetButtons( editor ) {
  1602. var widgets = editor.widgets.registered,
  1603. widget,
  1604. widgetName,
  1605. widgetButton;
  1606. for ( widgetName in widgets ) {
  1607. widget = widgets[ widgetName ];
  1608. // Create button if defined.
  1609. widgetButton = widget.button;
  1610. if ( widgetButton && editor.ui.addButton ) {
  1611. editor.ui.addButton( CKEDITOR.tools.capitalize( widget.name, true ), {
  1612. label: widgetButton,
  1613. command: widget.name,
  1614. toolbar: 'insert,10'
  1615. } );
  1616. }
  1617. }
  1618. }
  1619. // Create a command creating and editing widget.
  1620. //
  1621. // @param editor
  1622. // @param {CKEDITOR.plugins.widget.definition} widgetDef
  1623. function addWidgetCommand( editor, widgetDef ) {
  1624. editor.addCommand( widgetDef.name, {
  1625. exec: function( editor, commandData ) {
  1626. var focused = editor.widgets.focused;
  1627. // If a widget of the same type is focused, start editing.
  1628. if ( focused && focused.name == widgetDef.name )
  1629. focused.edit();
  1630. // Otherwise...
  1631. // ... use insert method is was defined.
  1632. else if ( widgetDef.insert )
  1633. widgetDef.insert();
  1634. // ... or create a brand-new widget from template.
  1635. else if ( widgetDef.template ) {
  1636. var defaults = typeof widgetDef.defaults == 'function' ? widgetDef.defaults() : widgetDef.defaults,
  1637. element = CKEDITOR.dom.element.createFromHtml( widgetDef.template.output( defaults ) ),
  1638. instance,
  1639. wrapper = editor.widgets.wrapElement( element, widgetDef.name ),
  1640. temp = new CKEDITOR.dom.documentFragment( wrapper.getDocument() );
  1641. // Append wrapper to a temporary document. This will unify the environment
  1642. // in which #data listeners work when creating and editing widget.
  1643. temp.append( wrapper );
  1644. instance = editor.widgets.initOn( element, widgetDef, commandData && commandData.startupData );
  1645. // Instance could be destroyed during initialization.
  1646. // In this case finalize creation if some new widget
  1647. // was left in temporary document fragment.
  1648. if ( !instance ) {
  1649. finalizeCreation();
  1650. return;
  1651. }
  1652. // Listen on edit to finalize widget insertion.
  1653. //
  1654. // * If dialog was set, then insert widget after dialog was successfully saved or destroy this
  1655. // temporary instance.
  1656. // * If dialog wasn't set and edit wasn't canceled, insert widget.
  1657. var editListener = instance.once( 'edit', function( evt ) {
  1658. if ( evt.data.dialog ) {
  1659. instance.once( 'dialog', function( evt ) {
  1660. var dialog = evt.data,
  1661. okListener,
  1662. cancelListener;
  1663. // Finalize creation AFTER (20) new data was set.
  1664. okListener = dialog.once( 'ok', finalizeCreation, null, null, 20 );
  1665. cancelListener = dialog.once( 'cancel', function( evt ) {
  1666. if ( !( evt.data && evt.data.hide === false ) ) {
  1667. editor.widgets.destroy( instance, true );
  1668. }
  1669. } );
  1670. dialog.once( 'hide', function() {
  1671. okListener.removeListener();
  1672. cancelListener.removeListener();
  1673. } );
  1674. } );
  1675. } else {
  1676. // Dialog hasn't been set, so insert widget now.
  1677. finalizeCreation();
  1678. }
  1679. }, null, null, 999 );
  1680. instance.edit();
  1681. // Remove listener in case someone canceled it before this
  1682. // listener was executed.
  1683. editListener.removeListener();
  1684. }
  1685. function finalizeCreation() {
  1686. editor.widgets.finalizeCreation( temp );
  1687. }
  1688. },
  1689. allowedContent: widgetDef.allowedContent,
  1690. requiredContent: widgetDef.requiredContent,
  1691. contentForms: widgetDef.contentForms,
  1692. contentTransformations: widgetDef.contentTransformations
  1693. } );
  1694. }
  1695. function addWidgetProcessors( widgetsRepo, widgetDef ) {
  1696. var upcast = widgetDef.upcast,
  1697. upcasts,
  1698. priority = widgetDef.upcastPriority || 10;
  1699. if ( !upcast )
  1700. return;
  1701. // Multiple upcasts defined in string.
  1702. if ( typeof upcast == 'string' ) {
  1703. upcasts = upcast.split( ',' );
  1704. while ( upcasts.length ) {
  1705. addUpcast( widgetDef.upcasts[ upcasts.pop() ], widgetDef.name, priority );
  1706. }
  1707. }
  1708. // Single rule which is automatically activated.
  1709. else {
  1710. addUpcast( upcast, widgetDef.name, priority );
  1711. }
  1712. function addUpcast( upcast, name, priority ) {
  1713. // Find index of the first higher (in terms of value) priority upcast.
  1714. var index = CKEDITOR.tools.getIndex( widgetsRepo._.upcasts, function( element ) {
  1715. return element[ 2 ] > priority;
  1716. } );
  1717. // Add at the end if it is the highest priority so far.
  1718. if ( index < 0 ) {
  1719. index = widgetsRepo._.upcasts.length;
  1720. }
  1721. widgetsRepo._.upcasts.splice( index, 0, [ upcast, name, priority ] );
  1722. }
  1723. }
  1724. function blurWidget( widgetsRepo, widget ) {
  1725. widgetsRepo.focused = null;
  1726. if ( widget.isInited() ) {
  1727. var isDirty = widget.editor.checkDirty();
  1728. // Widget could be destroyed in the meantime - e.g. data could be set.
  1729. widgetsRepo.fire( 'widgetBlurred', { widget: widget } );
  1730. widget.setFocused( false );
  1731. !isDirty && widget.editor.resetDirty();
  1732. }
  1733. }
  1734. function checkWidgets( evt ) {
  1735. var options = evt.data;
  1736. if ( this.editor.mode != 'wysiwyg' )
  1737. return;
  1738. var editable = this.editor.editable(),
  1739. instances = this.instances,
  1740. newInstances, i, count, wrapper, notYetInitialized;
  1741. if ( !editable )
  1742. return;
  1743. // Remove widgets which have no corresponding elements in DOM.
  1744. for ( i in instances ) {
  1745. // #13410 Remove widgets that are ready. This prevents from destroying widgets that are during loading process.
  1746. if ( instances[ i ].isReady() && !editable.contains( instances[ i ].wrapper ) )
  1747. this.destroy( instances[ i ], true );
  1748. }
  1749. // Init on all (new) if initOnlyNew option was passed.
  1750. if ( options && options.initOnlyNew )
  1751. newInstances = this.initOnAll();
  1752. else {
  1753. var wrappers = editable.find( '.cke_widget_wrapper' );
  1754. newInstances = [];
  1755. // Create widgets on existing wrappers if they do not exists.
  1756. for ( i = 0, count = wrappers.count(); i < count; i++ ) {
  1757. wrapper = wrappers.getItem( i );
  1758. notYetInitialized = !this.getByElement( wrapper, true );
  1759. // Check if:
  1760. // * there's no instance for this widget
  1761. // * wrapper is not inside some temporary element like copybin (#11088)
  1762. // * it was a nested widget's wrapper which has been detached from DOM,
  1763. // when nested editable has been initialized (it overwrites its innerHTML
  1764. // and initializes nested widgets).
  1765. if ( notYetInitialized && !findParent( wrapper, isDomTemp ) && editable.contains( wrapper ) ) {
  1766. // Add cke_widget_new class because otherwise
  1767. // widget will not be created on such wrapper.
  1768. wrapper.addClass( 'cke_widget_new' );
  1769. newInstances.push( this.initOn( wrapper.getFirst( Widget.isDomWidgetElement ) ) );
  1770. }
  1771. }
  1772. }
  1773. // If only single widget was initialized and focusInited was passed, focus it.
  1774. if ( options && options.focusInited && newInstances.length == 1 )
  1775. newInstances[ 0 ].focus();
  1776. }
  1777. // Unwraps widget element and clean up element.
  1778. //
  1779. // This function is used to clean up pasted widgets.
  1780. // It should have similar result to widget#destroy plus
  1781. // some additional adjustments, specific for pasting.
  1782. //
  1783. // @param {CKEDITOR.htmlParser.element} el
  1784. function cleanUpWidgetElement( el ) {
  1785. var parent = el.parent;
  1786. if ( parent.type == CKEDITOR.NODE_ELEMENT && parent.attributes[ 'data-cke-widget-wrapper' ] )
  1787. parent.replaceWith( el );
  1788. }
  1789. // Similar to cleanUpWidgetElement, but works on DOM and finds
  1790. // widget elements by its own.
  1791. //
  1792. // Unlike cleanUpWidgetElement it will wrap element back.
  1793. //
  1794. // @param {CKEDITOR.dom.element} container
  1795. function cleanUpAllWidgetElements( widgetsRepo, container ) {
  1796. var wrappers = container.find( '.cke_widget_wrapper' ),
  1797. wrapper, element,
  1798. i = 0,
  1799. l = wrappers.count();
  1800. for ( ; i < l; ++i ) {
  1801. wrapper = wrappers.getItem( i );
  1802. element = wrapper.getFirst( Widget.isDomWidgetElement );
  1803. // If wrapper contains widget element - unwrap it and wrap again.
  1804. if ( element.type == CKEDITOR.NODE_ELEMENT && element.data( 'widget' ) ) {
  1805. element.replace( wrapper );
  1806. widgetsRepo.wrapElement( element );
  1807. } else {
  1808. // Otherwise - something is wrong... clean this up.
  1809. wrapper.remove();
  1810. }
  1811. }
  1812. }
  1813. // Creates {@link CKEDITOR.filter} instance for given widget, editable and rules.
  1814. //
  1815. // Once filter for widget-editable pair is created it is cached, so the same instance
  1816. // will be returned when method is executed again.
  1817. //
  1818. // @param {String} widgetName
  1819. // @param {String} editableName
  1820. // @param {CKEDITOR.plugins.widget.nestedEditableDefinition} editableDefinition The nested editable definition.
  1821. // @returns {CKEDITOR.filter} Filter instance or `null` if rules are not defined.
  1822. // @context CKEDITOR.plugins.widget.repository
  1823. function createEditableFilter( widgetName, editableName, editableDefinition ) {
  1824. if ( !editableDefinition.allowedContent )
  1825. return null;
  1826. var editables = this._.filters[ widgetName ];
  1827. if ( !editables )
  1828. this._.filters[ widgetName ] = editables = {};
  1829. var filter = editables[ editableName ];
  1830. if ( !filter )
  1831. editables[ editableName ] = filter = new CKEDITOR.filter( editableDefinition.allowedContent );
  1832. return filter;
  1833. }
  1834. // Creates an iterator function which when executed on all
  1835. // elements in DOM tree will gather elements that should be wrapped
  1836. // and initialized as widgets.
  1837. function createUpcastIterator( widgetsRepo ) {
  1838. var toBeWrapped = [],
  1839. upcasts = widgetsRepo._.upcasts,
  1840. upcastCallbacks = widgetsRepo._.upcastCallbacks;
  1841. return {
  1842. toBeWrapped: toBeWrapped,
  1843. iterator: function( element ) {
  1844. var upcast, upcasted,
  1845. data,
  1846. i,
  1847. upcastsLength,
  1848. upcastCallbacksLength;
  1849. // Wrapper found - find widget element, add it to be
  1850. // cleaned up (unwrapped) and wrapped and stop iterating in this branch.
  1851. if ( 'data-cke-widget-wrapper' in element.attributes ) {
  1852. element = element.getFirst( Widget.isParserWidgetElement );
  1853. if ( element )
  1854. toBeWrapped.push( [ element ] );
  1855. // Do not iterate over descendants.
  1856. return false;
  1857. }
  1858. // Widget element found - add it to be cleaned up (just in case)
  1859. // and wrapped and stop iterating in this branch.
  1860. else if ( 'data-widget' in element.attributes ) {
  1861. toBeWrapped.push( [ element ] );
  1862. // Do not iterate over descendants.
  1863. return false;
  1864. }
  1865. else if ( ( upcastsLength = upcasts.length ) ) {
  1866. // Ignore elements with data-cke-widget-upcasted to avoid multiple upcasts (#11533).
  1867. // Do not iterate over descendants.
  1868. if ( element.attributes[ 'data-cke-widget-upcasted' ] )
  1869. return false;
  1870. // Check element with upcast callbacks first.
  1871. // If any of them return false abort upcasting.
  1872. for ( i = 0, upcastCallbacksLength = upcastCallbacks.length; i < upcastCallbacksLength; ++i ) {
  1873. if ( upcastCallbacks[ i ]( element ) === false )
  1874. return;
  1875. // Return nothing in order to continue iterating over ascendants.
  1876. // See http://dev.ckeditor.com/ticket/11186#comment:6
  1877. }
  1878. for ( i = 0; i < upcastsLength; ++i ) {
  1879. upcast = upcasts[ i ];
  1880. data = {};
  1881. if ( ( upcasted = upcast[ 0 ]( element, data ) ) ) {
  1882. // If upcast function returned element, upcast this one.
  1883. // It can be e.g. a new element wrapping the original one.
  1884. if ( upcasted instanceof CKEDITOR.htmlParser.element )
  1885. element = upcasted;
  1886. // Set initial data attr with data from upcast method.
  1887. element.attributes[ 'data-cke-widget-data' ] = encodeURIComponent( JSON.stringify( data ) );
  1888. element.attributes[ 'data-cke-widget-upcasted' ] = 1;
  1889. toBeWrapped.push( [ element, upcast[ 1 ] ] );
  1890. // Do not iterate over descendants.
  1891. return false;
  1892. }
  1893. }
  1894. }
  1895. }
  1896. };
  1897. }
  1898. // Finds a first parent that matches query.
  1899. //
  1900. // @param {CKEDITOR.dom.element} element
  1901. // @param {Function} query
  1902. function findParent( element, query ) {
  1903. var parent = element;
  1904. while ( ( parent = parent.getParent() ) ) {
  1905. if ( query( parent ) )
  1906. return true;
  1907. }
  1908. return false;
  1909. }
  1910. function getWrapperAttributes( inlineWidget ) {
  1911. return {
  1912. // tabindex="-1" means that it can receive focus by code.
  1913. tabindex: -1,
  1914. contenteditable: 'false',
  1915. 'data-cke-widget-wrapper': 1,
  1916. 'data-cke-filter': 'off',
  1917. // Class cke_widget_new marks widgets which haven't been initialized yet.
  1918. 'class': 'cke_widget_wrapper cke_widget_new cke_widget_' +
  1919. ( inlineWidget ? 'inline' : 'block' )
  1920. };
  1921. }
  1922. // Inserts element at given index.
  1923. // It will check DTD and split ancestor elements up to the first
  1924. // that can contain this element.
  1925. //
  1926. // @param {CKEDITOR.htmlParser.element} parent
  1927. // @param {Number} index
  1928. // @param {CKEDITOR.htmlParser.element} element
  1929. function insertElement( parent, index, element ) {
  1930. // Do not split doc fragment...
  1931. if ( parent.type == CKEDITOR.NODE_ELEMENT ) {
  1932. var parentAllows = CKEDITOR.dtd[ parent.name ];
  1933. // Parent element is known (included in DTD) and cannot contain
  1934. // this element.
  1935. if ( parentAllows && !parentAllows[ element.name ] ) {
  1936. var parent2 = parent.split( index ),
  1937. parentParent = parent.parent;
  1938. // Element will now be inserted at right parent's index.
  1939. index = parent2.getIndex();
  1940. // If left part of split is empty - remove it.
  1941. if ( !parent.children.length ) {
  1942. index -= 1;
  1943. parent.remove();
  1944. }
  1945. // If right part of split is empty - remove it.
  1946. if ( !parent2.children.length )
  1947. parent2.remove();
  1948. // Try inserting as grandpas' children.
  1949. return insertElement( parentParent, index, element );
  1950. }
  1951. }
  1952. // Finally we can add this element.
  1953. parent.add( element, index );
  1954. }
  1955. // Checks whether for the given widget definition and element widget should be created in inline or block mode.
  1956. //
  1957. // See also: {@link CKEDITOR.plugins.widget.definition#inline} and {@link CKEDITOR.plugins.widget#element}.
  1958. //
  1959. // @param {CKEDITOR.plugins.widget.definition} widgetDef The widget definition.
  1960. // @param {String} elementName The name of the widget element.
  1961. // @returns {Boolean}
  1962. function isWidgetInline( widgetDef, elementName ) {
  1963. return typeof widgetDef.inline == 'boolean' ? widgetDef.inline : !!CKEDITOR.dtd.$inline[ elementName ];
  1964. }
  1965. // @param {CKEDITOR.dom.element}
  1966. // @returns {Boolean}
  1967. function isDomTemp( element ) {
  1968. return element.hasAttribute( 'data-cke-temp' );
  1969. }
  1970. function onEditableKey( widget, keyCode ) {
  1971. var focusedEditable = widget.focusedEditable,
  1972. range;
  1973. // CTRL+A.
  1974. if ( keyCode == CKEDITOR.CTRL + 65 ) {
  1975. var bogus = focusedEditable.getBogus();
  1976. range = widget.editor.createRange();
  1977. range.selectNodeContents( focusedEditable );
  1978. // Exclude bogus if exists.
  1979. if ( bogus )
  1980. range.setEndAt( bogus, CKEDITOR.POSITION_BEFORE_START );
  1981. range.select();
  1982. // Cancel event - block default.
  1983. return false;
  1984. }
  1985. // DEL or BACKSPACE.
  1986. else if ( keyCode == 8 || keyCode == 46 ) {
  1987. var ranges = widget.editor.getSelection().getRanges();
  1988. range = ranges[ 0 ];
  1989. // Block del or backspace if at editable's boundary.
  1990. return !( ranges.length == 1 && range.collapsed &&
  1991. range.checkBoundaryOfElement( focusedEditable, CKEDITOR[ keyCode == 8 ? 'START' : 'END' ] ) );
  1992. }
  1993. }
  1994. function setFocusedEditable( widgetsRepo, widget, editableElement, offline ) {
  1995. var editor = widgetsRepo.editor;
  1996. editor.fire( 'lockSnapshot' );
  1997. if ( editableElement ) {
  1998. var editableName = editableElement.data( 'cke-widget-editable' ),
  1999. editableInstance = widget.editables[ editableName ];
  2000. widgetsRepo.widgetHoldingFocusedEditable = widget;
  2001. widget.focusedEditable = editableInstance;
  2002. editableElement.addClass( 'cke_widget_editable_focused' );
  2003. if ( editableInstance.filter )
  2004. editor.setActiveFilter( editableInstance.filter );
  2005. editor.setActiveEnterMode( editableInstance.enterMode, editableInstance.shiftEnterMode );
  2006. } else {
  2007. if ( !offline )
  2008. widget.focusedEditable.removeClass( 'cke_widget_editable_focused' );
  2009. widget.focusedEditable = null;
  2010. widgetsRepo.widgetHoldingFocusedEditable = null;
  2011. editor.setActiveFilter( null );
  2012. editor.setActiveEnterMode( null, null );
  2013. }
  2014. editor.fire( 'unlockSnapshot' );
  2015. }
  2016. function setupContextMenu( editor ) {
  2017. if ( !editor.contextMenu )
  2018. return;
  2019. editor.contextMenu.addListener( function( element ) {
  2020. var widget = editor.widgets.getByElement( element, true );
  2021. if ( widget )
  2022. return widget.fire( 'contextMenu', {} );
  2023. } );
  2024. }
  2025. // And now we've got two problems - original problem and RegExp.
  2026. // Some softeners:
  2027. // * FF tends to copy all blocks up to the copybin container.
  2028. // * IE tends to copy only the copybin, without its container.
  2029. // * We use spans on IE and blockless editors, but divs in other cases.
  2030. var pasteReplaceRegex = new RegExp(
  2031. '^' +
  2032. '(?:<(?:div|span)(?: data-cke-temp="1")?(?: id="cke_copybin")?(?: data-cke-temp="1")?>)?' +
  2033. '(?:<(?:div|span)(?: style="[^"]+")?>)?' +
  2034. '<span [^>]*data-cke-copybin-start="1"[^>]*>.?</span>([\\s\\S]+)<span [^>]*data-cke-copybin-end="1"[^>]*>.?</span>' +
  2035. '(?:</(?:div|span)>)?' +
  2036. '(?:</(?:div|span)>)?' +
  2037. '$',
  2038. // IE8 prefers uppercase when browsers stick to lowercase HTML (#13460).
  2039. 'i'
  2040. );
  2041. function pasteReplaceFn( match, wrapperHtml ) {
  2042. // Avoid polluting pasted data with any whitspaces,
  2043. // what's going to break check whether only one widget was pasted.
  2044. return CKEDITOR.tools.trim( wrapperHtml );
  2045. }
  2046. function setupDragAndDrop( widgetsRepo ) {
  2047. var editor = widgetsRepo.editor,
  2048. lineutils = CKEDITOR.plugins.lineutils;
  2049. // These listeners handle inline and block widgets drag and drop.
  2050. // The only thing we need to do to make block widgets custom drag and drop functionality
  2051. // is to fire those events with the right properties (like the target which must be the drag handle).
  2052. editor.on( 'dragstart', function( evt ) {
  2053. var target = evt.data.target;
  2054. if ( Widget.isDomDragHandler( target ) ) {
  2055. var widget = widgetsRepo.getByElement( target );
  2056. evt.data.dataTransfer.setData( 'cke/widget-id', widget.id );
  2057. // IE needs focus.
  2058. editor.focus();
  2059. // and widget need to be focused on drag start (#12172#comment:10).
  2060. widget.focus();
  2061. }
  2062. } );
  2063. editor.on( 'drop', function( evt ) {
  2064. var dataTransfer = evt.data.dataTransfer,
  2065. id = dataTransfer.getData( 'cke/widget-id' ),
  2066. dragRange = editor.createRange(),
  2067. sourceWidget;
  2068. if ( id === '' || dataTransfer.getTransferType( editor ) != CKEDITOR.DATA_TRANSFER_INTERNAL ) {
  2069. return;
  2070. }
  2071. sourceWidget = widgetsRepo.instances[ id ];
  2072. if ( !sourceWidget ) {
  2073. return;
  2074. }
  2075. dragRange.setStartBefore( sourceWidget.wrapper );
  2076. dragRange.setEndAfter( sourceWidget.wrapper );
  2077. evt.data.dragRange = dragRange;
  2078. // [IE8-9] Reset state of the clipboard#fixSplitNodesAfterDrop fix because by setting evt.data.dragRange
  2079. // (see above) after drop happened we do not need it. That fix is needed only if dragRange was created
  2080. // before drop (before text node was split).
  2081. delete CKEDITOR.plugins.clipboard.dragStartContainerChildCount;
  2082. delete CKEDITOR.plugins.clipboard.dragEndContainerChildCount;
  2083. evt.data.dataTransfer.setData( 'text/html', editor.editable().getHtmlFromRange( dragRange ).getHtml() );
  2084. editor.widgets.destroy( sourceWidget, true );
  2085. } );
  2086. editor.on( 'contentDom', function() {
  2087. var editable = editor.editable();
  2088. // Register Lineutils's utilities as properties of repo.
  2089. CKEDITOR.tools.extend( widgetsRepo, {
  2090. finder: new lineutils.finder( editor, {
  2091. lookups: {
  2092. // Element is block but not list item and not in nested editable.
  2093. 'default': function( el ) {
  2094. if ( el.is( CKEDITOR.dtd.$listItem ) )
  2095. return;
  2096. if ( !el.is( CKEDITOR.dtd.$block ) )
  2097. return;
  2098. // Allow drop line inside, but never before or after nested editable (#12006).
  2099. if ( Widget.isDomNestedEditable( el ) )
  2100. return;
  2101. // Do not allow droping inside the widget being dragged (#13397).
  2102. if ( widgetsRepo._.draggedWidget.wrapper.contains( el ) ) {
  2103. return;
  2104. }
  2105. // If element is nested editable, make sure widget can be dropped there (#12006).
  2106. var nestedEditable = Widget.getNestedEditable( editable, el );
  2107. if ( nestedEditable ) {
  2108. var draggedWidget = widgetsRepo._.draggedWidget;
  2109. // Don't let the widget to be dropped into its own nested editable.
  2110. if ( widgetsRepo.getByElement( nestedEditable ) == draggedWidget )
  2111. return;
  2112. var filter = CKEDITOR.filter.instances[ nestedEditable.data( 'cke-filter' ) ],
  2113. draggedRequiredContent = draggedWidget.requiredContent;
  2114. // There will be no relation if the filter of nested editable does not allow
  2115. // requiredContent of dragged widget.
  2116. if ( filter && draggedRequiredContent && !filter.check( draggedRequiredContent ) )
  2117. return;
  2118. }
  2119. return CKEDITOR.LINEUTILS_BEFORE | CKEDITOR.LINEUTILS_AFTER;
  2120. }
  2121. }
  2122. } ),
  2123. locator: new lineutils.locator( editor ),
  2124. liner: new lineutils.liner( editor, {
  2125. lineStyle: {
  2126. cursor: 'move !important',
  2127. 'border-top-color': '#666'
  2128. },
  2129. tipLeftStyle: {
  2130. 'border-left-color': '#666'
  2131. },
  2132. tipRightStyle: {
  2133. 'border-right-color': '#666'
  2134. }
  2135. } )
  2136. }, true );
  2137. } );
  2138. }
  2139. // Setup mouse observer which will trigger:
  2140. // * widget focus on widget click,
  2141. // * widget#doubleclick forwarded from editor#doubleclick.
  2142. function setupMouseObserver( widgetsRepo ) {
  2143. var editor = widgetsRepo.editor;
  2144. editor.on( 'contentDom', function() {
  2145. var editable = editor.editable(),
  2146. evtRoot = editable.isInline() ? editable : editor.document,
  2147. widget,
  2148. mouseDownOnDragHandler;
  2149. editable.attachListener( evtRoot, 'mousedown', function( evt ) {
  2150. var target = evt.data.getTarget();
  2151. // #10887 Clicking scrollbar in IE8 will invoke event with empty target object.
  2152. if ( !target.type )
  2153. return false;
  2154. widget = widgetsRepo.getByElement( target );
  2155. mouseDownOnDragHandler = 0; // Reset.
  2156. // Widget was clicked, but not editable nested in it.
  2157. if ( widget ) {
  2158. // Ignore mousedown on drag and drop handler if the widget is inline.
  2159. // Block widgets are handled by Lineutils.
  2160. if ( widget.inline && target.type == CKEDITOR.NODE_ELEMENT && target.hasAttribute( 'data-cke-widget-drag-handler' ) ) {
  2161. mouseDownOnDragHandler = 1;
  2162. return;
  2163. }
  2164. if ( !Widget.getNestedEditable( widget.wrapper, target ) ) {
  2165. evt.data.preventDefault();
  2166. if ( !CKEDITOR.env.ie )
  2167. widget.focus();
  2168. } else {
  2169. // Reset widget so mouseup listener is not confused.
  2170. widget = null;
  2171. }
  2172. }
  2173. } );
  2174. // Focus widget on mouseup if mousedown was fired on drag handler.
  2175. // Note: mouseup won't be fired at all if widget was dragged and dropped, so
  2176. // this code will be executed only when drag handler was clicked.
  2177. editable.attachListener( evtRoot, 'mouseup', function() {
  2178. // Check if widget is not destroyed (if widget is destroyed the wrapper will be null).
  2179. if ( mouseDownOnDragHandler && widget && widget.wrapper ) {
  2180. mouseDownOnDragHandler = 0;
  2181. widget.focus();
  2182. }
  2183. } );
  2184. // On IE it is not enough to block mousedown. If widget wrapper (element with
  2185. // contenteditable=false attribute) is clicked directly (it is a target),
  2186. // then after mouseup/click IE will select that element.
  2187. // It is not possible to prevent that default action,
  2188. // so we force fake selection after everything happened.
  2189. if ( CKEDITOR.env.ie ) {
  2190. editable.attachListener( evtRoot, 'mouseup', function() {
  2191. setTimeout( function() {
  2192. // Check if widget is not destroyed (if widget is destroyed the wrapper will be null) and
  2193. // in editable contains widget (it could be dragged and removed).
  2194. if ( widget && widget.wrapper && editable.contains( widget.wrapper ) ) {
  2195. widget.focus();
  2196. widget = null;
  2197. }
  2198. } );
  2199. } );
  2200. }
  2201. } );
  2202. editor.on( 'doubleclick', function( evt ) {
  2203. var widget = widgetsRepo.getByElement( evt.data.element );
  2204. // Not in widget or in nested editable.
  2205. if ( !widget || Widget.getNestedEditable( widget.wrapper, evt.data.element ) )
  2206. return;
  2207. return widget.fire( 'doubleclick', { element: evt.data.element } );
  2208. }, null, null, 1 );
  2209. }
  2210. // Setup editor#key observer which will forward it
  2211. // to focused widget.
  2212. function setupKeyboardObserver( widgetsRepo ) {
  2213. var editor = widgetsRepo.editor;
  2214. editor.on( 'key', function( evt ) {
  2215. var focused = widgetsRepo.focused,
  2216. widgetHoldingFocusedEditable = widgetsRepo.widgetHoldingFocusedEditable,
  2217. ret;
  2218. if ( focused )
  2219. ret = focused.fire( 'key', { keyCode: evt.data.keyCode } );
  2220. else if ( widgetHoldingFocusedEditable )
  2221. ret = onEditableKey( widgetHoldingFocusedEditable, evt.data.keyCode );
  2222. return ret;
  2223. }, null, null, 1 );
  2224. }
  2225. // Setup copybin on native copy and cut events in order to handle copy and cut commands
  2226. // if user accepted security alert on IEs.
  2227. // Note: when copying or cutting using keystroke, copySingleWidget will be first executed
  2228. // by the keydown listener. Conflict between two calls will be resolved by copy_bin existence check.
  2229. function setupNativeCutAndCopy( widgetsRepo ) {
  2230. var editor = widgetsRepo.editor;
  2231. editor.on( 'contentDom', function() {
  2232. var editable = editor.editable();
  2233. editable.attachListener( editable, 'copy', eventListener );
  2234. editable.attachListener( editable, 'cut', eventListener );
  2235. } );
  2236. function eventListener( evt ) {
  2237. if ( widgetsRepo.focused )
  2238. copySingleWidget( widgetsRepo.focused, evt.name == 'cut' );
  2239. }
  2240. }
  2241. // Setup selection observer which will trigger:
  2242. // * widget select & focus on selection change,
  2243. // * nested editable focus (related properites and classes) on selection change,
  2244. // * deselecting and blurring all widgets on data,
  2245. // * blurring widget on editor blur.
  2246. function setupSelectionObserver( widgetsRepo ) {
  2247. var editor = widgetsRepo.editor;
  2248. editor.on( 'selectionCheck', function() {
  2249. widgetsRepo.fire( 'checkSelection' );
  2250. } );
  2251. widgetsRepo.on( 'checkSelection', widgetsRepo.checkSelection, widgetsRepo );
  2252. editor.on( 'selectionChange', function( evt ) {
  2253. var nestedEditable = Widget.getNestedEditable( editor.editable(), evt.data.selection.getStartElement() ),
  2254. newWidget = nestedEditable && widgetsRepo.getByElement( nestedEditable ),
  2255. oldWidget = widgetsRepo.widgetHoldingFocusedEditable;
  2256. if ( oldWidget ) {
  2257. if ( oldWidget !== newWidget || !oldWidget.focusedEditable.equals( nestedEditable ) ) {
  2258. setFocusedEditable( widgetsRepo, oldWidget, null );
  2259. if ( newWidget && nestedEditable )
  2260. setFocusedEditable( widgetsRepo, newWidget, nestedEditable );
  2261. }
  2262. }
  2263. // It may happen that there's no widget even if editable was found -
  2264. // e.g. if selection was automatically set in editable although widget wasn't initialized yet.
  2265. else if ( newWidget && nestedEditable ) {
  2266. setFocusedEditable( widgetsRepo, newWidget, nestedEditable );
  2267. }
  2268. } );
  2269. // Invalidate old widgets early - immediately on dataReady.
  2270. editor.on( 'dataReady', function() {
  2271. // Deselect and blur all widgets.
  2272. stateUpdater( widgetsRepo ).commit();
  2273. } );
  2274. editor.on( 'blur', function() {
  2275. var widget;
  2276. if ( ( widget = widgetsRepo.focused ) )
  2277. blurWidget( widgetsRepo, widget );
  2278. if ( ( widget = widgetsRepo.widgetHoldingFocusedEditable ) )
  2279. setFocusedEditable( widgetsRepo, widget, null );
  2280. } );
  2281. }
  2282. // Set up actions like:
  2283. // * processing in toHtml/toDataFormat,
  2284. // * pasting handling,
  2285. // * insertion handling,
  2286. // * editable reload handling (setData, mode switch, undo/redo),
  2287. // * DOM invalidation handling,
  2288. // * widgets checks.
  2289. function setupWidgetsLifecycle( widgetsRepo ) {
  2290. setupWidgetsLifecycleStart( widgetsRepo );
  2291. setupWidgetsLifecycleEnd( widgetsRepo );
  2292. widgetsRepo.on( 'checkWidgets', checkWidgets );
  2293. widgetsRepo.editor.on( 'contentDomInvalidated', widgetsRepo.checkWidgets, widgetsRepo );
  2294. }
  2295. function setupWidgetsLifecycleEnd( widgetsRepo ) {
  2296. var editor = widgetsRepo.editor,
  2297. downcastingSessions = {};
  2298. // Listen before htmlDP#htmlFilter is applied to cache all widgets, because we'll
  2299. // loose data-cke-* attributes.
  2300. editor.on( 'toDataFormat', function( evt ) {
  2301. // To avoid conflicts between htmlDP#toDF calls done at the same time
  2302. // (e.g. nestedEditable#getData called during downcasting some widget)
  2303. // mark every toDataFormat event chain with the downcasting session id.
  2304. var id = CKEDITOR.tools.getNextNumber(),
  2305. toBeDowncasted = [];
  2306. evt.data.downcastingSessionId = id;
  2307. downcastingSessions[ id ] = toBeDowncasted;
  2308. evt.data.dataValue.forEach( function( element ) {
  2309. var attrs = element.attributes,
  2310. widget, widgetElement;
  2311. // Wrapper.
  2312. // Perform first part of downcasting (cleanup) and cache widgets,
  2313. // because after applying DP's filter all data-cke-* attributes will be gone.
  2314. if ( 'data-cke-widget-id' in attrs ) {
  2315. widget = widgetsRepo.instances[ attrs[ 'data-cke-widget-id' ] ];
  2316. if ( widget ) {
  2317. widgetElement = element.getFirst( Widget.isParserWidgetElement );
  2318. toBeDowncasted.push( {
  2319. wrapper: element,
  2320. element: widgetElement,
  2321. widget: widget,
  2322. editables: {}
  2323. } );
  2324. // If widget did not have data-cke-widget attribute before upcasting remove it.
  2325. if ( widgetElement.attributes[ 'data-cke-widget-keep-attr' ] != '1' )
  2326. delete widgetElement.attributes[ 'data-widget' ];
  2327. }
  2328. }
  2329. // Nested editable.
  2330. else if ( 'data-cke-widget-editable' in attrs ) {
  2331. // Save the reference to this nested editable in the closest widget to be downcasted.
  2332. // Nested editables are downcasted in the successive toDataFormat to create an opportunity
  2333. // for dataFilter's "excludeNestedEditable" option to do its job (that option relies on
  2334. // contenteditable="true" attribute) (#11372).
  2335. toBeDowncasted[ toBeDowncasted.length - 1 ].editables[ attrs[ 'data-cke-widget-editable' ] ] = element;
  2336. // Don't check children - there won't be next wrapper or nested editable which we
  2337. // should process in this session.
  2338. return false;
  2339. }
  2340. }, CKEDITOR.NODE_ELEMENT, true );
  2341. }, null, null, 8 );
  2342. // Listen after dataProcessor.htmlFilter and ACF were applied
  2343. // so wrappers securing widgets' contents are removed after all filtering was done.
  2344. editor.on( 'toDataFormat', function( evt ) {
  2345. // Ignore some unmarked sessions.
  2346. if ( !evt.data.downcastingSessionId )
  2347. return;
  2348. var toBeDowncasted = downcastingSessions[ evt.data.downcastingSessionId ],
  2349. toBe, widget, widgetElement, retElement, editableElement, e;
  2350. while ( ( toBe = toBeDowncasted.shift() ) ) {
  2351. widget = toBe.widget;
  2352. widgetElement = toBe.element;
  2353. retElement = widget._.downcastFn && widget._.downcastFn.call( widget, widgetElement );
  2354. // Replace nested editables' content with their output data.
  2355. for ( e in toBe.editables ) {
  2356. editableElement = toBe.editables[ e ];
  2357. delete editableElement.attributes.contenteditable;
  2358. editableElement.setHtml( widget.editables[ e ].getData() );
  2359. }
  2360. // Returned element always defaults to widgetElement.
  2361. if ( !retElement )
  2362. retElement = widgetElement;
  2363. toBe.wrapper.replaceWith( retElement );
  2364. }
  2365. }, null, null, 13 );
  2366. editor.on( 'contentDomUnload', function() {
  2367. widgetsRepo.destroyAll( true );
  2368. } );
  2369. }
  2370. function setupWidgetsLifecycleStart( widgetsRepo ) {
  2371. var editor = widgetsRepo.editor,
  2372. processedWidgetOnly,
  2373. snapshotLoaded;
  2374. // Listen after ACF (so data are filtered),
  2375. // but before dataProcessor.dataFilter was applied (so we can secure widgets' internals).
  2376. editor.on( 'toHtml', function( evt ) {
  2377. var upcastIterator = createUpcastIterator( widgetsRepo ),
  2378. toBeWrapped;
  2379. evt.data.dataValue.forEach( upcastIterator.iterator, CKEDITOR.NODE_ELEMENT, true );
  2380. // Clean up and wrap all queued elements.
  2381. while ( ( toBeWrapped = upcastIterator.toBeWrapped.pop() ) ) {
  2382. cleanUpWidgetElement( toBeWrapped[ 0 ] );
  2383. widgetsRepo.wrapElement( toBeWrapped[ 0 ], toBeWrapped[ 1 ] );
  2384. }
  2385. // Used to determine whether only widget was pasted.
  2386. if ( evt.data.protectedWhitespaces ) {
  2387. // Whitespaces are protected by wrapping content with spans. Take the middle node only.
  2388. processedWidgetOnly = evt.data.dataValue.children.length == 3 &&
  2389. Widget.isParserWidgetWrapper( evt.data.dataValue.children[ 1 ] );
  2390. } else {
  2391. processedWidgetOnly = evt.data.dataValue.children.length == 1 &&
  2392. Widget.isParserWidgetWrapper( evt.data.dataValue.children[ 0 ] );
  2393. }
  2394. }, null, null, 8 );
  2395. editor.on( 'dataReady', function() {
  2396. // Clean up all widgets loaded from snapshot.
  2397. if ( snapshotLoaded )
  2398. cleanUpAllWidgetElements( widgetsRepo, editor.editable() );
  2399. snapshotLoaded = 0;
  2400. // Some widgets were destroyed on contentDomUnload,
  2401. // some on loadSnapshot, but that does not include
  2402. // e.g. setHtml on inline editor or widgets removed just
  2403. // before setting data.
  2404. widgetsRepo.destroyAll( true );
  2405. widgetsRepo.initOnAll();
  2406. } );
  2407. // Set flag so dataReady will know that additional
  2408. // cleanup is needed, because snapshot containing widgets was loaded.
  2409. editor.on( 'loadSnapshot', function( evt ) {
  2410. // Primitive but sufficient check which will prevent from executing
  2411. // heavier cleanUpAllWidgetElements if not needed.
  2412. if ( ( /data-cke-widget/ ).test( evt.data ) )
  2413. snapshotLoaded = 1;
  2414. widgetsRepo.destroyAll( true );
  2415. }, null, null, 9 );
  2416. // Handle pasted single widget.
  2417. editor.on( 'paste', function( evt ) {
  2418. var data = evt.data;
  2419. data.dataValue = data.dataValue.replace( pasteReplaceRegex, pasteReplaceFn );
  2420. // If drag'n'drop kind of paste into nested editable (data.range), selection is set AFTER
  2421. // data is pasted, which means editor has no chance to change activeFilter's context.
  2422. // As a result, pasted data is filtered with default editor's filter instead of NE's and
  2423. // funny things get inserted. Changing the filter by analysis of the paste range below (#13186).
  2424. if ( data.range ) {
  2425. // Check if pasting into nested editable.
  2426. var nestedEditable = Widget.getNestedEditable( editor.editable(), data.range.startContainer );
  2427. if ( nestedEditable ) {
  2428. // Retrieve the filter from NE's data and set it active before editor.insertHtml is done
  2429. // in clipboard plugin.
  2430. var filter = CKEDITOR.filter.instances[ nestedEditable.data( 'cke-filter' ) ];
  2431. if ( filter ) {
  2432. editor.setActiveFilter( filter );
  2433. }
  2434. }
  2435. }
  2436. } );
  2437. // Listen with high priority to check widgets after data was inserted.
  2438. editor.on( 'afterInsertHtml', function( evt ) {
  2439. if ( evt.data.intoRange ) {
  2440. widgetsRepo.checkWidgets( { initOnlyNew: true } );
  2441. } else {
  2442. editor.fire( 'lockSnapshot' );
  2443. // Init only new for performance reason.
  2444. // Focus inited if only widget was processed.
  2445. widgetsRepo.checkWidgets( { initOnlyNew: true, focusInited: processedWidgetOnly } );
  2446. editor.fire( 'unlockSnapshot' );
  2447. }
  2448. } );
  2449. }
  2450. // Helper for coordinating which widgets should be
  2451. // selected/deselected and which one should be focused/blurred.
  2452. function stateUpdater( widgetsRepo ) {
  2453. var currentlySelected = widgetsRepo.selected,
  2454. toBeSelected = [],
  2455. toBeDeselected = currentlySelected.slice( 0 ),
  2456. focused = null;
  2457. return {
  2458. select: function( widget ) {
  2459. if ( CKEDITOR.tools.indexOf( currentlySelected, widget ) < 0 )
  2460. toBeSelected.push( widget );
  2461. var index = CKEDITOR.tools.indexOf( toBeDeselected, widget );
  2462. if ( index >= 0 )
  2463. toBeDeselected.splice( index, 1 );
  2464. return this;
  2465. },
  2466. focus: function( widget ) {
  2467. focused = widget;
  2468. return this;
  2469. },
  2470. commit: function() {
  2471. var focusedChanged = widgetsRepo.focused !== focused,
  2472. widget, isDirty;
  2473. widgetsRepo.editor.fire( 'lockSnapshot' );
  2474. if ( focusedChanged && ( widget = widgetsRepo.focused ) )
  2475. blurWidget( widgetsRepo, widget );
  2476. while ( ( widget = toBeDeselected.pop() ) ) {
  2477. currentlySelected.splice( CKEDITOR.tools.indexOf( currentlySelected, widget ), 1 );
  2478. // Widget could be destroyed in the meantime - e.g. data could be set.
  2479. if ( widget.isInited() ) {
  2480. isDirty = widget.editor.checkDirty();
  2481. widget.setSelected( false );
  2482. !isDirty && widget.editor.resetDirty();
  2483. }
  2484. }
  2485. if ( focusedChanged && focused ) {
  2486. isDirty = widgetsRepo.editor.checkDirty();
  2487. widgetsRepo.focused = focused;
  2488. widgetsRepo.fire( 'widgetFocused', { widget: focused } );
  2489. focused.setFocused( true );
  2490. !isDirty && widgetsRepo.editor.resetDirty();
  2491. }
  2492. while ( ( widget = toBeSelected.pop() ) ) {
  2493. currentlySelected.push( widget );
  2494. widget.setSelected( true );
  2495. }
  2496. widgetsRepo.editor.fire( 'unlockSnapshot' );
  2497. }
  2498. };
  2499. }
  2500. //
  2501. // WIDGET helpers ---------------------------------------------------------
  2502. //
  2503. // LEFT, RIGHT, UP, DOWN, DEL, BACKSPACE - unblock default fake sel handlers.
  2504. var keystrokesNotBlockedByWidget = { 37: 1, 38: 1, 39: 1, 40: 1, 8: 1, 46: 1 };
  2505. // Applies or removes style's classes from widget.
  2506. // @param {CKEDITOR.style} style Custom widget style.
  2507. // @param {Boolean} apply Whether to apply or remove style.
  2508. function applyRemoveStyle( widget, style, apply ) {
  2509. var changed = 0,
  2510. classes = getStyleClasses( style ),
  2511. updatedClasses = widget.data.classes || {},
  2512. cl;
  2513. // Ee... Something is wrong with this style.
  2514. if ( !classes )
  2515. return;
  2516. // Clone, because we need to break reference.
  2517. updatedClasses = CKEDITOR.tools.clone( updatedClasses );
  2518. while ( ( cl = classes.pop() ) ) {
  2519. if ( apply ) {
  2520. if ( !updatedClasses[ cl ] )
  2521. changed = updatedClasses[ cl ] = 1;
  2522. } else {
  2523. if ( updatedClasses[ cl ] ) {
  2524. delete updatedClasses[ cl ];
  2525. changed = 1;
  2526. }
  2527. }
  2528. }
  2529. if ( changed )
  2530. widget.setData( 'classes', updatedClasses );
  2531. }
  2532. function cancel( evt ) {
  2533. evt.cancel();
  2534. }
  2535. function copySingleWidget( widget, isCut ) {
  2536. var editor = widget.editor,
  2537. doc = editor.document;
  2538. // We're still handling previous copy/cut.
  2539. // When keystroke is used to copy/cut this will also prevent
  2540. // conflict with copySingleWidget called again for native copy/cut event.
  2541. if ( doc.getById( 'cke_copybin' ) )
  2542. return;
  2543. // [IE] Use span for copybin and its container to avoid bug with expanding editable height by
  2544. // absolutely positioned element.
  2545. var copybinName = ( editor.blockless || CKEDITOR.env.ie ) ? 'span' : 'div',
  2546. copybin = doc.createElement( copybinName ),
  2547. copybinContainer = doc.createElement( copybinName ),
  2548. // IE8 always jumps to the end of document.
  2549. needsScrollHack = CKEDITOR.env.ie && CKEDITOR.env.version < 9;
  2550. copybinContainer.setAttributes( {
  2551. id: 'cke_copybin',
  2552. 'data-cke-temp': '1'
  2553. } );
  2554. // Position copybin element outside current viewport.
  2555. copybin.setStyles( {
  2556. position: 'absolute',
  2557. width: '1px',
  2558. height: '1px',
  2559. overflow: 'hidden'
  2560. } );
  2561. copybin.setStyle( editor.config.contentsLangDirection == 'ltr' ? 'left' : 'right', '-5000px' );
  2562. var range = editor.createRange();
  2563. range.setStartBefore( widget.wrapper );
  2564. range.setEndAfter( widget.wrapper );
  2565. copybin.setHtml(
  2566. '<span data-cke-copybin-start="1">\u200b</span>' +
  2567. editor.editable().getHtmlFromRange( range ).getHtml() +
  2568. '<span data-cke-copybin-end="1">\u200b</span>' );
  2569. // Save snapshot with the current state.
  2570. editor.fire( 'saveSnapshot' );
  2571. // Ignore copybin.
  2572. editor.fire( 'lockSnapshot' );
  2573. copybinContainer.append( copybin );
  2574. editor.editable().append( copybinContainer );
  2575. var listener1 = editor.on( 'selectionChange', cancel, null, null, 0 ),
  2576. listener2 = widget.repository.on( 'checkSelection', cancel, null, null, 0 );
  2577. if ( needsScrollHack ) {
  2578. var docElement = doc.getDocumentElement().$,
  2579. scrollTop = docElement.scrollTop;
  2580. }
  2581. // Once the clone of the widget is inside of copybin, select
  2582. // the entire contents. This selection will be copied by the
  2583. // native browser's clipboard system.
  2584. range = editor.createRange();
  2585. range.selectNodeContents( copybin );
  2586. range.select();
  2587. if ( needsScrollHack )
  2588. docElement.scrollTop = scrollTop;
  2589. setTimeout( function() {
  2590. // [IE] Focus widget before removing copybin to avoid scroll jump.
  2591. if ( !isCut )
  2592. widget.focus();
  2593. copybinContainer.remove();
  2594. listener1.removeListener();
  2595. listener2.removeListener();
  2596. editor.fire( 'unlockSnapshot' );
  2597. if ( isCut ) {
  2598. widget.repository.del( widget );
  2599. editor.fire( 'saveSnapshot' );
  2600. }
  2601. }, 100 ); // Use 100ms, so Chrome (@Mac) will be able to grab the content.
  2602. }
  2603. // Extracts classes array from style instance.
  2604. function getStyleClasses( style ) {
  2605. var attrs = style.getDefinition().attributes,
  2606. classes = attrs && attrs[ 'class' ];
  2607. return classes ? classes.split( /\s+/ ) : null;
  2608. }
  2609. // [IE] Force keeping focus because IE sometimes forgets to fire focus on main editable
  2610. // when blurring nested editable.
  2611. // @context widget
  2612. function onEditableBlur() {
  2613. var active = CKEDITOR.document.getActive(),
  2614. editor = this.editor,
  2615. editable = editor.editable();
  2616. // If focus stays within editor override blur and set currentActive because it should be
  2617. // automatically changed to editable on editable#focus but it is not fired.
  2618. if ( ( editable.isInline() ? editable : editor.document.getWindow().getFrame() ).equals( active ) )
  2619. editor.focusManager.focus( editable );
  2620. }
  2621. // Force selectionChange when editable was focused.
  2622. // Similar to hack in selection.js#~620.
  2623. // @context widget
  2624. function onEditableFocus() {
  2625. // Gecko does not support 'DOMFocusIn' event on which we unlock selection
  2626. // in selection.js to prevent selection locking when entering nested editables.
  2627. if ( CKEDITOR.env.gecko )
  2628. this.editor.unlockSelection();
  2629. // We don't need to force selectionCheck on Webkit, because on Webkit
  2630. // we do that on DOMFocusIn in selection.js.
  2631. if ( !CKEDITOR.env.webkit ) {
  2632. this.editor.forceNextSelectionCheck();
  2633. this.editor.selectionChange( 1 );
  2634. }
  2635. }
  2636. // Setup listener on widget#data which will update (remove/add) classes
  2637. // by comparing newly set classes with the old ones.
  2638. function setupDataClassesListener( widget ) {
  2639. // Note: previousClasses and newClasses may be null!
  2640. // Tip: for ( cl in null ) is correct.
  2641. var previousClasses = null;
  2642. widget.on( 'data', function() {
  2643. var newClasses = this.data.classes,
  2644. cl;
  2645. // When setting new classes one need to remember
  2646. // that he must break reference.
  2647. if ( previousClasses == newClasses )
  2648. return;
  2649. for ( cl in previousClasses ) {
  2650. // Avoid removing and adding classes again.
  2651. if ( !( newClasses && newClasses[ cl ] ) )
  2652. this.removeClass( cl );
  2653. }
  2654. for ( cl in newClasses )
  2655. this.addClass( cl );
  2656. previousClasses = newClasses;
  2657. } );
  2658. }
  2659. function setupDragHandler( widget ) {
  2660. if ( !widget.draggable )
  2661. return;
  2662. var editor = widget.editor,
  2663. // Use getLast to find wrapper's direct descendant (#12022).
  2664. container = widget.wrapper.getLast( Widget.isDomDragHandlerContainer ),
  2665. img;
  2666. // Reuse drag handler if already exists (#11281).
  2667. if ( container )
  2668. img = container.findOne( 'img' );
  2669. else {
  2670. container = new CKEDITOR.dom.element( 'span', editor.document );
  2671. container.setAttributes( {
  2672. 'class': 'cke_reset cke_widget_drag_handler_container',
  2673. // Split background and background-image for IE8 which will break on rgba().
  2674. style: 'background:rgba(220,220,220,0.5);background-image:url(' + editor.plugins.widget.path + 'images/handle.png)'
  2675. } );
  2676. img = new CKEDITOR.dom.element( 'img', editor.document );
  2677. img.setAttributes( {
  2678. 'class': 'cke_reset cke_widget_drag_handler',
  2679. 'data-cke-widget-drag-handler': '1',
  2680. src: CKEDITOR.tools.transparentImageData,
  2681. width: DRAG_HANDLER_SIZE,
  2682. title: editor.lang.widget.move,
  2683. height: DRAG_HANDLER_SIZE
  2684. } );
  2685. widget.inline && img.setAttribute( 'draggable', 'true' );
  2686. container.append( img );
  2687. widget.wrapper.append( container );
  2688. }
  2689. // Preventing page reload when dropped content on widget wrapper (#13015).
  2690. // Widget is not editable so by default drop on it isn't allowed what means that
  2691. // browser handles it (there's no editable#drop event). If there's no drop event we cannot block
  2692. // the drop, so page is reloaded. This listener enables drop on widget wrappers.
  2693. widget.wrapper.on( 'dragover', function( evt ) {
  2694. evt.data.preventDefault();
  2695. } );
  2696. widget.wrapper.on( 'mouseenter', widget.updateDragHandlerPosition, widget );
  2697. setTimeout( function() {
  2698. widget.on( 'data', widget.updateDragHandlerPosition, widget );
  2699. }, 50 );
  2700. if ( !widget.inline ) {
  2701. img.on( 'mousedown', onBlockWidgetDrag, widget );
  2702. // On IE8 'dragstart' is propagated to editable, so editor#dragstart is fired twice on block widgets.
  2703. if ( CKEDITOR.env.ie && CKEDITOR.env.version < 9 ) {
  2704. img.on( 'dragstart', function( evt ) {
  2705. evt.data.preventDefault( true );
  2706. } );
  2707. }
  2708. }
  2709. widget.dragHandlerContainer = container;
  2710. }
  2711. function onBlockWidgetDrag( evt ) {
  2712. var finder = this.repository.finder,
  2713. locator = this.repository.locator,
  2714. liner = this.repository.liner,
  2715. editor = this.editor,
  2716. editable = editor.editable(),
  2717. listeners = [],
  2718. sorted = [];
  2719. // Mark dragged widget for repository#finder.
  2720. this.repository._.draggedWidget = this;
  2721. // Harvest all possible relations and display some closest.
  2722. var relations = finder.greedySearch(),
  2723. buffer = CKEDITOR.tools.eventsBuffer( 50, function() {
  2724. locations = locator.locate( relations );
  2725. // There's only a single line displayed for D&D.
  2726. sorted = locator.sort( y, 1 );
  2727. if ( sorted.length ) {
  2728. liner.prepare( relations, locations );
  2729. liner.placeLine( sorted[ 0 ] );
  2730. liner.cleanup();
  2731. }
  2732. } ),
  2733. locations, y;
  2734. // Let's have the "dragging cursor" over entire editable.
  2735. editable.addClass( 'cke_widget_dragging' );
  2736. // Cache mouse position so it is re-used in events buffer.
  2737. listeners.push( editable.on( 'mousemove', function( evt ) {
  2738. y = evt.data.$.clientY;
  2739. buffer.input();
  2740. } ) );
  2741. // Fire drag start as it happens during the native D&D.
  2742. editor.fire( 'dragstart', { target: evt.sender } );
  2743. function onMouseUp() {
  2744. var l;
  2745. buffer.reset();
  2746. // Stop observing events.
  2747. while ( ( l = listeners.pop() ) )
  2748. l.removeListener();
  2749. onBlockWidgetDrop.call( this, sorted, evt.sender );
  2750. }
  2751. // Mouseup means "drop". This is when the widget is being detached
  2752. // from DOM and placed at range determined by the line (location).
  2753. listeners.push( editor.document.once( 'mouseup', onMouseUp, this ) );
  2754. // Prevent calling 'onBlockWidgetDrop' twice in the inline editor.
  2755. // `removeListener` does not work if it is called at the same time event is fired.
  2756. if ( !editable.isInline() ) {
  2757. // Mouseup may occur when user hovers the line, which belongs to
  2758. // the outer document. This is, of course, a valid listener too.
  2759. listeners.push( CKEDITOR.document.once( 'mouseup', onMouseUp, this ) );
  2760. }
  2761. }
  2762. function onBlockWidgetDrop( sorted, dragTarget ) {
  2763. var finder = this.repository.finder,
  2764. liner = this.repository.liner,
  2765. editor = this.editor,
  2766. editable = this.editor.editable();
  2767. if ( !CKEDITOR.tools.isEmpty( liner.visible ) ) {
  2768. // Retrieve range for the closest location.
  2769. var dropRange = finder.getRange( sorted[ 0 ] );
  2770. // Focus widget (it could lost focus after mousedown+mouseup)
  2771. // and save this state as the one where we want to be taken back when undoing.
  2772. this.focus();
  2773. // Drag range will be set in the drop listener.
  2774. editor.fire( 'drop', {
  2775. dropRange: dropRange,
  2776. target: dropRange.startContainer
  2777. } );
  2778. }
  2779. // Clean-up custom cursor for editable.
  2780. editable.removeClass( 'cke_widget_dragging' );
  2781. // Clean-up all remaining lines.
  2782. liner.hideVisible();
  2783. // Clean-up drag & drop.
  2784. editor.fire( 'dragend', { target: dragTarget } );
  2785. }
  2786. function setupEditables( widget ) {
  2787. var editableName,
  2788. editableDef,
  2789. definedEditables = widget.editables;
  2790. widget.editables = {};
  2791. if ( !widget.editables )
  2792. return;
  2793. for ( editableName in definedEditables ) {
  2794. editableDef = definedEditables[ editableName ];
  2795. widget.initEditable( editableName, typeof editableDef == 'string' ? { selector: editableDef } : editableDef );
  2796. }
  2797. }
  2798. function setupMask( widget ) {
  2799. if ( !widget.mask )
  2800. return;
  2801. // Reuse mask if already exists (#11281).
  2802. var img = widget.wrapper.findOne( '.cke_widget_mask' );
  2803. if ( !img ) {
  2804. img = new CKEDITOR.dom.element( 'img', widget.editor.document );
  2805. img.setAttributes( {
  2806. src: CKEDITOR.tools.transparentImageData,
  2807. 'class': 'cke_reset cke_widget_mask'
  2808. } );
  2809. widget.wrapper.append( img );
  2810. }
  2811. widget.mask = img;
  2812. }
  2813. // Replace parts object containing:
  2814. // partName => selector pairs
  2815. // with:
  2816. // partName => element pairs
  2817. function setupParts( widget ) {
  2818. if ( widget.parts ) {
  2819. var parts = {},
  2820. el, partName;
  2821. for ( partName in widget.parts ) {
  2822. el = widget.wrapper.findOne( widget.parts[ partName ] );
  2823. parts[ partName ] = el;
  2824. }
  2825. widget.parts = parts;
  2826. }
  2827. }
  2828. function setupWidget( widget, widgetDef ) {
  2829. setupWrapper( widget );
  2830. setupParts( widget );
  2831. setupEditables( widget );
  2832. setupMask( widget );
  2833. setupDragHandler( widget );
  2834. setupDataClassesListener( widget );
  2835. // #11145: [IE8] Non-editable content of widget is draggable.
  2836. if ( CKEDITOR.env.ie && CKEDITOR.env.version < 9 ) {
  2837. widget.wrapper.on( 'dragstart', function( evt ) {
  2838. var target = evt.data.getTarget();
  2839. // Allow text dragging inside nested editables or dragging inline widget's drag handler.
  2840. if ( !Widget.getNestedEditable( widget, target ) && !( widget.inline && Widget.isDomDragHandler( target ) ) )
  2841. evt.data.preventDefault();
  2842. } );
  2843. }
  2844. widget.wrapper.removeClass( 'cke_widget_new' );
  2845. widget.element.addClass( 'cke_widget_element' );
  2846. widget.on( 'key', function( evt ) {
  2847. var keyCode = evt.data.keyCode;
  2848. // ENTER.
  2849. if ( keyCode == 13 ) {
  2850. widget.edit();
  2851. // CTRL+C or CTRL+X.
  2852. } else if ( keyCode == CKEDITOR.CTRL + 67 || keyCode == CKEDITOR.CTRL + 88 ) {
  2853. copySingleWidget( widget, keyCode == CKEDITOR.CTRL + 88 );
  2854. return; // Do not preventDefault.
  2855. } else if ( keyCode in keystrokesNotBlockedByWidget || ( CKEDITOR.CTRL & keyCode ) || ( CKEDITOR.ALT & keyCode ) ) {
  2856. // Pass chosen keystrokes to other plugins or default fake sel handlers.
  2857. // Pass all CTRL/ALT keystrokes.
  2858. return;
  2859. }
  2860. return false;
  2861. }, null, null, 999 );
  2862. // Listen with high priority so it's possible
  2863. // to overwrite this callback.
  2864. widget.on( 'doubleclick', function( evt ) {
  2865. if ( widget.edit() ) {
  2866. // We have to cancel event if edit method opens a dialog, otherwise
  2867. // link plugin may open extra dialog (#12140).
  2868. evt.cancel();
  2869. }
  2870. } );
  2871. if ( widgetDef.data )
  2872. widget.on( 'data', widgetDef.data );
  2873. if ( widgetDef.edit )
  2874. widget.on( 'edit', widgetDef.edit );
  2875. }
  2876. function setupWidgetData( widget, startupData ) {
  2877. var widgetDataAttr = widget.element.data( 'cke-widget-data' );
  2878. if ( widgetDataAttr )
  2879. widget.setData( JSON.parse( decodeURIComponent( widgetDataAttr ) ) );
  2880. if ( startupData )
  2881. widget.setData( startupData );
  2882. // Populate classes if they are not preset.
  2883. if ( !widget.data.classes )
  2884. widget.setData( 'classes', widget.getClasses() );
  2885. // Unblock data and...
  2886. widget.dataReady = true;
  2887. // Write data to element because this was blocked when data wasn't ready.
  2888. writeDataToElement( widget );
  2889. // Fire data event first time, because this was blocked when data wasn't ready.
  2890. widget.fire( 'data', widget.data );
  2891. }
  2892. function setupWrapper( widget ) {
  2893. // Retrieve widget wrapper. Assign an id to it.
  2894. var wrapper = widget.wrapper = widget.element.getParent();
  2895. wrapper.setAttribute( 'data-cke-widget-id', widget.id );
  2896. }
  2897. function writeDataToElement( widget ) {
  2898. widget.element.data( 'cke-widget-data', encodeURIComponent( JSON.stringify( widget.data ) ) );
  2899. }
  2900. //
  2901. // WIDGET STYLE HANDLER ---------------------------------------------------
  2902. //
  2903. ( function() {
  2904. /**
  2905. * The class representing a widget style. It is an {@link CKEDITOR#STYLE_OBJECT object} like
  2906. * the styles handler for widgets.
  2907. *
  2908. * **Note:** This custom style handler does not support all methods of the {@link CKEDITOR.style} class.
  2909. * Not supported methods: {@link #applyToRange}, {@link #removeFromRange}, {@link #applyToObject}.
  2910. *
  2911. * @since 4.4
  2912. * @class CKEDITOR.style.customHandlers.widget
  2913. * @extends CKEDITOR.style
  2914. */
  2915. CKEDITOR.style.addCustomHandler( {
  2916. type: 'widget',
  2917. setup: function( styleDefinition ) {
  2918. /**
  2919. * The name of widget to which this style can be applied.
  2920. * It is extracted from style definition's `widget` property.
  2921. *
  2922. * @property {String} widget
  2923. */
  2924. this.widget = styleDefinition.widget;
  2925. },
  2926. apply: function( editor ) {
  2927. // Before CKEditor 4.4 wasn't a required argument, so we need to
  2928. // handle a case when it wasn't provided.
  2929. if ( !( editor instanceof CKEDITOR.editor ) )
  2930. return;
  2931. // Theoretically we could bypass checkApplicable, get widget from
  2932. // widgets.focused and check its name, what would be faster, but then
  2933. // this custom style would work differently than the default style
  2934. // which checks if it's applicable before applying or removeing itself.
  2935. if ( this.checkApplicable( editor.elementPath(), editor ) )
  2936. editor.widgets.focused.applyStyle( this );
  2937. },
  2938. remove: function( editor ) {
  2939. // Before CKEditor 4.4 wasn't a required argument, so we need to
  2940. // handle a case when it wasn't provided.
  2941. if ( !( editor instanceof CKEDITOR.editor ) )
  2942. return;
  2943. if ( this.checkApplicable( editor.elementPath(), editor ) )
  2944. editor.widgets.focused.removeStyle( this );
  2945. },
  2946. checkActive: function( elementPath, editor ) {
  2947. return this.checkElementMatch( elementPath.lastElement, 0, editor );
  2948. },
  2949. checkApplicable: function( elementPath, editor ) {
  2950. // Before CKEditor 4.4 wasn't a required argument, so we need to
  2951. // handle a case when it wasn't provided.
  2952. if ( !( editor instanceof CKEDITOR.editor ) )
  2953. return false;
  2954. return this.checkElement( elementPath.lastElement );
  2955. },
  2956. checkElementMatch: checkElementMatch,
  2957. checkElementRemovable: checkElementMatch,
  2958. /**
  2959. * Checks if an element is a {@link CKEDITOR.plugins.widget#wrapper wrapper} of a
  2960. * widget whose name matches the {@link #widget widget name} specified in the style definition.
  2961. *
  2962. * @param {CKEDITOR.dom.element} element
  2963. * @returns {Boolean}
  2964. */
  2965. checkElement: function( element ) {
  2966. if ( !Widget.isDomWidgetWrapper( element ) )
  2967. return false;
  2968. var widgetElement = element.getFirst( Widget.isDomWidgetElement );
  2969. return widgetElement && widgetElement.data( 'widget' ) == this.widget;
  2970. },
  2971. buildPreview: function( label ) {
  2972. return label || this._.definition.name;
  2973. },
  2974. /**
  2975. * Returns allowed content rules which should be registered for this style.
  2976. * Uses widget's {@link CKEDITOR.plugins.widget.definition#styleableElements} to make a rule
  2977. * allowing classes on specified elements or use widget's
  2978. * {@link CKEDITOR.plugins.widget.definition#styleToAllowedContentRules} method to transform a style
  2979. * into allowed content rules.
  2980. *
  2981. * @param {CKEDITOR.editor} The editor instance.
  2982. * @returns {CKEDITOR.filter.allowedContentRules}
  2983. */
  2984. toAllowedContentRules: function( editor ) {
  2985. if ( !editor )
  2986. return null;
  2987. var widgetDef = editor.widgets.registered[ this.widget ],
  2988. classes,
  2989. rule = {};
  2990. if ( !widgetDef )
  2991. return null;
  2992. if ( widgetDef.styleableElements ) {
  2993. classes = this.getClassesArray();
  2994. if ( !classes )
  2995. return null;
  2996. rule[ widgetDef.styleableElements ] = {
  2997. classes: classes,
  2998. propertiesOnly: true
  2999. };
  3000. return rule;
  3001. }
  3002. if ( widgetDef.styleToAllowedContentRules )
  3003. return widgetDef.styleToAllowedContentRules( this );
  3004. return null;
  3005. },
  3006. /**
  3007. * Returns classes defined in the style in form of an array.
  3008. *
  3009. * @returns {String[]}
  3010. */
  3011. getClassesArray: function() {
  3012. var classes = this._.definition.attributes && this._.definition.attributes[ 'class' ];
  3013. return classes ? CKEDITOR.tools.trim( classes ).split( /\s+/ ) : null;
  3014. },
  3015. /**
  3016. * Not implemented.
  3017. *
  3018. * @method applyToRange
  3019. */
  3020. applyToRange: notImplemented,
  3021. /**
  3022. * Not implemented.
  3023. *
  3024. * @method removeFromRange
  3025. */
  3026. removeFromRange: notImplemented,
  3027. /**
  3028. * Not implemented.
  3029. *
  3030. * @method applyToObject
  3031. */
  3032. applyToObject: notImplemented
  3033. } );
  3034. function notImplemented() {}
  3035. // @context style
  3036. function checkElementMatch( element, fullMatch, editor ) {
  3037. // Before CKEditor 4.4 wasn't a required argument, so we need to
  3038. // handle a case when it wasn't provided.
  3039. if ( !editor )
  3040. return false;
  3041. if ( !this.checkElement( element ) )
  3042. return false;
  3043. var widget = editor.widgets.getByElement( element, true );
  3044. return widget && widget.checkStyleActive( this );
  3045. }
  3046. } )();
  3047. //
  3048. // EXPOSE PUBLIC API ------------------------------------------------------
  3049. //
  3050. CKEDITOR.plugins.widget = Widget;
  3051. Widget.repository = Repository;
  3052. Widget.nestedEditable = NestedEditable;
  3053. } )();
  3054. /**
  3055. * An event fired when a widget definition is registered by the {@link CKEDITOR.plugins.widget.repository#add} method.
  3056. * It is possible to modify the definition being registered.
  3057. *
  3058. * @event widgetDefinition
  3059. * @member CKEDITOR.editor
  3060. * @param {CKEDITOR.plugins.widget.definition} data Widget definition.
  3061. */
  3062. /**
  3063. * This is an abstract class that describes the definition of a widget.
  3064. * It is a type of {@link CKEDITOR.plugins.widget.repository#add} method's second argument.
  3065. *
  3066. * Widget instances inherit from registered widget definitions, although not in a prototypal way.
  3067. * They are simply extended with corresponding widget definitions. Note that not all properties of
  3068. * the widget definition become properties of a widget. Some, like {@link #data} or {@link #edit}, become
  3069. * widget's events listeners.
  3070. *
  3071. * @class CKEDITOR.plugins.widget.definition
  3072. * @abstract
  3073. * @mixins CKEDITOR.feature
  3074. */
  3075. /**
  3076. * Widget definition name. It is automatically set when the definition is
  3077. * {@link CKEDITOR.plugins.widget.repository#add registered}.
  3078. *
  3079. * @property {String} name
  3080. */
  3081. /**
  3082. * The method executed while initializing a widget, after a widget instance
  3083. * is created, but before it is ready. It is executed before the first
  3084. * {@link CKEDITOR.plugins.widget#event-data} is fired so it is common to
  3085. * use the `init` method to populate widget data with information loaded from
  3086. * the DOM, like for exmaple:
  3087. *
  3088. * init: function() {
  3089. * this.setData( 'width', this.element.getStyle( 'width' ) );
  3090. *
  3091. * if ( this.parts.caption.getStyle( 'display' ) != 'none' )
  3092. * this.setData( 'showCaption', true );
  3093. * }
  3094. *
  3095. * @property {Function} init
  3096. */
  3097. /**
  3098. * The function to be used to upcast an element to this widget or a
  3099. * comma-separated list of upcast methods from the {@link #upcasts} object.
  3100. *
  3101. * The upcast function **is not** executed in the widget context (because the widget
  3102. * does not exist yet) and two arguments are passed:
  3103. *
  3104. * * `element` ({@link CKEDITOR.htmlParser.element}) &ndash; The element to be checked.
  3105. * * `data` (`Object`) &ndash; The object which can be extended with data which will then be passed to the widget.
  3106. *
  3107. * An element will be upcasted if a function returned `true` or an instance of
  3108. * a {@link CKEDITOR.htmlParser.element} if upcasting meant DOM structure changes
  3109. * (in this case the widget will be initialized on the returned element).
  3110. *
  3111. * @property {String/Function} upcast
  3112. */
  3113. /**
  3114. * The object containing functions which can be used to upcast this widget.
  3115. * Only those pointed by the {@link #upcast} property will be used.
  3116. *
  3117. * In most cases it is appropriate to use {@link #upcast} directly,
  3118. * because majority of widgets need just one method.
  3119. * However, in some cases the widget author may want to expose more than one variant
  3120. * and then this property may be used.
  3121. *
  3122. * upcasts: {
  3123. * // This function may upcast only figure elements.
  3124. * figure: function() {
  3125. * // ...
  3126. * },
  3127. * // This function may upcast only image elements.
  3128. * image: function() {
  3129. * // ...
  3130. * },
  3131. * // More variants...
  3132. * }
  3133. *
  3134. * // Then, widget user may choose which upcast methods will be enabled.
  3135. * editor.on( 'widgetDefinition', function( evt ) {
  3136. * if ( evt.data.name == 'image' )
  3137. * evt.data.upcast = 'figure,image'; // Use both methods.
  3138. * } );
  3139. *
  3140. * @property {Object} upcasts
  3141. */
  3142. /**
  3143. * The {@link #upcast} method(s) priority. The upcast with a lower priority number will be called before
  3144. * the one with a higher number. The default priority is `10`.
  3145. *
  3146. * @since 4.5
  3147. * @property {Number} [upcastPriority=10]
  3148. */
  3149. /**
  3150. * The function to be used to downcast this widget or
  3151. * a name of the downcast option from the {@link #downcasts} object.
  3152. *
  3153. * The downcast funciton will be executed in the {@link CKEDITOR.plugins.widget} context
  3154. * and with `widgetElement` ({@link CKEDITOR.htmlParser.element}) argument which is
  3155. * the widget's main element.
  3156. *
  3157. * The function may return an instance of the {@link CKEDITOR.htmlParser.node} class if the widget
  3158. * needs to be downcasted to a different node than the widget's main element.
  3159. *
  3160. * @property {String/Function} downcast
  3161. */
  3162. /**
  3163. * The object containing functions which can be used to downcast this widget.
  3164. * Only the one pointed by the {@link #downcast} property will be used.
  3165. *
  3166. * In most cases it is appropriate to use {@link #downcast} directly,
  3167. * because majority of widgets have just one variant of downcasting (or none at all).
  3168. * However, in some cases the widget author may want to expose more than one variant
  3169. * and then this property may be used.
  3170. *
  3171. * downcasts: {
  3172. * // This downcast may transform the widget into the figure element.
  3173. * figure: function() {
  3174. * // ...
  3175. * },
  3176. * // This downcast may transform the widget into the image element with data-* attributes.
  3177. * image: function() {
  3178. * // ...
  3179. * }
  3180. * }
  3181. *
  3182. * // Then, the widget user may choose one of the downcast options when setting up his editor.
  3183. * editor.on( 'widgetDefinition', function( evt ) {
  3184. * if ( evt.data.name == 'image' )
  3185. * evt.data.downcast = 'figure';
  3186. * } );
  3187. *
  3188. * @property downcasts
  3189. */
  3190. /**
  3191. * If set, it will be added as the {@link CKEDITOR.plugins.widget#event-edit} event listener.
  3192. * This means that it will be executed when a widget is being edited.
  3193. * See the {@link CKEDITOR.plugins.widget#method-edit} method.
  3194. *
  3195. * @property {Function} edit
  3196. */
  3197. /**
  3198. * If set, it will be added as the {@link CKEDITOR.plugins.widget#event-data} event listener.
  3199. * This means that it will be executed every time the {@link CKEDITOR.plugins.widget#property-data widget data} changes.
  3200. *
  3201. * @property {Function} data
  3202. */
  3203. /**
  3204. * The method to be executed when the widget's command is executed in order to insert a new widget
  3205. * (widget of this type is not focused). If not defined, then the default action will be
  3206. * performed which means that:
  3207. *
  3208. * * An instance of the widget will be created in a detached {@link CKEDITOR.dom.documentFragment document fragment},
  3209. * * The {@link CKEDITOR.plugins.widget#method-edit} method will be called to trigger widget editing,
  3210. * * The widget element will be inserted into DOM.
  3211. *
  3212. * @property {Function} insert
  3213. */
  3214. /**
  3215. * The name of a dialog window which will be opened on {@link CKEDITOR.plugins.widget#method-edit}.
  3216. * If not defined, then the {@link CKEDITOR.plugins.widget#method-edit} method will not perform any action and
  3217. * widget's command will insert a new widget without opening a dialog window first.
  3218. *
  3219. * @property {String} dialog
  3220. */
  3221. /**
  3222. * The template which will be used to create a new widget element (when the widget's command is executed).
  3223. * This string is populated with {@link #defaults default values} by using the {@link CKEDITOR.template} format.
  3224. * Therefore it has to be a valid {@link CKEDITOR.template} argument.
  3225. *
  3226. * @property {String} template
  3227. */
  3228. /**
  3229. * The data object which will be used to populate the data of a newly created widget.
  3230. * See {@link CKEDITOR.plugins.widget#property-data}.
  3231. *
  3232. * defaults: {
  3233. * showCaption: true,
  3234. * align: 'none'
  3235. * }
  3236. *
  3237. * @property defaults
  3238. */
  3239. /**
  3240. * An object containing definitions of widget components (part name => CSS selector).
  3241. *
  3242. * parts: {
  3243. * image: 'img',
  3244. * caption: 'div.caption'
  3245. * }
  3246. *
  3247. * @property parts
  3248. */
  3249. /**
  3250. * An object containing definitions of nested editables (editable name => {@link CKEDITOR.plugins.widget.nestedEditable.definition}).
  3251. * Note that editables *have to* be defined in the same order as they are in DOM / {@link CKEDITOR.plugins.widget.definition#template template}.
  3252. * Otherwise errors will occur when nesting widgets inside each other.
  3253. *
  3254. * editables: {
  3255. * header: 'h1',
  3256. * content: {
  3257. * selector: 'div.content',
  3258. * allowedContent: 'p strong em; a[!href]'
  3259. * }
  3260. * }
  3261. *
  3262. * @property editables
  3263. */
  3264. /**
  3265. * Widget name displayed in elements path.
  3266. *
  3267. * @property {String} pathName
  3268. */
  3269. /**
  3270. * If set to `true`, the widget's element will be covered with a transparent mask.
  3271. * This will prevent its content from being clickable, which matters in case
  3272. * of special elements like embedded Flash or iframes that generate a separate "context".
  3273. *
  3274. * @property {Boolean} mask
  3275. */
  3276. /**
  3277. * If set to `true/false`, it will force the widget to be either an inline or a block widget.
  3278. * If not set, the widget type will be determined from the widget element.
  3279. *
  3280. * Widget type influences whether a block (`div`) or an inline (`span`) element is used
  3281. * for the wrapper.
  3282. *
  3283. * @property {Boolean} inline
  3284. */
  3285. /**
  3286. * The label for the widget toolbar button.
  3287. *
  3288. * editor.widgets.add( 'simplebox', {
  3289. * button: 'Create a simple box'
  3290. * } );
  3291. *
  3292. * editor.widgets.add( 'simplebox', {
  3293. * button: editor.lang.simplebox.title
  3294. * } );
  3295. *
  3296. * @property {String} button
  3297. */
  3298. /**
  3299. * Whether widget should be draggable. Defaults to `true`.
  3300. * If set to `false` drag handler will not be displayed when hovering widget.
  3301. *
  3302. * @property {Boolean} draggable
  3303. */
  3304. /**
  3305. * Names of element(s) (separated by spaces) for which the {@link CKEDITOR.filter} should allow classes
  3306. * defined in the widget styles. For example if your widget is upcasted from a simple `<div>`
  3307. * element, then in order to make it styleable you can set:
  3308. *
  3309. * editor.widgets.add( 'customWidget', {
  3310. * upcast: function( element ) {
  3311. * return element.name == 'div';
  3312. * },
  3313. *
  3314. * // ...
  3315. *
  3316. * styleableElements: 'div'
  3317. * } );
  3318. *
  3319. * Then, when the following style is defined:
  3320. *
  3321. * {
  3322. * name: 'Thick border', type: 'widget', widget: 'customWidget',
  3323. * attributes: { 'class': 'thickBorder' }
  3324. * }
  3325. *
  3326. * a rule allowing the `thickBorder` class for `div` elements will be registered in the {@link CKEDITOR.filter}.
  3327. *
  3328. * If you need to have more freedom when transforming widget style to allowed content rules,
  3329. * you can use the {@link #styleToAllowedContentRules} callback.
  3330. *
  3331. * @since 4.4
  3332. * @property {String} styleableElements
  3333. */
  3334. /**
  3335. * Function transforming custom widget's {@link CKEDITOR.style} instance into
  3336. * {@link CKEDITOR.filter.allowedContentRules}. It may be used when a static
  3337. * {@link #styleableElements} property is not enough to inform the {@link CKEDITOR.filter}
  3338. * what HTML features should be enabled when allowing the given style.
  3339. *
  3340. * In most cases, when style's classes just have to be added to element name(s) used by
  3341. * the widget element, it is recommended to use simpler {@link #styleableElements} property.
  3342. *
  3343. * In order to get parsed classes from the style definition you can use
  3344. * {@link CKEDITOR.style.customHandlers.widget#getClassesArray}.
  3345. *
  3346. * For example, if you want to use the [object format of allowed content rules](#!/guide/dev_allowed_content_rules-section-object-format),
  3347. * to specify `match` validator, your implementation could look like this:
  3348. *
  3349. * editor.widgets.add( 'customWidget', {
  3350. * // ...
  3351. *
  3352. * styleToAllowedContentRules: funciton( style ) {
  3353. * // Retrieve classes defined in the style.
  3354. * var classes = style.getClassesArray();
  3355. *
  3356. * // Do something crazy - for example return allowed content rules in object format,
  3357. * // with custom match property and propertiesOnly flag.
  3358. * return {
  3359. * h1: {
  3360. * match: isWidgetElement,
  3361. * propertiesOnly: true,
  3362. * classes: classes
  3363. * }
  3364. * };
  3365. * }
  3366. * } );
  3367. *
  3368. * @since 4.4
  3369. * @property {Function} styleToAllowedContentRules
  3370. * @param {CKEDITOR.style.customHandlers.widget} style The style to be transformed.
  3371. * @returns {CKEDITOR.filter.allowedContentRules}
  3372. */
  3373. /**
  3374. * This is an abstract class that describes the definition of a widget's nested editable.
  3375. * It is a type of values in the {@link CKEDITOR.plugins.widget.definition#editables} object.
  3376. *
  3377. * In the simplest case the definition is a string which is a CSS selector used to
  3378. * find an element that will become a nested editable inside the widget. Note that
  3379. * the widget element can be a nested editable, too.
  3380. *
  3381. * In the more advanced case a definition is an object with a required `selector` property.
  3382. *
  3383. * editables: {
  3384. * header: 'h1',
  3385. * content: {
  3386. * selector: 'div.content',
  3387. * allowedContent: 'p strong em; a[!href]'
  3388. * }
  3389. * }
  3390. *
  3391. * @class CKEDITOR.plugins.widget.nestedEditable.definition
  3392. * @abstract
  3393. */
  3394. /**
  3395. * The CSS selector used to find an element which will become a nested editable.
  3396. *
  3397. * @property {String} selector
  3398. */
  3399. /**
  3400. * The [Advanced Content Filter](#!/guide/dev_advanced_content_filter) rules
  3401. * which will be used to limit the content allowed in this nested editable.
  3402. * This option is similar to {@link CKEDITOR.config#allowedContent} and one can
  3403. * use it to limit the editor features available in the nested editable.
  3404. *
  3405. * @property {CKEDITOR.filter.allowedContentRules} allowedContent
  3406. */
  3407. /**
  3408. * Nested editable name displayed in elements path.
  3409. *
  3410. * @property {String} pathName
  3411. */