@foreverrbum/ethsign
Version:
This package will allow you to electronically sign documents within your application
1,149 lines (946 loc) • 48.5 kB
JavaScript
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.updateXFDF = exports.updateSignatureFinder = exports.styleWidgets = exports.resetStoredData = exports.replace = exports.redrawSignHereWidget = exports.isSignersWithFields = exports.handleDocChanges = exports.getxfdfString = exports.getStringFromDecryptedArr = exports.getShortenedName = exports.getFields = exports.getDefaultTool = exports.checkAndUpdateAnnotList = exports.areAllFieldsFilled = exports.applyFields = exports.addField = void 0;
var _lodash = _interopRequireDefault(require("lodash"));
var _dashboard = require("./dashboard");
var _window = require("./window");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var addField = function addField(type) {
var point = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
var value = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
var flag = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
// instance.setToolMode('AnnotationCreateTriangle');
var _instance = instance,
docViewer = _instance.docViewer,
Annotations = _instance.Annotations;
var annotManager = docViewer.getAnnotationManager();
var doc = docViewer.getDocument();
var displayMode = docViewer.getDisplayModeManager().getDisplayMode();
var page = displayMode.getSelectedPages(point, point);
if (!!point.x && page.first == null) {
return; //don't add field to an invalid page location
}
var page_idx = page.first !== null ? page.first : docViewer.getCurrentPage();
var page_info = doc.getPageInfo(page_idx);
var page_point = displayMode.windowToPage(point, page_idx);
var zoom = docViewer.getZoom();
var textAnnot = new Annotations.FreeTextAnnotation();
textAnnot.PageNumber = page_idx;
var rotation = docViewer.getCompleteRotation(page_idx) * 90;
textAnnot.Rotation = rotation;
if (rotation === 270 || rotation === 90) {
textAnnot.Width = 20.0;
textAnnot.Height = 140.0;
} else {
textAnnot.Width = 140.0;
textAnnot.Height = 20.0;
}
textAnnot.X = (page_point.x || page_info.width / 2) - textAnnot.Width / 2;
textAnnot.Y = (page_point.y || page_info.height / 2) - textAnnot.Height / 2;
textAnnot.LockedContents = true;
textAnnot.setPadding(new Annotations.Rect(0, 0, 0, 0));
textAnnot.custom = {
type: type,
value: value,
flag: flag,
name: "0x345...345 Signs Here"
}; // set the type of annot
textAnnot.setContents(textAnnot.custom.name);
textAnnot.FontSize = '' + 15.0 + 'px';
textAnnot.TextAlign = 'center';
textAnnot.autoSizeProperties = {
expandHeight: true
};
textAnnot.TextColor = new Annotations.Color(0, 0, 0);
textAnnot.StrokeThickness = 1;
textAnnot.StrokeColor = new Annotations.Color(211, 211, 211, 0);
textAnnot.TextAlign = 'center';
textAnnot.Author = annotManager.getCurrentUser();
var page_matrix = doc.getPageMatrix(page_idx);
textAnnot.fitText(page_info, page_matrix, rotation);
var pageMatrix = doc.getPageMatrix(page_idx);
var annotRect = textAnnot.getRect;
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.setLineDash([5, 3]);
/*dashes are 5px and spaces are 3px*/
ctx.beginPath();
ctx.moveTo(0, 100);
ctx.lineTo(3000, 100);
ctx.stroke(); // textAnnot.draw(ctx, pageMatrix)
annotManager.deselectAllAnnotations();
annotManager.addAnnotation(textAnnot, true);
annotManager.redrawAnnotation(textAnnot);
annotManager.selectAnnotation(textAnnot);
};
exports.addField = addField;
var redrawSignHereWidget = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(annots, instance, ethAccount, ethAlias, ethAvatar) {
var annotManager, docViewer, page_idx, rotation, signer, annotsToDraw;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
annotManager = instance.annotManager, docViewer = instance.docViewer;
page_idx = docViewer.getCurrentPage();
rotation = docViewer.getCompleteRotation(page_idx) * -90;
signer = {
rotation: rotation,
address: ethAccount,
alias: ethAlias,
avatar: ethAvatar
};
annotsToDraw = [];
_context2.next = 7;
return Promise.all(annots.map( /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(annot, index) {
var _yield$replace, inputAnnot;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return replace(instance, annot, index, signer);
case 2:
_yield$replace = _context.sent;
inputAnnot = _yield$replace.inputAnnot;
// draw the annotation the viewer
annotManager.addAnnotation(inputAnnot);
annotsToDraw.push(inputAnnot);
case 6:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x6, _x7) {
return _ref2.apply(this, arguments);
};
}()));
case 7:
_context2.next = 9;
return annotManager.drawAnnotationsFromList(annotsToDraw);
case 9:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function redrawSignHereWidget(_x, _x2, _x3, _x4, _x5) {
return _ref.apply(this, arguments);
};
}();
exports.redrawSignHereWidget = redrawSignHereWidget;
var replace = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(instance, annot, index, signer) {
var field, inputAnnot, Annotations, annotManager, rotation;
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
//annot is the original signature field
Annotations = instance.Annotations, annotManager = instance.annotManager;
try {
field = annot.getField();
} catch (e) {
field = new Annotations.Forms.Field("EthSign Signature Field" + Date.now() + index, {
type: 'Sig'
});
}
inputAnnot = new Annotations.SignatureWidgetAnnotation(field, {
appearance: '_DEFAULT',
appearances: {
_DEFAULT: {
Normal: {
data: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjEuMWMqnEsAAAANSURBVBhXY/j//z8DAAj8Av6IXwbgAAAAAElFTkSuQmCC',
offset: {
x: 100,
y: 100
}
}
}
}
});
inputAnnot.Author = annotManager.getCurrentUser();
if (signer) {
inputAnnot.Index = index;
inputAnnot.Signer = signer;
} else {
inputAnnot.Signer = annot.Signer;
inputAnnot.Index = annot.Index;
}
rotation = inputAnnot.Signer.rotation;
inputAnnot.createSignHereElement = function () {
var div = document.createElement('div');
div.style.height = "100%";
div.style.width = "100%";
div.style.cursor = 'pointer';
div.style.border = '1px dashed #E98234';
div.style.transform = "rotate(".concat(rotation, "deg)");
var inlineImg = "<img src=\"assets/sign_here.svg\" style=\"width:inherit; height:100%;\"></img>";
div.innerHTML = inlineImg;
return div;
}; // set position
inputAnnot.PageNumber = annot.getPageNumber();
if (rotation === -90 || rotation === -270) {
inputAnnot.X = annot.getX() - annot.getHeight() / 2 + annot.getWidth() / 2;
inputAnnot.Y = annot.getY() + annot.getHeight() / 2 - annot.getWidth() / 2;
inputAnnot.Width = annot.getHeight();
inputAnnot.Height = annot.getWidth();
} else {
inputAnnot.X = annot.getX();
inputAnnot.Y = annot.getY();
inputAnnot.Width = annot.getWidth();
inputAnnot.Height = annot.getHeight();
}
return _context3.abrupt("return", {
inputAnnot: inputAnnot,
field: field
});
case 10:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function replace(_x8, _x9, _x10, _x11) {
return _ref3.apply(this, arguments);
};
}();
exports.replace = replace;
var applyFields = /*#__PURE__*/function () {
var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(sigfields, instance, ethAccount, signatureData) {
var docViewer, annotManager, fieldManager, annotationsList, annotsToDelete, annotsToDraw;
return regeneratorRuntime.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
docViewer = instance.docViewer;
annotManager = docViewer.getAnnotationManager();
fieldManager = annotManager.getFieldManager();
annotationsList = sigfields; // const annotationsList = annotManager.getAnnotationsList();
annotsToDelete = [];
annotsToDraw = [];
_context5.next = 8;
return Promise.all(annotationsList.map( /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(annot, index) {
var address, sigDataIdx, _signatureData$sigDat, signed, _yield$replace2, inputAnnot, field;
return regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
annot.ReadOnly = true;
_context4.prev = 1;
address = annot.Signer.address;
sigDataIdx = _lodash.default.findIndex(signatureData, {
signer: address
});
if (!(sigDataIdx > -1)) {
_context4.next = 20;
break;
}
signed = (_signatureData$sigDat = signatureData[sigDataIdx]) === null || _signatureData$sigDat === void 0 ? void 0 : _signatureData$sigDat.fieldSigned[annot.Index];
if (!(signed == true)) {
_context4.next = 10;
break;
}
annotsToDelete.push(annot);
_context4.next = 20;
break;
case 10:
if (!(address.toLowerCase() == ethAccount)) {
_context4.next = 20;
break;
}
_context4.next = 13;
return replace(instance, annot, index);
case 13:
_yield$replace2 = _context4.sent;
inputAnnot = _yield$replace2.inputAnnot;
field = _yield$replace2.field;
// delete original annotation
annotsToDelete.push(annot); // draw the annotation the viewer
// draw the annotation the viewer
annotManager.addAnnotation(inputAnnot);
fieldManager.addField(field);
annotsToDraw.push(inputAnnot);
case 20:
_context4.next = 25;
break;
case 22:
_context4.prev = 22;
_context4.t0 = _context4["catch"](1);
console.log(_context4.t0); // errors might be caused by contracts made before we implemented the indexing feature
case 25:
case "end":
return _context4.stop();
}
}
}, _callee4, null, [[1, 22]]);
}));
return function (_x16, _x17) {
return _ref5.apply(this, arguments);
};
}()));
case 8:
// delete old annotations
annotManager.deleteAnnotations(annotsToDelete, null, true); // refresh viewer
_context5.next = 11;
return annotManager.drawAnnotationsFromList(annotsToDraw);
case 11:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
return function applyFields(_x12, _x13, _x14, _x15) {
return _ref4.apply(this, arguments);
};
}();
exports.applyFields = applyFields;
var isSignersWithFields = function isSignersWithFields(signers, annotList) {
var fields = _lodash.default.remove(annotList, function (n) {
return n.Subject == "SignatureField";
}); // setting indexes of fields
var addresses = [];
fields.map(function (field) {
var index = _lodash.default.indexOf(addresses, field.Signer.address);
if (index == -1) {
//address isn't added yet
addresses.push(field.Signer.address);
}
});
_lodash.default.pullAll(signers, addresses);
return signers.length == 0;
};
exports.isSignersWithFields = isSignersWithFields;
var styleWidgets = /*#__PURE__*/function () {
var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(instance, widgets) {
var annotManager, Annotations, Color;
return regeneratorRuntime.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
annotManager = instance.annotManager, Annotations = instance.Annotations;
Color = Annotations.Color;
_context7.next = 4;
return Promise.all(widgets.map( /*#__PURE__*/function () {
var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(widget, index) {
return regeneratorRuntime.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
widget.font.strokeColor = new Color(255, 0, 0);
annotManager.redrawAnnotation(widget);
case 2:
case "end":
return _context6.stop();
}
}
}, _callee6);
}));
return function (_x20, _x21) {
return _ref7.apply(this, arguments);
};
}()));
case 4:
case "end":
return _context7.stop();
}
}
}, _callee7);
}));
return function styleWidgets(_x18, _x19) {
return _ref6.apply(this, arguments);
};
}();
exports.styleWidgets = styleWidgets;
var getxfdfString = /*#__PURE__*/function () {
var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(instance, annotList) {
var annotManager, fields, addresses, count, xfdfStringSigFields, xfdfStringAnnots;
return regeneratorRuntime.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
if (instance) {
_context8.next = 2;
break;
}
return _context8.abrupt("return", {
sigFieldXFDF: '',
annotationsXFDF: '',
addresses: [],
count: 0
});
case 2:
annotManager = instance.annotManager;
fields = _lodash.default.remove(annotList, function (n) {
return n.Subject == "SignatureField";
}); // setting indexes of fields
addresses = [];
count = [];
fields.map(function (field) {
var index = _lodash.default.indexOf(addresses, field.Signer.address);
if (index == -1) {
//address isn't added yet
addresses.push(field.Signer.address);
count.push(1);
field.Index = 0;
} else {
field.Index = count[index];
count[index] = count[index] + 1;
}
});
_context8.next = 9;
return annotManager.exportAnnotations({
annotList: fields
});
case 9:
xfdfStringSigFields = _context8.sent;
_context8.next = 12;
return annotManager.exportAnnotations({
annotList: annotList
});
case 12:
xfdfStringAnnots = _context8.sent;
return _context8.abrupt("return", {
sigFieldsXFDF: xfdfStringSigFields,
annotationsXFDF: xfdfStringAnnots,
addresses: addresses,
count: count
});
case 14:
case "end":
return _context8.stop();
}
}
}, _callee8);
}));
return function getxfdfString(_x22, _x23) {
return _ref8.apply(this, arguments);
};
}();
exports.getxfdfString = getxfdfString;
var updateXFDF = /*#__PURE__*/function () {
var _ref9 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(instance, annotList, handleAnnotations, updateStoredData) {
var annotManager, xfdfStringAnnots;
return regeneratorRuntime.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
annotManager = instance.annotManager;
_context9.next = 3;
return annotManager.exportAnnotations({
annotList: annotList
});
case 3:
xfdfStringAnnots = _context9.sent;
handleAnnotations(xfdfStringAnnots);
updateStoredData(null, xfdfStringAnnots);
case 6:
case "end":
return _context9.stop();
}
}
}, _callee9);
}));
return function updateXFDF(_x24, _x25, _x26, _x27) {
return _ref9.apply(this, arguments);
};
}();
exports.updateXFDF = updateXFDF;
var getStringFromDecryptedArr = /*#__PURE__*/function () {
var _ref10 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee11(decryptedArr, formatMessage) {
var blob, reader;
return regeneratorRuntime.wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
blob = new Blob([decryptedArr], {
type: 'text/plain'
});
reader = new window.FileReader();
return _context11.abrupt("return", new Promise(function (resolve, reject) {
reader.onload = /*#__PURE__*/function () {
var _ref11 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee10(fileEvent) {
var xfdf;
return regeneratorRuntime.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
xfdf = fileEvent.target.result;
resolve(xfdf);
case 2:
case "end":
return _context10.stop();
}
}
}, _callee10);
}));
return function (_x30) {
return _ref11.apply(this, arguments);
};
}();
reader.onerror = function () {
reject(formatMessage({
id: 'OOPS_SOMETHING_WENT_WRONG'
}));
};
reader.readAsText(blob);
}));
case 3:
case "end":
return _context11.stop();
}
}
}, _callee11);
}));
return function getStringFromDecryptedArr(_x28, _x29) {
return _ref10.apply(this, arguments);
};
}();
exports.getStringFromDecryptedArr = getStringFromDecryptedArr;
var areFieldsFilled = function areFieldsFilled(field) {
var value = field.value;
var filled = true;
if (field.children.length > 0) {
field.children.forEach(function (childField) {
filled = filled && areFieldsFilled(childField);
});
} else {
filled = value !== "";
}
return filled;
};
var getFields = function getFields(annotManager) {
var fields = [];
annotManager.getFieldManager().forEachField(function (field) {
fields.push(field);
});
return fields;
}; // This fx is for debugging purposes only
exports.getFields = getFields;
var displayFieldNameAndValue = function displayFieldNameAndValue(field) {
// insert this in code
// annotManager.getFieldManager().forEachField((field)=>{
// displayFieldNameAndValue(field)
// });
var name = field.name,
value = field.value;
if (field.children.length == 0) {
console.log("Name: ".concat(name, ", Value: ").concat(value));
} // Check children fields
field.children.forEach(displayFieldNameAndValue);
};
var handleDocChanges = /*#__PURE__*/function () {
var _ref12 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee13(instance, handleFieldsByPage, handleNumOfSigned, handleNewChanges, savedAnnotations, handleFieldChanges, handleAllFieldsFilled, ethAccount) {
var annotManager;
return regeneratorRuntime.wrap(function _callee13$(_context13) {
while (1) {
switch (_context13.prev = _context13.next) {
case 0:
annotManager = instance.annotManager;
annotManager.on('annotationChanged', /*#__PURE__*/function () {
var _ref14 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee12(annotations, action, _ref13) {
var imported, annotList, signatures, annotationList;
return regeneratorRuntime.wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
imported = _ref13.imported;
annotList = annotManager.getAnnotationsList();
signatures = annotations.filter(function (a) {
return a.Subject == "Signature";
});
if (!imported) {
annotationList = _toConsumableArray(annotManager.getAnnotationsList());
_lodash.default.pullAll(annotationList, savedAnnotations);
handleNewChanges(annotationList.length > 0);
}
if (signatures.length > 0) {
if (action == "add") {
signatures.map(function (sig) {
// get widget of the added signature annotation first and then get the field of the widget to set the field value
var field = annotList.filter(function (a) {
return a.annot == sig;
})[0].getField();
field.setValue('signed');
});
updateSignatureFinder(annotManager, handleFieldsByPage, handleNumOfSigned, ethAccount);
}
}
case 5:
case "end":
return _context12.stop();
}
}
}, _callee12);
}));
return function (_x39, _x40, _x41) {
return _ref14.apply(this, arguments);
};
}());
if (handleFieldChanges) {
annotManager.on('fieldChanged', function (field, value) {
handleFieldChanges(true);
if (handleAllFieldsFilled) {
handleAllFieldsFilled(areAllFieldsFilled(annotManager));
}
});
}
case 3:
case "end":
return _context13.stop();
}
}
}, _callee13);
}));
return function handleDocChanges(_x31, _x32, _x33, _x34, _x35, _x36, _x37, _x38) {
return _ref12.apply(this, arguments);
};
}();
exports.handleDocChanges = handleDocChanges;
var areAllFieldsFilled = function areAllFieldsFilled(annotManager) {
var fieldManager = annotManager.getFieldManager();
var filled = true;
fieldManager.forEachField(function (field) {
filled = filled && areFieldsFilled(field);
});
return filled;
};
exports.areAllFieldsFilled = areAllFieldsFilled;
var checkAndUpdateAnnotList = /*#__PURE__*/function () {
var _ref15 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee15(file, filename, handleWebviewer, viewer, ethAlias, ethAccount, storedAnnotations, signers) {
return regeneratorRuntime.wrap(function _callee15$(_context15) {
while (1) {
switch (_context15.prev = _context15.next) {
case 0:
return _context15.abrupt("return", new Promise(function (resolve, reject) {
WebViewer({
licenseKey: '7m4ej8GFJuRlJGHs8B5l',
path: '/webviewer/lib',
disabledElements: ['header', 'toolsHeader']
}, viewer.current).then(function (instance) {
handleWebviewer(instance);
if (file != null) {
instance.loadDocument(file, {
filename: filename.name + filename.ext
});
}
var Annotations = instance.Annotations,
Tools = instance.Tools,
annotManager = instance.annotManager,
docViewer = instance.docViewer,
CoreControls = instance.CoreControls;
instance.openElements(['leftPanel']);
annotManager.setCurrentUser(ethAlias ? ethAlias : ethAccount); // new code
// new code
signers.map(function (signer, index) {
var SigFieldTxtAnnotation = /*#__PURE__*/function (_Annotations$CustomAn) {
_inherits(SigFieldTxtAnnotation, _Annotations$CustomAn);
var _super = _createSuper(SigFieldTxtAnnotation);
function SigFieldTxtAnnotation() {
var _this;
_classCallCheck(this, SigFieldTxtAnnotation);
_this = _super.call(this, 'SigFieldTxt'); // provide the custom XFDF element name
// provide the custom XFDF element name
var page_idx = docViewer.getCurrentPage();
var rotation = docViewer.getCompleteRotation(page_idx) * -90;
_this.PageRotation = rotation; // TODO: add index in Sending.js
// TODO: add index in Sending.js
_this.Subject = "SignatureField";
_this.Signer = {
address: signer.address,
rotation: rotation,
alias: signer.alias,
avatar: signer.avatar
};
_this.Index = 0;
_this.Address = signer.alias ? (0, _dashboard.truncate)(signer.alias) : (0, _dashboard.truncate)(signer.address);
_this.Signed = false;
_this.vertices = [];
var numVertices = 4;
for (var i = 0; i < numVertices; ++i) {
_this.vertices.push(new CoreControls.Math.Point());
}
_this.selectionModel = SigFieldSelectionModel;
return _this;
}
_createClass(SigFieldTxtAnnotation, [{
key: "serialize",
value: function serialize(element, pageMatrix) {
this.setCustomData('vertices', this.vertices);
var el = _get(_getPrototypeOf(SigFieldTxtAnnotation.prototype), "serialize", this).call(this, element, pageMatrix); // create an attribute to save the vertices list
// create an attribute to save the vertices list
el.setAttribute('Signer', JSON.stringify(this.Signer));
el.setAttribute('Index', this.Index);
el.setAttribute('Address', this.Address);
el.setAttribute('Signed', this.Signed);
return el;
}
}, {
key: "deserialize",
value: function deserialize(element, pageMatrix) {
_get(_getPrototypeOf(SigFieldTxtAnnotation.prototype), "deserialize", this).call(this, element, pageMatrix);
this.Signer = JSON.parse(element.getAttribute('Signer'));
this.Index = element.getAttribute('Index');
this.Address = element.getAttribute('Address');
this.Signed = element.getAttribute('Signed');
var storedVertices = this.getCustomData('vertices');
this.vertices = storedVertices.map(function (v) {
return new CoreControls.Math.Point(v.x, v.y);
});
}
}, {
key: "draw",
value: function draw(ctx, pageMatrix) {
this.setStyles(ctx, pageMatrix);
ctx.beginPath();
ctx.setLineDash([5, 3]);
ctx.moveTo(this.vertices[0].x, this.vertices[0].y);
ctx.lineTo(this.vertices[1].x, this.vertices[1].y);
ctx.lineTo(this.vertices[2].x, this.vertices[2].y);
ctx.lineTo(this.vertices[3].x, this.vertices[3].y);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "black";
var zoom = docViewer.getZoom();
var textAnnot = this.Address + " Signs Here";
ctx.save();
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.rotate(this.PageRotation / 180 * Math.PI);
if (this.PageRotation == -90 || this.PageRotation == -270) {
var textHeight = this.Height / 11;
ctx.font = "".concat(textHeight, "px san-serif");
if (this.PageRotation == -90) {
ctx.fillText(textAnnot, -this.vertices[0].y - this.Height / 2, this.vertices[0].x + this.Width / 2);
} else {
ctx.fillText(textAnnot, this.vertices[0].y + this.Height / 2, -this.vertices[0].x - this.Width / 2);
}
} else {
var _textHeight = this.Width / 11;
ctx.font = "".concat(_textHeight, "px san-serif");
if (this.PageRotation == -180) {
ctx.fillText(textAnnot, -this.vertices[0].x + (this.Width / 2 - this.Width), -this.vertices[0].y + this.Height / 2 - this.Height);
} else {
ctx.fillText(textAnnot, this.vertices[0].x + this.Width / 2, this.vertices[0].y + this.Height / 2);
}
}
ctx.stroke();
}
}, {
key: "resize",
value: function resize(rect) {
var annotRect = this.getRect();
var deltaX = rect.x1 - annotRect.x1;
var deltaY = rect.y1 - annotRect.y1;
this.vertices = this.vertices.map(function (vertex) {
vertex.translate(deltaX, deltaY);
return vertex;
});
this.setRect(rect);
}
}]);
return SigFieldTxtAnnotation;
}(Annotations.CustomAnnotation);
var SigFieldSelectionModel = /*#__PURE__*/function (_Annotations$Selectio) {
_inherits(SigFieldSelectionModel, _Annotations$Selectio);
var _super2 = _createSuper(SigFieldSelectionModel);
function SigFieldSelectionModel(annotation, canModify) {
var _this2;
_classCallCheck(this, SigFieldSelectionModel);
_this2 = _super2.call(this, annotation, canModify);
if (canModify) {
var controlHandles = _this2.getControlHandles();
controlHandles.push(new SigFieldControlHandle(annotation, 0));
controlHandles.push(new SigFieldControlHandle(annotation, 1));
controlHandles.push(new SigFieldControlHandle(annotation, 2));
controlHandles.push(new SigFieldControlHandle(annotation, 3));
}
return _this2;
}
return SigFieldSelectionModel;
}(Annotations.SelectionModel); // this is necessary to set the elementName before instantiation
// this is necessary to set the elementName before instantiation
SigFieldTxtAnnotation.prototype.elementName = 'SigFieldTxt';
SigFieldTxtAnnotation.SerializationType = Annotations.CustomAnnotation.SerializationTypes.CUSTOM; // register the annotation type so that it can be saved to XFDF files
// register the annotation type so that it can be saved to XFDF files
annotManager.registerAnnotationType(SigFieldTxtAnnotation.prototype.elementName, SigFieldTxtAnnotation);
var SigFieldTxtCreateTool = /*#__PURE__*/function (_Tools$GenericAnnotat) {
_inherits(SigFieldTxtCreateTool, _Tools$GenericAnnotat);
var _super3 = _createSuper(SigFieldTxtCreateTool);
function SigFieldTxtCreateTool(docViewer) {
_classCallCheck(this, SigFieldTxtCreateTool);
// TriangleAnnotation is the class (function) for our annotation we defined previously
return _super3.call(this, docViewer, SigFieldTxtAnnotation);
}
_createClass(SigFieldTxtCreateTool, [{
key: "mouseMove",
value: function mouseMove(e) {
_get(_getPrototypeOf(SigFieldTxtCreateTool.prototype), "mouseMove", this).call(this, e);
if (this.annotation) {
this.annotation.vertices[0].x = this.annotation.X;
this.annotation.vertices[0].y = this.annotation.Y;
this.annotation.vertices[1].x = this.annotation.X + this.annotation.Width;
this.annotation.vertices[1].y = this.annotation.Y;
this.annotation.vertices[2].x = this.annotation.X + this.annotation.Width;
this.annotation.vertices[2].y = this.annotation.Y + this.annotation.Height;
this.annotation.vertices[3].x = this.annotation.X;
this.annotation.vertices[3].y = this.annotation.Y + this.annotation.Height; // update the annotation appearance
// update the annotation appearance
annotManager.redrawAnnotation(this.annotation);
}
}
}]);
return SigFieldTxtCreateTool;
}(Tools.GenericAnnotationCreateTool);
;
var SigFieldTxtToolName = 'AnnotationCreateSigFieldTxt' + index;
var SigFieldTxtTool = new SigFieldTxtCreateTool(docViewer);
instance.registerTool({
toolName: SigFieldTxtToolName,
toolObject: SigFieldTxtTool,
buttonImage: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">' + '<path d="M12 7.77L18.39 18H5.61L12 7.77M12 4L2 20h20L12 4z"/>' + '<path fill="none" d="M0 0h24v24H0V0z"/>' + '</svg>',
buttonName: 'SigFieldTxtToolButton',
tooltip: 'SigFieldTxt'
}, SigFieldTxtAnnotation);
instance.setHeaderItems(function (header) {
header.getHeader('toolbarGroup-Shapes').get('freeHandToolGroupButton').insertBefore({
type: 'toolButton',
toolName: SigFieldTxtToolName
});
});
});
docViewer.on('documentLoaded', function () {
instance.annotManager.importAnnotations(storedAnnotations).then( /*#__PURE__*/function () {
var _ref16 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee14(importedAnnotations) {
return regeneratorRuntime.wrap(function _callee14$(_context14) {
while (1) {
switch (_context14.prev = _context14.next) {
case 0:
resolve(importedAnnotations);
case 1:
case "end":
return _context14.stop();
}
}
}, _callee14);
}));
return function (_x50) {
return _ref16.apply(this, arguments);
};
}());
});
});
}));
case 1:
case "end":
return _context15.stop();
}
}
}, _callee15);
}));
return function checkAndUpdateAnnotList(_x42, _x43, _x44, _x45, _x46, _x47, _x48, _x49) {
return _ref15.apply(this, arguments);
};
}();
exports.checkAndUpdateAnnotList = checkAndUpdateAnnotList;
var resetStoredData = function resetStoredData(handleStoredData) {
handleStoredData({
createProgress: 0,
progress: 0,
originalFilename: '',
filename: '',
signers: null,
indicatorProgress: 0,
storageHash: null,
storageProvider: 'FL',
annotations: null,
documentKey: null,
password: '',
expiryBlock: 0,
withPassword: true,
withExpiry: false
});
};
exports.resetStoredData = resetStoredData;
var getDefaultTool = function getDefaultTool() {
return (0, _window.isMobile)() ? 'Pan' : 'AnnotationEdit';
};
exports.getDefaultTool = getDefaultTool;
var getShortenedName = function getShortenedName(doc) {
if (doc.name.length + doc.ext.length >= 32) {
doc.name = doc.name.slice(0, 31 - doc.ext.length); // Our file name can only be 32 characters long WITH NULL TERMINATOR, including extension. Do calculation below and slice it.
}
return doc;
};
exports.getShortenedName = getShortenedName;
var updateSignatureFinder = function updateSignatureFinder(annotManager, handleFieldsByPage, handleNumOfSigned, ethAccount) {
var mySigFields = _toConsumableArray(annotManager.getAnnotationsList().filter(function (annot) {
return annot.Subject == "Widget" && annot.Signer != null || annot.Subject == "Signature" && annot.getCustomData('Signer').address == ethAccount;
}));
if (mySigFields != null) {
var temp_fieldsByPage = [];
var temp_numOfSigned = 0;
mySigFields.map(function (annot, idx) {
var signed = annot.Subject == "Widget" && annot.annot != null || annot.Subject == "Signature" && annot.getCustomData('Signer') != null;
var pageNumberAdded = _lodash.default.findIndex(temp_fieldsByPage, {
'page': annot.PageNumber
});
if (pageNumberAdded == -1) {
// page number has not been added yet
if (signed == true) {
temp_numOfSigned = temp_numOfSigned + 1;
}
temp_fieldsByPage.push({
page: annot.PageNumber,
annots: [annot],
length: 1,
signed: signed
});
} else {
// page number is already added
// currently length is number of not signed fields
temp_fieldsByPage[pageNumberAdded].annots.push(annot);
temp_fieldsByPage[pageNumberAdded].length = temp_fieldsByPage[pageNumberAdded].length + 1;
if (signed == true) {
temp_numOfSigned = temp_numOfSigned + 1;
}
temp_fieldsByPage[pageNumberAdded].signed = temp_fieldsByPage[pageNumberAdded].signed && signed;
}
});
var newFields = _lodash.default.orderBy(temp_fieldsByPage, ['page'], ['asc']);
handleNumOfSigned(temp_numOfSigned);
handleFieldsByPage(newFields);
}
};
exports.updateSignatureFinder = updateSignatureFinder;