What is the fastest way to create a union of many polygons in turfjs? - turfjs

I have something like this but with large sets it's awfully slow:
let unionize = (triangles) => {
if(triangles.length == 0) {
return null
}
let ret = triangles[0].feature
triangles.forEach((t, index) => {
if(index > 0) {
ret = turf.union(t, t)
}
})
return ret
}

featureEach tends to be faster than a trivial array forEach although with more features the gain decreases.
<script src="https://cdn.jsdelivr.net/npm/#turf/turf#5.1.6/turf.min.js"></script>
<script>
const generateGrid = (cellSide = 100, units = "kilometers") => {
const bbox = [-95, 30, -85, 40];
return turf.triangleGrid(bbox, cellSide, {
units
});
}
const unionizeForEach = (triangles) => {
console.time('unionizeForEach');
if (triangles.length == 0) {
return null
}
let ret = triangles[0];
triangles.forEach((t, index) => {
if (index > 0) {
ret = turf.union(ret, t)
}
});
console.timeEnd('unionizeForEach');
return ret
}
const unionizeFeatureEach = (triangles) => {
console.time('unionizeFeatureEach');
if (triangles.features.length === 0) {
return null
}
let ret = triangles.features[0];
turf.featureEach(triangles, function (currentFeature, featureIndex) {
if (featureIndex > 0) {
ret = turf.union(ret, currentFeature)
}
});
console.timeEnd('unionizeFeatureEach');
return ret;
}
[100, 50, 10].map(cellSide => {
const triangleGrid = generateGrid(cellSide, 'kilometers');
console.info(`triangleGrid has ${triangleGrid.features.length} features`);
const union_foreach = unionizeForEach(triangleGrid.features);
const union_featureeach = unionizeFeatureEach(triangleGrid);
console.assert(JSON.stringify(union_foreach) === JSON.stringify(union_featureeach));
console.log('\n---\n');
})
</script>

Related

Typewriter is not working when loaded via npm import (compiled with Babel)

I set up Typewriter on a site, it works fine when loaded via the direct src.
<script src="https://unpkg.com/typewriter-effect#2.3.1/dist/core.js"></script>
<script>
window.addEventListener('DOMContentLoaded', () => {document.getElementById('typewriter-container');
const typewriter = new Typewriter(whatever, { ... });
...
But when I do it with npm, it doesn't work.
What does "doing it with npm" mean?
Well, since loading stuff the traditional way seems to be outdated... I'm doing the same thing with npm and using the import into a file:
src/typewriter.js
import Typewriter from 'typewriter-effect/dist/core';
And then compiling this file with webpack and babel, and loading that file instead.
<script src="/my_site_stuff/dist/typewriter.js"></script>
This is the compiled file:
dist/typewriter.js
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ "./node_modules/typewriter-effect/dist/core.js":
/*!*****************************************************!*\
!*** ./node_modules/typewriter-effect/dist/core.js ***!
\*****************************************************/
/***/ (function(module, exports, __webpack_require__) {
/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(obj) { "#babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
!function (e, t) {
"object" == ( false ? 0 : _typeof(exports)) && "object" == ( false ? 0 : _typeof(module)) ? module.exports = t() : true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (t),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : 0;
}("undefined" != typeof self ? self : this, function () {
return function () {
var e = {
75: function _(e) {
(function () {
var t, n, r, o, a, s;
"undefined" != typeof performance && null !== performance && performance.now ? e.exports = function () {
return performance.now();
} : "undefined" != typeof process && null !== process && process.hrtime ? (e.exports = function () {
return (t() - a) / 1e6;
}, n = process.hrtime, o = (t = function t() {
var e;
return 1e9 * (e = n())[0] + e[1];
})(), s = 1e9 * process.uptime(), a = o - s) : Date.now ? (e.exports = function () {
return Date.now() - r;
}, r = Date.now()) : (e.exports = function () {
return new Date().getTime() - r;
}, r = new Date().getTime());
}).call(this);
},
4087: function _(e, t, n) {
for (var r = n(75), o = "undefined" == typeof window ? n.g : window, a = ["moz", "webkit"], s = "AnimationFrame", i = o["request" + s], u = o["cancel" + s] || o["cancelRequest" + s], l = 0; !i && l < a.length; l++) {
i = o[a[l] + "Request" + s], u = o[a[l] + "Cancel" + s] || o[a[l] + "CancelRequest" + s];
}
if (!i || !u) {
var c = 0,
p = 0,
d = [];
i = function i(e) {
if (0 === d.length) {
var t = r(),
n = Math.max(0, 16.666666666666668 - (t - c));
c = n + t, setTimeout(function () {
var e = d.slice(0);
d.length = 0;
for (var t = 0; t < e.length; t++) {
if (!e[t].cancelled) try {
e[t].callback(c);
} catch (e) {
setTimeout(function () {
throw e;
}, 0);
}
}
}, Math.round(n));
}
return d.push({
handle: ++p,
callback: e,
cancelled: !1
}), p;
}, u = function u(e) {
for (var t = 0; t < d.length; t++) {
d[t].handle === e && (d[t].cancelled = !0);
}
};
}
e.exports = function (e) {
return i.call(o, e);
}, e.exports.cancel = function () {
u.apply(o, arguments);
}, e.exports.polyfill = function (e) {
e || (e = o), e.requestAnimationFrame = i, e.cancelAnimationFrame = u;
};
}
},
t = {};
function n(r) {
var o = t[r];
if (void 0 !== o) return o.exports;
var a = t[r] = {
exports: {}
};
return e[r].call(a.exports, a, a.exports, n), a.exports;
}
n.n = function (e) {
var t = e && e.__esModule ? function () {
return e.default;
} : function () {
return e;
};
return n.d(t, {
a: t
}), t;
}, n.d = function (e, t) {
for (var r in t) {
n.o(t, r) && !n.o(e, r) && Object.defineProperty(e, r, {
enumerable: !0,
get: t[r]
});
}
}, n.g = function () {
if ("object" == (typeof globalThis === "undefined" ? "undefined" : _typeof(globalThis))) return globalThis;
try {
return this || new Function("return this")();
} catch (e) {
if ("object" == (typeof window === "undefined" ? "undefined" : _typeof(window))) return window;
}
}(), n.o = function (e, t) {
return Object.prototype.hasOwnProperty.call(e, t);
};
var r = {};
return function () {
"use strict";
n.d(r, {
default: function _default() {
return S;
}
});
var e = n(4087),
t = n.n(e);
var o = function o(e) {
return new RegExp(/<[a-z][\s\S]*>/i).test(e);
},
a = function a(e) {
var t = document.createElement("div");
return t.innerHTML = e, t.childNodes;
},
s = function s(e, t) {
return Math.floor(Math.random() * (t - e + 1)) + e;
};
var i = "TYPE_CHARACTER",
u = "REMOVE_CHARACTER",
l = "REMOVE_ALL",
c = "REMOVE_LAST_VISIBLE_NODE",
p = "PAUSE_FOR",
d = "CALL_FUNCTION",
f = "ADD_HTML_TAG_ELEMENT",
v = "CHANGE_DELETE_SPEED",
h = "CHANGE_DELAY",
m = "CHANGE_CURSOR",
y = "PASTE_STRING",
g = "HTML_TAG";
function E(e, t) {
var n = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var r = Object.getOwnPropertySymbols(e);
t && (r = r.filter(function (t) {
return Object.getOwnPropertyDescriptor(e, t).enumerable;
})), n.push.apply(n, r);
}
return n;
}
function w(e) {
for (var t = 1; t < arguments.length; t++) {
var n = null != arguments[t] ? arguments[t] : {};
t % 2 ? E(Object(n), !0).forEach(function (t) {
N(e, t, n[t]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : E(Object(n)).forEach(function (t) {
Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));
});
}
return e;
}
function T(e) {
return function (e) {
if (Array.isArray(e)) return b(e);
}(e) || function (e) {
if ("undefined" != typeof Symbol && null != e[Symbol.iterator] || null != e["##iterator"]) return Array.from(e);
}(e) || function (e, t) {
if (e) {
if ("string" == typeof e) return b(e, t);
var n = Object.prototype.toString.call(e).slice(8, -1);
return "Object" === n && e.constructor && (n = e.constructor.name), "Map" === n || "Set" === n ? Array.from(e) : "Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n) ? b(e, t) : void 0;
}
}(e) || function () {
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 b(e, t) {
(null == t || t > e.length) && (t = e.length);
for (var n = 0, r = new Array(t); n < t; n++) {
r[n] = e[n];
}
return r;
}
function A(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r);
}
}
function N(e, t, n) {
return t in e ? Object.defineProperty(e, t, {
value: n,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[t] = n, e;
}
var S = function () {
function n(r, E) {
var b = this;
if (function (e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function");
}(this, n), N(this, "state", {
cursorAnimation: null,
lastFrameTime: null,
pauseUntil: null,
eventQueue: [],
eventLoop: null,
eventLoopPaused: !1,
reverseCalledEvents: [],
calledEvents: [],
visibleNodes: [],
initialOptions: null,
elements: {
container: null,
wrapper: document.createElement("span"),
cursor: document.createElement("span")
}
}), N(this, "options", {
strings: null,
cursor: "|",
delay: "natural",
pauseFor: 1500,
deleteSpeed: "natural",
loop: !1,
autoStart: !1,
devMode: !1,
skipAddStyles: !1,
wrapperClassName: "Typewriter__wrapper",
cursorClassName: "Typewriter__cursor",
stringSplitter: null,
onCreateTextNode: null,
onRemoveNode: null
}), N(this, "setupWrapperElement", function () {
b.state.elements.container && (b.state.elements.wrapper.className = b.options.wrapperClassName, b.state.elements.cursor.className = b.options.cursorClassName, b.state.elements.cursor.innerHTML = b.options.cursor, b.state.elements.container.innerHTML = "", b.state.elements.container.appendChild(b.state.elements.wrapper), b.state.elements.container.appendChild(b.state.elements.cursor));
}), N(this, "start", function () {
return b.state.eventLoopPaused = !1, b.runEventLoop(), b;
}), N(this, "pause", function () {
return b.state.eventLoopPaused = !0, b;
}), N(this, "stop", function () {
return b.state.eventLoop && ((0, e.cancel)(b.state.eventLoop), b.state.eventLoop = null), b;
}), N(this, "pauseFor", function (e) {
return b.addEventToQueue(p, {
ms: e
}), b;
}), N(this, "typeOutAllStrings", function () {
return "string" == typeof b.options.strings ? (b.typeString(b.options.strings).pauseFor(b.options.pauseFor), b) : (b.options.strings.forEach(function (e) {
b.typeString(e).pauseFor(b.options.pauseFor).deleteAll(b.options.deleteSpeed);
}), b);
}), N(this, "typeString", function (e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null;
if (o(e)) return b.typeOutHTMLString(e, t);
if (e) {
var n = b.options || {},
r = n.stringSplitter,
a = "function" == typeof r ? r(e) : e.split("");
b.typeCharacters(a, t);
}
return b;
}), N(this, "pasteString", function (e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null;
return o(e) ? b.typeOutHTMLString(e, t, !0) : (e && b.addEventToQueue(y, {
character: e,
node: t
}), b);
}), N(this, "typeOutHTMLString", function (e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null,
n = arguments.length > 2 ? arguments[2] : void 0,
r = a(e);
if (r.length > 0) for (var o = 0; o < r.length; o++) {
var s = r[o],
i = s.innerHTML;
s && 3 !== s.nodeType ? (s.innerHTML = "", b.addEventToQueue(f, {
node: s,
parentNode: t
}), n ? b.pasteString(i, s) : b.typeString(i, s)) : s.textContent && (n ? b.pasteString(s.textContent, t) : b.typeString(s.textContent, t));
}
return b;
}), n;
}();
}(), r.default;
}();
});
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ id: moduleId,
/******/ loaded: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ !function() {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function() { return module['default']; } :
/******/ function() { return module; };
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ !function() {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/node module decorator */
/******/ !function() {
/******/ __webpack_require__.nmd = function(module) {
/******/ module.paths = [];
/******/ if (!module.children) module.children = [];
/******/ return module;
/******/ };
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
!function() {
"use strict";
/*!*************************************!*\
!*** ./src/js/typewriter-effect.js ***!
\*************************************/
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! typewriter-effect/dist/core */ "./node_modules/typewriter-effect/dist/core.js");
/* harmony import */ var typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0__);
}();
/******/ })()
;
//# sourceMappingURL=typeWriter.js.map
How do I know what the problem is?
Webpack encloses everything in the compiled file so nothing leaks into the global scope.
You'd have to change your src file and do:
import Typewriter from 'typewriter-effect/dist/core';
window.Typewriter = Typewriter;
Then, when using it, instead of:
const typewriter = new Typewriter(...);
Just do:
const typewriter = new window.Typewriter(...);
What we are doing here is, making it available to the global scope.

Vuejs-pdf print

I'm using vuejs-pdf to print some pages of my pdf and the print is not show the characters :
that's the code i'm using :
<button #click="$refs.myPdfComponent.print(100,pages)">Print </button>
<pdf v-for="i in pages" :key="i" ref="newpdf" :src="'pdf/'+src" :page="i" class="rounded border
border-info mb-4" :rotate="rotate" #progress="loadedRatio = $event" #error="error" #num-pages="numPages = $event" #link-clicked="page = $event" > </pdf>
and the pdf i'm printing is myPdfComponent the newpdf is the only the pages i need :
<pdf v-if="show" ref="myPdfComponent" class="rounded border border-info mb-4" :src="'pdf/'+src"
:page="page" :rotate="rotate" #progress="loadedRatio = $event" #error="error" #num-pages="numPages =
$event" #link-clicked="page = $event"></pdf>
Open the vue-pdf plugin directory node_modules/vue-pdf/src/pdfjsWrapper.js
and replace
import { PDFLinkService } from 'pdfjs-dist/es5/web/pdf_viewer';
var pendingOperation = Promise.resolve();
export default function(PDFJS) {
function isPDFDocumentLoadingTask(obj) {
return typeof(obj) === 'object' && obj !== null && obj.__PDFDocumentLoadingTask === true;
// or: return obj.constructor.name === 'PDFDocumentLoadingTask';
}
function createLoadingTask(src, options) {
var source;
if ( typeof(src) === 'string' )
source = { url: src };
else if ( src instanceof Uint8Array )
source = { data: src };
else if ( typeof(src) === 'object' && src !== null )
source = Object.assign({}, src);
else
throw new TypeError('invalid src type');
// source.verbosity = PDFJS.VerbosityLevel.INFOS;
// source.pdfBug = true;
// source.stopAtErrors = true;
if ( options && options.withCredentials )
source.withCredentials = options.withCredentials;
var loadingTask = PDFJS.getDocument(source);
loadingTask.__PDFDocumentLoadingTask = true; // since PDFDocumentLoadingTask is not public
if ( options && options.onPassword )
loadingTask.onPassword = options.onPassword;
if ( options && options.onProgress )
loadingTask.onProgress = options.onProgress;
return loadingTask;
}
function PDFJSWrapper(canvasElt, annotationLayerElt, emitEvent) {
var pdfDoc = null;
var pdfPage = null;
var pdfRender = null;
var canceling = false;
canvasElt.getContext('2d').save();
function clearCanvas() {
canvasElt.getContext('2d').clearRect(0, 0, canvasElt.width, canvasElt.height);
}
function clearAnnotations() {
while ( annotationLayerElt.firstChild )
annotationLayerElt.removeChild(annotationLayerElt.firstChild);
}
this.destroy = function() {
if ( pdfDoc === null )
return;
// Aborts all network requests and destroys worker.
pendingOperation = pdfDoc.destroy();
pdfDoc = null;
}
this.getResolutionScale = function() {
return canvasElt.offsetWidth / canvasElt.width;
}
this.printPage = function(dpi, pageNumberOnly) {
if ( pdfPage === null )
return;
// 1in == 72pt
// 1in == 96px
var PRINT_RESOLUTION = dpi === undefined ? 150 : dpi;
var PRINT_UNITS = PRINT_RESOLUTION / 72.0;
var CSS_UNITS = 96.0 / 72.0;
/*var iframeElt = document.createElement('iframe');
function removeIframe() {
iframeElt.parentNode.removeChild(iframeElt);
}*/
var printContainerElement = document.createElement('div');
printContainerElement.setAttribute('id', 'print-container')
function removePrintContainer() {
printContainerElement.parentNode.removeChild(printContainerElement);
}
new Promise(function(resolve, reject) {
/*
iframeElt.frameBorder = '0';
iframeElt.scrolling = 'no';
iframeElt.width = '0px;'
iframeElt.height = '0px;'
iframeElt.style.cssText = 'position: absolute; top: 0; left: 0';
iframeElt.onload = function() {
resolve(this.contentWindow);
}
window.document.body.appendChild(iframeElt);*/
printContainerElement.frameBorder = '0';
printContainerElement.scrolling = 'no';
printContainerElement.width = '0px;'
printContainerElement.height = '0px;'
printContainerElement.style.cssText = 'position: absolute; top: 0; left: 0';
window.document.body.appendChild(printContainerElement);
resolve(window)
})
.then(function(win) {
win.document.title = '';
return pdfDoc.getPage(1)
.then(function(page) {
var viewport = page.getViewport({ scale: 1 });
//win.document.head.appendChild(win.document.createElement('style')).textContent =
printContainerElement.appendChild(win.document.createElement('style')).textContent =
'#supports ((size:A4) and (size:1pt 1pt)) {' +
'#page { margin: 1pt; size: ' + ((viewport.width * PRINT_UNITS) / CSS_UNITS) + 'pt ' + ((viewport.height * PRINT_UNITS) / CSS_UNITS) + 'pt; }' +
'}' +
'#print-canvas { display: none }' +
'#media print {' +
'body { margin: 0 }' +
'canvas { page-break-before: avoid; page-break-after: always; page-break-inside: avoid }' +
'#print-canvas { page-break-before: avoid; page-break-after: always; page-break-inside: avoid; display: block }' +
'body > *:not(#print-container) { display: none; }' +
'}'+
'#media screen {' +
'body { margin: 0 }' +
'}'+
''
return win;
})
})
.then(function(win) {
var allPages = [];
for ( var pageNumber = 1; pageNumber <= pdfDoc.numPages; ++pageNumber ) {
if ( pageNumberOnly !== undefined && pageNumberOnly.indexOf(pageNumber) === -1 )
continue;
allPages.push(
pdfDoc.getPage(pageNumber)
.then(function(page) {
var viewport = page.getViewport({ scale: 1 });
//var printCanvasElt = win.document.body.appendChild(win.document.createElement('canvas'));
var printCanvasElt = printContainerElement.appendChild(win.document.createElement('canvas'));
printCanvasElt.setAttribute('id', 'print-canvas')
printCanvasElt.width = (viewport.width * PRINT_UNITS);
printCanvasElt.height = (viewport.height * PRINT_UNITS);
return page.render({
canvasContext: printCanvasElt.getContext('2d'),
transform: [ // Additional transform, applied just before viewport transform.
PRINT_UNITS, 0, 0,
PRINT_UNITS, 0, 0
],
viewport: viewport,
intent: 'print'
}).promise;
})
);
}
Promise.all(allPages)
.then(function() {
win.focus(); // Required for IE
if (win.document.queryCommandSupported('print')) {
win.document.execCommand('print', false, null);
} else {
win.print();
}
removePrintContainer();
})
.catch(function(err) {
removePrintContainer();
emitEvent('error', err);
})
})
}
this.renderPage = function(rotate) {
if ( pdfRender !== null ) {
if ( canceling )
return;
canceling = true;
pdfRender.cancel();
return;
}
if ( pdfPage === null )
return;
var pageRotate = (pdfPage.rotate === undefined ? 0 : pdfPage.rotate) + (rotate === undefined ? 0 : rotate);
var scale = canvasElt.offsetWidth / pdfPage.getViewport({ scale: 1 }).width * (window.devicePixelRatio || 1);
var viewport = pdfPage.getViewport({ scale: scale, rotation:pageRotate });
emitEvent('page-size', viewport.width, viewport.height, scale);
canvasElt.width = viewport.width;
canvasElt.height = viewport.height;
pdfRender = pdfPage.render({
canvasContext: canvasElt.getContext('2d'),
viewport: viewport
});
annotationLayerElt.style.visibility = 'hidden';
clearAnnotations();
var viewer = {
scrollPageIntoView: function(params) {
emitEvent('link-clicked', params.pageNumber)
},
};
var linkService = new PDFLinkService();
linkService.setDocument(pdfDoc);
linkService.setViewer(viewer);
pendingOperation = pendingOperation.then(function() {
var getAnnotationsOperation =
pdfPage.getAnnotations({ intent: 'display' })
.then(function(annotations) {
PDFJS.AnnotationLayer.render({
viewport: viewport.clone({ dontFlip: true }),
div: annotationLayerElt,
annotations: annotations,
page: pdfPage,
linkService: linkService,
renderInteractiveForms: false
});
});
var pdfRenderOperation =
pdfRender.promise
.then(function() {
annotationLayerElt.style.visibility = '';
canceling = false;
pdfRender = null;
})
.catch(function(err) {
pdfRender = null;
if ( err instanceof PDFJS.RenderingCancelledException ) {
canceling = false;
this.renderPage(rotate);
return;
}
emitEvent('error', err);
}.bind(this))
return Promise.all([getAnnotationsOperation, pdfRenderOperation]);
}.bind(this));
}
this.forEachPage = function(pageCallback) {
var numPages = pdfDoc.numPages;
(function next(pageNum) {
pdfDoc.getPage(pageNum)
.then(pageCallback)
.then(function() {
if ( ++pageNum <= numPages )
next(pageNum);
})
})(1);
}
this.loadPage = function(pageNumber, rotate) {
pdfPage = null;
if ( pdfDoc === null )
return;
pendingOperation = pendingOperation.then(function() {
return pdfDoc.getPage(pageNumber);
})
.then(function(page) {
pdfPage = page;
this.renderPage(rotate);
emitEvent('page-loaded', page.pageNumber);
}.bind(this))
.catch(function(err) {
clearCanvas();
clearAnnotations();
emitEvent('error', err);
});
}
this.loadDocument = function(src) {
pdfDoc = null;
pdfPage = null;
emitEvent('num-pages', undefined);
if ( !src ) {
canvasElt.removeAttribute('width');
canvasElt.removeAttribute('height');
clearAnnotations();
return;
}
// wait for pending operation ends
pendingOperation = pendingOperation.then(function() {
var loadingTask;
if ( isPDFDocumentLoadingTask(src) ) {
if ( src.destroyed ) {
emitEvent('error', new Error('loadingTask has been destroyed'));
return
}
loadingTask = src;
} else {
loadingTask = createLoadingTask(src, {
onPassword: function(updatePassword, reason) {
var reasonStr;
switch (reason) {
case PDFJS.PasswordResponses.NEED_PASSWORD:
reasonStr = 'NEED_PASSWORD';
break;
case PDFJS.PasswordResponses.INCORRECT_PASSWORD:
reasonStr = 'INCORRECT_PASSWORD';
break;
}
emitEvent('password', updatePassword, reasonStr);
},
onProgress: function(status) {
var ratio = status.loaded / status.total;
emitEvent('progress', Math.min(ratio, 1));
}
});
}
return loadingTask.promise;
})
.then(function(pdf) {
pdfDoc = pdf;
emitEvent('num-pages', pdf.numPages);
emitEvent('loaded');
})
.catch(function(err) {
clearCanvas();
clearAnnotations();
emitEvent('error', err);
})
}
annotationLayerElt.style.transformOrigin = '0 0';
}
return {
createLoadingTask: createLoadingTask,
PDFJSWrapper: PDFJSWrapper,
}
}

How to change the width of NormalPeoplePicker dropdown

I'm using default example of NormalPeoplePicker from https://developer.microsoft.com/en-us/fluentui#/controls/web/peoplepicker#IPeoplePickerProps.
When the dropdown displays it cuts off longer items (example: 'Anny Lundqvist, Junior Manager of Soft..'). How do I make it wider, so that the full item's text displays?
import * as React from 'react';
import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox';
import { IPersonaProps } from 'office-ui-fabric-react/lib/Persona';
import { IBasePickerSuggestionsProps, NormalPeoplePicker, ValidationState } from 'office-ui-fabric-react/lib/Pickers';
import { people, mru } from '#uifabric/example-data';
const suggestionProps: IBasePickerSuggestionsProps = {
suggestionsHeaderText: 'Suggested People',
mostRecentlyUsedHeaderText: 'Suggested Contacts',
noResultsFoundText: 'No results found',
loadingText: 'Loading',
showRemoveButtons: true,
suggestionsAvailableAlertText: 'People Picker Suggestions available',
suggestionsContainerAriaLabel: 'Suggested contacts',
};
const checkboxStyles = {
root: {
marginTop: 10,
},
};
export const PeoplePickerNormalExample: React.FunctionComponent = () => {
const [delayResults, setDelayResults] = React.useState(false);
const [isPickerDisabled, setIsPickerDisabled] = React.useState(false);
const [mostRecentlyUsed, setMostRecentlyUsed] = React.useState<IPersonaProps[]>(mru);
const [peopleList, setPeopleList] = React.useState<IPersonaProps[]>(people);
const picker = React.useRef(null);
const onFilterChanged = (
filterText: string,
currentPersonas: IPersonaProps[],
limitResults?: number,
): IPersonaProps[] | Promise<IPersonaProps[]> => {
if (filterText) {
let filteredPersonas: IPersonaProps[] = filterPersonasByText(filterText);
filteredPersonas = removeDuplicates(filteredPersonas, currentPersonas);
filteredPersonas = limitResults ? filteredPersonas.slice(0, limitResults) : filteredPersonas;
return filterPromise(filteredPersonas);
} else {
return [];
}
};
const filterPersonasByText = (filterText: string): IPersonaProps[] => {
return peopleList.filter(item => doesTextStartWith(item.text as string, filterText));
};
const filterPromise = (personasToReturn: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> => {
if (delayResults) {
return convertResultsToPromise(personasToReturn);
} else {
return personasToReturn;
}
};
const returnMostRecentlyUsed = (currentPersonas: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> => {
return filterPromise(removeDuplicates(mostRecentlyUsed, currentPersonas));
};
const onRemoveSuggestion = (item: IPersonaProps): void => {
const indexPeopleList: number = peopleList.indexOf(item);
const indexMostRecentlyUsed: number = mostRecentlyUsed.indexOf(item);
if (indexPeopleList >= 0) {
const newPeople: IPersonaProps[] = peopleList
.slice(0, indexPeopleList)
.concat(peopleList.slice(indexPeopleList + 1));
setPeopleList(newPeople);
}
if (indexMostRecentlyUsed >= 0) {
const newSuggestedPeople: IPersonaProps[] = mostRecentlyUsed
.slice(0, indexMostRecentlyUsed)
.concat(mostRecentlyUsed.slice(indexMostRecentlyUsed + 1));
setMostRecentlyUsed(newSuggestedPeople);
}
};
const onDisabledButtonClick = (): void => {
setIsPickerDisabled(!isPickerDisabled);
};
const onToggleDelayResultsChange = (): void => {
setDelayResults(!delayResults);
};
return (
<div>
<NormalPeoplePicker
// eslint-disable-next-line react/jsx-no-bind
onResolveSuggestions={onFilterChanged}
// eslint-disable-next-line react/jsx-no-bind
onEmptyInputFocus={returnMostRecentlyUsed}
getTextFromItem={getTextFromItem}
pickerSuggestionsProps={suggestionProps}
className={'ms-PeoplePicker'}
key={'normal'}
// eslint-disable-next-line react/jsx-no-bind
onRemoveSuggestion={onRemoveSuggestion}
onValidateInput={validateInput}
removeButtonAriaLabel={'Remove'}
inputProps={{
onBlur: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onBlur called'),
onFocus: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onFocus called'),
'aria-label': 'People Picker',
}}
componentRef={picker}
onInputChange={onInputChange}
resolveDelay={300}
disabled={isPickerDisabled}
/>
<Checkbox
label="Disable People Picker"
checked={isPickerDisabled}
// eslint-disable-next-line react/jsx-no-bind
onChange={onDisabledButtonClick}
styles={checkboxStyles}
/>
<Checkbox
label="Delay Suggestion Results"
defaultChecked={delayResults}
// eslint-disable-next-line react/jsx-no-bind
onChange={onToggleDelayResultsChange}
styles={checkboxStyles}
/>
</div>
);
};
function doesTextStartWith(text: string, filterText: string): boolean {
return text.toLowerCase().indexOf(filterText.toLowerCase()) === 0;
}
function removeDuplicates(personas: IPersonaProps[], possibleDupes: IPersonaProps[]) {
return personas.filter(persona => !listContainsPersona(persona, possibleDupes));
}
function listContainsPersona(persona: IPersonaProps, personas: IPersonaProps[]) {
if (!personas || !personas.length || personas.length === 0) {
return false;
}
return personas.filter(item => item.text === persona.text).length > 0;
}
function convertResultsToPromise(results: IPersonaProps[]): Promise<IPersonaProps[]> {
return new Promise<IPersonaProps[]>((resolve, reject) => setTimeout(() => resolve(results), 2000));
}
function getTextFromItem(persona: IPersonaProps): string {
return persona.text as string;
}
function validateInput(input: string): ValidationState {
if (input.indexOf('#') !== -1) {
return ValidationState.valid;
} else if (input.length > 1) {
return ValidationState.warning;
} else {
return ValidationState.invalid;
}
}
/**
* Takes in the picker input and modifies it in whichever way
* the caller wants, i.e. parsing entries copied from Outlook (sample
* input: "Aaron Reid <aaron>").
*
* #param input The text entered into the picker.
*/
function onInputChange(input: string): string {
const outlookRegEx = /<.*>/g;
const emailAddress = outlookRegEx.exec(input);
if (emailAddress && emailAddress[0]) {
return emailAddress[0].substring(1, emailAddress[0].length - 1);
}
return input;
}
Component which renders suggestion list have fixed width of 180px. Take a look at PeoplePickerItemSuggestion.styles.ts.
What you can do is to modify this class .ms-PeoplePicker-Persona:
.ms-PeoplePicker-Persona {
width: 260px; // Or what ever you want
}
UPDATE - Solution from comments
Change width trough styles property of PeoplePickerItemSuggestion Component
const onRenderSuggestionsItem = (personaProps, suggestionsProps) => (
<PeoplePickerItemSuggestion
personaProps={personaProps}
suggestionsProps={suggestionsProps}
styles={{ personaWrapper: { width: '100%' }}}
/>
);
<NormalPeoplePicker
onRenderSuggestionsItem={onRenderSuggestionsItem}
pickerCalloutProps={{ calloutWidth: 500 }}
...restProps
/>
Working Codepen example
For more information how to customize components read Component Styling.

React Native SectionList (title, data) - Search in the data field

I am trying to build Search function in SectionList. I have search inside the 'data' (second field) and not inside 'title' but I am not able to make it work.
My Data is about the Flat / resident details of an Apartment -
sectiondata =
[{"title":"GROUND FLOOR",
"data":[
{"id":"48","res_type":"owner","user_name":"Ashwani","flat_id":"1","flat_name":"001","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"98855550"},
{"id":"49","res_type":"owner","user_name":"Rahul","flat_id":"2","flat_name":"002","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"999999"}
]
}]
I am trying something like this but it is not working.
searchFilterFunction = (text) => {
let search = text.toLowerCase();
this.setState({
check: this.state.sectiondata.filter(
obj => obj.data['flat_name'].toLowerCase().includes(search))
});
}
How to filter data base on name? Please assist here.
Thanks.
You can try to search like this:
onChangeText(text) {
if (text.trim().length > 0) {
var temp = []
sectiondata.map((item) => {
var dataItem = {};
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.brandData = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})
} else {
this.setState({
sectiondata: this.state.tempData
})
}
}
searchFilterFunction(text) {
if( text == undefined || text == '') {
this.setState({
sectiondata: this.arrayholder
})
return;
}
if (text.trim().length > 0) {
var temp = []
this.state.sectiondata.map((item) => {
var dataItem = {};
var title = item.title;
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.title = title;
dataItem.data = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})

how to create a seating layout for bus react native

I was wondering to create seat layout for the bus. So, I found this link which show how to create the map of seats.
So following is the response I get from API
{"seats":[{"width":1,"fare":"","zIndex":0,"number":"A1","type":"A1","serviceTaxAmount":"0","convenience_charge":"0","commission":"","operatorServiceChargeAbsolute":"","operatorServiceChargePercent":"0","totalFareWithTaxes":"","ladiesSeat":"","bookedBy":"","ac":"true","sleeper":"","serviceTaxPer":"0","available":"","length":1,"id":"A1","seatid":"A1","row":0,"column":1},{"width":1,"fare":"1000","zIndex":0,"number":"A3","type":"A3","serviceTaxAmount":"0","convenience_charge":"0","commission":"","operatorServiceChargeAbsolute":"","operatorServiceChargePercent":"0","totalFareWithTaxes":"1000","ladiesSeat":"","bookedBy":"","ac":"true","sleeper":"","serviceTaxPer":"0","available":"1","length":1,"id":"A3","seatid":"A3","row":2,"column":1}]}
this is what I did so far
componentDidMount() {
return fetch(seat_url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
row: responseJson.seats.row,
column: responseJson.seats.column,
}, function() {
});
})
.catch((error) => {
console.error(error);
});
}
So how to use the above response in adjacent with ROWS and COLS because rows and cols will not be constant it will be dynamic on each row and column. In Example provided from above link cols and rows are fixed. I want to access them dynamically.
Use table component & create Rows, Columns. Install below package
npm install react-native-table-component
import { Table, TableWrapper, Row, Rows, Col, Cols, Cell } from 'react-native-table-component';
let myData1= [];
const rowData1= [];
const type_data= [];
let row_length=[];
let col_length=[];
let type_length=[];
let row_count,col_count,a,b,c,d;
componentDidMount() {
return fetch(seat_url)
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
var resultresponse = responseJson.result;
for (var i in resultresponse) {
var seatresponse = resultresponse[i].seats;
for(var j in seatresponse)
{
myData1.push(seatresponse[j]);
row_length.push(seatresponse[j].row);
col_length.push(seatresponse[j].column);
type_length.push(seatresponse[j].type);
rowData1.push(`${seatresponse[j].row},${seatresponse[j].column}`);
}
}
row_count = Array.from(new Set(row_length));
col_count = Array.from(new Set(col_length));
a = row_count.length.toString();
b = col_count.length.toString();
c = row_length.length.toString();
d = col_length.length.toString();
})
}
render() {
const state = this.state;
const tableData1 = [];
const tableData = [];
for (let i = 1; i <= b; i ++) {
rowData = [];
rowData2 = [];
// If table row & col matches with your response row & col then, push the data else assign as NULL.
for (let j = 0; j < a; j ++) {
rowData.push(${j},${i});
for (let k = 0; k <= rowData1.length && k<=type_length.length; k ++) {
if(${j},${i} === rowData1[k])
{
rowData[rowData.indexOf(${j},${i})] = myData1[k];
}
}
for (let l = 0; l <= rowData1.length; l ++) {
if(`${j},${i}` != rowData1[l])
{
rowData[rowData.indexOf(`${j},${i}`)] = 'NULL';
}
}
}
tableData.push(rowData);
}
return (
<View style={styles.MainContainer}>
<Table borderStyle={{borderColor: 'transparent'}} >
<Row style={styles.head} textStyle={styles.text}/>
{
tableData.map((rowData, index) => (
<TableWrapper key={index} style={styles.row}>
{
rowData.map((cellData, cellIndex) => (
<Cell style={{backgroundColor: 'orange', margin:5, height:40, width:40}} key={cellIndex} data={cellData.type} />
))
}
</TableWrapper>
))
}
</Table>
</View>
);
}