bbcode.js 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649
  1. /**
  2. * SCEditor BBCode Plugin
  3. * http://www.sceditor.com/
  4. *
  5. * Copyright (C) 2011-2017, Sam Clarke (samclarke.com)
  6. *
  7. * SCEditor is licensed under the MIT license:
  8. * http://www.opensource.org/licenses/mit-license.php
  9. *
  10. * @fileoverview SCEditor BBCode Format
  11. * @author Sam Clarke
  12. */
  13. (function (sceditor) {
  14. /*eslint max-depth: off*/
  15. 'use strict';
  16. var escapeEntities = sceditor.escapeEntities;
  17. var escapeUriScheme = sceditor.escapeUriScheme;
  18. var dom = sceditor.dom;
  19. var utils = sceditor.utils;
  20. var css = dom.css;
  21. var attr = dom.attr;
  22. var is = dom.is;
  23. var extend = utils.extend;
  24. var each = utils.each;
  25. var EMOTICON_DATA_ATTR = 'data-sceditor-emoticon';
  26. var getEditorCommand = sceditor.command.get;
  27. var QuoteType = {
  28. /** @lends BBCodeParser.QuoteType */
  29. /**
  30. * Always quote the attribute value
  31. * @type {Number}
  32. */
  33. always: 1,
  34. /**
  35. * Never quote the attributes value
  36. * @type {Number}
  37. */
  38. never: 2,
  39. /**
  40. * Only quote the attributes value when it contains spaces to equals
  41. * @type {Number}
  42. */
  43. auto: 3
  44. };
  45. var defaultCommandsOverrides = {
  46. bold: {
  47. txtExec: ['[b]', '[/b]']
  48. },
  49. italic: {
  50. txtExec: ['[i]', '[/i]']
  51. },
  52. underline: {
  53. txtExec: ['[u]', '[/u]']
  54. },
  55. strike: {
  56. txtExec: ['[s]', '[/s]']
  57. },
  58. subscript: {
  59. txtExec: ['[sub]', '[/sub]']
  60. },
  61. superscript: {
  62. txtExec: ['[sup]', '[/sup]']
  63. },
  64. left: {
  65. txtExec: ['[left]', '[/left]']
  66. },
  67. center: {
  68. txtExec: ['[center]', '[/center]']
  69. },
  70. right: {
  71. txtExec: ['[right]', '[/right]']
  72. },
  73. justify: {
  74. txtExec: ['[justify]', '[/justify]']
  75. },
  76. font: {
  77. txtExec: function (caller) {
  78. var editor = this;
  79. getEditorCommand('font')._dropDown(
  80. editor,
  81. caller,
  82. function (fontName) {
  83. editor.insertText(
  84. '[font=' + fontName + ']',
  85. '[/font]'
  86. );
  87. }
  88. );
  89. }
  90. },
  91. size: {
  92. txtExec: function (caller) {
  93. var editor = this;
  94. getEditorCommand('size')._dropDown(
  95. editor,
  96. caller,
  97. function (fontSize) {
  98. editor.insertText(
  99. '[size=' + fontSize + ']',
  100. '[/size]'
  101. );
  102. }
  103. );
  104. }
  105. },
  106. color: {
  107. txtExec: function (caller) {
  108. var editor = this;
  109. getEditorCommand('color')._dropDown(
  110. editor,
  111. caller,
  112. function (color) {
  113. editor.insertText(
  114. '[color=' + color + ']',
  115. '[/color]'
  116. );
  117. }
  118. );
  119. }
  120. },
  121. bulletlist: {
  122. txtExec: function (caller, selected) {
  123. this.insertText(
  124. '[ul]\n[li]' +
  125. selected.split(/\r?\n/).join('[/li]\n[li]') +
  126. '[/li]\n[/ul]'
  127. );
  128. }
  129. },
  130. orderedlist: {
  131. txtExec: function (caller, selected) {
  132. this.insertText(
  133. '[ol]\n[li]' +
  134. selected.split(/\r?\n/).join('[/li]\n[li]') +
  135. '[/li]\n[/ol]'
  136. );
  137. }
  138. },
  139. table: {
  140. txtExec: ['[table][tr][td]', '[/td][/tr][/table]']
  141. },
  142. horizontalrule: {
  143. txtExec: ['[hr]']
  144. },
  145. code: {
  146. txtExec: ['[code]', '[/code]']
  147. },
  148. image: {
  149. txtExec: function (caller, selected) {
  150. var editor = this;
  151. getEditorCommand('image')._dropDown(
  152. editor,
  153. caller,
  154. selected,
  155. function (url, width, height) {
  156. var attrs = '';
  157. if (width) {
  158. attrs += ' width=' + width;
  159. }
  160. if (height) {
  161. attrs += ' height=' + height;
  162. }
  163. editor.insertText(
  164. '[img' + attrs + ']' + url + '[/img]'
  165. );
  166. }
  167. );
  168. }
  169. },
  170. email: {
  171. txtExec: function (caller, selected) {
  172. var editor = this;
  173. getEditorCommand('email')._dropDown(
  174. editor,
  175. caller,
  176. function (url, text) {
  177. editor.insertText(
  178. '[email=' + url + ']' +
  179. (text || selected || url) +
  180. '[/email]'
  181. );
  182. }
  183. );
  184. }
  185. },
  186. link: {
  187. txtExec: function (caller, selected) {
  188. var editor = this;
  189. getEditorCommand('link')._dropDown(
  190. editor,
  191. caller,
  192. function (url, text) {
  193. editor.insertText(
  194. '[url=' + url + ']' +
  195. (text || selected || url) +
  196. '[/url]'
  197. );
  198. }
  199. );
  200. }
  201. },
  202. quote: {
  203. txtExec: ['[quote]', '[/quote]']
  204. },
  205. youtube: {
  206. txtExec: function (caller) {
  207. var editor = this;
  208. getEditorCommand('youtube')._dropDown(
  209. editor,
  210. caller,
  211. function (id) {
  212. editor.insertText('[youtube]' + id + '[/youtube]');
  213. }
  214. );
  215. }
  216. },
  217. rtl: {
  218. txtExec: ['[rtl]', '[/rtl]']
  219. },
  220. ltr: {
  221. txtExec: ['[ltr]', '[/ltr]']
  222. }
  223. };
  224. var bbcodeHandlers = {
  225. // START_COMMAND: Bold
  226. b: {
  227. tags: {
  228. b: null,
  229. strong: null
  230. },
  231. styles: {
  232. // 401 is for FF 3.5
  233. 'font-weight': ['bold', 'bolder', '401', '700', '800', '900']
  234. },
  235. format: '[b]{0}[/b]',
  236. html: '<strong>{0}</strong>'
  237. },
  238. // END_COMMAND
  239. // START_COMMAND: Italic
  240. i: {
  241. tags: {
  242. i: null,
  243. em: null
  244. },
  245. styles: {
  246. 'font-style': ['italic', 'oblique']
  247. },
  248. format: '[i]{0}[/i]',
  249. html: '<em>{0}</em>'
  250. },
  251. // END_COMMAND
  252. // START_COMMAND: Underline
  253. u: {
  254. tags: {
  255. u: null
  256. },
  257. styles: {
  258. 'text-decoration': ['underline']
  259. },
  260. format: '[u]{0}[/u]',
  261. html: '<u>{0}</u>'
  262. },
  263. // END_COMMAND
  264. // START_COMMAND: Strikethrough
  265. s: {
  266. tags: {
  267. s: null,
  268. strike: null
  269. },
  270. styles: {
  271. 'text-decoration': ['line-through']
  272. },
  273. format: '[s]{0}[/s]',
  274. html: '<s>{0}</s>'
  275. },
  276. // END_COMMAND
  277. // START_COMMAND: Subscript
  278. sub: {
  279. tags: {
  280. sub: null
  281. },
  282. format: '[sub]{0}[/sub]',
  283. html: '<sub>{0}</sub>'
  284. },
  285. // END_COMMAND
  286. // START_COMMAND: Superscript
  287. sup: {
  288. tags: {
  289. sup: null
  290. },
  291. format: '[sup]{0}[/sup]',
  292. html: '<sup>{0}</sup>'
  293. },
  294. // END_COMMAND
  295. // START_COMMAND: Font
  296. font: {
  297. tags: {
  298. font: {
  299. face: null
  300. }
  301. },
  302. styles: {
  303. 'font-family': null
  304. },
  305. quoteType: QuoteType.never,
  306. format: function (element, content) {
  307. var font;
  308. if (!is(element, 'font') || !(font = attr(element, 'face'))) {
  309. font = css(element, 'font-family');
  310. }
  311. return '[font=' + _stripQuotes(font) + ']' +
  312. content + '[/font]';
  313. },
  314. html: '<font face="{defaultattr}">{0}</font>'
  315. },
  316. // END_COMMAND
  317. // START_COMMAND: Size
  318. size: {
  319. tags: {
  320. font: {
  321. size: null
  322. }
  323. },
  324. styles: {
  325. 'font-size': null
  326. },
  327. format: function (element, content) {
  328. var fontSize = attr(element, 'size'),
  329. size = 2;
  330. if (!fontSize) {
  331. fontSize = css(element, 'fontSize');
  332. }
  333. // Most browsers return px value but IE returns 1-7
  334. if (fontSize.indexOf('px') > -1) {
  335. // convert size to an int
  336. fontSize = fontSize.replace('px', '') - 0;
  337. if (fontSize < 12) {
  338. size = 1;
  339. }
  340. if (fontSize > 15) {
  341. size = 3;
  342. }
  343. if (fontSize > 17) {
  344. size = 4;
  345. }
  346. if (fontSize > 23) {
  347. size = 5;
  348. }
  349. if (fontSize > 31) {
  350. size = 6;
  351. }
  352. if (fontSize > 47) {
  353. size = 7;
  354. }
  355. } else {
  356. size = fontSize;
  357. }
  358. return '[size=' + size + ']' + content + '[/size]';
  359. },
  360. html: '<font size="{defaultattr}">{!0}</font>'
  361. },
  362. // END_COMMAND
  363. // START_COMMAND: Color
  364. color: {
  365. tags: {
  366. font: {
  367. color: null
  368. }
  369. },
  370. styles: {
  371. color: null
  372. },
  373. quoteType: QuoteType.never,
  374. format: function (elm, content) {
  375. var color;
  376. if (!is(elm, 'font') || !(color = attr(elm, 'color'))) {
  377. color = elm.style.color || css(elm, 'color');
  378. }
  379. return '[color=' + _normaliseColour(color) + ']' +
  380. content + '[/color]';
  381. },
  382. html: function (token, attrs, content) {
  383. return '<font color="' +
  384. escapeEntities(_normaliseColour(attrs.defaultattr), true) +
  385. '">' + content + '</font>';
  386. }
  387. },
  388. // END_COMMAND
  389. // START_COMMAND: Lists
  390. ul: {
  391. tags: {
  392. ul: null
  393. },
  394. breakStart: true,
  395. isInline: false,
  396. skipLastLineBreak: true,
  397. format: '[ul]{0}[/ul]',
  398. html: '<ul>{0}</ul>'
  399. },
  400. list: {
  401. breakStart: true,
  402. isInline: false,
  403. skipLastLineBreak: true,
  404. html: '<ul>{0}</ul>'
  405. },
  406. ol: {
  407. tags: {
  408. ol: null
  409. },
  410. breakStart: true,
  411. isInline: false,
  412. skipLastLineBreak: true,
  413. format: '[ol]{0}[/ol]',
  414. html: '<ol>{0}</ol>'
  415. },
  416. li: {
  417. tags: {
  418. li: null
  419. },
  420. isInline: false,
  421. closedBy: ['/ul', '/ol', '/list', '*', 'li'],
  422. format: '[li]{0}[/li]',
  423. html: '<li>{0}</li>'
  424. },
  425. '*': {
  426. isInline: false,
  427. closedBy: ['/ul', '/ol', '/list', '*', 'li'],
  428. html: '<li>{0}</li>'
  429. },
  430. // END_COMMAND
  431. // START_COMMAND: Table
  432. table: {
  433. tags: {
  434. table: null
  435. },
  436. isInline: false,
  437. isHtmlInline: true,
  438. skipLastLineBreak: true,
  439. format: '[table]{0}[/table]',
  440. html: '<table>{0}</table>'
  441. },
  442. tr: {
  443. tags: {
  444. tr: null
  445. },
  446. isInline: false,
  447. skipLastLineBreak: true,
  448. format: '[tr]{0}[/tr]',
  449. html: '<tr>{0}</tr>'
  450. },
  451. th: {
  452. tags: {
  453. th: null
  454. },
  455. allowsEmpty: true,
  456. isInline: false,
  457. format: '[th]{0}[/th]',
  458. html: '<th>{0}</th>'
  459. },
  460. td: {
  461. tags: {
  462. td: null
  463. },
  464. allowsEmpty: true,
  465. isInline: false,
  466. format: '[td]{0}[/td]',
  467. html: '<td>{0}</td>'
  468. },
  469. // END_COMMAND
  470. // START_COMMAND: Emoticons
  471. emoticon: {
  472. allowsEmpty: true,
  473. tags: {
  474. img: {
  475. src: null,
  476. 'data-sceditor-emoticon': null
  477. }
  478. },
  479. format: function (element, content) {
  480. return attr(element, EMOTICON_DATA_ATTR) + content;
  481. },
  482. html: '{0}'
  483. },
  484. // END_COMMAND
  485. // START_COMMAND: Horizontal Rule
  486. hr: {
  487. tags: {
  488. hr: null
  489. },
  490. allowsEmpty: true,
  491. isSelfClosing: true,
  492. isInline: false,
  493. format: '[hr]{0}',
  494. html: '<hr />'
  495. },
  496. // END_COMMAND
  497. // START_COMMAND: Image
  498. img: {
  499. allowsEmpty: true,
  500. tags: {
  501. img: {
  502. src: null
  503. }
  504. },
  505. allowedChildren: ['#'],
  506. quoteType: QuoteType.never,
  507. format: function (element, content) {
  508. var width, height,
  509. attribs = '',
  510. style = function (name) {
  511. return element.style ? element.style[name] : null;
  512. };
  513. // check if this is an emoticon image
  514. if (attr(element, EMOTICON_DATA_ATTR)) {
  515. return content;
  516. }
  517. width = attr(element, 'width') || style('width');
  518. height = attr(element, 'height') || style('height');
  519. // only add width and height if one is specified
  520. if ((element.complete && (width || height)) ||
  521. (width && height)) {
  522. attribs = '=' + dom.width(element) + 'x' +
  523. dom.height(element);
  524. }
  525. return '[img' + attribs + ']' + attr(element, 'src') + '[/img]';
  526. },
  527. html: function (token, attrs, content) {
  528. var undef, width, height, match,
  529. attribs = '';
  530. // handle [img width=340 height=240]url[/img]
  531. width = attrs.width;
  532. height = attrs.height;
  533. // handle [img=340x240]url[/img]
  534. if (attrs.defaultattr) {
  535. match = attrs.defaultattr.split(/x/i);
  536. width = match[0];
  537. height = (match.length === 2 ? match[1] : match[0]);
  538. }
  539. if (width !== undef) {
  540. attribs += ' width="' + escapeEntities(width, true) + '"';
  541. }
  542. if (height !== undef) {
  543. attribs += ' height="' + escapeEntities(height, true) + '"';
  544. }
  545. return '<img' + attribs +
  546. ' src="' + escapeUriScheme(content) + '" />';
  547. }
  548. },
  549. // END_COMMAND
  550. // START_COMMAND: URL
  551. url: {
  552. allowsEmpty: true,
  553. tags: {
  554. a: {
  555. href: null
  556. }
  557. },
  558. quoteType: QuoteType.never,
  559. format: function (element, content) {
  560. var url = attr(element, 'href');
  561. // make sure this link is not an e-mail,
  562. // if it is return e-mail BBCode
  563. if (url.substr(0, 7) === 'mailto:') {
  564. return '[email="' + url.substr(7) + '"]' +
  565. content + '[/email]';
  566. }
  567. return '[url=' + url + ']' + content + '[/url]';
  568. },
  569. html: function (token, attrs, content) {
  570. attrs.defaultattr =
  571. escapeEntities(attrs.defaultattr, true) || content;
  572. return '<a href="' + escapeUriScheme(attrs.defaultattr) + '">' +
  573. content + '</a>';
  574. }
  575. },
  576. // END_COMMAND
  577. // START_COMMAND: E-mail
  578. email: {
  579. quoteType: QuoteType.never,
  580. html: function (token, attrs, content) {
  581. return '<a href="mailto:' +
  582. (escapeEntities(attrs.defaultattr, true) || content) +
  583. '">' + content + '</a>';
  584. }
  585. },
  586. // END_COMMAND
  587. // START_COMMAND: Quote
  588. quote: {
  589. tags: {
  590. blockquote: null
  591. },
  592. isInline: false,
  593. quoteType: QuoteType.never,
  594. format: function (element, content) {
  595. var authorAttr = 'data-author';
  596. var author = '';
  597. var cite;
  598. var children = element.children;
  599. for (var i = 0; !cite && i < children.length; i++) {
  600. if (is(children[i], 'cite')) {
  601. cite = children[i];
  602. }
  603. }
  604. if (cite || attr(element, authorAttr)) {
  605. author = cite && cite.textContent ||
  606. attr(element, authorAttr);
  607. attr(element, authorAttr, author);
  608. if (cite) {
  609. element.removeChild(cite);
  610. }
  611. content = this.elementToBbcode(element);
  612. author = '=' + author.replace(/(^\s+|\s+$)/g, '');
  613. if (cite) {
  614. element.insertBefore(cite, element.firstChild);
  615. }
  616. }
  617. return '[quote' + author + ']' + content + '[/quote]';
  618. },
  619. html: function (token, attrs, content) {
  620. if (attrs.defaultattr) {
  621. content = '<cite>' + escapeEntities(attrs.defaultattr) +
  622. '</cite>' + content;
  623. }
  624. return '<blockquote>' + content + '</blockquote>';
  625. }
  626. },
  627. // END_COMMAND
  628. // START_COMMAND: Code
  629. code: {
  630. tags: {
  631. code: null
  632. },
  633. isInline: false,
  634. allowedChildren: ['#', '#newline'],
  635. format: '[code]{0}[/code]',
  636. html: '<code>{0}</code>'
  637. },
  638. // END_COMMAND
  639. // START_COMMAND: Left
  640. left: {
  641. styles: {
  642. 'text-align': [
  643. 'left',
  644. '-webkit-left',
  645. '-moz-left',
  646. '-khtml-left'
  647. ]
  648. },
  649. isInline: false,
  650. allowsEmpty: true,
  651. format: '[left]{0}[/left]',
  652. html: '<div align="left">{0}</div>'
  653. },
  654. // END_COMMAND
  655. // START_COMMAND: Centre
  656. center: {
  657. styles: {
  658. 'text-align': [
  659. 'center',
  660. '-webkit-center',
  661. '-moz-center',
  662. '-khtml-center'
  663. ]
  664. },
  665. isInline: false,
  666. allowsEmpty: true,
  667. format: '[center]{0}[/center]',
  668. html: '<div align="center">{0}</div>'
  669. },
  670. // END_COMMAND
  671. // START_COMMAND: Right
  672. right: {
  673. styles: {
  674. 'text-align': [
  675. 'right',
  676. '-webkit-right',
  677. '-moz-right',
  678. '-khtml-right'
  679. ]
  680. },
  681. isInline: false,
  682. allowsEmpty: true,
  683. format: '[right]{0}[/right]',
  684. html: '<div align="right">{0}</div>'
  685. },
  686. // END_COMMAND
  687. // START_COMMAND: Justify
  688. justify: {
  689. styles: {
  690. 'text-align': [
  691. 'justify',
  692. '-webkit-justify',
  693. '-moz-justify',
  694. '-khtml-justify'
  695. ]
  696. },
  697. isInline: false,
  698. allowsEmpty: true,
  699. format: '[justify]{0}[/justify]',
  700. html: '<div align="justify">{0}</div>'
  701. },
  702. // END_COMMAND
  703. // START_COMMAND: YouTube
  704. youtube: {
  705. allowsEmpty: true,
  706. tags: {
  707. iframe: {
  708. 'data-youtube-id': null
  709. }
  710. },
  711. format: function (element, content) {
  712. element = attr(element, 'data-youtube-id');
  713. return element ? '[youtube]' + element + '[/youtube]' : content;
  714. },
  715. html: '<iframe width="560" height="315" frameborder="0" ' +
  716. 'src="https://www.youtube-nocookie.com/embed/{0}?wmode=opaque" ' +
  717. 'data-youtube-id="{0}" allowfullscreen></iframe>'
  718. },
  719. // END_COMMAND
  720. // START_COMMAND: Rtl
  721. rtl: {
  722. styles: {
  723. direction: ['rtl']
  724. },
  725. isInline: false,
  726. format: '[rtl]{0}[/rtl]',
  727. html: '<div style="direction: rtl">{0}</div>'
  728. },
  729. // END_COMMAND
  730. // START_COMMAND: Ltr
  731. ltr: {
  732. styles: {
  733. direction: ['ltr']
  734. },
  735. isInline: false,
  736. format: '[ltr]{0}[/ltr]',
  737. html: '<div style="direction: ltr">{0}</div>'
  738. },
  739. // END_COMMAND
  740. // this is here so that commands above can be removed
  741. // without having to remove the , after the last one.
  742. // Needed for IE.
  743. ignore: {}
  744. };
  745. /**
  746. * Formats a string replacing {name} with the values of
  747. * obj.name properties.
  748. *
  749. * If there is no property for the specified {name} then
  750. * it will be left intact.
  751. *
  752. * @param {string} str
  753. * @param {Object} obj
  754. * @return {string}
  755. * @since 2.0.0
  756. */
  757. function formatBBCodeString(str, obj) {
  758. return str.replace(/\{([^}]+)\}/g, function (match, group) {
  759. var undef,
  760. escape = true;
  761. if (group.charAt(0) === '!') {
  762. escape = false;
  763. group = group.substring(1);
  764. }
  765. if (group === '0') {
  766. escape = false;
  767. }
  768. if (obj[group] === undef) {
  769. return match;
  770. }
  771. return escape ? escapeEntities(obj[group], true) : obj[group];
  772. });
  773. }
  774. function isFunction(fn) {
  775. return typeof fn === 'function';
  776. }
  777. /**
  778. * Removes any leading or trailing quotes ('")
  779. *
  780. * @return string
  781. * @since v1.4.0
  782. */
  783. function _stripQuotes(str) {
  784. return str ?
  785. str.replace(/\\(.)/g, '$1').replace(/^(["'])(.*?)\1$/, '$2') : str;
  786. }
  787. /**
  788. * Formats a string replacing {0}, {1}, {2}, ect. with
  789. * the params provided
  790. *
  791. * @param {string} str The string to format
  792. * @param {...string} arg The strings to replace
  793. * @return {string}
  794. * @since v1.4.0
  795. */
  796. function _formatString(str) {
  797. var undef;
  798. var args = arguments;
  799. return str.replace(/\{(\d+)\}/g, function (_, matchNum) {
  800. return args[matchNum - 0 + 1] !== undef ?
  801. args[matchNum - 0 + 1] :
  802. '{' + matchNum + '}';
  803. });
  804. }
  805. var TOKEN_OPEN = 'open';
  806. var TOKEN_CONTENT = 'content';
  807. var TOKEN_NEWLINE = 'newline';
  808. var TOKEN_CLOSE = 'close';
  809. /*
  810. * @typedef {Object} TokenizeToken
  811. * @property {string} type
  812. * @property {string} name
  813. * @property {string} val
  814. * @property {Object.<string, string>} attrs
  815. * @property {array} children
  816. * @property {TokenizeToken} closing
  817. */
  818. /**
  819. * Tokenize token object
  820. *
  821. * @param {string} type The type of token this is,
  822. * should be one of tokenType
  823. * @param {string} name The name of this token
  824. * @param {string} val The originally matched string
  825. * @param {array} attrs Any attributes. Only set on
  826. * TOKEN_TYPE_OPEN tokens
  827. * @param {array} children Any children of this token
  828. * @param {TokenizeToken} closing This tokens closing tag.
  829. * Only set on TOKEN_TYPE_OPEN tokens
  830. * @class {TokenizeToken}
  831. * @name {TokenizeToken}
  832. * @memberOf BBCodeParser.prototype
  833. */
  834. // eslint-disable-next-line max-params
  835. function TokenizeToken(type, name, val, attrs, children, closing) {
  836. var base = this;
  837. base.type = type;
  838. base.name = name;
  839. base.val = val;
  840. base.attrs = attrs || {};
  841. base.children = children || [];
  842. base.closing = closing || null;
  843. };
  844. TokenizeToken.prototype = {
  845. /** @lends BBCodeParser.prototype.TokenizeToken */
  846. /**
  847. * Clones this token
  848. *
  849. * @return {TokenizeToken}
  850. */
  851. clone: function () {
  852. var base = this;
  853. return new TokenizeToken(
  854. base.type,
  855. base.name,
  856. base.val,
  857. extend({}, base.attrs),
  858. [],
  859. base.closing ? base.closing.clone() : null
  860. );
  861. },
  862. /**
  863. * Splits this token at the specified child
  864. *
  865. * @param {TokenizeToken} splitAt The child to split at
  866. * @return {TokenizeToken} The right half of the split token or
  867. * empty clone if invalid splitAt lcoation
  868. */
  869. splitAt: function (splitAt) {
  870. var offsetLength;
  871. var base = this;
  872. var clone = base.clone();
  873. var offset = base.children.indexOf(splitAt);
  874. if (offset > -1) {
  875. // Work out how many items are on the right side of the split
  876. // to pass to splice()
  877. offsetLength = base.children.length - offset;
  878. clone.children = base.children.splice(offset, offsetLength);
  879. }
  880. return clone;
  881. }
  882. };
  883. /**
  884. * SCEditor BBCode parser class
  885. *
  886. * @param {Object} options
  887. * @class BBCodeParser
  888. * @name BBCodeParser
  889. * @since v1.4.0
  890. */
  891. function BBCodeParser(options) {
  892. var base = this;
  893. base.opts = extend({}, BBCodeParser.defaults, options);
  894. /**
  895. * Takes a BBCode string and splits it into open,
  896. * content and close tags.
  897. *
  898. * It does no checking to verify a tag has a matching open
  899. * or closing tag or if the tag is valid child of any tag
  900. * before it. For that the tokens should be passed to the
  901. * parse function.
  902. *
  903. * @param {string} str
  904. * @return {array}
  905. * @memberOf BBCodeParser.prototype
  906. */
  907. base.tokenize = function (str) {
  908. var matches, type, i;
  909. var tokens = [];
  910. // The token types in reverse order of precedence
  911. // (they're looped in reverse)
  912. var tokenTypes = [
  913. {
  914. type: TOKEN_CONTENT,
  915. regex: /^([^\[\r\n]+|\[)/
  916. },
  917. {
  918. type: TOKEN_NEWLINE,
  919. regex: /^(\r\n|\r|\n)/
  920. },
  921. {
  922. type: TOKEN_OPEN,
  923. regex: /^\[[^\[\]]+\]/
  924. },
  925. // Close must come before open as they are
  926. // the same except close has a / at the start.
  927. {
  928. type: TOKEN_CLOSE,
  929. regex: /^\[\/[^\[\]]+\]/
  930. }
  931. ];
  932. strloop:
  933. while (str.length) {
  934. i = tokenTypes.length;
  935. while (i--) {
  936. type = tokenTypes[i].type;
  937. // Check if the string matches any of the tokens
  938. if (!(matches = str.match(tokenTypes[i].regex)) ||
  939. !matches[0]) {
  940. continue;
  941. }
  942. // Add the match to the tokens list
  943. tokens.push(tokenizeTag(type, matches[0]));
  944. // Remove the match from the string
  945. str = str.substr(matches[0].length);
  946. // The token has been added so start again
  947. continue strloop;
  948. }
  949. // If there is anything left in the string which doesn't match
  950. // any of the tokens then just assume it's content and add it.
  951. if (str.length) {
  952. tokens.push(tokenizeTag(TOKEN_CONTENT, str));
  953. }
  954. str = '';
  955. }
  956. return tokens;
  957. };
  958. /**
  959. * Extracts the name an params from a tag
  960. *
  961. * @param {string} type
  962. * @param {string} val
  963. * @return {Object}
  964. * @private
  965. */
  966. function tokenizeTag(type, val) {
  967. var matches, attrs, name,
  968. openRegex = /\[([^\]\s=]+)(?:([^\]]+))?\]/,
  969. closeRegex = /\[\/([^\[\]]+)\]/;
  970. // Extract the name and attributes from opening tags and
  971. // just the name from closing tags.
  972. if (type === TOKEN_OPEN && (matches = val.match(openRegex))) {
  973. name = lower(matches[1]);
  974. if (matches[2] && (matches[2] = matches[2].trim())) {
  975. attrs = tokenizeAttrs(matches[2]);
  976. }
  977. }
  978. if (type === TOKEN_CLOSE &&
  979. (matches = val.match(closeRegex))) {
  980. name = lower(matches[1]);
  981. }
  982. if (type === TOKEN_NEWLINE) {
  983. name = '#newline';
  984. }
  985. // Treat all tokens without a name and
  986. // all unknown BBCodes as content
  987. if (!name || ((type === TOKEN_OPEN || type === TOKEN_CLOSE) &&
  988. !bbcodeHandlers[name])) {
  989. type = TOKEN_CONTENT;
  990. name = '#';
  991. }
  992. return new TokenizeToken(type, name, val, attrs);
  993. }
  994. /**
  995. * Extracts the individual attributes from a string containing
  996. * all the attributes.
  997. *
  998. * @param {string} attrs
  999. * @return {Object} Assoc array of attributes
  1000. * @private
  1001. */
  1002. function tokenizeAttrs(attrs) {
  1003. var matches,
  1004. /*
  1005. ([^\s=]+) Anything that's not a space or equals
  1006. = Equals sign =
  1007. (?:
  1008. (?:
  1009. (["']) The opening quote
  1010. (
  1011. (?:\\\2|[^\2])*? Anything that isn't the
  1012. unescaped opening quote
  1013. )
  1014. \2 The opening quote again which
  1015. will close the string
  1016. )
  1017. | If not a quoted string then match
  1018. (
  1019. (?:.(?!\s\S+=))*.? Anything that isn't part of
  1020. [space][non-space][=] which
  1021. would be a new attribute
  1022. )
  1023. )
  1024. */
  1025. attrRegex = /([^\s=]+)=(?:(?:(["'])((?:\\\2|[^\2])*?)\2)|((?:.(?!\s\S+=))*.))/g,
  1026. ret = {};
  1027. // if only one attribute then remove the = from the start and
  1028. // strip any quotes
  1029. if (attrs.charAt(0) === '=' && attrs.indexOf('=', 1) < 0) {
  1030. ret.defaultattr = _stripQuotes(attrs.substr(1));
  1031. } else {
  1032. if (attrs.charAt(0) === '=') {
  1033. attrs = 'defaultattr' + attrs;
  1034. }
  1035. // No need to strip quotes here, the regex will do that.
  1036. while ((matches = attrRegex.exec(attrs))) {
  1037. ret[lower(matches[1])] =
  1038. _stripQuotes(matches[3]) || matches[4];
  1039. }
  1040. }
  1041. return ret;
  1042. }
  1043. /**
  1044. * Parses a string into an array of BBCodes
  1045. *
  1046. * @param {string} str
  1047. * @param {boolean} preserveNewLines If to preserve all new lines, not
  1048. * strip any based on the passed
  1049. * formatting options
  1050. * @return {array} Array of BBCode objects
  1051. * @memberOf BBCodeParser.prototype
  1052. */
  1053. base.parse = function (str, preserveNewLines) {
  1054. var ret = parseTokens(base.tokenize(str));
  1055. var opts = base.opts;
  1056. if (opts.fixInvalidNesting) {
  1057. fixNesting(ret);
  1058. }
  1059. normaliseNewLines(ret, null, preserveNewLines);
  1060. if (opts.removeEmptyTags) {
  1061. removeEmpty(ret);
  1062. }
  1063. return ret;
  1064. };
  1065. /**
  1066. * Checks if an array of TokenizeToken's contains the
  1067. * specified token.
  1068. *
  1069. * Checks the tokens name and type match another tokens
  1070. * name and type in the array.
  1071. *
  1072. * @param {string} name
  1073. * @param {string} type
  1074. * @param {array} arr
  1075. * @return {Boolean}
  1076. * @private
  1077. */
  1078. function hasTag(name, type, arr) {
  1079. var i = arr.length;
  1080. while (i--) {
  1081. if (arr[i].type === type && arr[i].name === name) {
  1082. return true;
  1083. }
  1084. }
  1085. return false;
  1086. }
  1087. /**
  1088. * Checks if the child tag is allowed as one
  1089. * of the parent tags children.
  1090. *
  1091. * @param {TokenizeToken} parent
  1092. * @param {TokenizeToken} child
  1093. * @return {Boolean}
  1094. * @private
  1095. */
  1096. function isChildAllowed(parent, child) {
  1097. var parentBBCode = parent ? bbcodeHandlers[parent.name] : {},
  1098. allowedChildren = parentBBCode.allowedChildren;
  1099. if (base.opts.fixInvalidChildren && allowedChildren) {
  1100. return allowedChildren.indexOf(child.name || '#') > -1;
  1101. }
  1102. return true;
  1103. }
  1104. // TODO: Tidy this parseTokens() function up a bit.
  1105. /**
  1106. * Parses an array of tokens created by tokenize()
  1107. *
  1108. * @param {array} toks
  1109. * @return {array} Parsed tokens
  1110. * @see tokenize()
  1111. * @private
  1112. */
  1113. function parseTokens(toks) {
  1114. var token, bbcode, curTok, clone, i, next,
  1115. cloned = [],
  1116. output = [],
  1117. openTags = [],
  1118. /**
  1119. * Returns the currently open tag or undefined
  1120. * @return {TokenizeToken}
  1121. */
  1122. currentTag = function () {
  1123. return last(openTags);
  1124. },
  1125. /**
  1126. * Adds a tag to either the current tags children
  1127. * or to the output array.
  1128. * @param {TokenizeToken} token
  1129. * @private
  1130. */
  1131. addTag = function (token) {
  1132. if (currentTag()) {
  1133. currentTag().children.push(token);
  1134. } else {
  1135. output.push(token);
  1136. }
  1137. },
  1138. /**
  1139. * Checks if this tag closes the current tag
  1140. * @param {string} name
  1141. * @return {Void}
  1142. */
  1143. closesCurrentTag = function (name) {
  1144. return currentTag() &&
  1145. (bbcode = bbcodeHandlers[currentTag().name]) &&
  1146. bbcode.closedBy &&
  1147. bbcode.closedBy.indexOf(name) > -1;
  1148. };
  1149. while ((token = toks.shift())) {
  1150. next = toks[0];
  1151. /*
  1152. * Fixes any invalid children.
  1153. *
  1154. * If it is an element which isn't allowed as a child of it's
  1155. * parent then it will be converted to content of the parent
  1156. * element. i.e.
  1157. * [code]Code [b]only[/b] allows text.[/code]
  1158. * Will become:
  1159. * <code>Code [b]only[/b] allows text.</code>
  1160. * Instead of:
  1161. * <code>Code <b>only</b> allows text.</code>
  1162. */
  1163. // Ignore tags that can't be children
  1164. if (!isChildAllowed(currentTag(), token)) {
  1165. // exclude closing tags of current tag
  1166. if (token.type !== TOKEN_CLOSE || !currentTag() ||
  1167. token.name !== currentTag().name) {
  1168. token.name = '#';
  1169. token.type = TOKEN_CONTENT;
  1170. }
  1171. }
  1172. switch (token.type) {
  1173. case TOKEN_OPEN:
  1174. // Check it this closes a parent,
  1175. // e.g. for lists [*]one [*]two
  1176. if (closesCurrentTag(token.name)) {
  1177. openTags.pop();
  1178. }
  1179. addTag(token);
  1180. bbcode = bbcodeHandlers[token.name];
  1181. // If this tag is not self closing and it has a closing
  1182. // tag then it is open and has children so add it to the
  1183. // list of open tags. If has the closedBy property then
  1184. // it is closed by other tags so include everything as
  1185. // it's children until one of those tags is reached.
  1186. if (bbcode && !bbcode.isSelfClosing &&
  1187. (bbcode.closedBy ||
  1188. hasTag(token.name, TOKEN_CLOSE, toks))) {
  1189. openTags.push(token);
  1190. } else if (!bbcode || !bbcode.isSelfClosing) {
  1191. token.type = TOKEN_CONTENT;
  1192. }
  1193. break;
  1194. case TOKEN_CLOSE:
  1195. // check if this closes the current tag,
  1196. // e.g. [/list] would close an open [*]
  1197. if (currentTag() && token.name !== currentTag().name &&
  1198. closesCurrentTag('/' + token.name)) {
  1199. openTags.pop();
  1200. }
  1201. // If this is closing the currently open tag just pop
  1202. // the close tag off the open tags array
  1203. if (currentTag() && token.name === currentTag().name) {
  1204. currentTag().closing = token;
  1205. openTags.pop();
  1206. // If this is closing an open tag that is the parent of
  1207. // the current tag then clone all the tags including the
  1208. // current one until reaching the parent that is being
  1209. // closed. Close the parent and then add the clones back
  1210. // in.
  1211. } else if (hasTag(token.name, TOKEN_OPEN, openTags)) {
  1212. // Remove the tag from the open tags
  1213. while ((curTok = openTags.pop())) {
  1214. // If it's the tag that is being closed then
  1215. // discard it and break the loop.
  1216. if (curTok.name === token.name) {
  1217. curTok.closing = token;
  1218. break;
  1219. }
  1220. // Otherwise clone this tag and then add any
  1221. // previously cloned tags as it's children
  1222. clone = curTok.clone();
  1223. if (cloned.length) {
  1224. clone.children.push(last(cloned));
  1225. }
  1226. cloned.push(clone);
  1227. }
  1228. // Place block linebreak before cloned tags
  1229. if (next && next.type === TOKEN_NEWLINE) {
  1230. bbcode = bbcodeHandlers[token.name];
  1231. if (bbcode && bbcode.isInline === false) {
  1232. addTag(next);
  1233. toks.shift();
  1234. }
  1235. }
  1236. // Add the last cloned child to the now current tag
  1237. // (the parent of the tag which was being closed)
  1238. addTag(last(cloned));
  1239. // Add all the cloned tags to the open tags list
  1240. i = cloned.length;
  1241. while (i--) {
  1242. openTags.push(cloned[i]);
  1243. }
  1244. cloned.length = 0;
  1245. // This tag is closing nothing so treat it as content
  1246. } else {
  1247. token.type = TOKEN_CONTENT;
  1248. addTag(token);
  1249. }
  1250. break;
  1251. case TOKEN_NEWLINE:
  1252. // handle things like
  1253. // [*]list\nitem\n[*]list1
  1254. // where it should come out as
  1255. // [*]list\nitem[/*]\n[*]list1[/*]
  1256. // instead of
  1257. // [*]list\nitem\n[/*][*]list1[/*]
  1258. if (currentTag() && next && closesCurrentTag(
  1259. (next.type === TOKEN_CLOSE ? '/' : '') +
  1260. next.name
  1261. )) {
  1262. // skip if the next tag is the closing tag for
  1263. // the option tag, i.e. [/*]
  1264. if (!(next.type === TOKEN_CLOSE &&
  1265. next.name === currentTag().name)) {
  1266. bbcode = bbcodeHandlers[currentTag().name];
  1267. if (bbcode && bbcode.breakAfter) {
  1268. openTags.pop();
  1269. } else if (bbcode &&
  1270. bbcode.isInline === false &&
  1271. base.opts.breakAfterBlock &&
  1272. bbcode.breakAfter !== false) {
  1273. openTags.pop();
  1274. }
  1275. }
  1276. }
  1277. addTag(token);
  1278. break;
  1279. default: // content
  1280. addTag(token);
  1281. break;
  1282. }
  1283. }
  1284. return output;
  1285. }
  1286. /**
  1287. * Normalise all new lines
  1288. *
  1289. * Removes any formatting new lines from the BBCode
  1290. * leaving only content ones. I.e. for a list:
  1291. *
  1292. * [list]
  1293. * [*] list item one
  1294. * with a line break
  1295. * [*] list item two
  1296. * [/list]
  1297. *
  1298. * would become
  1299. *
  1300. * [list] [*] list item one
  1301. * with a line break [*] list item two [/list]
  1302. *
  1303. * Which makes it easier to convert to HTML or add
  1304. * the formatting new lines back in when converting
  1305. * back to BBCode
  1306. *
  1307. * @param {array} children
  1308. * @param {TokenizeToken} parent
  1309. * @param {boolean} onlyRemoveBreakAfter
  1310. * @return {void}
  1311. */
  1312. function normaliseNewLines(children, parent, onlyRemoveBreakAfter) {
  1313. var token, left, right, parentBBCode, bbcode,
  1314. removedBreakEnd, removedBreakBefore, remove;
  1315. var childrenLength = children.length;
  1316. // TODO: this function really needs tidying up
  1317. if (parent) {
  1318. parentBBCode = bbcodeHandlers[parent.name];
  1319. }
  1320. var i = childrenLength;
  1321. while (i--) {
  1322. if (!(token = children[i])) {
  1323. continue;
  1324. }
  1325. if (token.type === TOKEN_NEWLINE) {
  1326. left = i > 0 ? children[i - 1] : null;
  1327. right = i < childrenLength - 1 ? children[i + 1] : null;
  1328. remove = false;
  1329. // Handle the start and end new lines
  1330. // e.g. [tag]\n and \n[/tag]
  1331. if (!onlyRemoveBreakAfter && parentBBCode &&
  1332. parentBBCode.isSelfClosing !== true) {
  1333. // First child of parent so must be opening line break
  1334. // (breakStartBlock, breakStart) e.g. [tag]\n
  1335. if (!left) {
  1336. if (parentBBCode.isInline === false &&
  1337. base.opts.breakStartBlock &&
  1338. parentBBCode.breakStart !== false) {
  1339. remove = true;
  1340. }
  1341. if (parentBBCode.breakStart) {
  1342. remove = true;
  1343. }
  1344. // Last child of parent so must be end line break
  1345. // (breakEndBlock, breakEnd)
  1346. // e.g. \n[/tag]
  1347. // remove last line break (breakEndBlock, breakEnd)
  1348. } else if (!removedBreakEnd && !right) {
  1349. if (parentBBCode.isInline === false &&
  1350. base.opts.breakEndBlock &&
  1351. parentBBCode.breakEnd !== false) {
  1352. remove = true;
  1353. }
  1354. if (parentBBCode.breakEnd) {
  1355. remove = true;
  1356. }
  1357. removedBreakEnd = remove;
  1358. }
  1359. }
  1360. if (left && left.type === TOKEN_OPEN) {
  1361. if ((bbcode = bbcodeHandlers[left.name])) {
  1362. if (!onlyRemoveBreakAfter) {
  1363. if (bbcode.isInline === false &&
  1364. base.opts.breakAfterBlock &&
  1365. bbcode.breakAfter !== false) {
  1366. remove = true;
  1367. }
  1368. if (bbcode.breakAfter) {
  1369. remove = true;
  1370. }
  1371. } else if (bbcode.isInline === false) {
  1372. remove = true;
  1373. }
  1374. }
  1375. }
  1376. if (!onlyRemoveBreakAfter && !removedBreakBefore &&
  1377. right && right.type === TOKEN_OPEN) {
  1378. if ((bbcode = bbcodeHandlers[right.name])) {
  1379. if (bbcode.isInline === false &&
  1380. base.opts.breakBeforeBlock &&
  1381. bbcode.breakBefore !== false) {
  1382. remove = true;
  1383. }
  1384. if (bbcode.breakBefore) {
  1385. remove = true;
  1386. }
  1387. removedBreakBefore = remove;
  1388. if (remove) {
  1389. children.splice(i, 1);
  1390. continue;
  1391. }
  1392. }
  1393. }
  1394. if (remove) {
  1395. children.splice(i, 1);
  1396. }
  1397. // reset double removedBreakBefore removal protection.
  1398. // This is needed for cases like \n\n[\tag] where
  1399. // only 1 \n should be removed but without this they both
  1400. // would be.
  1401. removedBreakBefore = false;
  1402. } else if (token.type === TOKEN_OPEN) {
  1403. normaliseNewLines(token.children, token,
  1404. onlyRemoveBreakAfter);
  1405. }
  1406. }
  1407. }
  1408. /**
  1409. * Fixes any invalid nesting.
  1410. *
  1411. * If it is a block level element inside 1 or more inline elements
  1412. * then those inline elements will be split at the point where the
  1413. * block level is and the block level element placed between the split
  1414. * parts. i.e.
  1415. * [inline]A[blocklevel]B[/blocklevel]C[/inline]
  1416. * Will become:
  1417. * [inline]A[/inline][blocklevel]B[/blocklevel][inline]C[/inline]
  1418. *
  1419. * @param {array} children
  1420. * @param {array} [parents] Null if there is no parents
  1421. * @param {boolea} [insideInline] If inside an inline element
  1422. * @param {array} [rootArr] Root array if there is one
  1423. * @return {array}
  1424. * @private
  1425. */
  1426. function fixNesting(children, parents, insideInline, rootArr) {
  1427. var token, i, parent, parentIndex, parentParentChildren, right;
  1428. var isInline = function (token) {
  1429. var bbcode = bbcodeHandlers[token.name];
  1430. return !bbcode || bbcode.isInline !== false;
  1431. };
  1432. parents = parents || [];
  1433. rootArr = rootArr || children;
  1434. // This must check the length each time as it can change when
  1435. // tokens are moved to fix the nesting.
  1436. for (i = 0; i < children.length; i++) {
  1437. if (!(token = children[i]) || token.type !== TOKEN_OPEN) {
  1438. continue;
  1439. }
  1440. if (insideInline && !isInline(token)) {
  1441. // if this is a blocklevel element inside an inline one then
  1442. // split the parent at the block level element
  1443. parent = last(parents);
  1444. right = parent.splitAt(token);
  1445. parentParentChildren = parents.length > 1 ?
  1446. parents[parents.length - 2].children : rootArr;
  1447. // If parent inline is allowed inside this tag, clone it and
  1448. // wrap this tags children in it.
  1449. if (isChildAllowed(token, parent)) {
  1450. var clone = parent.clone();
  1451. clone.children = token.children;
  1452. token.children = [clone];
  1453. }
  1454. parentIndex = parentParentChildren.indexOf(parent);
  1455. if (parentIndex > -1) {
  1456. // remove the block level token from the right side of
  1457. // the split inline element
  1458. right.children.splice(0, 1);
  1459. // insert the block level token and the right side after
  1460. // the left side of the inline token
  1461. parentParentChildren.splice(
  1462. parentIndex + 1, 0, token, right
  1463. );
  1464. // If token is a block and is followed by a newline,
  1465. // then move the newline along with it to the new parent
  1466. var next = right.children[0];
  1467. if (next && next.type === TOKEN_NEWLINE) {
  1468. if (!isInline(token)) {
  1469. right.children.splice(0, 1);
  1470. parentParentChildren.splice(
  1471. parentIndex + 2, 0, next
  1472. );
  1473. }
  1474. }
  1475. // return to parents loop as the
  1476. // children have now increased
  1477. return;
  1478. }
  1479. }
  1480. parents.push(token);
  1481. fixNesting(
  1482. token.children,
  1483. parents,
  1484. insideInline || isInline(token),
  1485. rootArr
  1486. );
  1487. parents.pop();
  1488. }
  1489. }
  1490. /**
  1491. * Removes any empty BBCodes which are not allowed to be empty.
  1492. *
  1493. * @param {array} tokens
  1494. * @private
  1495. */
  1496. function removeEmpty(tokens) {
  1497. var token, bbcode;
  1498. /**
  1499. * Checks if all children are whitespace or not
  1500. * @private
  1501. */
  1502. var isTokenWhiteSpace = function (children) {
  1503. var j = children.length;
  1504. while (j--) {
  1505. var type = children[j].type;
  1506. if (type === TOKEN_OPEN || type === TOKEN_CLOSE) {
  1507. return false;
  1508. }
  1509. if (type === TOKEN_CONTENT &&
  1510. /\S|\u00A0/.test(children[j].val)) {
  1511. return false;
  1512. }
  1513. }
  1514. return true;
  1515. };
  1516. var i = tokens.length;
  1517. while (i--) {
  1518. // So skip anything that isn't a tag since only tags can be
  1519. // empty, content can't
  1520. if (!(token = tokens[i]) || token.type !== TOKEN_OPEN) {
  1521. continue;
  1522. }
  1523. bbcode = bbcodeHandlers[token.name];
  1524. // Remove any empty children of this tag first so that if they
  1525. // are all removed this one doesn't think it's not empty.
  1526. removeEmpty(token.children);
  1527. if (isTokenWhiteSpace(token.children) && bbcode &&
  1528. !bbcode.isSelfClosing && !bbcode.allowsEmpty) {
  1529. tokens.splice.apply(tokens, [i, 1].concat(token.children));
  1530. }
  1531. }
  1532. }
  1533. /**
  1534. * Converts a BBCode string to HTML
  1535. *
  1536. * @param {string} str
  1537. * @param {boolean} preserveNewLines If to preserve all new lines, not
  1538. * strip any based on the passed
  1539. * formatting options
  1540. * @return {string}
  1541. * @memberOf BBCodeParser.prototype
  1542. */
  1543. base.toHTML = function (str, preserveNewLines) {
  1544. return convertToHTML(base.parse(str, preserveNewLines), true);
  1545. };
  1546. base.toHTMLFragment = function (str, preserveNewLines) {
  1547. return convertToHTML(base.parse(str, preserveNewLines), false);
  1548. };
  1549. /**
  1550. * @private
  1551. */
  1552. function convertToHTML(tokens, isRoot) {
  1553. var undef, token, bbcode, content, html, needsBlockWrap,
  1554. blockWrapOpen, isInline, lastChild,
  1555. ret = '';
  1556. isInline = function (bbcode) {
  1557. return (!bbcode || (bbcode.isHtmlInline !== undef ?
  1558. bbcode.isHtmlInline : bbcode.isInline)) !== false;
  1559. };
  1560. while (tokens.length > 0) {
  1561. if (!(token = tokens.shift())) {
  1562. continue;
  1563. }
  1564. if (token.type === TOKEN_OPEN) {
  1565. lastChild = token.children[token.children.length - 1] || {};
  1566. bbcode = bbcodeHandlers[token.name];
  1567. needsBlockWrap = isRoot && isInline(bbcode);
  1568. content = convertToHTML(token.children, false);
  1569. if (bbcode && bbcode.html) {
  1570. // Only add a line break to the end if this is
  1571. // blocklevel and the last child wasn't block-level
  1572. if (!isInline(bbcode) &&
  1573. isInline(bbcodeHandlers[lastChild.name]) &&
  1574. !bbcode.isPreFormatted &&
  1575. !bbcode.skipLastLineBreak) {
  1576. // Add placeholder br to end of block level
  1577. // elements
  1578. content += '<br />';
  1579. }
  1580. // Visman - удалить под одной пустой строке в начале и конце содержимого
  1581. content = content.replace(/^\x20*<br \/>/, '').replace(/<br \/>\x20*$/, '');
  1582. if (!isFunction(bbcode.html)) {
  1583. token.attrs['0'] = content;
  1584. html = formatBBCodeString(
  1585. bbcode.html,
  1586. token.attrs
  1587. );
  1588. } else {
  1589. html = bbcode.html.call(
  1590. base,
  1591. token,
  1592. token.attrs,
  1593. content
  1594. );
  1595. }
  1596. } else {
  1597. html = token.val + content +
  1598. (token.closing ? token.closing.val : '');
  1599. }
  1600. } else if (token.type === TOKEN_NEWLINE) {
  1601. if (!isRoot) {
  1602. ret += '<br />';
  1603. continue;
  1604. }
  1605. // If not already in a block wrap then start a new block
  1606. if (!blockWrapOpen) {
  1607. ret += '<div>';
  1608. }
  1609. ret += '<br />';
  1610. // Normally the div acts as a line-break with by moving
  1611. // whatever comes after onto a new line.
  1612. // If this is the last token, add an extra line-break so it
  1613. // shows as there will be nothing after it.
  1614. if (!tokens.length) {
  1615. ret += '<br />';
  1616. }
  1617. ret += '</div>\n';
  1618. blockWrapOpen = false;
  1619. continue;
  1620. // content
  1621. } else {
  1622. needsBlockWrap = isRoot;
  1623. html = escapeEntities(token.val, true);
  1624. }
  1625. if (needsBlockWrap && !blockWrapOpen) {
  1626. ret += '<div>';
  1627. blockWrapOpen = true;
  1628. } else if (!needsBlockWrap && blockWrapOpen) {
  1629. ret += '</div>\n';
  1630. blockWrapOpen = false;
  1631. }
  1632. ret += html;
  1633. }
  1634. if (blockWrapOpen) {
  1635. ret += '</div>\n';
  1636. }
  1637. return ret;
  1638. }
  1639. /**
  1640. * Takes a BBCode string, parses it then converts it back to BBCode.
  1641. *
  1642. * This will auto fix the BBCode and format it with the specified
  1643. * options.
  1644. *
  1645. * @param {string} str
  1646. * @param {boolean} preserveNewLines If to preserve all new lines, not
  1647. * strip any based on the passed
  1648. * formatting options
  1649. * @return {string}
  1650. * @memberOf BBCodeParser.prototype
  1651. */
  1652. base.toBBCode = function (str, preserveNewLines) {
  1653. return convertToBBCode(base.parse(str, preserveNewLines));
  1654. };
  1655. /**
  1656. * Converts parsed tokens back into BBCode with the
  1657. * formatting specified in the options and with any
  1658. * fixes specified.
  1659. *
  1660. * @param {array} toks Array of parsed tokens from base.parse()
  1661. * @return {string}
  1662. * @private
  1663. */
  1664. function convertToBBCode(toks) {
  1665. var token, attr, bbcode, isBlock, isSelfClosing, quoteType,
  1666. breakBefore, breakStart, breakEnd, breakAfter,
  1667. ret = '';
  1668. while (toks.length > 0) {
  1669. if (!(token = toks.shift())) {
  1670. continue;
  1671. }
  1672. // TODO: tidy this
  1673. bbcode = bbcodeHandlers[token.name];
  1674. isBlock = !(!bbcode || bbcode.isInline !== false);
  1675. isSelfClosing = bbcode && bbcode.isSelfClosing;
  1676. breakBefore = (isBlock && base.opts.breakBeforeBlock &&
  1677. bbcode.breakBefore !== false) ||
  1678. (bbcode && bbcode.breakBefore);
  1679. breakStart = (isBlock && !isSelfClosing &&
  1680. base.opts.breakStartBlock &&
  1681. bbcode.breakStart !== false) ||
  1682. (bbcode && bbcode.breakStart);
  1683. breakEnd = (isBlock && base.opts.breakEndBlock &&
  1684. bbcode.breakEnd !== false) ||
  1685. (bbcode && bbcode.breakEnd);
  1686. breakAfter = (isBlock && base.opts.breakAfterBlock &&
  1687. bbcode.breakAfter !== false) ||
  1688. (bbcode && bbcode.breakAfter);
  1689. quoteType = (bbcode ? bbcode.quoteType : null) ||
  1690. base.opts.quoteType || QuoteType.auto;
  1691. if (!bbcode && token.type === TOKEN_OPEN) {
  1692. ret += token.val;
  1693. if (token.children) {
  1694. ret += convertToBBCode(token.children);
  1695. }
  1696. if (token.closing) {
  1697. ret += token.closing.val;
  1698. }
  1699. } else if (token.type === TOKEN_OPEN) {
  1700. if (breakBefore) {
  1701. ret += '\n';
  1702. }
  1703. // Convert the tag and it's attributes to BBCode
  1704. ret += '[' + token.name;
  1705. if (token.attrs) {
  1706. if (token.attrs.defaultattr) {
  1707. ret += '=' + quote(
  1708. token.attrs.defaultattr,
  1709. quoteType,
  1710. 'defaultattr'
  1711. );
  1712. delete token.attrs.defaultattr;
  1713. }
  1714. for (attr in token.attrs) {
  1715. if (token.attrs.hasOwnProperty(attr)) {
  1716. ret += ' ' + attr + '=' +
  1717. quote(token.attrs[attr], quoteType, attr);
  1718. }
  1719. }
  1720. }
  1721. ret += ']';
  1722. if (breakStart) {
  1723. ret += '\n';
  1724. }
  1725. // Convert the tags children to BBCode
  1726. if (token.children) {
  1727. ret += convertToBBCode(token.children);
  1728. }
  1729. // add closing tag if not self closing
  1730. if (!isSelfClosing && !bbcode.excludeClosing) {
  1731. if (breakEnd) {
  1732. ret += '\n';
  1733. }
  1734. ret += '[/' + token.name + ']';
  1735. }
  1736. if (breakAfter) {
  1737. ret += '\n';
  1738. }
  1739. // preserve whatever was recognized as the
  1740. // closing tag if it is a self closing tag
  1741. if (token.closing && isSelfClosing) {
  1742. ret += token.closing.val;
  1743. }
  1744. } else {
  1745. ret += token.val;
  1746. }
  1747. }
  1748. return ret;
  1749. }
  1750. /**
  1751. * Quotes an attribute
  1752. *
  1753. * @param {string} str
  1754. * @param {BBCodeParser.QuoteType} quoteType
  1755. * @param {string} name
  1756. * @return {string}
  1757. * @private
  1758. */
  1759. function quote(str, quoteType, name) {
  1760. var needsQuotes = /\s|=/.test(str);
  1761. if (isFunction(quoteType)) {
  1762. return quoteType(str, name);
  1763. }
  1764. if (quoteType === QuoteType.never ||
  1765. (quoteType === QuoteType.auto && !needsQuotes)) {
  1766. return str;
  1767. }
  1768. return '"' + str.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
  1769. }
  1770. /**
  1771. * Returns the last element of an array or null
  1772. *
  1773. * @param {array} arr
  1774. * @return {Object} Last element
  1775. * @private
  1776. */
  1777. function last(arr) {
  1778. if (arr.length) {
  1779. return arr[arr.length - 1];
  1780. }
  1781. return null;
  1782. }
  1783. /**
  1784. * Converts a string to lowercase.
  1785. *
  1786. * @param {string} str
  1787. * @return {string} Lowercase version of str
  1788. * @private
  1789. */
  1790. function lower(str) {
  1791. return str.toLowerCase();
  1792. }
  1793. };
  1794. /**
  1795. * Quote type
  1796. * @type {Object}
  1797. * @class QuoteType
  1798. * @name BBCodeParser.QuoteType
  1799. * @since 1.4.0
  1800. */
  1801. BBCodeParser.QuoteType = QuoteType;
  1802. /**
  1803. * Default BBCode parser options
  1804. * @type {Object}
  1805. */
  1806. BBCodeParser.defaults = {
  1807. /**
  1808. * If to add a new line before block level elements
  1809. *
  1810. * @type {Boolean}
  1811. */
  1812. breakBeforeBlock: false,
  1813. /**
  1814. * If to add a new line after the start of block level elements
  1815. *
  1816. * @type {Boolean}
  1817. */
  1818. breakStartBlock: false,
  1819. /**
  1820. * If to add a new line before the end of block level elements
  1821. *
  1822. * @type {Boolean}
  1823. */
  1824. breakEndBlock: false,
  1825. /**
  1826. * If to add a new line after block level elements
  1827. *
  1828. * @type {Boolean}
  1829. */
  1830. breakAfterBlock: true,
  1831. /**
  1832. * If to remove empty tags
  1833. *
  1834. * @type {Boolean}
  1835. */
  1836. removeEmptyTags: true,
  1837. /**
  1838. * If to fix invalid nesting,
  1839. * i.e. block level elements inside inline elements.
  1840. *
  1841. * @type {Boolean}
  1842. */
  1843. fixInvalidNesting: true,
  1844. /**
  1845. * If to fix invalid children.
  1846. * i.e. A tag which is inside a parent that doesn't
  1847. * allow that type of tag.
  1848. *
  1849. * @type {Boolean}
  1850. */
  1851. fixInvalidChildren: true,
  1852. /**
  1853. * Attribute quote type
  1854. *
  1855. * @type {BBCodeParser.QuoteType}
  1856. * @since 1.4.1
  1857. */
  1858. quoteType: QuoteType.auto,
  1859. /**
  1860. * Whether to use strict matching on attributes and styles.
  1861. *
  1862. * When true this will perform AND matching requiring all tag
  1863. * attributes and styles to match.
  1864. *
  1865. * When false will perform OR matching and will match if any of
  1866. * a tags attributes or styles match.
  1867. *
  1868. * @type {Boolean}
  1869. * @since 3.1.0
  1870. */
  1871. strictMatch: false
  1872. };
  1873. /**
  1874. * Converts a number 0-255 to hex.
  1875. *
  1876. * Will return 00 if number is not a valid number.
  1877. *
  1878. * @param {any} number
  1879. * @return {string}
  1880. * @private
  1881. */
  1882. function toHex(number) {
  1883. number = parseInt(number, 10);
  1884. if (isNaN(number)) {
  1885. return '00';
  1886. }
  1887. number = Math.max(0, Math.min(number, 255)).toString(16);
  1888. return number.length < 2 ? '0' + number : number;
  1889. }
  1890. /**
  1891. * Normalises a CSS colour to hex #xxxxxx format
  1892. *
  1893. * @param {string} colorStr
  1894. * @return {string}
  1895. * @private
  1896. */
  1897. function _normaliseColour(colorStr) {
  1898. var match;
  1899. colorStr = colorStr || '#000';
  1900. // rgb(n,n,n);
  1901. if ((match =
  1902. colorStr.match(/rgb\((\d{1,3}),\s*?(\d{1,3}),\s*?(\d{1,3})\)/i))) {
  1903. return '#' +
  1904. toHex(match[1]) +
  1905. toHex(match[2]) +
  1906. toHex(match[3]);
  1907. }
  1908. // expand shorthand
  1909. if ((match = colorStr.match(/#([0-9a-f])([0-9a-f])([0-9a-f])\s*?$/i))) {
  1910. return '#' +
  1911. match[1] + match[1] +
  1912. match[2] + match[2] +
  1913. match[3] + match[3];
  1914. }
  1915. return colorStr;
  1916. }
  1917. /**
  1918. * SCEditor BBCode format
  1919. * @since 2.0.0
  1920. */
  1921. function bbcodeFormat() {
  1922. var base = this;
  1923. base.stripQuotes = _stripQuotes;
  1924. /**
  1925. * cache of all the tags pointing to their bbcodes to enable
  1926. * faster lookup of which bbcode a tag should have
  1927. * @private
  1928. */
  1929. var tagsToBBCodes = {};
  1930. /**
  1931. * Allowed children of specific HTML tags. Empty array if no
  1932. * children other than text nodes are allowed
  1933. * @private
  1934. */
  1935. var validChildren = {
  1936. ul: ['li', 'ol', 'ul'],
  1937. ol: ['li', 'ol', 'ul'],
  1938. table: ['tr'],
  1939. tr: ['td', 'th'],
  1940. code: ['br', 'p', 'div']
  1941. };
  1942. /**
  1943. * Populates tagsToBBCodes and stylesToBBCodes for easier lookups
  1944. *
  1945. * @private
  1946. */
  1947. function buildBbcodeCache() {
  1948. each(bbcodeHandlers, function (bbcode, handler) {
  1949. var
  1950. isBlock = handler.isInline === false,
  1951. tags = bbcodeHandlers[bbcode].tags,
  1952. styles = bbcodeHandlers[bbcode].styles;
  1953. if (styles) {
  1954. tagsToBBCodes['*'] = tagsToBBCodes['*'] || {};
  1955. tagsToBBCodes['*'][isBlock] =
  1956. tagsToBBCodes['*'][isBlock] || {};
  1957. tagsToBBCodes['*'][isBlock][bbcode] = [
  1958. ['style', Object.entries(styles)]
  1959. ];
  1960. }
  1961. if (tags) {
  1962. each(tags, function (tag, values) {
  1963. if (values && values.style) {
  1964. values.style = Object.entries(values.style);
  1965. }
  1966. tagsToBBCodes[tag] = tagsToBBCodes[tag] || {};
  1967. tagsToBBCodes[tag][isBlock] =
  1968. tagsToBBCodes[tag][isBlock] || {};
  1969. tagsToBBCodes[tag][isBlock][bbcode] =
  1970. values && Object.entries(values);
  1971. });
  1972. }
  1973. });
  1974. };
  1975. /**
  1976. * Handles adding newlines after block level elements
  1977. *
  1978. * @param {HTMLElement} element The element to convert
  1979. * @param {string} content The tags text content
  1980. * @return {string}
  1981. * @private
  1982. */
  1983. function handleBlockNewlines(element, content) {
  1984. var tag = element.nodeName.toLowerCase();
  1985. var isInline = dom.isInline;
  1986. if (!isInline(element, true) || tag === 'br') {
  1987. var isLastBlockChild, parent, parentLastChild,
  1988. previousSibling = element.previousSibling;
  1989. // Skips selection makers and ignored elements
  1990. // Skip empty inline elements
  1991. while (previousSibling &&
  1992. previousSibling.nodeType === 1 &&
  1993. !is(previousSibling, 'br') &&
  1994. isInline(previousSibling, true) &&
  1995. !previousSibling.firstChild) {
  1996. previousSibling = previousSibling.previousSibling;
  1997. }
  1998. // If it's the last block of an inline that is the last
  1999. // child of a block then it shouldn't cause a line break
  2000. // <block><inline><br></inline></block>
  2001. do {
  2002. parent = element.parentNode;
  2003. parentLastChild = parent && parent.lastChild;
  2004. isLastBlockChild = parentLastChild === element;
  2005. element = parent;
  2006. } while (parent && isLastBlockChild && isInline(parent, true));
  2007. // If this block is:
  2008. // * Not the last child of a block level element
  2009. // * Is a <li> tag (lists are blocks)
  2010. if (!isLastBlockChild || tag === 'li') {
  2011. content += '\n';
  2012. }
  2013. // Check for:
  2014. // <block>text<block>text</block></block>
  2015. //
  2016. // The second opening <block> opening tag should cause a
  2017. // line break because the previous sibing is inline.
  2018. if (tag !== 'br' && previousSibling &&
  2019. !is(previousSibling, 'br') &&
  2020. isInline(previousSibling, true)) {
  2021. content = '\n' + content;
  2022. }
  2023. }
  2024. return content;
  2025. }
  2026. /**
  2027. * Handles a HTML tag and finds any matching BBCodes
  2028. *
  2029. * @param {HTMLElement} element The element to convert
  2030. * @param {string} content The Tags text content
  2031. * @param {boolean} blockLevel
  2032. * @return {string} Content with any matching BBCode tags
  2033. * wrapped around it.
  2034. * @private
  2035. */
  2036. function handleTags(element, content, blockLevel) {
  2037. function isStyleMatch(style) {
  2038. var property = style[0];
  2039. var values = style[1];
  2040. var val = dom.getStyle(element, property);
  2041. var parent = element.parentNode;
  2042. // if the parent has the same style use that instead of this one
  2043. // so you don't end up with [i]parent[i]child[/i][/i]
  2044. if (!val || parent && dom.hasStyle(parent, property, val)) {
  2045. return false;
  2046. }
  2047. return !values || values.includes(val);
  2048. }
  2049. function createAttributeMatch(isStrict) {
  2050. return function (attribute) {
  2051. var name = attribute[0];
  2052. var value = attribute[1];
  2053. // code tags should skip most styles
  2054. if (name === 'style' && element.nodeName === 'CODE') {
  2055. return false;
  2056. }
  2057. if (name === 'style' && value) {
  2058. return value[isStrict ? 'every' : 'some'](isStyleMatch);
  2059. } else {
  2060. var val = attr(element, name);
  2061. return val && (!value || value.includes(val));
  2062. }
  2063. };
  2064. }
  2065. function handleTag(tag) {
  2066. if (!tagsToBBCodes[tag] || !tagsToBBCodes[tag][blockLevel]) {
  2067. return;
  2068. }
  2069. // loop all bbcodes for this tag
  2070. each(tagsToBBCodes[tag][blockLevel], function (bbcode, attrs) {
  2071. var fn, format,
  2072. isStrict = bbcodeHandlers[bbcode].strictMatch;
  2073. if (typeof isStrict === 'undefined') {
  2074. isStrict = base.opts.strictMatch;
  2075. }
  2076. // Skip if the element doesn't have the attribute or the
  2077. // attribute doesn't match one of the required values
  2078. fn = isStrict ? 'every' : 'some';
  2079. if (attrs && !attrs[fn](createAttributeMatch(isStrict))) {
  2080. return;
  2081. }
  2082. format = bbcodeHandlers[bbcode].format;
  2083. if (isFunction(format)) {
  2084. content = format.call(base, element, content);
  2085. } else {
  2086. content = _formatString(format, content);
  2087. }
  2088. return false;
  2089. });
  2090. }
  2091. handleTag('*');
  2092. handleTag(element.nodeName.toLowerCase());
  2093. return content;
  2094. }
  2095. /**
  2096. * Converts a HTML dom element to BBCode starting from
  2097. * the innermost element and working backwards
  2098. *
  2099. * @private
  2100. * @param {HTMLElement} element
  2101. * @param {boolean} hasCodeParent
  2102. * @return {string} BBCode
  2103. * @memberOf SCEditor.plugins.bbcode.prototype
  2104. */
  2105. function elementToBbcode(element, hasCodeParent) {
  2106. var toBBCode = function (node, hasCodeParent, vChildren) {
  2107. var ret = '';
  2108. dom.traverse(node, function (node) {
  2109. var content = '',
  2110. nodeType = node.nodeType,
  2111. tag = node.nodeName.toLowerCase(),
  2112. isCodeTag = tag === 'code',
  2113. isEmoticon = tag === 'img' &&
  2114. !!attr(node, EMOTICON_DATA_ATTR),
  2115. vChild = validChildren[tag],
  2116. firstChild = node.firstChild,
  2117. isValidChild = true;
  2118. if (vChildren) {
  2119. isValidChild = vChildren.indexOf(tag) > -1;
  2120. // Emoticons should always be converted
  2121. if (isEmoticon) {
  2122. isValidChild = true;
  2123. }
  2124. // if this tag is one of the parents allowed children
  2125. // then set this tags allowed children to whatever it
  2126. // allows, otherwise set to what the parent allows
  2127. if (!isValidChild) {
  2128. vChild = vChildren;
  2129. }
  2130. }
  2131. // 1 = element
  2132. if (nodeType === 1) {
  2133. // skip empty nlf elements (new lines automatically
  2134. // added after block level elements like quotes)
  2135. if (is(node, '.sceditor-nlf') && !firstChild) {
  2136. return;
  2137. }
  2138. // don't convert iframe contents
  2139. if (tag !== 'iframe') {
  2140. content = toBBCode(node, hasCodeParent || isCodeTag,
  2141. vChild);
  2142. }
  2143. // TODO: isValidChild is no longer needed. Should use
  2144. // valid children bbcodes instead by creating BBCode
  2145. // tokens like the parser.
  2146. if (isValidChild) {
  2147. // Emoticons should be converted if they have found
  2148. // their way into a code tag
  2149. if (!hasCodeParent || isEmoticon) {
  2150. if (!isCodeTag) {
  2151. // Parse inline codes first so they don't
  2152. // contain block level codes
  2153. content = handleTags(node, content, false);
  2154. }
  2155. content = handleTags(node, content, true);
  2156. }
  2157. ret += handleBlockNewlines(node, content);
  2158. } else {
  2159. ret += content;
  2160. }
  2161. // 3 = text
  2162. } else if (nodeType === 3) {
  2163. ret += node.nodeValue;
  2164. }
  2165. }, false, true);
  2166. return ret;
  2167. };
  2168. return toBBCode(element, hasCodeParent);
  2169. };
  2170. /**
  2171. * Initializer
  2172. * @private
  2173. */
  2174. base.init = function () {
  2175. base.opts = this.opts;
  2176. base.elementToBbcode = elementToBbcode;
  2177. // build the BBCode cache
  2178. buildBbcodeCache();
  2179. this.commands = extend(
  2180. true, {}, defaultCommandsOverrides, this.commands
  2181. );
  2182. // Add BBCode helper methods
  2183. this.toBBCode = base.toSource;
  2184. this.fromBBCode = base.toHtml;
  2185. };
  2186. /**
  2187. * Converts BBCode into HTML
  2188. *
  2189. * @param {boolean} asFragment
  2190. * @param {string} source
  2191. * @param {boolean} [legacyAsFragment] Used by fromBBCode() method
  2192. */
  2193. function toHtml(asFragment, source, legacyAsFragment) {
  2194. var parser = new BBCodeParser(base.opts.parserOptions);
  2195. var toHTML = (asFragment || legacyAsFragment) ?
  2196. parser.toHTMLFragment :
  2197. parser.toHTML;
  2198. return toHTML(base.opts.bbcodeTrim ? source.trim() : source);
  2199. }
  2200. /**
  2201. * Converts HTML into BBCode
  2202. *
  2203. * @param {boolean} asFragment
  2204. * @param {string} html
  2205. * @param {!Document} [context]
  2206. * @param {!HTMLElement} [parent]
  2207. * @return {string}
  2208. * @private
  2209. */
  2210. function toSource(asFragment, html, context, parent) {
  2211. context = context || document;
  2212. var bbcode, elements;
  2213. var hasCodeParent = !!dom.closest(parent, 'code');
  2214. var containerParent = context.createElement('div');
  2215. var container = context.createElement('div');
  2216. var parser = new BBCodeParser(base.opts.parserOptions);
  2217. container.innerHTML = html;
  2218. css(containerParent, 'visibility', 'hidden');
  2219. containerParent.appendChild(container);
  2220. context.body.appendChild(containerParent);
  2221. if (asFragment) {
  2222. // Add text before and after so removeWhiteSpace doesn't remove
  2223. // leading and trailing whitespace
  2224. containerParent.insertBefore(
  2225. context.createTextNode('#'),
  2226. containerParent.firstChild
  2227. );
  2228. containerParent.appendChild(context.createTextNode('#'));
  2229. }
  2230. // Match parents white-space handling
  2231. if (parent) {
  2232. css(container, 'whiteSpace', css(parent, 'whiteSpace'));
  2233. }
  2234. // Remove all nodes with sceditor-ignore class
  2235. elements = container.getElementsByClassName('sceditor-ignore');
  2236. while (elements.length) {
  2237. elements[0].parentNode.removeChild(elements[0]);
  2238. }
  2239. dom.removeWhiteSpace(containerParent);
  2240. bbcode = elementToBbcode(container, hasCodeParent);
  2241. context.body.removeChild(containerParent);
  2242. bbcode = parser.toBBCode(bbcode, true);
  2243. if (base.opts.bbcodeTrim) {
  2244. bbcode = bbcode.trim();
  2245. }
  2246. return bbcode;
  2247. };
  2248. base.toHtml = toHtml.bind(null, false);
  2249. base.fragmentToHtml = toHtml.bind(null, true);
  2250. base.toSource = toSource.bind(null, false);
  2251. base.fragmentToSource = toSource.bind(null, true);
  2252. };
  2253. /**
  2254. * Gets a BBCode
  2255. *
  2256. * @param {string} name
  2257. * @return {Object|null}
  2258. * @since 2.0.0
  2259. */
  2260. bbcodeFormat.get = function (name) {
  2261. return bbcodeHandlers[name] || null;
  2262. };
  2263. /**
  2264. * Adds a BBCode to the parser or updates an existing
  2265. * BBCode if a BBCode with the specified name already exists.
  2266. *
  2267. * @param {string} name
  2268. * @param {Object} bbcode
  2269. * @return {this}
  2270. * @since 2.0.0
  2271. */
  2272. bbcodeFormat.set = function (name, bbcode) {
  2273. if (name && bbcode) {
  2274. // merge any existing command properties
  2275. bbcode = extend(bbcodeHandlers[name] || {}, bbcode);
  2276. bbcode.remove = function () {
  2277. delete bbcodeHandlers[name];
  2278. };
  2279. bbcodeHandlers[name] = bbcode;
  2280. }
  2281. return this;
  2282. };
  2283. /**
  2284. * Renames a BBCode
  2285. *
  2286. * This does not change the format or HTML handling, those must be
  2287. * changed manually.
  2288. *
  2289. * @param {string} name [description]
  2290. * @param {string} newName [description]
  2291. * @return {this|false}
  2292. * @since 2.0.0
  2293. */
  2294. bbcodeFormat.rename = function (name, newName) {
  2295. if (name in bbcodeHandlers) {
  2296. bbcodeHandlers[newName] = bbcodeHandlers[name];
  2297. delete bbcodeHandlers[name];
  2298. }
  2299. return this;
  2300. };
  2301. /**
  2302. * Removes a BBCode
  2303. *
  2304. * @param {string} name
  2305. * @return {this}
  2306. * @since 2.0.0
  2307. */
  2308. bbcodeFormat.remove = function (name) {
  2309. if (name in bbcodeHandlers) {
  2310. delete bbcodeHandlers[name];
  2311. }
  2312. return this;
  2313. };
  2314. bbcodeFormat.formatBBCodeString = formatBBCodeString;
  2315. sceditor.formats.bbcode = bbcodeFormat;
  2316. sceditor.BBCodeParser = BBCodeParser;
  2317. }(sceditor));