bbcode.js 63 KB

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