PHP and Javascript implementations of a simple markdown parser
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

testjs.html 65KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Markdown Unit Tests</title>
  6. <link rel="icon" href="data:;base64,iVBORw0KGgo=">
  7. <style type="text/css">
  8. :root {
  9. font-family: sans-serif;
  10. --color-passed: #090;
  11. --color-failed: #a00;
  12. --color-errored: #a80;
  13. --color-untested: #888;
  14. --color-background: #fff;
  15. --color-text: #000;
  16. --color-secondary: #888;
  17. background-color: var(--color-background);
  18. color: var(--color-text);
  19. }
  20. .testclass {
  21. border: 1px solid var(--color-secondary);
  22. padding: 0.5em 1em;
  23. margin-bottom: 1em;
  24. max-width: 50em;
  25. }
  26. .testclassname {
  27. font-weight: bold;
  28. font-size: 1.25rem;
  29. padding-bottom: 0.25em;
  30. }
  31. .testclassstatus.passed { color: var(--color-passed); }
  32. .testclassstatus.failed { color: var(--color-failed); }
  33. .testclassstatus.errored { color: var(--color-errored); }
  34. .testclassstatus.untested { color: var(--color-untested); }
  35. .testcase {
  36. clear: both;
  37. padding: 0.2em 0;
  38. margin-left: 2em;
  39. }
  40. .testcase {
  41. border-top: 1px solid var(--color-secondary);
  42. }
  43. .testcasename {
  44. font-family: monospace;
  45. }
  46. .testcasestatus {
  47. font-weight: bold;
  48. font-size: 80%;
  49. float: left;
  50. }
  51. .testcasetiming {
  52. float: right;
  53. color: var(--color-secondary);
  54. font-size: 80%;
  55. }
  56. .testcasererun {
  57. float: right;
  58. padding-left: 0.5em;
  59. cursor: pointer;
  60. font-size: 150%;
  61. }
  62. .testcaseresult {
  63. height: 1em;
  64. }
  65. .testcasemessage {
  66. clear: both;
  67. }
  68. .result-untested {
  69. color: var(--color-untested);
  70. }
  71. .result-testing {
  72. color: var(--color-text);
  73. }
  74. .result-passed {
  75. color: var(--color-passed);
  76. }
  77. .result-failed {
  78. color: var(--color-failed);
  79. }
  80. .result-errored {
  81. color: var(--color-errored);
  82. }
  83. @media (prefers-color-scheme: dark) {
  84. :root {
  85. --color-passed: #090;
  86. --color-failed: #a00;
  87. --color-errored: #a80;
  88. --color-untested: #888;
  89. --color-background: #000;
  90. --color-text: #fff;
  91. --color-secondary: #888;
  92. }
  93. }
  94. </style>
  95. <script src="js/markdown.js"></script>
  96. <script src="js/spreadsheet.js"></script>
  97. <!-- Testing infrastructure -->
  98. <script>
  99. /**
  100. * @param {String} text
  101. * @returns {String}
  102. */
  103. function escapeHTML(text) {
  104. return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br/>\n');
  105. }
  106. class ResultType {
  107. static untested = new ResultType('untested');
  108. static testing = new ResultType('testing');
  109. static passed = new ResultType('passed');
  110. static failed = new ResultType('failed');
  111. static errored = new ResultType('errored');
  112. #name;
  113. constructor(name) {
  114. this.#name = name;
  115. }
  116. toString() {
  117. return `${this.constructor.name}.${this.#name}`;
  118. }
  119. }
  120. class FailureError extends Error {
  121. constructor(message=null) {
  122. super(message);
  123. }
  124. }
  125. class BaseTest {
  126. setUp() {}
  127. tearDown() {}
  128. /** @var {TestCaseRunner|null} */
  129. currentRunner = null;
  130. fail(failMessage=null) {
  131. throw new FailureError(failMessage || 'failed');
  132. }
  133. assertTrue(test, failMessage=null) {
  134. if (!test) this.fail(failMessage || `expected true, got ${test}`);
  135. }
  136. assertFalse(test, failMessage=null) {
  137. if (test) this.fail(failMessage || `expected false, got ${test}`);
  138. }
  139. assertEqual(a, b, floatDifferenceRatio=0.000001, failMessage=null) {
  140. if (MDUtils.equal(a, b, floatDifferenceRatio)) return;
  141. const aVal = (typeof a == 'string') ? `"${a}"` : `${a}`;
  142. const bVal = (typeof b == 'string') ? `"${b}"` : `${b}`;
  143. if (aVal.length > 20 || bVal.length > 20) {
  144. this.fail(failMessage || `equality failed:\n${aVal}\n!=\n${bVal}`);
  145. } else {
  146. this.fail(failMessage || `equality failed: ${aVal} != ${bVal}`);
  147. }
  148. }
  149. expectError(e=true) {
  150. if (this.currentRunner) this.currentRunner.expectedError = e;
  151. }
  152. /**
  153. * @param {number} maxTime maximum time in seconds
  154. * @param {function} timedCode code to run and time
  155. */
  156. profile(maxTime, timedCode) {
  157. const startTime = performance.now();
  158. const result = timedCode();
  159. const endTime = performance.now();
  160. const seconds = (endTime - startTime) / 1000.0;
  161. if (seconds > maxTime) {
  162. this.fail(`Expected <= ${maxTime}s execution time, actual ${seconds}s.`);
  163. }
  164. return result;
  165. }
  166. }
  167. /**
  168. * Manages the running and results of a single test method on a test
  169. * class.
  170. */
  171. class TestCaseRunner {
  172. /** @var {number} */
  173. static #nextUniqueId = 1;
  174. /** @var {number} */
  175. uniqueId = 0;
  176. /** @var {BaseTest} */
  177. #objectUnderTest;
  178. /** @var {method} */
  179. #method;
  180. /** @var {ResultType} */
  181. result = ResultType.untested;
  182. /** @var {String|null} */
  183. message = null;
  184. expectedError = null;
  185. duration = null;
  186. /** @var {String} */
  187. get className() { return this.#objectUnderTest.constructor.name; }
  188. /** @var {String} */
  189. get methodName() { return this.#method.name; }
  190. /**
  191. * @param {BaseTest} objectUnderTest
  192. * @param {method} method
  193. */
  194. constructor(objectUnderTest, method) {
  195. this.#objectUnderTest = objectUnderTest;
  196. this.#method = method;
  197. this.uniqueId = TestCaseRunner.#nextUniqueId++;
  198. }
  199. run() {
  200. var start;
  201. this.expectedError = null;
  202. this.#objectUnderTest.currentRunner = this;
  203. try {
  204. this.#objectUnderTest.setUp();
  205. } catch (e) {
  206. console.error(`Failed to run ${this.className}.setUp() - ${e.message}`);
  207. this.result = ResultType.errored;
  208. this.message = e.message;
  209. return;
  210. }
  211. try {
  212. start = performance.now();
  213. this.#method.bind(this.#objectUnderTest)();
  214. this.duration = performance.now() - start;
  215. this.result = ResultType.passed;
  216. this.message = null;
  217. } catch (e) {
  218. this.duration = performance.now() - start;
  219. if (e instanceof FailureError) {
  220. this.result = ResultType.failed;
  221. this.message = e.message;
  222. } else if (this.#isExpectedError(e)) {
  223. this.result = ResultType.passed;
  224. this.message = null;
  225. } else {
  226. this.result = ResultType.errored;
  227. this.message = e.message;
  228. if (e.stack !== undefined) {
  229. this.message += "\n" + e.stack;
  230. }
  231. }
  232. } finally {
  233. this.expectedError = null;
  234. try {
  235. this.#objectUnderTest.tearDown();
  236. this.#objectUnderTest.currentRunner = null;
  237. } catch (e0) {
  238. console.error(`Failed to run ${this.className}.tearDown() - ${e0.message}`);
  239. this.result = ResultType.errored;
  240. this.message = e0.message;
  241. }
  242. }
  243. }
  244. get #cssId() { return `testcase${this.uniqueId}`; }
  245. #isExpectedError(e) {
  246. if (this.expectedError === null) return false;
  247. if (this.expectedError === true) return true;
  248. // TODO: Have a way to specify details about what kind of error is expected. Maybe a prototype instance and/or a testing lambda.
  249. return false;
  250. }
  251. toHTML() {
  252. var html = `<div class="testcase" id="${this.#cssId}">`;
  253. html += `<div class="testcasename"><span class="testcasemethod">${this.methodName}</span></div>`;
  254. if (this.result == ResultType.passed || this.result == ResultType.failed || this.result == ResultType.errored) {
  255. const rerunId = `testcasererun-${this.#cssId}`;
  256. const testId = this.uniqueId;
  257. html += `<div class="testcasererun" id="${rerunId}">🔄</div>`;
  258. setTimeout(() => {
  259. const node = document.getElementById(rerunId);
  260. if (!node) return;
  261. node.addEventListener('click', () => {
  262. TestClassRunner.rerun(testId);
  263. });
  264. }, 0);
  265. }
  266. html += '<div class="testcaseresult">';
  267. switch (this.result) {
  268. case ResultType.untested:
  269. html += '<div class="testcasestatus result-untested">Waiting to test</div>';
  270. break;
  271. case ResultType.testing:
  272. html += '<div class="testcasestatus result-testing">Testing...</div>';
  273. break;
  274. case ResultType.passed:
  275. html += '<div class="testcasestatus result-passed">Passed</div>';
  276. break;
  277. case ResultType.failed:
  278. html += '<div class="testcasestatus result-failed">Failed</div>';
  279. break;
  280. case ResultType.errored:
  281. html += '<div class="testcasestatus result-errored">Errored</div>';
  282. break;
  283. }
  284. if (this.duration !== null) {
  285. html += `<div class="testcasetiming">${Number(this.duration / 1000.0).toFixed(3)}s</div>`;
  286. }
  287. html += '</div>';
  288. if (this.message !== null) {
  289. html += `<div class="testcasemessage">${escapeHTML(this.message)}</div>`;
  290. }
  291. html += `</div>`;
  292. return html;
  293. }
  294. /**
  295. * Updates the HTML node in-place with the current status, or
  296. * adds it if it does not exist yet.
  297. */
  298. updateHTML() {
  299. let existing = document.getElementById(this.#cssId);
  300. if (existing) {
  301. existing.outerHTML = this.toHTML();
  302. } else {
  303. document.getElementById('results').innerHTML += this.toHTML();
  304. }
  305. }
  306. /**
  307. * @param {object} objectUnderTest
  308. * @returns {TestCaseRunner[]}
  309. */
  310. static findTestCases(objectUnderTest) {
  311. if (!(objectUnderTest instanceof BaseTest)) return [];
  312. var members = [];
  313. var obj = objectUnderTest;
  314. do {
  315. members.push(...Object.getOwnPropertyNames(obj));
  316. } while (obj = Object.getPrototypeOf(obj));
  317. return members.sort().filter((e, i, arr) => {
  318. if (e != arr[i + 1] && typeof objectUnderTest[e] == 'function' && e.startsWith('test')) return true;
  319. }).map((name) => {
  320. return new TestCaseRunner(objectUnderTest, objectUnderTest[name]);
  321. });
  322. }
  323. }
  324. class TestClassRunner {
  325. static #nextUniqueId = 1;
  326. #uniqueId = 0;
  327. #theClass;
  328. #instance;
  329. #testCases;
  330. get testCases() { return this.#testCases; }
  331. constructor(theClass) {
  332. this.#theClass = theClass;
  333. this.#instance = new theClass();
  334. this.#testCases = TestCaseRunner.findTestCases(this.#instance);
  335. this.#uniqueId = TestClassRunner.#nextUniqueId++;
  336. }
  337. get #cssId() { return `testclass${this.#uniqueId}`; }
  338. #summaryHTML() {
  339. var anyTesting = false;
  340. var anyFailed = false;
  341. var anyErrored = false;
  342. var anyUntested = false;
  343. var anyPassed = false;
  344. var allPassed = true;
  345. for (const test of this.testCases) {
  346. switch (test.result) {
  347. case ResultType.untested:
  348. anyUntested = true;
  349. allPassed = false;
  350. break;
  351. case ResultType.testing:
  352. anyTesting = true;
  353. allPassed = false;
  354. break;
  355. case ResultType.passed:
  356. anyPassed = true;
  357. break;
  358. case ResultType.failed:
  359. anyFailed = true;
  360. allPassed = false;
  361. break;
  362. case ResultType.errored:
  363. anyErrored = true;
  364. allPassed = false;
  365. break;
  366. }
  367. }
  368. var html = '';
  369. html += `<summary class="testclasssummary" id="${this.#cssId}summary">`;
  370. html += `<span class="testclassname">${this.#theClass.name}</span> `;
  371. if (anyTesting || (anyUntested && (anyPassed || anyFailed || anyErrored))) {
  372. html += '<span class="testclassstatus testing">Testing...</span>';
  373. } else if (anyErrored) {
  374. html += '<span class="testclassstatus errored">Errored</span>';
  375. } else if (anyFailed) {
  376. html += '<span class="testclassstatus failed">Failed</span>';
  377. } else if (allPassed) {
  378. html += '<span class="testclassstatus passed">Passed</span>';
  379. }
  380. html += '</summary>';
  381. return html;
  382. }
  383. toHTML() {
  384. var html = '';
  385. html += `<div class="testclass" id="${this.#cssId}">`;
  386. html += `<details id="${this.#cssId}details">`;
  387. html += this.#summaryHTML();
  388. for (const testCase of this.#testCases) {
  389. html += testCase.toHTML();
  390. }
  391. html += '</details>';
  392. html += '</div>';
  393. return html;
  394. }
  395. updateHTML() {
  396. var existing = document.getElementById(`${this.#cssId}summary`);
  397. if (!existing) {
  398. document.getElementById('results').innerHTML += this.toHTML();
  399. } else {
  400. existing.outerHTML = this.#summaryHTML();
  401. var allPassed = true;
  402. for (const test of this.testCases) {
  403. if (test.result != ResultType.passed) {
  404. allPassed = false;
  405. break;
  406. }
  407. }
  408. if (!TestClassRunner.#isRerunning) {
  409. document.getElementById(`${this.#cssId}details`).open = !allPassed;
  410. }
  411. }
  412. }
  413. static #idToTestCase = {}; // number -> [TestClassRunner, TestCaseRunner]
  414. static runAll(testClasses) {
  415. for (const testClass of testClasses) {
  416. const classRunner = new TestClassRunner(testClass);
  417. classRunner.updateHTML();
  418. const cases = classRunner.testCases.map(function(test) { return [ classRunner, test ] });
  419. for (const testTuple of cases) {
  420. this.#idToTestCase[testTuple[1].uniqueId] = testTuple;
  421. }
  422. this.#testQueue.push(...cases);
  423. }
  424. this.#runTestQueue();
  425. }
  426. static #testQueue = []; // tuples of [TestClassRunner, TestCaseRunner]
  427. static #testInterval = null;
  428. static #isRerunning = false;
  429. static #runTestQueue() {
  430. if (this.#testInterval) return;
  431. this.#testInterval = setInterval(function() {
  432. if (TestClassRunner.#testQueue.length == 0) {
  433. clearInterval(TestClassRunner.#testInterval);
  434. TestClassRunner.#testInterval = null;
  435. return;
  436. }
  437. var classRunner;
  438. var testCase;
  439. [ classRunner, testCase ] = TestClassRunner.#testQueue[0];
  440. if (testCase.result == ResultType.untested) {
  441. testCase.result = ResultType.testing;
  442. testCase.updateHTML();
  443. classRunner.updateHTML();
  444. } else if (testCase.result == ResultType.testing) {
  445. TestClassRunner.#testQueue.splice(0, 1);
  446. testCase.run();
  447. testCase.updateHTML();
  448. classRunner.updateHTML();
  449. }
  450. }, 1);
  451. }
  452. static rerun(testId) {
  453. const tuple = this.#idToTestCase[testId];
  454. if (!tuple) return;
  455. /** @type {TestClassRunner} */
  456. const testClass = tuple[0];
  457. /** @type {TestCaseRunner} */
  458. const testCase = tuple[1];
  459. testCase.result = ResultType.untested;
  460. testCase.updateHTML();
  461. this.#testQueue.push([testClass, testCase]);
  462. this.#isRerunning = true;
  463. this.#runTestQueue();
  464. }
  465. }
  466. </script>
  467. <!-- Tests -->
  468. <script>
  469. function onLoad() {
  470. let testClasses = [
  471. TokenTests,
  472. UtilsTests,
  473. InlineTests,
  474. BlockTests,
  475. CellValueTests,
  476. CellAddressRangeTests,
  477. ExpressionSetTests,
  478. SpreadsheetMarkdownIntegrationTests,
  479. ];
  480. TestClassRunner.runAll(testClasses);
  481. }
  482. document.addEventListener('DOMContentLoaded', onLoad);
  483. function normalizeWhitespace(str) {
  484. return str.replace(/\s+/g, ' ').replace(/(?:^\s+|\s+$)/g, '');
  485. }
  486. class TokenTests extends BaseTest {
  487. test_findFirstTokens() {
  488. const tokens = [
  489. new MDToken('Lorem', MDTokenType.Text),
  490. new MDToken(' ', MDTokenType.Whitespace),
  491. new MDToken('_', MDTokenType.Underscore),
  492. new MDToken('ipsum', MDTokenType.Text),
  493. new MDToken('_', MDTokenType.Underscore),
  494. new MDToken(' ', MDTokenType.Whitespace),
  495. new MDToken('dolor', MDTokenType.Text),
  496. new MDToken('_', MDTokenType.Underscore),
  497. new MDToken('sit', MDTokenType.Text),
  498. new MDToken('_', MDTokenType.Underscore),
  499. ];
  500. const pattern = [
  501. MDTokenType.Underscore,
  502. ];
  503. const result = MDToken.findFirstTokens(tokens, pattern);
  504. const expected = {
  505. tokens: [ tokens[2] ],
  506. index: 2,
  507. };
  508. this.assertEqual(result, expected);
  509. }
  510. test_findFirstTokens_optionalWhitespace1() {
  511. const tokens = [
  512. new MDToken('Lorem', MDTokenType.Text),
  513. new MDToken(' ', MDTokenType.Whitespace),
  514. new MDToken('[ipsum]', MDTokenType.Label, 'ipsum'),
  515. new MDToken('(link.html)', MDTokenType.URL, 'link.html'),
  516. new MDToken(' ', MDTokenType.Whitespace),
  517. new MDToken('dolor', MDTokenType.Text),
  518. ];
  519. const pattern = [
  520. MDTokenType.Label,
  521. MDTokenType.META_OptionalWhitespace,
  522. MDTokenType.URL,
  523. ];
  524. const result = MDToken.findFirstTokens(tokens, pattern);
  525. const expected = {
  526. tokens: [ tokens[2], tokens[3] ],
  527. index: 2,
  528. };
  529. this.assertEqual(result, expected);
  530. }
  531. test_findFirstTokens_optionalWhitespace2() {
  532. const tokens = [
  533. new MDToken('Lorem', MDTokenType.Text),
  534. new MDToken(' ', MDTokenType.Whitespace),
  535. new MDToken('[ipsum]', MDTokenType.Label, 'ipsum'),
  536. new MDToken(' ', MDTokenType.Whitespace),
  537. new MDToken('(link.html)', MDTokenType.URL, 'link.html'),
  538. new MDToken(' ', MDTokenType.Whitespace),
  539. new MDToken('dolor', MDTokenType.Text),
  540. ];
  541. const pattern = [
  542. MDTokenType.Label,
  543. MDTokenType.META_OptionalWhitespace,
  544. MDTokenType.URL,
  545. ];
  546. const result = MDToken.findFirstTokens(tokens, pattern);
  547. const expected = {
  548. tokens: [ tokens[2], tokens[3], tokens[4] ],
  549. index: 2,
  550. };
  551. this.assertEqual(result, expected);
  552. }
  553. test_findPairedTokens() {
  554. const tokens = [
  555. new MDToken('Lorem', MDTokenType.Text),
  556. new MDToken(' ', MDTokenType.Whitespace),
  557. new MDToken('_', MDTokenType.Underscore),
  558. new MDToken('ipsum', MDTokenType.Text),
  559. new MDToken('_', MDTokenType.Underscore),
  560. new MDToken(' ', MDTokenType.Whitespace),
  561. new MDToken('dolor', MDTokenType.Text),
  562. new MDToken('_', MDTokenType.Underscore),
  563. new MDToken('sit', MDTokenType.Text),
  564. new MDToken('_', MDTokenType.Underscore),
  565. ];
  566. const pattern = [
  567. MDTokenType.Underscore,
  568. ];
  569. const result = MDToken.findPairedTokens(tokens, pattern, pattern);
  570. const expected = {
  571. startTokens: [ tokens[2] ],
  572. contentTokens: [ tokens[3] ],
  573. endTokens: [ tokens[4] ],
  574. startIndex: 2,
  575. contentIndex: 3,
  576. endIndex: 4,
  577. totalLength: 3,
  578. }
  579. this.assertEqual(result, expected);
  580. }
  581. }
  582. class UtilsTests extends BaseTest {
  583. test_stripIndent() {
  584. this.assertEqual(MDUtils.stripIndent(''), '');
  585. this.assertEqual(MDUtils.stripIndent(' '), '');
  586. this.assertEqual(MDUtils.stripIndent('foo'), 'foo');
  587. this.assertEqual(MDUtils.stripIndent(' foo'), 'foo');
  588. this.assertEqual(MDUtils.stripIndent(' foo'), 'foo');
  589. this.assertEqual(MDUtils.stripIndent(' foo'), 'foo');
  590. this.assertEqual(MDUtils.stripIndent(' foo'), 'foo');
  591. this.assertEqual(MDUtils.stripIndent(' foo'), ' foo');
  592. this.assertEqual(MDUtils.stripIndent('\tfoo'), 'foo');
  593. this.assertEqual(MDUtils.stripIndent('\t\tfoo'), '\tfoo');
  594. this.assertEqual(MDUtils.stripIndent('\t\tfoo', 2), 'foo');
  595. this.assertEqual(MDUtils.stripIndent(' foo', 2), 'foo');
  596. }
  597. test_countIndents() {
  598. this.assertEqual(MDUtils.countIndents(''), 0);
  599. this.assertEqual(MDUtils.countIndents(' '), 1);
  600. this.assertEqual(MDUtils.countIndents(' '), 1);
  601. this.assertEqual(MDUtils.countIndents('foo'), 0);
  602. this.assertEqual(MDUtils.countIndents('foo'), 0);
  603. this.assertEqual(MDUtils.countIndents(' foo'), 1);
  604. this.assertEqual(MDUtils.countIndents(' foo'), 1);
  605. this.assertEqual(MDUtils.countIndents(' foo'), 1);
  606. this.assertEqual(MDUtils.countIndents(' foo'), 1);
  607. this.assertEqual(MDUtils.countIndents(' foo'), 2);
  608. this.assertEqual(MDUtils.countIndents('\tfoo'), 1);
  609. this.assertEqual(MDUtils.countIndents('\t\tfoo'), 2);
  610. this.assertEqual(MDUtils.countIndents('', true), 0);
  611. this.assertEqual(MDUtils.countIndents(' ', true), 0);
  612. this.assertEqual(MDUtils.countIndents(' ', true), 1);
  613. this.assertEqual(MDUtils.countIndents('foo', true), 0);
  614. this.assertEqual(MDUtils.countIndents(' foo', true), 0);
  615. this.assertEqual(MDUtils.countIndents(' foo', true), 0);
  616. this.assertEqual(MDUtils.countIndents(' foo', true), 0);
  617. this.assertEqual(MDUtils.countIndents(' foo', true), 1);
  618. this.assertEqual(MDUtils.countIndents(' foo', true), 1);
  619. this.assertEqual(MDUtils.countIndents('\tfoo', true), 1);
  620. this.assertEqual(MDUtils.countIndents('\t\tfoo', true), 2);
  621. }
  622. test_tokenizeLabel() {
  623. // Escapes are preserved
  624. this.assertEqual(MDToken.tokenizeLabel('[foo] bar'), [ '[foo]', 'foo' ]);
  625. this.assertEqual(MDToken.tokenizeLabel('[foo\\[] bar'), [ '[foo\\[]', 'foo\\[' ]);
  626. this.assertEqual(MDToken.tokenizeLabel('[foo\\]] bar'), [ '[foo\\]]', 'foo\\]' ]);
  627. this.assertEqual(MDToken.tokenizeLabel('[foo[]] bar'), [ '[foo[]]', 'foo[]' ]);
  628. this.assertEqual(MDToken.tokenizeLabel('[foo\\(] bar'), [ '[foo\\(]', 'foo\\(' ]);
  629. this.assertEqual(MDToken.tokenizeLabel('[foo\\)] bar'), [ '[foo\\)]', 'foo\\)' ]);
  630. this.assertEqual(MDToken.tokenizeLabel('[foo()] bar'), [ '[foo()]', 'foo()' ]);
  631. this.assertEqual(MDToken.tokenizeLabel('foo bar'), null);
  632. this.assertEqual(MDToken.tokenizeLabel('[foo\\] bar'), null);
  633. this.assertEqual(MDToken.tokenizeLabel('[foo bar'), null);
  634. this.assertEqual(MDToken.tokenizeLabel('[foo[] bar'), null);
  635. }
  636. test_tokenizeURL() {
  637. this.assertEqual(MDToken.tokenizeURL('(page.html) foo'), [ '(page.html)', 'page.html', null ]);
  638. this.assertEqual(MDToken.tokenizeURL('(page.html "link title") foo'), [ '(page.html "link title")', 'page.html', 'link title' ]);
  639. this.assertEqual(MDToken.tokenizeURL('(https://example.com/path/page.html?query=foo&bar=baz#fragment) foo'), [ '(https://example.com/path/page.html?query=foo&bar=baz#fragment)', 'https://example.com/path/page.html?query=foo&bar=baz#fragment', null ]);
  640. this.assertEqual(MDToken.tokenizeURL('page.html foo'), null);
  641. this.assertEqual(MDToken.tokenizeURL('(page.html foo'), null);
  642. this.assertEqual(MDToken.tokenizeURL('page.html) foo'), null);
  643. this.assertEqual(MDToken.tokenizeURL('(page.html "title) foo'), null);
  644. this.assertEqual(MDToken.tokenizeURL('(page .html) foo'), null);
  645. this.assertEqual(MDToken.tokenizeURL('(user@example.com) foo'), null);
  646. this.assertEqual(MDToken.tokenizeURL('(user@example.com "title") foo'), null);
  647. }
  648. test_tokenizeEmail() {
  649. this.assertEqual(MDToken.tokenizeEmail('(user@example.com)'), [ '(user@example.com)', 'user@example.com', null ]);
  650. this.assertEqual(MDToken.tokenizeEmail('(user@example.com "link title")'), [ '(user@example.com "link title")', 'user@example.com', 'link title' ]);
  651. this.assertEqual(MDToken.tokenizeEmail('(https://example.com) foo'), null);
  652. this.assertEqual(MDToken.tokenizeEmail('(https://example.com "link title") foo'), null);
  653. this.assertEqual(MDToken.tokenizeEmail('(user@example.com "link title) foo'), null);
  654. this.assertEqual(MDToken.tokenizeEmail('(user@example.com foo'), null);
  655. this.assertEqual(MDToken.tokenizeEmail('user@example.com) foo'), null);
  656. }
  657. }
  658. class InlineTests extends BaseTest {
  659. /** @type {Markdown} */
  660. parser;
  661. md(markdown) {
  662. return normalizeWhitespace(this.parser.toHTML(markdown));
  663. }
  664. setUp() {
  665. this.parser = Markdown.completeParser;
  666. }
  667. test_simpleText() {
  668. let markdown = 'Lorem ipsum';
  669. let expected = 'Lorem ipsum';
  670. let actual = this.md(markdown);
  671. this.assertEqual(actual, expected);
  672. }
  673. test_strong() {
  674. let markdown = 'Lorem **ipsum** dolor **sit**';
  675. let expected = 'Lorem <strong>ipsum</strong> dolor <strong>sit</strong>';
  676. let actual = this.md(markdown);
  677. this.assertEqual(actual, expected);
  678. }
  679. test_emphasis() {
  680. let markdown = 'Lorem _ipsum_ dolor _sit_';
  681. let expected = 'Lorem <em>ipsum</em> dolor <em>sit</em>';
  682. let actual = this.md(markdown);
  683. this.assertEqual(actual, expected);
  684. }
  685. test_strongEmphasis_cleanNesting1() {
  686. let markdown = 'Lorem **ipsum *dolor* sit** amet';
  687. let expected = 'Lorem <strong>ipsum <em>dolor</em> sit</strong> amet';
  688. let actual = this.md(markdown);
  689. this.assertEqual(actual, expected);
  690. }
  691. test_strongEmphasis_cleanNesting2() {
  692. let markdown = 'Lorem *ipsum **dolor** sit* amet';
  693. let expected = 'Lorem <em>ipsum <strong>dolor</strong> sit</em> amet';
  694. let actual = this.md(markdown);
  695. this.assertEqual(actual, expected);
  696. }
  697. test_strongEmphasis_tightNesting() {
  698. let markdown = 'Lorem ***ipsum*** dolor';
  699. let expected1 = 'Lorem <strong><em>ipsum</em></strong> dolor';
  700. let expected2 = 'Lorem <em><strong>ipsum</strong></em> dolor';
  701. let actual = this.md(markdown);
  702. this.assertTrue(actual == expected1 || actual == expected2);
  703. }
  704. test_strongEmphasis_lopsidedNesting1() {
  705. let markdown = 'Lorem ***ipsum* dolor** sit';
  706. let expected = 'Lorem <strong><em>ipsum</em> dolor</strong> sit';
  707. let actual = this.md(markdown);
  708. this.assertEqual(actual, expected);
  709. }
  710. test_strongEmphasis_lopsidedNesting2() {
  711. let markdown = 'Lorem ***ipsum** dolor* sit';
  712. let expected = 'Lorem <em><strong>ipsum</strong> dolor</em> sit';
  713. let actual = this.md(markdown);
  714. this.assertEqual(actual, expected);
  715. }
  716. test_strongEmphasis_lopsidedNesting3() {
  717. let markdown = 'Lorem **ipsum *dolor*** sit';
  718. let expected = 'Lorem <strong>ipsum <em>dolor</em></strong> sit';
  719. let actual = this.md(markdown);
  720. this.assertEqual(actual, expected);
  721. }
  722. test_strongEmphasis_lopsidedNesting4() {
  723. let markdown = 'Lorem *ipsum **dolor*** sit';
  724. let expected = 'Lorem <em>ipsum <strong>dolor</strong></em> sit';
  725. let actual = this.md(markdown);
  726. this.assertEqual(actual, expected);
  727. }
  728. test_inlineCode() {
  729. let markdown = 'Lorem `ipsum` dolor';
  730. let expected = 'Lorem <code>ipsum</code> dolor';
  731. let actual = this.md(markdown);
  732. this.assertEqual(actual, expected);
  733. }
  734. test_inlineCode_withInnerBacktick() {
  735. let markdown = 'Lorem ``ip`su`m`` dolor';
  736. let expected = 'Lorem <code>ip`su`m</code> dolor';
  737. let actual = this.md(markdown);
  738. this.assertEqual(actual, expected);
  739. }
  740. test_strikethrough_double() {
  741. let markdown = 'Lorem ~~ipsum~~ dolor';
  742. let expected = 'Lorem <s>ipsum</s> dolor';
  743. let actual = this.md(markdown);
  744. this.assertEqual(actual, expected);
  745. }
  746. test_subscript() {
  747. let markdown = 'H~2~O';
  748. let expected = 'H<sub>2</sub>O';
  749. let actual = this.md(markdown);
  750. this.assertEqual(actual, expected);
  751. }
  752. test_superscript() {
  753. let markdown = 'E=mc^2^';
  754. let expected = 'E=mc<sup>2</sup>';
  755. let actual = this.md(markdown);
  756. this.assertEqual(actual, expected);
  757. }
  758. test_highlight() {
  759. let markdown = 'Lorem ==ipsum== dolor';
  760. let expected = 'Lorem <mark>ipsum</mark> dolor';
  761. let actual = this.md(markdown);
  762. this.assertEqual(actual, expected);
  763. }
  764. test_underline() {
  765. let markdown = 'Lorem __ipsum__ dolor';
  766. let expected = 'Lorem <u>ipsum</u> dolor';
  767. let actual = this.md(markdown);
  768. this.assertEqual(actual, expected);
  769. }
  770. test_link_fullyQualified() {
  771. let markdown = 'Lorem [ipsum](https://example.com/path/page.html) dolor';
  772. let expected = 'Lorem <a href="https://example.com/path/page.html">ipsum</a> dolor';
  773. let actual = this.md(markdown);
  774. this.assertEqual(actual, expected);
  775. }
  776. test_link_relative() {
  777. let markdown = 'Lorem [ipsum](page.html) dolor';
  778. let expected = 'Lorem <a href="page.html">ipsum</a> dolor';
  779. let actual = this.md(markdown);
  780. this.assertEqual(actual, expected);
  781. }
  782. test_link_title() {
  783. let markdown = 'Lorem [ipsum](page.html "link title") dolor';
  784. let expected = 'Lorem <a href="page.html" title="link title">ipsum</a> dolor';
  785. let actual = this.md(markdown);
  786. this.assertEqual(actual, expected);
  787. }
  788. test_link_literal() {
  789. let markdown = 'Lorem <https://example.com> dolor';
  790. let expected = 'Lorem <a href="https://example.com">https://example.com</a> dolor';
  791. let actual = this.md(markdown);
  792. this.assertEqual(actual, expected);
  793. }
  794. test_link_ref() {
  795. let markdown = "Lorem [ipsum][ref] dolor\n\n[ref]: https://example.com";
  796. let expected = '<p>Lorem <a href="https://example.com">ipsum</a> dolor</p>';
  797. let actual = this.md(markdown);
  798. this.assertEqual(actual, expected);
  799. }
  800. test_link_email() {
  801. let markdown = 'Lorem [ipsum](user@example.com) dolor';
  802. let expected = 'Lorem <a href="mailto:&#117;&#115;&#101;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;">ipsum</a> dolor';
  803. let actual = this.md(markdown);
  804. this.assertEqual(actual, expected);
  805. }
  806. test_link_email_withTitle() {
  807. let markdown = 'Lorem [ipsum](user@example.com "title") dolor';
  808. let expected = 'Lorem <a href="mailto:&#117;&#115;&#101;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;" title="title">ipsum</a> dolor';
  809. let actual = this.md(markdown);
  810. this.assertEqual(actual, expected);
  811. }
  812. test_link_literalEmail() {
  813. let markdown = 'Lorem <user@example.com> dolor';
  814. let expected = 'Lorem <a href="mailto:&#117;&#115;&#101;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;">&#117;&#115;&#101;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;</a> dolor';
  815. let actual = this.md(markdown);
  816. this.assertEqual(actual, expected);
  817. }
  818. test_link_image() {
  819. let markdown = 'Lorem [![alt](image.jpg)](page.html) ipsum';
  820. let expected = 'Lorem <a href="page.html"><img src="image.jpg" alt="alt"></a> ipsum';
  821. let actual = this.md(markdown);
  822. this.assertEqual(actual, expected);
  823. }
  824. test_link_image_complex() {
  825. let markdown = 'Lorem [![alt] (image.jpg "image title")] (page.html "link title") ipsum';
  826. let expected = 'Lorem <a href="page.html" title="link title"><img src="image.jpg" alt="alt" title="image title"></a> ipsum';
  827. let actual = this.md(markdown);
  828. this.assertEqual(actual, expected);
  829. }
  830. test_image() {
  831. let markdown = 'Lorem ![alt text](image.jpg) dolor';
  832. let expected = 'Lorem <img src="image.jpg" alt="alt text"> dolor';
  833. let actual = this.md(markdown);
  834. this.assertEqual(actual, expected);
  835. }
  836. test_image_noAlt() {
  837. let markdown = 'Lorem ![](image.jpg) dolor';
  838. let expected = 'Lorem <img src="image.jpg"> dolor';
  839. let actual = this.md(markdown);
  840. this.assertEqual(actual, expected);
  841. }
  842. test_image_withTitle() {
  843. let markdown = 'Lorem ![alt text](image.jpg "image title") dolor';
  844. let expected = 'Lorem <img src="image.jpg" alt="alt text" title="image title"> dolor';
  845. let actual = this.md(markdown);
  846. this.assertEqual(actual, expected);
  847. }
  848. test_image_ref() {
  849. let markdown = 'Lorem ![alt text][ref] dolor\n\n' +
  850. '[ref]: image.jpg "image title"';
  851. let expected = '<p>Lorem <img src="image.jpg" alt="alt text" title="image title"> dolor</p>';
  852. let actual = this.md(markdown);
  853. this.assertEqual(actual, expected);
  854. }
  855. test_htmlTags() {
  856. let markdown = 'Lorem <strong title=\'with " quote\' id="with \' apostrophe" lang=unquoted translate forbidden="true">ipsum</strong> dolor';
  857. let expected = 'Lorem <strong title="with &quot; quote" id="with \' apostrophe" lang="unquoted" translate>ipsum</strong> dolor';
  858. let actual = this.md(markdown);
  859. this.assertEqual(actual, expected);
  860. }
  861. }
  862. class BlockTests extends BaseTest {
  863. /** @type {Markdown} */
  864. parser;
  865. md(markdown) {
  866. return normalizeWhitespace(this.parser.toHTML(markdown));
  867. }
  868. setUp() {
  869. this.parser = Markdown.completeParser;
  870. }
  871. test_paragraphs() {
  872. let markdown = "Lorem ipsum\n\nDolor sit amet";
  873. let expected = "<p>Lorem ipsum</p> <p>Dolor sit amet</p>";
  874. let actual = this.md(markdown);
  875. this.assertEqual(actual, expected);
  876. }
  877. test_paragraph_lineGrouping() {
  878. let markdown = "Lorem ipsum\ndolor sit amet";
  879. let expected = "Lorem ipsum dolor sit amet";
  880. let actual = this.md(markdown);
  881. this.assertEqual(actual, expected);
  882. }
  883. test_header_underlineH1() {
  884. let markdown = "Header 1\n===\n\nLorem ipsum";
  885. let expected = "<h1>Header 1</h1> <p>Lorem ipsum</p>";
  886. let actual = this.md(markdown);
  887. this.assertEqual(actual, expected);
  888. }
  889. test_header_underlineH2() {
  890. let markdown = "Header 2\n---\n\nLorem ipsum";
  891. let expected = "<h2>Header 2</h2> <p>Lorem ipsum</p>";
  892. let actual = this.md(markdown);
  893. this.assertEqual(actual, expected);
  894. }
  895. test_header_hash() {
  896. let markdown = "# Header 1\n## Header 2\n### Header 3\n#### Header 4\n##### Header 5\n###### Header 6\n";
  897. let expected = '<h1>Header 1</h1> <h2>Header 2</h2> <h3>Header 3</h3> <h4>Header 4</h4> <h5>Header 5</h5> <h6>Header 6</h6>';
  898. let actual = this.md(markdown);
  899. this.assertEqual(actual, expected);
  900. }
  901. test_header_hash_trailing() {
  902. let markdown = "# Header 1 #\n## Header 2 ##\n### Header 3 ######";
  903. let expected = '<h1>Header 1</h1> <h2>Header 2</h2> <h3>Header 3</h3>';
  904. let actual = this.md(markdown);
  905. this.assertEqual(actual, expected);
  906. }
  907. test_unorderedList() {
  908. let markdown = "* Lorem\n* Ipsum\n* Dolor";
  909. let expected = '<ul> <li>Lorem</li> <li>Ipsum</li> <li>Dolor</li> </ul>';
  910. let actual = this.md(markdown);
  911. this.assertEqual(actual, expected);
  912. }
  913. test_unorderedList_nested() {
  914. let markdown = "* Lorem\n + Ipsum\n* Dolor";
  915. let expected = '<ul> <li>Lorem<ul> <li>Ipsum</li> </ul> </li> <li>Dolor</li> </ul>';
  916. let actual = this.md(markdown);
  917. this.assertEqual(actual, expected);
  918. }
  919. test_unorderedList_hitch() {
  920. // This incomplete bulleted list locked up the browser at one
  921. // point, not forever but a REALLY long time
  922. this.profile(1.0, () => {
  923. let markdown = "Testing\n\n* ";
  924. let expected = '<p>Testing</p> <ul> <li></li> </ul>';
  925. let actual = this.md(markdown);
  926. this.assertEqual(actual, expected);
  927. });
  928. }
  929. test_orderedList() {
  930. let markdown = "1. Lorem\n1. Ipsum\n5. Dolor";
  931. let expected = '<ol> <li>Lorem</li> <li>Ipsum</li> <li>Dolor</li> </ol>';
  932. let actual = this.md(markdown);
  933. this.assertEqual(actual, expected);
  934. }
  935. test_orderedList_numbering() {
  936. let markdown = "4. Lorem\n1. Ipsum\n9. Dolor";
  937. let expected = '<ol start="4"> <li>Lorem</li> <li>Ipsum</li> <li>Dolor</li> </ol>';
  938. let actual = this.md(markdown);
  939. this.assertEqual(actual, expected);
  940. }
  941. test_orderedList_nested1() {
  942. let markdown = "1. Lorem\n 1. Ipsum\n1. Dolor";
  943. let expected = '<ol> <li>Lorem<ol> <li>Ipsum</li> </ol> </li> <li>Dolor</li> </ol>';
  944. let actual = this.md(markdown);
  945. this.assertEqual(actual, expected);
  946. }
  947. test_orderedList_nested2() {
  948. let markdown = "1. Lorem\n 1. Ipsum\n 1. Dolor\n 1. Sit\n1. Amet";
  949. let expected = '<ol> <li>Lorem<ol> <li>Ipsum<ol> <li>Dolor</li> </ol> </li> <li>Sit</li> </ol> </li> <li>Amet</li> </ol>';
  950. let actual = this.md(markdown);
  951. this.assertEqual(actual, expected);
  952. }
  953. test_blockquote() {
  954. let markdown = '> Lorem ipsum dolor';
  955. let expected = '<blockquote>Lorem ipsum dolor</blockquote>';
  956. let actual = this.md(markdown);
  957. this.assertEqual(actual, expected);
  958. }
  959. test_blockquote_paragraphs() {
  960. let markdown = '> Lorem ipsum dolor\n>\n>Sit amet';
  961. let expected = '<blockquote> <p>Lorem ipsum dolor</p> <p>Sit amet</p> </blockquote>';
  962. let actual = this.md(markdown);
  963. this.assertEqual(actual, expected);
  964. }
  965. test_blockquote_list() {
  966. let markdown = '> 1. Lorem\n> 2. Ipsum';
  967. let expected = '<blockquote> <ol> <li>Lorem</li> <li>Ipsum</li> </ol> </blockquote>';
  968. let actual = this.md(markdown);
  969. this.assertEqual(actual, expected);
  970. }
  971. test_codeBlock_indented() {
  972. let markdown = "Code\n\n function foo() {\n return 'bar';\n }\n\nend";
  973. let expected = "<p>Code</p>\n\n<pre><code>function foo() {\n return 'bar';\n}</code></pre>\n\n<p>end</p>";
  974. let actual = this.parser.toHTML(markdown).trim(); // don't normalize whitespace
  975. this.assertEqual(actual.replace(/ /g, '⎵'), expected.replace(/ /g, '⎵'));
  976. }
  977. test_codeBlock_fenced() {
  978. let markdown = "Code\n\n```\nfunction foo() {\n return 'bar';\n}\n```\n\nend";
  979. let expected = "<p>Code</p>\n\n<pre><code>function foo() {\n return 'bar';\n}</code></pre>\n\n<p>end</p>";
  980. let actual = this.parser.toHTML(markdown).trim(); // don't normalize whitespace
  981. this.assertEqual(actual.replace(/ /g, '⎵'), expected.replace(/ /g, '⎵'));
  982. }
  983. test_codeBlock_fenced_language() {
  984. let markdown = "Code\n\n```javascript\nfunction foo() {\n return 'bar';\n}\n```\n\nend";
  985. let expected = "<p>Code</p>\n\n<pre><code class=\"language-javascript\">function foo() {\n return 'bar';\n}</code></pre>\n\n<p>end</p>";
  986. let actual = this.parser.toHTML(markdown).trim(); // don't normalize whitespace
  987. this.assertEqual(actual.replace(/ /g, '⎵'), expected.replace(/ /g, '⎵'));
  988. }
  989. test_horizontalRule() {
  990. let markdown = "Before\n\n---\n\n- - -\n\n***\n\n* * * * * * *\n\nafter";
  991. let expected = "<p>Before</p> <hr> <hr> <hr> <hr> <p>after</p>";
  992. let actual = this.md(markdown);
  993. this.assertEqual(actual, expected);
  994. }
  995. test_table_unfenced() {
  996. let markdown = "Column A | Column B | Column C\n--- | --- | ---\n1 | 2 | 3\n4 | 5 | 6";
  997. let expected = "<table> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>6</td> </tr> </tbody> </table>";
  998. let actual = this.md(markdown);
  999. this.assertEqual(actual, expected);
  1000. }
  1001. test_table_fenced() {
  1002. let markdown = "| Column A | Column B | Column C |\n| --- | --- | --- |\n| 1 | 2 | 3\n4 | 5 | 6 |";
  1003. let expected = "<table> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>6</td> </tr> </tbody> </table>";
  1004. let actual = this.md(markdown);
  1005. this.assertEqual(actual, expected);
  1006. }
  1007. test_table_alignment() {
  1008. let markdown = 'Column A | Column B | Column C\n' +
  1009. ':--- | :---: | ---:\n' +
  1010. '1 | 2 | 3\n' +
  1011. '4 | 5 | 6';
  1012. let expected = '<table> ' +
  1013. '<thead> ' +
  1014. '<tr> ' +
  1015. '<th style="text-align: left;">Column A</th> ' +
  1016. '<th style="text-align: center;">Column B</th> ' +
  1017. '<th style="text-align: right;">Column C</th> ' +
  1018. '</tr> ' +
  1019. '</thead> ' +
  1020. '<tbody> ' +
  1021. '<tr> ' +
  1022. '<td style="text-align: left;">1</td> ' +
  1023. '<td style="text-align: center;">2</td> ' +
  1024. '<td style="text-align: right;">3</td> ' +
  1025. '</tr> ' +
  1026. '<tr> ' +
  1027. '<td style="text-align: left;">4</td> ' +
  1028. '<td style="text-align: center;">5</td> ' +
  1029. '<td style="text-align: right;">6</td> ' +
  1030. '</tr> ' +
  1031. '</tbody> ' +
  1032. '</table>';
  1033. let actual = this.md(markdown);
  1034. this.assertEqual(actual, expected);
  1035. }
  1036. test_table_holes() {
  1037. let markdown = 'Column A||Column C\n' +
  1038. '---|---|---\n' +
  1039. '|1|2||\n' +
  1040. '|4||6|\n' +
  1041. '||8|9|';
  1042. let expected = '<table> ' +
  1043. '<thead> ' +
  1044. '<tr> ' +
  1045. '<th>Column A</th> ' +
  1046. '<th></th> ' +
  1047. '<th>Column C</th> ' +
  1048. '</tr> ' +
  1049. '</thead> ' +
  1050. '<tbody> ' +
  1051. '<tr> ' +
  1052. '<td>1</td> ' +
  1053. '<td>2</td> ' +
  1054. '<td></td> ' +
  1055. '</tr> ' +
  1056. '<tr> ' +
  1057. '<td>4</td> ' +
  1058. '<td></td> ' +
  1059. '<td>6</td> ' +
  1060. '</tr> ' +
  1061. '<tr> ' +
  1062. '<td></td> ' +
  1063. '<td>8</td> ' +
  1064. '<td>9</td> ' +
  1065. '</tr> ' +
  1066. '</tbody> ' +
  1067. '</table>';
  1068. let actual = this.md(markdown);
  1069. this.assertEqual(actual, expected);
  1070. }
  1071. test_definitionList() {
  1072. let markdown = 'term\n' +
  1073. ': definition\n' +
  1074. 'another' +
  1075. ' term\n' +
  1076. ': def 1\n' +
  1077. ' broken on next line\n' +
  1078. ': def 2';
  1079. let expected = '<dl> ' +
  1080. '<dt>term</dt> ' +
  1081. '<dd>definition</dd> ' +
  1082. '<dt>another term</dt> ' +
  1083. '<dd>def 1 broken on next line</dd> ' +
  1084. '<dd>def 2</dd> ' +
  1085. '</dl>';
  1086. let actual = this.md(markdown);
  1087. this.assertEqual(actual, expected);
  1088. }
  1089. test_footnotes() {
  1090. let markdown = 'Lorem ipsum[^1] dolor[^2] sit[^1] amet\n\n[^1]: A footnote\n[^2]: Another footnote';
  1091. let expected = '<p>Lorem ipsum<sup id="footnoteref_1"><a href="#footnote_1">1</a></sup> ' +
  1092. 'dolor<sup id="footnoteref_2"><a href="#footnote_2">2</a></sup> ' +
  1093. 'sit<sup id="footnoteref_3"><a href="#footnote_1">1</a></sup> amet</p> ' +
  1094. '<div class="footnotes">' +
  1095. '<hr/>' +
  1096. '<ol>' +
  1097. '<li value="1" id="footnote_1">A footnote <a href="#footnoteref_1" class="footnote-backref">↩︎</a> <a href="#footnoteref_3" class="footnote-backref">↩︎</a></li> ' +
  1098. '<li value="2" id="footnote_2">Another footnote <a href="#footnoteref_2" class="footnote-backref">↩︎</a></li> ' +
  1099. '</ol>' +
  1100. '</div>';
  1101. let actual = this.md(markdown);
  1102. this.assertEqual(actual, expected);
  1103. }
  1104. test_abbreviations() {
  1105. let markdown = 'Lorem ipsum HTML dolor HTML sit\n' +
  1106. '\n' +
  1107. '*[HTML]: Hypertext Markup Language';
  1108. let expected = '<p>Lorem ipsum <abbr title="Hypertext Markup Language">HTML</abbr> dolor <abbr title="Hypertext Markup Language">HTML</abbr> sit</p>';
  1109. let actual = this.md(markdown);
  1110. this.assertEqual(actual, expected);
  1111. }
  1112. }
  1113. class CellValueTests extends BaseTest {
  1114. test_fromCellString_blank() {
  1115. var value;
  1116. value = CellValue.fromCellString('');
  1117. this.assertEqual(value.type, CellValue.TYPE_BLANK);
  1118. this.assertEqual(value.formattedValue, '');
  1119. this.assertEqual(value.value, null);
  1120. value = CellValue.fromCellString(' ');
  1121. this.assertEqual(value.type, CellValue.TYPE_BLANK);
  1122. this.assertEqual(value.formattedValue, '');
  1123. this.assertEqual(value.value, null);
  1124. }
  1125. test_fromCellString_number() {
  1126. var value;
  1127. value = CellValue.fromCellString('123');
  1128. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1129. this.assertEqual(value.formattedValue, '123');
  1130. this.assertEqual(value.value, 123);
  1131. this.assertEqual(value.decimals, 0);
  1132. value = CellValue.fromCellString('-0');
  1133. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1134. this.assertEqual(value.formattedValue, '-0');
  1135. this.assertEqual(value.value, 0);
  1136. this.assertEqual(value.decimals, 0);
  1137. value = CellValue.fromCellString('1,234');
  1138. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1139. this.assertEqual(value.formattedValue, '1,234');
  1140. this.assertEqual(value.value, 1234);
  1141. this.assertEqual(value.decimals, 0);
  1142. value = CellValue.fromCellString('-1,234,567.89');
  1143. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1144. this.assertEqual(value.formattedValue, '-1,234,567.89');
  1145. this.assertEqual(value.value, -1234567.89);
  1146. this.assertEqual(value.decimals, 2);
  1147. }
  1148. test_fromCellString_percent() {
  1149. var value;
  1150. value = CellValue.fromCellString('123%');
  1151. this.assertEqual(value.type, CellValue.TYPE_PERCENT);
  1152. this.assertEqual(value.formattedValue, '123%');
  1153. this.assertEqual(value.value, 1.23, 0.0001);
  1154. this.assertEqual(value.decimals, 0);
  1155. value = CellValue.fromCellString('-12.3%');
  1156. this.assertEqual(value.type, CellValue.TYPE_PERCENT);
  1157. this.assertEqual(value.formattedValue, '-12.3%');
  1158. this.assertEqual(value.value, -0.123, 0.0001);
  1159. this.assertEqual(value.decimals, 1);
  1160. }
  1161. test_fromCellString_currency() {
  1162. var value;
  1163. value = CellValue.fromCellString('$123');
  1164. this.assertEqual(value.type, CellValue.TYPE_CURRENCY);
  1165. this.assertEqual(value.formattedValue, '$123');
  1166. this.assertEqual(value.value, 123);
  1167. this.assertEqual(value.decimals, 0);
  1168. value = CellValue.fromCellString('-$12.34');
  1169. this.assertEqual(value.type, CellValue.TYPE_CURRENCY);
  1170. this.assertEqual(value.formattedValue, '-$12.34');
  1171. this.assertEqual(value.value, -12.34, 0.0001);
  1172. this.assertEqual(value.decimals, 2);
  1173. }
  1174. test_fromCellString_boolean() {
  1175. var value;
  1176. value = CellValue.fromCellString('true');
  1177. this.assertEqual(value.type, CellValue.TYPE_BOOLEAN);
  1178. this.assertEqual(value.formattedValue, 'TRUE');
  1179. this.assertEqual(value.value, true);
  1180. value = CellValue.fromCellString('false');
  1181. this.assertEqual(value.type, CellValue.TYPE_BOOLEAN);
  1182. this.assertEqual(value.formattedValue, 'FALSE');
  1183. this.assertEqual(value.value, false);
  1184. }
  1185. test_fromCellString_string() {
  1186. var value;
  1187. value = CellValue.fromCellString('some text');
  1188. this.assertEqual(value.type, CellValue.TYPE_STRING);
  1189. this.assertEqual(value.formattedValue, 'some text');
  1190. this.assertEqual(value.value, 'some text');
  1191. value = CellValue.fromCellString("'0123");
  1192. this.assertEqual(value.type, CellValue.TYPE_STRING);
  1193. this.assertEqual(value.formattedValue, '0123');
  1194. this.assertEqual(value.value, '0123');
  1195. value = CellValue.fromCellString("'=123");
  1196. this.assertEqual(value.type, CellValue.TYPE_STRING);
  1197. this.assertEqual(value.formattedValue, '=123');
  1198. this.assertEqual(value.value, '=123');
  1199. }
  1200. test_fromCellString_formula() {
  1201. var value;
  1202. value = CellValue.fromCellString('=A*B');
  1203. this.assertEqual(value.type, CellValue.TYPE_FORMULA);
  1204. this.assertEqual(value.formattedValue, '=A*B');
  1205. this.assertEqual(value.value, '=A*B');
  1206. value = CellValue.fromCellString('=MAX(A, 3)');
  1207. this.assertEqual(value.type, CellValue.TYPE_FORMULA);
  1208. this.assertEqual(value.formattedValue, '=MAX(A, 3)');
  1209. this.assertEqual(value.value, '=MAX(A, 3)');
  1210. }
  1211. test_fromValue_null() {
  1212. var value;
  1213. value = CellValue.fromValue(null);
  1214. this.assertEqual(value.type, CellValue.TYPE_BLANK);
  1215. }
  1216. test_fromValue_number() {
  1217. var value;
  1218. value = CellValue.fromValue(123);
  1219. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1220. this.assertEqual(value.formattedValue, '123');
  1221. value = CellValue.fromValue(3.141592);
  1222. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1223. this.assertEqual(value.formattedValue, '3.141592');
  1224. value = CellValue.fromValue(123456789);
  1225. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1226. this.assertEqual(value.formattedValue, '123,456,789');
  1227. }
  1228. test_fromValue_boolean() {
  1229. var value;
  1230. value = CellValue.fromValue(true);
  1231. this.assertEqual(value.type, CellValue.TYPE_BOOLEAN);
  1232. this.assertEqual(value.formattedValue, 'TRUE');
  1233. value = CellValue.fromValue(false);
  1234. this.assertEqual(value.type, CellValue.TYPE_BOOLEAN);
  1235. this.assertEqual(value.formattedValue, 'FALSE');
  1236. }
  1237. test_fromValue_string() {
  1238. var value;
  1239. value = CellValue.fromValue('foo');
  1240. this.assertEqual(value.type, CellValue.TYPE_STRING);
  1241. this.assertEqual(value.formattedValue, 'foo');
  1242. value = CellValue.fromValue('123');
  1243. this.assertEqual(value.type, CellValue.TYPE_STRING);
  1244. this.assertEqual(value.formattedValue, '123');
  1245. }
  1246. test_fromValue_formula() {
  1247. var value;
  1248. value = CellValue.fromValue('=A*B');
  1249. this.assertEqual(value.type, CellValue.TYPE_FORMULA);
  1250. this.assertEqual(value.formattedValue, '=A*B');
  1251. }
  1252. test_operation_add() {
  1253. var a, b, result, expected;
  1254. a = CellValue.fromValue(3);
  1255. b = CellValue.fromValue(4);
  1256. result = a.add(b)
  1257. expected = new CellValue('7', 7, CellValue.TYPE_NUMBER, 0);
  1258. this.assertEqual(result, expected);
  1259. a = CellValue.fromCellString('100%');
  1260. b = CellValue.fromCellString('50%');
  1261. result = a.add(b);
  1262. expected = new CellValue('150%', 1.5, CellValue.TYPE_PERCENT, 0);
  1263. this.assertEqual(result, expected);
  1264. a = CellValue.fromCellString('$123');
  1265. b = CellValue.fromCellString('$321');
  1266. result = a.add(b);
  1267. expected = new CellValue('$444.00', 444, CellValue.TYPE_CURRENCY, 2);
  1268. this.assertEqual(result, expected);
  1269. }
  1270. test_operation_subtract() {
  1271. var a, b, result, expected;
  1272. a = CellValue.fromValue(9);
  1273. b = CellValue.fromValue(4);
  1274. result = a.subtract(b)
  1275. expected = new CellValue('5', 5, CellValue.TYPE_NUMBER, 0);
  1276. this.assertEqual(result, expected);
  1277. a = CellValue.fromCellString('100%');
  1278. b = CellValue.fromCellString('50%');
  1279. result = a.subtract(b);
  1280. expected = new CellValue('50%', 0.5, CellValue.TYPE_PERCENT, 0);
  1281. this.assertEqual(result, expected);
  1282. a = CellValue.fromCellString('$321');
  1283. b = CellValue.fromCellString('$123');
  1284. result = a.subtract(b);
  1285. expected = new CellValue('$198.00', 198, CellValue.TYPE_CURRENCY, 2);
  1286. this.assertEqual(result, expected);
  1287. }
  1288. test_operation_multiply() {
  1289. var a, b, result, expected;
  1290. a = CellValue.fromValue(3);
  1291. b = CellValue.fromValue(4);
  1292. result = a.multiply(b)
  1293. expected = new CellValue('12', 12, CellValue.TYPE_NUMBER, 0);
  1294. this.assertEqual(result, expected);
  1295. a = CellValue.fromCellString('150%');
  1296. b = CellValue.fromCellString('50%');
  1297. result = a.multiply(b);
  1298. expected = new CellValue('75%', 0.75, CellValue.TYPE_PERCENT, 0);
  1299. this.assertEqual(result, expected);
  1300. a = CellValue.fromCellString('$321');
  1301. b = CellValue.fromCellString('50%');
  1302. result = a.multiply(b);
  1303. expected = new CellValue('$160.50', 160.50, CellValue.TYPE_CURRENCY, 2);
  1304. this.assertEqual(result, expected);
  1305. }
  1306. test_operation_divide() {
  1307. var a, b, result, expected;
  1308. a = CellValue.fromValue(12);
  1309. b = CellValue.fromValue(4);
  1310. result = a.divide(b)
  1311. expected = new CellValue('3', 3, CellValue.TYPE_NUMBER, 0);
  1312. this.assertEqual(result, expected);
  1313. a = CellValue.fromCellString('150%');
  1314. b = CellValue.fromCellString('50%');
  1315. result = a.divide(b);
  1316. expected = new CellValue('300%', 3.0, CellValue.TYPE_PERCENT, 0);
  1317. this.assertEqual(result, expected);
  1318. a = CellValue.fromCellString('$321');
  1319. b = CellValue.fromCellString('200%');
  1320. result = a.divide(b);
  1321. expected = new CellValue('$160.50', 160.50, CellValue.TYPE_CURRENCY, 2);
  1322. this.assertEqual(result, expected);
  1323. }
  1324. test_operation_modulo() {
  1325. var a, b, result, expected;
  1326. a = CellValue.fromValue(7);
  1327. b = CellValue.fromValue(4);
  1328. result = a.modulo(b)
  1329. expected = new CellValue('3', 3, CellValue.TYPE_NUMBER, 0);
  1330. this.assertEqual(result, expected);
  1331. a = CellValue.fromCellString('175%');
  1332. b = CellValue.fromCellString('50%');
  1333. result = a.modulo(b);
  1334. expected = new CellValue('25%', 0.25, CellValue.TYPE_PERCENT, 0);
  1335. this.assertEqual(result, expected);
  1336. a = CellValue.fromCellString('$327');
  1337. b = CellValue.fromCellString('$20');
  1338. result = a.modulo(b);
  1339. expected = new CellValue('$7.00', 7.00, CellValue.TYPE_CURRENCY, 2);
  1340. this.assertEqual(result, expected);
  1341. }
  1342. test_operation_unaryNot() {
  1343. this.assertEqual(CellValue.fromValue(true).not(), CellValue.fromValue(false));
  1344. this.assertEqual(CellValue.fromValue(false).not(), CellValue.fromValue(true));
  1345. }
  1346. test_operation_comparators() {
  1347. const a = CellValue.fromValue(3);
  1348. const b = CellValue.fromValue(4);
  1349. const t = CellValue.fromValue(true);
  1350. const f = CellValue.fromValue(false);
  1351. this.assertEqual(a.lt(b), t);
  1352. this.assertEqual(a.lte(b), t);
  1353. this.assertEqual(a.gt(b), f);
  1354. this.assertEqual(a.gte(b), f);
  1355. this.assertEqual(a.eq(b), f);
  1356. this.assertEqual(a.neq(b), t);
  1357. this.assertEqual(b.lt(a), f);
  1358. this.assertEqual(b.lte(a), f);
  1359. this.assertEqual(b.gt(a), t);
  1360. this.assertEqual(b.gte(a), t);
  1361. this.assertEqual(b.eq(a), f);
  1362. this.assertEqual(b.neq(a), t);
  1363. this.assertEqual(a.lt(a), f);
  1364. this.assertEqual(a.lte(a), t);
  1365. this.assertEqual(a.gt(a), f);
  1366. this.assertEqual(a.gte(a), t);
  1367. this.assertEqual(a.eq(a), t);
  1368. this.assertEqual(a.neq(a), f);
  1369. }
  1370. test_operation_concatenate() {
  1371. const a = CellValue.fromValue('abc');
  1372. const b = CellValue.fromValue('xyz');
  1373. const result = a.concatenate(b);
  1374. const expected = CellValue.fromValue('abcxyz');
  1375. this.assertEqual(result, expected);
  1376. }
  1377. }
  1378. class CellAddressRangeTests extends BaseTest {
  1379. test_iterator() {
  1380. const grid = new SpreadsheetGrid(3, 4);
  1381. let range = new CellAddressRange(new CellAddress(0, 0), new CellAddress(2, 3));
  1382. var visited = [];
  1383. var sanity = 100;
  1384. for (const address of range.cellsIn(grid)) {
  1385. visited.push(address.name);
  1386. if (sanity-- < 0) break;
  1387. }
  1388. const result = visited.join(',');
  1389. const expected = 'A1,A2,A3,A4,B1,B2,B3,B4,C1,C2,C3,C4';
  1390. this.assertEqual(result, expected);
  1391. }
  1392. test_iterator_column() {
  1393. const grid = new SpreadsheetGrid(3, 4);
  1394. let range = new CellAddressRange(new CellAddress(1, -1), new CellAddress(2, -1));
  1395. var visited = [];
  1396. var sanity = 100;
  1397. for (const address of range.cellsIn(grid)) {
  1398. visited.push(address.name);
  1399. if (sanity-- < 0) break;
  1400. }
  1401. const result = visited.join(',');
  1402. const expected = 'B1,B2,B3,B4,C1,C2,C3,C4';
  1403. this.assertEqual(result, expected);
  1404. }
  1405. test_iterator_beyondBounds() {
  1406. const grid = new SpreadsheetGrid(3, 4);
  1407. let range = new CellAddressRange(new CellAddress(0, 1), new CellAddress(9, 9));
  1408. var visited = [];
  1409. var sanity = 100;
  1410. for (const address of range.cellsIn(grid)) {
  1411. visited.push(address.name);
  1412. if (sanity-- < 0) break;
  1413. }
  1414. const result = visited.join(',');
  1415. const expected = 'A2,A3,A4,B2,B3,B4,C2,C3,C4';
  1416. this.assertEqual(result, expected);
  1417. }
  1418. test_iterator_outOfBounds() {
  1419. const grid = new SpreadsheetGrid(3, 4);
  1420. let range = new CellAddressRange(new CellAddress(5, 0), new CellAddress(5, 9));
  1421. var visited = [];
  1422. var sanity = 100;
  1423. for (const address of range.cellsIn(grid)) {
  1424. visited.push(address.name);
  1425. if (sanity-- < 0) break;
  1426. }
  1427. const result = visited.join(',');
  1428. const expected = '';
  1429. this.assertEqual(result, expected);
  1430. }
  1431. }
  1432. class ExpressionSetTests extends BaseTest {
  1433. test_simpleMath() {
  1434. const grid = new SpreadsheetGrid(1, 1);
  1435. grid.cells[0][0].originalValue = CellValue.fromCellString('=7*3');
  1436. const expressionSet = new CellExpressionSet(grid);
  1437. expressionSet.calculateCells();
  1438. const expected = CellValue.fromValue(21);
  1439. this.assertEqual(grid.cells[0][0].outputValue, expected);
  1440. }
  1441. test_reference() {
  1442. const grid = new SpreadsheetGrid(3, 1);
  1443. grid.cells[0][0].originalValue = CellValue.fromValue(123);
  1444. grid.cells[1][0].originalValue = CellValue.fromValue(3);
  1445. grid.cells[2][0].originalValue = CellValue.fromCellString('=A1*B1');
  1446. const expressionSet = new CellExpressionSet(grid);
  1447. expressionSet.calculateCells();
  1448. const expected = CellValue.fromValue(369);
  1449. this.assertEqual(grid.cells[2][0].outputValue, expected);
  1450. }
  1451. test_infixPriority() {
  1452. const grid = new SpreadsheetGrid(1, 1);
  1453. grid.cells[0][0].originalValue = CellValue.fromCellString('=4*9/3+7-4');
  1454. const expressionSet = new CellExpressionSet(grid);
  1455. expressionSet.calculateCells();
  1456. const expected = CellValue.fromValue(15);
  1457. this.assertEqual(grid.cells[0][0].outputValue, expected);
  1458. }
  1459. test_filledFormula() {
  1460. const grid = new SpreadsheetGrid(3, 3);
  1461. grid.cells[0][0].originalValue = CellValue.fromValue(4);
  1462. grid.cells[1][0].originalValue = CellValue.fromValue(5);
  1463. grid.cells[2][0].originalValue = CellValue.fromCellString('=A1*B1 FILL');
  1464. grid.cells[0][1].originalValue = CellValue.fromValue(6);
  1465. grid.cells[1][1].originalValue = CellValue.fromValue(7);
  1466. grid.cells[0][2].originalValue = CellValue.fromValue(8);
  1467. grid.cells[1][2].originalValue = CellValue.fromValue(9);
  1468. const expressionSet = new CellExpressionSet(grid);
  1469. expressionSet.calculateCells();
  1470. this.assertEqual(grid.cells[2][0].outputValue, CellValue.fromValue(20));
  1471. this.assertEqual(grid.cells[2][1].outputValue, CellValue.fromValue(42));
  1472. this.assertEqual(grid.cells[2][2].outputValue, CellValue.fromValue(72));
  1473. }
  1474. test_dependencies() {
  1475. const grid = new SpreadsheetGrid(2, 4);
  1476. grid.cells[0][0].originalValue = CellValue.fromValue(1);
  1477. grid.cells[1][0].originalValue = CellValue.fromCellString('=A1+B2');
  1478. grid.cells[0][1].originalValue = CellValue.fromValue(2);
  1479. grid.cells[1][1].originalValue = CellValue.fromCellString('=A2+B3');
  1480. grid.cells[0][2].originalValue = CellValue.fromValue(3);
  1481. grid.cells[1][2].originalValue = CellValue.fromCellString('=A3+B4');
  1482. grid.cells[0][3].originalValue = CellValue.fromValue(4);
  1483. grid.cells[1][3].originalValue = CellValue.fromCellString('=A4');
  1484. const expressionSet = new CellExpressionSet(grid);
  1485. expressionSet.calculateCells();
  1486. this.assertEqual(grid.cells[1][0].outputValue, CellValue.fromValue(10));
  1487. this.assertEqual(grid.cells[1][1].outputValue, CellValue.fromValue(9));
  1488. this.assertEqual(grid.cells[1][2].outputValue, CellValue.fromValue(7));
  1489. this.assertEqual(grid.cells[1][3].outputValue, CellValue.fromValue(4));
  1490. }
  1491. _test_simple_formula(formula, expected) {
  1492. const grid = new SpreadsheetGrid(1, 1);
  1493. grid.cells[0][0].originalValue = CellValue.fromCellString(formula);
  1494. const expressionSet = new CellExpressionSet(grid);
  1495. expressionSet.calculateCells();
  1496. const result = grid.cells[0][0].outputValue;
  1497. const exp = (expected instanceof CellValue) ? expected : CellValue.fromValue(expected);
  1498. this.assertEqual(result.type, exp.type);
  1499. this.assertEqual(result.decimals, exp.decimals);
  1500. this.assertEqual(result.formattedValue, exp.formattedValue);
  1501. this.assertEqual(result.value, exp.value);
  1502. }
  1503. test_func_abs() {
  1504. this._test_simple_formula('=ABS(-3)', 3);
  1505. this._test_simple_formula('=ABS(4)', 4);
  1506. }
  1507. test_func_and() {
  1508. this._test_simple_formula('=AND(FALSE, FALSE)', false);
  1509. this._test_simple_formula('=AND(FALSE, TRUE)', false);
  1510. this._test_simple_formula('=AND(TRUE, FALSE)', false);
  1511. this._test_simple_formula('=AND(TRUE, TRUE)', true);
  1512. this._test_simple_formula('=AND(TRUE, TRUE, TRUE, TRUE)', true);
  1513. this._test_simple_formula('=AND(TRUE, TRUE, TRUE, FALSE)', false);
  1514. }
  1515. test_func_average() {
  1516. this._test_simple_formula('=AVERAGE(4, 6, 2, 4)', 4);
  1517. this._test_simple_formula('=AVERAGE(4, 6, 2, "foo", 4)', 4);
  1518. }
  1519. test_func_ceiling() {
  1520. this._test_simple_formula('=CEILING(3.1)', 4);
  1521. this._test_simple_formula('=CEILING(3)', 3);
  1522. this._test_simple_formula('=CEILING(-3.1)', -3);
  1523. }
  1524. test_func_exp() {
  1525. this._test_simple_formula('=EXP(1)', 2.718281828459045);
  1526. }
  1527. test_func_floor() {
  1528. this._test_simple_formula('=FLOOR(3.1)', 3);
  1529. this._test_simple_formula('=FLOOR(3)', 3);
  1530. this._test_simple_formula('=FLOOR(-3.1)', -4);
  1531. }
  1532. test_func_if() {
  1533. this._test_simple_formula('=IF(FALSE, 4, 6)', 6);
  1534. this._test_simple_formula('=IF(TRUE, 4, 6)', 4);
  1535. }
  1536. test_func_ifs() {
  1537. this._test_simple_formula('=IFS(TRUE, 1, FALSE, 2, FALSE, 3, FALSE, 4, 5)', 1);
  1538. this._test_simple_formula('=IFS(FALSE, 1, TRUE, 2, FALSE, 3, FALSE, 4, 5)', 2);
  1539. this._test_simple_formula('=IFS(FALSE, 1, FALSE, 2, TRUE, 3, FALSE, 4, 5)', 3);
  1540. this._test_simple_formula('=IFS(FALSE, 1, FALSE, 2, FALSE, 3, TRUE, 4, 5)', 4);
  1541. this._test_simple_formula('=IFS(FALSE, 1, FALSE, 2, FALSE, 3, FALSE, 4, 5)', 5);
  1542. }
  1543. test_func_ln() {
  1544. this._test_simple_formula('=LN(2.718281828459045)', 1);
  1545. }
  1546. test_func_log() {
  1547. this._test_simple_formula('=LOG(1000, 10)', 3);
  1548. this._test_simple_formula('=LOG(64, 2)', 6);
  1549. }
  1550. test_func_lower() {
  1551. this._test_simple_formula('=LOWER("MiXeD")', 'mixed');
  1552. }
  1553. test_func_max() {
  1554. this._test_simple_formula('=MAX(4, 8, 5, 2)', 8);
  1555. }
  1556. test_func_min() {
  1557. this._test_simple_formula('=MIN(4, 8, 5, 2)', 2);
  1558. }
  1559. test_func_mod() {
  1560. this._test_simple_formula('=MOD(37, 4)', 1);
  1561. }
  1562. test_func_not() {
  1563. this._test_simple_formula('=NOT(TRUE)', false);
  1564. this._test_simple_formula('=NOT(FALSE)', true);
  1565. }
  1566. test_func_or() {
  1567. this._test_simple_formula('=OR(FALSE, FALSE)', false);
  1568. this._test_simple_formula('=OR(FALSE, TRUE)', true);
  1569. this._test_simple_formula('=OR(TRUE, FALSE)', true);
  1570. this._test_simple_formula('=OR(TRUE, TRUE)', true);
  1571. this._test_simple_formula('=OR(FALSE, FALSE, FALSE, TRUE)', true);
  1572. }
  1573. test_func_power() {
  1574. this._test_simple_formula('=POWER(2, 3)', 8);
  1575. }
  1576. test_func_round() {
  1577. this._test_simple_formula('=ROUND(3.1)', 3);
  1578. this._test_simple_formula('=ROUND(3.5)', 4);
  1579. this._test_simple_formula('=ROUND(4)', 4);
  1580. this._test_simple_formula('=ROUND(-3.1)', -3);
  1581. this._test_simple_formula('=ROUND(-3.5)', -3);
  1582. this._test_simple_formula('=ROUND(-3.9)', -4);
  1583. this._test_simple_formula('=ROUND(3.1415926535, 1)', 3.1);
  1584. this._test_simple_formula('=ROUND(3.1415926535, 2)', 3.14);
  1585. this._test_simple_formula('=ROUND(31.415926535, -1)', 30);
  1586. }
  1587. test_func_sqrt() {
  1588. this._test_simple_formula('=SQRT(16)', 4);
  1589. }
  1590. test_func_substitute() {
  1591. this._test_simple_formula('=SUBSTITUTE("cat sat on the mat", "at", "ot")', 'cot sot on the mot');
  1592. this._test_simple_formula('=SUBSTITUTE("cAt saT on the mat", "at", "ot")', 'cot sot on the mot');
  1593. this._test_simple_formula('=SUBSTITUTE("c.*t s.*t on the m.*t", ".*t", "ot")', 'cot sot on the mot');
  1594. }
  1595. test_func_sum() {
  1596. this._test_simple_formula('=SUM(1, 2, 3, 4, 5)', 15);
  1597. }
  1598. test_func_upper() {
  1599. this._test_simple_formula('=UPPER("mIxEd")', 'MIXED');
  1600. }
  1601. test_func_xor() {
  1602. this._test_simple_formula('=XOR(FALSE, FALSE)', false);
  1603. this._test_simple_formula('=XOR(FALSE, TRUE)', true);
  1604. this._test_simple_formula('=XOR(TRUE, FALSE)', true);
  1605. this._test_simple_formula('=XOR(TRUE, TRUE)', false);
  1606. this._test_simple_formula('=XOR(FALSE, FALSE, TRUE)', true);
  1607. this._test_simple_formula('=XOR(TRUE, FALSE, TRUE)', false);
  1608. }
  1609. test_format() {
  1610. this._test_simple_formula('=2.718281828459045 ; number 3', new CellValue('2.718', 2.718281828459045, 'number', 3));
  1611. this._test_simple_formula('=2.718281828459045 ; percent 2', new CellValue('271.83%', 2.718281828459045, 'percent', 2));
  1612. this._test_simple_formula('=2.718281828459045 ; currency 2', new CellValue('$2.72', 2.718281828459045, 'currency', 2));
  1613. }
  1614. }
  1615. class SpreadsheetMarkdownIntegrationTests extends BaseTest {
  1616. parser;
  1617. setUp() {
  1618. this.parser = new Markdown([ ...Markdown.allReaders, new MDSpreadsheetReader() ]);
  1619. }
  1620. md(markdown) {
  1621. return normalizeWhitespace(this.parser.toHTML(markdown));
  1622. }
  1623. test_integration() {
  1624. const markdown = '| A | B | C |\n| --- | --- | --- |\n| 3 | 4 | =A*B |';
  1625. const expected = '<table> <thead> ' +
  1626. '<tr> <th>A</th> <th>B</th> <th>C</th> </tr> ' +
  1627. '</thead> <tbody> <tr> ' +
  1628. '<td class="spreadsheet-type-number" data-numeric-value="3" data-string-value="3">3</td> ' +
  1629. '<td class="spreadsheet-type-number" data-numeric-value="4" data-string-value="4">4</td> ' +
  1630. '<td class="calculated spreadsheet-type-number" data-numeric-value="12" data-string-value="12">12</td> ' +
  1631. '</tr> </tbody> </table>';
  1632. const result = this.md(markdown);
  1633. this.assertEqual(result, expected);
  1634. }
  1635. test_bailOut() {
  1636. // If no formulas found table isn't modified
  1637. const markdown = '| A | B | C |\n| --- | --- | --- |\n| 3 | 4 | A*B |';
  1638. const expected = '<table> <thead> ' +
  1639. '<tr> <th>A</th> <th>B</th> <th>C</th> </tr> ' +
  1640. '</thead> <tbody> <tr> ' +
  1641. '<td>3</td> ' +
  1642. '<td>4</td> ' +
  1643. '<td>A*B</td> ' +
  1644. '</tr> </tbody> </table>';
  1645. const result = this.md(markdown);
  1646. this.assertEqual(result, expected);
  1647. }
  1648. test_observedError1() {
  1649. // Saw "Uncaught Error: columnIndex must be number, got string" from this
  1650. const markdown = '| Unit Price | Qty | Subtotal |\n| ---: | ---: | ---: |\n| $1.23 | 2 | =A*B FILL |\n| $4.99 | 6 | |\n| Total | | =SUM(C:C) |';
  1651. const expected = '<table> <thead> <tr> ' +
  1652. '<th style="text-align: right;">Unit Price</th> ' +
  1653. '<th style="text-align: right;">Qty</th> ' +
  1654. '<th>Subtotal</th> ' +
  1655. '</tr> </thead> <tbody> <tr> ' +
  1656. '<td class="spreadsheet-type-currency" style="text-align: right;" data-numeric-value="1.23" data-string-value="1.23">$1.23</td> ' +
  1657. '<td class="spreadsheet-type-number" style="text-align: right;" data-numeric-value="2" data-string-value="2">2</td> ' +
  1658. '<td class="calculated spreadsheet-type-currency" data-numeric-value="2.46" data-string-value="2.46">$2.46</td> ' +
  1659. '</tr> <tr> ' +
  1660. '<td class="spreadsheet-type-currency" style="text-align: right;" data-numeric-value="4.99" data-string-value="4.99">$4.99</td> ' +
  1661. '<td class="spreadsheet-type-number" style="text-align: right;" data-numeric-value="6" data-string-value="6">6</td> ' +
  1662. '<td class="calculated spreadsheet-type-currency" data-numeric-value="29.94" data-string-value="29.94">$29.94</td> ' +
  1663. '</tr> <tr> ' +
  1664. '<td class="spreadsheet-type-string" style="text-align: right;" data-string-value="Total">Total</td> ' +
  1665. '<td class="spreadsheet-type-blank" style="text-align: right;" data-numeric-value="0" data-string-value=""></td> ' +
  1666. '<td class="calculated spreadsheet-type-currency" data-numeric-value="32.4" data-string-value="32.4">$32.40</td> ' +
  1667. '</tr> </tbody> </table>';
  1668. const result = this.md(markdown);
  1669. this.assertEqual(result, expected);
  1670. }
  1671. }
  1672. </script>
  1673. </head>
  1674. <body>
  1675. <div id="results"></div>
  1676. </body>
  1677. </html>