bbcode.js 62 KB

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