identiconDirective.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. angular.module('syncthing.core')
  2. .directive('identicon', ['$window', function ($window) {
  3. var svgNS = 'http://www.w3.org/2000/svg';
  4. function Identicon(value, size) {
  5. var svg = document.createElementNS(svgNS, 'svg');
  6. var shouldFillRectAt = function (row, col) {
  7. return !($window.parseInt(value.charCodeAt(row + col * size), 10) % 2);
  8. };
  9. var shouldMirrorRectAt = function (row, col) {
  10. return !(size % 2 && col === middleCol)
  11. };
  12. var mirrorColFor = function (col) {
  13. return size - col - 1;
  14. };
  15. var fillRectAt = function (row, col) {
  16. var rect = document.createElementNS(svgNS, 'rect');
  17. rect.setAttribute('x', (col * rectSize) + '%');
  18. rect.setAttribute('y', (row * rectSize) + '%');
  19. rect.setAttribute('width', rectSize + '%');
  20. rect.setAttribute('height', rectSize + '%');
  21. svg.appendChild(rect);
  22. };
  23. var row;
  24. var col;
  25. var middleCol;
  26. var rectSize;
  27. svg.setAttribute('class', 'identicon');
  28. size = size || 5;
  29. rectSize = 100 / size;
  30. middleCol = Math.ceil(size / 2) - 1;
  31. if (value) {
  32. value = value.toString().replace(/[\W_]/g, '');
  33. for (row = 0; row < size; ++row) {
  34. for (col = middleCol; col > -1; --col) {
  35. if (shouldFillRectAt(row, col)) {
  36. fillRectAt(row, col);
  37. if (shouldMirrorRectAt(row, col)) {
  38. fillRectAt(row, mirrorColFor(col));
  39. }
  40. }
  41. }
  42. }
  43. }
  44. return svg;
  45. }
  46. return {
  47. restrict: 'E',
  48. scope: {
  49. value: '='
  50. },
  51. link: function (scope, element, attributes) {
  52. element.append(new Identicon(scope.value));
  53. }
  54. }
  55. }]);