GitHub Font Preview

A userscript that adds a font file preview

当前为 2020-09-08 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name GitHub Font Preview
  3. // @version 1.0.22
  4. // @description A userscript that adds a font file preview
  5. // @license MIT
  6. // @author Rob Garrison
  7. // @namespace https://github.com/Mottie
  8. // @include 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://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=666427
  17. // @require https://greasyfork.org/scripts/20469-opentype-js/code/opentypejs.js?version=130870
  18. // @icon https://github.githubassets.com/pinned-octocat.svg
  19. // ==/UserScript==
  20. /* global opentype */
  21. (() => {
  22. "use strict";
  23.  
  24. let font;
  25. let showUnicode = GM_getValue("gfp-show-unicode", false);
  26. let showPoints = GM_getValue("gfp-show-points", true);
  27. let showArrows = GM_getValue("gfp-show-arrows", true);
  28. let currentIndex = 0;
  29.  
  30. // supported font types
  31. const fontExt = /\.(otf|ttf|woff)$/i;
  32.  
  33. // canvas colors
  34. const glyphFillColor = "#808080"; // (big) (mini) fill color
  35. const bigGlyphStrokeColor = "#111111"; // (big) stroke color
  36. const bigGlyphMarkerColor = "#f00"; // (big) min & max width marker
  37. const miniGlyphMarkerColor = "#606060"; // (mini) glyph index (bottom left corner)
  38. const glyphRulerColor = "#a0a0a0"; // (mini) min & max width marker & (big) glyph horizontal lines
  39.  
  40. function startLoad() {
  41. const block = $(".blob-wrapper a[href*='?raw=true']");
  42. const body = block && block.closest(".Box-body");
  43. if (body) {
  44. body.classList.add("ghfp-body");
  45. body.innerHTML = "<span class='gfp-loading ghd-invert'></span>";
  46. }
  47. return block && block.href;
  48. }
  49.  
  50. function getFont() {
  51. const url = startLoad();
  52. if (url) {
  53. // add loading indicator
  54. GM_xmlhttpRequest({
  55. method: "GET",
  56. url,
  57. responseType: "arraybuffer",
  58. onload: response => {
  59. setupFont(response.response);
  60. }
  61. });
  62. }
  63. }
  64.  
  65. function setupFont(data) {
  66. const block = $(".ghfp-body");
  67. const el = $(".final-path");
  68. if (block && el) {
  69. try {
  70. font = opentype.parse(data);
  71. addHTML(block, el);
  72. showErrorMessage("");
  73. onFontLoaded(font);
  74. } catch (err) {
  75. block.innerHTML = "<h2 class='gfp-message cdel'></h2>";
  76. showErrorMessage(err.toString());
  77. if (err.stack) {
  78. console.error(err.stack);
  79. }
  80. throw (err);
  81. }
  82. }
  83. }
  84.  
  85. function addHTML(block, el) {
  86. let name = el.textContent || "";
  87. block.innerHTML = `
  88. <div id="gfp-wrapper">
  89. <span class="gfp-info" id="gfp-font-name">${name}</span>
  90. <h2 class="gfp-message cdel"></h2>
  91. <hr>
  92. <div id="gfp-font-data">
  93. <div class="gfp-collapsed">Font Header table <a href="https://www.microsoft.com/typography/OTSPEC/head.htm" target="_blank">head</a></div>
  94. <dl id="gfp-head-table"><dt>Undefined</dt></dl>
  95. <div class="gfp-collapsed">Horizontal Header table <a href="https://www.microsoft.com/typography/OTSPEC/hhea.htm" target="_blank">hhea</a></div>
  96. <dl id="gfp-hhea-table"><dt>Undefined</dt></dl>
  97. <div class="gfp-collapsed">Maximum Profile table <a href="https://www.microsoft.com/typography/OTSPEC/maxp.htm" target="_blank">maxp</a></div>
  98. <dl id="gfp-maxp-table"><dt>Undefined</dt></dl>
  99. <div class="gfp-collapsed">Naming table <a href="https://www.microsoft.com/typography/OTSPEC/name.htm" target="_blank">name</a></div>
  100. <dl id="gfp-name-table"><dt>Undefined</dt></dl>
  101. <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>
  102. <dl id="gfp-os2-table"><dt>Undefined</dt></dl>
  103. <div class="gfp-collapsed">PostScript table <a href="https://www.microsoft.com/typography/OTSPEC/post.htm" target="_blank">post</a></div>
  104. <dl id="gfp-post-table"><dt>Undefined</dt></dl>
  105. <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>
  106. <dl id="gfp-cmap-table"><dt>Undefined</dt></dl>
  107. <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>
  108. <dl id="gfp-fvar-table"><dt>Undefined</dt></dl>
  109. </div>
  110. <hr>
  111. <div>
  112. <div>Show unicode: <input class="gfp-show-unicode" type="checkbox"${showUnicode ? " checked" : ""}></div>
  113. Glyphs <span id="gfp-pagination"></span>
  114. <br>
  115. <div id="gfp-glyph-list-end"></div>
  116. </div>
  117. <div style="position: relative">
  118. <div id="gfp-glyph-display">
  119. <canvas id="gfp-glyph-bg" class="ghd-invert" width="500" height="500"></canvas>
  120. <canvas id="gfp-glyph" class="ghd-invert" width="500" height="500"></canvas>
  121. </div>
  122. <div id="gfp-glyph-data"></div>
  123. <div style="clear: both"></div>
  124. </div>
  125. <span style="font-size:0.8em">Powered by <a href="https://github.com/nodebox/opentype.js">opentype.js</a></span>
  126. </div>
  127. `;
  128. prepareGlyphList();
  129. // Add bindings for collapsible font data
  130. let tableHeaders = document.getElementById("gfp-font-data").getElementsByTagName("div"),
  131. indx = tableHeaders.length;
  132. while (indx--) {
  133. tableHeaders[indx].addEventListener("click", event => {
  134. event.target && event.target.classList.toggle("gfp-collapsed");
  135. }, false);
  136. }
  137. addBindings();
  138. }
  139.  
  140. function addBindings() {
  141. $(".gfp-show-unicode").addEventListener("change", function() {
  142. showUnicode = this.checked;
  143. GM_setValue("gfp-show-unicode", showUnicode);
  144. displayGlyphPage(pageSelected);
  145. return false;
  146. }, false);
  147.  
  148. $("#gfp-glyph-data").addEventListener("change", function() {
  149. showPoints = $(".gfp-show-points", this).checked;
  150. showArrows = $(".gfp-show-arrows", this).checked;
  151. GM_setValue("gfp-show-points", showPoints);
  152. GM_setValue("gfp-show-arrows", showArrows);
  153. cellSelect();
  154. return false;
  155. }, false);
  156. }
  157.  
  158. function $(selector, el) {
  159. return (el || document).querySelector(selector);
  160. }
  161.  
  162. function init() {
  163. // get file name from bread crumb
  164. let el = $(".final-path");
  165. // font extension supported?
  166. if (el && fontExt.test(el.textContent || "")) {
  167. getFont();
  168. }
  169. }
  170.  
  171. document.addEventListener("ghmo:container", init);
  172. init();
  173.  
  174. /* Code modified from http://opentype.js.org/ demos */
  175. GM_addStyle(`
  176. #gfp-wrapper { text-align:left; padding:20px; }
  177. #gfp-wrapper canvas { background-image:none !important; background-color:transparent !important; }
  178. .gfp-message { position:relative; top:-3px; padding:1px 5px; font-weight:bold; border-radius:2px; display:none; clear:both; }
  179. #gfp-glyphs { width:950px; }
  180. .gfp-info { float:right; font-size:14px; color:#999; }
  181. #gfp-wrapper hr { clear:both; border:none; border-bottom:1px solid #ccc; margin:20px 0 20px 0; padding:0; }
  182. /* Font Inspector */
  183. #gfp-font-data div { font-weight:normal; margin:0; cursor:pointer; }
  184. #gfp-font-data div:before { font-size:85%; content:"▼"; display:inline-block; margin-right:6px; transform:unset; }
  185. #gfp-font-data .gfp-collapsed:before { transform:rotate(-90deg); }
  186. #gfp-font-data div.gfp-collapsed + dl { display:none; }
  187. #gfp-font-data dl { margin-top:0; padding-left:2em; color:#777; }
  188. #gfp-font-data dt { float:left; }
  189. #gfp-font-data dd { margin-left: 12em; word-break:break-all; max-height:100px; overflow-y:auto; }
  190. #gfp-font-data .gfp-langtag { font-size:85%; color:#999; white-space:nowrap; }
  191. #gfp-font-data .gfp-langname { padding-right:0.5em; }
  192. #gfp-font-data .gfp-underline { border-bottom:1px solid #555; }
  193. /* Glyph Inspector */
  194. #gfp-pagination span { margin:0 0.3em; cursor:pointer; }
  195. #gfp-pagination span.gfp-page-selected { font-weight:bold; cursor:default; -webkit-filter:brightness(150%); filter:brightness(150%); }
  196. canvas.gfp-item { float:left; border:solid 1px #a0a0a0; margin-right:-1px; margin-bottom:-1px; cursor:pointer; }
  197. canvas.gfp-item:hover { opacity:.8; }
  198. #gfp-glyph-list-end { clear:both; height:20px; }
  199. #gfp-glyph-display { float:left; border:solid 1px #a0a0a0; position:relative; width:500px; height:500px; }
  200. #gfp-glyph, #gfp-glyph-bg { position:absolute; top:0; left:0; border:0; }
  201. #gfp-glyph-data { float:left; margin-left:2em; }
  202. #gfp-glyph-data dl { margin:0; }
  203. #gfp-glyph-data dt { float:left; }
  204. #gfp-glyph-data dd { margin-left:12em; }
  205. #gfp-glyph-data pre { font-size:11px; }
  206. pre.gfp-path { margin:0; }
  207. pre.gfp-contour { margin:0 0 1em 2em; border-bottom:solid 1px #a0a0a0; }
  208. span.gfp-oncurve { color:blue; }
  209. span.gfp-offcurve { color:red; }
  210. .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; }
  211. @keyframes gfploading { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
  212. `);
  213.  
  214. /*eslint-disable */
  215. /* Code copied from http://opentype.js.org/font-inspector.html */
  216. function escapeHtml(unsafe) {
  217. return unsafe
  218. .replace(/&/g, '&amp;')
  219. .replace(/</g, '&lt;')
  220. .replace(/>/g, '&gt;')
  221. .replace(/\u0022/g, '&quot;')
  222. .replace(/\u0027/g, '&#039;');
  223. }
  224.  
  225. function displayNames(names) {
  226. let indx, property, translations, langs, lang, langIndx, langLen, esclang,
  227. html = '',
  228. properties = Object.keys(names),
  229. len = properties.length;
  230. for (indx = 0; indx < len; indx++) {
  231. property = properties[indx];
  232. html += '<dt>' + escapeHtml(property) + '</dt><dd>';
  233. translations = names[property];
  234. langs = Object.keys(translations);
  235. langLen = langs.length;
  236. for (langIndx = 0; langIndx < langLen; langIndx++) {
  237. lang = langs[langIndx];
  238. esclang = escapeHtml(lang);
  239. html += '<span class="gfp-langtag">' + esclang +
  240. '</span> <span class="gfp-langname" lang=' + esclang + '>' +
  241. escapeHtml(translations[lang]) + '</span> ';
  242. }
  243. html += '</dd>';
  244. }
  245. document.getElementById('gfp-name-table').innerHTML = html;
  246. }
  247.  
  248. function displayFontData() {
  249. let html, tablename, table, property, value, element;
  250. for (tablename in font.tables) {
  251. if (font.tables.hasOwnProperty(tablename)) {
  252. table = font.tables[tablename];
  253. if (tablename === 'name') {
  254. displayNames(table);
  255. continue;
  256. }
  257. html = '';
  258. for (property in table) {
  259. if (table.hasOwnProperty(property)) {
  260. value = table[property];
  261. html += '<dt>' + property + '</dt><dd>';
  262. if (Array.isArray(value) && typeof value[0] === 'object') {
  263. html += value.map(item => {
  264. return JSON.stringify(item);
  265. }).join('<br>');
  266. } else if (typeof value === 'object') {
  267. html += JSON.stringify(value);
  268. } else {
  269. html += value;
  270. }
  271. html += '</dd>';
  272. }
  273. }
  274. element = document.getElementById('gfp-' + tablename + '-table');
  275. if (element) {
  276. element.innerHTML = html;
  277. }
  278. }
  279. }
  280. }
  281.  
  282. /* Code copied from http://opentype.js.org/glyph-inspector.html */
  283. const cellCount = 100,
  284. cellWidth = 62,
  285. cellHeight = 60,
  286. cellMarginTop = 1,
  287. cellMarginBottom = 8,
  288. cellMarginLeftRight = 1,
  289. glyphMargin = 5,
  290. pixelRatio = window.devicePixelRatio || 1,
  291. arrowLength = 10,
  292. arrowAperture = 4;
  293.  
  294. let pageSelected, fontScale, fontSize, fontBaseline, glyphScale, glyphSize, glyphBaseline;
  295.  
  296. function enableHighDPICanvas(canvas) {
  297. let pixelRatio, oldWidth, oldHeight;
  298. if (typeof canvas === 'string') {
  299. canvas = document.getElementById(canvas);
  300. }
  301. pixelRatio = window.devicePixelRatio || 1;
  302. if (pixelRatio === 1) {
  303. return;
  304. }
  305. oldWidth = canvas.width;
  306. oldHeight = canvas.height;
  307. canvas.width = oldWidth * pixelRatio;
  308. canvas.height = oldHeight * pixelRatio;
  309. canvas.style.width = oldWidth + 'px';
  310. canvas.style.height = oldHeight + 'px';
  311. canvas.getContext('2d').scale(pixelRatio, pixelRatio);
  312. }
  313.  
  314. function showErrorMessage(message) {
  315. let el = $('.gfp-message');
  316. el.style.display = (!message || message.trim().length === 0) ? 'none' : 'block';
  317. el.innerHTML = message;
  318. }
  319.  
  320. function pathCommandToString(cmd) {
  321. let str = '<strong>' + cmd.type + '</strong> ' +
  322. ((cmd.x !== undefined) ? 'x=' + cmd.x + ' y=' + cmd.y + ' ' : '') +
  323. ((cmd.x1 !== undefined) ? 'x1=' + cmd.x1 + ' y1=' + cmd.y1 + ' ' : '') +
  324. ((cmd.x2 !== undefined) ? 'x2=' + cmd.x2 + ' y2=' + cmd.y2 : '');
  325. return str;
  326. }
  327.  
  328. function contourToString(contour) {
  329. return '<pre class="gfp-contour">' + contour.map(point => {
  330. // ".text-blue" class modified by GitHub Dark style
  331. // ".cdel" class modified by GitHub Dark style - more readable red
  332. return '<span class="gfp-' + (point.onCurve ? 'oncurve text-blue' : 'offcurve cdel') +
  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. document.getElementById('gfp-p' + pageNum).className = 'gfp-page-selected';
  533. let indx,
  534. firstGlyph = pageNum * cellCount;
  535. for (indx = 0; indx < cellCount; indx++) {
  536. renderGlyphItem(document.getElementById('gfp-g' + indx), firstGlyph + indx);
  537. }
  538. }
  539.  
  540. function pageSelect(event) {
  541. document.getElementsByClassName('gfp-page-selected')[0].className = 'text-blue';
  542. displayGlyphPage((event.target.id || '').replace('gfp-p', ''));
  543. }
  544.  
  545. function initGlyphDisplay() {
  546. let glyphBgCanvas = document.getElementById('gfp-glyph-bg'),
  547. w = glyphBgCanvas.width / pixelRatio,
  548. h = glyphBgCanvas.height / pixelRatio,
  549. glyphW = w - glyphMargin * 2,
  550. glyphH = h - glyphMargin * 2,
  551. head = font.tables.head,
  552. maxHeight = head.yMax - head.yMin,
  553. ctx = glyphBgCanvas.getContext('2d');
  554.  
  555. glyphScale = Math.min(glyphW / (head.xMax - head.xMin), glyphH / maxHeight);
  556. glyphSize = glyphScale * font.unitsPerEm;
  557. glyphBaseline = glyphMargin + glyphH * head.yMax / maxHeight;
  558.  
  559. function hline(text, yunits) {
  560. let ypx = glyphBaseline - yunits * glyphScale;
  561. ctx.fillText(text, 2, ypx + 3);
  562. ctx.fillRect(80, ypx, w, 1);
  563. }
  564.  
  565. ctx.clearRect(0, 0, w, h);
  566. ctx.fillStyle = glyphRulerColor;
  567. hline('Baseline', 0);
  568. hline('yMax', font.tables.head.yMax);
  569. hline('yMin', font.tables.head.yMin);
  570. hline('Ascender', font.tables.hhea.ascender);
  571. hline('Descender', font.tables.hhea.descender);
  572. hline('Typo Ascender', font.tables.os2.sTypoAscender);
  573. hline('Typo Descender', font.tables.os2.sTypoDescender);
  574. }
  575.  
  576. function onFontLoaded(font) {
  577. let indx, link, lastIndex,
  578. w = cellWidth - cellMarginLeftRight * 2,
  579. h = cellHeight - cellMarginTop - cellMarginBottom,
  580. head = font.tables.head,
  581. maxHeight = head.yMax - head.yMin,
  582. pagination = document.getElementById('gfp-pagination'),
  583. fragment = document.createDocumentFragment(),
  584. numPages = Math.ceil(font.numGlyphs / cellCount);
  585.  
  586. fontScale = Math.min(w / (head.xMax - head.xMin), h / maxHeight);
  587. fontSize = fontScale * font.unitsPerEm;
  588. fontBaseline = cellMarginTop + h * head.yMax / maxHeight;
  589. pagination.innerHTML = '';
  590.  
  591. for (indx = 0; indx < numPages; indx++) {
  592. link = document.createElement('span');
  593. lastIndex = Math.min(font.numGlyphs - 1, (indx + 1) * cellCount - 1);
  594. link.textContent = indx * cellCount + '-' + lastIndex;
  595. link.id = 'gfp-p' + indx;
  596. link.className = 'text-blue';
  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. })();