epiceditor.js
90.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
/**
* EpicEditor - An Embeddable JavaScript Markdown Editor (https://github.com/OscarGodson/EpicEditor)
* Copyright (c) 2011-2012, Oscar Godson. (MIT Licensed)
*/
(function (window, undefined) {
/**
* Applies attributes to a DOM object
* @param {object} context The DOM obj you want to apply the attributes to
* @param {object} attrs A key/value pair of attributes you want to apply
* @returns {undefined}
*/
function _applyAttrs(context, attrs) {
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
context.setAttribute(attr, attrs[attr]);
}
}
}
/**
* Applies styles to a DOM object
* @param {object} context The DOM obj you want to apply the attributes to
* @param {object} attrs A key/value pair of attributes you want to apply
* @returns {undefined}
*/
function _applyStyles(context, attrs) {
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
context.style[attr] = attrs[attr];
}
}
}
/**
* Returns a DOM objects computed style
* @param {object} el The element you want to get the style from
* @param {string} styleProp The property you want to get from the element
* @returns {string} Returns a string of the value. If property is not set it will return a blank string
*/
function _getStyle(el, styleProp) {
var x = el
, y = null;
if (window.getComputedStyle) {
y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
}
else if (x.currentStyle) {
y = x.currentStyle[styleProp];
}
return y;
}
/**
* Saves the current style state for the styles requested, then applies styles
* to overwrite the existing one. The old styles are returned as an object so
* you can pass it back in when you want to revert back to the old style
* @param {object} el The element to get the styles of
* @param {string} type Can be "save" or "apply". apply will just apply styles you give it. Save will write styles
* @param {object} styles Key/value style/property pairs
* @returns {object}
*/
function _saveStyleState(el, type, styles) {
var returnState = {}
, style;
if (type === 'save') {
for (style in styles) {
if (styles.hasOwnProperty(style)) {
returnState[style] = _getStyle(el, style);
}
}
// After it's all done saving all the previous states, change the styles
_applyStyles(el, styles);
}
else if (type === 'apply') {
_applyStyles(el, styles);
}
return returnState;
}
/**
* Gets an elements total width including it's borders and padding
* @param {object} el The element to get the total width of
* @returns {int}
*/
function _outerWidth(el) {
var b = parseInt(_getStyle(el, 'border-left-width'), 10) + parseInt(_getStyle(el, 'border-right-width'), 10)
, p = parseInt(_getStyle(el, 'padding-left'), 10) + parseInt(_getStyle(el, 'padding-right'), 10)
, w = el.offsetWidth
, t;
// For IE in case no border is set and it defaults to "medium"
if (isNaN(b)) { b = 0; }
t = b + p + w;
return t;
}
/**
* Gets an elements total height including it's borders and padding
* @param {object} el The element to get the total width of
* @returns {int}
*/
function _outerHeight(el) {
var b = parseInt(_getStyle(el, 'border-top-width'), 10) + parseInt(_getStyle(el, 'border-bottom-width'), 10)
, p = parseInt(_getStyle(el, 'padding-top'), 10) + parseInt(_getStyle(el, 'padding-bottom'), 10)
, w = parseInt(_getStyle(el, 'height'), 10)
, t;
// For IE in case no border is set and it defaults to "medium"
if (isNaN(b)) { b = 0; }
t = b + p + w;
return t;
}
/**
* Inserts a <link> tag specifically for CSS
* @param {string} path The path to the CSS file
* @param {object} context In what context you want to apply this to (document, iframe, etc)
* @param {string} id An id for you to reference later for changing properties of the <link>
* @returns {undefined}
*/
function _insertCSSLink(path, context, id) {
id = id || '';
var headID = context.getElementsByTagName("head")[0]
, cssNode = context.createElement('link');
_applyAttrs(cssNode, {
type: 'text/css'
, id: id
, rel: 'stylesheet'
, href: path
, name: path
, media: 'screen'
});
headID.appendChild(cssNode);
}
// Simply replaces a class (o), to a new class (n) on an element provided (e)
function _replaceClass(e, o, n) {
e.className = e.className.replace(o, n);
}
// Feature detects an iframe to get the inner document for writing to
function _getIframeInnards(el) {
return el.contentDocument || el.contentWindow.document;
}
// Grabs the text from an element and preserves whitespace
function _getText(el) {
var theText;
// Make sure to check for type of string because if the body of the page
// doesn't have any text it'll be "" which is falsey and will go into
// the else which is meant for Firefox and shit will break
if (typeof document.body.innerText == 'string') {
theText = el.innerText;
}
else {
// First replace <br>s before replacing the rest of the HTML
theText = el.innerHTML.replace(/<br>/gi, "\n");
// Now we can clean the HTML
theText = theText.replace(/<(?:.|\n)*?>/gm, '');
// Now fix HTML entities
theText = theText.replace(/</gi, '<');
theText = theText.replace(/>/gi, '>');
}
return theText;
}
function _setText(el, content) {
// Don't convert lt/gt characters as HTML when viewing the editor window
// TODO: Write a test to catch regressions for this
content = content.replace(/</g, '<');
content = content.replace(/>/g, '>');
content = content.replace(/\n/g, '<br>');
// Make sure to there aren't two spaces in a row (replace one with )
// If you find and replace every space with a text will not wrap.
// Hence the name (Non-Breaking-SPace).
// TODO: Probably need to test this somehow...
content = content.replace(/<br>\s/g, '<br> ')
content = content.replace(/\s\s\s/g, ' ')
content = content.replace(/\s\s/g, ' ')
content = content.replace(/^ /, ' ')
el.innerHTML = content;
return true;
}
/**
* Converts the 'raw' format of a file's contents into plaintext
* @param {string} content Contents of the file
* @returns {string} the sanitized content
*/
function _sanitizeRawContent(content) {
// Get this, 2 spaces in a content editable actually converts to:
// 0020 00a0, meaning, "space no-break space". So, manually convert
// no-break spaces to spaces again before handing to marked.
// Also, WebKit converts no-break to unicode equivalent and FF HTML.
return content.replace(/\u00a0/g, ' ').replace(/ /g, ' ');
}
/**
* Will return the version number if the browser is IE. If not will return -1
* TRY NEVER TO USE THIS AND USE FEATURE DETECTION IF POSSIBLE
* @returns {Number} -1 if false or the version number if true
*/
function _isIE() {
var rv = -1 // Return value assumes failure.
, ua = navigator.userAgent
, re;
if (navigator.appName == 'Microsoft Internet Explorer') {
re = /MSIE ([0-9]{1,}[\.0-9]{0,})/;
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1, 10);
}
}
return rv;
}
/**
* Same as the isIE(), but simply returns a boolean
* THIS IS TERRIBLE AND IS ONLY USED BECAUSE FULLSCREEN IN SAFARI IS BORKED
* If some other engine uses WebKit and has support for fullscreen they
* probably wont get native fullscreen until Safari's fullscreen is fixed
* @returns {Boolean} true if Safari
*/
function _isSafari() {
var n = window.navigator;
return n.userAgent.indexOf('Safari') > -1 && n.userAgent.indexOf('Chrome') == -1;
}
/**
* Same as the isIE(), but simply returns a boolean
* THIS IS TERRIBLE ONLY USE IF ABSOLUTELY NEEDED
* @returns {Boolean} true if Safari
*/
function _isFirefox() {
var n = window.navigator;
return n.userAgent.indexOf('Firefox') > -1 && n.userAgent.indexOf('Seamonkey') == -1;
}
/**
* Determines if supplied value is a function
* @param {object} object to determine type
*/
function _isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param {boolean} [deepMerge=false] If true, will deep merge meaning it will merge sub-objects like {obj:obj2{foo:'bar'}}
* @param {object} first object
* @param {object} second object
* @returnss {object} a new object based on obj1 and obj2
*/
function _mergeObjs() {
// copy reference to target object
var target = arguments[0] || {}
, i = 1
, length = arguments.length
, deep = false
, options
, name
, src
, copy
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !_isFunction(target)) {
target = {};
}
// extend jQuery itself if only one argument is passed
if (length === i) {
target = this;
--i;
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
// @NOTE: added hasOwnProperty check
if (options.hasOwnProperty(name)) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging object values
if (deep && copy && typeof copy === "object" && !copy.nodeType) {
target[name] = _mergeObjs(deep,
// Never move original objects, clone them
src || (copy.length != null ? [] : {})
, copy);
} else if (copy !== undefined) { // Don't bring in undefined values
target[name] = copy;
}
}
}
}
}
// Return the modified object
return target;
}
/**
* Initiates the EpicEditor object and sets up offline storage as well
* @class Represents an EpicEditor instance
* @param {object} options An optional customization object
* @returns {object} EpicEditor will be returned
*/
function EpicEditor(options) {
// Default settings will be overwritten/extended by options arg
var self = this
, opts = options || {}
, _defaultFileSchema
, _defaultFile
, defaults = { container: 'epiceditor'
, basePath: 'epiceditor'
, textarea: undefined
, clientSideStorage: true
, localStorageName: 'epiceditor'
, useNativeFullscreen: true
, file: { name: null
, defaultContent: ''
, autoSave: 100 // Set to false for no auto saving
}
, theme: { base: '/epiceditor/themes/base/epiceditor.css'
, preview: '/epiceditor/themes/preview/github.css'
, editor: '/epiceditor/themes/editor/epic-dark.css'
}
, focusOnLoad: false
, shortcut: { modifier: 18 // alt keycode
, fullscreen: 70 // f keycode
, preview: 80 // p keycode
}
, string: { togglePreview: 'Toggle Preview Mode'
, toggleEdit: 'Toggle Edit Mode'
, toggleFullscreen: 'Enter Fullscreen'
}
, parser: typeof marked == 'function' ? marked : null
, autogrow: false
, button: { fullscreen: true
, preview: true
, bar: "auto"
}
}
, defaultStorage
, autogrowDefaults = { minHeight: 80
, maxHeight: false
, scroll: true
};
self.settings = _mergeObjs(true, defaults, opts);
var buttons = self.settings.button;
self._fullscreenEnabled = typeof(buttons) === 'object' ? typeof buttons.fullscreen === 'undefined' || buttons.fullscreen : buttons === true;
self._editEnabled = typeof(buttons) === 'object' ? typeof buttons.edit === 'undefined' || buttons.edit : buttons === true;
self._previewEnabled = typeof(buttons) === 'object' ? typeof buttons.preview === 'undefined' || buttons.preview : buttons === true;
if (!(typeof self.settings.parser == 'function' && typeof self.settings.parser('TEST') == 'string')) {
self.settings.parser = function (str) {
return str;
}
}
if (self.settings.autogrow) {
if (self.settings.autogrow === true) {
self.settings.autogrow = autogrowDefaults;
}
else {
self.settings.autogrow = _mergeObjs(true, autogrowDefaults, self.settings.autogrow);
}
self._oldHeight = -1;
}
// If you put an absolute link as the path of any of the themes ignore the basePath
// preview theme
if (!self.settings.theme.preview.match(/^https?:\/\//)) {
self.settings.theme.preview = self.settings.theme.preview;
}
// editor theme
if (!self.settings.theme.editor.match(/^https?:\/\//)) {
self.settings.theme.editor = self.settings.theme.editor;
}
// base theme
if (!self.settings.theme.base.match(/^https?:\/\//)) {
self.settings.theme.base = self.settings.theme.base;
}
// Grab the container element and save it to self.element
// if it's a string assume it's an ID and if it's an object
// assume it's a DOM element
if (typeof self.settings.container == 'string') {
self.element = document.getElementById(self.settings.container);
}
else if (typeof self.settings.container == 'object') {
self.element = self.settings.container;
}
if (typeof self.settings.textarea == 'undefined' && typeof self.element != 'undefined') {
var textareas = self.element.getElementsByTagName('textarea');
if (textareas.length > 0) {
self.settings.textarea = textareas[0];
_applyStyles(self.settings.textarea, {
display: 'none'
});
}
}
// Figure out the file name. If no file name is given we'll use the ID.
// If there's no ID either we'll use a namespaced file name that's incremented
// based on the calling order. As long as it doesn't change, drafts will be saved.
if (!self.settings.file.name) {
if (typeof self.settings.container == 'string') {
self.settings.file.name = self.settings.container;
}
else if (typeof self.settings.container == 'object') {
if (self.element.id) {
self.settings.file.name = self.element.id;
}
else {
if (!EpicEditor._data.unnamedEditors) {
EpicEditor._data.unnamedEditors = [];
}
EpicEditor._data.unnamedEditors.push(self);
self.settings.file.name = '__epiceditor-untitled-' + EpicEditor._data.unnamedEditors.length;
}
}
}
if (self.settings.button.bar === "show") {
self.settings.button.bar = true;
}
if (self.settings.button.bar === "hide") {
self.settings.button.bar = false;
}
// Protect the id and overwrite if passed in as an option
// TODO: Put underscrore to denote that this is private
self._instanceId = 'epiceditor-' + Math.round(Math.random() * 100000);
self._storage = {};
self._canSave = true;
// Setup local storage of files
self._defaultFileSchema = function () {
return {
content: self.settings.file.defaultContent
, created: new Date()
, modified: new Date()
}
}
if (localStorage && self.settings.clientSideStorage) {
this._storage = localStorage;
if (this._storage[self.settings.localStorageName] && self.getFiles(self.settings.file.name) === undefined) {
_defaultFile = self._defaultFileSchema();
_defaultFile.content = self.settings.file.defaultContent;
}
}
if (!this._storage[self.settings.localStorageName]) {
defaultStorage = {};
defaultStorage[self.settings.file.name] = self._defaultFileSchema();
defaultStorage = JSON.stringify(defaultStorage);
this._storage[self.settings.localStorageName] = defaultStorage;
}
// A string to prepend files with to save draft versions of files
// and reset all preview drafts on each load!
self._previewDraftLocation = '__draft-';
self._storage[self._previewDraftLocation + self.settings.localStorageName] = self._storage[self.settings.localStorageName];
// This needs to replace the use of classes to check the state of EE
self._eeState = {
fullscreen: false
, preview: false
, edit: false
, loaded: false
, unloaded: false
}
// Now that it exists, allow binding of events if it doesn't exist yet
if (!self.events) {
self.events = {};
}
return this;
}
/**
* Inserts the EpicEditor into the DOM via an iframe and gets it ready for editing and previewing
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.load = function (callback) {
// Get out early if it's already loaded
if (this.is('loaded')) { return this; }
// TODO: Gotta get the privates with underscores!
// TODO: Gotta document what these are for...
var self = this
, _HtmlTemplates
, iframeElement
, baseTag
, utilBtns
, utilBar
, utilBarTimer
, keypressTimer
, mousePos = { y: -1, x: -1 }
, _elementStates
, _isInEdit
, nativeFs = false
, nativeFsWebkit = false
, nativeFsMoz = false
, nativeFsW3C = false
, fsElement
, isMod = false
, isCtrl = false
, eventableIframes
, i // i is reused for loops
, boundAutogrow;
// Startup is a way to check if this EpicEditor is starting up. Useful for
// checking and doing certain things before EpicEditor emits a load event.
self._eeState.startup = true;
if (self.settings.useNativeFullscreen) {
nativeFsWebkit = document.body.webkitRequestFullScreen ? true : false;
nativeFsMoz = document.body.mozRequestFullScreen ? true : false;
nativeFsW3C = document.body.requestFullscreen ? true : false;
nativeFs = nativeFsWebkit || nativeFsMoz || nativeFsW3C;
}
// Fucking Safari's native fullscreen works terribly
// REMOVE THIS IF SAFARI 7 WORKS BETTER
if (_isSafari()) {
nativeFs = false;
nativeFsWebkit = false;
}
// It opens edit mode by default (for now);
if (!self.is('edit') && !self.is('preview')) {
self._eeState.edit = true;
}
callback = callback || function () {};
// The editor HTML
// TODO: edit-mode class should be dynamically added
_HtmlTemplates = {
// This is wrapping iframe element. It contains the other two iframes and the utilbar
chrome: '<div id="epiceditor-wrapper" class="epiceditor-edit-mode">' +
'<iframe frameborder="0" id="epiceditor-editor-frame"></iframe>' +
'<iframe frameborder="0" id="epiceditor-previewer-frame"></iframe>' +
'<div id="epiceditor-utilbar">' +
(self._previewEnabled ? '<button title="' + this.settings.string.togglePreview + '" class="epiceditor-toggle-btn epiceditor-toggle-preview-btn"></button> ' : '') +
(self._editEnabled ? '<button title="' + this.settings.string.toggleEdit + '" class="epiceditor-toggle-btn epiceditor-toggle-edit-btn"></button> ' : '') +
(self._fullscreenEnabled ? '<button title="' + this.settings.string.toggleFullscreen + '" class="epiceditor-fullscreen-btn"></button>' : '') +
'</div>' +
'</div>'
// The previewer is just an empty box for the generated HTML to go into
, previewer: '<div id="epiceditor-preview"></div>'
, editor: '<!doctype HTML>'
};
// Write an iframe and then select it for the editor
iframeElement = document.createElement('iframe');
_applyAttrs(iframeElement, {
scrolling: 'no',
frameborder: 0,
id: self._instanceId
});
self.element.appendChild(iframeElement);
// Because browsers add things like invisible padding and margins and stuff
// to iframes, we need to set manually set the height so that the height
// doesn't keep increasing (by 2px?) every time reflow() is called.
// FIXME: Figure out how to fix this without setting this
self.element.style.height = self.element.offsetHeight + 'px';
// Store a reference to the iframeElement itself
self.iframeElement = iframeElement;
// Grab the innards of the iframe (returns the document.body)
// TODO: Change self.iframe to self.iframeDocument
self.iframe = _getIframeInnards(iframeElement);
self.iframe.open();
self.iframe.write(_HtmlTemplates.chrome);
// Now that we got the innards of the iframe, we can grab the other iframes
self.editorIframe = self.iframe.getElementById('epiceditor-editor-frame')
self.previewerIframe = self.iframe.getElementById('epiceditor-previewer-frame');
// Setup the editor iframe
self.editorIframeDocument = _getIframeInnards(self.editorIframe);
self.editorIframeDocument.open();
// Need something for... you guessed it, Firefox
self.editorIframeDocument.write(_HtmlTemplates.editor);
self.editorIframeDocument.close();
// Setup the previewer iframe
self.previewerIframeDocument = _getIframeInnards(self.previewerIframe);
self.previewerIframeDocument.open();
self.previewerIframeDocument.write(_HtmlTemplates.previewer);
// Base tag is added so that links will open a new tab and not inside of the iframes
baseTag = self.previewerIframeDocument.createElement('base');
baseTag.target = '_blank';
self.previewerIframeDocument.getElementsByTagName('head')[0].appendChild(baseTag);
self.previewerIframeDocument.close();
self.reflow();
// Insert Base Stylesheet
_insertCSSLink(self.settings.theme.base, self.iframe, 'theme');
// Insert Editor Stylesheet
_insertCSSLink(self.settings.theme.editor, self.editorIframeDocument, 'theme');
// Insert Previewer Stylesheet
_insertCSSLink(self.settings.theme.preview, self.previewerIframeDocument, 'theme');
// Add a relative style to the overall wrapper to keep CSS relative to the editor
self.iframe.getElementById('epiceditor-wrapper').style.position = 'relative';
// Set the position to relative so we hide them with left: -999999px
self.editorIframe.style.position = 'absolute';
self.previewerIframe.style.position = 'absolute';
// Now grab the editor and previewer for later use
self.editor = self.editorIframeDocument.body;
self.previewer = self.previewerIframeDocument.getElementById('epiceditor-preview');
self.editor.contentEditable = true;
// Firefox's <body> gets all fucked up so, to be sure, we need to hardcode it
self.iframe.body.style.height = this.element.offsetHeight + 'px';
// Should actually check what mode it's in!
self.previewerIframe.style.left = '-999999px';
// Keep long lines from being longer than the editor
this.editorIframeDocument.body.style.wordWrap = 'break-word';
// FIXME figure out why it needs +2 px
if (_isIE() > -1) {
this.previewer.style.height = parseInt(_getStyle(this.previewer, 'height'), 10) + 2;
}
// If there is a file to be opened with that filename and it has content...
this.open(self.settings.file.name);
if (self.settings.focusOnLoad) {
// We need to wait until all three iframes are done loading by waiting until the parent
// iframe's ready state == complete, then we can focus on the contenteditable
self.iframe.addEventListener('readystatechange', function () {
if (self.iframe.readyState == 'complete') {
self.focus();
}
});
}
// Because IE scrolls the whole window to hash links, we need our own
// method of scrolling the iframe to an ID from clicking a hash
self.previewerIframeDocument.addEventListener('click', function (e) {
var el = e.target
, body = self.previewerIframeDocument.body;
if (el.nodeName == 'A') {
// Make sure the link is a hash and the link is local to the iframe
if (el.hash && el.hostname == window.location.hostname) {
// Prevent the whole window from scrolling
e.preventDefault();
// Prevent opening a new window
el.target = '_self';
// Scroll to the matching element, if an element exists
if (body.querySelector(el.hash)) {
body.scrollTop = body.querySelector(el.hash).offsetTop;
}
}
}
});
utilBtns = self.iframe.getElementById('epiceditor-utilbar');
// TODO: Move into fullscreen setup function (_setupFullscreen)
_elementStates = {}
self._goFullscreen = function (el, callback) {
callback = callback || function () {};
var wait = 0;
this._fixScrollbars('auto');
if (self.is('fullscreen')) {
self._exitFullscreen(el, callback);
return;
}
if (nativeFs) {
if (nativeFsWebkit) {
el.webkitRequestFullScreen();
wait = 750;
}
else if (nativeFsMoz) {
el.mozRequestFullScreen();
}
else if (nativeFsW3C) {
el.requestFullscreen();
}
}
_isInEdit = self.is('edit');
// Why does this need to be in a randomly "750"ms setTimeout? WebKit's
// implementation of fullscreen seem to trigger the webkitfullscreenchange
// event _after_ everything is done. Instead, it triggers _during_ the
// transition. This means calculations of what's half, 100%, etc are wrong
// so to combat this we throw down the hammer with a setTimeout and wait
// to trigger our calculation code.
// See: https://code.google.com/p/chromium/issues/detail?id=181116
setTimeout(function () {
// Set the state of EE in fullscreen
// We set edit and preview to true also because they're visible
// we might want to allow fullscreen edit mode without preview (like a "zen" mode)
self._eeState.fullscreen = true;
self._eeState.edit = true;
self._eeState.preview = true;
// Cache calculations
var windowInnerWidth = window.innerWidth
, windowInnerHeight = window.innerHeight
, windowOuterWidth = window.outerWidth
, windowOuterHeight = window.outerHeight;
// Without this the scrollbars will get hidden when scrolled to the bottom in faux fullscreen (see #66)
if (!nativeFs) {
windowOuterHeight = window.innerHeight;
}
// This MUST come first because the editor is 100% width so if we change the width of the iframe or wrapper
// the editor's width wont be the same as before
_elementStates.editorIframe = _saveStyleState(self.editorIframe, 'save', {
'width': (windowOuterWidth / 2 - 20) + 'px'
, 'height': windowOuterHeight + 'px'
, 'float': 'left' // Most browsers
, 'cssFloat': 'left' // FF
, 'styleFloat': 'left' // Older IEs
, 'display': 'block'
, 'position': 'static'
, 'left': ''
});
alert((windowOuterWidth / 2 - 20) + 'px');
// the previewer
_elementStates.previewerIframe = _saveStyleState(self.previewerIframe, 'save', {
'width': (windowOuterWidth / 2 - 20) + 'px'
, 'height': windowOuterHeight + 'px'
, 'float': 'right' // Most browsers
, 'cssFloat': 'right' // FF
, 'styleFloat': 'right' // Older IEs
, 'display': 'block'
, 'position': 'static'
, 'left': ''
});
// Setup the containing element CSS for fullscreen
_elementStates.element = _saveStyleState(self.element, 'save', {
'position': 'fixed'
, 'top': '0'
, 'left': '0'
, 'width': '100%'
, 'z-index': '9999' // Most browsers
, 'zIndex': '9999' // Firefox
, 'border': 'none'
, 'margin': '0'
// Should use the base styles background!
, 'background': _getStyle(self.editor, 'background-color') // Try to hide the site below
, 'height': windowInnerHeight + 'px'
});
// The iframe element
_elementStates.iframeElement = _saveStyleState(self.iframeElement, 'save', {
'width': windowOuterWidth + 'px'
, 'height': windowInnerHeight + 'px'
});
// ...Oh, and hide the buttons and prevent scrolling
utilBtns.style.visibility = 'hidden';
if (!nativeFs) {
document.body.style.overflow = 'hidden';
}
self.preview();
self.focus();
self.emit('fullscreenenter');
callback.call(self);
}, wait);
};
self._exitFullscreen = function (el, callback) {
callback = callback || function () {};
this._fixScrollbars();
_saveStyleState(self.element, 'apply', _elementStates.element);
_saveStyleState(self.iframeElement, 'apply', _elementStates.iframeElement);
_saveStyleState(self.editorIframe, 'apply', _elementStates.editorIframe);
_saveStyleState(self.previewerIframe, 'apply', _elementStates.previewerIframe);
// We want to always revert back to the original styles in the CSS so,
// if it's a fluid width container it will expand on resize and not get
// stuck at a specific width after closing fullscreen.
self.element.style.width = self._eeState.reflowWidth ? self._eeState.reflowWidth : '';
self.element.style.height = self._eeState.reflowHeight ? self._eeState.reflowHeight : '';
utilBtns.style.visibility = 'visible';
// Put the editor back in the right state
// TODO: This is ugly... how do we make this nicer?
// setting fullscreen to false here prevents the
// native fs callback from calling this function again
self._eeState.fullscreen = false;
if (!nativeFs) {
document.body.style.overflow = 'auto';
}
else {
if (nativeFsWebkit) {
document.webkitCancelFullScreen();
}
else if (nativeFsMoz) {
document.mozCancelFullScreen();
}
else if (nativeFsW3C) {
document.exitFullscreen();
}
}
if (_isInEdit) {
self.edit();
}
else {
self.preview();
}
self.reflow();
self.emit('fullscreenexit');
callback.call(self);
};
// This setups up live previews by triggering preview() IF in fullscreen on keyup
self.editor.addEventListener('keyup', function () {
if (keypressTimer) {
window.clearTimeout(keypressTimer);
}
keypressTimer = window.setTimeout(function () {
if (self.is('fullscreen')) {
self.preview();
}
}, 250);
});
fsElement = self.iframeElement;
// Sets up the onclick event on utility buttons
utilBtns.addEventListener('click', function (e) {
var targetClass = e.target.className;
if (targetClass.indexOf('epiceditor-toggle-preview-btn') > -1) {
self.preview();
}
else if (targetClass.indexOf('epiceditor-toggle-edit-btn') > -1) {
self.edit();
}
else if (targetClass.indexOf('epiceditor-fullscreen-btn') > -1) {
self._goFullscreen(fsElement);
}
});
// Sets up the NATIVE fullscreen editor/previewer for WebKit
if (nativeFsWebkit) {
document.addEventListener('webkitfullscreenchange', function () {
if (!document.webkitIsFullScreen && self._eeState.fullscreen) {
self._exitFullscreen(fsElement);
}
}, false);
}
else if (nativeFsMoz) {
document.addEventListener('mozfullscreenchange', function () {
if (!document.mozFullScreen && self._eeState.fullscreen) {
self._exitFullscreen(fsElement);
}
}, false);
}
else if (nativeFsW3C) {
document.addEventListener('fullscreenchange', function () {
if (document.fullscreenElement == null && self._eeState.fullscreen) {
self._exitFullscreen(fsElement);
}
}, false);
}
// TODO: Move utilBar stuff into a utilBar setup function (_setupUtilBar)
utilBar = self.iframe.getElementById('epiceditor-utilbar');
// Hide it at first until they move their mouse
if (self.settings.button.bar !== true) {
utilBar.style.display = 'none';
}
utilBar.addEventListener('mouseover', function () {
if (utilBarTimer) {
clearTimeout(utilBarTimer);
}
});
function utilBarHandler(e) {
if (self.settings.button.bar !== "auto") {
return;
}
// Here we check if the mouse has moves more than 5px in any direction before triggering the mousemove code
// we do this for 2 reasons:
// 1. On Mac OS X lion when you scroll and it does the iOS like "jump" when it hits the top/bottom of the page itll fire off
// a mousemove of a few pixels depending on how hard you scroll
// 2. We give a slight buffer to the user in case he barely touches his touchpad or mouse and not trigger the UI
if (Math.abs(mousePos.y - e.pageY) >= 5 || Math.abs(mousePos.x - e.pageX) >= 5) {
utilBar.style.display = 'block';
// if we have a timer already running, kill it out
if (utilBarTimer) {
clearTimeout(utilBarTimer);
}
// begin a new timer that hides our object after 1000 ms
utilBarTimer = window.setTimeout(function () {
utilBar.style.display = 'none';
}, 1000);
}
mousePos = { y: e.pageY, x: e.pageX };
}
// Add keyboard shortcuts for convenience.
function shortcutHandler(e) {
if (e.keyCode == self.settings.shortcut.modifier) { isMod = true } // check for modifier press(default is alt key), save to var
if (e.keyCode == 17) { isCtrl = true } // check for ctrl/cmnd press, in order to catch ctrl/cmnd + s
if (e.keyCode == 18) { isCtrl = false }
// Check for alt+p and make sure were not in fullscreen - default shortcut to switch to preview
if (isMod === true && e.keyCode == self.settings.shortcut.preview && !self.is('fullscreen')) {
e.preventDefault();
if (self.is('edit') && self._previewEnabled) {
self.preview();
}
else if (self._editEnabled) {
self.edit();
}
}
// Check for alt+f - default shortcut to make editor fullscreen
if (isMod === true && e.keyCode == self.settings.shortcut.fullscreen && self._fullscreenEnabled) {
e.preventDefault();
self._goFullscreen(fsElement);
}
// Set the modifier key to false once *any* key combo is completed
// or else, on Windows, hitting the alt key will lock the isMod state to true (ticket #133)
if (isMod === true && e.keyCode !== self.settings.shortcut.modifier) {
isMod = false;
}
// When a user presses "esc", revert everything!
if (e.keyCode == 27 && self.is('fullscreen')) {
self._exitFullscreen(fsElement);
}
// Check for ctrl + s (since a lot of people do it out of habit) and make it do nothing
if (isCtrl === true && e.keyCode == 83) {
self.save();
e.preventDefault();
isCtrl = false;
}
// Do the same for Mac now (metaKey == cmd).
if (e.metaKey && e.keyCode == 83) {
self.save();
e.preventDefault();
}
}
function shortcutUpHandler(e) {
if (e.keyCode == self.settings.shortcut.modifier) { isMod = false }
if (e.keyCode == 17) { isCtrl = false }
}
function pasteHandler(e) {
var content;
if (e.clipboardData) {
//FF 22, Webkit, "standards"
e.preventDefault();
content = e.clipboardData.getData("text/plain");
self.editorIframeDocument.execCommand("insertText", false, content);
}
else if (window.clipboardData) {
//IE, "nasty"
e.preventDefault();
content = window.clipboardData.getData("Text");
content = content.replace(/</g, '<');
content = content.replace(/>/g, '>');
content = content.replace(/\n/g, '<br>');
content = content.replace(/\r/g, ''); //fuck you, ie!
content = content.replace(/<br>\s/g, '<br> ')
content = content.replace(/\s\s\s/g, ' ')
content = content.replace(/\s\s/g, ' ')
self.editorIframeDocument.selection.createRange().pasteHTML(content);
}
}
// Hide and show the util bar based on mouse movements
eventableIframes = [self.previewerIframeDocument, self.editorIframeDocument];
for (i = 0; i < eventableIframes.length; i++) {
eventableIframes[i].addEventListener('mousemove', function (e) {
utilBarHandler(e);
});
eventableIframes[i].addEventListener('scroll', function (e) {
utilBarHandler(e);
});
eventableIframes[i].addEventListener('keyup', function (e) {
shortcutUpHandler(e);
});
eventableIframes[i].addEventListener('keydown', function (e) {
shortcutHandler(e);
});
eventableIframes[i].addEventListener('paste', function (e) {
pasteHandler(e);
});
}
// Save the document every 100ms by default
// TODO: Move into autosave setup function (_setupAutoSave)
if (self.settings.file.autoSave) {
self._saveIntervalTimer = window.setInterval(function () {
if (!self._canSave) {
return;
}
self.save(false, true);
}, self.settings.file.autoSave);
}
// Update a textarea automatically if a textarea is given so you don't need
// AJAX to submit a form and instead fall back to normal form behavior
if (self.settings.textarea) {
self._setupTextareaSync();
}
window.addEventListener('resize', function () {
// If NOT webkit, and in fullscreen, we need to account for browser resizing
// we don't care about webkit because you can't resize in webkit's fullscreen
if (self.is('fullscreen')) {
_applyStyles(self.iframeElement, {
'width': window.outerWidth + 'px'
, 'height': window.innerHeight + 'px'
});
_applyStyles(self.element, {
'height': window.innerHeight + 'px'
});
_applyStyles(self.previewerIframe, {
'width': window.outerWidth / 2 + 'px'
, 'height': window.innerHeight + 'px'
});
_applyStyles(self.editorIframe, {
'width': window.outerWidth / 2 + 'px'
, 'height': window.innerHeight + 'px'
});
}
// Makes the editor support fluid width when not in fullscreen mode
else if (!self.is('fullscreen')) {
self.reflow();
}
});
// Set states before flipping edit and preview modes
self._eeState.loaded = true;
self._eeState.unloaded = false;
if (self.is('preview')) {
self.preview();
}
else {
self.edit();
}
self.iframe.close();
self._eeState.startup = false;
if (self.settings.autogrow) {
self._fixScrollbars();
boundAutogrow = function () {
setTimeout(function () {
self._autogrow();
}, 1);
};
//for if autosave is disabled or very slow
['keydown', 'keyup', 'paste', 'cut'].forEach(function (ev) {
self.getElement('editor').addEventListener(ev, boundAutogrow);
});
self.on('__update', boundAutogrow);
self.on('edit', function () {
setTimeout(boundAutogrow, 50)
});
self.on('preview', function () {
setTimeout(boundAutogrow, 50)
});
//for browsers that have rendering delays
setTimeout(boundAutogrow, 50);
boundAutogrow();
}
// The callback and call are the same thing, but different ways to access them
callback.call(this);
this.emit('load');
return this;
}
EpicEditor.prototype._setupTextareaSync = function () {
var self = this
, _syncTextarea;
// Even if autoSave is false, we want to make sure to keep the textarea synced
// with the editor's content. One bad thing about this tho is that we're
// creating two timers now in some configurations. We keep the textarea synced
// by saving and opening the textarea content from the draft file storage.
self._textareaSaveTimer = window.setInterval(function () {
if (!self._canSave) {
return;
}
self.save(true);
}, 100);
_syncTextarea = function () {
// TODO: Figure out root cause for having to do this ||.
// This only happens for draft files. Probably has something to do with
// the fact draft files haven't been saved by the time this is called.
// TODO: Add test for this case.
// Get the file.name each time as it can change. DO NOT save this to a
// var outside of this closure or the editor will stop syncing when the
// file is changed with importFile or open.
self._textareaElement.value = self.exportFile(self.settings.file.name, 'text', true) || self.settings.file.defaultContent;
}
if (typeof self.settings.textarea == 'string') {
self._textareaElement = document.getElementById(self.settings.textarea);
}
else if (typeof self.settings.textarea == 'object') {
self._textareaElement = self.settings.textarea;
}
// On page load, if there's content in the textarea that means one of two
// different things:
//
// 1. The editor didn't load and the user was writing in the textarea and
// now he refreshed the page or the JS loaded and the textarea now has
// content. If this is the case the user probably expects his content is
// moved into the editor and not lose what he typed.
//
// 2. The developer put content in the textarea from some server side
// code. In this case, the textarea will take precedence.
//
// If the developer wants drafts to be recoverable they should check if
// the local file in localStorage's modified date is newer than the server.
if (self._textareaElement.value !== '') {
self.importFile(self.settings.file.name, self._textareaElement.value);
// manually save draft after import so there is no delay between the
// import and exporting in _syncTextarea. Without this, _syncTextarea
// will pull the saved data from localStorage which will be <=100ms old.
self.save(true);
}
// Update the textarea on load and pull from drafts
_syncTextarea();
// Make sure to keep it updated
self.on('__update', _syncTextarea);
self.on('__create', _syncTextarea);
self.on('__save', _syncTextarea);
}
/**
* Will NOT focus the editor if the editor is still starting up AND
* focusOnLoad is set to false. This allows you to place this in code that
* gets fired during .load() without worrying about it overriding the user's
* option. For example use cases see preview() and edit().
* @returns {undefined}
*/
// Prevent focus when the user sets focusOnLoad to false by checking if the
// editor is starting up AND if focusOnLoad is true
EpicEditor.prototype._focusExceptOnLoad = function () {
var self = this;
if ((self._eeState.startup && self.settings.focusOnLoad) || !self._eeState.startup) {
self.focus();
}
}
/**
* Will remove the editor, but not offline files
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.unload = function (callback) {
// Make sure the editor isn't already unloaded.
if (this.is('unloaded')) {
throw new Error('Editor isn\'t loaded');
}
var self = this
, editor = window.parent.document.getElementById(self._instanceId);
editor.parentNode.removeChild(editor);
self._eeState.loaded = false;
self._eeState.unloaded = true;
callback = callback || function () {};
if (self.settings.textarea) {
self.removeListener('__update');
}
if (self._saveIntervalTimer) {
window.clearInterval(self._saveIntervalTimer);
}
if (self._textareaSaveTimer) {
window.clearInterval(self._textareaSaveTimer);
}
callback.call(this);
self.emit('unload');
return self;
}
/**
* reflow allows you to dynamically re-fit the editor in the parent without
* having to unload and then reload the editor again.
*
* reflow will also emit a `reflow` event and will return the new dimensions.
* If it's called without params it'll return the new width and height and if
* it's called with just width or just height it'll just return the width or
* height. It's returned as an object like: { width: '100px', height: '1px' }
*
* @param {string|null} kind Can either be 'width' or 'height' or null
* if null, both the height and width will be resized
* @param {function} callback A function to fire after the reflow is finished.
* Will return the width / height in an obj as the first param of the callback.
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.reflow = function (kind, callback) {
var self = this
, widthDiff = _outerWidth(self.element) - self.element.offsetWidth
, heightDiff = _outerHeight(self.element) - self.element.offsetHeight
, elements = [self.iframeElement, self.editorIframe, self.previewerIframe]
, eventData = {}
, newWidth
, newHeight;
if (typeof kind == 'function') {
callback = kind;
kind = null;
}
if (!callback) {
callback = function () {};
}
for (var x = 0; x < elements.length; x++) {
if (!kind || kind == 'width') {
newWidth = self.element.offsetWidth - widthDiff + 'px';
elements[x].style.width = newWidth;
self._eeState.reflowWidth = newWidth;
eventData.width = newWidth;
}
if (!kind || kind == 'height') {
newHeight = self.element.offsetHeight - heightDiff + 'px';
elements[x].style.height = newHeight;
self._eeState.reflowHeight = newHeight
eventData.height = newHeight;
}
}
self.emit('reflow', eventData);
callback.call(this, eventData);
return self;
}
/**
* Will take the markdown and generate a preview view based on the theme
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.preview = function () {
var self = this
, x
, theme = self.settings.theme.preview
, anchors;
_replaceClass(self.getElement('wrapper'), 'epiceditor-edit-mode', 'epiceditor-preview-mode');
// Check if no CSS theme link exists
if (!self.previewerIframeDocument.getElementById('theme')) {
_insertCSSLink(theme, self.previewerIframeDocument, 'theme');
}
else if (self.previewerIframeDocument.getElementById('theme').name !== theme) {
self.previewerIframeDocument.getElementById('theme').href = theme;
}
// Save a preview draft since it might not be saved to the real file yet
self.save(true);
// Add the generated draft HTML into the previewer
self.previewer.innerHTML = self.exportFile(null, 'html', true);
// Hide the editor and display the previewer
if (!self.is('fullscreen')) {
self.editorIframe.style.left = '-999999px';
self.previewerIframe.style.left = '';
self._eeState.preview = true;
self._eeState.edit = false;
self._focusExceptOnLoad();
}
self.emit('preview');
return self;
}
/**
* Helper to focus on the editor iframe. Will figure out which iframe to
* focus on based on which one is active and will handle the cross browser
* issues with focusing on the iframe vs the document body.
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.focus = function (pageload) {
var self = this
, isPreview = self.is('preview')
, focusElement = isPreview ? self.previewerIframeDocument.body
: self.editorIframeDocument.body;
if (_isFirefox() && isPreview) {
focusElement = self.previewerIframe;
}
focusElement.focus();
return this;
}
/**
* Puts the editor into fullscreen mode
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.enterFullscreen = function (callback) {
callback = callback || function () {};
if (this.is('fullscreen')) {
callback.call(this);
return this;
}
this._goFullscreen(this.iframeElement, callback);
return this;
}
/**
* Closes fullscreen mode if opened
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.exitFullscreen = function (callback) {
callback = callback || function () {};
if (!this.is('fullscreen')) {
callback.call(this);
return this;
}
this._exitFullscreen(this.iframeElement, callback);
return this;
}
/**
* Hides the preview and shows the editor again
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.edit = function () {
var self = this;
_replaceClass(self.getElement('wrapper'), 'epiceditor-preview-mode', 'epiceditor-edit-mode');
self._eeState.preview = false;
self._eeState.edit = true;
self.editorIframe.style.left = '';
self.previewerIframe.style.left = '-999999px';
self._focusExceptOnLoad();
self.emit('edit');
return this;
}
/**
* Grabs a specificed HTML node. Use it as a shortcut to getting the iframe contents
* @param {String} name The name of the node (can be document, body, editor, previewer, or wrapper)
* @returns {Object|Null}
*/
EpicEditor.prototype.getElement = function (name) {
var available = {
"container": this.element
, "wrapper": this.iframe.getElementById('epiceditor-wrapper')
, "wrapperIframe": this.iframeElement
, "editor": this.editorIframeDocument
, "editorIframe": this.editorIframe
, "previewer": this.previewerIframeDocument
, "previewerIframe": this.previewerIframe
}
// Check that the given string is a possible option and verify the editor isn't unloaded
// without this, you'd be given a reference to an object that no longer exists in the DOM
if (!available[name] || this.is('unloaded')) {
return null;
}
else {
return available[name];
}
}
/**
* Returns a boolean of each "state" of the editor. For example "editor.is('loaded')" // returns true/false
* @param {String} what the state you want to check for
* @returns {Boolean}
*/
EpicEditor.prototype.is = function (what) {
var self = this;
switch (what) {
case 'loaded':
return self._eeState.loaded;
case 'unloaded':
return self._eeState.unloaded
case 'preview':
return self._eeState.preview
case 'edit':
return self._eeState.edit;
case 'fullscreen':
return self._eeState.fullscreen;
// TODO: This "works", but the tests are saying otherwise. Come back to this
// and figure out how to fix it.
// case 'focused':
// return document.activeElement == self.iframeElement;
default:
return false;
}
}
/**
* Opens a file
* @param {string} name The name of the file you want to open
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.open = function (name) {
var self = this
, defaultContent = self.settings.file.defaultContent
, fileObj;
name = name || self.settings.file.name;
self.settings.file.name = name;
if (this._storage[self.settings.localStorageName]) {
fileObj = self.exportFile(name);
if (fileObj !== undefined) {
_setText(self.editor, fileObj);
self.emit('read');
}
else {
_setText(self.editor, defaultContent);
self.save(); // ensure a save
self.emit('create');
}
self.previewer.innerHTML = self.exportFile(null, 'html');
self.emit('open');
}
return this;
}
/**
* Saves content for offline use
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.save = function (_isPreviewDraft, _isAuto) {
var self = this
, storage
, isUpdate = false
, isNew = false
, file = self.settings.file.name
, previewDraftName = ''
, data = this._storage[previewDraftName + self.settings.localStorageName]
, content = _getText(this.editor);
if (_isPreviewDraft) {
previewDraftName = self._previewDraftLocation;
}
// This could have been false but since we're manually saving
// we know it's save to start autoSaving again
this._canSave = true;
// Guard against storage being wiped out without EpicEditor knowing
// TODO: Emit saving error - storage seems to have been wiped
if (data) {
storage = JSON.parse(this._storage[previewDraftName + self.settings.localStorageName]);
// If the file doesn't exist we need to create it
if (storage[file] === undefined) {
storage[file] = self._defaultFileSchema();
isNew = true;
}
// If it does, we need to check if the content is different and
// if it is, send the update event and update the timestamp
else if (content !== storage[file].content) {
storage[file].modified = new Date();
isUpdate = true;
}
//don't bother autosaving if the content hasn't actually changed
else if (_isAuto) {
return;
}
storage[file].content = content;
this._storage[previewDraftName + self.settings.localStorageName] = JSON.stringify(storage);
// If it's a new file, send a create event as well as a private one for
// use internally.
if (isNew) {
self.emit('create');
self.emit('__create');
}
// After the content is actually changed, emit update so it emits the
// updated content. Also send a private event for interal use.
if (isUpdate) {
self.emit('update');
self.emit('__update');
}
if (_isAuto) {
this.emit('autosave');
}
else if (!_isPreviewDraft) {
this.emit('save');
self.emit('__save');
}
}
return this;
}
/**
* Removes a page
* @param {string} name The name of the file you want to remove from localStorage
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.remove = function (name) {
var self = this
, s;
name = name || self.settings.file.name;
// If you're trying to delete a page you have open, block saving
if (name == self.settings.file.name) {
self._canSave = false;
}
s = JSON.parse(this._storage[self.settings.localStorageName]);
delete s[name];
this._storage[self.settings.localStorageName] = JSON.stringify(s);
this.emit('remove');
return this;
};
/**
* Renames a file
* @param {string} oldName The old file name
* @param {string} newName The new file name
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.rename = function (oldName, newName) {
var self = this
, s = JSON.parse(this._storage[self.settings.localStorageName]);
s[newName] = s[oldName];
delete s[oldName];
this._storage[self.settings.localStorageName] = JSON.stringify(s);
self.open(newName);
return this;
};
/**
* Imports a file and it's contents and opens it
* @param {string} name The name of the file you want to import (will overwrite existing files!)
* @param {string} content Content of the file you want to import
* @param {string} kind The kind of file you want to import (TBI)
* @param {object} meta Meta data you want to save with your file.
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.importFile = function (name, content, kind, meta) {
var self = this;
name = name || self.settings.file.name;
content = content || '';
kind = kind || 'md';
meta = meta || {};
// Set our current file to the new file and update the content
self.settings.file.name = name;
_setText(self.editor, content);
self.save();
if (self.is('fullscreen')) {
self.preview();
}
//firefox has trouble with importing and working out the size right away
if (self.settings.autogrow) {
setTimeout(function () {
self._autogrow();
}, 50);
}
return this;
};
/**
* Gets the local filestore
* @param {string} name Name of the file in the store
* @returns {object|undefined} the local filestore, or a specific file in the store, if a name is given
*/
EpicEditor.prototype._getFileStore = function (name, _isPreviewDraft) {
var previewDraftName = ''
, store;
if (_isPreviewDraft) {
previewDraftName = this._previewDraftLocation;
}
store = JSON.parse(this._storage[previewDraftName + this.settings.localStorageName]);
if (name) {
return store[name];
}
else {
return store;
}
}
/**
* Exports a file as a string in a supported format
* @param {string} name Name of the file you want to export (case sensitive)
* @param {string} kind Kind of file you want the content in (currently supports html and text, default is the format the browser "wants")
* @returns {string|undefined} The content of the file in the content given or undefined if it doesn't exist
*/
EpicEditor.prototype.exportFile = function (name, kind, _isPreviewDraft) {
var self = this
, file
, content;
name = name || self.settings.file.name;
kind = kind || 'text';
file = self._getFileStore(name, _isPreviewDraft);
// If the file doesn't exist just return early with undefined
if (file === undefined) {
return;
}
content = file.content;
switch (kind) {
case 'html':
content = _sanitizeRawContent(content);
return self.settings.parser(content);
case 'text':
return _sanitizeRawContent(content);
case 'json':
file.content = _sanitizeRawContent(file.content);
return JSON.stringify(file);
case 'raw':
return content;
default:
return content;
}
}
/**
* Gets the contents and metadata for files
* @param {string} name Name of the file whose data you want (case sensitive)
* @param {boolean} excludeContent whether the contents of files should be excluded
* @returns {object} An object with the names and data of every file, or just the data of one file if a name was given
*/
EpicEditor.prototype.getFiles = function (name, excludeContent) {
var file
, data = this._getFileStore(name);
if (name) {
if (data !== undefined) {
if (excludeContent) {
delete data.content;
}
else {
data.content = _sanitizeRawContent(data.content);
}
}
return data;
}
else {
for (file in data) {
if (data.hasOwnProperty(file)) {
if (excludeContent) {
delete data[file].content;
}
else {
data[file].content = _sanitizeRawContent(data[file].content);
}
}
}
return data;
}
}
// EVENTS
// TODO: Support for namespacing events like "preview.foo"
/**
* Sets up an event handler for a specified event
* @param {string} ev The event name
* @param {function} handler The callback to run when the event fires
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.on = function (ev, handler) {
var self = this;
if (!this.events[ev]) {
this.events[ev] = [];
}
this.events[ev].push(handler);
return self;
};
/**
* This will emit or "trigger" an event specified
* @param {string} ev The event name
* @param {any} data Any data you want to pass into the callback
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.emit = function (ev, data) {
var self = this
, x;
data = data || self.getFiles(self.settings.file.name);
if (!this.events[ev]) {
return;
}
function invokeHandler(handler) {
handler.call(self, data);
}
for (x = 0; x < self.events[ev].length; x++) {
invokeHandler(self.events[ev][x]);
}
return self;
};
/**
* Will remove any listeners added from EpicEditor.on()
* @param {string} ev The event name
* @param {function} handler Handler to remove
* @returns {object} EpicEditor will be returned
*/
EpicEditor.prototype.removeListener = function (ev, handler) {
var self = this;
if (!handler) {
this.events[ev] = [];
return self;
}
if (!this.events[ev]) {
return self;
}
// Otherwise a handler and event exist, so take care of it
this.events[ev].splice(this.events[ev].indexOf(handler), 1);
return self;
}
/**
* Handles autogrowing the editor
*/
EpicEditor.prototype._autogrow = function () {
var editorHeight
, newHeight
, minHeight
, maxHeight
, el
, style
, maxedOut = false;
//autogrow in fullscreen is nonsensical
if (!this.is('fullscreen')) {
if (this.is('edit')) {
el = this.getElement('editor').documentElement;
}
else {
el = this.getElement('previewer').documentElement;
}
editorHeight = _outerHeight(el);
newHeight = editorHeight;
//handle minimum
minHeight = this.settings.autogrow.minHeight;
if (typeof minHeight === 'function') {
minHeight = minHeight(this);
}
if (minHeight && newHeight < minHeight) {
newHeight = minHeight;
}
//handle maximum
maxHeight = this.settings.autogrow.maxHeight;
if (typeof maxHeight === 'function') {
maxHeight = maxHeight(this);
}
if (maxHeight && newHeight > maxHeight) {
newHeight = maxHeight;
maxedOut = true;
}
if (maxedOut) {
this._fixScrollbars('auto');
} else {
this._fixScrollbars('hidden');
}
//actual resize
if (newHeight != this.oldHeight) {
this.getElement('container').style.height = newHeight + 'px';
this.reflow();
if (this.settings.autogrow.scroll) {
window.scrollBy(0, newHeight - this.oldHeight);
}
this.oldHeight = newHeight;
}
}
}
/**
* Shows or hides scrollbars based on the autogrow setting
* @param {string} forceSetting a value to force the overflow to
*/
EpicEditor.prototype._fixScrollbars = function (forceSetting) {
var setting;
if (this.settings.autogrow) {
setting = 'hidden';
}
else {
setting = 'auto';
}
setting = forceSetting || setting;
this.getElement('editor').documentElement.style.overflow = setting;
this.getElement('previewer').documentElement.style.overflow = setting;
}
EpicEditor.version = '0.2.2';
// Used to store information to be shared across editors
EpicEditor._data = {};
if (typeof window.define === 'function' && window.define.amd) {
window.define(function () { return EpicEditor; });
} else {
window.EpicEditor = EpicEditor;
}
})(window);
/**
* marked - a markdown parser
* Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
* https://github.com/chjj/marked
*/
;(function() {
/**
* Block-Level Grammar
*/
var block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: noop,
hr: /^( *[-*_]){3,} *(?:\n+|$)/,
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
nptable: noop,
lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
table: noop,
paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
text: /^[^\n]+/
};
block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, 'gm')
(/bull/g, block.bullet)
();
block.list = replace(block.list)
(/bull/g, block.bullet)
('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
('def', '\\n+(?=' + block.def.source + ')')
();
block.blockquote = replace(block.blockquote)
('def', block.def)
();
block._tag = '(?!(?:'
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
+ '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
block.html = replace(block.html)
('comment', /<!--[\s\S]*?-->/)
('closed', /<(tag)[\s\S]+?<\/\1>/)
('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
(/tag/g, block._tag)
();
block.paragraph = replace(block.paragraph)
('hr', block.hr)
('heading', block.heading)
('lheading', block.lheading)
('blockquote', block.blockquote)
('tag', '<' + block._tag)
('def', block.def)
();
/**
* Normal Block Grammar
*/
block.normal = merge({}, block);
/**
* GFM Block Grammar
*/
block.gfm = merge({}, block.normal, {
fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/,
paragraph: /^/
});
block.gfm.paragraph = replace(block.paragraph)
('(?!', '(?!'
+ block.gfm.fences.source.replace('\\1', '\\2') + '|'
+ block.list.source.replace('\\1', '\\3') + '|')
();
/**
* GFM + Tables Block Grammar
*/
block.tables = merge({}, block.gfm, {
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
});
/**
* Block Lexer
*/
function Lexer(options) {
this.tokens = [];
this.tokens.links = {};
this.options = options || marked.defaults;
this.rules = block.normal;
if (this.options.gfm) {
if (this.options.tables) {
this.rules = block.tables;
} else {
this.rules = block.gfm;
}
}
}
/**
* Expose Block Rules
*/
Lexer.rules = block;
/**
* Static Lex Method
*/
Lexer.lex = function(src, options) {
var lexer = new Lexer(options);
return lexer.lex(src);
};
/**
* Preprocessing
*/
Lexer.prototype.lex = function(src) {
src = src
.replace(/\r\n|\r/g, '\n')
.replace(/\t/g, ' ')
.replace(/\u00a0/g, ' ')
.replace(/\u2424/g, '\n');
return this.token(src, true);
};
/**
* Lexing
*/
Lexer.prototype.token = function(src, top, bq) {
var src = src.replace(/^ +$/gm, '')
, next
, loose
, cap
, bull
, b
, item
, space
, i
, l;
while (src) {
// newline
if (cap = this.rules.newline.exec(src)) {
src = src.substring(cap[0].length);
if (cap[0].length > 1) {
this.tokens.push({
type: 'space'
});
}
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
cap = cap[0].replace(/^ {4}/gm, '');
this.tokens.push({
type: 'code',
text: !this.options.pedantic
? cap.replace(/\n+$/, '')
: cap
});
continue;
}
// fences (gfm)
if (cap = this.rules.fences.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'code',
lang: cap[2],
text: cap[3]
});
continue;
}
// heading
if (cap = this.rules.heading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[1].length,
text: cap[2]
});
continue;
}
// table no leading pipe (gfm)
if (top && (cap = this.rules.nptable.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// lheading
if (cap = this.rules.lheading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[2] === '=' ? 1 : 2,
text: cap[1]
});
continue;
}
// hr
if (cap = this.rules.hr.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'hr'
});
continue;
}
// blockquote
if (cap = this.rules.blockquote.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'blockquote_start'
});
cap = cap[0].replace(/^ *> ?/gm, '');
// Pass `top` to keep the current
// "toplevel" state. This is exactly
// how markdown.pl works.
this.token(cap, top, true);
this.tokens.push({
type: 'blockquote_end'
});
continue;
}
// list
if (cap = this.rules.list.exec(src)) {
src = src.substring(cap[0].length);
bull = cap[2];
this.tokens.push({
type: 'list_start',
ordered: bull.length > 1
});
// Get each top-level item.
cap = cap[0].match(this.rules.item);
next = false;
l = cap.length;
i = 0;
for (; i < l; i++) {
item = cap[i];
// Remove the list item's bullet
// so it is seen as the next token.
space = item.length;
item = item.replace(/^ *([*+-]|\d+\.) +/, '');
// Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) {
space -= item.length;
item = !this.options.pedantic
? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
: item.replace(/^ {1,4}/gm, '');
}
// Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (this.options.smartLists && i !== l - 1) {
b = block.bullet.exec(cap[i + 1])[0];
if (bull !== b && !(bull.length > 1 && b.length > 1)) {
src = cap.slice(i + 1).join('\n') + src;
i = l - 1;
}
}
// Determine whether item is loose or not.
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
// for discount behavior.
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item.charAt(item.length - 1) === '\n';
if (!loose) loose = next;
}
this.tokens.push({
type: loose
? 'loose_item_start'
: 'list_item_start'
});
// Recurse.
this.token(item, false, bq);
this.tokens.push({
type: 'list_item_end'
});
}
this.tokens.push({
type: 'list_end'
});
continue;
}
// html
if (cap = this.rules.html.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: this.options.sanitize
? 'paragraph'
: 'html',
pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',
text: cap[0]
});
continue;
}
// def
if ((!bq && top) && (cap = this.rules.def.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.links[cap[1].toLowerCase()] = {
href: cap[2],
title: cap[3]
};
continue;
}
// table (gfm)
if (top && (cap = this.rules.table.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i]
.replace(/^ *\| *| *\| *$/g, '')
.split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// top-level paragraph
if (top && (cap = this.rules.paragraph.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'paragraph',
text: cap[1].charAt(cap[1].length - 1) === '\n'
? cap[1].slice(0, -1)
: cap[1]
});
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
this.tokens.push({
type: 'text',
text: cap[0]
});
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return this.tokens;
};
/**
* Inline-Level Grammar
*/
var inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
};
inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
inline.link = replace(inline.link)
('inside', inline._inside)
('href', inline._href)
();
inline.reflink = replace(inline.reflink)
('inside', inline._inside)
();
/**
* Normal Inline Grammar
*/
inline.normal = merge({}, inline);
/**
* Pedantic Inline Grammar
*/
inline.pedantic = merge({}, inline.normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
});
/**
* GFM Inline Grammar
*/
inline.gfm = merge({}, inline.normal, {
escape: replace(inline.escape)('])', '~|])')(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)
(']|', '~]|')
('|', '|https?://|')
()
});
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge({}, inline.gfm, {
br: replace(inline.br)('{2,}', '*')(),
text: replace(inline.gfm.text)('{2,}', '*')()
});
/**
* Inline Lexer & Compiler
*/
function InlineLexer(links, options) {
this.options = options || marked.defaults;
this.links = links;
this.rules = inline.normal;
this.renderer = this.options.renderer || new Renderer;
this.renderer.options = this.options;
if (!this.links) {
throw new
Error('Tokens array requires a `links` property.');
}
if (this.options.gfm) {
if (this.options.breaks) {
this.rules = inline.breaks;
} else {
this.rules = inline.gfm;
}
} else if (this.options.pedantic) {
this.rules = inline.pedantic;
}
}
/**
* Expose Inline Rules
*/
InlineLexer.rules = inline;
/**
* Static Lexing/Compiling Method
*/
InlineLexer.output = function(src, links, options) {
var inline = new InlineLexer(links, options);
return inline.output(src);
};
/**
* Lexing/Compiling
*/
InlineLexer.prototype.output = function(src) {
var out = ''
, link
, text
, href
, cap;
while (src) {
// escape
if (cap = this.rules.escape.exec(src)) {
src = src.substring(cap[0].length);
out += cap[1];
continue;
}
// autolink
if (cap = this.rules.autolink.exec(src)) {
src = src.substring(cap[0].length);
if (cap[2] === '@') {
text = cap[1].charAt(6) === ':'
? this.mangle(cap[1].substring(7))
: this.mangle(cap[1]);
href = this.mangle('mailto:') + text;
} else {
text = escape(cap[1]);
href = text;
}
out += this.renderer.link(href, null, text);
continue;
}
// url (gfm)
if (!this.inLink && (cap = this.rules.url.exec(src))) {
src = src.substring(cap[0].length);
text = escape(cap[1]);
href = text;
out += this.renderer.link(href, null, text);
continue;
}
// tag
if (cap = this.rules.tag.exec(src)) {
if (!this.inLink && /^<a /i.test(cap[0])) {
this.inLink = true;
} else if (this.inLink && /^<\/a>/i.test(cap[0])) {
this.inLink = false;
}
src = src.substring(cap[0].length);
out += this.options.sanitize
? escape(cap[0])
: cap[0];
continue;
}
// link
if (cap = this.rules.link.exec(src)) {
src = src.substring(cap[0].length);
this.inLink = true;
out += this.outputLink(cap, {
href: cap[2],
title: cap[3]
});
this.inLink = false;
continue;
}
// reflink, nolink
if ((cap = this.rules.reflink.exec(src))
|| (cap = this.rules.nolink.exec(src))) {
src = src.substring(cap[0].length);
link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = this.links[link.toLowerCase()];
if (!link || !link.href) {
out += cap[0].charAt(0);
src = cap[0].substring(1) + src;
continue;
}
this.inLink = true;
out += this.outputLink(cap, link);
this.inLink = false;
continue;
}
// strong
if (cap = this.rules.strong.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.strong(this.output(cap[2] || cap[1]));
continue;
}
// em
if (cap = this.rules.em.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.em(this.output(cap[2] || cap[1]));
continue;
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.codespan(escape(cap[2], true));
continue;
}
// br
if (cap = this.rules.br.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.br();
continue;
}
// del (gfm)
if (cap = this.rules.del.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.del(this.output(cap[1]));
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
src = src.substring(cap[0].length);
out += escape(this.smartypants(cap[0]));
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return out;
};
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function(cap, link) {
var href = escape(link.href)
, title = link.title ? escape(link.title) : null;
return cap[0].charAt(0) !== '!'
? this.renderer.link(href, title, this.output(cap[1]))
: this.renderer.image(href, title, escape(cap[1]));
};
/**
* Smartypants Transformations
*/
InlineLexer.prototype.smartypants = function(text) {
if (!this.options.smartypants) return text;
return text
// em-dashes
.replace(/--/g, '\u2014')
// opening singles
.replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
// closing singles & apostrophes
.replace(/'/g, '\u2019')
// opening doubles
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
// closing doubles
.replace(/"/g, '\u201d')
// ellipses
.replace(/\.{3}/g, '\u2026');
};
/**
* Mangle Links
*/
InlineLexer.prototype.mangle = function(text) {
var out = ''
, l = text.length
, i = 0
, ch;
for (; i < l; i++) {
ch = text.charCodeAt(i);
if (Math.random() > 0.5) {
ch = 'x' + ch.toString(16);
}
out += '&#' + ch + ';';
}
return out;
};
/**
* Renderer
*/
function Renderer(options) {
this.options = options || {};
}
Renderer.prototype.code = function(code, lang, escaped) {
if (this.options.highlight) {
var out = this.options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out;
}
}
if (!lang) {
return '<pre><code>'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>';
}
return '<pre><code class="'
+ this.options.langPrefix
+ escape(lang, true)
+ '">'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>\n';
};
Renderer.prototype.blockquote = function(quote) {
return '<blockquote>\n' + quote + '</blockquote>\n';
};
Renderer.prototype.html = function(html) {
return html;
};
Renderer.prototype.heading = function(text, level, raw) {
return '<h'
+ level
+ ' id="'
+ this.options.headerPrefix
+ raw.toLowerCase().replace(/[^\w]+/g, '-')
+ '">'
+ text
+ '</h'
+ level
+ '>\n';
};
Renderer.prototype.hr = function() {
return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
};
Renderer.prototype.list = function(body, ordered) {
var type = ordered ? 'ol' : 'ul';
return '<' + type + '>\n' + body + '</' + type + '>\n';
};
Renderer.prototype.listitem = function(text) {
return '<li>' + text + '</li>\n';
};
Renderer.prototype.paragraph = function(text) {
return '<p>' + text + '</p>\n';
};
Renderer.prototype.table = function(header, body) {
return '<table>\n'
+ '<thead>\n'
+ header
+ '</thead>\n'
+ '<tbody>\n'
+ body
+ '</tbody>\n'
+ '</table>\n';
};
Renderer.prototype.tablerow = function(content) {
return '<tr>\n' + content + '</tr>\n';
};
Renderer.prototype.tablecell = function(content, flags) {
var type = flags.header ? 'th' : 'td';
var tag = flags.align
? '<' + type + ' style="text-align:' + flags.align + '">'
: '<' + type + '>';
return tag + content + '</' + type + '>\n';
};
// span level renderer
Renderer.prototype.strong = function(text) {
return '<strong>' + text + '</strong>';
};
Renderer.prototype.em = function(text) {
return '<em>' + text + '</em>';
};
Renderer.prototype.codespan = function(text) {
return '<code>' + text + '</code>';
};
Renderer.prototype.br = function() {
return this.options.xhtml ? '<br/>' : '<br>';
};
Renderer.prototype.del = function(text) {
return '<del>' + text + '</del>';
};
Renderer.prototype.link = function(href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href))
.replace(/[^\w:]/g, '')
.toLowerCase();
} catch (e) {
return '';
}
if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
return '';
}
}
var out = '<a href="' + href + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>' + text + '</a>';
return out;
};
Renderer.prototype.image = function(href, title, text) {
var out = '<img src="' + href + '" alt="' + text + '"';
if (title) {
out += ' title="' + title + '"';
}
out += this.options.xhtml ? '/>' : '>';
return out;
};
/**
* Parsing & Compiling
*/
function Parser(options) {
this.tokens = [];
this.token = null;
this.options = options || marked.defaults;
this.options.renderer = this.options.renderer || new Renderer;
this.renderer = this.options.renderer;
this.renderer.options = this.options;
}
/**
* Static Parse Method
*/
Parser.parse = function(src, options, renderer) {
var parser = new Parser(options, renderer);
return parser.parse(src);
};
/**
* Parse Loop
*/
Parser.prototype.parse = function(src) {
this.inline = new InlineLexer(src.links, this.options, this.renderer);
this.tokens = src.reverse();
var out = '';
while (this.next()) {
out += this.tok();
}
return out;
};
/**
* Next Token
*/
Parser.prototype.next = function() {
return this.token = this.tokens.pop();
};
/**
* Preview Next Token
*/
Parser.prototype.peek = function() {
return this.tokens[this.tokens.length - 1] || 0;
};
/**
* Parse Text Tokens
*/
Parser.prototype.parseText = function() {
var body = this.token.text;
while (this.peek().type === 'text') {
body += '\n' + this.next().text;
}
return this.inline.output(body);
};
/**
* Parse Current Token
*/
Parser.prototype.tok = function() {
switch (this.token.type) {
case 'space': {
return '';
}
case 'hr': {
return this.renderer.hr();
}
case 'heading': {
return this.renderer.heading(
this.inline.output(this.token.text),
this.token.depth,
this.token.text);
}
case 'code': {
return this.renderer.code(this.token.text,
this.token.lang,
this.token.escaped);
}
case 'table': {
var header = ''
, body = ''
, i
, row
, cell
, flags
, j;
// header
cell = '';
for (i = 0; i < this.token.header.length; i++) {
flags = { header: true, align: this.token.align[i] };
cell += this.renderer.tablecell(
this.inline.output(this.token.header[i]),
{ header: true, align: this.token.align[i] }
);
}
header += this.renderer.tablerow(cell);
for (i = 0; i < this.token.cells.length; i++) {
row = this.token.cells[i];
cell = '';
for (j = 0; j < row.length; j++) {
cell += this.renderer.tablecell(
this.inline.output(row[j]),
{ header: false, align: this.token.align[j] }
);
}
body += this.renderer.tablerow(cell);
}
return this.renderer.table(header, body);
}
case 'blockquote_start': {
var body = '';
while (this.next().type !== 'blockquote_end') {
body += this.tok();
}
return this.renderer.blockquote(body);
}
case 'list_start': {
var body = ''
, ordered = this.token.ordered;
while (this.next().type !== 'list_end') {
body += this.tok();
}
return this.renderer.list(body, ordered);
}
case 'list_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.token.type === 'text'
? this.parseText()
: this.tok();
}
return this.renderer.listitem(body);
}
case 'loose_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.tok();
}
return this.renderer.listitem(body);
}
case 'html': {
var html = !this.token.pre && !this.options.pedantic
? this.inline.output(this.token.text)
: this.token.text;
return this.renderer.html(html);
}
case 'paragraph': {
return this.renderer.paragraph(this.inline.output(this.token.text));
}
case 'text': {
return this.renderer.paragraph(this.parseText());
}
}
};
/**
* Helpers
*/
function escape(html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function unescape(html) {
return html.replace(/&([#\w]+);/g, function(_, n) {
n = n.toLowerCase();
if (n === 'colon') return ':';
if (n.charAt(0) === '#') {
return n.charAt(1) === 'x'
? String.fromCharCode(parseInt(n.substring(2), 16))
: String.fromCharCode(+n.substring(1));
}
return '';
});
}
function replace(regex, opt) {
regex = regex.source;
opt = opt || '';
return function self(name, val) {
if (!name) return new RegExp(regex, opt);
val = val.source || val;
val = val.replace(/(^|[^\[])\^/g, '$1');
regex = regex.replace(name, val);
return self;
};
}
function noop() {}
noop.exec = noop;
function merge(obj) {
var i = 1
, target
, key;
for (; i < arguments.length; i++) {
target = arguments[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key];
}
}
}
return obj;
}
/**
* Marked
*/
function marked(src, opt, callback) {
if (callback || typeof opt === 'function') {
if (!callback) {
callback = opt;
opt = null;
}
opt = merge({}, marked.defaults, opt || {});
var highlight = opt.highlight
, tokens
, pending
, i = 0;
try {
tokens = Lexer.lex(src, opt)
} catch (e) {
return callback(e);
}
pending = tokens.length;
var done = function(err) {
if (err) {
opt.highlight = highlight;
return callback(err);
}
var out;
try {
out = Parser.parse(tokens, opt);
} catch (e) {
err = e;
}
opt.highlight = highlight;
return err
? callback(err)
: callback(null, out);
};
if (!highlight || highlight.length < 3) {
return done();
}
delete opt.highlight;
if (!pending) return done();
for (; i < tokens.length; i++) {
(function(token) {
if (token.type !== 'code') {
return --pending || done();
}
return highlight(token.text, token.lang, function(err, code) {
if (err) return done(err);
if (code == null || code === token.text) {
return --pending || done();
}
token.text = code;
token.escaped = true;
--pending || done();
});
})(tokens[i]);
}
return;
}
try {
if (opt) opt = merge({}, marked.defaults, opt);
return Parser.parse(Lexer.lex(src, opt), opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/chjj/marked.';
if ((opt || marked.defaults).silent) {
return '<p>An error occured:</p><pre>'
+ escape(e.message + '', true)
+ '</pre>';
}
throw e;
}
}
/**
* Options
*/
marked.options =
marked.setOptions = function(opt) {
merge(marked.defaults, opt);
return marked;
};
marked.defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: false,
silent: false,
highlight: null,
langPrefix: 'lang-',
smartypants: false,
headerPrefix: '',
renderer: new Renderer,
xhtml: false
};
/**
* Expose
*/
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Renderer = Renderer;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;
marked.parse = marked;
if (typeof module !== 'undefined' && typeof exports === 'object') {
module.exports = marked;
} else if (typeof define === 'function' && define.amd) {
define(function() { return marked; });
} else {
this.marked = marked;
}
}).call(function() {
return this || (typeof window !== 'undefined' ? window : global);
}());