GitHub Font Preview

A userscript that adds a font file preview

目前為 2016-12-29 提交的版本,檢視 最新版本

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