UNPKG

llh-pdf

Version:

一个基于 Vue3 的 PDF 预览组件,集成了 PDF.js,提供了丰富的 PDF 预览功能。

1,617 lines (1,583 loc) 547 kB
/** * @licstart The following is the entire license notice for the * JavaScript code in this page * * Copyright 2023 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @licend The above is the entire license notice for the * JavaScript code in this page */ /******/ var __webpack_modules__ = ({ /***/ 588: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { // EXPORTS __webpack_require__.d(__webpack_exports__, { FluentBundle: () => (/* reexport */ FluentBundle), FluentResource: () => (/* reexport */ FluentResource) }); function defer() { let resolve; let reject; const promise = new Promise((_resolve, _reject) => { resolve = _resolve; reject = _reject; }); return { resolve, reject, promise }; } Promise.withResolvers = defer; function at(n) { // Convert the argument to an integer n = Math.trunc(n) || 0; // 去掉小数点 // Allow negative indexing from the end if (n < 0) n += this.length; // Out-of-bounds access returns undefined if (n < 0 || n >= this.length) return undefined; // Otherwise, this is just normal property access return this[n]; } Array.prototype.at = at; // UNUSED EXPORTS: FluentDateTime, FluentNone, FluentNumber, FluentType ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/types.js class FluentType { constructor(value) { this.value = value; } valueOf() { return this.value; } } class FluentNone extends FluentType { constructor(value = "???") { super(value); } toString(scope) { return `{${this.value}}`; } } class FluentNumber extends FluentType { constructor(value, opts = {}) { super(value); this.opts = opts; } toString(scope) { try { const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts); return nf.format(this.value); } catch (err) { scope.reportError(err); return this.value.toString(10); } } } class FluentDateTime extends FluentType { constructor(value, opts = {}) { super(value); this.opts = opts; } toString(scope) { try { const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts); return dtf.format(this.value); } catch (err) { scope.reportError(err); return new Date(this.value).toISOString(); } } } ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/resolver.js const MAX_PLACEABLES = 100; const FSI = "\u2068"; const PDI = "\u2069"; function match(scope, selector, key) { if (key === selector) { return true; } if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) { return true; } if (selector instanceof FluentNumber && typeof key === "string") { let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value); if (key === category) { return true; } } return false; } function getDefault(scope, variants, star) { if (variants[star]) { return resolvePattern(scope, variants[star].value); } scope.reportError(new RangeError("No default")); return new FluentNone(); } function getArguments(scope, args) { const positional = []; const named = Object.create(null); for (const arg of args) { if (arg.type === "narg") { named[arg.name] = resolveExpression(scope, arg.value); } else { positional.push(resolveExpression(scope, arg)); } } return { positional, named }; } function resolveExpression(scope, expr) { switch (expr.type) { case "str": return expr.value; case "num": return new FluentNumber(expr.value, { minimumFractionDigits: expr.precision }); case "var": return resolveVariableReference(scope, expr); case "mesg": return resolveMessageReference(scope, expr); case "term": return resolveTermReference(scope, expr); case "func": return resolveFunctionReference(scope, expr); case "select": return resolveSelectExpression(scope, expr); default: return new FluentNone(); } } function resolveVariableReference(scope, { name }) { let arg; if (scope.params) { if (Object.prototype.hasOwnProperty.call(scope.params, name)) { arg = scope.params[name]; } else { return new FluentNone(`$${name}`); } } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) { arg = scope.args[name]; } else { scope.reportError(new ReferenceError(`Unknown variable: $${name}`)); return new FluentNone(`$${name}`); } if (arg instanceof FluentType) { return arg; } switch (typeof arg) { case "string": return arg; case "number": return new FluentNumber(arg); case "object": if (arg instanceof Date) { return new FluentDateTime(arg.getTime()); } default: scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`)); return new FluentNone(`$${name}`); } } function resolveMessageReference(scope, { name, attr }) { const message = scope.bundle._messages.get(name); if (!message) { scope.reportError(new ReferenceError(`Unknown message: ${name}`)); return new FluentNone(name); } if (attr) { const attribute = message.attributes[attr]; if (attribute) { return resolvePattern(scope, attribute); } scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); return new FluentNone(`${name}.${attr}`); } if (message.value) { return resolvePattern(scope, message.value); } scope.reportError(new ReferenceError(`No value: ${name}`)); return new FluentNone(name); } function resolveTermReference(scope, { name, attr, args }) { const id = `-${name}`; const term = scope.bundle._terms.get(id); if (!term) { scope.reportError(new ReferenceError(`Unknown term: ${id}`)); return new FluentNone(id); } if (attr) { const attribute = term.attributes[attr]; if (attribute) { scope.params = getArguments(scope, args).named; const resolved = resolvePattern(scope, attribute); scope.params = null; return resolved; } scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); return new FluentNone(`${id}.${attr}`); } scope.params = getArguments(scope, args).named; const resolved = resolvePattern(scope, term.value); scope.params = null; return resolved; } function resolveFunctionReference(scope, { name, args }) { let func = scope.bundle._functions[name]; if (!func) { scope.reportError(new ReferenceError(`Unknown function: ${name}()`)); return new FluentNone(`${name}()`); } if (typeof func !== "function") { scope.reportError(new TypeError(`Function ${name}() is not callable`)); return new FluentNone(`${name}()`); } try { let resolved = getArguments(scope, args); return func(resolved.positional, resolved.named); } catch (err) { scope.reportError(err); return new FluentNone(`${name}()`); } } function resolveSelectExpression(scope, { selector, variants, star }) { let sel = resolveExpression(scope, selector); if (sel instanceof FluentNone) { return getDefault(scope, variants, star); } for (const variant of variants) { const key = resolveExpression(scope, variant.key); if (match(scope, sel, key)) { return resolvePattern(scope, variant.value); } } return getDefault(scope, variants, star); } function resolveComplexPattern(scope, ptn) { if (scope.dirty.has(ptn)) { scope.reportError(new RangeError("Cyclic reference")); return new FluentNone(); } scope.dirty.add(ptn); const result = []; const useIsolating = scope.bundle._useIsolating && ptn.length > 1; for (const elem of ptn) { if (typeof elem === "string") { result.push(scope.bundle._transform(elem)); continue; } scope.placeables++; if (scope.placeables > MAX_PLACEABLES) { scope.dirty.delete(ptn); throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`); } if (useIsolating) { result.push(FSI); } result.push(resolveExpression(scope, elem).toString(scope)); if (useIsolating) { result.push(PDI); } } scope.dirty.delete(ptn); return result.join(""); } function resolvePattern(scope, value) { if (typeof value === "string") { return scope.bundle._transform(value); } return resolveComplexPattern(scope, value); } ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/scope.js class Scope { constructor(bundle, errors, args) { this.dirty = new WeakSet(); this.params = null; this.placeables = 0; this.bundle = bundle; this.errors = errors; this.args = args; } reportError(error) { if (!this.errors || !(error instanceof Error)) { throw error; } this.errors.push(error); } memoizeIntlObject(ctor, opts) { let cache = this.bundle._intls.get(ctor); if (!cache) { cache = {}; this.bundle._intls.set(ctor, cache); } let id = JSON.stringify(opts); if (!cache[id]) { cache[id] = new ctor(this.bundle.locales, opts); } return cache[id]; } } ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/builtins.js function values(opts, allowed) { const unwrapped = Object.create(null); for (const [name, opt] of Object.entries(opts)) { if (allowed.includes(name)) { unwrapped[name] = opt.valueOf(); } } return unwrapped; } const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"]; function NUMBER(args, opts) { let arg = args[0]; if (arg instanceof FluentNone) { return new FluentNone(`NUMBER(${arg.valueOf()})`); } if (arg instanceof FluentNumber) { return new FluentNumber(arg.valueOf(), { ...arg.opts, ...values(opts, NUMBER_ALLOWED) }); } if (arg instanceof FluentDateTime) { return new FluentNumber(arg.valueOf(), { ...values(opts, NUMBER_ALLOWED) }); } throw new TypeError("Invalid argument to NUMBER"); } const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"]; function DATETIME(args, opts) { let arg = args[0]; if (arg instanceof FluentNone) { return new FluentNone(`DATETIME(${arg.valueOf()})`); } if (arg instanceof FluentDateTime) { return new FluentDateTime(arg.valueOf(), { ...arg.opts, ...values(opts, DATETIME_ALLOWED) }); } if (arg instanceof FluentNumber) { return new FluentDateTime(arg.valueOf(), { ...values(opts, DATETIME_ALLOWED) }); } throw new TypeError("Invalid argument to DATETIME"); } ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/memoizer.js const cache = new Map(); function getMemoizerForLocale(locales) { const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales; let memoizer = cache.get(stringLocale); if (memoizer === undefined) { memoizer = new Map(); cache.set(stringLocale, memoizer); } return memoizer; } ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/bundle.js class FluentBundle { constructor(locales, { functions, useIsolating = true, transform = v => v } = {}) { this._terms = new Map(); this._messages = new Map(); this.locales = Array.isArray(locales) ? locales : [locales]; this._functions = { NUMBER: NUMBER, DATETIME: DATETIME, ...functions }; this._useIsolating = useIsolating; this._transform = transform; this._intls = getMemoizerForLocale(locales); } hasMessage(id) { return this._messages.has(id); } getMessage(id) { return this._messages.get(id); } addResource(res, { allowOverrides = false } = {}) { const errors = []; for (let i = 0; i < res.body.length; i++) { let entry = res.body[i]; if (entry.id.startsWith("-")) { if (allowOverrides === false && this._terms.has(entry.id)) { errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`)); continue; } this._terms.set(entry.id, entry); } else { if (allowOverrides === false && this._messages.has(entry.id)) { errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`)); continue; } this._messages.set(entry.id, entry); } } return errors; } formatPattern(pattern, args = null, errors = null) { if (typeof pattern === "string") { return this._transform(pattern); } let scope = new Scope(this, errors, args); try { let value = resolveComplexPattern(scope, pattern); return value.toString(scope); } catch (err) { if (scope.errors && err instanceof Error) { scope.errors.push(err); return new FluentNone().toString(scope); } throw err; } } } ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/resource.js const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm; const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y; const RE_VARIANT_START = /\*?\[/y; const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y; const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y; const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y; const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/; const RE_TEXT_RUN = /([^{}\n\r]+)/y; const RE_STRING_RUN = /([^\\"\n\r]*)/y; const RE_STRING_ESCAPE = /\\([\\"])/y; const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y; const RE_LEADING_NEWLINES = /^\n+/; const RE_TRAILING_SPACES = / +$/; const RE_BLANK_LINES = / *\r?\n/g; const RE_INDENT = /( *)$/; const TOKEN_BRACE_OPEN = /{\s*/y; const TOKEN_BRACE_CLOSE = /\s*}/y; const TOKEN_BRACKET_OPEN = /\[\s*/y; const TOKEN_BRACKET_CLOSE = /\s*] */y; const TOKEN_PAREN_OPEN = /\s*\(\s*/y; const TOKEN_ARROW = /\s*->\s*/y; const TOKEN_COLON = /\s*:\s*/y; const TOKEN_COMMA = /\s*,?\s*/y; const TOKEN_BLANK = /\s+/y; class FluentResource { constructor(source) { this.body = []; RE_MESSAGE_START.lastIndex = 0; let cursor = 0; while (true) { let next = RE_MESSAGE_START.exec(source); if (next === null) { break; } cursor = RE_MESSAGE_START.lastIndex; try { this.body.push(parseMessage(next[1])); } catch (err) { if (err instanceof SyntaxError) { continue; } throw err; } } function test(re) { re.lastIndex = cursor; return re.test(source); } function consumeChar(char, errorClass) { if (source[cursor] === char) { cursor++; return true; } if (errorClass) { throw new errorClass(`Expected ${char}`); } return false; } function consumeToken(re, errorClass) { if (test(re)) { cursor = re.lastIndex; return true; } if (errorClass) { throw new errorClass(`Expected ${re.toString()}`); } return false; } function match(re) { re.lastIndex = cursor; let result = re.exec(source); if (result === null) { throw new SyntaxError(`Expected ${re.toString()}`); } cursor = re.lastIndex; return result; } function match1(re) { return match(re)[1]; } function parseMessage(id) { let value = parsePattern(); let attributes = parseAttributes(); if (value === null && Object.keys(attributes).length === 0) { throw new SyntaxError("Expected message value or attributes"); } return { id, value, attributes }; } function parseAttributes() { let attrs = Object.create(null); while (test(RE_ATTRIBUTE_START)) { let name = match1(RE_ATTRIBUTE_START); let value = parsePattern(); if (value === null) { throw new SyntaxError("Expected attribute value"); } attrs[name] = value; } return attrs; } function parsePattern() { let first; if (test(RE_TEXT_RUN)) { first = match1(RE_TEXT_RUN); } if (source[cursor] === "{" || source[cursor] === "}") { return parsePatternElements(first ? [first] : [], Infinity); } let indent = parseIndent(); if (indent) { if (first) { return parsePatternElements([first, indent], indent.length); } indent.value = trim(indent.value, RE_LEADING_NEWLINES); return parsePatternElements([indent], indent.length); } if (first) { return trim(first, RE_TRAILING_SPACES); } return null; } function parsePatternElements(elements = [], commonIndent) { while (true) { if (test(RE_TEXT_RUN)) { elements.push(match1(RE_TEXT_RUN)); continue; } if (source[cursor] === "{") { elements.push(parsePlaceable()); continue; } if (source[cursor] === "}") { throw new SyntaxError("Unbalanced closing brace"); } let indent = parseIndent(); if (indent) { elements.push(indent); commonIndent = Math.min(commonIndent, indent.length); continue; } break; } let lastIndex = elements.length - 1; let lastElement = elements[lastIndex]; if (typeof lastElement === "string") { elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES); } let baked = []; for (let element of elements) { if (element instanceof Indent) { element = element.value.slice(0, element.value.length - commonIndent); } if (element) { baked.push(element); } } return baked; } function parsePlaceable() { consumeToken(TOKEN_BRACE_OPEN, SyntaxError); let selector = parseInlineExpression(); if (consumeToken(TOKEN_BRACE_CLOSE)) { return selector; } if (consumeToken(TOKEN_ARROW)) { let variants = parseVariants(); consumeToken(TOKEN_BRACE_CLOSE, SyntaxError); return { type: "select", selector, ...variants }; } throw new SyntaxError("Unclosed placeable"); } function parseInlineExpression() { if (source[cursor] === "{") { return parsePlaceable(); } if (test(RE_REFERENCE)) { let [, sigil, name, attr = null] = match(RE_REFERENCE); if (sigil === "$") { return { type: "var", name }; } if (consumeToken(TOKEN_PAREN_OPEN)) { let args = parseArguments(); if (sigil === "-") { return { type: "term", name, attr, args }; } if (RE_FUNCTION_NAME.test(name)) { return { type: "func", name, args }; } throw new SyntaxError("Function names must be all upper-case"); } if (sigil === "-") { return { type: "term", name, attr, args: [] }; } return { type: "mesg", name, attr }; } return parseLiteral(); } function parseArguments() { let args = []; while (true) { switch (source[cursor]) { case ")": cursor++; return args; case undefined: throw new SyntaxError("Unclosed argument list"); } args.push(parseArgument()); consumeToken(TOKEN_COMMA); } } function parseArgument() { let expr = parseInlineExpression(); if (expr.type !== "mesg") { return expr; } if (consumeToken(TOKEN_COLON)) { return { type: "narg", name: expr.name, value: parseLiteral() }; } return expr; } function parseVariants() { let variants = []; let count = 0; let star; while (test(RE_VARIANT_START)) { if (consumeChar("*")) { star = count; } let key = parseVariantKey(); let value = parsePattern(); if (value === null) { throw new SyntaxError("Expected variant value"); } variants[count++] = { key, value }; } if (count === 0) { return null; } if (star === undefined) { throw new SyntaxError("Expected default variant"); } return { variants, star }; } function parseVariantKey() { consumeToken(TOKEN_BRACKET_OPEN, SyntaxError); let key; if (test(RE_NUMBER_LITERAL)) { key = parseNumberLiteral(); } else { key = { type: "str", value: match1(RE_IDENTIFIER) }; } consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError); return key; } function parseLiteral() { if (test(RE_NUMBER_LITERAL)) { return parseNumberLiteral(); } if (source[cursor] === '"') { return parseStringLiteral(); } throw new SyntaxError("Invalid expression"); } function parseNumberLiteral() { let [, value, fraction = ""] = match(RE_NUMBER_LITERAL); let precision = fraction.length; return { type: "num", value: parseFloat(value), precision }; } function parseStringLiteral() { consumeChar('"', SyntaxError); let value = ""; while (true) { value += match1(RE_STRING_RUN); if (source[cursor] === "\\") { value += parseEscapeSequence(); continue; } if (consumeChar('"')) { return { type: "str", value }; } throw new SyntaxError("Unclosed string literal"); } } function parseEscapeSequence() { if (test(RE_STRING_ESCAPE)) { return match1(RE_STRING_ESCAPE); } if (test(RE_UNICODE_ESCAPE)) { let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE); let codepoint = parseInt(codepoint4 || codepoint6, 16); return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�"; } throw new SyntaxError("Unknown escape sequence"); } function parseIndent() { let start = cursor; consumeToken(TOKEN_BLANK); switch (source[cursor]) { case ".": case "[": case "*": case "}": case undefined: return false; case "{": return makeIndent(source.slice(start, cursor)); } if (source[cursor - 1] === " ") { return makeIndent(source.slice(start, cursor)); } return false; } function trim(text, re) { return text.replace(re, ""); } function makeIndent(blank) { let value = blank.replace(RE_BLANK_LINES, "\n"); let length = RE_INDENT.exec(blank)[1].length; return new Indent(value, length); } } } class Indent { constructor(value, length) { this.value = value; this.length = length; } } ;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/index.js /***/ }), /***/ 5273: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { // EXPORTS __webpack_require__.d(__webpack_exports__, { DOMLocalization: () => (/* reexport */ DOMLocalization) }); // UNUSED EXPORTS: Localization ;// CONCATENATED MODULE: ./node_modules/@fluent/dom/esm/overlay.js const reOverlay = /<|&#?\w+;/; const TEXT_LEVEL_ELEMENTS = { "http://www.w3.org/1999/xhtml": ["em", "strong", "small", "s", "cite", "q", "dfn", "abbr", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u", "mark", "bdi", "bdo", "span", "br", "wbr"] }; const LOCALIZABLE_ATTRIBUTES = { "http://www.w3.org/1999/xhtml": { global: ["title", "aria-label", "aria-valuetext"], a: ["download"], area: ["download", "alt"], input: ["alt", "placeholder"], menuitem: ["label"], menu: ["label"], optgroup: ["label"], option: ["label"], track: ["label"], img: ["alt"], textarea: ["placeholder"], th: ["abbr"] }, "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": { global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"], description: ["value"], key: ["key", "keycode"], label: ["value"], textbox: ["placeholder", "value"] } }; function translateElement(element, translation) { const { value } = translation; if (typeof value === "string") { if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") { element.textContent = value; } else if (!reOverlay.test(value)) { element.textContent = value; } else { const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template"); templateElement.innerHTML = value; overlayChildNodes(templateElement.content, element); } } overlayAttributes(translation, element); } function overlayChildNodes(fromFragment, toElement) { for (const childNode of fromFragment.childNodes) { if (childNode.nodeType === childNode.TEXT_NODE) { continue; } if (childNode.hasAttribute("data-l10n-name")) { const sanitized = getNodeForNamedElement(toElement, childNode); fromFragment.replaceChild(sanitized, childNode); continue; } if (isElementAllowed(childNode)) { const sanitized = createSanitizedElement(childNode); fromFragment.replaceChild(sanitized, childNode); continue; } console.warn(`An element of forbidden type "${childNode.localName}" was found in ` + "the translation. Only safe text-level elements and elements with " + "data-l10n-name are allowed."); fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode); } toElement.textContent = ""; toElement.appendChild(fromFragment); } function hasAttribute(attributes, name) { if (!attributes) { return false; } for (let attr of attributes) { if (attr.name === name) { return true; } } return false; } function overlayAttributes(fromElement, toElement) { const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null; for (const attr of Array.from(toElement.attributes)) { if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) { toElement.removeAttribute(attr.name); } } if (!fromElement.attributes) { return; } for (const attr of Array.from(fromElement.attributes)) { if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) { toElement.setAttribute(attr.name, attr.value); } } } function getNodeForNamedElement(sourceElement, translatedChild) { const childName = translatedChild.getAttribute("data-l10n-name"); const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`); if (!sourceChild) { console.warn(`An element named "${childName}" wasn't found in the source.`); return createTextNodeFromTextContent(translatedChild); } if (sourceChild.localName !== translatedChild.localName) { console.warn(`An element named "${childName}" was found in the translation ` + `but its type ${translatedChild.localName} didn't match the ` + `element found in the source (${sourceChild.localName}).`); return createTextNodeFromTextContent(translatedChild); } sourceElement.removeChild(sourceChild); const clone = sourceChild.cloneNode(false); return shallowPopulateUsing(translatedChild, clone); } function createSanitizedElement(element) { const clone = element.ownerDocument.createElement(element.localName); return shallowPopulateUsing(element, clone); } function createTextNodeFromTextContent(element) { return element.ownerDocument.createTextNode(element.textContent); } function isElementAllowed(element) { const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI]; return allowed && allowed.includes(element.localName); } function isAttrNameLocalizable(name, element, explicitlyAllowed = null) { if (explicitlyAllowed && explicitlyAllowed.includes(name)) { return true; } const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI]; if (!allowed) { return false; } const attrName = name.toLowerCase(); const elemName = element.localName; if (allowed.global.includes(attrName)) { return true; } if (!allowed[elemName]) { return false; } if (allowed[elemName].includes(attrName)) { return true; } if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") { const type = element.type.toLowerCase(); if (type === "submit" || type === "button" || type === "reset") { return true; } } return false; } function shallowPopulateUsing(fromElement, toElement) { toElement.textContent = fromElement.textContent; overlayAttributes(fromElement, toElement); return toElement; } ;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_iterable.mjs class CachedIterable extends Array { static from(iterable) { if (iterable instanceof this) { return iterable; } return new this(iterable); } } ;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_sync_iterable.mjs class CachedSyncIterable extends CachedIterable { constructor(iterable) { super(); if (Symbol.iterator in Object(iterable)) { this.iterator = iterable[Symbol.iterator](); } else { throw new TypeError("Argument must implement the iteration protocol."); } } [Symbol.iterator]() { const cached = this; let cur = 0; return { next() { if (cached.length <= cur) { cached.push(cached.iterator.next()); } return cached[cur++]; } }; } touchNext(count = 1) { let idx = 0; while (idx++ < count) { const last = this[this.length - 1]; if (last && last.done) { break; } this.push(this.iterator.next()); } return this[this.length - 1]; } } ;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_async_iterable.mjs class CachedAsyncIterable extends CachedIterable { constructor(iterable) { super(); if (Symbol.asyncIterator in Object(iterable)) { this.iterator = iterable[Symbol.asyncIterator](); } else if (Symbol.iterator in Object(iterable)) { this.iterator = iterable[Symbol.iterator](); } else { throw new TypeError("Argument must implement the iteration protocol."); } } [Symbol.asyncIterator]() { const cached = this; let cur = 0; return { async next() { if (cached.length <= cur) { cached.push(cached.iterator.next()); } return cached[cur++]; } }; } async touchNext(count = 1) { let idx = 0; while (idx++ < count) { const last = this[this.length - 1]; if (last && (await last).done) { break; } this.push(this.iterator.next()); } return this[this.length - 1]; } } ;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/index.mjs ;// CONCATENATED MODULE: ./node_modules/@fluent/dom/esm/localization.js class Localization { constructor(resourceIds = [], generateBundles) { this.resourceIds = resourceIds; this.generateBundles = generateBundles; this.onChange(true); } addResourceIds(resourceIds, eager = false) { this.resourceIds.push(...resourceIds); this.onChange(eager); return this.resourceIds.length; } removeResourceIds(resourceIds) { this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r)); this.onChange(); return this.resourceIds.length; } async formatWithFallback(keys, method) { const translations = []; let hasAtLeastOneBundle = false; for await (const bundle of this.bundles) { hasAtLeastOneBundle = true; const missingIds = keysFromBundle(method, bundle, keys, translations); if (missingIds.size === 0) { break; } if (typeof console !== "undefined") { const locale = bundle.locales[0]; const ids = Array.from(missingIds).join(", "); console.warn(`[fluent] Missing translations in ${locale}: ${ids}`); } } if (!hasAtLeastOneBundle && typeof console !== "undefined") { console.warn(`[fluent] Request for keys failed because no resource bundles got generated. keys: ${JSON.stringify(keys)}. resourceIds: ${JSON.stringify(this.resourceIds)}.`); } return translations; } formatMessages(keys) { return this.formatWithFallback(keys, messageFromBundle); } formatValues(keys) { return this.formatWithFallback(keys, valueFromBundle); } async formatValue(id, args) { const [val] = await this.formatValues([{ id, args }]); return val; } handleEvent() { this.onChange(); } onChange(eager = false) { this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds)); if (eager) { this.bundles.touchNext(2); } } } function valueFromBundle(bundle, errors, message, args) { if (message.value) { return bundle.formatPattern(message.value, args, errors); } return null; } function messageFromBundle(bundle, errors, message, args) { const formatted = { value: null, attributes: null }; if (message.value) { formatted.value = bundle.formatPattern(message.value, args, errors); } let attrNames = Object.keys(message.attributes); if (attrNames.length > 0) { formatted.attributes = new Array(attrNames.length); for (let [i, name] of attrNames.entries()) { let value = bundle.formatPattern(message.attributes[name], args, errors); formatted.attributes[i] = { name, value }; } } return formatted; } function keysFromBundle(method, bundle, keys, translations) { const messageErrors = []; const missingIds = new Set(); keys.forEach(({ id, args }, i) => { if (translations[i] !== undefined) { return; } let message = bundle.getMessage(id); if (message) { messageErrors.length = 0; translations[i] = method(bundle, messageErrors, message, args); if (messageErrors.length > 0 && typeof console !== "undefined") { const locale = bundle.locales[0]; const errors = messageErrors.join(", "); console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`); } } else { missingIds.add(id); } }); return missingIds; } ;// CONCATENATED MODULE: ./node_modules/@fluent/dom/esm/dom_localization.js const L10NID_ATTR_NAME = "data-l10n-id"; const L10NARGS_ATTR_NAME = "data-l10n-args"; const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`; class DOMLocalization extends Localization { constructor(resourceIds, generateBundles) { super(resourceIds, generateBundles); this.roots = new Set(); this.pendingrAF = null; this.pendingElements = new Set(); this.windowElement = null; this.mutationObserver = null; this.observerConfig = { attributes: true, characterData: false, childList: true, subtree: true, attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME] }; } onChange(eager = false) { super.onChange(eager); if (this.roots) { this.translateRoots(); } } setAttributes(element, id, args) { element.setAttribute(L10NID_ATTR_NAME, id); if (args) { element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args)); } else { element.removeAttribute(L10NARGS_ATTR_NAME); } return element; } getAttributes(element) { return { id: element.getAttribute(L10NID_ATTR_NAME), args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) }; } connectRoot(newRoot) { for (const root of this.roots) { if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) { throw new Error("Cannot add a root that overlaps with existing root."); } } if (this.windowElement) { if (this.windowElement !== newRoot.ownerDocument.defaultView) { throw new Error(`Cannot connect a root: DOMLocalization already has a root from a different window.`); } } else { this.windowElement = newRoot.ownerDocument.defaultView; this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations)); } this.roots.add(newRoot); this.mutationObserver.observe(newRoot, this.observerConfig); } disconnectRoot(root) { this.roots.delete(root); this.pauseObserving(); if (this.roots.size === 0) { this.mutationObserver = null; this.windowElement = null; this.pendingrAF = null; this.pendingElements.clear(); return true; } this.resumeObserving(); return false; } translateRoots() { const roots = Array.from(this.roots); return Promise.all(roots.map(root => this.translateFragment(root))); } pauseObserving() { if (!this.mutationObserver) { return; } this.translateMutations(this.mutationObserver.takeRecords()); this.mutationObserver.disconnect(); } resumeObserving() { if (!this.mutationObserver) { return; } for (const root of this.roots) { this.mutationObserver.observe(root, this.observerConfig); } } translateMutations(mutations) { for (const mutation of mutations) { switch (mutation.type) { case "attributes": if (mutation.target.hasAttribute("data-l10n-id")) { this.pendingElements.add(mutation.target); } break; case "childList": for (const addedNode of mutation.addedNodes) { if (addedNode.nodeType === addedNode.ELEMENT_NODE) { if (addedNode.childElementCount) { for (const element of this.getTranslatables(addedNode)) { this.pendingElements.add(element); } } else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) { this.pendingElements.add(addedNode); } } } break; } } if (this.pendingElements.size > 0) { if (this.pendingrAF === null) { this.pendingrAF = this.windowElement.requestAnimationFrame(() => { this.translateElements(Array.from(this.pendingElements)); this.pendingElements.clear(); this.pendingrAF = null; }); } } } translateFragment(frag) { return this.translateElements(this.getTranslatables(frag)); } async translateElements(elements) { if (!elements.length) { return undefined; } const keys = elements.map(this.getKeysForElement); const translations = await this.formatMessages(keys); return this.applyTranslations(elements, translations); } applyTranslations(elements, translations) { this.pauseObserving(); for (let i = 0; i < elements.length; i++) { if (translations[i] !== undefined) { translateElement(elements[i], translations[i]); } } this.resumeObserving(); } getTranslatables(element) { const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY)); if (typeof element.hasAttribute === "function" && element.hasAttribute(L10NID_ATTR_NAME)) { nodes.push(element); } return nodes; } getKeysForElement(element) { return { id: element.getAttribute(L10NID_ATTR_NAME), args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) }; } } ;// CONCATENATED MODULE: ./node_modules/@fluent/dom/esm/index.js /***/ }), /***/ 259: /***/ ((__webpack_module__, __webpack_exports__, __webpack_require__) => { __webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AltTextManager: () => (/* binding */ AltTextManager) /* harmony export */ }); /* harmony import */ var pdfjs_lib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2603); var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([pdfjs_lib__WEBPACK_IMPORTED_MODULE_0__]); pdfjs_lib__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0]; class AltTextManager { #boundUpdateUIState = this.#updateUIState.bind(this); #boundSetPosition = this.#setPosition.bind(this); #boundOnClick = this.#onClick.bind(this); #currentEditor = null; #cancelButton; #dialog; #eventBus; #hasUsedPointer = false; #optionDescription; #optionDecorative; #overlayManager; #saveButton; #textarea; #uiManager; #previousAltText = null; #svgElement = null; #rectElement = null; #container; #telemetryData = null; constructor({ dialog, optionDescription, optionDecorative, textarea, cancelButton, saveButton }, container, overlayManager, eventBus) { this.#dialog = dialog; this.#optionDescription = optionDescription; this.#optionDecorative = optionDecorative; this.#textarea = textarea; this.#cancelButton = cancelButton; this.#saveButton = saveButton; this.#overlayManager = overlayManager; this.#eventBus = eventBus; this.#container = container; dialog.addEventListener("close", this.#close.bind(this)); dialog.addEventListener("contextmenu", event => { if (event.target !== this.#textarea) { event.preventDefault(); } }); cancelButton.addEventListener("click", this.#finish.bind(this)); saveButton.addEventListener("click", this.#save.bind(this)); optionDescription.addEventListener("change", this.#boundUpdateUIState); optionDecorative.addEventListener("change", this.#boundUpdateUIState); this.#overlayManager.register(dialog); } get _elements() { return (0,pdfjs_lib__WEBPACK_IMPORTED_MODULE_0__.shadow)(this, "_elements", [this.#optionDescription, this.#optionDecorative, this.#textarea, this.#saveButton, this.#cancelButton]); } #createSVGElement() { if (this.#svgElement) { return; } const svgFactory = new pdfjs_lib__WEBPACK_IMPORTED_MODULE_0__.DOMSVGFactory(); const svg = this.#svgElement = svgFactory.createElement("svg"); svg.setAttribute("width", "0"); svg.setAttribute("height", "0"); const defs = svgFactory.createElement("defs"); svg.append(defs); const mask = svgFactory.createElement("mask"); defs.append(mask); mask.setAttribute("id", "alttext-manager-mask"); mask.setAttribute("maskContentUnits", "objectBoundingBox"); let rect = svgFactory.createElement("rect"); mask.append(rect); rect.setAttribute("fill", "white"); rect.setAttribute("width", "1"); rect.setAttribute("height", "1"); rect.setAttribute("x", "0"); rect.setAttribute("y", "0"); rect = this.#rectElement = svgFactory.createElement("rect"); mask.append(rect); rect.setAttribute("fill", "black"); this.#dialog.append(svg); } async editAltText(uiManager, editor) { if (this.#currentEditor || !editor) { return; } this.#createSVGElement(); this.#hasUsedPointer = false; for (const element of this._elements) { element.addEventListener("click", this.#boundOnClick); } const { altText, decorative } = editor.altTextData; if (decorative === true) { this.#optionDecorative.checked = true; this.#optionDescription.checked = false; } else { this.#optionDecorative.checked = false; this.#optionDescription.checked = true; } this.#previousAltText = this.#textarea.value = altText?.trim() || ""; this.#updateUIState(); this.#currentEditor = editor; this.#uiManager = uiManager; this.#uiManager.removeEditListeners(); this.#eventBus._on("resize", this.#boundSetPosition); try { await this.#overlayManager.open(this.#dialog); this.#setPosition(); } catch (ex) { this.#close(); throw ex; } } #setPosition() { if (!this.#currentEditor) { return; } const dialog = this.#dialog; const { style } = dialog; const { x: containerX, y: containerY, width: containerW, height: containerH } = this.#container.getBoundingClientRect(); const { innerWidth: windowW, innerHeight: windowH } = window; const { width: dialogW, height: dialogH } = dialog.getBoundingClientRect(); const { x, y, width, height } = this.#currentEditor.getClientDimensions(); const MARGIN = 10; const isLTR = this.#uiManager.direction === "ltr"; const xs = Math.max(x, containerX); const xe = Math.min(x + width, containerX + containerW); const ys = Math.max(y, containerY); const ye = Math.min(y + height, containerY + containerH); this.#rectElement.setAttribute("width", `${(xe - xs) / windowW}`); this.#rectElement.setAttribute("height", `${(ye - ys) / windowH}`); this.#rectElement.setAttribute("x", `${xs / windowW}`); this.#rectElement.setAttribute("y", `${ys / windowH}`); let left = null; let top = Math.max(y, 0); top += Math.min(windowH - (top + dialogH), 0); if (isLTR) { if (x + width + MARGIN + dialogW < windowW) { left = x + width + MARGIN; } else if (x > dialogW + MARGIN) { left = x - dialogW - MARGIN; } } else if (x > dialogW + MARGIN) { left = x - dialogW - MARGIN; } else if (x + width + MARGIN + dialogW < windowW) { left = x + width + MARGIN; } if (left === null) { top = null; left = Math.max(x, 0); left += Math.min(windowW - (left + dialogW), 0); if (y > dialogH + MARGIN) { top = y - dialogH - MARGIN; } else if (y + height + MARGIN + dialogH < windowH) { top = y + height + MARGIN; } } if (top !== null) { dialog.classList.add("positioned"); if (isLTR) { style.left = `${left}px`; } else { style.right = `${windowW - left - dialogW}px`; } style.top = `${top}px`; } else { dialog.classList.remove("positioned"); style.left = ""; style.top = ""; } } #finish() { if (this.#overlayManager.active === this.#dialog) { this.#overlayManager.close(this.#dialog); } } #close() { this.#currentEditor._reportTelemetry(this.#telemetryData || { action: "alt_text_cancel", alt_text_keyboard: !this.#hasUsedPointer }); this.#telemetryData = null; this.#removeOnClickListeners(); this.#uiManager?.addEditListeners(); this.#eventBus._off("resize", this.#boundSetPosition); this.#currentEditor.altTextFinish(); this.#currentEditor = null; this.#uiManager = null; } #updateUIState() { this.#textarea.disabled = this.#optionDecorative.checked; } #save() { const altText = this.#textarea.value.trim(); const decorative = this.#optionDecora