Introduce some logical assignment in the src/core/ folder

This commit is contained in:
Jonas Jenwald 2022-07-17 11:24:05 +02:00
parent 317abd6d07
commit d950b91c4e
20 changed files with 62 additions and 103 deletions

View File

@ -1556,11 +1556,10 @@ class WidgetAnnotation extends Annotation {
this.setDefaultAppearance(params); this.setDefaultAppearance(params);
data.hasAppearance = data.hasAppearance ||=
(this._needAppearances && this._needAppearances &&
data.fieldValue !== undefined && data.fieldValue !== undefined &&
data.fieldValue !== null) || data.fieldValue !== null;
data.hasAppearance;
const fieldType = getInheritableProperty({ dict, key: "FT" }); const fieldType = getInheritableProperty({ dict, key: "FT" });
data.fieldType = fieldType instanceof Name ? fieldType.name : null; data.fieldType = fieldType instanceof Name ? fieldType.name : null;
@ -1808,7 +1807,7 @@ class WidgetAnnotation extends Annotation {
if (!this._hasValueFromXFA && rotation === undefined) { if (!this._hasValueFromXFA && rotation === undefined) {
return null; return null;
} }
value = value || this.data.fieldValue; value ||= this.data.fieldValue;
} }
// Value can be an array (with choice list and multiple selections) // Value can be an array (with choice list and multiple selections)
@ -3472,7 +3471,7 @@ class LinkAnnotation extends Annotation {
} }
// The color entry for a link annotation is the color of the border. // The color entry for a link annotation is the color of the border.
this.data.borderColor = this.data.borderColor || this.data.color; this.data.borderColor ||= this.data.color;
Catalog.parseDestDictionary({ Catalog.parseDestDictionary({
destDict: params.dict, destDict: params.dict,

View File

@ -985,12 +985,8 @@ class Catalog {
} else if (typeof js !== "string") { } else if (typeof js !== "string") {
return; return;
} }
if (javaScript === null) {
javaScript = new Map();
}
js = stringToPDFString(js).replaceAll("\x00", ""); js = stringToPDFString(js).replaceAll("\x00", "");
javaScript.set(name, js); (javaScript ||= new Map()).set(name, js);
} }
if (obj instanceof Dict && obj.has("JavaScript")) { if (obj instanceof Dict && obj.has("JavaScript")) {

View File

@ -1220,9 +1220,9 @@ const CalRGBCS = (function CalRGBCSClosure() {
"WhitePoint missing - required for color space CalRGB" "WhitePoint missing - required for color space CalRGB"
); );
} }
blackPoint = blackPoint || new Float32Array(3); blackPoint ||= new Float32Array(3);
gamma = gamma || new Float32Array([1, 1, 1]); gamma ||= new Float32Array([1, 1, 1]);
matrix = matrix || new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]); matrix ||= new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
// Translate arguments to spec variables. // Translate arguments to spec variables.
const XW = whitePoint[0]; const XW = whitePoint[0];
@ -1396,8 +1396,8 @@ const LabCS = (function LabCSClosure() {
"WhitePoint missing - required for color space Lab" "WhitePoint missing - required for color space Lab"
); );
} }
blackPoint = blackPoint || [0, 0, 0]; blackPoint ||= [0, 0, 0];
range = range || [-100, 100, -100, 100]; range ||= [-100, 100, -100, 100];
// Translate args to spec variables // Translate args to spec variables
this.XW = whitePoint[0]; this.XW = whitePoint[0];

View File

@ -137,10 +137,7 @@ function getInheritableProperty({
if (stopWhenFound) { if (stopWhenFound) {
return value; return value;
} }
if (!values) { (values ||= []).push(value);
values = [];
}
values.push(value);
} }
dict = dict.get("Parent"); dict = dict.get("Parent");
} }
@ -322,7 +319,7 @@ function _collectJS(entry, xref, list, parents) {
} else if (typeof js === "string") { } else if (typeof js === "string") {
code = js; code = js;
} }
code = code && stringToPDFString(code).replaceAll("\x00", ""); code &&= stringToPDFString(code).replaceAll("\x00", "");
if (code) { if (code) {
list.push(code); list.push(code);
} }

View File

@ -495,12 +495,8 @@ class Page {
for (const { opList, separateForm, separateCanvas } of opLists) { for (const { opList, separateForm, separateCanvas } of opLists) {
pageOpList.addOpList(opList); pageOpList.addOpList(opList);
if (separateForm) { form ||= separateForm;
form = separateForm; canvas ||= separateCanvas;
}
if (separateCanvas) {
canvas = separateCanvas;
}
} }
pageOpList.flush( pageOpList.flush(
/* lastChunk = */ true, /* lastChunk = */ true,
@ -580,8 +576,8 @@ class Page {
return []; return [];
} }
const textContentPromises = []; const annotationsData = [],
const annotationsData = []; textContentPromises = [];
let partialEvaluator; let partialEvaluator;
const intentAny = !!(intent & RenderingIntentFlag.ANY), const intentAny = !!(intent & RenderingIntentFlag.ANY),
@ -597,19 +593,18 @@ class Page {
} }
if (annotation.hasTextContent && isVisible) { if (annotation.hasTextContent && isVisible) {
if (!partialEvaluator) { partialEvaluator ||= new PartialEvaluator({
partialEvaluator = new PartialEvaluator({ xref: this.xref,
xref: this.xref, handler,
handler, pageIndex: this.pageIndex,
pageIndex: this.pageIndex, idFactory: this._localIdFactory,
idFactory: this._localIdFactory, fontCache: this.fontCache,
fontCache: this.fontCache, builtInCMapCache: this.builtInCMapCache,
builtInCMapCache: this.builtInCMapCache, standardFontDataCache: this.standardFontDataCache,
standardFontDataCache: this.standardFontDataCache, globalImageCache: this.globalImageCache,
globalImageCache: this.globalImageCache, options: this.evaluatorOptions,
options: this.evaluatorOptions, });
});
}
textContentPromises.push( textContentPromises.push(
annotation annotation
.extractTextContent(partialEvaluator, task, this.view) .extractTextContent(partialEvaluator, task, this.view)
@ -665,10 +660,7 @@ class Page {
continue; continue;
} }
if (annotation instanceof PopupAnnotation) { if (annotation instanceof PopupAnnotation) {
if (!popupAnnotations) { (popupAnnotations ||= []).push(annotation);
popupAnnotations = [];
}
popupAnnotations.push(annotation);
continue; continue;
} }
sortedAnnotations.push(annotation); sortedAnnotations.push(annotation);

View File

@ -519,7 +519,7 @@ class PartialEvaluator {
} }
if (smask && smask.backdrop) { if (smask && smask.backdrop) {
colorSpace = colorSpace || ColorSpace.singletons.rgb; colorSpace ||= ColorSpace.singletons.rgb;
smask.backdrop = colorSpace.getRgb(smask.backdrop, 0); smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
} }
@ -1272,10 +1272,7 @@ class PartialEvaluator {
} }
if (hash && descriptor instanceof Dict) { if (hash && descriptor instanceof Dict) {
if (!descriptor.fontAliases) { const fontAliases = (descriptor.fontAliases ||= Object.create(null));
descriptor.fontAliases = Object.create(null);
}
const fontAliases = descriptor.fontAliases;
if (fontAliases[hash]) { if (fontAliases[hash]) {
const aliasFontRef = fontAliases[hash].aliasRef; const aliasFontRef = fontAliases[hash].aliasRef;
@ -1668,8 +1665,8 @@ class PartialEvaluator {
}) { }) {
// Ensure that `resources`/`initialState` is correctly initialized, // Ensure that `resources`/`initialState` is correctly initialized,
// even if the provided parameter is e.g. `null`. // even if the provided parameter is e.g. `null`.
resources = resources || Dict.empty; resources ||= Dict.empty;
initialState = initialState || new EvalState(); initialState ||= new EvalState();
if (!operatorList) { if (!operatorList) {
throw new Error('getOperatorList: missing "operatorList" parameter'); throw new Error('getOperatorList: missing "operatorList" parameter');
@ -2276,11 +2273,11 @@ class PartialEvaluator {
}) { }) {
// Ensure that `resources`/`stateManager` is correctly initialized, // Ensure that `resources`/`stateManager` is correctly initialized,
// even if the provided parameter is e.g. `null`. // even if the provided parameter is e.g. `null`.
resources = resources || Dict.empty; resources ||= Dict.empty;
stateManager = stateManager || new StateManager(new TextState()); stateManager ||= new StateManager(new TextState());
if (includeMarkedContent) { if (includeMarkedContent) {
markedContentData = markedContentData || { level: 0 }; markedContentData ||= { level: 0 };
} }
const textContent = { const textContent = {
@ -4255,7 +4252,7 @@ class PartialEvaluator {
} }
} }
} }
fontName = fontName || baseFont; fontName ||= baseFont;
if (!(fontName instanceof Name)) { if (!(fontName instanceof Name)) {
throw new FormatError("invalid font name"); throw new FormatError("invalid font name");

View File

@ -743,7 +743,7 @@ function validateOS2Table(os2, file) {
} }
function createOS2Table(properties, charstrings, override) { function createOS2Table(properties, charstrings, override) {
override = override || { override ||= {
unitsPerEm: 0, unitsPerEm: 0,
yMax: 0, yMax: 0,
yMin: 0, yMin: 0,
@ -3090,10 +3090,7 @@ class Font {
let charCodes = null; let charCodes = null;
for (const charCode in charCodeToGlyphId) { for (const charCode in charCodeToGlyphId) {
if (glyphId === charCodeToGlyphId[charCode]) { if (glyphId === charCodeToGlyphId[charCode]) {
if (!charCodes) { (charCodes ||= []).push(charCode | 0);
charCodes = [];
}
charCodes.push(charCode | 0);
} }
} }
return charCodes; return charCodes;
@ -3285,8 +3282,7 @@ class Font {
break; // the non-zero width found break; // the non-zero width found
} }
} }
width = width || this.defaultWidth; return shadow(this, "spaceWidth", width || this.defaultWidth);
return shadow(this, "spaceWidth", width);
} }
/** /**

View File

@ -25,7 +25,7 @@ function addState(parentState, pattern, checkFn, iterateFn, processFn) {
let state = parentState; let state = parentState;
for (let i = 0, ii = pattern.length - 1; i < ii; i++) { for (let i = 0, ii = pattern.length - 1; i < ii; i++) {
const item = pattern[i]; const item = pattern[i];
state = state[item] || (state[item] = []); state = state[item] ||= [];
} }
state[pattern.at(-1)] = { state[pattern.at(-1)] = {
checkFn, checkFn,

View File

@ -896,7 +896,7 @@ class Lexer {
throw new FormatError(msg); throw new FormatError(msg);
} }
sign = sign || 1; sign ||= 1;
let baseValue = ch - 0x30; // '0' let baseValue = ch - 0x30; // '0'
let powerValue = 0; let powerValue = 0;
let powerValueSign = 1; let powerValueSign = 1;

View File

@ -366,13 +366,10 @@ const getB = (function getBClosure() {
} }
return lut; return lut;
} }
const cache = []; const cache = Object.create(null);
return function (count) { return function (count) {
if (!cache[count]) { return (cache[count] ||= buildB(count));
cache[count] = buildB(count);
}
return cache[count];
}; };
})(); })();

View File

@ -48,8 +48,7 @@ class BasePdfManager {
// Check `OffscreenCanvas` support once, rather than repeatedly throughout // Check `OffscreenCanvas` support once, rather than repeatedly throughout
// the worker-thread code. // the worker-thread code.
args.evaluatorOptions.isOffscreenCanvasSupported = args.evaluatorOptions.isOffscreenCanvasSupported &&=
args.evaluatorOptions.isOffscreenCanvasSupported &&
FeatureTest.isOffscreenCanvasSupported; FeatureTest.isOffscreenCanvasSupported;
this.evaluatorOptions = args.evaluatorOptions; this.evaluatorOptions = args.evaluatorOptions;
} }

View File

@ -41,7 +41,7 @@ class Name {
static get(name) { static get(name) {
// eslint-disable-next-line no-restricted-syntax // eslint-disable-next-line no-restricted-syntax
return NameCache[name] || (NameCache[name] = new Name(name)); return (NameCache[name] ||= new Name(name));
} }
} }
@ -58,7 +58,7 @@ class Cmd {
static get(cmd) { static get(cmd) {
// eslint-disable-next-line no-restricted-syntax // eslint-disable-next-line no-restricted-syntax
return CmdCache[cmd] || (CmdCache[cmd] = new Cmd(cmd)); return (CmdCache[cmd] ||= new Cmd(cmd));
} }
} }
@ -282,7 +282,7 @@ class Ref {
static get(num, gen) { static get(num, gen) {
const key = gen === 0 ? `${num}R` : `${num}R${gen}`; const key = gen === 0 ? `${num}R` : `${num}R${gen}`;
// eslint-disable-next-line no-restricted-syntax // eslint-disable-next-line no-restricted-syntax
return RefCache[key] || (RefCache[key] = new Ref(num, gen)); return (RefCache[key] ||= new Ref(num, gen));
} }
} }

View File

@ -120,11 +120,7 @@ class PostScriptToken {
} }
static getOperator(op) { static getOperator(op) {
const opValue = PostScriptToken.opCache[op]; return (PostScriptToken.opCache[op] ||= new PostScriptToken(
if (opValue) {
return opValue;
}
return (PostScriptToken.opCache[op] = new PostScriptToken(
PostScriptTokenTypes.OPERATOR, PostScriptTokenTypes.OPERATOR,
op op
)); ));

View File

@ -261,8 +261,7 @@ class WorkerMessageHandler {
pdfManagerArgs.source = pdfStream; pdfManagerArgs.source = pdfStream;
pdfManagerArgs.length = fullRequest.contentLength; pdfManagerArgs.length = fullRequest.contentLength;
// We don't need auto-fetch when streaming is enabled. // We don't need auto-fetch when streaming is enabled.
pdfManagerArgs.disableAutoFetch = pdfManagerArgs.disableAutoFetch ||= fullRequest.isStreamingSupported;
pdfManagerArgs.disableAutoFetch || fullRequest.isStreamingSupported;
newPdfManager = new NetworkPdfManager(pdfManagerArgs); newPdfManager = new NetworkPdfManager(pdfManagerArgs);
// There may be a chance that `newPdfManager` is not initialized for // There may be a chance that `newPdfManager` is not initialized for
@ -661,7 +660,6 @@ class WorkerMessageHandler {
}); });
} }
const lastXRefStreamPos = xref.lastXRefStreamPos;
newXrefInfo = { newXrefInfo = {
rootRef: xref.trailer.getRaw("Root") || null, rootRef: xref.trailer.getRaw("Root") || null,
encryptRef: xref.trailer.getRaw("Encrypt") || null, encryptRef: xref.trailer.getRaw("Encrypt") || null,
@ -669,8 +667,7 @@ class WorkerMessageHandler {
infoRef: xref.trailer.getRaw("Info") || null, infoRef: xref.trailer.getRaw("Info") || null,
info: infoObj, info: infoObj,
fileIds: xref.trailer.get("ID") || null, fileIds: xref.trailer.get("ID") || null,
startXRef: startXRef: xref.lastXRefStreamPos ?? startXRef,
lastXRefStreamPos === null ? startXRef : lastXRefStreamPos,
filename, filename,
}; };
} }

View File

@ -275,7 +275,7 @@ class SimpleExprParser {
} }
parse(tok) { parse(tok) {
tok = tok || this.lexer.next(); tok ||= this.lexer.next();
while (true) { while (true) {
// Token ids (see form_lexer.js) are consecutive in order // Token ids (see form_lexer.js) are consecutive in order
@ -1005,7 +1005,7 @@ class Parser {
} }
parseExpr(tok) { parseExpr(tok) {
tok = tok || this.lexer.next(); tok ||= this.lexer.next();
switch (tok.id) { switch (tok.id) {
case TOKEN.identifier: case TOKEN.identifier:
return this.parseAssigmentOrExpr(tok); return this.parseAssigmentOrExpr(tok);

View File

@ -107,10 +107,7 @@ class XFAParser extends XMLParserBase {
nsAttrs = attributeObj[$nsAttributes] = Object.create(null); nsAttrs = attributeObj[$nsAttributes] = Object.create(null);
} }
const [ns, attrName] = [name.slice(0, i), name.slice(i + 1)]; const [ns, attrName] = [name.slice(0, i), name.slice(i + 1)];
let attrs = nsAttrs[ns]; const attrs = (nsAttrs[ns] ||= Object.create(null));
if (!attrs) {
attrs = nsAttrs[ns] = Object.create(null);
}
attrs[attrName] = value; attrs[attrName] = value;
} }
} }

View File

@ -5573,8 +5573,7 @@ class Template extends XFAObject {
const flush = index => { const flush = index => {
const html = root[$flushHTML](); const html = root[$flushHTML]();
if (html) { if (html) {
hasSomething = hasSomething ||= !!html.children && html.children.length !== 0;
hasSomething || (html.children && html.children.length !== 0);
htmlContentAreas[index].children.push(html); htmlContentAreas[index].children.push(html);
} }
}; };
@ -5597,9 +5596,8 @@ class Template extends XFAObject {
const html = root[$toHTML](space); const html = root[$toHTML](space);
if (html.success) { if (html.success) {
if (html.html) { if (html.html) {
hasSomething = hasSomething ||=
hasSomething || !!html.html.children && html.html.children.length !== 0;
(html.html.children && html.html.children.length !== 0);
htmlContentAreas[i].children.push(html.html); htmlContentAreas[i].children.push(html.html);
} else if (!hasSomething && mainHtml.children.length > 1) { } else if (!hasSomething && mainHtml.children.length > 1) {
mainHtml.children.pop(); mainHtml.children.pop();

View File

@ -75,7 +75,7 @@ function getStringOption(data, options) {
} }
function getMeasurement(str, def = "0") { function getMeasurement(str, def = "0") {
def = def || "0"; def ||= "0";
if (!str) { if (!str) {
return getMeasurement(def); return getMeasurement(def);
} }

View File

@ -451,7 +451,7 @@ class AnnotationElement {
_createPopup(trigger, data) { _createPopup(trigger, data) {
let container = this.container; let container = this.container;
if (this.quadrilaterals) { if (this.quadrilaterals) {
trigger = trigger || this.quadrilaterals; trigger ||= this.quadrilaterals;
container = this.quadrilaterals[0]; container = this.quadrilaterals[0];
} }

View File

@ -3356,9 +3356,7 @@ class InternalRenderTask {
operatorListChanged() { operatorListChanged() {
if (!this.graphicsReady) { if (!this.graphicsReady) {
if (!this.graphicsReadyCallback) { this.graphicsReadyCallback ||= this._continueBound;
this.graphicsReadyCallback = this._continueBound;
}
return; return;
} }
this.stepper?.updateOperatorList(this.operatorList); this.stepper?.updateOperatorList(this.operatorList);