PHP and Javascript implementations of a simple markdown parser
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

testjs.html 65KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841
  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[^abc] sit[^1] amet\n\n[^1]: A footnote\n[^abc]: Another footnote';
  1091. let expected = '<p>Lorem ipsum<sup class="footnote" id="footnoteref_1"><a href="#footnote_1">1</a></sup> ' +
  1092. 'dolor<sup class="footnote" id="footnoteref_2"><a href="#footnote_2">2</a></sup> ' +
  1093. 'sit<sup class="footnote" id="footnoteref_3"><a href="#footnote_1">1</a></sup> amet</p> ' +
  1094. '<div class="footnotes">' +
  1095. '<ol>' +
  1096. '<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> ' +
  1097. '<li value="2" id="footnote_2">Another footnote <a href="#footnoteref_2" class="footnote-backref">↩︎</a></li> ' +
  1098. '</ol>' +
  1099. '</div>';
  1100. let actual = this.md(markdown);
  1101. this.assertEqual(actual, expected);
  1102. }
  1103. test_abbreviations() {
  1104. let markdown = 'Lorem ipsum HTML dolor HTML sit\n' +
  1105. '\n' +
  1106. '*[HTML]: Hypertext Markup Language';
  1107. let expected = '<p>Lorem ipsum <abbr title="Hypertext Markup Language">HTML</abbr> dolor <abbr title="Hypertext Markup Language">HTML</abbr> sit</p>';
  1108. let actual = this.md(markdown);
  1109. this.assertEqual(actual, expected);
  1110. }
  1111. }
  1112. class CellValueTests extends BaseTest {
  1113. test_fromCellString_blank() {
  1114. var value;
  1115. value = CellValue.fromCellString('');
  1116. this.assertEqual(value.type, CellValue.TYPE_BLANK);
  1117. this.assertEqual(value.formattedValue, '');
  1118. this.assertEqual(value.value, null);
  1119. value = CellValue.fromCellString(' ');
  1120. this.assertEqual(value.type, CellValue.TYPE_BLANK);
  1121. this.assertEqual(value.formattedValue, '');
  1122. this.assertEqual(value.value, null);
  1123. }
  1124. test_fromCellString_number() {
  1125. var value;
  1126. value = CellValue.fromCellString('123');
  1127. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1128. this.assertEqual(value.formattedValue, '123');
  1129. this.assertEqual(value.value, 123);
  1130. this.assertEqual(value.decimals, 0);
  1131. value = CellValue.fromCellString('-0');
  1132. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1133. this.assertEqual(value.formattedValue, '-0');
  1134. this.assertEqual(value.value, 0);
  1135. this.assertEqual(value.decimals, 0);
  1136. value = CellValue.fromCellString('1,234');
  1137. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1138. this.assertEqual(value.formattedValue, '1,234');
  1139. this.assertEqual(value.value, 1234);
  1140. this.assertEqual(value.decimals, 0);
  1141. value = CellValue.fromCellString('-1,234,567.89');
  1142. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1143. this.assertEqual(value.formattedValue, '-1,234,567.89');
  1144. this.assertEqual(value.value, -1234567.89);
  1145. this.assertEqual(value.decimals, 2);
  1146. }
  1147. test_fromCellString_percent() {
  1148. var value;
  1149. value = CellValue.fromCellString('123%');
  1150. this.assertEqual(value.type, CellValue.TYPE_PERCENT);
  1151. this.assertEqual(value.formattedValue, '123%');
  1152. this.assertEqual(value.value, 1.23, 0.0001);
  1153. this.assertEqual(value.decimals, 0);
  1154. value = CellValue.fromCellString('-12.3%');
  1155. this.assertEqual(value.type, CellValue.TYPE_PERCENT);
  1156. this.assertEqual(value.formattedValue, '-12.3%');
  1157. this.assertEqual(value.value, -0.123, 0.0001);
  1158. this.assertEqual(value.decimals, 1);
  1159. }
  1160. test_fromCellString_currency() {
  1161. var value;
  1162. value = CellValue.fromCellString('$123');
  1163. this.assertEqual(value.type, CellValue.TYPE_CURRENCY);
  1164. this.assertEqual(value.formattedValue, '$123');
  1165. this.assertEqual(value.value, 123);
  1166. this.assertEqual(value.decimals, 0);
  1167. value = CellValue.fromCellString('-$12.34');
  1168. this.assertEqual(value.type, CellValue.TYPE_CURRENCY);
  1169. this.assertEqual(value.formattedValue, '-$12.34');
  1170. this.assertEqual(value.value, -12.34, 0.0001);
  1171. this.assertEqual(value.decimals, 2);
  1172. }
  1173. test_fromCellString_boolean() {
  1174. var value;
  1175. value = CellValue.fromCellString('true');
  1176. this.assertEqual(value.type, CellValue.TYPE_BOOLEAN);
  1177. this.assertEqual(value.formattedValue, 'TRUE');
  1178. this.assertEqual(value.value, true);
  1179. value = CellValue.fromCellString('false');
  1180. this.assertEqual(value.type, CellValue.TYPE_BOOLEAN);
  1181. this.assertEqual(value.formattedValue, 'FALSE');
  1182. this.assertEqual(value.value, false);
  1183. }
  1184. test_fromCellString_string() {
  1185. var value;
  1186. value = CellValue.fromCellString('some text');
  1187. this.assertEqual(value.type, CellValue.TYPE_STRING);
  1188. this.assertEqual(value.formattedValue, 'some text');
  1189. this.assertEqual(value.value, 'some text');
  1190. value = CellValue.fromCellString("'0123");
  1191. this.assertEqual(value.type, CellValue.TYPE_STRING);
  1192. this.assertEqual(value.formattedValue, '0123');
  1193. this.assertEqual(value.value, '0123');
  1194. value = CellValue.fromCellString("'=123");
  1195. this.assertEqual(value.type, CellValue.TYPE_STRING);
  1196. this.assertEqual(value.formattedValue, '=123');
  1197. this.assertEqual(value.value, '=123');
  1198. }
  1199. test_fromCellString_formula() {
  1200. var value;
  1201. value = CellValue.fromCellString('=A*B');
  1202. this.assertEqual(value.type, CellValue.TYPE_FORMULA);
  1203. this.assertEqual(value.formattedValue, '=A*B');
  1204. this.assertEqual(value.value, '=A*B');
  1205. value = CellValue.fromCellString('=MAX(A, 3)');
  1206. this.assertEqual(value.type, CellValue.TYPE_FORMULA);
  1207. this.assertEqual(value.formattedValue, '=MAX(A, 3)');
  1208. this.assertEqual(value.value, '=MAX(A, 3)');
  1209. }
  1210. test_fromValue_null() {
  1211. var value;
  1212. value = CellValue.fromValue(null);
  1213. this.assertEqual(value.type, CellValue.TYPE_BLANK);
  1214. }
  1215. test_fromValue_number() {
  1216. var value;
  1217. value = CellValue.fromValue(123);
  1218. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1219. this.assertEqual(value.formattedValue, '123');
  1220. value = CellValue.fromValue(3.141592);
  1221. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1222. this.assertEqual(value.formattedValue, '3.141592');
  1223. value = CellValue.fromValue(123456789);
  1224. this.assertEqual(value.type, CellValue.TYPE_NUMBER);
  1225. this.assertEqual(value.formattedValue, '123,456,789');
  1226. }
  1227. test_fromValue_boolean() {
  1228. var value;
  1229. value = CellValue.fromValue(true);
  1230. this.assertEqual(value.type, CellValue.TYPE_BOOLEAN);
  1231. this.assertEqual(value.formattedValue, 'TRUE');
  1232. value = CellValue.fromValue(false);
  1233. this.assertEqual(value.type, CellValue.TYPE_BOOLEAN);
  1234. this.assertEqual(value.formattedValue, 'FALSE');
  1235. }
  1236. test_fromValue_string() {
  1237. var value;
  1238. value = CellValue.fromValue('foo');
  1239. this.assertEqual(value.type, CellValue.TYPE_STRING);
  1240. this.assertEqual(value.formattedValue, 'foo');
  1241. value = CellValue.fromValue('123');
  1242. this.assertEqual(value.type, CellValue.TYPE_STRING);
  1243. this.assertEqual(value.formattedValue, '123');
  1244. }
  1245. test_fromValue_formula() {
  1246. var value;
  1247. value = CellValue.fromValue('=A*B');
  1248. this.assertEqual(value.type, CellValue.TYPE_FORMULA);
  1249. this.assertEqual(value.formattedValue, '=A*B');
  1250. }
  1251. test_operation_add() {
  1252. var a, b, result, expected;
  1253. a = CellValue.fromValue(3);
  1254. b = CellValue.fromValue(4);
  1255. result = a.add(b)
  1256. expected = new CellValue('7', 7, CellValue.TYPE_NUMBER, 0);
  1257. this.assertEqual(result, expected);
  1258. a = CellValue.fromCellString('100%');
  1259. b = CellValue.fromCellString('50%');
  1260. result = a.add(b);
  1261. expected = new CellValue('150%', 1.5, CellValue.TYPE_PERCENT, 0);
  1262. this.assertEqual(result, expected);
  1263. a = CellValue.fromCellString('$123');
  1264. b = CellValue.fromCellString('$321');
  1265. result = a.add(b);
  1266. expected = new CellValue('$444.00', 444, CellValue.TYPE_CURRENCY, 2);
  1267. this.assertEqual(result, expected);
  1268. }
  1269. test_operation_subtract() {
  1270. var a, b, result, expected;
  1271. a = CellValue.fromValue(9);
  1272. b = CellValue.fromValue(4);
  1273. result = a.subtract(b)
  1274. expected = new CellValue('5', 5, CellValue.TYPE_NUMBER, 0);
  1275. this.assertEqual(result, expected);
  1276. a = CellValue.fromCellString('100%');
  1277. b = CellValue.fromCellString('50%');
  1278. result = a.subtract(b);
  1279. expected = new CellValue('50%', 0.5, CellValue.TYPE_PERCENT, 0);
  1280. this.assertEqual(result, expected);
  1281. a = CellValue.fromCellString('$321');
  1282. b = CellValue.fromCellString('$123');
  1283. result = a.subtract(b);
  1284. expected = new CellValue('$198.00', 198, CellValue.TYPE_CURRENCY, 2);
  1285. this.assertEqual(result, expected);
  1286. }
  1287. test_operation_multiply() {
  1288. var a, b, result, expected;
  1289. a = CellValue.fromValue(3);
  1290. b = CellValue.fromValue(4);
  1291. result = a.multiply(b)
  1292. expected = new CellValue('12', 12, CellValue.TYPE_NUMBER, 0);
  1293. this.assertEqual(result, expected);
  1294. a = CellValue.fromCellString('150%');
  1295. b = CellValue.fromCellString('50%');
  1296. result = a.multiply(b);
  1297. expected = new CellValue('75%', 0.75, CellValue.TYPE_PERCENT, 0);
  1298. this.assertEqual(result, expected);
  1299. a = CellValue.fromCellString('$321');
  1300. b = CellValue.fromCellString('50%');
  1301. result = a.multiply(b);
  1302. expected = new CellValue('$160.50', 160.50, CellValue.TYPE_CURRENCY, 2);
  1303. this.assertEqual(result, expected);
  1304. }
  1305. test_operation_divide() {
  1306. var a, b, result, expected;
  1307. a = CellValue.fromValue(12);
  1308. b = CellValue.fromValue(4);
  1309. result = a.divide(b)
  1310. expected = new CellValue('3', 3, CellValue.TYPE_NUMBER, 0);
  1311. this.assertEqual(result, expected);
  1312. a = CellValue.fromCellString('150%');
  1313. b = CellValue.fromCellString('50%');
  1314. result = a.divide(b);
  1315. expected = new CellValue('300%', 3.0, CellValue.TYPE_PERCENT, 0);
  1316. this.assertEqual(result, expected);
  1317. a = CellValue.fromCellString('$321');
  1318. b = CellValue.fromCellString('200%');
  1319. result = a.divide(b);
  1320. expected = new CellValue('$160.50', 160.50, CellValue.TYPE_CURRENCY, 2);
  1321. this.assertEqual(result, expected);
  1322. }
  1323. test_operation_modulo() {
  1324. var a, b, result, expected;
  1325. a = CellValue.fromValue(7);
  1326. b = CellValue.fromValue(4);
  1327. result = a.modulo(b)
  1328. expected = new CellValue('3', 3, CellValue.TYPE_NUMBER, 0);
  1329. this.assertEqual(result, expected);
  1330. a = CellValue.fromCellString('175%');
  1331. b = CellValue.fromCellString('50%');
  1332. result = a.modulo(b);
  1333. expected = new CellValue('25%', 0.25, CellValue.TYPE_PERCENT, 0);
  1334. this.assertEqual(result, expected);
  1335. a = CellValue.fromCellString('$327');
  1336. b = CellValue.fromCellString('$20');
  1337. result = a.modulo(b);
  1338. expected = new CellValue('$7.00', 7.00, CellValue.TYPE_CURRENCY, 2);
  1339. this.assertEqual(result, expected);
  1340. }
  1341. test_operation_unaryNot() {
  1342. this.assertEqual(CellValue.fromValue(true).not(), CellValue.fromValue(false));
  1343. this.assertEqual(CellValue.fromValue(false).not(), CellValue.fromValue(true));
  1344. }
  1345. test_operation_comparators() {
  1346. const a = CellValue.fromValue(3);
  1347. const b = CellValue.fromValue(4);
  1348. const t = CellValue.fromValue(true);
  1349. const f = CellValue.fromValue(false);
  1350. this.assertEqual(a.lt(b), t);
  1351. this.assertEqual(a.lte(b), t);
  1352. this.assertEqual(a.gt(b), f);
  1353. this.assertEqual(a.gte(b), f);
  1354. this.assertEqual(a.eq(b), f);
  1355. this.assertEqual(a.neq(b), t);
  1356. this.assertEqual(b.lt(a), f);
  1357. this.assertEqual(b.lte(a), f);
  1358. this.assertEqual(b.gt(a), t);
  1359. this.assertEqual(b.gte(a), t);
  1360. this.assertEqual(b.eq(a), f);
  1361. this.assertEqual(b.neq(a), t);
  1362. this.assertEqual(a.lt(a), f);
  1363. this.assertEqual(a.lte(a), t);
  1364. this.assertEqual(a.gt(a), f);
  1365. this.assertEqual(a.gte(a), t);
  1366. this.assertEqual(a.eq(a), t);
  1367. this.assertEqual(a.neq(a), f);
  1368. }
  1369. test_operation_concatenate() {
  1370. const a = CellValue.fromValue('abc');
  1371. const b = CellValue.fromValue('xyz');
  1372. const result = a.concatenate(b);
  1373. const expected = CellValue.fromValue('abcxyz');
  1374. this.assertEqual(result, expected);
  1375. }
  1376. }
  1377. class CellAddressRangeTests extends BaseTest {
  1378. test_iterator() {
  1379. const grid = new SpreadsheetGrid(3, 4);
  1380. let range = new CellAddressRange(new CellAddress(0, 0), new CellAddress(2, 3));
  1381. var visited = [];
  1382. var sanity = 100;
  1383. for (const address of range.cellsIn(grid)) {
  1384. visited.push(address.name);
  1385. if (sanity-- < 0) break;
  1386. }
  1387. const result = visited.join(',');
  1388. const expected = 'A1,A2,A3,A4,B1,B2,B3,B4,C1,C2,C3,C4';
  1389. this.assertEqual(result, expected);
  1390. }
  1391. test_iterator_column() {
  1392. const grid = new SpreadsheetGrid(3, 4);
  1393. let range = new CellAddressRange(new CellAddress(1, -1), new CellAddress(2, -1));
  1394. var visited = [];
  1395. var sanity = 100;
  1396. for (const address of range.cellsIn(grid)) {
  1397. visited.push(address.name);
  1398. if (sanity-- < 0) break;
  1399. }
  1400. const result = visited.join(',');
  1401. const expected = 'B1,B2,B3,B4,C1,C2,C3,C4';
  1402. this.assertEqual(result, expected);
  1403. }
  1404. test_iterator_beyondBounds() {
  1405. const grid = new SpreadsheetGrid(3, 4);
  1406. let range = new CellAddressRange(new CellAddress(0, 1), new CellAddress(9, 9));
  1407. var visited = [];
  1408. var sanity = 100;
  1409. for (const address of range.cellsIn(grid)) {
  1410. visited.push(address.name);
  1411. if (sanity-- < 0) break;
  1412. }
  1413. const result = visited.join(',');
  1414. const expected = 'A2,A3,A4,B2,B3,B4,C2,C3,C4';
  1415. this.assertEqual(result, expected);
  1416. }
  1417. test_iterator_outOfBounds() {
  1418. const grid = new SpreadsheetGrid(3, 4);
  1419. let range = new CellAddressRange(new CellAddress(5, 0), new CellAddress(5, 9));
  1420. var visited = [];
  1421. var sanity = 100;
  1422. for (const address of range.cellsIn(grid)) {
  1423. visited.push(address.name);
  1424. if (sanity-- < 0) break;
  1425. }
  1426. const result = visited.join(',');
  1427. const expected = '';
  1428. this.assertEqual(result, expected);
  1429. }
  1430. }
  1431. class ExpressionSetTests extends BaseTest {
  1432. test_simpleMath() {
  1433. const grid = new SpreadsheetGrid(1, 1);
  1434. grid.cells[0][0].originalValue = CellValue.fromCellString('=7*3');
  1435. const expressionSet = new CellExpressionSet(grid);
  1436. expressionSet.calculateCells();
  1437. const expected = CellValue.fromValue(21);
  1438. this.assertEqual(grid.cells[0][0].outputValue, expected);
  1439. }
  1440. test_reference() {
  1441. const grid = new SpreadsheetGrid(3, 1);
  1442. grid.cells[0][0].originalValue = CellValue.fromValue(123);
  1443. grid.cells[1][0].originalValue = CellValue.fromValue(3);
  1444. grid.cells[2][0].originalValue = CellValue.fromCellString('=A1*B1');
  1445. const expressionSet = new CellExpressionSet(grid);
  1446. expressionSet.calculateCells();
  1447. const expected = CellValue.fromValue(369);
  1448. this.assertEqual(grid.cells[2][0].outputValue, expected);
  1449. }
  1450. test_infixPriority() {
  1451. const grid = new SpreadsheetGrid(1, 1);
  1452. grid.cells[0][0].originalValue = CellValue.fromCellString('=4*9/3+7-4');
  1453. const expressionSet = new CellExpressionSet(grid);
  1454. expressionSet.calculateCells();
  1455. const expected = CellValue.fromValue(15);
  1456. this.assertEqual(grid.cells[0][0].outputValue, expected);
  1457. }
  1458. test_filledFormula() {
  1459. const grid = new SpreadsheetGrid(3, 3);
  1460. grid.cells[0][0].originalValue = CellValue.fromValue(4);
  1461. grid.cells[1][0].originalValue = CellValue.fromValue(5);
  1462. grid.cells[2][0].originalValue = CellValue.fromCellString('=A1*B1 FILL');
  1463. grid.cells[0][1].originalValue = CellValue.fromValue(6);
  1464. grid.cells[1][1].originalValue = CellValue.fromValue(7);
  1465. grid.cells[0][2].originalValue = CellValue.fromValue(8);
  1466. grid.cells[1][2].originalValue = CellValue.fromValue(9);
  1467. const expressionSet = new CellExpressionSet(grid);
  1468. expressionSet.calculateCells();
  1469. this.assertEqual(grid.cells[2][0].outputValue, CellValue.fromValue(20));
  1470. this.assertEqual(grid.cells[2][1].outputValue, CellValue.fromValue(42));
  1471. this.assertEqual(grid.cells[2][2].outputValue, CellValue.fromValue(72));
  1472. }
  1473. test_dependencies() {
  1474. const grid = new SpreadsheetGrid(2, 4);
  1475. grid.cells[0][0].originalValue = CellValue.fromValue(1);
  1476. grid.cells[1][0].originalValue = CellValue.fromCellString('=A1+B2');
  1477. grid.cells[0][1].originalValue = CellValue.fromValue(2);
  1478. grid.cells[1][1].originalValue = CellValue.fromCellString('=A2+B3');
  1479. grid.cells[0][2].originalValue = CellValue.fromValue(3);
  1480. grid.cells[1][2].originalValue = CellValue.fromCellString('=A3+B4');
  1481. grid.cells[0][3].originalValue = CellValue.fromValue(4);
  1482. grid.cells[1][3].originalValue = CellValue.fromCellString('=A4');
  1483. const expressionSet = new CellExpressionSet(grid);
  1484. expressionSet.calculateCells();
  1485. this.assertEqual(grid.cells[1][0].outputValue, CellValue.fromValue(10));
  1486. this.assertEqual(grid.cells[1][1].outputValue, CellValue.fromValue(9));
  1487. this.assertEqual(grid.cells[1][2].outputValue, CellValue.fromValue(7));
  1488. this.assertEqual(grid.cells[1][3].outputValue, CellValue.fromValue(4));
  1489. }
  1490. _test_simple_formula(formula, expected) {
  1491. const grid = new SpreadsheetGrid(1, 1);
  1492. grid.cells[0][0].originalValue = CellValue.fromCellString(formula);
  1493. const expressionSet = new CellExpressionSet(grid);
  1494. expressionSet.calculateCells();
  1495. const result = grid.cells[0][0].outputValue;
  1496. const exp = (expected instanceof CellValue) ? expected : CellValue.fromValue(expected);
  1497. this.assertEqual(result.type, exp.type);
  1498. this.assertEqual(result.decimals, exp.decimals);
  1499. this.assertEqual(result.formattedValue, exp.formattedValue);
  1500. this.assertEqual(result.value, exp.value);
  1501. }
  1502. test_func_abs() {
  1503. this._test_simple_formula('=ABS(-3)', 3);
  1504. this._test_simple_formula('=ABS(4)', 4);
  1505. }
  1506. test_func_and() {
  1507. this._test_simple_formula('=AND(FALSE, FALSE)', false);
  1508. this._test_simple_formula('=AND(FALSE, TRUE)', false);
  1509. this._test_simple_formula('=AND(TRUE, FALSE)', false);
  1510. this._test_simple_formula('=AND(TRUE, TRUE)', true);
  1511. this._test_simple_formula('=AND(TRUE, TRUE, TRUE, TRUE)', true);
  1512. this._test_simple_formula('=AND(TRUE, TRUE, TRUE, FALSE)', false);
  1513. }
  1514. test_func_average() {
  1515. this._test_simple_formula('=AVERAGE(4, 6, 2, 4)', 4);
  1516. this._test_simple_formula('=AVERAGE(4, 6, 2, "foo", 4)', 4);
  1517. }
  1518. test_func_ceiling() {
  1519. this._test_simple_formula('=CEILING(3.1)', 4);
  1520. this._test_simple_formula('=CEILING(3)', 3);
  1521. this._test_simple_formula('=CEILING(-3.1)', -3);
  1522. }
  1523. test_func_exp() {
  1524. this._test_simple_formula('=EXP(1)', 2.718281828459045);
  1525. }
  1526. test_func_floor() {
  1527. this._test_simple_formula('=FLOOR(3.1)', 3);
  1528. this._test_simple_formula('=FLOOR(3)', 3);
  1529. this._test_simple_formula('=FLOOR(-3.1)', -4);
  1530. }
  1531. test_func_if() {
  1532. this._test_simple_formula('=IF(FALSE, 4, 6)', 6);
  1533. this._test_simple_formula('=IF(TRUE, 4, 6)', 4);
  1534. }
  1535. test_func_ifs() {
  1536. this._test_simple_formula('=IFS(TRUE, 1, FALSE, 2, FALSE, 3, FALSE, 4, 5)', 1);
  1537. this._test_simple_formula('=IFS(FALSE, 1, TRUE, 2, FALSE, 3, FALSE, 4, 5)', 2);
  1538. this._test_simple_formula('=IFS(FALSE, 1, FALSE, 2, TRUE, 3, FALSE, 4, 5)', 3);
  1539. this._test_simple_formula('=IFS(FALSE, 1, FALSE, 2, FALSE, 3, TRUE, 4, 5)', 4);
  1540. this._test_simple_formula('=IFS(FALSE, 1, FALSE, 2, FALSE, 3, FALSE, 4, 5)', 5);
  1541. }
  1542. test_func_ln() {
  1543. this._test_simple_formula('=LN(2.718281828459045)', 1);
  1544. }
  1545. test_func_log() {
  1546. this._test_simple_formula('=LOG(1000, 10)', 3);
  1547. this._test_simple_formula('=LOG(64, 2)', 6);
  1548. }
  1549. test_func_lower() {
  1550. this._test_simple_formula('=LOWER("MiXeD")', 'mixed');
  1551. }
  1552. test_func_max() {
  1553. this._test_simple_formula('=MAX(4, 8, 5, 2)', 8);
  1554. }
  1555. test_func_min() {
  1556. this._test_simple_formula('=MIN(4, 8, 5, 2)', 2);
  1557. }
  1558. test_func_mod() {
  1559. this._test_simple_formula('=MOD(37, 4)', 1);
  1560. }
  1561. test_func_not() {
  1562. this._test_simple_formula('=NOT(TRUE)', false);
  1563. this._test_simple_formula('=NOT(FALSE)', true);
  1564. }
  1565. test_func_or() {
  1566. this._test_simple_formula('=OR(FALSE, FALSE)', false);
  1567. this._test_simple_formula('=OR(FALSE, TRUE)', true);
  1568. this._test_simple_formula('=OR(TRUE, FALSE)', true);
  1569. this._test_simple_formula('=OR(TRUE, TRUE)', true);
  1570. this._test_simple_formula('=OR(FALSE, FALSE, FALSE, TRUE)', true);
  1571. }
  1572. test_func_power() {
  1573. this._test_simple_formula('=POWER(2, 3)', 8);
  1574. }
  1575. test_func_round() {
  1576. this._test_simple_formula('=ROUND(3.1)', 3);
  1577. this._test_simple_formula('=ROUND(3.5)', 4);
  1578. this._test_simple_formula('=ROUND(4)', 4);
  1579. this._test_simple_formula('=ROUND(-3.1)', -3);
  1580. this._test_simple_formula('=ROUND(-3.5)', -3);
  1581. this._test_simple_formula('=ROUND(-3.9)', -4);
  1582. this._test_simple_formula('=ROUND(3.1415926535, 1)', 3.1);
  1583. this._test_simple_formula('=ROUND(3.1415926535, 2)', 3.14);
  1584. this._test_simple_formula('=ROUND(31.415926535, -1)', 30);
  1585. }
  1586. test_func_sqrt() {
  1587. this._test_simple_formula('=SQRT(16)', 4);
  1588. }
  1589. test_func_substitute() {
  1590. this._test_simple_formula('=SUBSTITUTE("cat sat on the mat", "at", "ot")', 'cot sot on the mot');
  1591. this._test_simple_formula('=SUBSTITUTE("cAt saT on the mat", "at", "ot")', 'cot sot on the mot');
  1592. this._test_simple_formula('=SUBSTITUTE("c.*t s.*t on the m.*t", ".*t", "ot")', 'cot sot on the mot');
  1593. }
  1594. test_func_sum() {
  1595. this._test_simple_formula('=SUM(1, 2, 3, 4, 5)', 15);
  1596. }
  1597. test_func_upper() {
  1598. this._test_simple_formula('=UPPER("mIxEd")', 'MIXED');
  1599. }
  1600. test_func_xor() {
  1601. this._test_simple_formula('=XOR(FALSE, FALSE)', false);
  1602. this._test_simple_formula('=XOR(FALSE, TRUE)', true);
  1603. this._test_simple_formula('=XOR(TRUE, FALSE)', true);
  1604. this._test_simple_formula('=XOR(TRUE, TRUE)', false);
  1605. this._test_simple_formula('=XOR(FALSE, FALSE, TRUE)', true);
  1606. this._test_simple_formula('=XOR(TRUE, FALSE, TRUE)', false);
  1607. }
  1608. test_format() {
  1609. this._test_simple_formula('=2.718281828459045 ; number 3', new CellValue('2.718', 2.718281828459045, 'number', 3));
  1610. this._test_simple_formula('=2.718281828459045 ; percent 2', new CellValue('271.83%', 2.718281828459045, 'percent', 2));
  1611. this._test_simple_formula('=2.718281828459045 ; currency 2', new CellValue('$2.72', 2.718281828459045, 'currency', 2));
  1612. }
  1613. }
  1614. class SpreadsheetMarkdownIntegrationTests extends BaseTest {
  1615. parser;
  1616. setUp() {
  1617. this.parser = new Markdown([ ...Markdown.allReaders, new MDSpreadsheetReader() ]);
  1618. }
  1619. md(markdown) {
  1620. return normalizeWhitespace(this.parser.toHTML(markdown));
  1621. }
  1622. test_integration() {
  1623. const markdown = '| A | B | C |\n| --- | --- | --- |\n| 3 | 4 | =A*B |';
  1624. const expected = '<table> <thead> ' +
  1625. '<tr> <th>A</th> <th>B</th> <th>C</th> </tr> ' +
  1626. '</thead> <tbody> <tr> ' +
  1627. '<td class="spreadsheet-type-number" data-numeric-value="3" data-string-value="3">3</td> ' +
  1628. '<td class="spreadsheet-type-number" data-numeric-value="4" data-string-value="4">4</td> ' +
  1629. '<td class="calculated spreadsheet-type-number" data-numeric-value="12" data-string-value="12">12</td> ' +
  1630. '</tr> </tbody> </table>';
  1631. const result = this.md(markdown);
  1632. this.assertEqual(result, expected);
  1633. }
  1634. test_bailOut() {
  1635. // If no formulas found table isn't modified
  1636. const markdown = '| A | B | C |\n| --- | --- | --- |\n| 3 | 4 | A*B |';
  1637. const expected = '<table> <thead> ' +
  1638. '<tr> <th>A</th> <th>B</th> <th>C</th> </tr> ' +
  1639. '</thead> <tbody> <tr> ' +
  1640. '<td>3</td> ' +
  1641. '<td>4</td> ' +
  1642. '<td>A*B</td> ' +
  1643. '</tr> </tbody> </table>';
  1644. const result = this.md(markdown);
  1645. this.assertEqual(result, expected);
  1646. }
  1647. test_observedError1() {
  1648. // Saw "Uncaught Error: columnIndex must be number, got string" from this
  1649. const markdown = '| Unit Price | Qty | Subtotal |\n| ---: | ---: | ---: |\n| $1.23 | 2 | =A*B FILL |\n| $4.99 | 6 | |\n| Total | | =SUM(C:C) |';
  1650. const expected = '<table> <thead> <tr> ' +
  1651. '<th style="text-align: right;">Unit Price</th> ' +
  1652. '<th style="text-align: right;">Qty</th> ' +
  1653. '<th>Subtotal</th> ' +
  1654. '</tr> </thead> <tbody> <tr> ' +
  1655. '<td class="spreadsheet-type-currency" style="text-align: right;" data-numeric-value="1.23" data-string-value="1.23">$1.23</td> ' +
  1656. '<td class="spreadsheet-type-number" style="text-align: right;" data-numeric-value="2" data-string-value="2">2</td> ' +
  1657. '<td class="calculated spreadsheet-type-currency" data-numeric-value="2.46" data-string-value="2.46">$2.46</td> ' +
  1658. '</tr> <tr> ' +
  1659. '<td class="spreadsheet-type-currency" style="text-align: right;" data-numeric-value="4.99" data-string-value="4.99">$4.99</td> ' +
  1660. '<td class="spreadsheet-type-number" style="text-align: right;" data-numeric-value="6" data-string-value="6">6</td> ' +
  1661. '<td class="calculated spreadsheet-type-currency" data-numeric-value="29.94" data-string-value="29.94">$29.94</td> ' +
  1662. '</tr> <tr> ' +
  1663. '<td class="spreadsheet-type-string" style="text-align: right;" data-string-value="Total">Total</td> ' +
  1664. '<td class="spreadsheet-type-blank" style="text-align: right;" data-numeric-value="0" data-string-value=""></td> ' +
  1665. '<td class="calculated spreadsheet-type-currency" data-numeric-value="32.4" data-string-value="32.4">$32.40</td> ' +
  1666. '</tr> </tbody> </table>';
  1667. const result = this.md(markdown);
  1668. this.assertEqual(result, expected);
  1669. }
  1670. }
  1671. </script>
  1672. </head>
  1673. <body>
  1674. <div id="results"></div>
  1675. </body>
  1676. </html>