bbcode.js 63 KB

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