GitHub Font Preview

A userscript that adds a font file preview

目前為 2019-06-07 提交的版本,檢視 最新版本

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