NH_widget

Widgets for user interactions.

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/478676/1337642/NH_widget.js

  1. // ==UserScript==
  2. // ==UserLibrary==
  3. // @name NH_widget
  4. // @description Widgets for user interactions.
  5. // @version 45
  6. // @license GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0-standalone.html
  7. // @homepageURL https://github.com/nexushoratio/userscripts
  8. // @supportURL https://github.com/nexushoratio/userscripts/issues
  9. // @match https://www.example.com/*
  10. // ==/UserLibrary==
  11. // ==/UserScript==
  12.  
  13. window.NexusHoratio ??= {};
  14.  
  15. window.NexusHoratio.widget = (function widget() {
  16. 'use strict';
  17.  
  18. /** @type {number} - Bumped per release. */
  19. const version = 45;
  20.  
  21. const NH = window.NexusHoratio.base.ensure([
  22. {name: 'xunit', minVersion: 39},
  23. {name: 'base', minVersion: 52},
  24. ]);
  25.  
  26. /** Library specific exception. */
  27. class Exception extends NH.base.Exception {}
  28.  
  29. /** Thrown on verification errors. */
  30. class VerificationError extends Exception {}
  31.  
  32. /** Useful for matching in tests. */
  33. const HEX = '[0-9a-f]';
  34. const GUID = `${HEX}{8}-(${HEX}{4}-){3}${HEX}{12}`;
  35.  
  36. /** @typedef {(string|HTMLElement|Widget)} Content */
  37.  
  38. /**
  39. * Base class for rendering widgets.
  40. *
  41. * Subclasses should NOT override methods here, except for constructor().
  42. * Instead they should register listeners for appropriate events.
  43. *
  44. * Generally, methods will fire two event verbs. The first, in present
  45. * tense, will instruct what should happen (build, destroy, etc). The
  46. * second, in past tense, will describe what should have happened (built,
  47. * destroyed, etc). Typically, subclasses will act upon the present tense,
  48. * and users of the class may act upon the past tense.
  49. *
  50. * Methods should generally be able to be chained.
  51. *
  52. * If a variable holding a widget is set to a new value, the previous widget
  53. * should be explicitly destroyed.
  54. *
  55. * When a Widget is instantiated, it should only create a container of the
  56. * requested type (done in this base class). And install any widget styles
  57. * it needs in order to function. The container property can then be placed
  58. * into the DOM.
  59. *
  60. * If a Widget needs specific CSS to function, that CSS should be shared
  61. * across all instances of the Widget by using the same values in a call to
  62. * installStyle(). Anything used for presentation should include the
  63. * Widget's id as part of the style's id.
  64. *
  65. * The build() method will fire 'build'/'built' events. Subclasses then
  66. * populate the container with HTML as appropriate. Widgets should
  67. * generally be designed to not update the internal HTML until build() is
  68. * explicitly called.
  69. *
  70. * The destroy() method will fire 'destroy'/'destroyed' events and also
  71. * clear the innerHTML of the container. Subclasses are responsible for any
  72. * internal cleanup, such as nested Widgets.
  73. *
  74. * The verify() method will fire 'verify'/'verified' events. Subclasses can
  75. * handle these to validate any internal structures they need for. For
  76. * example, Widgets that have ARIA support can ensure appropriate attributes
  77. * are in place. If a Widget fails, it should throw a VerificationError
  78. * with details.
  79. */
  80. class Widget {
  81.  
  82. /**
  83. * Each subclass should take a caller provided name.
  84. * @param {string} name - Name for this instance.
  85. * @param {string} element - Type of element to use for the container.
  86. */
  87. constructor(name, element) {
  88. if (new.target === Widget) {
  89. throw new TypeError('Abstract class; do not instantiate directly.');
  90. }
  91.  
  92. this.#name = `${this.constructor.name} ${name}`;
  93. this.#id = NH.base.uuId(NH.base.safeId(this.name));
  94. this.#container = document.createElement(element);
  95. this.#container.id = `${this.id}-container`;
  96. this.#dispatcher = new NH.base.Dispatcher(...Widget.#knownEvents);
  97. this.#logger = new NH.base.Logger(`${this.constructor.name}`);
  98. this.#visible = true;
  99.  
  100. this.installStyle('nh-widget',
  101. [`.${Widget.classHidden} {display: none}`]);
  102. }
  103.  
  104. /** @type {string} - CSS class applied to hide element. */
  105. static get classHidden() {
  106. return 'nh-widget-hidden';
  107. }
  108.  
  109. /** @type {Element} */
  110. get container() {
  111. return this.#container;
  112. }
  113.  
  114. /** @type {string} */
  115. get id() {
  116. return this.#id;
  117. }
  118.  
  119. /** @type {NH.base.Logger} */
  120. get logger() {
  121. return this.#logger;
  122. }
  123.  
  124. /** @type {string} */
  125. get name() {
  126. return this.#name;
  127. }
  128.  
  129. /** @type {boolean} */
  130. get visible() {
  131. return this.#visible;
  132. }
  133.  
  134. /**
  135. * Materialize the contents into the container.
  136. *
  137. * Each time this is called, the Widget should repopulate the contents.
  138. * @fires 'build' 'built'
  139. * @returns {Widget} - This instance, for chaining.
  140. */
  141. build() {
  142. this.#dispatcher.fire('build', this);
  143. this.#dispatcher.fire('built', this);
  144. this.verify();
  145. return this;
  146. }
  147.  
  148. /**
  149. * Tears down internals. E.g., any Widget that has other Widgets should
  150. * call their destroy() method as well.
  151. * @fires 'destroy' 'destroyed'
  152. * @returns {Widget} - This instance, for chaining.
  153. */
  154. destroy() {
  155. this.#container.innerHTML = '';
  156. this.#dispatcher.fire('destroy', this);
  157. this.#dispatcher.fire('destroyed', this);
  158. return this;
  159. }
  160.  
  161. /**
  162. * Shows the Widget by removing a CSS class.
  163. * @fires 'show' 'showed'
  164. * @returns {Widget} - This instance, for chaining.
  165. */
  166. show() {
  167. this.verify();
  168. this.#dispatcher.fire('show', this);
  169. this.container.classList.remove(Widget.classHidden);
  170. this.#visible = true;
  171. this.#dispatcher.fire('showed', this);
  172. return this;
  173. }
  174.  
  175. /**
  176. * Hides the Widget by adding a CSS class.
  177. * @fires 'hide' 'hidden'
  178. * @returns {Widget} - This instance, for chaining.
  179. */
  180. hide() {
  181. this.#dispatcher.fire('hide', this);
  182. this.container.classList.add(Widget.classHidden);
  183. this.#visible = false;
  184. this.#dispatcher.fire('hidden', this);
  185. return this;
  186. }
  187.  
  188. /**
  189. * Verifies a Widget's internal state.
  190. *
  191. * For example, a Widget may use this to enforce certain ARIA criteria.
  192. * @fires 'verify' 'verified'
  193. * @returns {Widget} - This instance, for chaining.
  194. */
  195. verify() {
  196. this.#dispatcher.fire('verify', this);
  197. this.#dispatcher.fire('verified', this);
  198. return this;
  199. }
  200.  
  201. /** Clears the container element. */
  202. clear() {
  203. this.logger.log('clear is deprecated');
  204. this.#container.innerHTML = '';
  205. }
  206.  
  207. /**
  208. * Attach a function to an eventType.
  209. * @param {string} eventType - Event type to connect with.
  210. * @param {NH.base.Dispatcher~Handler} func - Single argument function to
  211. * call.
  212. * @returns {Widget} - This instance, for chaining.
  213. */
  214. on(eventType, func) {
  215. this.#dispatcher.on(eventType, func);
  216. return this;
  217. }
  218.  
  219. /**
  220. * Remove all instances of a function registered to an eventType.
  221. * @param {string} eventType - Event type to disconnect from.
  222. * @param {NH.base.Dispatcher~Handler} func - Function to remove.
  223. * @returns {Widget} - This instance, for chaining.
  224. */
  225. off(eventType, func) {
  226. this.#dispatcher.off(eventType, func);
  227. return this;
  228. }
  229.  
  230. /**
  231. * Helper that sets an attribute to value.
  232. *
  233. * If value is null, the attribute is removed.
  234. * @example
  235. * w.attrText('aria-label', 'Information about the application.')
  236. * @param {string} attr - Name of the attribute.
  237. * @param {?string} value - Value to assign.
  238. * @returns {Widget} - This instance, for chaining.
  239. */
  240. attrText(attr, value) {
  241. if (value === null) {
  242. this.container.removeAttribute(attr);
  243. } else {
  244. this.container.setAttribute(attr, value);
  245. }
  246. return this;
  247. }
  248.  
  249. /**
  250. * Helper that sets an attribute to space separated {Element} ids.
  251. *
  252. * This will collect the appropriate id from each value passed then assign
  253. * that collection to the attribute. If any value is null, the everything
  254. * up to that point will be reset. If the collection ends up being empty
  255. * (e.g., no values were passed or the last was null), the attribute will
  256. * be removed.
  257. * @param {string} attr - Name of the attribute.
  258. * @param {?Content} values - Value to assign.
  259. * @returns {Widget} - This instance, for chaining.
  260. */
  261. attrElements(attr, ...values) {
  262. const strs = [];
  263. for (const value of values) {
  264. if (value === null) {
  265. strs.length = 0;
  266. } else if (typeof value === 'string' || value instanceof String) {
  267. strs.push(value);
  268. } else if (value instanceof HTMLElement) {
  269. if (value.id) {
  270. strs.push(value.id);
  271. }
  272. } else if (value instanceof Widget) {
  273. if (value.container.id) {
  274. strs.push(value.container.id);
  275. }
  276. }
  277. }
  278. if (strs.length) {
  279. this.container.setAttribute(attr, strs.join(' '));
  280. } else {
  281. this.container.removeAttribute(attr);
  282. }
  283. return this;
  284. }
  285.  
  286. /**
  287. * Install a style if not already present.
  288. *
  289. * It will NOT overwrite an existing one.
  290. * @param {string} id - Base to use for the style id.
  291. * @param {string[]} rules - CSS rules in 'selector { declarations }'.
  292. * @returns {HTMLStyleElement} - Resulting <style> element.
  293. */
  294. installStyle(id, rules) {
  295. const me = 'installStyle';
  296. this.logger.entered(me, id, rules);
  297.  
  298. const safeId = `${NH.base.safeId(id)}-style`;
  299. let style = document.querySelector(`#${safeId}`);
  300. if (!style) {
  301. style = document.createElement('style');
  302. style.id = safeId;
  303. style.textContent = rules.join('\n');
  304. document.head.append(style);
  305. }
  306.  
  307. this.logger.leaving(me, style);
  308. return style;
  309. }
  310.  
  311. static #knownEvents = [
  312. 'build',
  313. 'built',
  314. 'verify',
  315. 'verified',
  316. 'destroy',
  317. 'destroyed',
  318. 'show',
  319. 'showed',
  320. 'hide',
  321. 'hidden',
  322. ];
  323.  
  324. #container
  325. #dispatcher
  326. #id
  327. #logger
  328. #name
  329. #visible
  330.  
  331. }
  332.  
  333. /* eslint-disable require-jsdoc */
  334. class Test extends Widget {
  335.  
  336. constructor() {
  337. super('test', 'section');
  338. }
  339.  
  340. }
  341. /* eslint-enable */
  342.  
  343. /* eslint-disable max-statements */
  344. /* eslint-disable no-magic-numbers */
  345. /* eslint-disable no-new */
  346. /* eslint-disable require-jsdoc */
  347. class WidgetTestCase extends NH.xunit.TestCase {
  348.  
  349. testAbstract() {
  350. this.assertRaises(TypeError, () => {
  351. new Widget();
  352. });
  353. }
  354.  
  355. testProperties() {
  356. // Assemble
  357. const w = new Test();
  358.  
  359. // Assert
  360. this.assertTrue(w.container instanceof HTMLElement, 'element');
  361. this.assertRegExp(
  362. w.container.id,
  363. RegExp(`^Test-test-${GUID}-container$`, 'u'),
  364. 'container'
  365. );
  366.  
  367. this.assertRegExp(w.id, RegExp(`^Test-test-${GUID}`, 'u'), 'id');
  368. this.assertTrue(w.logger instanceof NH.base.Logger, 'logger');
  369. this.assertEqual(w.name, 'Test test', 'name');
  370. }
  371.  
  372. testSimpleEvents() {
  373. // Assemble
  374. const calls = [];
  375. const cb = (...rest) => {
  376. calls.push(rest);
  377. };
  378. const w = new Test()
  379. .on('build', cb)
  380. .on('built', cb)
  381. .on('verify', cb)
  382. .on('verified', cb)
  383. .on('destroy', cb)
  384. .on('destroyed', cb)
  385. .on('show', cb)
  386. .on('showed', cb)
  387. .on('hide', cb)
  388. .on('hidden', cb);
  389.  
  390. // Act
  391. w.build()
  392. .show()
  393. .hide()
  394. .destroy();
  395.  
  396. // Assert
  397. this.assertEqual(calls, [
  398. ['build', w],
  399. ['built', w],
  400. // After build()
  401. ['verify', w],
  402. ['verified', w],
  403. // Before show()
  404. ['verify', w],
  405. ['verified', w],
  406. ['show', w],
  407. ['showed', w],
  408. ['hide', w],
  409. ['hidden', w],
  410. ['destroy', w],
  411. ['destroyed', w],
  412. ]);
  413. }
  414.  
  415. testDestroyCleans() {
  416. // Assemble
  417. const w = new Test();
  418. // XXX: Broken HTML on purpose
  419. w.container.innerHTML = '<p>Paragraph<p>';
  420.  
  421. this.assertEqual(w.container.innerHTML,
  422. '<p>Paragraph</p><p></p>',
  423. 'html got fixed');
  424. this.assertEqual(w.container.children.length, 2, 'initial count');
  425.  
  426. // Act
  427. w.destroy();
  428.  
  429. // Assert
  430. this.assertEqual(w.container.children.length, 0, 'post destroy count');
  431. }
  432.  
  433. testHideShow() {
  434. // Assemble
  435. const w = new Test();
  436.  
  437. this.assertTrue(w.visible, 'init vis');
  438. this.assertFalse(w.container.classList.contains(Widget.classHidden),
  439. 'init class');
  440.  
  441. w.hide();
  442.  
  443. this.assertFalse(w.visible, 'hide vis');
  444. this.assertTrue(w.container.classList.contains(Widget.classHidden),
  445. 'hide class');
  446.  
  447. w.show();
  448.  
  449. this.assertTrue(w.visible, 'show viz');
  450. this.assertFalse(w.container.classList.contains(Widget.classHidden),
  451. 'show class');
  452. }
  453.  
  454. testVerifyFails() {
  455. // Assemble
  456. const calls = [];
  457. const cb = (...rest) => {
  458. calls.push(rest);
  459. };
  460. const onVerify = () => {
  461. throw new VerificationError('oopsie');
  462. };
  463. const w = new Test()
  464. .on('build', cb)
  465. .on('verify', onVerify)
  466. .on('show', cb);
  467.  
  468. // Act/Assert
  469. this.assertRaises(
  470. VerificationError,
  471. () => {
  472. w.build()
  473. .show();
  474. },
  475. 'verify fails on purpose'
  476. );
  477. this.assertEqual(calls, [['build', w]], 'we made it past build');
  478. }
  479.  
  480. testOnOff() {
  481. // Assemble
  482. const calls = [];
  483. const cb = (...rest) => {
  484. calls.push(rest);
  485. };
  486. const w = new Test()
  487. .on('build', cb)
  488. .on('built', cb)
  489. .on('destroyed', cb)
  490. .off('build', cb)
  491. .on('destroy', cb)
  492. .off('destroyed', cb);
  493.  
  494. // Act
  495. w.build()
  496. .hide()
  497. .show()
  498. .destroy();
  499.  
  500. // Assert
  501. this.assertEqual(calls, [
  502. ['built', w],
  503. ['destroy', w],
  504. ]);
  505. }
  506.  
  507. testAttrText() {
  508. // Assemble
  509. const attr = 'aria-label';
  510. const w = new Test();
  511.  
  512. function f() {
  513. return w.container.getAttribute(attr);
  514. }
  515.  
  516. this.assertEqual(f(), null, 'init does not exist');
  517.  
  518. // First value
  519. w.attrText(attr, 'App info.');
  520. this.assertEqual(f(), 'App info.', 'exists');
  521.  
  522. // Change
  523. w.attrText(attr, 'Different value');
  524. this.assertEqual(f(), 'Different value', 'post change');
  525.  
  526. // Empty string
  527. w.attrText(attr, '');
  528. this.assertEqual(f(), '', 'empty string');
  529.  
  530. // Remove
  531. w.attrText(attr, null);
  532. this.assertEqual(f(), null, 'now gone');
  533. }
  534.  
  535. testAttrElements() {
  536. const attr = 'aria-labelledby';
  537. const text = 'id1 id2';
  538. const div = document.createElement('div');
  539. div.id = 'div-id';
  540. const w = new Test();
  541. w.container.id = 'w-id';
  542.  
  543. function g() {
  544. return w.container.getAttribute(attr);
  545. }
  546.  
  547. this.assertEqual(g(), null, 'init does not exist');
  548.  
  549. // Single value
  550. w.attrElements(attr, 'bob');
  551. this.assertEqual(g(), 'bob', 'single value');
  552.  
  553. // Replace with spaces
  554. w.attrElements(attr, text);
  555. this.assertEqual(g(), 'id1 id2', 'spaces');
  556.  
  557. // Remove
  558. w.attrElements(attr, null);
  559. this.assertEqual(g(), null, 'first remove');
  560.  
  561. // Multiple values of different types
  562. w.attrElements(attr, text, div, w);
  563. this.assertEqual(g(), 'id1 id2 div-id w-id', 'everything');
  564.  
  565. // Duplicates
  566. w.attrElements(attr, text, text);
  567. this.assertEqual(g(), 'id1 id2 id1 id2', 'duplicates');
  568.  
  569. // Null in the middle
  570. w.attrElements(attr, w, null, text, null, text);
  571. this.assertEqual(g(), 'id1 id2', 'mid null');
  572.  
  573. // Null at the end
  574. w.attrElements(attr, text, w, div, null);
  575. this.assertEqual(g(), null, 'end null');
  576. }
  577.  
  578. }
  579. /* eslint-enable */
  580.  
  581. NH.xunit.testing.testCases.push(WidgetTestCase);
  582.  
  583. /**
  584. * An adapter for raw HTML.
  585. *
  586. * Other Widgets may use this to wrap any HTML they may be handed so they do
  587. * not need to special case their implementation outside of construction.
  588. */
  589. class StringAdapter extends Widget {
  590.  
  591. /**
  592. * @param {string} name - Name for this instance.
  593. * @param {string} content - Item to be adapted.
  594. */
  595. constructor(name, content) {
  596. super(name, 'content');
  597. this.#content = content;
  598. this.on('build', this.#onBuild);
  599. }
  600.  
  601. #content
  602.  
  603. #onBuild = (...rest) => {
  604. const me = 'onBuild';
  605. this.logger.entered(me, rest);
  606.  
  607. this.container.innerHTML = this.#content;
  608.  
  609. this.logger.leaving(me);
  610. }
  611.  
  612. }
  613.  
  614. /* eslint-disable no-new-wrappers */
  615. /* eslint-disable require-jsdoc */
  616. class StringAdapterTestCase extends NH.xunit.TestCase {
  617.  
  618. testPrimitiveString() {
  619. // Assemble
  620. let p = '<p id="bob">This is my paragraph.</p>';
  621. const content = new StringAdapter(this.id, p);
  622.  
  623. // Act
  624. content.build();
  625.  
  626. // Assert
  627. this.assertTrue(content.container instanceof HTMLUnknownElement,
  628. 'is HTMLUnknownElement');
  629. this.assertTrue((/my paragraph./u).test(content.container.innerText),
  630. 'expected text');
  631. this.assertEqual(content.container.firstChild.tagName, 'P', 'is para');
  632. this.assertEqual(content.container.firstChild.id, 'bob', 'is bob');
  633.  
  634. // Tweak
  635. content.container.firstChild.id = 'joe';
  636. this.assertNotEqual(content.container.firstChild.id, 'bob', 'not bob');
  637.  
  638. // Rebuild
  639. content.build();
  640. this.assertEqual(content.container.firstChild.id, 'bob', 'bob again');
  641.  
  642. // Tweak - Not a live string
  643. p = '<p id="changed">New para.</p>';
  644. this.assertEqual(content.container.firstChild.id, 'bob', 'still bob');
  645. }
  646.  
  647. testStringObject() {
  648. // Assemble
  649. const p = new String('<p id="pat">This is my paragraph.</p>');
  650. const content = new StringAdapter(this.id, p);
  651.  
  652. // Act
  653. content.build();
  654. // Assert
  655. this.assertTrue(content.container instanceof HTMLUnknownElement,
  656. 'is HTMLUnknownElement');
  657. this.assertTrue((/my paragraph./u).test(content.container.innerText),
  658. 'expected text');
  659. this.assertEqual(content.container.firstChild.tagName, 'P', 'is para');
  660. this.assertEqual(content.container.firstChild.id, 'pat', 'is pat');
  661. }
  662.  
  663. }
  664. /* eslint-enable */
  665.  
  666. NH.xunit.testing.testCases.push(StringAdapterTestCase);
  667.  
  668. /**
  669. * An adapter for HTMLElement.
  670. *
  671. * Other Widgets may use this to wrap any HTMLElements they may be handed so
  672. * they do not need to special case their implementation outside of
  673. * construction.
  674. */
  675. class ElementAdapter extends Widget {
  676.  
  677. /**
  678. * @param {string} name - Name for this instance.
  679. * @param {HTMLElement} content - Item to be adapted.
  680. */
  681. constructor(name, content) {
  682. super(name, 'content');
  683. this.#content = content;
  684. this.on('build', this.#onBuild);
  685. }
  686.  
  687. #content
  688.  
  689. #onBuild = (...rest) => {
  690. const me = 'onBuild';
  691. this.logger.entered(me, rest);
  692.  
  693. this.container.replaceChildren(this.#content);
  694.  
  695. this.logger.leaving(me);
  696. }
  697.  
  698. }
  699. /* eslint-disable require-jsdoc */
  700. class ElementAdapterTestCase extends NH.xunit.TestCase {
  701.  
  702. testElement() {
  703. // Assemble
  704. const div = document.createElement('div');
  705. div.id = 'pat';
  706. div.innerText = 'I am a div.';
  707. const content = new ElementAdapter(this.id, div);
  708.  
  709. // Act
  710. content.build();
  711.  
  712. // Assert
  713. this.assertTrue(content.container instanceof HTMLUnknownElement,
  714. 'is HTMLUnknownElement');
  715. this.assertTrue((/I am a div./u).test(content.container.innerText),
  716. 'expected text');
  717. this.assertEqual(content.container.firstChild.tagName, 'DIV', 'is div');
  718. this.assertEqual(content.container.firstChild.id, 'pat', 'is pat');
  719.  
  720. // Tweak
  721. content.container.firstChild.id = 'joe';
  722. this.assertNotEqual(content.container.firstChild.id, 'pat', 'not pat');
  723. this.assertEqual(div.id, 'joe', 'demos is a live element');
  724.  
  725. // Rebuild
  726. content.build();
  727. this.assertEqual(content.container.firstChild.id, 'joe', 'still joe');
  728.  
  729. // Multiple times
  730. content.build();
  731. content.build();
  732. content.build();
  733. this.assertEqual(content.container.childNodes.length, 1, 'child nodes');
  734. }
  735.  
  736. }
  737. /* eslint-enable */
  738.  
  739. NH.xunit.testing.testCases.push(ElementAdapterTestCase);
  740.  
  741. /**
  742. * Selects the best adapter to wrap the content.
  743. * @param {string} name - Name for this instance.
  744. * @param {Content} content - Content to be adapted.
  745. * @throws {TypeError} - On type not handled.
  746. * @returns {Widget} - Appropriate adapter for content.
  747. */
  748. function contentWrapper(name, content) {
  749. if (typeof content === 'string' || content instanceof String) {
  750. return new StringAdapter(name, content);
  751. } else if (content instanceof HTMLElement) {
  752. return new ElementAdapter(name, content);
  753. } else if (content instanceof Widget) {
  754. return content;
  755. }
  756. throw new TypeError(`Unknown type for "${name}": ${content}`);
  757. }
  758.  
  759. /* eslint-disable no-magic-numbers */
  760. /* eslint-disable no-new-wrappers */
  761. /* eslint-disable require-jsdoc */
  762. class ContentWrapperTestCase extends NH.xunit.TestCase {
  763.  
  764. testPrimitiveString() {
  765. const x = contentWrapper(this.id, 'a string');
  766.  
  767. this.assertTrue(x instanceof StringAdapter);
  768. }
  769.  
  770. testStringObject() {
  771. const x = contentWrapper(this.id, new String('a string'));
  772.  
  773. this.assertTrue(x instanceof StringAdapter);
  774. }
  775.  
  776. testElement() {
  777. const element = document.createElement('div');
  778. const x = contentWrapper(this.id, element);
  779.  
  780. this.assertTrue(x instanceof ElementAdapter);
  781. }
  782.  
  783. testWidget() {
  784. const t = new Test();
  785. const x = contentWrapper(this.id, t);
  786.  
  787. this.assertEqual(x, t);
  788. }
  789.  
  790. testUnknown() {
  791. this.assertRaises(
  792. TypeError,
  793. () => {
  794. contentWrapper(this.id, null);
  795. },
  796. 'null'
  797. );
  798.  
  799. this.assertRaises(
  800. TypeError,
  801. () => {
  802. contentWrapper(this.id, 5);
  803. },
  804. 'int'
  805. );
  806.  
  807. this.assertRaises(
  808. TypeError,
  809. () => {
  810. contentWrapper(this.id, new Error('why not?'));
  811. },
  812. 'error-type'
  813. );
  814. }
  815.  
  816. }
  817. /* eslint-enable */
  818.  
  819. NH.xunit.testing.testCases.push(ContentWrapperTestCase);
  820.  
  821. /**
  822. * Implements the Layout pattern.
  823. */
  824. class Layout extends Widget {
  825.  
  826. /** @param {string} name - Name for this instance. */
  827. constructor(name) {
  828. super(name, 'div');
  829. this.on('build', this.#onBuild)
  830. .on('destroy', this.#onDestroy);
  831. for (const panel of Layout.#Panel.known) {
  832. this.set(panel, '');
  833. }
  834. }
  835.  
  836. /** @type {Widget} */
  837. get bottom() {
  838. return this.#panels.get(Layout.BOTTOM);
  839. }
  840.  
  841. /** @type {Widget} */
  842. get left() {
  843. return this.#panels.get(Layout.LEFT);
  844. }
  845.  
  846. /** @type {Widget} */
  847. get main() {
  848. return this.#panels.get(Layout.MAIN);
  849. }
  850.  
  851. /** @type {Widget} */
  852. get right() {
  853. return this.#panels.get(Layout.RIGHT);
  854. }
  855.  
  856. /** @type {Widget} */
  857. get top() {
  858. return this.#panels.get(Layout.TOP);
  859. }
  860.  
  861. /**
  862. * Sets a panel for this instance.
  863. *
  864. * @param {Layout.#Panel} panel - Panel to set.
  865. * @param {Content} content - Content to use.
  866. * @returns {Widget} - This instance, for chaining.
  867. */
  868. set(panel, content) {
  869. if (!(panel instanceof Layout.#Panel)) {
  870. throw new TypeError('"panel" argument is not a Layout.#Panel');
  871. }
  872.  
  873. this.#panels.get(panel)
  874. ?.destroy();
  875.  
  876. this.#panels.set(panel,
  877. contentWrapper(`${panel} panel content`, content));
  878.  
  879. return this;
  880. }
  881.  
  882. /** Panel enum. */
  883. static #Panel = class {
  884.  
  885. /** @param {string} name - Panel name. */
  886. constructor(name) {
  887. this.#name = name;
  888.  
  889. Layout.#Panel.known.add(this);
  890. }
  891.  
  892. static known = new Set();
  893.  
  894. /** @returns {string} - The name. */
  895. toString() {
  896. return this.#name;
  897. }
  898.  
  899. #name
  900.  
  901. }
  902.  
  903. static {
  904. Layout.BOTTOM = new Layout.#Panel('bottom');
  905. Layout.LEFT = new Layout.#Panel('left');
  906. Layout.MAIN = new Layout.#Panel('main');
  907. Layout.RIGHT = new Layout.#Panel('right');
  908. Layout.TOP = new Layout.#Panel('top');
  909. }
  910.  
  911. #panels = new Map();
  912.  
  913. #onBuild = (...rest) => {
  914. const me = 'onBuild';
  915. this.logger.entered(me, rest);
  916.  
  917. for (const panel of this.#panels.values()) {
  918. panel.build();
  919. }
  920.  
  921. const middle = document.createElement('div');
  922. middle.append(
  923. this.left.container, this.main.container, this.right.container
  924. );
  925. this.container.replaceChildren(
  926. this.top.container, middle, this.bottom.container
  927. );
  928.  
  929. this.logger.leaving(me);
  930. }
  931.  
  932. #onDestroy = (...rest) => {
  933. const me = 'onDestroy';
  934. this.logger.entered(me, rest);
  935.  
  936. for (const panel of this.#panels.values()) {
  937. panel.destroy();
  938. }
  939. this.#panels.clear();
  940.  
  941. this.logger.leaving(me);
  942. }
  943.  
  944. }
  945.  
  946. /* eslint-disable require-jsdoc */
  947. /* eslint-disable no-undefined */
  948. class LayoutTestCase extends NH.xunit.TestCase {
  949.  
  950. testIsDiv() {
  951. // Assemble
  952. const w = new Layout(this.id);
  953.  
  954. // Assert
  955. this.assertEqual(w.container.tagName, 'DIV', 'correct element');
  956. }
  957.  
  958. testPanelsStartSimple() {
  959. // Assemble
  960. const w = new Layout(this.id);
  961.  
  962. // Assert
  963. this.assertTrue(w.main instanceof Widget, 'main');
  964. this.assertRegExp(w.main.name, / main panel content/u, 'main name');
  965. this.assertTrue(w.top instanceof Widget, 'top');
  966. this.assertRegExp(w.top.name, / top panel content/u, 'top name');
  967. this.assertTrue(w.bottom instanceof Widget, 'bottom');
  968. this.assertTrue(w.left instanceof Widget, 'left');
  969. this.assertTrue(w.right instanceof Widget, 'right');
  970. }
  971.  
  972. testSetWorks() {
  973. // Assemble
  974. const w = new Layout(this.id);
  975.  
  976. // Act
  977. w.set(Layout.MAIN, 'main')
  978. .set(Layout.TOP, document.createElement('div'));
  979.  
  980. // Assert
  981. this.assertTrue(w.main instanceof Widget, 'main');
  982. this.assertEqual(
  983. w.main.name, 'StringAdapter main panel content', 'main name'
  984. );
  985. this.assertTrue(w.top instanceof Widget, 'top');
  986. this.assertEqual(
  987. w.top.name, 'ElementAdapter top panel content', 'top name'
  988. );
  989. }
  990.  
  991. testSetRequiresPanel() {
  992. // Assemble
  993. const w = new Layout(this.id);
  994.  
  995. // Act/Assert
  996. this.assertRaises(
  997. TypeError,
  998. () => {
  999. w.set('main', 'main');
  1000. }
  1001. );
  1002. }
  1003.  
  1004. testDefaultBuilds() {
  1005. // Assemble
  1006. const w = new Layout(this.id);
  1007.  
  1008. // Act
  1009. w.build();
  1010.  
  1011. // Assert
  1012. const expected = [
  1013. '<content.*-top-panel-.*></content>',
  1014. '<div>',
  1015. '<content.*-left-panel-.*></content>',
  1016. '<content.*-main-panel-.*></content>',
  1017. '<content.*-right-panel-.*></content>',
  1018. '</div>',
  1019. '<content.*-bottom-panel-.*></content>',
  1020. ].join('');
  1021. this.assertRegExp(w.container.innerHTML, RegExp(expected, 'u'));
  1022. }
  1023.  
  1024. testWithContentBuilds() {
  1025. // Assemble
  1026. const w = new Layout(this.id);
  1027. w.set(Layout.MAIN, 'main')
  1028. .set(Layout.TOP, 'top')
  1029. .set(Layout.BOTTOM, 'bottom')
  1030. .set(Layout.RIGHT, 'right')
  1031. .set(Layout.LEFT, 'left');
  1032.  
  1033. // Act
  1034. w.build();
  1035.  
  1036. // Assert
  1037. this.assertEqual(w.container.innerText, 'topleftmainrightbottom');
  1038. }
  1039.  
  1040. testResetingPanelDestroysPrevious() {
  1041. // Assemble
  1042. const calls = [];
  1043. const cb = (...rest) => {
  1044. calls.push(rest);
  1045. };
  1046. const w = new Layout(this.id);
  1047. const initMain = w.main;
  1048. initMain.on('destroy', cb);
  1049. const newMain = contentWrapper(this.id, 'Replacement main');
  1050.  
  1051. // Act
  1052. w.set(Layout.MAIN, newMain);
  1053. w.build();
  1054.  
  1055. // Assert
  1056. this.assertEqual(calls, [['destroy', initMain]], 'old main destroyed');
  1057. this.assertEqual(
  1058. w.container.innerText, 'Replacement main', 'new content'
  1059. );
  1060. }
  1061.  
  1062. testDestroy() {
  1063. // Assemble
  1064. const calls = [];
  1065. const cb = (evt) => {
  1066. calls.push(evt);
  1067. };
  1068. const w = new Layout(this.id)
  1069. .set(Layout.MAIN, 'main')
  1070. .build();
  1071.  
  1072. w.top.on('destroy', cb);
  1073. w.left.on('destroy', cb);
  1074. w.main.on('destroy', cb);
  1075. w.right.on('destroy', cb);
  1076. w.bottom.on('destroy', cb);
  1077.  
  1078. this.assertEqual(w.container.innerText, 'main', 'sanity check');
  1079.  
  1080. // Act
  1081. w.destroy();
  1082.  
  1083. // Assert
  1084. this.assertEqual(w.container.innerText, '', 'post destroy inner');
  1085. this.assertEqual(w.main, undefined, 'post destroy main');
  1086. this.assertEqual(
  1087. calls,
  1088. ['destroy', 'destroy', 'destroy', 'destroy', 'destroy'],
  1089. 'each panel was destroyed'
  1090. );
  1091. }
  1092.  
  1093. }
  1094. /* eslint-enable */
  1095.  
  1096. NH.xunit.testing.testCases.push(LayoutTestCase);
  1097.  
  1098. /**
  1099. * Arbitrary object to be used as data for {@link Grid}.
  1100. * @typedef {object} GridRecord
  1101. */
  1102.  
  1103. /** Column for the {@link Grid} widget. */
  1104. class GridColumn {
  1105.  
  1106. /**
  1107. * @callback ColumnClassesFunc
  1108. * @param {GridRecord} record - Record to style.
  1109. * @param {string} field - Field to style.
  1110. * @returns {string[]} - CSS classes for item.
  1111. */
  1112.  
  1113. /**
  1114. * @callback RenderFunc
  1115. * @param {GridRecord} record - Record to render.
  1116. * @param {string} field - Field to render.
  1117. * @returns {Widget} - Rendered content.
  1118. */
  1119.  
  1120. /** @param {string} field - Which field to render by default. */
  1121. constructor(field) {
  1122. if (!field) {
  1123. throw new Exception('A "field" is required');
  1124. }
  1125. this.#field = field;
  1126. this.#uid = NH.base.uuId(this.constructor.name);
  1127. this.colClassesFunc()
  1128. .renderFunc()
  1129. .setTitle();
  1130. }
  1131.  
  1132. /**
  1133. * The default implementation uses the field.
  1134. *
  1135. * @implements {ColumnClassesFunc}
  1136. * @param {GridRecord} record - Record to style.
  1137. * @param {string} field - Field to style.
  1138. * @returns {string[]} - CSS classes for item.
  1139. */
  1140. static defaultClassesFunc = (record, field) => {
  1141. const result = [field];
  1142. return result;
  1143. }
  1144.  
  1145. /**
  1146. * @implements {RenderFunc}
  1147. * @param {GridRecord} record - Record to render.
  1148. * @param {string} field - Field to render.
  1149. * @returns {Widget} - Rendered content.
  1150. */
  1151. static defaultRenderFunc = (record, field) => {
  1152. const result = contentWrapper(field, record[field]);
  1153. return result;
  1154. }
  1155.  
  1156. /** @type {string} - The name of the property from the record to show. */
  1157. get field() {
  1158. return this.#field;
  1159. }
  1160.  
  1161. /** @type {string} - A human readable value to use in the header. */
  1162. get title() {
  1163. return this.#title;
  1164. }
  1165.  
  1166. /** @type {string} */
  1167. get uid() {
  1168. return this.#uid;
  1169. }
  1170.  
  1171. /**
  1172. * Use the registered rendering function to create the widget.
  1173. *
  1174. * @param {GridRecord} record - Record to render.
  1175. * @returns {Widget} - Rendered content.
  1176. */
  1177. render(record) {
  1178. return contentWrapper(
  1179. this.#field, this.#renderFunc(record, this.#field)
  1180. );
  1181. }
  1182.  
  1183. /**
  1184. * Use the registered {ColClassesFunc} to return CSS classes.
  1185. *
  1186. * @param {GridRecord} record - Record to examine.
  1187. * @returns {string[]} - CSS classes for this record.
  1188. */
  1189. classList(record) {
  1190. return this.#colClassesFunc(record, this.#field);
  1191. }
  1192.  
  1193. /**
  1194. * Sets the function used to style a cell.
  1195. *
  1196. * If no value is passed, it will set the default function.
  1197. *
  1198. * @param {ColClassesFunc} func - Styling function.
  1199. * @returns {GridColumn} - This instance, for chaining.
  1200. */
  1201. colClassesFunc(func = GridColumn.defaultClassesFunc) {
  1202. if (!(func instanceof Function)) {
  1203. throw new Exception(
  1204. 'Invalid argument: is not a function'
  1205. );
  1206. }
  1207. this.#colClassesFunc = func;
  1208. return this;
  1209. }
  1210.  
  1211. /**
  1212. * Sets the function used to render the column.
  1213. *
  1214. * If no value is passed, it will set the default function.
  1215. *
  1216. * @param {RenderFunc} [func] - Rendering function.
  1217. * @returns {GridColumn} - This instance, for chaining.
  1218. */
  1219. renderFunc(func = GridColumn.defaultRenderFunc) {
  1220. if (!(func instanceof Function)) {
  1221. throw new Exception(
  1222. 'Invalid argument: is not a function'
  1223. );
  1224. }
  1225. this.#renderFunc = func;
  1226. return this;
  1227. }
  1228.  
  1229. /**
  1230. * Set the title string.
  1231. *
  1232. * If no value is passed, it will default back to the name of the field.
  1233. *
  1234. * @param {string} [title] - New title for the column.
  1235. * @returns {GridColumn} - This instance, for chaining.
  1236. */
  1237. setTitle(title) {
  1238. this.#title = title ?? NH.base.simpleParseWords(this.#field)
  1239. .join(' ');
  1240. return this;
  1241. }
  1242.  
  1243. #colClassesFunc
  1244. #field
  1245. #renderFunc
  1246. #title
  1247. #uid
  1248.  
  1249. }
  1250.  
  1251. /* eslint-disable no-empty-function */
  1252. /* eslint-disable no-new */
  1253. /* eslint-disable require-jsdoc */
  1254. class GridColumnTestCase extends NH.xunit.TestCase {
  1255.  
  1256. testNoArgment() {
  1257. this.assertRaisesRegExp(
  1258. Exception,
  1259. /A "field" is required/u,
  1260. () => {
  1261. new GridColumn();
  1262. }
  1263. );
  1264. }
  1265.  
  1266. testWithFieldName() {
  1267. // Assemble
  1268. const col = new GridColumn('fieldName');
  1269.  
  1270. // Assert
  1271. this.assertEqual(col.field, 'fieldName');
  1272. }
  1273.  
  1274. testBadRenderFunc() {
  1275. this.assertRaisesRegExp(
  1276. Exception,
  1277. /Invalid argument: is not a function/u,
  1278. () => {
  1279. new GridColumn('testField')
  1280. .renderFunc('string');
  1281. }
  1282. );
  1283. }
  1284.  
  1285. testGoodRenderFunc() {
  1286. this.assertNoRaises(
  1287. () => {
  1288. new GridColumn('fiend')
  1289. .renderFunc(() => {});
  1290. }
  1291. );
  1292. }
  1293.  
  1294. testExplicitTitle() {
  1295. // Assemble
  1296. const col = new GridColumn('fieldName')
  1297. .setTitle('Col Title');
  1298.  
  1299. // Assert
  1300. this.assertEqual(col.title, 'Col Title');
  1301. }
  1302.  
  1303. testDefaultTitle() {
  1304. // Assemble
  1305. const col = new GridColumn('fieldName');
  1306.  
  1307. // Assert
  1308. this.assertEqual(col.title, 'field Name');
  1309. }
  1310.  
  1311. testUid() {
  1312. // Assemble
  1313. const col = new GridColumn(this.id);
  1314.  
  1315. // Assert
  1316. this.assertRegExp(col.uid, /^GridColumn-/u);
  1317. }
  1318.  
  1319. testDefaultRenderer() {
  1320. // Assemble
  1321. const col = new GridColumn('name');
  1322. const record = {name: 'Bob', job: 'Artist'};
  1323.  
  1324. // Act
  1325. const w = col.render(record);
  1326.  
  1327. // Assert
  1328. this.assertTrue(w instanceof Widget, 'correct type');
  1329. this.assertEqual(w.build().container.innerHTML, 'Bob', 'right content');
  1330. }
  1331.  
  1332. testCanSetRenderFunc() {
  1333. // Assemble
  1334. function renderFunc(record, field) {
  1335. return contentWrapper(
  1336. this.id, `${record.name}|${record.job}|${field}`
  1337. );
  1338. }
  1339.  
  1340. const col = new GridColumn('name');
  1341. const record = {name: 'Bob', job: 'Artist'};
  1342.  
  1343. // Act I - Default
  1344. this.assertEqual(
  1345. col.render(record)
  1346. .build().container.innerHTML,
  1347. 'Bob',
  1348. 'default func'
  1349. );
  1350.  
  1351. // Act II - Custom
  1352. this.assertEqual(
  1353. col.renderFunc(renderFunc)
  1354. .render(record)
  1355. .build().container.innerHTML,
  1356. 'Bob|Artist|name',
  1357. 'custom func'
  1358. );
  1359.  
  1360. // Act III - Back to default
  1361. this.assertEqual(
  1362. col.renderFunc()
  1363. .render(record)
  1364. .build().container.innerHTML,
  1365. 'Bob',
  1366. 'back to default'
  1367. );
  1368. }
  1369.  
  1370. testRenderAlwaysReturnsWidget() {
  1371. // Assemble
  1372. function renderFunc(record, field) {
  1373. return `${record.name}|${record.job}|${field}`;
  1374. }
  1375.  
  1376. const col = new GridColumn('name')
  1377. .renderFunc(renderFunc);
  1378. const record = {name: 'Bob', job: 'Artist'};
  1379.  
  1380. // Act
  1381. const w = col.render(record);
  1382.  
  1383. // Assert
  1384. this.assertTrue(w instanceof Widget);
  1385. }
  1386.  
  1387. testDefaultClassesFunc() {
  1388. // Assemble
  1389. const col = new GridColumn('name');
  1390. const record = {name: 'Bob', job: 'Artist'};
  1391.  
  1392. // Act
  1393. const cl = col.classList(record);
  1394.  
  1395. // Assert
  1396. this.assertTrue(cl.includes('name'));
  1397. }
  1398.  
  1399. testCanSetClassesFunc() {
  1400. // Assemble
  1401. function colClassesFunc(record, field) {
  1402. return [`my-${field}`, 'xyzzy'];
  1403. }
  1404. const col = new GridColumn('name');
  1405. const record = {name: 'Bob', job: 'Artist'};
  1406.  
  1407. // Act I - Default
  1408. let cl = col.classList(record);
  1409.  
  1410. // Assert
  1411. this.assertTrue(cl.includes('name'), 'default func has field');
  1412. this.assertFalse(cl.includes('xyzzy'), 'no magic');
  1413.  
  1414. // Act II - Custom
  1415. col.colClassesFunc(colClassesFunc);
  1416. cl = col.classList(record);
  1417.  
  1418. // Assert
  1419. this.assertTrue(cl.includes('my-name'), 'custom has field');
  1420. this.assertTrue(cl.includes('xyzzy'), 'plays adventure');
  1421.  
  1422. // Act III - Back to default
  1423. col.colClassesFunc();
  1424. cl = col.classList(record);
  1425.  
  1426. // Assert
  1427. this.assertTrue(cl.includes('name'), 'back to default');
  1428. this.assertFalse(cl.includes('xyzzy'), 'no more magic');
  1429. }
  1430.  
  1431. }
  1432. /* eslint-enable */
  1433.  
  1434. NH.xunit.testing.testCases.push(GridColumnTestCase);
  1435.  
  1436. /**
  1437. * Implements the Grid pattern.
  1438. *
  1439. * Grid widgets will need `aria-*` attributes, TBD.
  1440. *
  1441. * A Grid consist of defined columns and data.
  1442. *
  1443. * The data is an array of objects that the caller can manipulate as needed,
  1444. * such as adding/removing/updating items, sorting, etc.
  1445. *
  1446. * The columns is an array of {@link GridColumn}s that the caller can
  1447. * manipulate as needed.
  1448. *
  1449. * Row based CSS classes can be controlled by setting a {Grid~ClassFunc}
  1450. * using the rowClassesFunc() method.
  1451. */
  1452. class Grid extends Widget {
  1453.  
  1454. /**
  1455. * @callback RowClassesFunc
  1456. * @param {GridRecord} record - Record to style.
  1457. * @returns {string[]} - CSS classes to add to row.
  1458. */
  1459.  
  1460. /** @param {string} name - Name for this instance. */
  1461. constructor(name) {
  1462. super(name, 'table');
  1463. this.on('build', this.#onBuild)
  1464. .on('destroy', this.#onDestroy)
  1465. .rowClassesFunc();
  1466. }
  1467.  
  1468. /**
  1469. * The default implementation sets no classes.
  1470. *
  1471. * @implements {RowClassesFunc}
  1472. * @returns {string[]} - CSS classes to add to row.
  1473. */
  1474. static defaultClassesFunc = () => {
  1475. const result = [];
  1476. return result;
  1477. }
  1478.  
  1479. /** @type {GridColumns[]} - Column definitions for the Grid. */
  1480. get columns() {
  1481. return this.#columns;
  1482. }
  1483.  
  1484. /** @type {object[]} - Data used by the Grid. */
  1485. get data() {
  1486. return this.#data;
  1487. }
  1488.  
  1489. /**
  1490. * @param {object[]} array - Data used by the Grid.
  1491. * @returns {Grid} - This instance, for chaining.
  1492. */
  1493. set(array) {
  1494. this.#data = array;
  1495. return this;
  1496. }
  1497.  
  1498. /**
  1499. * Sets the function used to style a row.
  1500. *
  1501. * If no value is passed, it will set the default function.
  1502. *
  1503. * @param {RowClassesFunc} func - Styling function.
  1504. * @returns {Grid} - This instance, for chaining.
  1505. */
  1506. rowClassesFunc(func = Grid.defaultClassesFunc) {
  1507. if (!(func instanceof Function)) {
  1508. throw new Exception(
  1509. 'Invalid argument: is not a function'
  1510. );
  1511. }
  1512. this.#rowClassesFunc = func;
  1513. return this;
  1514. }
  1515.  
  1516. #built = [];
  1517. #columns = [];
  1518. #data = [];
  1519. #rowClassesFunc;
  1520. #tbody
  1521. #thead
  1522.  
  1523. #resetBuilt = () => {
  1524. for (const row of this.#built) {
  1525. for (const cell of row.cells) {
  1526. cell.widget.destroy();
  1527. }
  1528. }
  1529.  
  1530. this.#built.length = 0;
  1531. }
  1532.  
  1533. #resetContainer = () => {
  1534. this.container.innerHTML = '';
  1535. this.#thead = document.createElement('thead');
  1536. this.#tbody = document.createElement('tbody');
  1537. this.container.append(this.#thead, this.#tbody);
  1538. }
  1539.  
  1540. #populateBuilt = () => {
  1541. for (const row of this.#data) {
  1542. const built = {
  1543. classes: this.#rowClassesFunc(row),
  1544. cells: [],
  1545. };
  1546. for (const col of this.#columns) {
  1547. built.cells.push(
  1548. {
  1549. widget: col.render(row),
  1550. classes: col.classList(row),
  1551. }
  1552. );
  1553. }
  1554. this.#built.push(built);
  1555. }
  1556. }
  1557.  
  1558. #buildHeader = () => {
  1559. const tr = document.createElement('tr');
  1560. for (const col of this.#columns) {
  1561. const th = document.createElement('th');
  1562. th.append(col.title);
  1563. tr.append(th);
  1564. }
  1565. this.#thead.append(tr);
  1566. }
  1567.  
  1568. #buildRows = () => {
  1569. for (const row of this.#built) {
  1570. const tr = document.createElement('tr');
  1571. tr.classList.add(...row.classes);
  1572. for (const cell of row.cells) {
  1573. const td = document.createElement('td');
  1574. td.append(cell.widget.build().container);
  1575. td.classList.add(...cell.classes);
  1576. tr.append(td);
  1577. }
  1578. this.#tbody.append(tr);
  1579. }
  1580. }
  1581.  
  1582. #onBuild = (...rest) => {
  1583. const me = 'onBuild';
  1584. this.logger.entered(me, rest);
  1585.  
  1586. this.#resetBuilt();
  1587. this.#resetContainer();
  1588. this.#populateBuilt();
  1589. this.#buildHeader();
  1590. this.#buildRows();
  1591.  
  1592. this.logger.leaving(me);
  1593. }
  1594.  
  1595. #onDestroy = (...rest) => {
  1596. const me = 'onDestroy';
  1597. this.logger.entered(me, rest);
  1598.  
  1599. this.#resetBuilt();
  1600.  
  1601. this.logger.leaving(me);
  1602. }
  1603.  
  1604. }
  1605.  
  1606. /* eslint-disable max-lines-per-function */
  1607. /* eslint-disable require-jsdoc */
  1608. class GridTestCase extends NH.xunit.TestCase {
  1609.  
  1610. testDefaults() {
  1611. // Assemble
  1612. const w = new Grid(this.id);
  1613.  
  1614. // Assert
  1615. this.assertEqual(w.container.tagName, 'TABLE', 'correct element');
  1616. this.assertEqual(w.columns, [], 'default columns');
  1617. this.assertEqual(w.data, [], 'default data');
  1618. }
  1619.  
  1620. testColumnsAreLive() {
  1621. // Assemble
  1622. const w = new Grid(this.id);
  1623. const col = new GridColumn('fieldName');
  1624.  
  1625. // Act
  1626. w.columns.push(col, 1);
  1627.  
  1628. // Assert
  1629. this.assertEqual(w.columns, [col, 1], 'note lack of sanity checking');
  1630. }
  1631.  
  1632. testSetUpdatesData() {
  1633. // Assemble
  1634. const w = new Grid(this.id);
  1635.  
  1636. // Act
  1637. w.set([{id: 1, name: 'Sally'}]);
  1638.  
  1639. // Assert
  1640. this.assertEqual(w.data, [{id: 1, name: 'Sally'}]);
  1641. }
  1642.  
  1643. testBadRowClasses() {
  1644. this.assertRaisesRegExp(
  1645. Exception,
  1646. /Invalid argument: is not a function/u,
  1647. () => {
  1648. new Grid(this.id)
  1649. .rowClassesFunc('string');
  1650. }
  1651. );
  1652. }
  1653.  
  1654. testDataIsLive() {
  1655. // Assemble
  1656. const w = new Grid(this.id);
  1657. const data = [{id: 1, name: 'Sally'}];
  1658. w.set(data);
  1659.  
  1660. // Act I - More
  1661. data.push({id: 2, name: 'Jane'}, {id: 3, name: 'Puff'});
  1662.  
  1663. // Assert
  1664. this.assertEqual(
  1665. w.data,
  1666. [
  1667. {id: 1, name: 'Sally'},
  1668. {id: 2, name: 'Jane'},
  1669. {id: 3, name: 'Puff'},
  1670. ],
  1671. 'new data was added'
  1672. );
  1673.  
  1674. // Act II - Sort
  1675. data.sort((a, b) => a.name.localeCompare(b.name));
  1676.  
  1677. // Assert
  1678. this.assertEqual(
  1679. w.data,
  1680. [
  1681. {name: 'Jane', id: 2},
  1682. {name: 'Puff', id: 3},
  1683. {name: 'Sally', id: 1},
  1684. ],
  1685. 'data was sorted'
  1686. );
  1687. }
  1688.  
  1689. testEmptyBuild() {
  1690. // Assemble
  1691. const w = new Grid(this.id);
  1692.  
  1693. // Act
  1694. w.build();
  1695.  
  1696. // Assert
  1697. const expected = [
  1698. `<table id="Grid-[^-]*-${GUID}[^"]*">`,
  1699. '<thead><tr></tr></thead>',
  1700. '<tbody></tbody>',
  1701. '</table>',
  1702. ].join('');
  1703. this.assertRegExp(w.container.outerHTML, RegExp(expected, 'u'));
  1704. }
  1705.  
  1706. testBuildWithData() {
  1707. // Assemble
  1708. function renderInt(record, field) {
  1709. const span = document.createElement('span');
  1710. span.append(record[field]);
  1711. return span;
  1712. }
  1713. function renderType(record) {
  1714. return `${record.stage}, ${record.species}`;
  1715. }
  1716.  
  1717. const w = new Grid(this.id);
  1718. const data = [
  1719. {id: 1, name: 'Sally', species: 'human', stage: 'juvenile'},
  1720. {name: 'Jane', id: 2, species: 'human', stage: 'juvenile'},
  1721. {name: 'Puff', id: 3, species: 'feline', stage: 'juvenile'},
  1722. ];
  1723. w.set(data);
  1724. w.columns.push(
  1725. new GridColumn('id')
  1726. .renderFunc(renderInt),
  1727. new GridColumn('name'),
  1728. new GridColumn('typ')
  1729. .setTitle('Type')
  1730. .renderFunc(renderType),
  1731. );
  1732.  
  1733. // Act I - First build
  1734. w.build();
  1735.  
  1736. // Assert
  1737. const expected = [
  1738. '<table id="Grid-[^"]*">',
  1739. '<thead>',
  1740. '<tr><th>id</th><th>name</th><th>Type</th></tr>',
  1741. '</thead>',
  1742. '<tbody>',
  1743. '<tr class="">',
  1744.  
  1745. `<td class="id"><content id="ElementAdapter-id-${GUID}-container">`,
  1746. '<span>1</span>',
  1747. '</content></td>',
  1748.  
  1749. '<td class="name"><content id="StringAdapter-name-.*-container">',
  1750. 'Sally',
  1751. '</content></td>',
  1752.  
  1753. `<td class="typ"><content id="StringAdapter-typ-${GUID}-container">`,
  1754. 'juvenile, human',
  1755. '</content></td>',
  1756.  
  1757. '</tr>',
  1758. '<tr class="">',
  1759.  
  1760. `<td class="id"><content id="ElementAdapter-id-${GUID}-container">`,
  1761. '<span>2</span>',
  1762. '</content></td>',
  1763.  
  1764. '<td class="name"><content id="StringAdapter-name-.*-container">',
  1765. 'Jane',
  1766. '</content></td>',
  1767.  
  1768. `<td class="typ"><content id="StringAdapter-typ-${GUID}-container">`,
  1769. 'juvenile, human',
  1770. '</content></td>',
  1771.  
  1772. '</tr>',
  1773. '<tr class="">',
  1774.  
  1775. `<td class="id"><content id="ElementAdapter-id-${GUID}-container">`,
  1776. '<span>3</span>',
  1777. '</content></td>',
  1778.  
  1779. '<td class="name"><content id="StringAdapter-name-.*-container">',
  1780. 'Puff',
  1781. '</content></td>',
  1782.  
  1783. `<td class="typ"><content id="StringAdapter-typ-${GUID}-container">`,
  1784. 'juvenile, feline',
  1785. '</content></td>',
  1786.  
  1787. '</tr>',
  1788. '</tbody>',
  1789. '</table>',
  1790. ].join('');
  1791. this.assertRegExp(
  1792. w.container.outerHTML,
  1793. RegExp(expected, 'u'),
  1794. 'first build'
  1795. );
  1796.  
  1797. // Act II - Rebuild is sensible
  1798. w.build();
  1799. this.assertRegExp(
  1800. w.container.outerHTML,
  1801. RegExp(expected, 'u'),
  1802. 'second build'
  1803. );
  1804. }
  1805.  
  1806. testBuildWithClasses() {
  1807. // Assemble
  1808. function renderInt(record, field) {
  1809. const span = document.createElement('span');
  1810. span.append(record[field]);
  1811. return span;
  1812. }
  1813. function renderType(record) {
  1814. return `${record.stage}, ${record.species}`;
  1815. }
  1816. function rowClassesFunc(record) {
  1817. return [record.species, record.stage];
  1818. }
  1819.  
  1820. const data = [
  1821. {id: 1, name: 'Sally', species: 'human', stage: 'juvenile'},
  1822. {name: 'Puff', id: 3, species: 'feline', stage: 'juvenile'},
  1823. {name: 'Bob', id: 4, species: 'alien', stage: 'adolescent'},
  1824. ];
  1825. const w = new Grid(this.id)
  1826. .set(data)
  1827. .rowClassesFunc(rowClassesFunc);
  1828. w.columns.push(
  1829. new GridColumn('id')
  1830. .renderFunc(renderInt),
  1831. new GridColumn('name'),
  1832. new GridColumn('tpe')
  1833. .setTitle('Type')
  1834. .renderFunc(renderType),
  1835. );
  1836.  
  1837. // Act
  1838. w.build();
  1839.  
  1840. // Assert
  1841. const expected = [
  1842. '<table id="Grid-[^"]*">',
  1843. '<thead>',
  1844. '<tr><th>id</th><th>name</th><th>Type</th></tr>',
  1845. '</thead>',
  1846. '<tbody>',
  1847. '<tr class="human juvenile">',
  1848.  
  1849. `<td class="id"><content id="ElementAdapter-id-${GUID}-container">`,
  1850. '<span>1</span>',
  1851. '</content></td>',
  1852.  
  1853. '<td class="name"><content id="StringAdapter-name-.*-container">',
  1854. 'Sally',
  1855. '</content></td>',
  1856.  
  1857. `<td class="tpe"><content id="StringAdapter-tpe-${GUID}-container">`,
  1858. 'juvenile, human',
  1859. '</content></td>',
  1860.  
  1861. '</tr>',
  1862. '<tr class="feline juvenile">',
  1863.  
  1864. `<td class="id"><content id="ElementAdapter-id-${GUID}-container">`,
  1865. '<span>3</span>',
  1866. '</content></td>',
  1867.  
  1868. '<td class="name"><content id="StringAdapter-name-.*-container">',
  1869. 'Puff',
  1870. '</content></td>',
  1871.  
  1872. `<td class="tpe"><content id="StringAdapter-tpe-${GUID}-container">`,
  1873. 'juvenile, feline',
  1874. '</content></td>',
  1875.  
  1876. '</tr>',
  1877. '<tr class="alien adolescent">',
  1878.  
  1879. `<td class="id"><content id="ElementAdapter-id-${GUID}-container">`,
  1880. '<span>4</span>',
  1881. '</content></td>',
  1882.  
  1883. '<td class="name"><content id="StringAdapter-name-.*-container">',
  1884. 'Bob',
  1885. '</content></td>',
  1886.  
  1887. `<td class="tpe"><content id="StringAdapter-tpe-${GUID}-container">`,
  1888. 'adolescent, alien',
  1889. '</content></td>',
  1890.  
  1891. '</tr>',
  1892. '</tbody>',
  1893. '</table>',
  1894. ].join('');
  1895. this.assertRegExp(
  1896. w.container.outerHTML,
  1897. RegExp(expected, 'u'),
  1898. );
  1899. }
  1900.  
  1901. testRebuildDestroys() {
  1902. // Assemble
  1903. const calls = [];
  1904. const cb = (...rest) => {
  1905. calls.push(rest);
  1906. };
  1907. const item = contentWrapper(this.id, 'My data.')
  1908. .on('destroy', cb);
  1909. const w = new Grid(this.id);
  1910. w.data.push({item: item});
  1911. w.columns.push(new GridColumn('item'));
  1912.  
  1913. // Act
  1914. w.build()
  1915. .build();
  1916.  
  1917. // Assert
  1918. this.assertEqual(calls, [['destroy', item]]);
  1919. }
  1920.  
  1921. testDestroy() {
  1922. // Assemble
  1923. const calls = [];
  1924. const cb = (...rest) => {
  1925. calls.push(rest);
  1926. };
  1927. const item = contentWrapper(this.id, 'My data.')
  1928. .on('destroy', cb);
  1929. const w = new Grid(this.id);
  1930. w.data.push({item: item});
  1931. w.columns.push(new GridColumn('item'));
  1932.  
  1933. // Act
  1934. w.build()
  1935. .destroy();
  1936.  
  1937. // Assert
  1938. this.assertEqual(calls, [['destroy', item]]);
  1939. }
  1940.  
  1941. }
  1942. /* eslint-enable */
  1943.  
  1944. NH.xunit.testing.testCases.push(GridTestCase);
  1945.  
  1946. /** Tab for the {@link Tabs} widget. */
  1947. class TabEntry {
  1948.  
  1949. /**
  1950. * @callback LabelClassesFunc
  1951. * @param {string} label - Label to style.
  1952. * @returns {string[]} - CSS classes for item.
  1953. */
  1954.  
  1955. /** @param {string} label - The label for this entry. */
  1956. constructor(label) {
  1957. if (!label) {
  1958. throw new Exception('A "label" is required');
  1959. }
  1960. this.#label = label;
  1961. this.#uid = NH.base.uuId(this.constructor.name);
  1962. this.labelClassesFunc()
  1963. .set();
  1964. }
  1965.  
  1966. /**
  1967. * The default implementation uses the label.
  1968. *
  1969. * @implements {LabelClassesFunc}
  1970. * @param {string} label - Label to style.
  1971. * @returns {string[]} - CSS classes for item.
  1972. */
  1973. static defaultClassesFunc(label) {
  1974. const result = [NH.base.safeId(label)];
  1975. return result;
  1976. }
  1977.  
  1978. /** @type {string} */
  1979. get label() {
  1980. return this.#label;
  1981. }
  1982.  
  1983. /** @type {Widget} */
  1984. get panel() {
  1985. return this.#panel;
  1986. }
  1987.  
  1988. /** @type {string} */
  1989. get uid() {
  1990. return this.#uid;
  1991. }
  1992.  
  1993. /**
  1994. * Use the registered {LabelClassesFunc} to return CSS classes.
  1995. *
  1996. * @returns {string[]} - CSS classes for this record.
  1997. */
  1998. classList() {
  1999. return this.#labelClassesFunc(this.#label);
  2000. }
  2001.  
  2002. /**
  2003. * Sets the function used to style the label.
  2004. *
  2005. * If no value is passed, it will set the default function.
  2006. *
  2007. * @param {LabelClassesFunc} func - Styling function.
  2008. * @returns {TabEntry} - This instance, for chaining.
  2009. */
  2010. labelClassesFunc(func = TabEntry.defaultClassesFunc) {
  2011. if (!(func instanceof Function)) {
  2012. throw new Exception(
  2013. 'Invalid argument: is not a function'
  2014. );
  2015. }
  2016. this.#labelClassesFunc = func;
  2017. return this;
  2018. }
  2019.  
  2020. /**
  2021. * Set the panel content for this entry.
  2022. *
  2023. * If no value is passed, defaults to an empty string.
  2024. * @param {Content} [panel] - Panel content.
  2025. * @returns {TabEntry} - This instance, for chaining.
  2026. */
  2027. set(panel = '') {
  2028. this.#panel = contentWrapper('panel content', panel);
  2029. return this;
  2030. }
  2031.  
  2032. #label
  2033. #labelClassesFunc
  2034. #panel
  2035. #uid
  2036.  
  2037. }
  2038.  
  2039. /* eslint-disable no-new */
  2040. /* eslint-disable require-jsdoc */
  2041. class TabEntryTestCase extends NH.xunit.TestCase {
  2042.  
  2043. testNoArgument() {
  2044. this.assertRaisesRegExp(
  2045. Exception,
  2046. /A "label" is required/u,
  2047. () => {
  2048. new TabEntry();
  2049. }
  2050. );
  2051. }
  2052.  
  2053. testWithLabel() {
  2054. // Assemble
  2055. const entry = new TabEntry(this.id);
  2056.  
  2057. this.assertEqual(entry.label, this.id);
  2058. }
  2059.  
  2060. testUid() {
  2061. // Assemble
  2062. const entry = new TabEntry(this.id);
  2063.  
  2064. // Assert
  2065. this.assertRegExp(entry.uid, RegExp(`^TabEntry-${GUID}`, 'u'));
  2066. }
  2067.  
  2068. testDefaultClassesFunc() {
  2069. // Assemble
  2070. const entry = new TabEntry('Tab Entry');
  2071.  
  2072. // Assert
  2073. this.assertEqual(entry.classList(), ['Tab-Entry']);
  2074. }
  2075.  
  2076. testCanSetClassesFunc() {
  2077. // Assemble
  2078. function labelClassesFunc(label) {
  2079. return [`my-${label}`, 'abc123'];
  2080. }
  2081. const entry = new TabEntry('tab-entry');
  2082.  
  2083. // Act I - Default
  2084. let cl = entry.classList();
  2085.  
  2086. // Assert
  2087. this.assertTrue(cl.includes('tab-entry'), 'default func has label');
  2088. this.assertFalse(cl.includes('abc123'), 'no alnum');
  2089.  
  2090. // Act II - Custom
  2091. entry.labelClassesFunc(labelClassesFunc);
  2092. cl = entry.classList();
  2093.  
  2094. // Assert
  2095. this.assertTrue(cl.includes('my-tab-entry'), 'custom func is custom');
  2096. this.assertTrue(cl.includes('abc123'), 'has alnum');
  2097.  
  2098. // Act III - Back to default
  2099. entry.labelClassesFunc();
  2100. cl = entry.classList();
  2101.  
  2102. // Assert
  2103. this.assertTrue(cl.includes('tab-entry'), 'default func back to label');
  2104. this.assertFalse(cl.includes('abc123'), 'no more alnum');
  2105. }
  2106.  
  2107. testPanel() {
  2108. // Assemble/Act I - Default
  2109. const entry = new TabEntry(this.id);
  2110.  
  2111. // Assert
  2112. this.assertTrue(entry.panel instanceof Widget, 'default widget');
  2113. this.assertEqual(
  2114. entry.panel.name, 'StringAdapter panel content', 'default name'
  2115. );
  2116.  
  2117. // Act II - Custom
  2118. entry.set(contentWrapper('custom content', 'new panel content'));
  2119.  
  2120. // Assert
  2121. this.assertEqual(
  2122. entry.panel.name, 'StringAdapter custom content', 'custom content'
  2123. );
  2124.  
  2125. // Act III - Back to default
  2126. entry.set();
  2127.  
  2128. // Assert
  2129. this.assertEqual(
  2130. entry.panel.name, 'StringAdapter panel content', 'default again'
  2131. );
  2132. }
  2133.  
  2134. }
  2135. /* eslint-enable */
  2136.  
  2137. NH.xunit.testing.testCases.push(TabEntryTestCase);
  2138.  
  2139. /**
  2140. * Implements the Tabs pattern.
  2141. *
  2142. * Tabs widgets will need `aria-*` attributes, TBD.
  2143. */
  2144. class Tabs extends Widget {
  2145.  
  2146. /** @param {string} name - Name for this instance. */
  2147. constructor(name) {
  2148. super(name, 'tabs');
  2149. this.on('build', this.#onBuild)
  2150. .on('destroy', this.#onDestroy);
  2151. }
  2152.  
  2153. #tablist
  2154.  
  2155. #resetContainer = () => {
  2156. this.container.innerHTML = '';
  2157. this.#tablist = document.createElement('tablist');
  2158. this.#tablist.role = 'tablist';
  2159. this.container.append(this.#tablist);
  2160. }
  2161.  
  2162. #onBuild = (...rest) => {
  2163. const me = 'onBuild';
  2164. this.logger.entered(me, rest);
  2165.  
  2166. this.#resetContainer();
  2167.  
  2168. this.logger.leaving(me);
  2169. }
  2170.  
  2171. #onDestroy = (...rest) => {
  2172. const me = 'onDestroy';
  2173. this.logger.entered(me, rest);
  2174.  
  2175. this.logger.leaving(me);
  2176. }
  2177.  
  2178. }
  2179.  
  2180. /* eslint-disable require-jsdoc */
  2181. class TabsTestCase extends NH.xunit.TestCase {
  2182.  
  2183. testDefaults() {
  2184. // Assemble
  2185. const w = new Tabs(this.id);
  2186.  
  2187. // Assert
  2188. this.assertEqual(w.container.tagName, 'TABS', 'correct element');
  2189. }
  2190.  
  2191. testEmptyBuild() {
  2192. // Assemble
  2193. const w = new Tabs(this.id);
  2194.  
  2195. // Act
  2196. w.build();
  2197.  
  2198. // Assert
  2199. const expected = [
  2200. `^<tabs id="Tabs-[^-]*-${GUID}[^"]*">`,
  2201. '<tablist role="tablist">',
  2202. '</tablist>',
  2203. '</tabs>$',
  2204. ].join('');
  2205. this.assertRegExp(w.container.outerHTML, RegExp(expected, 'u'));
  2206. }
  2207.  
  2208. }
  2209. /* eslint-enable */
  2210.  
  2211. NH.xunit.testing.testCases.push(TabsTestCase);
  2212.  
  2213. /**
  2214. * Implements the Modal pattern.
  2215. *
  2216. * Modal widgets should have exactly one of the `aria-labelledby` or
  2217. * `aria-label` attributes.
  2218. *
  2219. * Modal widgets can use `aria-describedby` to reference an element that
  2220. * describes the purpose if not clear from the initial content.
  2221. */
  2222. class Modal extends Widget {
  2223.  
  2224. /** @param {string} name - Name for this instance. */
  2225. constructor(name) {
  2226. super(name, 'dialog');
  2227. this.on('build', this.#onBuild)
  2228. .on('destroy', this.#onDestroy)
  2229. .on('verify', this.#onVerify)
  2230. .on('show', this.#onShow)
  2231. .on('hide', this.#onHide)
  2232. .set('')
  2233. .hide();
  2234. }
  2235.  
  2236. /** @type {Widget} */
  2237. get content() {
  2238. return this.#content;
  2239. }
  2240.  
  2241. /**
  2242. * Sets the content of this instance.
  2243. * @param {Content} content - Content to use.
  2244. * @returns {Widget} - This instance, for chaining.
  2245. */
  2246. set(content) {
  2247. this.#content?.destroy();
  2248. this.#content = contentWrapper('modal content', content);
  2249. return this;
  2250. }
  2251.  
  2252. #content
  2253.  
  2254. #onBuild = (...rest) => {
  2255. const me = 'onBuild';
  2256. this.logger.entered(me, rest);
  2257.  
  2258. this.#content.build();
  2259. this.container.replaceChildren(this.#content.container);
  2260.  
  2261. this.logger.leaving(me);
  2262. }
  2263.  
  2264. #onDestroy = (...rest) => {
  2265. const me = 'onDestroy';
  2266. this.logger.entered(me, rest);
  2267.  
  2268. this.#content.destroy();
  2269. this.#content = null;
  2270.  
  2271. this.logger.leaving(me);
  2272. }
  2273.  
  2274. #onVerify = (...rest) => {
  2275. const me = 'onVerify';
  2276. this.logger.entered(me, rest);
  2277.  
  2278. const labelledBy = this.container.getAttribute('aria-labelledby');
  2279. const label = this.container.getAttribute('aria-label');
  2280.  
  2281. if (!labelledBy && !label) {
  2282. throw new VerificationError(
  2283. `Modal "${this.name}" should have one of "aria-labelledby" ` +
  2284. 'or "aria-label" attributes'
  2285. );
  2286. }
  2287.  
  2288. if (labelledBy && label) {
  2289. throw new VerificationError(
  2290. `Modal "${this.name}" should not have both ` +
  2291. `"aria-labelledby=${labelledBy}" and "aria-label=${label}"`
  2292. );
  2293. }
  2294.  
  2295. this.logger.leaving(me);
  2296. }
  2297.  
  2298. #onShow = (...rest) => {
  2299. const me = 'onShow';
  2300. this.logger.entered(me, rest);
  2301.  
  2302. this.container.showModal();
  2303. this.#content.show();
  2304.  
  2305. this.logger.leaving(me);
  2306. }
  2307.  
  2308. #onHide = (...rest) => {
  2309. const me = 'onHide';
  2310. this.logger.entered(me, rest);
  2311.  
  2312. this.#content.hide();
  2313. this.container.close();
  2314.  
  2315. this.logger.leaving(me);
  2316. }
  2317.  
  2318. }
  2319.  
  2320. /* eslint-disable require-jsdoc */
  2321. class ModalTestCase extends NH.xunit.TestCase {
  2322.  
  2323. testDefaults() {
  2324. // Assemble
  2325. const w = new Modal(this.id);
  2326.  
  2327. // Assert
  2328. this.assertEqual(w.container.tagName, 'DIALOG', 'correct element');
  2329. this.assertFalse(w.visible, 'visibility');
  2330. this.assertTrue(w.content instanceof Widget, 'is widget');
  2331. this.assertRegExp(w.content.name, / modal content/u, 'content name');
  2332. }
  2333.  
  2334. testSetDestroysPrevious() {
  2335. // Assemble
  2336. const calls = [];
  2337. const cb = (...rest) => {
  2338. calls.push(rest);
  2339. };
  2340. const w = new Modal(this.id);
  2341. const content = w.content.on('destroy', cb);
  2342.  
  2343. // Act
  2344. w.set('new stuff');
  2345.  
  2346. // Assert
  2347. this.assertEqual(calls, [['destroy', content]]);
  2348. }
  2349.  
  2350. testCallsNestedWidget() {
  2351. // Assemble
  2352. const calls = [];
  2353. const cb = (...rest) => {
  2354. calls.push(rest);
  2355. };
  2356. const w = new Modal(this.id)
  2357. .attrText('aria-label', 'test widget');
  2358. const nest = contentWrapper(this.id, 'test content');
  2359.  
  2360. nest.on('build', cb)
  2361. .on('destroy', cb)
  2362. .on('show', cb)
  2363. .on('hide', cb);
  2364.  
  2365. // Act
  2366. w.set(nest)
  2367. .build()
  2368. .hide()
  2369. .destroy();
  2370.  
  2371. // Assert
  2372. this.assertEqual(calls, [
  2373. ['build', nest],
  2374. ['hide', nest],
  2375. ['destroy', nest],
  2376. ]);
  2377. }
  2378.  
  2379. testVerify() {
  2380. // Assemble
  2381. const w = new Modal(this.id);
  2382.  
  2383. // Assert
  2384. this.assertRaisesRegExp(
  2385. VerificationError,
  2386. /should have one of/u,
  2387. () => {
  2388. w.build();
  2389. },
  2390. 'no aria attributes'
  2391. );
  2392.  
  2393. // Add labelledby
  2394. w.attrText('aria-labelledby', 'some-element');
  2395. this.assertNoRaises(() => {
  2396. w.build();
  2397. }, 'post add aria-labelledby');
  2398.  
  2399. // Add label
  2400. w.attrText('aria-label', 'test modal');
  2401. this.assertRaisesRegExp(
  2402. VerificationError,
  2403. /should not have both "[^"]*" and "[^"]*"/u,
  2404. () => {
  2405. w.build();
  2406. },
  2407. 'both aria attributes'
  2408. );
  2409.  
  2410. // Remove labelledby
  2411. w.attrText('aria-labelledby', null);
  2412. this.assertNoRaises(() => {
  2413. w.build();
  2414. }, 'post remove aria-labelledby');
  2415. }
  2416.  
  2417. }
  2418. /* eslint-enable */
  2419.  
  2420. NH.xunit.testing.testCases.push(ModalTestCase);
  2421.  
  2422. /**
  2423. * A widget that can be opened and closed on demand, designed for fairly
  2424. * persistent information.
  2425. *
  2426. * The element will get `open` and `close` events.
  2427. */
  2428. class Info extends Widget {
  2429.  
  2430. /** @param {string} name - Name for this instance. */
  2431. constructor(name) {
  2432. super(name, 'dialog');
  2433. this.logger.log(`${this.name} constructed`);
  2434. }
  2435.  
  2436. /** Open the widget. */
  2437. open() {
  2438. this.container.showModal();
  2439. this.container.dispatchEvent(new Event('open'));
  2440. }
  2441.  
  2442. /** Close the widget. */
  2443. close() {
  2444. // HTMLDialogElement sends a close event natively.
  2445. this.container.close();
  2446. }
  2447.  
  2448. }
  2449.  
  2450. return {
  2451. version: version,
  2452. Widget: Widget,
  2453. Layout: Layout,
  2454. GridColumn: GridColumn,
  2455. Grid: Grid,
  2456. Modal: Modal,
  2457. Info: Info,
  2458. };
  2459.  
  2460. }());

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址