table.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*global module:true*/
  2. (function(){
  3. var table = function(converter) {
  4. var tables = {}, style = 'text-align:left;', filter;
  5. tables.th = function(header){
  6. if (header.trim() === "") { return "";}
  7. var id = header.trim().replace(/ /g, '_').toLowerCase();
  8. return '<th id="' + id + '" style="'+style+'">' + header + '</th>';
  9. };
  10. tables.td = function(cell) {
  11. return '<td style="'+style+'">' + cell + '</td>';
  12. };
  13. tables.ths = function(){
  14. var out = "", i = 0, hs = [].slice.apply(arguments);
  15. for (i;i<hs.length;i+=1) {
  16. out += tables.th(hs[i]) + '\n';
  17. }
  18. return out;
  19. };
  20. tables.tds = function(){
  21. var out = "", i = 0, ds = [].slice.apply(arguments);
  22. for (i;i<ds.length;i+=1) {
  23. out += tables.td(ds[i]) + '\n';
  24. }
  25. return out;
  26. };
  27. tables.thead = function() {
  28. var out, i = 0, hs = [].slice.apply(arguments);
  29. out = "<thead>\n";
  30. out += "<tr>\n";
  31. out += tables.ths.apply(this, hs);
  32. out += "</tr>\n";
  33. out += "</thead>\n";
  34. return out;
  35. };
  36. tables.tr = function() {
  37. var out, i = 0, cs = [].slice.apply(arguments);
  38. out = "<tr>\n";
  39. out += tables.tds.apply(this, cs);
  40. out += "</tr>\n";
  41. return out;
  42. };
  43. filter = function(text) {
  44. var i=0, lines = text.split('\n'), tbl = [], line, hs, rows, out = [];
  45. for (i; i<lines.length;i+=1) {
  46. line = lines[i];
  47. // looks like a table heading
  48. if (line.trim().match(/^[|]{1}.*[|]{1}$/)) {
  49. line = line.trim();
  50. tbl.push('<table>');
  51. hs = line.substring(1, line.length -1).split('|');
  52. tbl.push(tables.thead.apply(this, hs));
  53. line = lines[++i];
  54. if (!line.trim().match(/^[|]{1}[-=| ]+[|]{1}$/)) {
  55. // not a table rolling back
  56. line = lines[--i];
  57. }
  58. else {
  59. line = lines[++i];
  60. tbl.push('<tbody>');
  61. while (line.trim().match(/^[|]{1}.*[|]{1}$/)) {
  62. line = line.trim();
  63. tbl.push(tables.tr.apply(this, line.substring(1, line.length -1).split('|')));
  64. line = lines[++i];
  65. }
  66. tbl.push('</tbody>');
  67. tbl.push('</table>');
  68. // we are done with this table and we move along
  69. out.push(tbl.join('\n'));
  70. ++i;
  71. continue;
  72. }
  73. }
  74. out.push(line);
  75. }
  76. return out.join('\n');
  77. };
  78. return [
  79. {
  80. type: 'lang',
  81. filter: filter
  82. }
  83. ];
  84. };
  85. // Client-side export
  86. if (typeof window !== 'undefined' && window.Showdown && window.Showdown.extensions) { window.Showdown.extensions.table = table; }
  87. // Server-side export
  88. if (typeof module !== 'undefined') {
  89. module.exports = table;
  90. }
  91. }());