OSDN Git Service

2417533cb4c63eff8f32d93c039c4afe98d35447
[webchat/WebChat.git] / public / scripts / bbcode.js
1 // -----------------------------------------------------------------------
2 // Copyright (c) 2008, Stone Steps Inc. 
3 // All rights reserved
4 // http://www.stonesteps.ca/legal/bsd-license/
5 //
6 // This is a BBCode parser written in JavaScript. The parser is intended
7 // to demonstrate how to parse text containing BBCode tags in one pass 
8 // using regular expressions.
9 //
10 // The parser may be used as a backend component in ASP or in the browser, 
11 // after the text containing BBCode tags has been served to the client. 
12 //
13 // Following BBCode expressions are recognized:
14 //
15 // [b]bold[/b]
16 // [i]italic[/i]
17 // [u]underlined[/u]
18 // [s]strike-through[/s]
19 // [samp]sample[/samp]
20 //
21 // [color=red]red[/color]
22 // [color=#FF0000]red[/color]
23 // [size=1.2]1.2em[/size]
24 //
25 // [url]http://blogs.stonesteps.ca/showpost.asp?pid=33[/url]
26 // [url=http://blogs.stonesteps.ca/showpost.asp?pid=33][b]BBCode[/b] Parser[/url]
27 //
28 // [q=http://blogs.stonesteps.ca/showpost.asp?pid=33]inline quote[/q]
29 // [q]inline quote[/q]
30 // [blockquote=http://blogs.stonesteps.ca/showpost.asp?pid=33]block quote[/blockquote]
31 // [blockquote]block quote[/blockquote]
32 //
33 // [pre]formatted 
34 //     text[/pre]
35 // [code]if(a == b) 
36 //   print("done");[/code]
37 //
38 // text containing [noparse] [brackets][/noparse]
39 //
40 // -----------------------------------------------------------------------
41 var opentags;           // open tag stack
42 var crlf2br = true;     // convert CRLF to <br>?
43 var noparse = false;    // ignore BBCode tags?
44 var urlstart = -1;      // beginning of the URL if zero or greater (ignored if -1)
45
46 // aceptable BBcode tags, optionally prefixed with a slash
47 var tagname_re = /^\/?(?:b|i|u|pre|samp|code|colou?r|size|noparse|url|s|q|blockquote)$/;
48
49 // color names or hex color
50 var color_re = /^(:?black|silver|gray|white|maroon|red|purple|fuchsia|green|lime|olive|yellow|navy|blue|teal|aqua|#(?:[0-9a-f]{3})?[0-9a-f]{3})$/i;
51
52 // numbers
53 var number_re = /^[\\.0-9]{1,8}$/i;
54
55 // reserved, unreserved, escaped and alpha-numeric [RFC2396]
56 var uri_re = /^[-;\/\?:@&=\+\$,_\.!~\*'\(\)%0-9a-z]{1,512}$/i;
57
58 // main regular expression: CRLF, [tag=option], [tag] or [/tag]
59 var postfmt_re = /([\r\n])|(?:\[([a-z]{1,16})(?:=([^\x00-\x1F"'\(\)<>\[\]]{1,256}))?\])|(?:\[\/([a-z]{1,16})\])/ig;
60
61 // stack frame object
62 function taginfo_t(bbtag, etag)
63 {
64    this.bbtag = bbtag;
65    this.etag = etag;
66 }
67
68 // check if it's a valid BBCode tag
69 function isValidTag(str)
70 {
71    if(!str || !str.length)
72       return false;
73
74    return tagname_re.test(str);
75 }
76
77 //
78 // m1 - CR or LF
79 // m2 - the tag of the [tag=option] expression
80 // m3 - the option of the [tag=option] expression
81 // m4 - the end tag of the [/tag] expression
82 //
83 function textToHtmlCB(mstr, m1, m2, m3, m4, offset, string)
84 {
85    //
86    // CR LF sequences
87    //
88    if(m1 && m1.length) {
89       if(!crlf2br)
90          return mstr;
91
92       switch (m1) {
93          case '\r':
94             return "";
95          case '\n':
96             return "<br>";
97       }
98    }
99
100    //
101    // handle start tags
102    //
103    if(isValidTag(m2)) {
104       // if in the noparse state, just echo the tag
105       if(noparse)
106          return "[" + m2 + "]";
107
108       // ignore any tags if there's an open option-less [url] tag
109       if(opentags.length && opentags[opentags.length-1].bbtag == "url" && urlstart >= 0)
110          return "[" + m2 + "]";
111
112       switch (m2) {
113          case "code":
114             opentags.push(new taginfo_t(m2, "</code></pre>"));
115             crlf2br = false;
116             return "<pre><code>";
117
118          case "pre":
119             opentags.push(new taginfo_t(m2, "</pre>"));
120             crlf2br = false;
121             return "<pre>";
122
123          case "color":
124          case "colour":
125             if(!m3 || !color_re.test(m3))
126                m3 = "inherit";
127             opentags.push(new taginfo_t(m2, "</span>"));
128             return "<span style=\"color: " + m3 + "\">";
129
130          case "size":
131             if(!m3 || !number_re.test(m3))
132                m3 = "1";
133             opentags.push(new taginfo_t(m2, "</span>"));
134             return "<span style=\"font-size: " + Math.min(Math.max(m3, 0.7), 3) + "em\">";
135
136          case "s":
137             opentags.push(new taginfo_t(m2, "</span>"));
138             return "<span style=\"text-decoration: line-through\">";
139
140          case "noparse":
141             noparse = true;
142             return "";
143
144          case "url":
145             opentags.push(new taginfo_t(m2, "</a>"));
146             
147             // check if there's a valid option
148             if(m3 && uri_re.test(m3)) {
149                // if there is, output a complete start anchor tag
150                urlstart = -1;
151                return "<a href=\"" + m3 + "\">";
152             }
153
154             // otherwise, remember the URL offset 
155             urlstart = mstr.length + offset;
156
157             // and treat the text following [url] as a URL
158             return "<a href=\"";
159
160          case "q":
161          case "blockquote":
162             opentags.push(new taginfo_t(m2, "</" + m2 + ">"));
163             return m3 && m3.length && uri_re.test(m3) ? "<" + m2 + " cite=\"" + m3 + "\">" : "<" + m2 + ">";
164
165          case "b":
166             opentags.push(new taginfo_t(m2, "</span>"));
167             return "<span style=\"font-weight: bold\">";
168
169          case "i":
170             opentags.push(new taginfo_t(m2, "</span>"));
171             return "<span style=\"font-style:italic\">";
172
173          case "u":
174             opentags.push(new taginfo_t(m2, "</span>"));
175             return "<span style=\"text-decoration: underline\">";
176
177          default:
178             // [samp]don't need special processing
179             opentags.push(new taginfo_t(m2, "</" + m2 + ">"));
180             return "<" + m2 + ">";
181             
182       }
183    }
184
185    //
186    // process end tags
187    //
188    if(isValidTag(m4)) {
189       if(noparse) {
190          // if it's the closing noparse tag, flip the noparse state
191          if(m4 == "noparse")  {
192             noparse = false;
193             return "";
194          }
195          
196          // otherwise just output the original text
197          return "[/" + m4 + "]";
198       }
199       
200       // highlight mismatched end tags
201       if(!opentags.length || opentags[opentags.length-1].bbtag != m4)
202          return "<span style=\"color: red\">[/" + m4 + "]</span>";
203
204       if(m4 == "url") {
205          // if there was no option, use the content of the [url] tag
206          if(urlstart > 0)
207             return "\">" + string.substr(urlstart, offset-urlstart) + opentags.pop().etag;
208          
209          // otherwise just close the tag
210          return opentags.pop().etag;
211       }
212       else if(m4 == "code" || m4 == "pre")
213          crlf2br = true;
214
215       // other tags require no special processing, just output the end tag
216       return opentags.pop().etag;
217    }
218
219    return mstr;
220 }
221
222 //
223 // post must be HTML-encoded
224 //
225 function parseBBCode(post)
226 {
227    var result, endtags, tag;
228
229    // convert CRLF to <br> by default
230    crlf2br = true;
231
232    // create a new array for open tags
233    if(opentags == null || opentags.length)
234       opentags = new Array(0);
235
236    // run the text through main regular expression matcher
237    result = post.replace(postfmt_re, textToHtmlCB);
238
239    // reset noparse, if it was unbalanced
240    if(noparse)
241       noparse = false;
242    
243    // if there are any unbalanced tags, make sure to close them
244    if(opentags.length) {
245       endtags = new String();
246       
247       // if there's an open [url] at the top, close it
248       if(opentags[opentags.length-1].bbtag == "url") {
249          opentags.pop();
250          endtags += "\">" + post.substr(urlstart, post.length-urlstart) + "</a>";
251       }
252       
253       // close remaining open tags
254       while(opentags.length)
255          endtags += opentags.pop().etag;
256    }
257
258    return endtags ? result + endtags : result;
259 }