GitHub Font Preview

A userscript that adds a font file preview

Από την 13/06/2016. Δείτε την τελευταία έκδοση.

  1. // ==UserScript==
  2. // @name GitHub Font Preview
  3. // @version 1.0.2
  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, targets, 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. bigGlyphStrokeColor = '#111111', // (big) stroke color
  35. bigGlyphFillColor = '#808080', // (big) fill 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. document.querySelector('.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 = document.querySelector('.file .image');
  58. if (target) {
  59. try {
  60. font = opentype.parse(data);
  61. addHTML(target);
  62. showErrorMessage('');
  63. onFontLoaded(font);
  64. } catch (err) {
  65. target.innerHTML = '<h2 class="gfp-message cdel"></h2>';
  66. showErrorMessage(err.toString());
  67. if (err.stack) {
  68. console.error(err.stack);
  69. }
  70. throw(err);
  71. }
  72. }
  73. busy = false;
  74. }
  75.  
  76. function addHTML(target) {
  77. let name = document.querySelector('.final-path').textContent || '';
  78. target.innerHTML = `
  79. <div id="gfp-wrapper">
  80. <span class="gfp-info" id="gfp-font-name">${name}</span>
  81. <h2 class="gfp-message cdel"></h2>
  82. <hr>
  83. <div id="gfp-font-data">
  84. <div class="gfp-collapsed">Font Header table <a href="https://www.microsoft.com/typography/OTSPEC/head.htm" target="_blank">head</a></div>
  85. <dl id="gfp-head-table"><dt>Undefined</dt></dl>
  86. <div class="gfp-collapsed">Horizontal Header table <a href="https://www.microsoft.com/typography/OTSPEC/hhea.htm" target="_blank">hhea</a></div>
  87. <dl id="gfp-hhea-table"><dt>Undefined</dt></dl>
  88. <div class="gfp-collapsed">Maximum Profile table <a href="https://www.microsoft.com/typography/OTSPEC/maxp.htm" target="_blank">maxp</a></div>
  89. <dl id="gfp-maxp-table"><dt>Undefined</dt></dl>
  90. <div class="gfp-collapsed">Naming table <a href="https://www.microsoft.com/typography/OTSPEC/name.htm" target="_blank">name</a></div>
  91. <dl id="gfp-name-table"><dt>Undefined</dt></dl>
  92. <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>
  93. <dl id="gfp-os2-table"><dt>Undefined</dt></dl>
  94. <div class="gfp-collapsed">PostScript table <a href="https://www.microsoft.com/typography/OTSPEC/post.htm" target="_blank">post</a></div>
  95. <dl id="gfp-post-table"><dt>Undefined</dt></dl>
  96. <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>
  97. <dl id="gfp-cmap-table"><dt>Undefined</dt></dl>
  98. <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>
  99. <dl id="gfp-fvar-table"><dt>Undefined</dt></dl>
  100. </div>
  101. <hr>
  102. <div>
  103. <div>Show unicode: <input class="gfp-show-unicode" type="checkbox"${showUnicode ? ' checked' : ''}></div>
  104. Glyphs <span id="gfp-pagination"></span>
  105. <br>
  106. <div id="gfp-glyph-list-end"></div>
  107. </div>
  108. <div style="position: relative">
  109. <div id="gfp-glyph-display">
  110. <canvas id="gfp-glyph-bg" class="ghd-invert" width="500" height="500"></canvas>
  111. <canvas id="gfp-glyph" class="ghd-invert" width="500" height="500"></canvas>
  112. </div>
  113. <div id="gfp-glyph-data"></div>
  114. <div style="clear: both"></div>
  115. </div>
  116. <span style="font-size:0.8em">Powered by <a href="https://github.com/nodebox/opentype.js">opentype.js</a></span>
  117. </div>
  118. `;
  119. prepareGlyphList();
  120. // Add bindings for collapsible font data
  121. let tableHeaders = document.getElementById('gfp-font-data').getElementsByTagName('div'),
  122. indx = tableHeaders.length;
  123. while (indx--) {
  124. tableHeaders[indx].addEventListener('click', function(e) {
  125. e.target.classList.toggle('gfp-collapsed');
  126. }, false);
  127. }
  128. addBindings();
  129. }
  130.  
  131. function addBindings() {
  132. document.querySelector('.gfp-show-unicode').addEventListener('change', function() {
  133. showUnicode = this.checked;
  134. GM_setValue('gfp-show-unicode', showUnicode);
  135. displayGlyphPage(pageSelected);
  136. return false;
  137. }, false);
  138. document.querySelector('#gfp-glyph-data').addEventListener('change', function() {
  139. showPoints = this.querySelector('.gfp-show-points').checked;
  140. showArrows = this.querySelector('.gfp-show-arrows').checked;
  141. GM_setValue('gfp-show-points', showPoints);
  142. GM_setValue('gfp-show-arrows', showArrows);
  143. cellSelect();
  144. return false;
  145. }, false);
  146. }
  147.  
  148. function init() {
  149. let name,
  150. el = document.querySelector('.file .image');
  151. if (el) {
  152. name = document.querySelector('.final-path').textContent || '';
  153. if (name && fontExt.test(name)) {
  154. getFont(el.querySelector('a').href || '');
  155. }
  156. }
  157. }
  158.  
  159. // DOM targets - to detect GitHub dynamic ajax page loading
  160. targets = document.querySelectorAll([
  161. '#js-repo-pjax-container',
  162. '.context-loader-container',
  163. '[data-pjax-container]'
  164. ].join(','));
  165.  
  166. Array.prototype.forEach.call(targets, function(target) {
  167. new MutationObserver(function(mutations) {
  168. mutations.forEach(function(mutation) {
  169. // preform checks before adding code wrap to minimize function calls
  170. if (!busy && mutation.target === target) {
  171. clearTimeout(timer);
  172. timer = setTimeout(init, 200);
  173. }
  174. });
  175. }).observe(target, {
  176. childList: true,
  177. subtree: true
  178. });
  179. });
  180.  
  181. init();
  182.  
  183. /* Code modified from http://opentype.js.org/ demos */
  184. GM_addStyle(`
  185. #gfp-wrapper { text-align:left; }
  186. #gfp-wrapper canvas { background-image:none !important; background-color:transparent !important; }
  187. .gfp-message { position:relative; top:-3px; padding:1px 5px; font-weight:bold; border-radius:2px; display:none; clear:both; }
  188. #gfp-glyphs { width:950px; }
  189. .gfp-info { float:right; font-size:11px; color:#999; }
  190. hr { clear:both; border:none; border-bottom:1px solid #ccc; margin:20px 0 20px 0; padding:0; }
  191. /* Font Inspector */
  192. #gfp-font-data div { font-weight:normal; margin:0; cursor:pointer; }
  193. #gfp-font-data div:before { font-size:85%; content:'▼ '; }
  194. #gfp-font-data div.gfp-collapsed:before { font-size:85%; content:'► '; }
  195. #gfp-font-data div.gfp-collapsed + dl { display:none; }
  196. #gfp-font-data dl { margin-top:0; padding-left:2em; color:#777; }
  197. #gfp-font-data dt { float:left; }
  198. #gfp-font-data dd { margin-left: 12em; }
  199. #gfp-font-data .gfp-langtag { font-size:85%; color:#999; white-space:nowrap; }
  200. #gfp-font-data .gfp-langname { padding-right:0.5em; }
  201. #gfp-font-data .gfp-underline { border-bottom:1px solid #555; }
  202. /* Glyph Inspector */
  203. #gfp-pagination span { margin:0 0.3em; cursor:pointer; }
  204. #gfp-pagination span.gfp-page-selected { font-weight:bold; cursor:default; -webkit-filter:brightness(150%); filter:brightness(150%); }
  205. canvas.gfp-item { float:left; border:solid 1px #a0a0a0; margin-right:-1px; margin-bottom:-1px; cursor:pointer; }
  206. canvas.gfp-item:hover { opacity:.8; }
  207. #gfp-glyph-list-end { clear:both; height:20px; }
  208. #gfp-glyph-display { float:left; border:solid 1px #a0a0a0; position:relative; width:500px; height:500px; }
  209. #gfp-glyph, #gfp-glyph-bg { position:absolute; top:0; left:0; border:0; }
  210. #gfp-glyph-data { float:left; margin-left:2em; }
  211. #gfp-glyph-data dl { margin:0; }
  212. #gfp-glyph-data dt { float:left; }
  213. #gfp-glyph-data dd { margin-left:12em; }
  214. #gfp-glyph-data pre { font-size:11px; }
  215. pre.gfp-path { margin:0; }
  216. pre.gfp-contour { margin:0 0 1em 2em; border-bottom:solid 1px #a0a0a0; }
  217. span.gfp-oncurve { color:blue; }
  218. span.gfp-offcurve { color:red; }
  219. .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; }
  220. @keyframes gfploading { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
  221. `);
  222.  
  223. /* Code copied from http://opentype.js.org/font-inspector.html */
  224. function escapeHtml(unsafe) {
  225. return unsafe
  226. .replace(/&/g, '&amp;')
  227. .replace(/</g, '&lt;')
  228. .replace(/>/g, '&gt;')
  229. .replace(/\u0022/g, '&quot;')
  230. .replace(/\u0027/g, '&#039;');
  231. }
  232.  
  233. function displayNames(names) {
  234. let indx, property, translations, langs, lang, langIndx, langLen, esclang,
  235. html = '',
  236. properties = Object.keys(names),
  237. len = properties.length;
  238. for (indx = 0; indx < len; indx++) {
  239. property = properties[indx];
  240. html += '<dt>' + escapeHtml(property) + '</dt><dd>';
  241. translations = names[property];
  242. langs = Object.keys(translations);
  243. langLen = langs.length;
  244. for (langIndx = 0; langIndx < langLen; langIndx++) {
  245. lang = langs[langIndx];
  246. esclang = escapeHtml(lang);
  247. html += '<span class="gfp-langtag">' + esclang +
  248. '</span> <span class="gfp-langname" lang=' + esclang + '>' +
  249. escapeHtml(translations[lang]) + '</span> ';
  250. }
  251. html += '</dd>';
  252. }
  253. document.getElementById('gfp-name-table').innerHTML = html;
  254. }
  255.  
  256. function displayFontData() {
  257. let html, tablename, table, property, value, element;
  258. for (tablename in font.tables) {
  259. if (font.tables.hasOwnProperty(tablename)) {
  260. table = font.tables[tablename];
  261. if (tablename === 'name') {
  262. displayNames(table);
  263. continue;
  264. }
  265. html = '';
  266. for (property in table) {
  267. if (table.hasOwnProperty(property)) {
  268. value = table[property];
  269. html += '<dt>' + property + '</dt><dd>';
  270. if (Array.isArray(value) && typeof value[0] === 'object') {
  271. html += value.map(function(item) {
  272. return JSON.stringify(item);
  273. }).join('<br>');
  274. } else if (typeof value === 'object') {
  275. html += JSON.stringify(value);
  276. } else {
  277. html += value;
  278. }
  279. html += '</dd>';
  280. }
  281. }
  282. element = document.getElementById('gfp-' + tablename + '-table');
  283. if (element) {
  284. element.innerHTML = html;
  285. }
  286. }
  287. }
  288. }
  289.  
  290. /* Code copied from http://opentype.js.org/glyph-inspector.html */
  291. const cellCount = 100,
  292. cellWidth = 62,
  293. cellHeight = 60,
  294. cellMarginTop = 1,
  295. cellMarginBottom = 8,
  296. cellMarginLeftRight = 1,
  297. glyphMargin = 5,
  298. pixelRatio = window.devicePixelRatio || 1,
  299. arrowLength = 10,
  300. arrowAperture = 4;
  301.  
  302. let pageSelected, fontScale, fontSize, fontBaseline, glyphScale, glyphSize, glyphBaseline;
  303.  
  304. function enableHighDPICanvas(canvas) {
  305. let pixelRatio, oldWidth, oldHeight;
  306. if (typeof canvas === 'string') {
  307. canvas = document.getElementById(canvas);
  308. }
  309. pixelRatio = window.devicePixelRatio || 1;
  310. if (pixelRatio === 1) { return; }
  311. oldWidth = canvas.width;
  312. oldHeight = canvas.height;
  313. canvas.width = oldWidth * pixelRatio;
  314. canvas.height = oldHeight * pixelRatio;
  315. canvas.style.width = oldWidth + 'px';
  316. canvas.style.height = oldHeight + 'px';
  317. canvas.getContext('2d').scale(pixelRatio, pixelRatio);
  318. }
  319.  
  320. function showErrorMessage(message) {
  321. let el = document.querySelector('.gfp-message');
  322. el.style.display = (!message || message.trim().length === 0) ? 'none' : 'block';
  323. el.innerHTML = message;
  324. }
  325.  
  326. function pathCommandToString(cmd) {
  327. let str = '<strong>' + cmd.type + '</strong> ' +
  328. ((cmd.x !== undefined) ? 'x=' + cmd.x + ' y=' + cmd.y + ' ' : '') +
  329. ((cmd.x1 !== undefined) ? 'x1=' + cmd.x1 + ' y1=' + cmd.y1 + ' ' : '') +
  330. ((cmd.x2 !== undefined) ? 'x2=' + cmd.x2 + ' y2=' + cmd.y2 : '');
  331. return str;
  332. }
  333.  
  334. function contourToString(contour) {
  335. return '<pre class="gfp-contour">' + contour.map(function(point) {
  336. // ".alert.tip" class modified by GitHub Dark style - more readable blue
  337. // ".cdel" class modified by GitHub Dark style - more readable red
  338. return '<span class="gfp-' + (point.onCurve ? 'oncurve alert tip' : 'offcurve cdel') +
  339. '">x=' + point.x + ' y=' + point.y + '</span>';
  340. }).join('\n') + '</pre>';
  341. }
  342.  
  343. function formatUnicode(unicode) {
  344. unicode = unicode.toString(16);
  345. if (unicode.length > 4) {
  346. return ('000000' + unicode.toUpperCase()).substr(-6);
  347. } else {
  348. return ('0000' + unicode.toUpperCase()).substr(-4);
  349. }
  350. }
  351.  
  352. function displayGlyphData(glyphIndex) {
  353. let glyph, contours, html,
  354. container = document.getElementById('gfp-glyph-data'),
  355. addItem = function(name) {
  356. return glyph[name] ? `<dt>${name}</dt><dd>${glyph[name]}</dd>` : '';
  357. };
  358. if (glyphIndex < 0) {
  359. container.innerHTML = '';
  360. return;
  361. }
  362. glyph = font.glyphs.get(glyphIndex);
  363. html = `<dl>
  364. <dt>Show points</dt>
  365. <dd><input class="gfp-show-points" type="checkbox"${showPoints ? ' checked' : ''}></dd>
  366. <dt>Show arrows</dt>
  367. <dd><input class="gfp-show-arrows" type="checkbox"${showArrows ? ' checked' : ''}></dd>
  368. <dt>name</dt><dd>${glyph.name}</dd>`;
  369.  
  370. if (glyph.unicode) {
  371. html += '<dt>unicode</dt><dd>' + glyph.unicodes.map(formatUnicode).join(', ') + '</dd>';
  372. }
  373. html += addItem('index') +
  374. addItem('xMin') +
  375. addItem('xMax') +
  376. addItem('yMin') +
  377. addItem('yMax') +
  378. addItem('advanceWidth') +
  379. addItem('leftSideBearing') +
  380. '</dl>';
  381.  
  382. if (glyph.numberOfContours > 0) {
  383. contours = glyph.getContours();
  384. html += 'contours:<br>' + contours.map(contourToString).join('\n');
  385. } else if (glyph.isComposite) {
  386. html += '<br>This composite glyph is a combination of :<ul><li>' +
  387. glyph.components.map(function(component) {
  388. return 'glyph ' + component.glyphIndex + ' at dx=' + component.dx +
  389. ', dy=' + component.dy;
  390. }).join('</li><li>') + '</li></ul>';
  391. } else if (glyph.path) {
  392. html += 'path:<br><pre class="gfp-path"> ' +
  393. glyph.path.commands.map(pathCommandToString).join('\n ') + '\n</pre>';
  394. }
  395. container.innerHTML = html;
  396. }
  397.  
  398. function drawArrow(ctx, x1, y1, x2, y2) {
  399. let dx = x2 - x1,
  400. dy = y2 - y1,
  401. segmentLength = Math.sqrt(dx * dx + dy * dy),
  402. unitx = dx / segmentLength,
  403. unity = dy / segmentLength,
  404. basex = x2 - arrowLength * unitx,
  405. basey = y2 - arrowLength * unity,
  406. normalx = arrowAperture * unity,
  407. normaly = -arrowAperture * unitx;
  408. ctx.beginPath();
  409. ctx.moveTo(x2, y2);
  410. ctx.lineTo(basex + normalx, basey + normaly);
  411. ctx.lineTo(basex - normalx, basey - normaly);
  412. ctx.lineTo(x2, y2);
  413. ctx.closePath();
  414. ctx.fill();
  415. }
  416.  
  417. /**
  418. * This function is Path.prototype.draw with an arrow
  419. * at the end of each contour.
  420. */
  421. function drawPathWithArrows(ctx, path) {
  422. let indx, cmd, x1, y1, x2, y2,
  423. arrows = [],
  424. len = path.commands.length;
  425. ctx.beginPath();
  426. for (indx = 0; indx < len; indx++) {
  427. cmd = path.commands[indx];
  428. if (cmd.type === 'M') {
  429. if (x1 !== undefined) {
  430. arrows.push([ctx, x1, y1, x2, y2]);
  431. }
  432. ctx.moveTo(cmd.x, cmd.y);
  433. } else if (cmd.type === 'L') {
  434. ctx.lineTo(cmd.x, cmd.y);
  435. x1 = x2;
  436. y1 = y2;
  437. } else if (cmd.type === 'C') {
  438. ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
  439. x1 = cmd.x2;
  440. y1 = cmd.y2;
  441. } else if (cmd.type === 'Q') {
  442. ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y);
  443. x1 = cmd.x1;
  444. y1 = cmd.y1;
  445. } else if (cmd.type === 'Z') {
  446. arrows.push([ctx, x1, y1, x2, y2]);
  447. ctx.closePath();
  448. }
  449. x2 = cmd.x;
  450. y2 = cmd.y;
  451. }
  452. if (path.fill) {
  453. ctx.fillStyle = path.fill;
  454. ctx.fill();
  455. }
  456. if (path.stroke) {
  457. ctx.strokeStyle = path.stroke;
  458. ctx.lineWidth = path.strokeWidth;
  459. ctx.stroke();
  460. }
  461. ctx.fillStyle = bigGlyphStrokeColor;
  462. if (showArrows) {
  463. arrows.forEach(function(arrow) {
  464. drawArrow.apply(null, arrow);
  465. });
  466. }
  467. }
  468.  
  469. function displayGlyph(glyphIndex) {
  470. let glyph, glyphWidth, xmin, xmax, x0, markSize, path,
  471. canvas = document.getElementById('gfp-glyph'),
  472. ctx = canvas.getContext('2d'),
  473. width = canvas.width / pixelRatio,
  474. height = canvas.height / pixelRatio;
  475. ctx.clearRect(0, 0, width, height);
  476. if (glyphIndex < 0) { return; }
  477. glyph = font.glyphs.get(glyphIndex);
  478. glyphWidth = glyph.advanceWidth * glyphScale;
  479. xmin = (width - glyphWidth)/2;
  480. xmax = (width + glyphWidth)/2;
  481. x0 = xmin;
  482. markSize = 10;
  483.  
  484. ctx.fillStyle = bigGlyphMarkerColor;
  485. ctx.fillRect(xmin-markSize+1, glyphBaseline, markSize, 1);
  486. ctx.fillRect(xmin, glyphBaseline, 1, markSize);
  487. ctx.fillRect(xmax, glyphBaseline, markSize, 1);
  488. ctx.fillRect(xmax, glyphBaseline, 1, markSize);
  489. ctx.textAlign = 'center';
  490. ctx.fillText('0', xmin, glyphBaseline + markSize + 10);
  491. ctx.fillText(glyph.advanceWidth, xmax, glyphBaseline + markSize + 10);
  492.  
  493. ctx.fillStyle = bigGlyphStrokeColor;
  494. path = glyph.getPath(x0, glyphBaseline, glyphSize);
  495. path.fill = bigGlyphFillColor;
  496. path.stroke = bigGlyphStrokeColor;
  497. path.strokeWidth = 1.5;
  498. drawPathWithArrows(ctx, path);
  499. if (showPoints) {
  500. glyph.drawPoints(ctx, x0, glyphBaseline, glyphSize);
  501. }
  502. }
  503.  
  504. function renderGlyphItem(canvas, glyphIndex) {
  505. const cellMarkSize = 4,
  506. ctx = canvas.getContext('2d');
  507. ctx.clearRect(0, 0, cellWidth, cellHeight);
  508. if (glyphIndex >= font.numGlyphs) { return; }
  509.  
  510. ctx.fillStyle = miniGlyphMarkerColor;
  511. ctx.font = '10px sans-serif';
  512. let glyph = font.glyphs.get(glyphIndex),
  513. glyphWidth = glyph.advanceWidth * fontScale,
  514. xmin = (cellWidth - glyphWidth) / 2,
  515. xmax = (cellWidth + glyphWidth) / 2,
  516. x0 = xmin;
  517.  
  518. ctx.fillText(showUnicode ? glyph.unicodes.map(formatUnicode).join(', ') : glyphIndex, 1, cellHeight-1);
  519.  
  520. ctx.fillStyle = glyphRulerColor;
  521. ctx.fillRect(xmin-cellMarkSize+1, fontBaseline, cellMarkSize, 1);
  522. ctx.fillRect(xmin, fontBaseline, 1, cellMarkSize);
  523. ctx.fillRect(xmax, fontBaseline, cellMarkSize, 1);
  524. ctx.fillRect(xmax, fontBaseline, 1, cellMarkSize);
  525.  
  526. ctx.fillStyle = '#000000';
  527. glyph.draw(ctx, x0, fontBaseline, fontSize);
  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) { return; }
  614. let firstGlyphIndex = pageSelected * cellCount,
  615. cellIndex = event ? +event.target.id.replace('gfp-g', '') : currentIndex,
  616. glyphIndex = firstGlyphIndex + cellIndex;
  617. currentIndex = cellIndex;
  618. if (glyphIndex < font.numGlyphs) {
  619. displayGlyph(glyphIndex);
  620. displayGlyphData(glyphIndex);
  621. }
  622. }
  623.  
  624. function prepareGlyphList() {
  625. let indx, canvas,
  626. marker = document.getElementById('gfp-glyph-list-end'),
  627. parent = marker.parentElement;
  628. for (indx = 0; indx < cellCount; indx++) {
  629. canvas = document.createElement('canvas');
  630. canvas.width = cellWidth;
  631. canvas.height = cellHeight;
  632. canvas.className = 'gfp-item ghd-invert';
  633. canvas.id = 'gfp-g' + indx;
  634. canvas.addEventListener('click', cellSelect, false);
  635. enableHighDPICanvas(canvas);
  636. parent.insertBefore(canvas, marker);
  637. }
  638. }
  639.  
  640. })();