GitHub Font Preview

A userscript that adds a font file preview

  1. // ==UserScript==
  2. // @name GitHub Font Preview
  3. // @version 1.0.26
  4. // @description A userscript that adds a font file preview
  5. // @license MIT
  6. // @author Rob Garrison
  7. // @namespace https://github.com/Mottie
  8. // @match https://github.com/*
  9. // @run-at document-idle
  10. // @grant GM_addStyle
  11. // @grant GM_getValue
  12. // @grant GM_setValue
  13. // @grant GM_xmlhttpRequest
  14. // @connect github.com
  15. // @connect githubusercontent.com
  16. // @require https://greatest.deepsurf.us/scripts/28721-mutations/code/mutations.js?version=1108163
  17. // @require https://greatest.deepsurf.us/scripts/20469-opentype-js/code/opentypejs.js?version=130870
  18. // @icon https://github.githubassets.com/pinned-octocat.svg
  19. // @supportURL https://github.com/Mottie/GitHub-userscripts/issues
  20. // ==/UserScript==
  21.  
  22. /* global opentype */
  23. (() => {
  24. "use strict";
  25.  
  26. let font;
  27. let showUnicode = GM_getValue("gfp-show-unicode", false);
  28. let showPoints = GM_getValue("gfp-show-points", true);
  29. let showArrows = GM_getValue("gfp-show-arrows", true);
  30. let currentIndex = 0;
  31.  
  32. // supported font types
  33. const fontExt = /\.(otf|ttf|woff)$/i;
  34.  
  35. // canvas colors
  36. const glyphFillColor = "#808080"; // (big) (mini) fill color
  37. const bigGlyphStrokeColor = "#111111"; // (big) stroke color
  38. const bigGlyphMarkerColor = "#f00"; // (big) min & max width marker
  39. const miniGlyphMarkerColor = "#606060"; // (mini) glyph index (bottom left corner)
  40. const glyphRulerColor = "#a0a0a0"; // (mini) min & max width marker & (big) glyph horizontal lines
  41.  
  42. function startLoad() {
  43. const block = $(".blob-wrapper a[href*='?raw=true']");
  44. const body = block && block.closest(".Box-body");
  45. if (body) {
  46. body.classList.add("ghfp-body");
  47. body.innerHTML = "<span class='gfp-loading ghd-invert'></span>";
  48. }
  49. return block && block.href;
  50. }
  51.  
  52. function getFont() {
  53. const url = startLoad();
  54. if (url) {
  55. // add loading indicator
  56. GM_xmlhttpRequest({
  57. method: "GET",
  58. url,
  59. responseType: "arraybuffer",
  60. onload: response => {
  61. setupFont(response.response);
  62. }
  63. });
  64. }
  65. }
  66.  
  67. function setupFont(data) {
  68. const block = $(".ghfp-body");
  69. const el = $(".final-path");
  70. if (block && el) {
  71. try {
  72. font = opentype.parse(data);
  73. addHTML(block, el);
  74. showErrorMessage("");
  75. onFontLoaded(font);
  76. } catch (err) {
  77. block.innerHTML = "<h2 class='gfp-message cdel'></h2>";
  78. showErrorMessage(err.toString());
  79. if (err.stack) {
  80. console.error(err.stack);
  81. }
  82. throw (err);
  83. }
  84. }
  85. }
  86.  
  87. function addHTML(block, el) {
  88. let name = el.textContent || "";
  89. block.innerHTML = `
  90. <div id="gfp-wrapper">
  91. <span class="gfp-info" id="gfp-font-name">${name}</span>
  92. <h2 class="gfp-message cdel"></h2>
  93. <hr>
  94. <div id="gfp-font-data">
  95. <div class="gfp-collapsed">Font Header table <a href="https://www.microsoft.com/typography/OTSPEC/head.htm" target="_blank">head</a></div>
  96. <dl id="gfp-head-table"><dt>Undefined</dt></dl>
  97. <div class="gfp-collapsed">Horizontal Header table <a href="https://www.microsoft.com/typography/OTSPEC/hhea.htm" target="_blank">hhea</a></div>
  98. <dl id="gfp-hhea-table"><dt>Undefined</dt></dl>
  99. <div class="gfp-collapsed">Maximum Profile table <a href="https://www.microsoft.com/typography/OTSPEC/maxp.htm" target="_blank">maxp</a></div>
  100. <dl id="gfp-maxp-table"><dt>Undefined</dt></dl>
  101. <div class="gfp-collapsed">Naming table <a href="https://www.microsoft.com/typography/OTSPEC/name.htm" target="_blank">name</a></div>
  102. <dl id="gfp-name-table"><dt>Undefined</dt></dl>
  103. <div class="gfp-collapsed">OS/2 and Windows Metrics table <a href="https://www.microsoft.com/typography/OTSPEC/os2.htm" target="_blank">OS/2</a></div>
  104. <dl id="gfp-os2-table"><dt>Undefined</dt></dl>
  105. <div class="gfp-collapsed">PostScript table <a href="https://www.microsoft.com/typography/OTSPEC/post.htm" target="_blank">post</a></div>
  106. <dl id="gfp-post-table"><dt>Undefined</dt></dl>
  107. <div class="gfp-collapsed">Character To Glyph Index Mapping Table <a href="https://www.microsoft.com/typography/OTSPEC/cmap.htm" target="_blank">cmap</a></div>
  108. <dl id="gfp-cmap-table"><dt>Undefined</dt></dl>
  109. <div class="gfp-collapsed">Font Variations table <a href="https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html" target="_blank">fvar</a></div>
  110. <dl id="gfp-fvar-table"><dt>Undefined</dt></dl>
  111. </div>
  112. <hr>
  113. <div>
  114. <div>Show unicode: <input class="gfp-show-unicode" type="checkbox"${showUnicode ? " checked" : ""}></div>
  115. Glyphs <span id="gfp-pagination"></span>
  116. <br>
  117. <div id="gfp-glyph-list-end"></div>
  118. </div>
  119. <div style="position: relative">
  120. <div id="gfp-glyph-display">
  121. <canvas id="gfp-glyph-bg" class="ghd-invert" width="500" height="500"></canvas>
  122. <canvas id="gfp-glyph" class="ghd-invert" width="500" height="500"></canvas>
  123. </div>
  124. <div id="gfp-glyph-data"></div>
  125. <div style="clear: both"></div>
  126. </div>
  127. <span style="font-size:0.8em">Powered by <a href="https://github.com/nodebox/opentype.js">opentype.js</a></span>
  128. </div>
  129. `;
  130. prepareGlyphList();
  131. // Add bindings for collapsible font data
  132. let tableHeaders = document.getElementById("gfp-font-data").getElementsByTagName("div"),
  133. indx = tableHeaders.length;
  134. while (indx--) {
  135. tableHeaders[indx].addEventListener("click", event => {
  136. event.target && event.target.classList.toggle("gfp-collapsed");
  137. }, false);
  138. }
  139. addBindings();
  140. }
  141.  
  142. function addBindings() {
  143. $(".gfp-show-unicode").addEventListener("change", function() {
  144. showUnicode = this.checked;
  145. GM_setValue("gfp-show-unicode", showUnicode);
  146. displayGlyphPage(pageSelected);
  147. return false;
  148. }, false);
  149.  
  150. $("#gfp-glyph-data").addEventListener("change", function() {
  151. showPoints = $(".gfp-show-points", this).checked;
  152. showArrows = $(".gfp-show-arrows", this).checked;
  153. GM_setValue("gfp-show-points", showPoints);
  154. GM_setValue("gfp-show-arrows", showArrows);
  155. cellSelect();
  156. return false;
  157. }, false);
  158. }
  159.  
  160. function $(selector, el) {
  161. return (el || document).querySelector(selector);
  162. }
  163.  
  164. function init() {
  165. // get file name from bread crumb
  166. let el = $(".final-path");
  167. // font extension supported?
  168. if (el && fontExt.test(el.textContent || "")) {
  169. getFont();
  170. }
  171. }
  172.  
  173. document.addEventListener("ghmo:container", init);
  174. init();
  175.  
  176. /* Code modified from http://opentype.js.org/ demos */
  177. GM_addStyle(`
  178. #gfp-wrapper { text-align:left; padding:20px; }
  179. #gfp-wrapper canvas { background-image:none !important; background-color:transparent !important; }
  180. .gfp-message { position:relative; top:-3px; padding:1px 5px; font-weight:bold; border-radius:2px; display:none; clear:both; }
  181. #gfp-glyphs { width:950px; }
  182. .gfp-info { float:right; font-size:14px; color:#999; }
  183. #gfp-wrapper hr { clear:both; border:none; border-bottom:1px solid #ccc; margin:20px 0 20px 0; padding:0; }
  184. /* Font Inspector */
  185. #gfp-font-data div { font-weight:normal; margin:0; cursor:pointer; }
  186. #gfp-font-data div:before { font-size:85%; content:"▼"; display:inline-block; margin-right:6px; transform:unset; }
  187. #gfp-font-data .gfp-collapsed:before { transform:rotate(-90deg); }
  188. #gfp-font-data div.gfp-collapsed + dl { display:none; }
  189. #gfp-font-data dl { margin-top:0; padding-left:2em; color:#777; }
  190. #gfp-font-data dt { float:left; }
  191. #gfp-font-data dd { margin-left: 12em; word-break:break-all; max-height:100px; overflow-y:auto; }
  192. #gfp-font-data .gfp-langtag { font-size:85%; color:#999; white-space:nowrap; }
  193. #gfp-font-data .gfp-langname { padding-right:0.5em; }
  194. #gfp-font-data .gfp-underline { border-bottom:1px solid #555; }
  195. /* Glyph Inspector */
  196. #gfp-pagination a { margin:0 0.3em; cursor:pointer; }
  197. #gfp-pagination .gfp-page-selected { font-weight:bold; cursor:default; -webkit-filter:brightness(150%); filter:brightness(150%); }
  198. canvas.gfp-item { float:left; border:solid 1px #a0a0a0; margin-right:-1px; margin-bottom:-1px; cursor:pointer; }
  199. canvas.gfp-item:hover { opacity:.8; }
  200. #gfp-glyph-list-end { clear:both; height:20px; }
  201. #gfp-glyph-display { float:left; border:solid 1px #a0a0a0; position:relative; width:500px; height:500px; }
  202. #gfp-glyph, #gfp-glyph-bg { position:absolute; top:0; left:0; border:0; }
  203. #gfp-glyph-data { float:left; margin-left:2em; }
  204. #gfp-glyph-data dl { margin:0; }
  205. #gfp-glyph-data dt { float:left; }
  206. #gfp-glyph-data dd { margin-left:12em; }
  207. #gfp-glyph-data pre { font-size:11px; }
  208. pre.gfp-path { margin:0; }
  209. pre.gfp-contour { margin:0 0 1em 2em; border-bottom:solid 1px #a0a0a0; }
  210. span.gfp-oncurve { color:var(--color-scale-blue-6); }
  211. span.gfp-offcurve { color:var(--color-scale-red-6); }
  212. .gfp-loading { display:block; margin:20px auto; border-radius:50%; border-width:2px; border-style:solid; border-color: transparent transparent #000 #000; width:30px; height:30px; animation:gfploading .5s infinite linear; }
  213. @keyframes gfploading { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
  214. `);
  215.  
  216. /*eslint-disable */
  217. /* Code copied from http://opentype.js.org/font-inspector.html */
  218. function escapeHtml(unsafe) {
  219. return unsafe
  220. .replace(/&/g, '&amp;')
  221. .replace(/</g, '&lt;')
  222. .replace(/>/g, '&gt;')
  223. .replace(/\u0022/g, '&quot;')
  224. .replace(/\u0027/g, '&#039;');
  225. }
  226.  
  227. function displayNames(names) {
  228. let indx, property, translations, langs, lang, langIndx, langLen, esclang,
  229. html = '',
  230. properties = Object.keys(names),
  231. len = properties.length;
  232. for (indx = 0; indx < len; indx++) {
  233. property = properties[indx];
  234. html += '<dt>' + escapeHtml(property) + '</dt><dd>';
  235. translations = names[property];
  236. langs = Object.keys(translations);
  237. langLen = langs.length;
  238. for (langIndx = 0; langIndx < langLen; langIndx++) {
  239. lang = langs[langIndx];
  240. esclang = escapeHtml(lang);
  241. html += '<span class="gfp-langtag">' + esclang +
  242. '</span> <span class="gfp-langname" lang=' + esclang + '>' +
  243. escapeHtml(translations[lang]) + '</span> ';
  244. }
  245. html += '</dd>';
  246. }
  247. document.getElementById('gfp-name-table').innerHTML = html;
  248. }
  249.  
  250. function displayFontData() {
  251. let html, tablename, table, property, value, element;
  252. for (tablename in font.tables) {
  253. if (font.tables.hasOwnProperty(tablename)) {
  254. table = font.tables[tablename];
  255. if (tablename === 'name') {
  256. displayNames(table);
  257. continue;
  258. }
  259. html = '';
  260. for (property in table) {
  261. if (table.hasOwnProperty(property)) {
  262. value = table[property];
  263. html += '<dt>' + property + '</dt><dd>';
  264. if (Array.isArray(value) && typeof value[0] === 'object') {
  265. html += value.map(item => {
  266. return JSON.stringify(item);
  267. }).join('<br>');
  268. } else if (typeof value === 'object') {
  269. html += JSON.stringify(value);
  270. } else {
  271. html += value;
  272. }
  273. html += '</dd>';
  274. }
  275. }
  276. element = document.getElementById('gfp-' + tablename + '-table');
  277. if (element) {
  278. element.innerHTML = html;
  279. }
  280. }
  281. }
  282. }
  283.  
  284. /* Code copied from http://opentype.js.org/glyph-inspector.html */
  285. const cellCount = 100,
  286. cellWidth = 62,
  287. cellHeight = 60,
  288. cellMarginTop = 1,
  289. cellMarginBottom = 8,
  290. cellMarginLeftRight = 1,
  291. glyphMargin = 5,
  292. pixelRatio = window.devicePixelRatio || 1,
  293. arrowLength = 10,
  294. arrowAperture = 4;
  295.  
  296. let pageSelected, fontScale, fontSize, fontBaseline, glyphScale, glyphSize, glyphBaseline;
  297.  
  298. function enableHighDPICanvas(canvas) {
  299. let pixelRatio, oldWidth, oldHeight;
  300. if (typeof canvas === 'string') {
  301. canvas = document.getElementById(canvas);
  302. }
  303. pixelRatio = window.devicePixelRatio || 1;
  304. if (pixelRatio === 1) {
  305. return;
  306. }
  307. oldWidth = canvas.width;
  308. oldHeight = canvas.height;
  309. canvas.width = oldWidth * pixelRatio;
  310. canvas.height = oldHeight * pixelRatio;
  311. canvas.style.width = oldWidth + 'px';
  312. canvas.style.height = oldHeight + 'px';
  313. canvas.getContext('2d').scale(pixelRatio, pixelRatio);
  314. }
  315.  
  316. function showErrorMessage(message) {
  317. let el = $('.gfp-message');
  318. el.style.display = (!message || message.trim().length === 0) ? 'none' : 'block';
  319. el.innerHTML = message;
  320. }
  321.  
  322. function pathCommandToString(cmd) {
  323. let str = '<strong>' + cmd.type + '</strong> ' +
  324. ((cmd.x !== undefined) ? 'x=' + cmd.x + ' y=' + cmd.y + ' ' : '') +
  325. ((cmd.x1 !== undefined) ? 'x1=' + cmd.x1 + ' y1=' + cmd.y1 + ' ' : '') +
  326. ((cmd.x2 !== undefined) ? 'x2=' + cmd.x2 + ' y2=' + cmd.y2 : '');
  327. return str;
  328. }
  329.  
  330. function contourToString(contour) {
  331. return '<pre class="gfp-contour">' + contour.map(point => {
  332. return '<span class="gfp-' + (point.onCurve ? 'oncurve' : 'offcurve') +
  333. '">x=' + point.x + ' y=' + point.y + '</span>';
  334. }).join('\n') + '</pre>';
  335. }
  336.  
  337. function formatUnicode(unicode) {
  338. unicode = unicode.toString(16);
  339. if (unicode.length > 4) {
  340. return ('000000' + unicode.toUpperCase()).substr(-6);
  341. } else {
  342. return ('0000' + unicode.toUpperCase()).substr(-4);
  343. }
  344. }
  345.  
  346. function displayGlyphData(glyphIndex) {
  347. let glyph, contours, html,
  348. container = document.getElementById('gfp-glyph-data'),
  349. addItem = name => {
  350. return glyph[name] ? `<dt>${name}</dt><dd>${glyph[name]}</dd>` : '';
  351. };
  352. if (glyphIndex < 0) {
  353. container.innerHTML = '';
  354. return;
  355. }
  356. glyph = font.glyphs.get(glyphIndex);
  357. html = `<dl>
  358. <dt>Show points</dt>
  359. <dd><input class="gfp-show-points" type="checkbox"${showPoints ? ' checked' : ''}></dd>
  360. <dt>Show arrows</dt>
  361. <dd><input class="gfp-show-arrows" type="checkbox"${showArrows ? ' checked' : ''}></dd>
  362. <dt>name</dt><dd>${glyph.name}</dd>`;
  363.  
  364. if (glyph.unicode) {
  365. html += '<dt>unicode</dt><dd>' + glyph.unicodes.map(formatUnicode).join(', ') + '</dd>';
  366. }
  367. html += addItem('index') +
  368. addItem('xMin') +
  369. addItem('xMax') +
  370. addItem('yMin') +
  371. addItem('yMax') +
  372. addItem('advanceWidth') +
  373. addItem('leftSideBearing') +
  374. '</dl>';
  375.  
  376. if (glyph.numberOfContours > 0) {
  377. contours = glyph.getContours();
  378. html += 'contours:<br>' + contours.map(contourToString).join('\n');
  379. } else if (glyph.isComposite) {
  380. html += '<br>This composite glyph is a combination of :<ul><li>' +
  381. glyph.components.map(component => {
  382. return 'glyph ' + component.glyphIndex + ' at dx=' + component.dx +
  383. ', dy=' + component.dy;
  384. }).join('</li><li>') + '</li></ul>';
  385. } else if (glyph.path) {
  386. html += 'path:<br><pre class="gfp-path"> ' +
  387. glyph.path.commands.map(pathCommandToString).join('\n ') + '\n</pre>';
  388. }
  389. container.innerHTML = html;
  390. }
  391.  
  392. function drawArrow(ctx, x1, y1, x2, y2) {
  393. let dx = x2 - x1,
  394. dy = y2 - y1,
  395. segmentLength = Math.sqrt(dx * dx + dy * dy),
  396. unitx = dx / segmentLength,
  397. unity = dy / segmentLength,
  398. basex = x2 - arrowLength * unitx,
  399. basey = y2 - arrowLength * unity,
  400. normalx = arrowAperture * unity,
  401. normaly = -arrowAperture * unitx;
  402. ctx.beginPath();
  403. ctx.moveTo(x2, y2);
  404. ctx.lineTo(basex + normalx, basey + normaly);
  405. ctx.lineTo(basex - normalx, basey - normaly);
  406. ctx.lineTo(x2, y2);
  407. ctx.closePath();
  408. ctx.fill();
  409. }
  410.  
  411. /**
  412. * This function is Path.prototype.draw with an arrow
  413. * at the end of each contour.
  414. */
  415. function drawPathWithArrows(ctx, path) {
  416. let indx, cmd, x1, y1, x2, y2,
  417. arrows = [],
  418. len = path.commands.length;
  419. ctx.beginPath();
  420. for (indx = 0; indx < len; indx++) {
  421. cmd = path.commands[indx];
  422. if (cmd.type === 'M') {
  423. if (x1 !== undefined) {
  424. arrows.push([ctx, x1, y1, x2, y2]);
  425. }
  426. ctx.moveTo(cmd.x, cmd.y);
  427. } else if (cmd.type === 'L') {
  428. ctx.lineTo(cmd.x, cmd.y);
  429. x1 = x2;
  430. y1 = y2;
  431. } else if (cmd.type === 'C') {
  432. ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
  433. x1 = cmd.x2;
  434. y1 = cmd.y2;
  435. } else if (cmd.type === 'Q') {
  436. ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y);
  437. x1 = cmd.x1;
  438. y1 = cmd.y1;
  439. } else if (cmd.type === 'Z') {
  440. arrows.push([ctx, x1, y1, x2, y2]);
  441. ctx.closePath();
  442. }
  443. x2 = cmd.x;
  444. y2 = cmd.y;
  445. }
  446. if (path.fill) {
  447. ctx.fillStyle = path.fill;
  448. ctx.fill();
  449. }
  450. if (path.stroke) {
  451. ctx.strokeStyle = path.stroke;
  452. ctx.lineWidth = path.strokeWidth;
  453. ctx.stroke();
  454. }
  455. ctx.fillStyle = bigGlyphStrokeColor;
  456. if (showArrows) {
  457. arrows.forEach(arrow => {
  458. drawArrow.apply(null, arrow);
  459. });
  460. }
  461. }
  462.  
  463. function displayGlyph(glyphIndex) {
  464. let glyph, glyphWidth, xmin, xmax, x0, markSize, path,
  465. canvas = document.getElementById('gfp-glyph'),
  466. ctx = canvas.getContext('2d'),
  467. width = canvas.width / pixelRatio,
  468. height = canvas.height / pixelRatio;
  469. ctx.clearRect(0, 0, width, height);
  470. if (glyphIndex < 0) {
  471. return;
  472. }
  473. glyph = font.glyphs.get(glyphIndex);
  474. glyphWidth = glyph.advanceWidth * glyphScale;
  475. xmin = (width - glyphWidth) / 2;
  476. xmax = (width + glyphWidth) / 2;
  477. x0 = xmin;
  478. markSize = 10;
  479.  
  480. ctx.fillStyle = bigGlyphMarkerColor;
  481. ctx.fillRect(xmin - markSize + 1, glyphBaseline, markSize, 1);
  482. ctx.fillRect(xmin, glyphBaseline, 1, markSize);
  483. ctx.fillRect(xmax, glyphBaseline, markSize, 1);
  484. ctx.fillRect(xmax, glyphBaseline, 1, markSize);
  485. ctx.textAlign = 'center';
  486. ctx.fillText('0', xmin, glyphBaseline + markSize + 10);
  487. ctx.fillText(glyph.advanceWidth, xmax, glyphBaseline + markSize + 10);
  488.  
  489. ctx.fillStyle = bigGlyphStrokeColor;
  490. path = glyph.getPath(x0, glyphBaseline, glyphSize);
  491. path.fill = glyphFillColor;
  492. path.stroke = bigGlyphStrokeColor;
  493. path.strokeWidth = 1.5;
  494. drawPathWithArrows(ctx, path);
  495. if (showPoints) {
  496. glyph.drawPoints(ctx, x0, glyphBaseline, glyphSize);
  497. }
  498. }
  499.  
  500. function renderGlyphItem(canvas, glyphIndex) {
  501. const cellMarkSize = 4,
  502. ctx = canvas.getContext('2d');
  503. ctx.clearRect(0, 0, cellWidth, cellHeight);
  504. if (glyphIndex >= font.numGlyphs) {
  505. return;
  506. }
  507.  
  508. ctx.fillStyle = miniGlyphMarkerColor;
  509. ctx.font = '10px sans-serif';
  510. let glyph = font.glyphs.get(glyphIndex),
  511. glyphWidth = glyph.advanceWidth * fontScale,
  512. xmin = (cellWidth - glyphWidth) / 2,
  513. xmax = (cellWidth + glyphWidth) / 2,
  514. x0 = xmin;
  515.  
  516. ctx.fillText(showUnicode ? glyph.unicodes.map(formatUnicode).join(', ') : glyphIndex, 1, cellHeight - 1);
  517.  
  518. ctx.fillStyle = glyphRulerColor;
  519. ctx.fillRect(xmin - cellMarkSize + 1, fontBaseline, cellMarkSize, 1);
  520. ctx.fillRect(xmin, fontBaseline, 1, cellMarkSize);
  521. ctx.fillRect(xmax, fontBaseline, cellMarkSize, 1);
  522. ctx.fillRect(xmax, fontBaseline, 1, cellMarkSize);
  523.  
  524. ctx.fillStyle = '#000000';
  525. let path = glyph.getPath(x0, fontBaseline, fontSize);
  526. path.fill = glyphFillColor;
  527. path.draw(ctx);
  528. }
  529.  
  530. function displayGlyphPage(pageNum) {
  531. pageSelected = pageNum;
  532. const last = $('.gfp-page-selected');
  533. if (last) last.className = '';
  534. document.getElementById('gfp-p' + pageNum).className = 'gfp-page-selected';
  535. let indx,
  536. firstGlyph = pageNum * cellCount;
  537. for (indx = 0; indx < cellCount; indx++) {
  538. renderGlyphItem(document.getElementById('gfp-g' + indx), firstGlyph + indx);
  539. }
  540. }
  541.  
  542. function pageSelect(event) {
  543. displayGlyphPage((event.target.id || '').replace('gfp-p', ''));
  544. }
  545.  
  546. function initGlyphDisplay() {
  547. let glyphBgCanvas = document.getElementById('gfp-glyph-bg'),
  548. w = glyphBgCanvas.width / pixelRatio,
  549. h = glyphBgCanvas.height / pixelRatio,
  550. glyphW = w - glyphMargin * 2,
  551. glyphH = h - glyphMargin * 2,
  552. head = font.tables.head,
  553. maxHeight = head.yMax - head.yMin,
  554. ctx = glyphBgCanvas.getContext('2d');
  555.  
  556. glyphScale = Math.min(glyphW / (head.xMax - head.xMin), glyphH / maxHeight);
  557. glyphSize = glyphScale * font.unitsPerEm;
  558. glyphBaseline = glyphMargin + glyphH * head.yMax / maxHeight;
  559.  
  560. function hline(text, yunits) {
  561. let ypx = glyphBaseline - yunits * glyphScale;
  562. ctx.fillText(text, 2, ypx + 3);
  563. ctx.fillRect(80, ypx, w, 1);
  564. }
  565.  
  566. ctx.clearRect(0, 0, w, h);
  567. ctx.fillStyle = glyphRulerColor;
  568. hline('Baseline', 0);
  569. hline('yMax', font.tables.head.yMax);
  570. hline('yMin', font.tables.head.yMin);
  571. hline('Ascender', font.tables.hhea.ascender);
  572. hline('Descender', font.tables.hhea.descender);
  573. hline('Typo Ascender', font.tables.os2.sTypoAscender);
  574. hline('Typo Descender', font.tables.os2.sTypoDescender);
  575. }
  576.  
  577. function onFontLoaded(font) {
  578. let indx, link, lastIndex,
  579. w = cellWidth - cellMarginLeftRight * 2,
  580. h = cellHeight - cellMarginTop - cellMarginBottom,
  581. head = font.tables.head,
  582. maxHeight = head.yMax - head.yMin,
  583. pagination = document.getElementById('gfp-pagination'),
  584. fragment = document.createDocumentFragment(),
  585. numPages = Math.ceil(font.numGlyphs / cellCount);
  586.  
  587. fontScale = Math.min(w / (head.xMax - head.xMin), h / maxHeight);
  588. fontSize = fontScale * font.unitsPerEm;
  589. fontBaseline = cellMarginTop + h * head.yMax / maxHeight;
  590. pagination.innerHTML = '';
  591.  
  592. for (indx = 0; indx < numPages; indx++) {
  593. link = document.createElement('a');
  594. lastIndex = Math.min(font.numGlyphs - 1, (indx + 1) * cellCount - 1);
  595. link.textContent = indx * cellCount + '-' + lastIndex;
  596. link.id = 'gfp-p' + indx;
  597. link.addEventListener('click', pageSelect, false);
  598. fragment.appendChild(link);
  599. // A white space allows to break very long lines into multiple lines.
  600. // This is needed for fonts with thousands of glyphs.
  601. fragment.appendChild(document.createTextNode(' '));
  602. }
  603. pagination.appendChild(fragment);
  604.  
  605. displayFontData();
  606. initGlyphDisplay();
  607. displayGlyphPage(0);
  608. displayGlyph(-1);
  609. displayGlyphData(-1);
  610. }
  611.  
  612. function cellSelect(event) {
  613. if (!font) {
  614. return;
  615. }
  616. let firstGlyphIndex = pageSelected * cellCount,
  617. cellIndex = event ? +event.target.id.replace('gfp-g', '') : currentIndex,
  618. glyphIndex = firstGlyphIndex + cellIndex;
  619. currentIndex = cellIndex;
  620. if (glyphIndex < font.numGlyphs) {
  621. displayGlyph(glyphIndex);
  622. displayGlyphData(glyphIndex);
  623. }
  624. }
  625.  
  626. function prepareGlyphList() {
  627. let indx, canvas,
  628. marker = document.getElementById('gfp-glyph-list-end'),
  629. parent = marker.parentElement;
  630. for (indx = 0; indx < cellCount; indx++) {
  631. canvas = document.createElement('canvas');
  632. canvas.width = cellWidth;
  633. canvas.height = cellHeight;
  634. canvas.className = 'gfp-item ghd-invert';
  635. canvas.id = 'gfp-g' + indx;
  636. canvas.addEventListener('click', cellSelect, false);
  637. enableHighDPICanvas(canvas);
  638. parent.insertBefore(canvas, marker);
  639. }
  640. }
  641. /* eslint-enable */
  642.  
  643. })();