pretty-json-custom-element-js.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. // @ts-check
  2. /**
  3. * @typedef {string | number | null | undefined | bigint | boolean | symbol} Primitive
  4. * @typedef {(...args: any[]) => any} AnyFunction
  5. */
  6. class PrettyJSONError extends Error {
  7. /**
  8. *
  9. * @param {string} message
  10. */
  11. constructor(message) {
  12. super(message);
  13. this.name = "PrettyJSONError";
  14. }
  15. }
  16. class PrettyJSON extends HTMLElement {
  17. /**
  18. * @type {any}
  19. */
  20. #input;
  21. /**
  22. * @type {boolean}
  23. */
  24. #isExpanded;
  25. static get observedAttributes() {
  26. return ["expand", "key", "truncate-string"];
  27. }
  28. static styles = `/* css */
  29. :host {
  30. --key-color: #cc0000;
  31. --arrow-color: #737373;
  32. --brace-color: #0030f0;
  33. --bracket-color: #0030f0;
  34. --string-color: #009900;
  35. --number-color: #0000ff;
  36. --null-color: #666666;
  37. --boolean-color: #d23c91;
  38. --comma-color: #666666;
  39. --ellipsis-color: #666666;
  40. --indent: 2rem;
  41. }
  42. @media (prefers-color-scheme: dark) {
  43. :host {
  44. --key-color: #f73d3d;
  45. --arrow-color: #6c6c6c;
  46. --brace-color: #0690bc;
  47. --bracket-color: #0690bc;
  48. --string-color: #21c521;
  49. --number-color: #0078b3;
  50. --null-color: #8c8888;
  51. --boolean-color: #c737b3;
  52. --comma-color: #848181;
  53. --ellipsis-color: #c2c2c2;
  54. }
  55. }
  56. button {
  57. border: none;
  58. background: transparent;
  59. cursor: pointer;
  60. font-family: inherit;
  61. font-size: 1rem;
  62. vertical-align: text-bottom;
  63. }
  64. .container {
  65. font-family: monospace;
  66. font-size: 1rem;
  67. }
  68. .key {
  69. color: var(--key-color);
  70. margin-right: 0.5rem;
  71. padding: 0;
  72. }
  73. .key .arrow {
  74. width: 1rem;
  75. height: 0.75rem;
  76. margin-left: -1.25rem;
  77. padding-right: 0.25rem;
  78. vertical-align: baseline;
  79. }
  80. .arrow .triangle {
  81. fill: var(--arrow-color);
  82. }
  83. .comma {
  84. color: var(--comma-color);
  85. }
  86. .brace {
  87. color: var(--brace-color);
  88. }
  89. .string,
  90. .url {
  91. color: var(--string-color);
  92. }
  93. .number,
  94. .bigint {
  95. color: var(--number-color);
  96. }
  97. .null {
  98. color: var(--null-color);
  99. }
  100. .boolean {
  101. color: var(--boolean-color);
  102. }
  103. .ellipsis {
  104. width: 1rem;
  105. padding: 0;
  106. color: var(--ellipsis-color);
  107. }
  108. .ellipsis::after {
  109. content: "…";
  110. }
  111. .string .ellipsis::after {
  112. color: var(--string-color);
  113. }
  114. .triangle {
  115. fill: black;
  116. stroke: black;
  117. stroke-width: 0;
  118. }
  119. .row {
  120. padding-left: var(--indent);
  121. }
  122. .row .row {
  123. display: block;
  124. }
  125. .row > div,
  126. .row > span {
  127. display: inline-block;
  128. }
  129. `;
  130. constructor() {
  131. super();
  132. this.#isExpanded = true;
  133. this.attachShadow({ mode: "open" });
  134. }
  135. get #expandAttributeValue() {
  136. const expandAttribute = this.getAttribute("expand");
  137. if (expandAttribute === null) {
  138. return 1;
  139. }
  140. const expandValue = Number.parseInt(expandAttribute);
  141. return isNaN(expandValue) || expandValue < 0 ? 0 : expandValue;
  142. }
  143. get #truncateStringAttributeValue() {
  144. const DEFAULT_TRUNCATE_STRING = 500;
  145. const truncateStringAttribute = this.getAttribute("truncate-string");
  146. if (truncateStringAttribute === null) {
  147. return DEFAULT_TRUNCATE_STRING;
  148. }
  149. const truncateStringValue = Number.parseInt(truncateStringAttribute);
  150. return isNaN(truncateStringValue) || truncateStringValue < 0
  151. ? 0
  152. : truncateStringValue;
  153. }
  154. #toggle() {
  155. this.#isExpanded = !this.#isExpanded;
  156. this.setAttribute(
  157. "expand",
  158. this.#isExpanded ? String(this.#expandAttributeValue + 1) : "0"
  159. );
  160. this.#render();
  161. }
  162. /**
  163. * @param {Record<any, any> | any[] | Primitive | AnyFunction} input
  164. * @param {number} expand
  165. * @param {string} [key]
  166. * @returns {HTMLElement}
  167. */
  168. #createChild(input, expand, key) {
  169. if (this.#isPrimitiveValue(input)) {
  170. const container = this.#createContainer();
  171. container.appendChild(this.#createPrimitiveValueElement(input));
  172. return container;
  173. }
  174. return this.#createObjectOrArray(input);
  175. }
  176. /**
  177. * @param {any} input
  178. * @returns {input is Primitive}
  179. */
  180. #isPrimitiveValue(input) {
  181. return typeof input !== "object" || input === null;
  182. }
  183. #isValidStringURL() {
  184. try {
  185. new URL(this.#input);
  186. return true;
  187. } catch (error) {
  188. return false;
  189. }
  190. }
  191. /**
  192. * @param {Primitive} input
  193. * @returns {HTMLElement}
  194. */
  195. #createPrimitiveValueElement(input) {
  196. const container = document.createElement("div");
  197. const type = typeof input === "object" ? "null" : typeof input;
  198. container.className = `primitive value ${type}`;
  199. if (typeof input === "string") {
  200. if (this.#isValidStringURL()) {
  201. const anchor = document.createElement("a");
  202. anchor.className = "url";
  203. anchor.href = this.#input;
  204. anchor.target = "_blank";
  205. anchor.textContent = input;
  206. container.append('"', anchor, '"');
  207. } else if (input.length > this.#truncateStringAttributeValue) {
  208. container.appendChild(this.#createTruncatedStringElement(input));
  209. } else {
  210. container.textContent = JSON.stringify(input);
  211. }
  212. } else {
  213. container.textContent = JSON.stringify(input);
  214. }
  215. return container;
  216. }
  217. /**
  218. * @param {string} input
  219. */
  220. #createTruncatedStringElement(input) {
  221. const container = document.createElement("div");
  222. container.dataset.expandedTimes = "1";
  223. container.className = "truncated string";
  224. const ellipsis = document.createElement("button");
  225. ellipsis.className = "ellipsis";
  226. ellipsis.addEventListener("click", () => {
  227. const expandedTimes = Number.parseInt(
  228. container.dataset.expandedTimes ?? "1"
  229. );
  230. container.dataset.expandedTimes = String(expandedTimes + 1);
  231. const expandedString = input.slice(
  232. 0,
  233. (expandedTimes + 1) * this.#truncateStringAttributeValue
  234. );
  235. const textChild = container.childNodes[1];
  236. container.replaceChild(
  237. document.createTextNode(expandedString),
  238. textChild
  239. );
  240. });
  241. container.append(
  242. '"',
  243. input.slice(0, this.#truncateStringAttributeValue),
  244. ellipsis,
  245. '"'
  246. );
  247. return container;
  248. }
  249. /**
  250. * @returns {HTMLElement}
  251. */
  252. #createContainer() {
  253. const container = document.createElement("div");
  254. container.className = "container";
  255. return container;
  256. }
  257. /**
  258. * @param {Record<any, any> | any[]} object
  259. * @returns {HTMLElement}
  260. */
  261. #createObjectOrArray(object) {
  262. const isArray = Array.isArray(object);
  263. const objectKeyName = this.getAttribute("key");
  264. const expand = this.#expandAttributeValue;
  265. const container = this.#createContainer();
  266. container.classList.add(isArray ? "array" : "object");
  267. if (objectKeyName) {
  268. // if objectKeyName is provided, then it is a row
  269. container.classList.add("row");
  270. const keyElement = this.#createKeyElement(objectKeyName, {
  271. withArrow: true,
  272. expanded: this.#isExpanded,
  273. });
  274. keyElement.addEventListener("click", this.#toggle.bind(this));
  275. container.appendChild(keyElement);
  276. }
  277. const openingBrace = document.createElement("span");
  278. openingBrace.className = "open brace";
  279. openingBrace.textContent = isArray ? "[" : "{";
  280. container.appendChild(openingBrace);
  281. const closingBrace = document.createElement("span");
  282. closingBrace.className = "close brace";
  283. closingBrace.textContent = isArray ? "]" : "}";
  284. if (!this.#isExpanded) {
  285. const ellipsis = document.createElement("button");
  286. ellipsis.className = "ellipsis";
  287. container.appendChild(ellipsis);
  288. ellipsis.addEventListener("click", this.#toggle.bind(this));
  289. container.appendChild(closingBrace);
  290. return container;
  291. }
  292. Object.entries(object).forEach(([key, value], index) => {
  293. // for primitives we make a row here
  294. if (this.#isPrimitiveValue(value)) {
  295. const rowContainer = document.createElement("div");
  296. rowContainer.className = "row";
  297. if (!isArray) {
  298. const keyElement = this.#createKeyElement(key);
  299. rowContainer.appendChild(keyElement);
  300. }
  301. rowContainer.appendChild(this.#createPrimitiveValueElement(value));
  302. container.appendChild(rowContainer);
  303. const isLast = index === Object.keys(object).length - 1;
  304. if (!isLast) {
  305. const comma = document.createElement("span");
  306. comma.className = "comma";
  307. comma.textContent = ",";
  308. rowContainer.appendChild(comma);
  309. }
  310. return;
  311. }
  312. // for objects and arrays we make a "container row"
  313. const prettyJsonElement = document.createElement("pretty-json");
  314. prettyJsonElement.textContent = JSON.stringify(value);
  315. prettyJsonElement.setAttribute("expand", String(expand - 1));
  316. prettyJsonElement.setAttribute("key", key);
  317. container.appendChild(prettyJsonElement);
  318. });
  319. container.appendChild(closingBrace);
  320. return container;
  321. }
  322. /**
  323. * @param {{ expanded?: boolean }} [options]
  324. * @returns {SVGElement}
  325. */
  326. #createArrowElement({ expanded = false } = {}) {
  327. const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  328. svg.setAttribute("width", "100");
  329. svg.setAttribute("height", "100");
  330. svg.setAttribute("viewBox", "0 0 100 100");
  331. svg.setAttribute("class", "arrow");
  332. const polygon = document.createElementNS(
  333. "http://www.w3.org/2000/svg",
  334. "polygon"
  335. );
  336. polygon.setAttribute("class", "triangle");
  337. polygon.setAttribute("points", "0,0 100,50 0,100");
  338. if (expanded) {
  339. polygon.setAttribute("transform", "rotate(90 50 50)");
  340. }
  341. svg.appendChild(polygon);
  342. return svg;
  343. }
  344. /**
  345. * @param {string} key
  346. * @param {{ withArrow?: boolean, expanded?: boolean }} [options]
  347. * @returns {HTMLElement}
  348. */
  349. #createKeyElement(key, { withArrow = false, expanded = false } = {}) {
  350. const keyElement = document.createElement(withArrow ? "button" : "span");
  351. keyElement.className = "key";
  352. if (withArrow) {
  353. const arrow = this.#createArrowElement({ expanded });
  354. keyElement.appendChild(arrow);
  355. }
  356. const keyName = document.createElement("span");
  357. keyName.className = "key-name";
  358. keyName.textContent = JSON.stringify(key);
  359. keyElement.appendChild(keyName);
  360. const colon = document.createElement("span");
  361. colon.className = "colon";
  362. colon.textContent = ":";
  363. keyElement.appendChild(colon);
  364. return keyElement;
  365. }
  366. #render() {
  367. if (!this.shadowRoot) {
  368. throw new PrettyJSONError("Shadow root not available");
  369. }
  370. this.shadowRoot.innerHTML = "";
  371. this.shadowRoot.appendChild(
  372. this.#createChild(this.#input, this.#expandAttributeValue)
  373. );
  374. if (this.shadowRoot.querySelector("[data-pretty-json]")) {
  375. return;
  376. }
  377. const styles = document.createElement("style");
  378. styles.setAttribute("data-pretty-json", "");
  379. styles.textContent = PrettyJSON.styles;
  380. this.shadowRoot.appendChild(styles);
  381. }
  382. /**
  383. * Handle when attributes change
  384. * @param {string} name
  385. * @param {string} _oldValue
  386. * @param {string | null} newValue
  387. */
  388. attributeChangedCallback(name, _oldValue, newValue) {
  389. if (name === "expand") {
  390. if (newValue === null) {
  391. this.#isExpanded = false;
  392. } else {
  393. const expandValue = Number.parseInt(newValue);
  394. this.#isExpanded = !isNaN(expandValue) && expandValue > 0;
  395. }
  396. this.#render();
  397. }
  398. }
  399. connectedCallback() {
  400. try {
  401. this.#input = JSON.parse(this.textContent ?? "");
  402. } catch (jsonParseError) {
  403. const message = `Error parsing JSON: ${jsonParseError instanceof Error ? jsonParseError.message : "Unknown error"}`;
  404. throw new PrettyJSONError(message);
  405. }
  406. this.#render();
  407. }
  408. }
  409. // Define pretty-json custom element
  410. customElements.define("pretty-json", PrettyJSON);