bbcode.js 63 KB

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