code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
function setAttributeNS(node, attributeNamespace, attributeName, attributeValue) { node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
Set attribute with namespace for a node. The attribute value can be either string or Trusted value (if application uses Trusted Types).
setAttributeNS ( node , attributeNamespace , attributeName , attributeValue )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function setValueForProperty(node, name, value, isCustomComponentTag) { var propertyInfo = getPropertyInfo(name); if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { return; } if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { value = null; } // If the prop isn't in the special list, treat it as a simple attribute. if (isCustomComponentTag || propertyInfo === null) { if (isAttributeNameSafe(name)) { var _attributeName = name; if (value === null) { node.removeAttribute(_attributeName); } else { setAttribute(node, _attributeName, toStringOrTrustedType(value)); } } return; } var mustUseProperty = propertyInfo.mustUseProperty; if (mustUseProperty) { var propertyName = propertyInfo.propertyName; if (value === null) { var type = propertyInfo.type; node[propertyName] = type === BOOLEAN ? false : ''; } else { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propertyName] = value; } return; } // The rest are treated as attributes with special cases. var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace; if (value === null) { node.removeAttribute(attributeName); } else { var _type = propertyInfo.type; var attributeValue; if (_type === BOOLEAN || (_type === OVERLOADED_BOOLEAN && value === true)) { // If attribute type is boolean, we know for sure it won't be an execution sink // and we won't require Trusted Type here. attributeValue = ''; } else { // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. attributeValue = toStringOrTrustedType(value); if (propertyInfo.sanitizeURL) { sanitizeURL(attributeValue.toString()); } } if (attributeNamespace) { setAttributeNS(node, attributeNamespace, attributeName, attributeValue); } else { setAttribute(node, attributeName, attributeValue); } }
Sets the value for a property on a node. @param {DOMElement} node @param {string} name @param {*} value
setValueForProperty ( node , name , value , isCustomComponentTag )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
ReactControlledValuePropTypes.checkPropTypes = function(tagName, props) { checkPropTypes(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum);
Provide a linked `value` attribute for controlled forms. You should not use this outside of the ReactDOM controlled form components.
ReactControlledValuePropTypes.checkPropTypes ( tagName , props )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function checkSelectPropTypes(props) { ReactControlledValuePropTypes.checkPropTypes('select', props); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var isArray = Array.isArray(props[propName]); if (props.multiple && !isArray) { warning$1( false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(), ); } else if (!props.multiple && isArray) { warning$1( false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(), ); } }
Validation function for `value` and `defaultValue`.
checkSelectPropTypes ( props )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function get(key) { return key._reactInternalFiber;
This API should be called `delete` but we'd have to make sure to always transform these to strings for IE support. When this transform is fully supported we can rename it.
get ( key )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = getParent(inst); } var i; for (i = path.length; i-- > 0; ) { fn(path[i], 'captured', arg); } for (i = 0; i < path.length; i++) { fn(path[i], 'bubbled', arg); }
Simulates the traversal of a two-phase, capture/bubble event dispatch.
traverseTwoPhase ( inst , fn , arg )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (true) { if (!from) { break; } if (from === common) { break; } var alternate = from.alternate; if (alternate !== null && alternate === common) { break; } pathFrom.push(from); from = getParent(from); } var pathTo = []; while (true) { if (!to) { break; } if (to === common) { break; } var _alternate = to.alternate; if (_alternate !== null && _alternate === common) { break; } pathTo.push(to); to = getParent(to); } for (var i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], 'bubbled', argFrom); } for (var _i = pathTo.length; _i-- > 0; ) { fn(pathTo[_i], 'captured', argTo); }
Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that should would receive a `mouseEnter` or `mouseLeave` event. Does not invoke the callback on the nearest common ancestor because nothing "entered" or "left" that element.
traverseEnterLeave ( from , to , fn , argFrom , argTo )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); }
Collect dispatches (must be entirely collected before dispatching - see unit tests). Lazily allocate the array to conserve memory. We must loop through each event and perform the traversal for each one. We cannot perform a single traversal for the entire collection of events because each event may have a different target.
accumulateTwoPhaseDispatchesSingle ( event )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function accumulateDispatches(inst, ignoredDirection, event) { if (inst && event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } }
Accumulates without regard to direction, does not look for phased registration names. Same as `accumulateDirectDispatchesSingle` but without requiring that the `dispatchMarker` be the same as the dispatched ID.
accumulateDispatches ( inst , ignoredDirection , event )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); }
Accumulates dispatches on an `SyntheticEvent`, but only for the `dispatchMarker`. @param {SyntheticEvent} event
accumulateDirectDispatchesSingle ( event )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; delete this.isDefaultPrevented; delete this.isPropagationStopped; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = functionThatReturnsTrue; } else { this.isDefaultPrevented = functionThatReturnsFalse; } this.isPropagationStopped = functionThatReturnsFalse; return this;
Synthetic events are dispatched by event plugins, typically in response to a top-level event delegation handler. These systems should generally use pooling to reduce the frequency of garbage collection. The system should check `isPersistent` to determine whether the event should be released into the pool after being dispatched. Users that need a persisted event should invoke `persist`. Synthetic events (and subclasses) implement the DOM Level 3 Events API by normalizing browser quirks. Subclasses do not necessarily have to implement a DOM interface; custom application-specific events can also subclass this. @param {object} dispatchConfig Configuration used to dispatch this event. @param {*} targetInst Marker identifying the event target. @param {object} nativeEvent Native browser event. @param {DOMEventTarget} nativeEventTarget Target node.
SyntheticEvent ( dispatchConfig , targetInst , nativeEvent , nativeEventTarget )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
SyntheticEvent.extend = function(Interface) { var Super = this; var E = function() {}; E.prototype = Super.prototype; var prototype = new E(); function Class() { return Super.apply(this, arguments); } _assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = _assign({}, Super.Interface, Interface); Class.extend = Super.extend; addEventPoolingTo(Class); return Class;
Helper to reduce boilerplate when creating subclasses.
SyntheticEvent.extend ( Interface )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get, }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; !warningCondition ? warningWithoutStack$1( false, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result, ) : void 0; }
Helper to nullify syntheticEvent instance properties when destructing @param {String} propName @param {?object} getVal @return {object} defineProperty object
getPooledWarningPropertyDefinition ( propName , getVal )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
var SyntheticAnimationEvent = SyntheticEvent.extend({ animationName: null, elapsedTime: null, pseudoElement: null, }); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var SyntheticClipboardEvent = SyntheticEvent.extend({ clipboardData: function(event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; },
@interface Event @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
SyntheticEvent.extend ( { animationName : null , elapsedTime : null , pseudoElement : null , } )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function listenTo(registrationName, mountAt) { var listeningSet = getListeningSetForElement(mountAt); var dependencies = registrationNameDependencies[registrationName]; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; listenToTopLevel(dependency, mountAt, listeningSet); }
We listen for bubbled touch events on the document object. Firefox v8.01 (and possibly others) exhibited strange behavior when mounting `onmousemove` events at some node that was not the document element. The symptoms were that if your mouse is not moving over something contained within that mount point (for example on the background) the top-level listeners for `onmousemove` won't be called. However, if you register the `mousemove` on the document object, then it will of course catch all `mousemove`s. This along with iOS quirks, justifies restricting top-level listeners to the document object only, at least for these movement types of events and possibly all events. @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but they bubble to document. @param {string} registrationName Name of listener (e.g. `onClick`). @param {object} mountAt Container where to mount the listener
listenTo ( registrationName , mountAt )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function dangerousStyleValue(name, value, isCustomProperty) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } if ( !isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) ) { return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers } return ('' + value).trim();
Convert a value into the proper css writable value. The style name `name` should be logical (no hyphens), as specified in `CSSProperty.isUnitlessNumber`. @param {string} name CSS property name such as `topMargin`. @param {*} value CSS property value such as `10px`. @return {string} Normalized style value with dimensions applied.
dangerousStyleValue ( name , value , isCustomProperty )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function getCompositionEventType(topLevelType) { switch (topLevelType) { case TOP_COMPOSITION_START: return eventTypes$1.compositionStart; case TOP_COMPOSITION_END: return eventTypes$1.compositionEnd; case TOP_COMPOSITION_UPDATE: return eventTypes$1.compositionUpdate; }
Translate native top level events into event types. @param {string} topLevelType @return {object}
getCompositionEventType ( topLevelType )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
Does our fallback best-guess model think this event signifies that composition has begun? @param {string} topLevelType @param {object} nativeEvent @return {boolean}
isFallbackCompositionStart ( topLevelType , nativeEvent )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case TOP_KEY_UP: // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case TOP_KEY_DOWN: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case TOP_KEY_PRESS: case TOP_MOUSE_DOWN: case TOP_BLUR: // Events are not possible without cancelling IME. return true; default: return false; }
Does our fallback mode think that this event is the end of composition? @param {string} topLevelType @param {object} nativeEvent @return {boolean}
isFallbackCompositionEnd ( topLevelType , nativeEvent )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case TOP_COMPOSITION_END: return getDataFromCustomEvent(nativeEvent); case TOP_KEY_PRESS: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case TOP_TEXT_INPUT: // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to ignore it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; }
@param {TopLevelType} topLevelType Number from `TopLevelType`. @param {object} nativeEvent Native browser event. @return {?string} The string corresponding to this `beforeInput` event.
getNativeBeforeInputChars ( topLevelType , nativeEvent )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. // If composition event is available, we extract a string only at // compositionevent, otherwise extract it at fallback events. if (isComposing) { if ( topLevelType === TOP_COMPOSITION_END || (!canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) ) { var chars = getData(); reset(); isComposing = false; return chars; } return null; } switch (topLevelType) { case TOP_PASTE: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case TOP_KEY_PRESS: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (!isKeypressCommand(nativeEvent)) { // IE fires the `keypress` event when a user types an emoji via // Touch keyboard of Windows. In such a case, the `char` property // holds an emoji character like `\uD83D\uDE0A`. Because its length // is 2, the property `which` does not represent an emoji correctly. // In such a case, we directly return the `char` property instead of // using `which`. if (nativeEvent.char && nativeEvent.char.length > 1) { return nativeEvent.char; } else if (nativeEvent.which) { return String.fromCharCode(nativeEvent.which); } } return null; case TOP_COMPOSITION_END: return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data; default: return null; }
For browsers that do not provide the `textInput` event, extract the appropriate string to use for SyntheticInputEvent. @param {number} topLevelType Number from `TopLevelEventTypes`. @param {object} nativeEvent Native browser event. @return {?string} The fallback string for this `beforeInput` event.
getFallbackBeforeInputChars ( topLevelType , nativeEvent )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function getSelection$1(node) { if ('selectionStart' in node && hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd, }; } else { var win = (node.ownerDocument && node.ownerDocument.defaultView) || window; var selection = win.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset, }; }
Get an object which is a unique representation of the current selection. The return value will not be consistent across nodes or browsers, but two identical selections on the same node will return identical objects. @param {DOMElement} node @return {object}
$1 ( node )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
function getEventTargetDocument(eventTarget) { return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
Get document associated with the event target. @param {object} nativeEventTarget @return {Document}
getEventTargetDocument ( eventTarget )
javascript
fuse-box/fuse-box
src/compiler/playground/source_test/react.dom.development.js
https://github.com/fuse-box/fuse-box/blob/master/src/compiler/playground/source_test/react.dom.development.js
MIT
async decode(fileDirectory, buffer) { if (this._awaitingDecoder) { await this._awaitingDecoder; } return this.size === 0 ? getDecoder(fileDirectory).then((decoder) => decoder.decode(fileDirectory, buffer)) : new Promise((resolve) => { const worker = this.workers.find((candidate) => candidate.idle) || this.workers[Math.floor(Math.random() * this.size)]; worker.idle = false; const id = this.messageId++; const onMessage = (e) => { if (e.data.id === id) { worker.idle = true; resolve(e.data.decoded); worker.worker.removeEventListener('message', onMessage); } }; worker.worker.addEventListener('message', onMessage); worker.worker.postMessage({ fileDirectory, buffer, id }, [buffer]); }); }
Decode the given block of bytes with the set compression method. @param {ArrayBuffer} buffer the array buffer of bytes to decode. @returns {Promise<ArrayBuffer>} the decoded result as a `Promise`
decode ( fileDirectory , buffer )
javascript
geotiffjs/geotiff.js
src/pool.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/pool.js
MIT
function getFieldTypeLength(fieldType) { switch (fieldType) { case fieldTypes.BYTE: case fieldTypes.ASCII: case fieldTypes.SBYTE: case fieldTypes.UNDEFINED: return 1; case fieldTypes.SHORT: case fieldTypes.SSHORT: return 2; case fieldTypes.LONG: case fieldTypes.SLONG: case fieldTypes.FLOAT: case fieldTypes.IFD: return 4; case fieldTypes.RATIONAL: case fieldTypes.SRATIONAL: case fieldTypes.DOUBLE: case fieldTypes.LONG8: case fieldTypes.SLONG8: case fieldTypes.IFD8: return 8; default: throw new RangeError(`Invalid field type: ${fieldType}`); } }
The autogenerated docs are a little confusing here. The effective type is: `(TypedArray | TypedArray[]) & { height: number; width: number}` @typedef {TypedArrayWithDimensions | TypedArrayArrayWithDimensions} ReadRasterResult
getFieldTypeLength ( fieldType )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
constructor(fileDirectory, rawFileDirectory, geoKeyDirectory, nextIFDByteOffset) { this.fileDirectory = fileDirectory; this.rawFileDirectory = rawFileDirectory; this.geoKeyDirectory = geoKeyDirectory; this.nextIFDByteOffset = nextIFDByteOffset; }
Create an ImageFileDirectory. @param {object} fileDirectory the file directory, mapping tag names to values @param {Map} rawFileDirectory the raw file directory, mapping tag IDs to values @param {object} geoKeyDirectory the geo key directory, mapping geo key names to values @param {number} nextIFDByteOffset the byte offset to the next IFD
constructor ( fileDirectory , rawFileDirectory , geoKeyDirectory , nextIFDByteOffset )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
async readRasters(options = {}) { const { window: imageWindow, width, height } = options; let { resX, resY, bbox } = options; const firstImage = await this.getImage(); let usedImage = firstImage; const imageCount = await this.getImageCount(); const imgBBox = firstImage.getBoundingBox(); if (imageWindow && bbox) { throw new Error('Both "bbox" and "window" passed.'); } // if width/height is passed, transform it to resolution if (width || height) { // if we have an image window (pixel coordinates), transform it to a BBox // using the origin/resolution of the first image. if (imageWindow) { const [oX, oY] = firstImage.getOrigin(); const [rX, rY] = firstImage.getResolution(); bbox = [ oX + (imageWindow[0] * rX), oY + (imageWindow[1] * rY), oX + (imageWindow[2] * rX), oY + (imageWindow[3] * rY), ]; } // if we have a bbox (or calculated one) const usedBBox = bbox || imgBBox; if (width) { if (resX) { throw new Error('Both width and resX passed'); } resX = (usedBBox[2] - usedBBox[0]) / width; } if (height) { if (resY) { throw new Error('Both width and resY passed'); } resY = (usedBBox[3] - usedBBox[1]) / height; } } // if resolution is set or calculated, try to get the image with the worst acceptable resolution if (resX || resY) { const allImages = []; for (let i = 0; i < imageCount; ++i) { const image = await this.getImage(i); const { SubfileType: subfileType, NewSubfileType: newSubfileType } = image.fileDirectory; if (i === 0 || subfileType === 2 || newSubfileType & 1) { allImages.push(image); } } allImages.sort((a, b) => a.getWidth() - b.getWidth()); for (let i = 0; i < allImages.length; ++i) { const image = allImages[i]; const imgResX = (imgBBox[2] - imgBBox[0]) / image.getWidth(); const imgResY = (imgBBox[3] - imgBBox[1]) / image.getHeight(); usedImage = image; if ((resX && resX > imgResX) || (resY && resY > imgResY)) { break; } } } let wnd = imageWindow; if (bbox) { const [oX, oY] = firstImage.getOrigin(); const [imageResX, imageResY] = usedImage.getResolution(firstImage); wnd = [ Math.round((bbox[0] - oX) / imageResX), Math.round((bbox[1] - oY) / imageResY), Math.round((bbox[2] - oX) / imageResX), Math.round((bbox[3] - oY) / imageResY), ]; wnd = [ Math.min(wnd[0], wnd[2]), Math.min(wnd[1], wnd[3]), Math.max(wnd[0], wnd[2]), Math.max(wnd[1], wnd[3]), ]; } return usedImage.readRasters({ ...options, window: wnd }); }
(experimental) Reads raster data from the best fitting image. This function uses the image with the lowest resolution that is still a higher resolution than the requested resolution. When specified, the `bbox` option is translated to the `window` option and the `resX` and `resY` to `width` and `height` respectively. Then, the [readRasters]{@link GeoTIFFImage#readRasters} method of the selected image is called and the result returned. @see GeoTIFFImage.readRasters @param {import('./geotiffimage').ReadRasterOptions} [options={}] optional parameters @returns {Promise<ReadRasterResult>} the decoded array(s), with `height` and `width`, as a promise
readRasters ( options = { } )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
constructor(source, littleEndian, bigTiff, firstIFDOffset, options = {}) { super(); this.source = source; this.littleEndian = littleEndian; this.bigTiff = bigTiff; this.firstIFDOffset = firstIFDOffset; this.cache = options.cache || false; this.ifdRequests = []; this.ghostValues = null; }
@constructor @param {*} source The datasource to read from. @param {boolean} littleEndian Whether the image uses little endian. @param {boolean} bigTiff Whether the image uses bigTIFF conventions. @param {number} firstIFDOffset The numeric byte-offset from the start of the image to the first IFD. @param {GeoTIFFOptions} [options] further options.
constructor ( source , littleEndian , bigTiff , firstIFDOffset , options = { } )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
constructor(mainFile, overviewFiles) { super(); this.mainFile = mainFile; this.overviewFiles = overviewFiles; this.imageFiles = [mainFile].concat(overviewFiles); this.fileDirectoriesPerFile = null; this.fileDirectoriesPerFileParsing = null; this.imageCount = null; }
Construct a new MultiGeoTIFF from a main and several overview files. @param {GeoTIFF} mainFile The main GeoTIFF file. @param {GeoTIFF[]} overviewFiles An array of overview files.
constructor ( mainFile , overviewFiles )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
async getImage(index = 0) { await this.getImageCount(); await this.parseFileDirectoriesPerFile(); let visited = 0; let relativeIndex = 0; for (let i = 0; i < this.imageFiles.length; i++) { const imageFile = this.imageFiles[i]; for (let ii = 0; ii < this.imageCounts[i]; ii++) { if (index === visited) { const ifd = await imageFile.requestIFD(relativeIndex); return new GeoTIFFImage( ifd.fileDirectory, ifd.geoKeyDirectory, imageFile.dataView, imageFile.littleEndian, imageFile.cache, imageFile.source, ); } visited++; relativeIndex++; } relativeIndex = 0; } throw new RangeError('Invalid image index'); }
Get the n-th internal subfile of an image. By default, the first is returned. @param {number} [index=0] the index of the image to return. @returns {Promise<GeoTIFFImage>} the image at the given index
getImage ( index = 0 )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
async getImageCount() { if (this.imageCount !== null) { return this.imageCount; } const requests = [this.mainFile.getImageCount()] .concat(this.overviewFiles.map((file) => file.getImageCount())); this.imageCounts = await Promise.all(requests); this.imageCount = this.imageCounts.reduce((count, ifds) => count + ifds, 0); return this.imageCount; }
Returns the count of the internal subfiles. @returns {Promise<number>} the number of internal subfile images
getImageCount ( )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
export async function fromUrl(url, options = {}, signal) { return GeoTIFF.fromSource(makeRemoteSource(url, options), signal); }
Creates a new GeoTIFF from a remote URL. @param {string} url The URL to access the image from @param {object} [options] Additional options to pass to the source. See {@link makeRemoteSource} for details. @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is to be aborted @returns {Promise<GeoTIFF>} The resulting GeoTIFF file.
fromUrl ( url , options = { } , signal )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
export async function fromCustomClient(client, options = {}, signal) { return GeoTIFF.fromSource(makeCustomSource(client, options), signal); }
Creates a new GeoTIFF from a custom {@link BaseClient}. @param {BaseClient} client The client. @param {object} [options] Additional options to pass to the source. See {@link makeRemoteSource} for details. @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is to be aborted @returns {Promise<GeoTIFF>} The resulting GeoTIFF file.
fromCustomClient ( client , options = { } , signal )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
export async function fromArrayBuffer(arrayBuffer, signal) { return GeoTIFF.fromSource(makeBufferSource(arrayBuffer), signal); }
Construct a new GeoTIFF from an [ArrayBuffer]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer}. @param {ArrayBuffer} arrayBuffer The data to read the file from. @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is to be aborted @returns {Promise<GeoTIFF>} The resulting GeoTIFF file.
fromArrayBuffer ( arrayBuffer , signal )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
export async function fromFile(path, signal) { return GeoTIFF.fromSource(makeFileSource(path), signal); }
Construct a GeoTIFF from a local file path. This uses the node [filesystem API]{@link https://nodejs.org/api/fs.html} and is not available on browsers. N.B. After the GeoTIFF has been completely processed it needs to be closed but only if it has been constructed from a file. @param {string} path The file path to read from. @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is to be aborted @returns {Promise<GeoTIFF>} The resulting GeoTIFF file.
fromFile ( path , signal )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
export async function fromBlob(blob, signal) { return GeoTIFF.fromSource(makeFileReaderSource(blob), signal); }
Construct a GeoTIFF from an HTML [Blob]{@link https://developer.mozilla.org/en-US/docs/Web/API/Blob} or [File]{@link https://developer.mozilla.org/en-US/docs/Web/API/File} object. @param {Blob|File} blob The Blob or File object to read from. @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is to be aborted @returns {Promise<GeoTIFF>} The resulting GeoTIFF file.
fromBlob ( blob , signal )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
export async function fromUrls(mainUrl, overviewUrls = [], options = {}, signal) { const mainFile = await GeoTIFF.fromSource(makeRemoteSource(mainUrl, options), signal); const overviewFiles = await Promise.all( overviewUrls.map((url) => GeoTIFF.fromSource(makeRemoteSource(url, options))), ); return new MultiGeoTIFF(mainFile, overviewFiles); }
Construct a MultiGeoTIFF from the given URLs. @param {string} mainUrl The URL for the main file. @param {string[]} overviewUrls An array of URLs for the overview images. @param {Object} [options] Additional options to pass to the source. See [makeRemoteSource]{@link module:source.makeRemoteSource} for details. @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is to be aborted @returns {Promise<MultiGeoTIFF>} The resulting MultiGeoTIFF file.
fromUrls ( mainUrl , overviewUrls = [ ] , options = { } , signal )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
export function writeArrayBuffer(values, metadata) { return writeGeotiff(values, metadata); }
Main creating function for GeoTIFF files. @param {(Array)} array of pixel values @returns {metadata} metadata
writeArrayBuffer ( values , metadata )
javascript
geotiffjs/geotiff.js
src/geotiff.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiff.js
MIT
constructor(fileDirectory, geoKeys, dataView, littleEndian, cache, source) { this.fileDirectory = fileDirectory; this.geoKeys = geoKeys; this.dataView = dataView; this.littleEndian = littleEndian; this.tiles = cache ? {} : null; this.isTiled = !fileDirectory.StripOffsets; const planarConfiguration = fileDirectory.PlanarConfiguration; this.planarConfiguration = (typeof planarConfiguration === 'undefined') ? 1 : planarConfiguration; if (this.planarConfiguration !== 1 && this.planarConfiguration !== 2) { throw new Error('Invalid planar configuration.'); } this.source = source; }
@constructor @param {Object} fileDirectory The parsed file directory @param {Object} geoKeys The parsed geo-keys @param {DataView} dataView The DataView for the underlying file. @param {Boolean} littleEndian Whether the file is encoded in little or big endian @param {Boolean} cache Whether or not decoded tiles shall be cached @param {import('./source/basesource').BaseSource} source The datasource to read from
constructor ( fileDirectory , geoKeys , dataView , littleEndian , cache , source )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getFileDirectory() { return this.fileDirectory; }
Returns the associated parsed file directory. @returns {Object} the parsed file directory
getFileDirectory ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getGeoKeys() { return this.geoKeys; }
Returns the associated parsed geo keys. @returns {Object} the parsed geo keys
getGeoKeys ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getWidth() { return this.fileDirectory.ImageWidth; }
Returns the width of the image. @returns {Number} the width of the image
getWidth ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getHeight() { return this.fileDirectory.ImageLength; }
Returns the height of the image. @returns {Number} the height of the image
getHeight ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getSamplesPerPixel() { return typeof this.fileDirectory.SamplesPerPixel !== 'undefined' ? this.fileDirectory.SamplesPerPixel : 1; }
Returns the number of samples per pixel. @returns {Number} the number of samples per pixel
getSamplesPerPixel ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getTileWidth() { return this.isTiled ? this.fileDirectory.TileWidth : this.getWidth(); }
Returns the width of each tile. @returns {Number} the width of each tile
getTileWidth ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getTileHeight() { if (this.isTiled) { return this.fileDirectory.TileLength; } if (typeof this.fileDirectory.RowsPerStrip !== 'undefined') { return Math.min(this.fileDirectory.RowsPerStrip, this.getHeight()); } return this.getHeight(); }
Returns the height of each tile. @returns {Number} the height of each tile
getTileHeight ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getBytesPerPixel() { let bytes = 0; for (let i = 0; i < this.fileDirectory.BitsPerSample.length; ++i) { bytes += this.getSampleByteSize(i); } return bytes; }
Calculates the number of bytes for each pixel across all samples. Only full bytes are supported, an exception is thrown when this is not the case. @returns {Number} the bytes per pixel
getBytesPerPixel ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
async getTileOrStrip(x, y, sample, poolOrDecoder, signal) { const numTilesPerRow = Math.ceil(this.getWidth() / this.getTileWidth()); const numTilesPerCol = Math.ceil(this.getHeight() / this.getTileHeight()); let index; const { tiles } = this; if (this.planarConfiguration === 1) { index = (y * numTilesPerRow) + x; } else if (this.planarConfiguration === 2) { index = (sample * numTilesPerRow * numTilesPerCol) + (y * numTilesPerRow) + x; } let offset; let byteCount; if (this.isTiled) { offset = this.fileDirectory.TileOffsets[index]; byteCount = this.fileDirectory.TileByteCounts[index]; } else { offset = this.fileDirectory.StripOffsets[index]; byteCount = this.fileDirectory.StripByteCounts[index]; } const slice = (await this.source.fetch([{ offset, length: byteCount }], signal))[0]; let request; if (tiles === null || !tiles[index]) { // resolve each request by potentially applying array normalization request = (async () => { let data = await poolOrDecoder.decode(this.fileDirectory, slice); const sampleFormat = this.getSampleFormat(); const bitsPerSample = this.getBitsPerSample(); if (needsNormalization(sampleFormat, bitsPerSample)) { data = normalizeArray( data, sampleFormat, this.planarConfiguration, this.getSamplesPerPixel(), bitsPerSample, this.getTileWidth(), this.getBlockHeight(y), ); } return data; })(); // set the cache if (tiles !== null) { tiles[index] = request; } } else { // get from the cache request = tiles[index]; } // cache the tile request return { x, y, sample, data: await request }; }
Returns the decoded strip or tile. @param {Number} x the strip or tile x-offset @param {Number} y the tile y-offset (0 for stripped images) @param {Number} sample the sample to get for separated samples @param {import("./geotiff").Pool|import("./geotiff").BaseDecoder} poolOrDecoder the decoder or decoder pool @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is to be aborted @returns {Promise.<{x: number, y: number, sample: number, data: ArrayBuffer}>} the decoded strip or tile
getTileOrStrip ( x , y , sample , poolOrDecoder , signal )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
async _readRaster(imageWindow, samples, valueArrays, interleave, poolOrDecoder, width, height, resampleMethod, signal) { const tileWidth = this.getTileWidth(); const tileHeight = this.getTileHeight(); const imageWidth = this.getWidth(); const imageHeight = this.getHeight(); const minXTile = Math.max(Math.floor(imageWindow[0] / tileWidth), 0); const maxXTile = Math.min( Math.ceil(imageWindow[2] / tileWidth), Math.ceil(imageWidth / tileWidth), ); const minYTile = Math.max(Math.floor(imageWindow[1] / tileHeight), 0); const maxYTile = Math.min( Math.ceil(imageWindow[3] / tileHeight), Math.ceil(imageHeight / tileHeight), ); const windowWidth = imageWindow[2] - imageWindow[0]; let bytesPerPixel = this.getBytesPerPixel(); const srcSampleOffsets = []; const sampleReaders = []; for (let i = 0; i < samples.length; ++i) { if (this.planarConfiguration === 1) { srcSampleOffsets.push(sum(this.fileDirectory.BitsPerSample, 0, samples[i]) / 8); } else { srcSampleOffsets.push(0); } sampleReaders.push(this.getReaderForSample(samples[i])); } const promises = []; const { littleEndian } = this; for (let yTile = minYTile; yTile < maxYTile; ++yTile) { for (let xTile = minXTile; xTile < maxXTile; ++xTile) { let getPromise; if (this.planarConfiguration === 1) { getPromise = this.getTileOrStrip(xTile, yTile, 0, poolOrDecoder, signal); } for (let sampleIndex = 0; sampleIndex < samples.length; ++sampleIndex) { const si = sampleIndex; const sample = samples[sampleIndex]; if (this.planarConfiguration === 2) { bytesPerPixel = this.getSampleByteSize(sample); getPromise = this.getTileOrStrip(xTile, yTile, sample, poolOrDecoder, signal); } const promise = getPromise.then((tile) => { const buffer = tile.data; const dataView = new DataView(buffer); const blockHeight = this.getBlockHeight(tile.y); const firstLine = tile.y * tileHeight; const firstCol = tile.x * tileWidth; const lastLine = firstLine + blockHeight; const lastCol = (tile.x + 1) * tileWidth; const reader = sampleReaders[si]; const ymax = Math.min(blockHeight, blockHeight - (lastLine - imageWindow[3]), imageHeight - firstLine); const xmax = Math.min(tileWidth, tileWidth - (lastCol - imageWindow[2]), imageWidth - firstCol); for (let y = Math.max(0, imageWindow[1] - firstLine); y < ymax; ++y) { for (let x = Math.max(0, imageWindow[0] - firstCol); x < xmax; ++x) { const pixelOffset = ((y * tileWidth) + x) * bytesPerPixel; const value = reader.call( dataView, pixelOffset + srcSampleOffsets[si], littleEndian, ); let windowCoordinate; if (interleave) { windowCoordinate = ((y + firstLine - imageWindow[1]) * windowWidth * samples.length) + ((x + firstCol - imageWindow[0]) * samples.length) + si; valueArrays[windowCoordinate] = value; } else { windowCoordinate = ( (y + firstLine - imageWindow[1]) * windowWidth ) + x + firstCol - imageWindow[0]; valueArrays[si][windowCoordinate] = value; } } } }); promises.push(promise); } } } await Promise.all(promises); if ((width && (imageWindow[2] - imageWindow[0]) !== width) || (height && (imageWindow[3] - imageWindow[1]) !== height)) { let resampled; if (interleave) { resampled = resampleInterleaved( valueArrays, imageWindow[2] - imageWindow[0], imageWindow[3] - imageWindow[1], width, height, samples.length, resampleMethod, ); } else { resampled = resample( valueArrays, imageWindow[2] - imageWindow[0], imageWindow[3] - imageWindow[1], width, height, resampleMethod, ); } resampled.width = width; resampled.height = height; return resampled; } valueArrays.width = width || imageWindow[2] - imageWindow[0]; valueArrays.height = height || imageWindow[3] - imageWindow[1]; return valueArrays; }
Internal read function. @private @param {Array} imageWindow The image window in pixel coordinates @param {Array} samples The selected samples (0-based indices) @param {TypedArray|TypedArray[]} valueArrays The array(s) to write into @param {Boolean} interleave Whether or not to write in an interleaved manner @param {import("./geotiff").Pool|AbstractDecoder} poolOrDecoder the decoder or decoder pool @param {number} width the width of window to be read into @param {number} height the height of window to be read into @param {number} resampleMethod the resampling method to be used when interpolating @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is to be aborted @returns {Promise<ReadRasterResult>}
_readRaster ( imageWindow , samples , valueArrays , interleave , poolOrDecoder , width , height , resampleMethod , signal )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
async readRasters({ window: wnd, samples = [], interleave, pool = null, width, height, resampleMethod, fillValue, signal, } = {}) { const imageWindow = wnd || [0, 0, this.getWidth(), this.getHeight()]; // check parameters if (imageWindow[0] > imageWindow[2] || imageWindow[1] > imageWindow[3]) { throw new Error('Invalid subsets'); } const imageWindowWidth = imageWindow[2] - imageWindow[0]; const imageWindowHeight = imageWindow[3] - imageWindow[1]; const numPixels = imageWindowWidth * imageWindowHeight; const samplesPerPixel = this.getSamplesPerPixel(); if (!samples || !samples.length) { for (let i = 0; i < samplesPerPixel; ++i) { samples.push(i); } } else { for (let i = 0; i < samples.length; ++i) { if (samples[i] >= samplesPerPixel) { return Promise.reject(new RangeError(`Invalid sample index '${samples[i]}'.`)); } } } let valueArrays; if (interleave) { const format = this.fileDirectory.SampleFormat ? Math.max.apply(null, this.fileDirectory.SampleFormat) : 1; const bitsPerSample = Math.max.apply(null, this.fileDirectory.BitsPerSample); valueArrays = arrayForType(format, bitsPerSample, numPixels * samples.length); if (fillValue) { valueArrays.fill(fillValue); } } else { valueArrays = []; for (let i = 0; i < samples.length; ++i) { const valueArray = this.getArrayForSample(samples[i], numPixels); if (Array.isArray(fillValue) && i < fillValue.length) { valueArray.fill(fillValue[i]); } else if (fillValue && !Array.isArray(fillValue)) { valueArray.fill(fillValue); } valueArrays.push(valueArray); } } const poolOrDecoder = pool || await getDecoder(this.fileDirectory); const result = await this._readRaster( imageWindow, samples, valueArrays, interleave, poolOrDecoder, width, height, resampleMethod, signal, ); return result; }
Reads raster data from the image. This function reads all selected samples into separate arrays of the correct type for that sample or into a single combined array when `interleave` is set. When provided, only a subset of the raster is read for each sample. @param {ReadRasterOptions} [options={}] optional parameters @returns {Promise<ReadRasterResult>} the decoded arrays as a promise
readRasters ( { window : wnd , samples = [ ] , interleave , pool = null , width , height , resampleMethod , fillValue , signal , } = { } )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
async readRGB({ window, interleave = true, pool = null, width, height, resampleMethod, enableAlpha = false, signal } = {}) { const imageWindow = window || [0, 0, this.getWidth(), this.getHeight()]; // check parameters if (imageWindow[0] > imageWindow[2] || imageWindow[1] > imageWindow[3]) { throw new Error('Invalid subsets'); } const pi = this.fileDirectory.PhotometricInterpretation; if (pi === photometricInterpretations.RGB) { let s = [0, 1, 2]; if ((!(this.fileDirectory.ExtraSamples === ExtraSamplesValues.Unspecified)) && enableAlpha) { s = []; for (let i = 0; i < this.fileDirectory.BitsPerSample.length; i += 1) { s.push(i); } } return this.readRasters({ window, interleave, samples: s, pool, width, height, resampleMethod, signal, }); } let samples; switch (pi) { case photometricInterpretations.WhiteIsZero: case photometricInterpretations.BlackIsZero: case photometricInterpretations.Palette: samples = [0]; break; case photometricInterpretations.CMYK: samples = [0, 1, 2, 3]; break; case photometricInterpretations.YCbCr: case photometricInterpretations.CIELab: samples = [0, 1, 2]; break; default: throw new Error('Invalid or unsupported photometric interpretation.'); } const subOptions = { window: imageWindow, interleave: true, samples, pool, width, height, resampleMethod, signal, }; const { fileDirectory } = this; const raster = await this.readRasters(subOptions); const max = 2 ** this.fileDirectory.BitsPerSample[0]; let data; switch (pi) { case photometricInterpretations.WhiteIsZero: data = fromWhiteIsZero(raster, max); break; case photometricInterpretations.BlackIsZero: data = fromBlackIsZero(raster, max); break; case photometricInterpretations.Palette: data = fromPalette(raster, fileDirectory.ColorMap); break; case photometricInterpretations.CMYK: data = fromCMYK(raster); break; case photometricInterpretations.YCbCr: data = fromYCbCr(raster); break; case photometricInterpretations.CIELab: data = fromCIELab(raster); break; default: throw new Error('Unsupported photometric interpretation.'); } // if non-interleaved data is requested, we must split the channels // into their respective arrays if (!interleave) { const red = new Uint8Array(data.length / 3); const green = new Uint8Array(data.length / 3); const blue = new Uint8Array(data.length / 3); for (let i = 0, j = 0; i < data.length; i += 3, ++j) { red[j] = data[i]; green[j] = data[i + 1]; blue[j] = data[i + 2]; } data = [red, green, blue]; } data.width = raster.width; data.height = raster.height; return data; }
Reads raster data from the image as RGB. The result is always an interleaved typed array. Colorspaces other than RGB will be transformed to RGB, color maps expanded. When no other method is applicable, the first sample is used to produce a grayscale image. When provided, only a subset of the raster is read for each sample. @param {Object} [options] optional parameters @param {Array<number>} [options.window] the subset to read data from in pixels. @param {boolean} [options.interleave=true] whether the data shall be read in one single array or separate arrays. @param {import("./geotiff").Pool} [options.pool=null] The optional decoder pool to use. @param {number} [options.width] The desired width of the output. When the width is no the same as the images, resampling will be performed. @param {number} [options.height] The desired height of the output. When the width is no the same as the images, resampling will be performed. @param {string} [options.resampleMethod='nearest'] The desired resampling method. @param {boolean} [options.enableAlpha=false] Enable reading alpha channel if present. @param {AbortSignal} [options.signal] An AbortSignal that may be signalled if the request is to be aborted @returns {Promise<ReadRasterResult>} the RGB array as a Promise
readRGB ( { window , interleave = true , pool = null , width , height , resampleMethod , enableAlpha = false , signal } = { } )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getTiePoints() { if (!this.fileDirectory.ModelTiepoint) { return []; } const tiePoints = []; for (let i = 0; i < this.fileDirectory.ModelTiepoint.length; i += 6) { tiePoints.push({ i: this.fileDirectory.ModelTiepoint[i], j: this.fileDirectory.ModelTiepoint[i + 1], k: this.fileDirectory.ModelTiepoint[i + 2], x: this.fileDirectory.ModelTiepoint[i + 3], y: this.fileDirectory.ModelTiepoint[i + 4], z: this.fileDirectory.ModelTiepoint[i + 5], }); } return tiePoints; }
Returns an array of tiepoints. @returns {Object[]}
getTiePoints ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getGDALMetadata(sample = null) { const metadata = {}; if (!this.fileDirectory.GDAL_METADATA) { return null; } const string = this.fileDirectory.GDAL_METADATA; let items = findTagsByName(string, 'Item'); if (sample === null) { items = items.filter((item) => getAttribute(item, 'sample') === undefined); } else { items = items.filter((item) => Number(getAttribute(item, 'sample')) === sample); } for (let i = 0; i < items.length; ++i) { const item = items[i]; metadata[getAttribute(item, 'name')] = item.inner; } return metadata; }
Returns the parsed GDAL metadata items. If sample is passed to null, dataset-level metadata will be returned. Otherwise only metadata specific to the provided sample will be returned. @param {number} [sample=null] The sample index. @returns {Object}
getGDALMetadata ( sample = null )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getGDALNoData() { if (!this.fileDirectory.GDAL_NODATA) { return null; } const string = this.fileDirectory.GDAL_NODATA; return Number(string.substring(0, string.length - 1)); }
Returns the GDAL nodata value @returns {number|null}
getGDALNoData ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getOrigin() { const tiePoints = this.fileDirectory.ModelTiepoint; const modelTransformation = this.fileDirectory.ModelTransformation; if (tiePoints && tiePoints.length === 6) { return [ tiePoints[3], tiePoints[4], tiePoints[5], ]; } if (modelTransformation) { return [ modelTransformation[3], modelTransformation[7], modelTransformation[11], ]; } throw new Error('The image does not have an affine transformation.'); }
Returns the image origin as a XYZ-vector. When the image has no affine transformation, then an exception is thrown. @returns {Array<number>} The origin as a vector
getOrigin ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getResolution(referenceImage = null) { const modelPixelScale = this.fileDirectory.ModelPixelScale; const modelTransformation = this.fileDirectory.ModelTransformation; if (modelPixelScale) { return [ modelPixelScale[0], -modelPixelScale[1], modelPixelScale[2], ]; } if (modelTransformation) { if (modelTransformation[1] === 0 && modelTransformation[4] === 0) { return [ modelTransformation[0], -modelTransformation[5], modelTransformation[10], ]; } return [ Math.sqrt((modelTransformation[0] * modelTransformation[0]) + (modelTransformation[4] * modelTransformation[4])), -Math.sqrt((modelTransformation[1] * modelTransformation[1]) + (modelTransformation[5] * modelTransformation[5])), modelTransformation[10]]; } if (referenceImage) { const [refResX, refResY, refResZ] = referenceImage.getResolution(); return [ refResX * referenceImage.getWidth() / this.getWidth(), refResY * referenceImage.getHeight() / this.getHeight(), refResZ * referenceImage.getWidth() / this.getWidth(), ]; } throw new Error('The image does not have an affine transformation.'); }
Returns the image resolution as a XYZ-vector. When the image has no affine transformation, then an exception is thrown. @param {GeoTIFFImage} [referenceImage=null] A reference image to calculate the resolution from in cases when the current image does not have the required tags on its own. @returns {Array<number>} The resolution as a vector
getResolution ( referenceImage = null )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
pixelIsArea() { return this.geoKeys.GTRasterTypeGeoKey === 1; }
Returns whether or not the pixels of the image depict an area (or point). @returns {Boolean} Whether the pixels are a point
pixelIsArea ( )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
getBoundingBox(tilegrid = false) { const height = this.getHeight(); const width = this.getWidth(); if (this.fileDirectory.ModelTransformation && !tilegrid) { // eslint-disable-next-line no-unused-vars const [a, b, c, d, e, f, g, h] = this.fileDirectory.ModelTransformation; const corners = [ [0, 0], [0, height], [width, 0], [width, height], ]; const projected = corners.map(([I, J]) => [ d + (a * I) + (b * J), h + (e * I) + (f * J), ]); const xs = projected.map((pt) => pt[0]); const ys = projected.map((pt) => pt[1]); return [ Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys), ]; } else { const origin = this.getOrigin(); const resolution = this.getResolution(); const x1 = origin[0]; const y1 = origin[1]; const x2 = x1 + (resolution[0] * width); const y2 = y1 + (resolution[1] * height); return [ Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2), ]; } }
Returns the image bounding box as an array of 4 values: min-x, min-y, max-x and max-y. When the image has no affine transformation, then an exception is thrown. @param {boolean} [tilegrid=false] If true return extent for a tilegrid without adjustment for ModelTransformation. @returns {Array<number>} The bounding box
getBoundingBox ( tilegrid = false )
javascript
geotiffjs/geotiff.js
src/geotiffimage.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/geotiffimage.js
MIT
export function registerTag(tag, name, type = undefined, isArray = false) { fieldTags[name] = tag; fieldTagNames[tag] = name; if (type) { fieldTypes[name] = type; } if (isArray) { arrayFields.push(tag); } }
Registers a new field tag @param {number} tag the numeric tiff tag @param {string} name the name of the tag that will be reported in the IFD @param {number} type the tags data type @param {Boolean} isArray whether the tag is an array
registerTag ( tag , name , type = undefined , isArray = false )
javascript
geotiffjs/geotiff.js
src/globals.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/globals.js
MIT
export function resampleNearest(valueArrays, inWidth, inHeight, outWidth, outHeight) { const relX = inWidth / outWidth; const relY = inHeight / outHeight; return valueArrays.map((array) => { const newArray = copyNewSize(array, outWidth, outHeight); for (let y = 0; y < outHeight; ++y) { const cy = Math.min(Math.round(relY * y), inHeight - 1); for (let x = 0; x < outWidth; ++x) { const cx = Math.min(Math.round(relX * x), inWidth - 1); const value = array[(cy * inWidth) + cx]; newArray[(y * outWidth) + x] = value; } } return newArray; }); }
Resample the input arrays using nearest neighbor value selection. @param {TypedArray[]} valueArrays The input arrays to resample @param {number} inWidth The width of the input rasters @param {number} inHeight The height of the input rasters @param {number} outWidth The desired width of the output rasters @param {number} outHeight The desired height of the output rasters @returns {TypedArray[]} The resampled rasters
resampleNearest ( valueArrays , inWidth , inHeight , outWidth , outHeight )
javascript
geotiffjs/geotiff.js
src/resample.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/resample.js
MIT
export function resampleBilinear(valueArrays, inWidth, inHeight, outWidth, outHeight) { const relX = inWidth / outWidth; const relY = inHeight / outHeight; return valueArrays.map((array) => { const newArray = copyNewSize(array, outWidth, outHeight); for (let y = 0; y < outHeight; ++y) { const rawY = relY * y; const yl = Math.floor(rawY); const yh = Math.min(Math.ceil(rawY), (inHeight - 1)); for (let x = 0; x < outWidth; ++x) { const rawX = relX * x; const tx = rawX % 1; const xl = Math.floor(rawX); const xh = Math.min(Math.ceil(rawX), (inWidth - 1)); const ll = array[(yl * inWidth) + xl]; const hl = array[(yl * inWidth) + xh]; const lh = array[(yh * inWidth) + xl]; const hh = array[(yh * inWidth) + xh]; const value = lerp( lerp(ll, hl, tx), lerp(lh, hh, tx), rawY % 1, ); newArray[(y * outWidth) + x] = value; } } return newArray; }); }
Resample the input arrays using bilinear interpolation. @param {TypedArray[]} valueArrays The input arrays to resample @param {number} inWidth The width of the input rasters @param {number} inHeight The height of the input rasters @param {number} outWidth The desired width of the output rasters @param {number} outHeight The desired height of the output rasters @returns {TypedArray[]} The resampled rasters
resampleBilinear ( valueArrays , inWidth , inHeight , outWidth , outHeight )
javascript
geotiffjs/geotiff.js
src/resample.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/resample.js
MIT
export function resample(valueArrays, inWidth, inHeight, outWidth, outHeight, method = 'nearest') { switch (method.toLowerCase()) { case 'nearest': return resampleNearest(valueArrays, inWidth, inHeight, outWidth, outHeight); case 'bilinear': case 'linear': return resampleBilinear(valueArrays, inWidth, inHeight, outWidth, outHeight); default: throw new Error(`Unsupported resampling method: '${method}'`); } }
Resample the input arrays using the selected resampling method. @param {TypedArray[]} valueArrays The input arrays to resample @param {number} inWidth The width of the input rasters @param {number} inHeight The height of the input rasters @param {number} outWidth The desired width of the output rasters @param {number} outHeight The desired height of the output rasters @param {string} [method = 'nearest'] The desired resampling method @returns {TypedArray[]} The resampled rasters
resample ( valueArrays , inWidth , inHeight , outWidth , outHeight , method = 'nearest' )
javascript
geotiffjs/geotiff.js
src/resample.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/resample.js
MIT
export function resampleNearestInterleaved( valueArray, inWidth, inHeight, outWidth, outHeight, samples) { const relX = inWidth / outWidth; const relY = inHeight / outHeight; const newArray = copyNewSize(valueArray, outWidth, outHeight, samples); for (let y = 0; y < outHeight; ++y) { const cy = Math.min(Math.round(relY * y), inHeight - 1); for (let x = 0; x < outWidth; ++x) { const cx = Math.min(Math.round(relX * x), inWidth - 1); for (let i = 0; i < samples; ++i) { const value = valueArray[(cy * inWidth * samples) + (cx * samples) + i]; newArray[(y * outWidth * samples) + (x * samples) + i] = value; } } } return newArray; }
Resample the pixel interleaved input array using nearest neighbor value selection. @param {TypedArray} valueArrays The input arrays to resample @param {number} inWidth The width of the input rasters @param {number} inHeight The height of the input rasters @param {number} outWidth The desired width of the output rasters @param {number} outHeight The desired height of the output rasters @param {number} samples The number of samples per pixel for pixel interleaved data @returns {TypedArray} The resampled raster
resampleNearestInterleaved ( valueArray , inWidth , inHeight , outWidth , outHeight , samples )
javascript
geotiffjs/geotiff.js
src/resample.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/resample.js
MIT
export function resampleBilinearInterleaved( valueArray, inWidth, inHeight, outWidth, outHeight, samples) { const relX = inWidth / outWidth; const relY = inHeight / outHeight; const newArray = copyNewSize(valueArray, outWidth, outHeight, samples); for (let y = 0; y < outHeight; ++y) { const rawY = relY * y; const yl = Math.floor(rawY); const yh = Math.min(Math.ceil(rawY), (inHeight - 1)); for (let x = 0; x < outWidth; ++x) { const rawX = relX * x; const tx = rawX % 1; const xl = Math.floor(rawX); const xh = Math.min(Math.ceil(rawX), (inWidth - 1)); for (let i = 0; i < samples; ++i) { const ll = valueArray[(yl * inWidth * samples) + (xl * samples) + i]; const hl = valueArray[(yl * inWidth * samples) + (xh * samples) + i]; const lh = valueArray[(yh * inWidth * samples) + (xl * samples) + i]; const hh = valueArray[(yh * inWidth * samples) + (xh * samples) + i]; const value = lerp( lerp(ll, hl, tx), lerp(lh, hh, tx), rawY % 1, ); newArray[(y * outWidth * samples) + (x * samples) + i] = value; } } } return newArray; }
Resample the pixel interleaved input array using bilinear interpolation. @param {TypedArray} valueArrays The input arrays to resample @param {number} inWidth The width of the input rasters @param {number} inHeight The height of the input rasters @param {number} outWidth The desired width of the output rasters @param {number} outHeight The desired height of the output rasters @param {number} samples The number of samples per pixel for pixel interleaved data @returns {TypedArray} The resampled raster
resampleBilinearInterleaved ( valueArray , inWidth , inHeight , outWidth , outHeight , samples )
javascript
geotiffjs/geotiff.js
src/resample.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/resample.js
MIT
export function resampleInterleaved(valueArray, inWidth, inHeight, outWidth, outHeight, samples, method = 'nearest') { switch (method.toLowerCase()) { case 'nearest': return resampleNearestInterleaved( valueArray, inWidth, inHeight, outWidth, outHeight, samples, ); case 'bilinear': case 'linear': return resampleBilinearInterleaved( valueArray, inWidth, inHeight, outWidth, outHeight, samples, ); default: throw new Error(`Unsupported resampling method: '${method}'`); } }
Resample the pixel interleaved input array using the selected resampling method. @param {TypedArray} valueArray The input array to resample @param {number} inWidth The width of the input rasters @param {number} inHeight The height of the input rasters @param {number} outWidth The desired width of the output rasters @param {number} outHeight The desired height of the output rasters @param {number} samples The number of samples per pixel for pixel interleaved data @param {string} [method = 'nearest'] The desired resampling method @returns {TypedArray} The resampled rasters
resampleInterleaved ( valueArray , inWidth , inHeight , outWidth , outHeight , samples , method = 'nearest' )
javascript
geotiffjs/geotiff.js
src/resample.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/resample.js
MIT
constructor(client, headers, maxRanges, allowFullFile) { super(); this.client = client; this.headers = headers; this.maxRanges = maxRanges; this.allowFullFile = allowFullFile; this._fileSize = null; }
@param {BaseClient} client @param {object} headers @param {numbers} maxRanges @param {boolean} allowFullFile
constructor ( client , headers , maxRanges , allowFullFile )
javascript
geotiffjs/geotiff.js
src/source/remote.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/remote.js
MIT
export function makeRemoteSource(url, { forceXHR = false, ...clientOptions } = {}) { if (typeof fetch === 'function' && !forceXHR) { return makeFetchSource(url, clientOptions); } if (typeof XMLHttpRequest !== 'undefined') { return makeXHRSource(url, clientOptions); } return makeHttpSource(url, clientOptions); }
@param {string} url @param {object} options
makeRemoteSource ( url , { forceXHR = false , ... clientOptions } = { } )
javascript
geotiffjs/geotiff.js
src/source/remote.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/remote.js
MIT
function parseHeaders(text) { const items = text .split('\r\n') .map((line) => { const kv = line.split(':').map((str) => str.trim()); kv[0] = kv[0].toLowerCase(); return kv; }); return itemsToObject(items); }
Parse HTTP headers from a given string. @param {String} text the text to parse the headers from @returns {Object} the parsed headers with lowercase keys
parseHeaders ( text )
javascript
geotiffjs/geotiff.js
src/source/httputils.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/httputils.js
MIT
export function parseContentRange(rawContentRange) { let start; let end; let total; if (rawContentRange) { [, start, end, total] = rawContentRange.match(/bytes (\d+)-(\d+)\/(\d+)/); start = parseInt(start, 10); end = parseInt(end, 10); total = parseInt(total, 10); }
Parse a 'Content-Range' header value to its start, end, and total parts @param {String} rawContentRange the raw string to parse from @returns {Object} the parsed parts
parseContentRange ( rawContentRange )
javascript
geotiffjs/geotiff.js
src/source/httputils.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/httputils.js
MIT
constructor(offset, length, data = null) { this.offset = offset; this.length = length; this.data = data; }
@param {number} offset @param {number} length @param {ArrayBuffer} [data]
constructor ( offset , length , data = null )
javascript
geotiffjs/geotiff.js
src/source/blockedsource.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/blockedsource.js
MIT
get top() { return this.offset + this.length; }
@returns {number} the top byte border
top ( )
javascript
geotiffjs/geotiff.js
src/source/blockedsource.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/blockedsource.js
MIT
constructor(offset, length, blockIds) { this.offset = offset; this.length = length; this.blockIds = blockIds; }
@param {number} offset @param {number} length @param {number[]} blockIds
constructor ( offset , length , blockIds )
javascript
geotiffjs/geotiff.js
src/source/blockedsource.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/blockedsource.js
MIT
async fetch(slices, signal) { const blockRequests = []; const missingBlockIds = []; const allBlockIds = []; this.evictedBlocks.clear(); for (const { offset, length } of slices) { let top = offset + length; const { fileSize } = this; if (fileSize !== null) { top = Math.min(top, fileSize); } const firstBlockOffset = Math.floor(offset / this.blockSize) * this.blockSize; for (let current = firstBlockOffset; current < top; current += this.blockSize) { const blockId = Math.floor(current / this.blockSize); if (!this.blockCache.has(blockId) && !this.blockRequests.has(blockId)) { this.blockIdsToFetch.add(blockId); missingBlockIds.push(blockId); } if (this.blockRequests.has(blockId)) { blockRequests.push(this.blockRequests.get(blockId)); } allBlockIds.push(blockId); } } // allow additional block requests to accumulate await wait(); this.fetchBlocks(signal); // Gather all of the new requests that this fetch call is contributing to `fetch`. const missingRequests = []; for (const blockId of missingBlockIds) { // The requested missing block could already be in the cache // instead of having its request still be outstanding. if (this.blockRequests.has(blockId)) { missingRequests.push(this.blockRequests.get(blockId)); } } // Actually await all pending requests that are needed for this `fetch`. await Promise.allSettled(blockRequests); await Promise.allSettled(missingRequests); // Perform retries if a block was interrupted by a previous signal const abortedBlockRequests = []; const abortedBlockIds = allBlockIds .filter((id) => this.abortedBlockIds.has(id) || !this.blockCache.has(id)); abortedBlockIds.forEach((id) => this.blockIdsToFetch.add(id)); // start the retry of some blocks if required if (abortedBlockIds.length > 0 && signal && !signal.aborted) { this.fetchBlocks(null); for (const blockId of abortedBlockIds) { const block = this.blockRequests.get(blockId); if (!block) { throw new Error(`Block ${blockId} is not in the block requests`); } abortedBlockRequests.push(block); } await Promise.allSettled(abortedBlockRequests); } // throw an abort error if (signal && signal.aborted) { throw new AbortError('Request was aborted'); } const blocks = allBlockIds.map((id) => this.blockCache.get(id) || this.evictedBlocks.get(id)); const failedBlocks = blocks.filter((i) => !i); if (failedBlocks.length) { throw new AggregateError(failedBlocks, 'Request failed'); } // create a final Map, with all required blocks for this request to satisfy const requiredBlocks = new Map(zip(allBlockIds, blocks)); // TODO: satisfy each slice return this.readSliceData(slices, requiredBlocks); }
@param {import("./basesource").Slice[]} slices
fetch ( slices , signal )
javascript
geotiffjs/geotiff.js
src/source/blockedsource.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/blockedsource.js
MIT
groupBlocks(blockIds) { const sortedBlockIds = Array.from(blockIds).sort((a, b) => a - b); if (sortedBlockIds.length === 0) { return []; } let current = []; let lastBlockId = null; const groups = []; for (const blockId of sortedBlockIds) { if (lastBlockId === null || lastBlockId + 1 === blockId) { current.push(blockId); lastBlockId = blockId; } else { groups.push(new BlockGroup( current[0] * this.blockSize, current.length * this.blockSize, current, )); current = [blockId]; lastBlockId = blockId; } } groups.push(new BlockGroup( current[0] * this.blockSize, current.length * this.blockSize, current, )); return groups; }
@param {Set} blockIds @returns {BlockGroup[]}
groupBlocks ( blockIds )
javascript
geotiffjs/geotiff.js
src/source/blockedsource.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/blockedsource.js
MIT
readSliceData(slices, blocks) { return slices.map((slice) => { let top = slice.offset + slice.length; if (this.fileSize !== null) { top = Math.min(this.fileSize, top); } const blockIdLow = Math.floor(slice.offset / this.blockSize); const blockIdHigh = Math.floor(top / this.blockSize); const sliceData = new ArrayBuffer(slice.length); const sliceView = new Uint8Array(sliceData); for (let blockId = blockIdLow; blockId <= blockIdHigh; ++blockId) { const block = blocks.get(blockId); const delta = block.offset - slice.offset; const topDelta = block.top - top; let blockInnerOffset = 0; let rangeInnerOffset = 0; let usedBlockLength; if (delta < 0) { blockInnerOffset = -delta; } else if (delta > 0) { rangeInnerOffset = delta; } if (topDelta < 0) { usedBlockLength = block.length - blockInnerOffset; } else { usedBlockLength = top - block.offset - blockInnerOffset; } const blockView = new Uint8Array(block.data, blockInnerOffset, usedBlockLength); sliceView.set(blockView, rangeInnerOffset); } return sliceData; }); }
@param {import("./basesource").Slice[]} slices @param {Map} blocks
readSliceData ( slices , blocks )
javascript
geotiffjs/geotiff.js
src/source/blockedsource.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/blockedsource.js
MIT
export function makeFileReaderSource(file) { return new FileReaderSource(file); }
Create a new source from a given file/blob. @param {Blob} file The file or blob to read from. @returns The constructed source
makeFileReaderSource ( file )
javascript
geotiffjs/geotiff.js
src/source/filereader.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/filereader.js
MIT
async fetch(slices, signal = undefined) { return Promise.all( slices.map((slice) => this.fetchSlice(slice, signal)), ); }
@param {Slice[]} slices @returns {ArrayBuffer[]}
fetch ( slices , signal = undefined )
javascript
geotiffjs/geotiff.js
src/source/basesource.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/basesource.js
MIT
async fetchSlice(slice) { throw new Error(`fetching of slice ${slice} not possible, not implemented`); }
@param {Slice} slice @returns {ArrayBuffer}
fetchSlice ( slice )
javascript
geotiffjs/geotiff.js
src/source/basesource.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/basesource.js
MIT
get fileSize() { return null; }
Returns the filesize if already determined and null otherwise
fileSize ( )
javascript
geotiffjs/geotiff.js
src/source/basesource.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/basesource.js
MIT
constructor(xhr, data) { super(); this.xhr = xhr; this.data = data; }
BaseResponse facade for XMLHttpRequest @param {XMLHttpRequest} xhr @param {ArrayBuffer} data
constructor ( xhr , data )
javascript
geotiffjs/geotiff.js
src/source/client/xhr.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/client/xhr.js
MIT
constructor(response) { super(); this.response = response; }
BaseResponse facade for fetch API Response @param {Response} response
constructor ( response )
javascript
geotiffjs/geotiff.js
src/source/client/fetch.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/client/fetch.js
MIT
async request({ headers, signal } = {}) { const response = await fetch(this.url, { headers, credentials: this.credentials, signal, }); return new FetchResponse(response); }
@param {{headers: HeadersInit, signal: AbortSignal}} [options={}] @returns {Promise<FetchResponse>}
request ( { headers , signal } = { } )
javascript
geotiffjs/geotiff.js
src/source/client/fetch.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/client/fetch.js
MIT
get ok() { return this.status >= 200 && this.status <= 299; }
Returns whether the response has an ok'ish status code
ok ( )
javascript
geotiffjs/geotiff.js
src/source/client/base.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/client/base.js
MIT
get status() { throw new Error('not implemented'); }
Returns the status code of the response
status ( )
javascript
geotiffjs/geotiff.js
src/source/client/base.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/client/base.js
MIT
getHeader(headerName) { // eslint-disable-line no-unused-vars throw new Error('not implemented'); }
Returns the value of the specified header @param {string} headerName the header name @returns {string} the header value
getHeader ( headerName )
javascript
geotiffjs/geotiff.js
src/source/client/base.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/client/base.js
MIT
async getData() { throw new Error('not implemented'); }
@returns {ArrayBuffer} the response data of the request
getData ( )
javascript
geotiffjs/geotiff.js
src/source/client/base.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/client/base.js
MIT
async request({ headers, signal } = {}) { // eslint-disable-line no-unused-vars throw new Error('request is not implemented'); }
Send a request with the options @param {{headers: HeadersInit, signal: AbortSignal}} [options={}] @returns {Promise<BaseResponse>}
request ( { headers , signal } = { } )
javascript
geotiffjs/geotiff.js
src/source/client/base.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/client/base.js
MIT
constructor(response, dataPromise) { super(); this.response = response; this.dataPromise = dataPromise; }
BaseResponse facade for node HTTP/HTTPS API Response @param {http.ServerResponse} response
constructor ( response , dataPromise )
javascript
geotiffjs/geotiff.js
src/source/client/http.js
https://github.com/geotiffjs/geotiff.js/blob/master/src/source/client/http.js
MIT
export default function solveClass(props) { let {class: classes, ...rest} = props; const args = [{}]; if (classes) args.push.apply(args, emptyArray.concat(classes)); args.push(rest); return merge.apply(null, args); }
Solves the given props by applying classes. @param {object} props - The component's props. @return {object} - The solved props.
solveClass ( props )
javascript
Yomguithereal/react-blessed
src/shared/solveClass.js
https://github.com/Yomguithereal/react-blessed/blob/master/src/shared/solveClass.js
MIT
export default function update(node, options) { // TODO: enforce some kind of shallow equality? // TODO: handle position const selectQue = []; for (let key in options) { let value = options[key]; if (key === 'selected' && node.select) selectQue.push({ node, value: typeof value === 'string' ? +value : value }); // Setting label else if (key === 'label') node.setLabel(value); // Removing hoverText else if (key === 'hoverText' && !value) node.removeHover(); // Setting hoverText else if (key === 'hoverText' && value) node.setHover(value); // Setting content else if (key === 'content') node.setContent(value); // Updating style else if (key === 'style') node.style = merge({}, node.style, value); // Updating items else if (key === 'items') node.setItems(value); // Border edge case else if (key === 'border') node.border = merge({}, node.border, value); // Textarea value else if (key === 'value' && node.setValue) node.setValue(value); // Progress bar else if (key === 'filled' && node.filled !== value) node.setProgress(value); // Table / ListTable rows / data else if ((key === 'rows' || key === 'data') && node.setData) node.setData(value); else if (key === 'focused' && value && !node[key]) node.focus(); // Raw attributes else if (RAW_ATTRIBUTES.has(key)) node[key] = value; } selectQue.forEach(({node, value}) => node.select(value)); }
Updates the given blessed node. @param {BlessedNode} node - Node to update. @param {object} options - Props of the component without children.
update ( node , options )
javascript
Yomguithereal/react-blessed
src/shared/update.js
https://github.com/Yomguithereal/react-blessed/blob/master/src/shared/update.js
MIT
getUserQueuedAmt(ip) { return this.users[ip] || 0; }
Returns number of requests the ip currently has queued
getUserQueuedAmt ( ip )
javascript
csfloat/inspect
lib/queue.js
https://github.com/csfloat/inspect/blob/master/lib/queue.js
MIT
export function modelToText (model, separator = '') { return listToText(modelToValues(model, 'value'), separator) }
内部数据模型或输出数据模型转换为名称文本,使用分隔符连接 @param {RegionModel | InternalModel} model 数据模型 @returns {string}
modelToText ( model , separator = '' )
javascript
TerryZ/v-region
src/core/parse.js
https://github.com/TerryZ/v-region/blob/master/src/core/parse.js
MIT
export function getAvailableLevels (props, fullLevels) { const levels = [props.city, props.area, props.town && fullLevels] const unavailableLevelIndex = levels.findIndex(val => !val) if (unavailableLevelIndex === -1) return LEVEL_KEYS return LEVEL_KEYS.filter((val, idx) => idx <= unavailableLevelIndex) }
获得组件配置的有效区域级别列表 @param {object} props @param {boolean} fullLevels
getAvailableLevels ( props , fullLevels )
javascript
TerryZ/v-region
src/core/helper.js
https://github.com/TerryZ/v-region/blob/master/src/core/helper.js
MIT
export function keysEqualModels (keys, models) { if (keys.length === models.length) { // 均为空数组 if (!keys.length) return true return models.every(val => keys.includes(val.key)) } return false }
检查初始化数据是否与当前选中数据相同 @param {string[]} keys - 选中城市的键值列表 @param {{ key: string, value: string }[]} cities - 选中城市的模型列表 @returns {boolean}
keysEqualModels ( keys , models )
javascript
TerryZ/v-region
src/core/helper.js
https://github.com/TerryZ/v-region/blob/master/src/core/helper.js
MIT
const resetLowerLevel = level => { if (level === KEY_TOWN) return getLowerLevels(level).forEach(level => resetLevel(level)) }
清除级别数据 @param {string} level 级别编码,传递空内容则清除所有级别数据
resetLowerLevel
javascript
TerryZ/v-region
src/core/base.js
https://github.com/TerryZ/v-region/blob/master/src/core/base.js
MIT
async function parseValueToModel () { if (!props.modelValue || !Object.keys(props.modelValue).length) { setTriggerText?.(lang.pleaseSelect) return }
将 v-model 输入的值转换为数据模型 入参数据模型格式: { province: string, city: string, area: string, town: string } 数据模型格式: { province: { key: string, value: string }, city: { key: string, value: string }, area: { key: string, value: string }, town: { key: string, value: string } }
parseValueToModel ( )
javascript
TerryZ/v-region
src/core/base.js
https://github.com/TerryZ/v-region/blob/master/src/core/base.js
MIT
export function useRegion (props, emit, options) { const { emitUpdateModelValue, emitUpdateNames, emitChange } = useEvent(emit) const { hasCity, hasArea, hasTown } = useState(props) const lang = getLanguage(props.language) const { data, availableLevels, getNextLevel, parseDataValues, setLevelByModel, setModelByValues, resetLowerLevel, parseDataModel, setupTownListLoader } = useData(props) const { setTriggerText } = inject(injectDropdown, {}) const regionText = computed(() => ( listToText(modelToValues(data.value, 'name'), props.separator || '') )) const isComplete = computed(() => ( availableLevels.value.every(level => !!data.value[level].key) )) watch(() => props.modelValue, parseValueToModel) // 界面渲染完成,乡镇级别挂载完成,执行数据转换与匹配 onMounted(parseValueToModel) /** * 将 v-model 输入的值转换为数据模型 * * 入参数据模型格式: * { * province: string, * city: string, * area: string, * town: string * } * * 数据模型格式: * { * province: { key: string, value: string }, * city: { key: string, value: string }, * area: { key: string, value: string }, * town: { key: string, value: string } * } */ async function parseValueToModel () { if (!props.modelValue || !Object.keys(props.modelValue).length) { setTriggerText?.(lang.pleaseSelect) return } // 值与模型一致,不进行转换 if (valueEqualToModel(props.modelValue, data.value)) { return } // 校验与清洗后的 modelValue 值 const cleanedValues = getAvailableValues(props.modelValue) if (isEmptyValues(cleanedValues)) return reset() await setModelByValues(cleanedValues) // 经过校验和清洗后,若值发生变化,则响应 modelValue 变更事件 emitData(!valueEqualToModel(props.modelValue, data.value)) // 提供一个函数入口,在 v-model 值变化处理完成的后续处理 options?.afterModelChange?.()
Region 核心数据与组件交互,与组件对接 @param {object} props @param {string[]} emit @returns {object}
useRegion ( props , emit , options )
javascript
TerryZ/v-region
src/core/base.js
https://github.com/TerryZ/v-region/blob/master/src/core/base.js
MIT
function Fontmin() { if (!(this instanceof Fontmin)) { return new Fontmin(); } EventEmitter.call(this); this.streams = []; }
Initialize Fontmin @constructor @api public
Fontmin ( )
javascript
ecomfe/fontmin
index.js
https://github.com/ecomfe/fontmin/blob/master/index.js
MIT
Fontmin.prototype.src = function (file) { if (!arguments.length) { return this._src; } this._src = arguments; return this; };
Get or set the source files @param {Array|Buffer|string} file files to be optimized @return {Object} fontmin @api public
Fontmin.prototype.src ( file )
javascript
ecomfe/fontmin
index.js
https://github.com/ecomfe/fontmin/blob/master/index.js
MIT
Fontmin.prototype.dest = function (dir) { if (!arguments.length) { return this._dest; } this._dest = arguments; return this; };
Get or set the destination folder @param {string} dir folder to written @return {Object} fontmin @api public
Fontmin.prototype.dest ( dir )
javascript
ecomfe/fontmin
index.js
https://github.com/ecomfe/fontmin/blob/master/index.js
MIT