repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/system-service.js
server/monitor-types/system-service.js
const { MonitorType } = require("./monitor-type"); const { execFile } = require("child_process"); const process = require("process"); const { UP } = require("../../src/util"); class SystemServiceMonitorType extends MonitorType { name = "system-service"; description = "Checks if a system service is running (systemd on Linux, Service Manager on Windows)."; /** * Check the system service status. * Detects OS and dispatches to the appropriate check method. * @param {object} monitor The monitor object containing monitor.system_service_name. * @param {object} heartbeat The heartbeat object to update. * @returns {Promise<void>} Resolves when check is complete. */ async check(monitor, heartbeat) { if (!monitor.system_service_name) { throw new Error("Service Name is required."); } if (process.platform === "win32") { return this.checkWindows(monitor.system_service_name, heartbeat); } else if (process.platform === "linux") { return this.checkLinux(monitor.system_service_name, heartbeat); } else { throw new Error(`System Service monitoring is not supported on ${process.platform}`); } } /** * Linux Check (Systemd) * @param {string} serviceName The name of the service to check. * @param {object} heartbeat The heartbeat object. * @returns {Promise<void>} */ async checkLinux(serviceName, heartbeat) { return new Promise((resolve, reject) => { // SECURITY: Prevent Argument Injection // Only allow alphanumeric, dots, dashes, underscores, and @ if (!serviceName || !/^[a-zA-Z0-9._\-@]+$/.test(serviceName)) { reject(new Error("Invalid service name. Please use the internal Service Name (no spaces).")); return; } execFile("systemctl", [ "is-active", serviceName ], { timeout: 5000 }, (error, stdout, stderr) => { // Combine output and truncate to ~200 chars to prevent DB bloat let output = (stderr || stdout || "").toString().trim(); if (output.length > 200) { output = output.substring(0, 200) + "..."; } if (error) { reject(new Error(output || `Service '${serviceName}' is not running.`)); return; } heartbeat.status = UP; heartbeat.msg = `Service '${serviceName}' is running.`; resolve(); }); }); } /** * Windows Check (PowerShell) * @param {string} serviceName The name of the service to check. * @param {object} heartbeat The heartbeat object. * @returns {Promise<void>} Resolves on success, rejects on error. */ async checkWindows(serviceName, heartbeat) { return new Promise((resolve, reject) => { // SECURITY: Validate service name to reduce command-injection risk if (!/^[A-Za-z0-9._-]+$/.test(serviceName)) { throw new Error( "Invalid service name. Only alphanumeric characters and '.', '_', '-' are allowed." ); } const cmd = "powershell"; const args = [ "-NoProfile", "-NonInteractive", "-Command", // Single quotes around the service name `(Get-Service -Name '${serviceName.replaceAll("'", "''")}').Status` ]; execFile(cmd, args, { timeout: 5000 }, (error, stdout, stderr) => { let output = (stderr || stdout || "").toString().trim(); if (output.length > 200) { output = output.substring(0, 200) + "..."; } if (error || stderr) { reject(new Error(`Service '${serviceName}' is not running/found.`)); return; } if (output === "Running") { heartbeat.status = UP; heartbeat.msg = `Service '${serviceName}' is running.`; resolve(); } else { reject(new Error(`Service '${serviceName}' is ${output}.`)); } }); }); } } module.exports = { SystemServiceMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/websocket-upgrade.js
server/monitor-types/websocket-upgrade.js
const { MonitorType } = require("./monitor-type"); const WebSocket = require("ws"); const { UP } = require("../../src/util"); const { checkStatusCode } = require("../util-server"); // Define closing error codes https://www.iana.org/assignments/websocket/websocket.xml#close-code-number const WS_ERR_CODE = { 1002: "Protocol error", 1003: "Unsupported Data", 1005: "No Status Received", 1006: "Abnormal Closure", 1007: "Invalid frame payload data", 1008: "Policy Violation", 1009: "Message Too Big", 1010: "Mandatory Extension Missing", 1011: "Internal Error", 1012: "Service Restart", 1013: "Try Again Later", 1014: "Bad Gateway", 1015: "TLS Handshake Failed", 3000: "Unauthorized", 3003: "Forbidden", 3008: "Timeout", }; class WebSocketMonitorType extends MonitorType { name = "websocket-upgrade"; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { const [ message, code ] = await this.attemptUpgrade(monitor); if (typeof code !== "undefined") { // If returned status code matches user controlled accepted status code(default 1000), return success if (checkStatusCode(code, JSON.parse(monitor.accepted_statuscodes_json))) { heartbeat.status = UP; heartbeat.msg = message; return; // success at this point } // Throw an error using friendly name if defined, fallback to generic msg throw new Error(WS_ERR_CODE[code] || `Unexpected status code: ${code}`); } // If no close code, then an error has occurred, display to user if (typeof message !== "undefined") { throw new Error(`${message}`); } // Throw generic error if nothing is defined, should never happen throw new Error("Unknown Websocket Error"); } /** * Uses the ws Node.js library to establish a connection to target server * @param {object} monitor The monitor object for input parameters. * @returns {[ string, int ]} Array containing a status message and response code */ async attemptUpgrade(monitor) { return new Promise((resolve) => { const timeoutMs = (monitor.timeout ?? 20) * 1000; // If user inputs subprotocol(s), convert to array, set Sec-WebSocket-Protocol header, timeout in ms. Subprotocol Identifier column: https://www.iana.org/assignments/websocket/websocket.xml#subprotocol-name const subprotocol = monitor.wsSubprotocol ? monitor.wsSubprotocol.replace(/\s/g, "").split(",") : undefined; const ws = new WebSocket(monitor.url, subprotocol, { handshakeTimeout: timeoutMs }); ws.addEventListener("open", (event) => { // Immediately close the connection ws.close(1000); }); ws.onerror = (error) => { // Give user the choice to ignore Sec-WebSocket-Accept header for non compliant servers // Header in HTTP 101 Switching Protocols response from server, technically already upgraded to WS if (monitor.wsIgnoreSecWebsocketAcceptHeader && error.message === "Invalid Sec-WebSocket-Accept header") { resolve([ "1000 - OK", 1000 ]); return; } // Upgrade failed, return message to user resolve([ error.message, error.code ]); }; ws.onclose = (event) => { // Return the close code, if connection didn't close cleanly, return the reason if present resolve([ event.wasClean ? event.code.toString() + " - OK" : event.reason, event.code ]); }; }); } } module.exports = { WebSocketMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/postgres.js
server/monitor-types/postgres.js
const { MonitorType } = require("./monitor-type"); const { log, UP } = require("../../src/util"); const dayjs = require("dayjs"); const postgresConParse = require("pg-connection-string").parse; const { Client } = require("pg"); class PostgresMonitorType extends MonitorType { name = "postgres"; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { let startTime = dayjs().valueOf(); let query = monitor.databaseQuery; // No query provided by user, use SELECT 1 if (!query || (typeof query === "string" && query.trim() === "")) { query = "SELECT 1"; } await this.postgresQuery(monitor.databaseConnectionString, query); heartbeat.msg = ""; heartbeat.status = UP; heartbeat.ping = dayjs().valueOf() - startTime; } /** * Run a query on Postgres * @param {string} connectionString The database connection string * @param {string} query The query to validate the database with * @returns {Promise<(string[] | object[] | object)>} Response from * server */ async postgresQuery(connectionString, query) { return new Promise((resolve, reject) => { const config = postgresConParse(connectionString); // Fix #3868, which true/false is not parsed to boolean if (typeof config.ssl === "string") { config.ssl = config.ssl === "true"; } if (config.password === "") { // See https://github.com/brianc/node-postgres/issues/1927 reject(new Error("Password is undefined.")); return; } const client = new Client(config); client.on("error", (error) => { log.debug("postgres", "Error caught in the error event handler."); reject(error); }); client.connect((err) => { if (err) { reject(err); client.end(); } else { // Connected here try { client.query(query, (err, res) => { if (err) { reject(err); } else { resolve(res); } client.end(); }); } catch (e) { reject(e); client.end(); } } }); }); } } module.exports = { PostgresMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/grpc.js
server/monitor-types/grpc.js
const { MonitorType } = require("./monitor-type"); const { UP, log } = require("../../src/util"); const dayjs = require("dayjs"); const grpc = require("@grpc/grpc-js"); const protojs = require("protobufjs"); class GrpcKeywordMonitorType extends MonitorType { name = "grpc-keyword"; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { const startTime = dayjs().valueOf(); const service = this.constructGrpcService(monitor.grpcUrl, monitor.grpcProtobuf, monitor.grpcServiceName, monitor.grpcEnableTls); let response = await this.grpcQuery(service, monitor.grpcMethod, monitor.grpcBody); heartbeat.ping = dayjs().valueOf() - startTime; log.debug(this.name, "gRPC response:", response); let keywordFound = response.toString().includes(monitor.keyword); if (keywordFound !== !monitor.isInvertKeyword()) { log.debug(this.name, `GRPC response [${response}] + ", but keyword [${monitor.keyword}] is ${keywordFound ? "present" : "not"} in [" + ${response} + "]"`); let truncatedResponse = (response.length > 50) ? response.toString().substring(0, 47) + "..." : response; throw new Error(`keyword [${monitor.keyword}] is ${keywordFound ? "present" : "not"} in [" + ${truncatedResponse} + "]`); } heartbeat.status = UP; heartbeat.msg = `${response}, keyword [${monitor.keyword}] ${keywordFound ? "is" : "not"} found`; } /** * Create gRPC client * @param {string} url grpc Url * @param {string} protobufData grpc ProtobufData * @param {string} serviceName grpc ServiceName * @param {string} enableTls grpc EnableTls * @returns {grpc.Service} grpc Service */ constructGrpcService(url, protobufData, serviceName, enableTls) { const protocObject = protojs.parse(protobufData); const protoServiceObject = protocObject.root.lookupService(serviceName); const Client = grpc.makeGenericClientConstructor({}); const credentials = enableTls ? grpc.credentials.createSsl() : grpc.credentials.createInsecure(); const client = new Client(url, credentials); return protoServiceObject.create((method, requestData, cb) => { const fullServiceName = method.fullName; const serviceFQDN = fullServiceName.split("."); const serviceMethod = serviceFQDN.pop(); const serviceMethodClientImpl = `/${serviceFQDN.slice(1).join(".")}/${serviceMethod}`; log.debug(this.name, `gRPC method ${serviceMethodClientImpl}`); client.makeUnaryRequest( serviceMethodClientImpl, arg => arg, arg => arg, requestData, cb); }, false, false); } /** * Create gRPC client stib * @param {grpc.Service} service grpc Url * @param {string} method grpc Method * @param {string} body grpc Body * @returns {Promise<string>} Result of gRPC query */ async grpcQuery(service, method, body) { return new Promise((resolve, reject) => { try { service[method](JSON.parse(body), (err, response) => { if (err) { if (err.code !== 1) { reject(err); } log.debug(this.name, `ignoring ${err.code} ${err.details}, as code=1 is considered OK`); resolve(`${err.code} is considered OK because ${err.details}`); } resolve(JSON.stringify(response)); }); } catch (err) { reject(err); } }); } } module.exports = { GrpcKeywordMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/mqtt.js
server/monitor-types/mqtt.js
const { MonitorType } = require("./monitor-type"); const { log, UP } = require("../../src/util"); const mqtt = require("mqtt"); const jsonata = require("jsonata"); class MqttMonitorType extends MonitorType { name = "mqtt"; /** * @inheritdoc */ async check(monitor, heartbeat, server) { const [ messageTopic, receivedMessage ] = await this.mqttAsync(monitor.hostname, monitor.mqttTopic, { port: monitor.port, username: monitor.mqttUsername, password: monitor.mqttPassword, interval: monitor.interval, websocketPath: monitor.mqttWebsocketPath, }); if (monitor.mqttCheckType == null || monitor.mqttCheckType === "") { // use old default monitor.mqttCheckType = "keyword"; } if (monitor.mqttCheckType === "keyword") { if (receivedMessage != null && receivedMessage.includes(monitor.mqttSuccessMessage)) { heartbeat.msg = `Topic: ${messageTopic}; Message: ${receivedMessage}`; heartbeat.status = UP; } else { throw Error(`Message Mismatch - Topic: ${monitor.mqttTopic}; Message: ${receivedMessage}`); } } else if (monitor.mqttCheckType === "json-query") { const parsedMessage = JSON.parse(receivedMessage); let expression = jsonata(monitor.jsonPath); let result = await expression.evaluate(parsedMessage); if (result?.toString() === monitor.expectedValue) { heartbeat.msg = "Message received, expected value is found"; heartbeat.status = UP; } else { throw new Error("Message received but value is not equal to expected value, value was: [" + result + "]"); } } else { throw Error("Unknown MQTT Check Type"); } } /** * Connect to MQTT Broker, subscribe to topic and receive message as String * @param {string} hostname Hostname / address of machine to test * @param {string} topic MQTT topic * @param {object} options MQTT options. Contains port, username, * password, websocketPath and interval (interval defaults to 20) * @returns {Promise<string>} Received MQTT message */ mqttAsync(hostname, topic, options = {}) { return new Promise((resolve, reject) => { const { port, username, password, websocketPath, interval = 20 } = options; // Adds MQTT protocol to the hostname if not already present if (!/^(?:http|mqtt|ws)s?:\/\//.test(hostname)) { hostname = "mqtt://" + hostname; } const timeoutID = setTimeout(() => { log.debug("mqtt", "MQTT timeout triggered"); client.end(); reject(new Error("Timeout, Message not received")); }, interval * 1000 * 0.8); // Construct the URL based on protocol let mqttUrl = `${hostname}:${port}`; if (hostname.startsWith("ws://") || hostname.startsWith("wss://")) { if (websocketPath && !websocketPath.startsWith("/")) { mqttUrl = `${hostname}:${port}/${websocketPath || ""}`; } else { mqttUrl = `${hostname}:${port}${websocketPath || ""}`; } } log.debug("mqtt", `MQTT connecting to ${mqttUrl}`); let client = mqtt.connect(mqttUrl, { username, password, clientId: "uptime-kuma_" + Math.random().toString(16).substr(2, 8) }); client.on("connect", () => { log.debug("mqtt", "MQTT connected"); try { client.subscribe(topic, () => { log.debug("mqtt", "MQTT subscribed to topic"); }); } catch (e) { client.end(); clearTimeout(timeoutID); reject(new Error("Cannot subscribe topic")); } }); client.on("error", (error) => { client.end(); clearTimeout(timeoutID); reject(error); }); client.on("message", (messageTopic, message) => { client.end(); clearTimeout(timeoutID); resolve([ messageTopic, message.toString("utf8") ]); }); }); } } module.exports = { MqttMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/real-browser-monitor-type.js
server/monitor-types/real-browser-monitor-type.js
const { MonitorType } = require("./monitor-type"); const { chromium } = require("playwright-core"); const { UP, log } = require("../../src/util"); const { Settings } = require("../settings"); const childProcess = require("child_process"); const path = require("path"); const Database = require("../database"); const jwt = require("jsonwebtoken"); const config = require("../config"); const { RemoteBrowser } = require("../remote-browser"); const { commandExists } = require("../util-server"); /** * Cached instance of a browser * @type {import ("playwright-core").Browser} */ let browser = null; let allowedList = []; let lastAutoDetectChromeExecutable = null; if (process.platform === "win32") { allowedList.push(process.env.LOCALAPPDATA + "\\Google\\Chrome\\Application\\chrome.exe"); allowedList.push(process.env.PROGRAMFILES + "\\Google\\Chrome\\Application\\chrome.exe"); allowedList.push(process.env["ProgramFiles(x86)"] + "\\Google\\Chrome\\Application\\chrome.exe"); // Allow Chromium too allowedList.push(process.env.LOCALAPPDATA + "\\Chromium\\Application\\chrome.exe"); allowedList.push(process.env.PROGRAMFILES + "\\Chromium\\Application\\chrome.exe"); allowedList.push(process.env["ProgramFiles(x86)"] + "\\Chromium\\Application\\chrome.exe"); // Allow MS Edge allowedList.push(process.env["ProgramFiles(x86)"] + "\\Microsoft\\Edge\\Application\\msedge.exe"); // For Loop A to Z for (let i = 65; i <= 90; i++) { let drive = String.fromCharCode(i); allowedList.push(drive + ":\\Program Files\\Google\\Chrome\\Application\\chrome.exe"); allowedList.push(drive + ":\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"); } } else if (process.platform === "linux") { allowedList = [ "chromium", "chromium-browser", "google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome", "/snap/bin/chromium", // Ubuntu ]; } else if (process.platform === "darwin") { allowedList = [ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", ]; } /** * Is the executable path allowed? * @param {string} executablePath Path to executable * @returns {Promise<boolean>} The executable is allowed? */ async function isAllowedChromeExecutable(executablePath) { console.log(config.args); if (config.args["allow-all-chrome-exec"] || process.env.UPTIME_KUMA_ALLOW_ALL_CHROME_EXEC === "1") { return true; } // Check if the executablePath is in the list of allowed executables return allowedList.includes(executablePath); } /** * Get the current instance of the browser. If there isn't one, create * it. * @returns {Promise<import ("playwright-core").Browser>} The browser */ async function getBrowser() { if (browser && browser.isConnected()) { return browser; } else { let executablePath = await Settings.get("chromeExecutable"); executablePath = await prepareChromeExecutable(executablePath); browser = await chromium.launch({ //headless: false, executablePath, }); return browser; } } /** * Get the current instance of the browser. If there isn't one, create it * @param {integer} remoteBrowserID Path to executable * @param {integer} userId User ID * @returns {Promise<Browser>} The browser */ async function getRemoteBrowser(remoteBrowserID, userId) { let remoteBrowser = await RemoteBrowser.get(remoteBrowserID, userId); log.debug("MONITOR", `Using remote browser: ${remoteBrowser.name} (${remoteBrowser.id})`); browser = await chromium.connect(remoteBrowser.url); return browser; } /** * Prepare the chrome executable path * @param {string} executablePath Path to chrome executable * @returns {Promise<string>} Executable path */ async function prepareChromeExecutable(executablePath) { // Special code for using the playwright_chromium if (typeof executablePath === "string" && executablePath.toLocaleLowerCase() === "#playwright_chromium") { // Set to undefined = use playwright_chromium executablePath = undefined; } else if (!executablePath) { if (process.env.UPTIME_KUMA_IS_CONTAINER) { executablePath = "/usr/bin/chromium"; // Install chromium in container via apt install if (! await commandExists(executablePath)) { await new Promise((resolve, reject) => { log.info("Chromium", "Installing Chromium..."); let child = childProcess.exec("apt update && apt --yes --no-install-recommends install chromium fonts-indic fonts-noto fonts-noto-cjk"); // On exit child.on("exit", (code) => { log.info("Chromium", "apt install chromium exited with code " + code); if (code === 0) { log.info("Chromium", "Installed Chromium"); let version = childProcess.execSync(executablePath + " --version").toString("utf8"); log.info("Chromium", "Chromium version: " + version); resolve(); } else if (code === 100) { reject(new Error("Installing Chromium, please wait...")); } else { reject(new Error("apt install chromium failed with code " + code)); } }); }); } } else { executablePath = await findChrome(allowedList); } } else { // User specified a path // Check if the executablePath is in the list of allowed if (!await isAllowedChromeExecutable(executablePath)) { throw new Error("This Chromium executable path is not allowed by default. If you are sure this is safe, please add an environment variable UPTIME_KUMA_ALLOW_ALL_CHROME_EXEC=1 to allow it."); } } return executablePath; } /** * Find the chrome executable * @param {string[]} executables Executables to search through * @returns {Promise<string>} Executable * @throws {Error} Could not find executable */ async function findChrome(executables) { // Use the last working executable, so we don't have to search for it again if (lastAutoDetectChromeExecutable) { if (await commandExists(lastAutoDetectChromeExecutable)) { return lastAutoDetectChromeExecutable; } } for (let executable of executables) { if (await commandExists(executable)) { lastAutoDetectChromeExecutable = executable; return executable; } } throw new Error("Chromium not found, please specify Chromium executable path in the settings page."); } /** * Reset chrome * @returns {Promise<void>} */ async function resetChrome() { if (browser) { await browser.close(); browser = null; } } /** * Test if the chrome executable is valid and return the version * @param {string} executablePath Path to executable * @returns {Promise<string>} Chrome version */ async function testChrome(executablePath) { try { executablePath = await prepareChromeExecutable(executablePath); log.info("Chromium", "Testing Chromium executable: " + executablePath); const browser = await chromium.launch({ executablePath, }); const version = browser.version(); await browser.close(); return version; } catch (e) { throw new Error(e.message); } } // test remote browser /** * @param {string} remoteBrowserURL Remote Browser URL * @returns {Promise<boolean>} Returns if connection worked */ async function testRemoteBrowser(remoteBrowserURL) { try { const browser = await chromium.connect(remoteBrowserURL); browser.version(); await browser.close(); return true; } catch (e) { throw new Error(e.message); } } class RealBrowserMonitorType extends MonitorType { name = "real-browser"; /** * @inheritdoc */ async check(monitor, heartbeat, server) { const browser = monitor.remote_browser ? await getRemoteBrowser(monitor.remote_browser, monitor.user_id) : await getBrowser(); const context = await browser.newContext(); const page = await context.newPage(); // Prevent Local File Inclusion // Accept only http:// and https:// // https://github.com/louislam/uptime-kuma/security/advisories/GHSA-2qgm-m29m-cj2h let url = new URL(monitor.url); if (url.protocol !== "http:" && url.protocol !== "https:") { throw new Error("Invalid url protocol, only http and https are allowed."); } const res = await page.goto(monitor.url, { waitUntil: "networkidle", timeout: monitor.interval * 1000 * 0.8, }); let filename = jwt.sign(monitor.id, server.jwtSecret) + ".png"; await page.screenshot({ path: path.join(Database.screenshotDir, filename), }); await context.close(); if (res.status() >= 200 && res.status() < 400) { heartbeat.status = UP; heartbeat.msg = res.status(); const timing = res.request().timing(); heartbeat.ping = timing.responseEnd; } else { throw new Error(res.status() + ""); } } } module.exports = { RealBrowserMonitorType, testChrome, resetChrome, testRemoteBrowser, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/group.js
server/monitor-types/group.js
const { UP, PENDING, DOWN } = require("../../src/util"); const { MonitorType } = require("./monitor-type"); const Monitor = require("../model/monitor"); class GroupMonitorType extends MonitorType { name = "group"; allowCustomStatus = true; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { const children = await Monitor.getChildren(monitor.id); if (children.length === 0) { // Set status pending if group is empty heartbeat.status = PENDING; heartbeat.msg = "Group empty"; return; } let worstStatus = UP; const downChildren = []; const pendingChildren = []; for (const child of children) { if (!child.active) { // Ignore inactive (=paused) children continue; } const label = child.name || `#${child.id}`; const lastBeat = await Monitor.getPreviousHeartbeat(child.id); if (!lastBeat) { if (worstStatus === UP) { worstStatus = PENDING; } pendingChildren.push(label); continue; } if (lastBeat.status === DOWN) { worstStatus = DOWN; downChildren.push(label); } else if (lastBeat.status === PENDING) { if (worstStatus !== DOWN) { worstStatus = PENDING; } pendingChildren.push(label); } } if (worstStatus === UP) { heartbeat.status = UP; heartbeat.msg = "All children up and running"; return; } if (worstStatus === PENDING) { heartbeat.status = PENDING; heartbeat.msg = `Pending child monitors: ${pendingChildren.join(", ")}`; return; } heartbeat.status = DOWN; let message = `Child monitors down: ${downChildren.join(", ")}`; if (pendingChildren.length > 0) { message += `; pending: ${pendingChildren.join(", ")}`; } // Throw to leverage the generic retry handling and notification flow throw new Error(message); } } module.exports = { GroupMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/tailscale-ping.js
server/monitor-types/tailscale-ping.js
const { MonitorType } = require("./monitor-type"); const { UP } = require("../../src/util"); const childProcessAsync = require("promisify-child-process"); class TailscalePing extends MonitorType { name = "tailscale-ping"; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { try { let tailscaleOutput = await this.runTailscalePing(monitor.hostname, monitor.interval); this.parseTailscaleOutput(tailscaleOutput, heartbeat); } catch (err) { // trigger log function somewhere to display a notification or alert to the user (but how?) throw new Error(`Error checking Tailscale ping: ${err}`); } } /** * Runs the Tailscale ping command to the given URL. * @param {string} hostname The hostname to ping. * @param {number} interval Interval to send ping * @returns {Promise<string>} A Promise that resolves to the output of the Tailscale ping command * @throws Will throw an error if the command execution encounters any error. */ async runTailscalePing(hostname, interval) { let timeout = interval * 1000 * 0.8; let res = await childProcessAsync.spawn("tailscale", [ "ping", "--c", "1", hostname ], { timeout: timeout, encoding: "utf8", }); if (res.stderr && res.stderr.toString() && res.code !== 0) { throw new Error(`Error in output: ${res.stderr.toString()}`); } if (res.stdout && res.stdout.toString()) { return res.stdout.toString(); } else { throw new Error("No output from Tailscale ping"); } } /** * Parses the output of the Tailscale ping command to update the heartbeat. * @param {string} tailscaleOutput The output of the Tailscale ping command. * @param {object} heartbeat The heartbeat object to update. * @returns {void} * @throws Will throw an eror if the output contains any unexpected string. */ parseTailscaleOutput(tailscaleOutput, heartbeat) { let lines = tailscaleOutput.split("\n"); for (let line of lines) { if (line.includes("pong from")) { heartbeat.status = UP; let time = line.split(" in ")[1].split(" ")[0]; heartbeat.ping = parseInt(time); heartbeat.msg = "OK"; break; } else if (line.includes("timed out")) { throw new Error(`Ping timed out: "${line}"`); // Immediately throws upon "timed out" message, the server is expected to re-call the check function } else if (line.includes("no matching peer")) { throw new Error(`Nonexistant or inaccessible due to ACLs: "${line}"`); } else if (line.includes("is local Tailscale IP")) { throw new Error(`Tailscale only works if used on other machines: "${line}"`); } else if (line !== "") { throw new Error(`Unexpected output: "${line}"`); } } } } module.exports = { TailscalePing, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/dns.js
server/monitor-types/dns.js
const { MonitorType } = require("./monitor-type"); const { UP } = require("../../src/util"); const dayjs = require("dayjs"); const { dnsResolve } = require("../util-server"); const { R } = require("redbean-node"); const { ConditionVariable } = require("../monitor-conditions/variables"); const { defaultStringOperators } = require("../monitor-conditions/operators"); const { ConditionExpressionGroup } = require("../monitor-conditions/expression"); const { evaluateExpressionGroup } = require("../monitor-conditions/evaluator"); class DnsMonitorType extends MonitorType { name = "dns"; supportsConditions = true; conditionVariables = [ new ConditionVariable("record", defaultStringOperators ), ]; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { let startTime = dayjs().valueOf(); let dnsMessage = ""; let dnsRes = await dnsResolve(monitor.hostname, monitor.dns_resolve_server, monitor.port, monitor.dns_resolve_type); heartbeat.ping = dayjs().valueOf() - startTime; const conditions = ConditionExpressionGroup.fromMonitor(monitor); let conditionsResult = true; const handleConditions = (data) => conditions ? evaluateExpressionGroup(conditions, data) : true; switch (monitor.dns_resolve_type) { case "A": case "AAAA": case "PTR": dnsMessage = `Records: ${dnsRes.join(" | ")}`; conditionsResult = dnsRes.some(record => handleConditions({ record })); break; case "TXT": dnsMessage = `Records: ${dnsRes.join(" | ")}`; conditionsResult = dnsRes.flat().some(record => handleConditions({ record })); break; case "CNAME": dnsMessage = dnsRes[0]; conditionsResult = handleConditions({ record: dnsRes[0] }); break; case "CAA": // .filter(Boolean) was added because some CAA records do not contain an issue key, resulting in a blank list item. // Hypothetical dnsRes [{ critical: 0, issuewild: 'letsencrypt.org' }, { critical: 0, issue: 'letsencrypt.org' }] dnsMessage = `Records: ${dnsRes.map(record => record.issue).filter(Boolean).join(" | ")}`; conditionsResult = dnsRes.some(record => handleConditions({ record: record.issue })); break; case "MX": dnsMessage = dnsRes.map(record => `Hostname: ${record.exchange} - Priority: ${record.priority}`).join(" | "); conditionsResult = dnsRes.some(record => handleConditions({ record: record.exchange })); break; case "NS": dnsMessage = `Servers: ${dnsRes.join(" | ")}`; conditionsResult = dnsRes.some(record => handleConditions({ record })); break; case "SOA": dnsMessage = `NS-Name: ${dnsRes.nsname} | Hostmaster: ${dnsRes.hostmaster} | Serial: ${dnsRes.serial} | Refresh: ${dnsRes.refresh} | Retry: ${dnsRes.retry} | Expire: ${dnsRes.expire} | MinTTL: ${dnsRes.minttl}`; conditionsResult = handleConditions({ record: dnsRes.nsname }); break; case "SRV": dnsMessage = dnsRes.map(record => `Name: ${record.name} | Port: ${record.port} | Priority: ${record.priority} | Weight: ${record.weight}`).join(" | "); conditionsResult = dnsRes.some(record => handleConditions({ record: record.name })); break; } if (monitor.dns_last_result !== dnsMessage && dnsMessage !== undefined) { await R.exec("UPDATE `monitor` SET dns_last_result = ? WHERE id = ? ", [ dnsMessage, monitor.id ]); } if (!conditionsResult) { throw new Error(dnsMessage); } heartbeat.msg = dnsMessage; heartbeat.status = UP; } } module.exports = { DnsMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/mssql.js
server/monitor-types/mssql.js
const { MonitorType } = require("./monitor-type"); const { log, UP } = require("../../src/util"); const dayjs = require("dayjs"); const mssql = require("mssql"); const { ConditionVariable } = require("../monitor-conditions/variables"); const { defaultStringOperators } = require("../monitor-conditions/operators"); const { ConditionExpressionGroup, } = require("../monitor-conditions/expression"); const { evaluateExpressionGroup } = require("../monitor-conditions/evaluator"); class MssqlMonitorType extends MonitorType { name = "sqlserver"; supportsConditions = true; conditionVariables = [ new ConditionVariable("result", defaultStringOperators), ]; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { let startTime = dayjs().valueOf(); let query = monitor.databaseQuery; // No query provided by user, use SELECT 1 if (!query || (typeof query === "string" && query.trim() === "")) { query = "SELECT 1"; } let result; try { result = await this.mssqlQuery( monitor.databaseConnectionString, query ); } catch (error) { log.error("sqlserver", "Database query failed:", error.message); throw new Error( `Database connection/query failed: ${error.message}` ); } finally { heartbeat.ping = dayjs().valueOf() - startTime; } const conditions = ConditionExpressionGroup.fromMonitor(monitor); const handleConditions = (data) => conditions ? evaluateExpressionGroup(conditions, data) : true; // Since result is now a single value, pass it directly to conditions const conditionsResult = handleConditions({ result: String(result) }); if (!conditionsResult) { throw new Error( `Query result did not meet the specified conditions (${result})` ); } heartbeat.msg = ""; heartbeat.status = UP; } /** * Run a query on MSSQL server * @param {string} connectionString The database connection string * @param {string} query The query to validate the database with * @returns {Promise<any>} Single value from the first column of the first row */ async mssqlQuery(connectionString, query) { let pool; try { pool = new mssql.ConnectionPool(connectionString); await pool.connect(); const result = await pool.request().query(query); // Check if we have results if (!result.recordset || result.recordset.length === 0) { throw new Error("Query returned no results"); } // Check if we have multiple rows if (result.recordset.length > 1) { throw new Error( "Multiple values were found, expected only one value" ); } const firstRow = result.recordset[0]; const columnNames = Object.keys(firstRow); // Check if we have multiple columns if (columnNames.length > 1) { throw new Error( "Multiple columns were found, expected only one value" ); } // Return the single value from the first (and only) column return firstRow[columnNames[0]]; } catch (err) { log.debug( "sqlserver", "Error caught in the query execution.", err.message ); throw err; } finally { if (pool) { await pool.close(); } } } } module.exports = { MssqlMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/mongodb.js
server/monitor-types/mongodb.js
const { MonitorType } = require("./monitor-type"); const { UP } = require("../../src/util"); const { MongoClient } = require("mongodb"); const jsonata = require("jsonata"); class MongodbMonitorType extends MonitorType { name = "mongodb"; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { let command = { "ping": 1 }; if (monitor.databaseQuery) { command = JSON.parse(monitor.databaseQuery); } let result = await this.runMongodbCommand(monitor.databaseConnectionString, command); if (result["ok"] !== 1) { throw new Error("MongoDB command failed"); } else { heartbeat.msg = "Command executed successfully"; } if (monitor.jsonPath) { let expression = jsonata(monitor.jsonPath); result = await expression.evaluate(result); if (result) { heartbeat.msg = "Command executed successfully and the jsonata expression produces a result."; } else { throw new Error("Queried value not found."); } } if (monitor.expectedValue) { if (result.toString() === monitor.expectedValue) { heartbeat.msg = "Command executed successfully and expected value was found"; } else { throw new Error("Query executed, but value is not equal to expected value, value was: [" + JSON.stringify(result) + "]"); } } heartbeat.status = UP; } /** * Connect to and run MongoDB command on a MongoDB database * @param {string} connectionString The database connection string * @param {object} command MongoDB command to run on the database * @returns {Promise<(string[] | object[] | object)>} Response from server */ async runMongodbCommand(connectionString, command) { let client = await MongoClient.connect(connectionString); let result = await client.db().command(command); await client.close(); return result; } } module.exports = { MongodbMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/gamedig.js
server/monitor-types/gamedig.js
const { MonitorType } = require("./monitor-type"); const { UP } = require("../../src/util"); const { GameDig } = require("gamedig"); const dns = require("dns").promises; const net = require("net"); class GameDigMonitorType extends MonitorType { name = "gamedig"; /** * @inheritdoc */ async check(monitor, heartbeat, server) { let host = monitor.hostname; if (net.isIP(host) === 0) { host = await this.resolveHostname(host); } try { const state = await GameDig.query({ type: monitor.game, host: host, port: monitor.port, givenPortOnly: Boolean(monitor.gamedigGivenPortOnly), }); heartbeat.msg = state.name; heartbeat.status = UP; heartbeat.ping = state.ping; } catch (e) { throw new Error(e.message); } } /** * Resolves a domain name to its IPv4 address. * @param {string} hostname - The domain name to resolve (e.g., "example.dyndns.org"). * @returns {Promise<string>} - The resolved IP address. * @throws Will throw an error if the DNS resolution fails. */ async resolveHostname(hostname) { try { const result = await dns.lookup(hostname); return result.address; } catch (err) { throw new Error(`DNS resolution failed for ${hostname}: ${err.message}`); } } } module.exports = { GameDigMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/rabbitmq.js
server/monitor-types/rabbitmq.js
const { MonitorType } = require("./monitor-type"); const { log, UP } = require("../../src/util"); const { axiosAbortSignal } = require("../util-server"); const axios = require("axios"); class RabbitMqMonitorType extends MonitorType { name = "rabbitmq"; /** * @inheritdoc */ async check(monitor, heartbeat, server) { let baseUrls = []; try { baseUrls = JSON.parse(monitor.rabbitmqNodes); } catch (error) { throw new Error("Invalid RabbitMQ Nodes"); } for (let baseUrl of baseUrls) { try { // Without a trailing slash, path in baseUrl will be removed. https://example.com/api -> https://example.com if ( !baseUrl.endsWith("/") ) { baseUrl += "/"; } const options = { // Do not start with slash, it will strip the trailing slash from baseUrl url: new URL("api/health/checks/alarms/", baseUrl).href, method: "get", timeout: monitor.timeout * 1000, headers: { "Accept": "application/json", "Authorization": "Basic " + Buffer.from(`${monitor.rabbitmqUsername || ""}:${monitor.rabbitmqPassword || ""}`).toString("base64"), }, signal: axiosAbortSignal((monitor.timeout + 10) * 1000), // Capture reason for 503 status validateStatus: (status) => status === 200 || status === 503, }; log.debug("monitor", `[${monitor.name}] Axios Request: ${JSON.stringify(options)}`); const res = await axios.request(options); log.debug("monitor", `[${monitor.name}] Axios Response: status=${res.status} body=${JSON.stringify(res.data)}`); if (res.status === 200) { heartbeat.status = UP; heartbeat.msg = "OK"; break; } else if (res.status === 503) { throw new Error(res.data.reason); } else { throw new Error(`${res.status} - ${res.statusText}`); } } catch (error) { if (axios.isCancel(error)) { log.debug("monitor", `[${monitor.name}] Request timed out`); throw new Error("Request timed out"); } else { log.debug("monitor", `[${monitor.name}] Axios Error: ${JSON.stringify(error.message)}`); throw new Error(error.message); } } } } } module.exports = { RabbitMqMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/manual.js
server/monitor-types/manual.js
const { MonitorType } = require("./monitor-type"); const { UP, DOWN, PENDING } = require("../../src/util"); class ManualMonitorType extends MonitorType { name = "Manual"; type = "manual"; description = "A monitor that allows manual control of the status"; supportsConditions = false; conditionVariables = []; allowCustomStatus = true; /** * @inheritdoc */ async check(monitor, heartbeat) { if (monitor.manual_status !== null) { heartbeat.status = monitor.manual_status; switch (monitor.manual_status) { case UP: heartbeat.msg = "Up"; break; case DOWN: heartbeat.msg = "Down"; break; default: heartbeat.msg = "Pending"; } } else { heartbeat.status = PENDING; heartbeat.msg = "Manual monitoring - No status set"; } } } module.exports = { ManualMonitorType };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/snmp.js
server/monitor-types/snmp.js
const { MonitorType } = require("./monitor-type"); const { UP, log, evaluateJsonQuery } = require("../../src/util"); const snmp = require("net-snmp"); class SNMPMonitorType extends MonitorType { name = "snmp"; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { let session; try { const sessionOptions = { port: monitor.port || "161", retries: monitor.maxretries, timeout: monitor.timeout * 1000, version: snmp.Version[monitor.snmpVersion], }; session = snmp.createSession(monitor.hostname, monitor.radiusPassword, sessionOptions); // Handle errors during session creation session.on("error", (error) => { throw new Error(`Error creating SNMP session: ${error.message}`); }); const varbinds = await new Promise((resolve, reject) => { session.get([ monitor.snmpOid ], (error, varbinds) => { error ? reject(error) : resolve(varbinds); }); }); log.debug("monitor", `SNMP: Received varbinds (Type: ${snmp.ObjectType[varbinds[0].type]} Value: ${varbinds[0].value})`); if (varbinds.length === 0) { throw new Error(`No varbinds returned from SNMP session (OID: ${monitor.snmpOid})`); } if (varbinds[0].type === snmp.ObjectType.NoSuchInstance) { throw new Error(`The SNMP query returned that no instance exists for OID ${monitor.snmpOid}`); } // We restrict querying to one OID per monitor, therefore `varbinds[0]` will always contain the value we're interested in. const value = varbinds[0].value; const { status, response } = await evaluateJsonQuery(value, monitor.jsonPath, monitor.jsonPathOperator, monitor.expectedValue); if (status) { heartbeat.status = UP; heartbeat.msg = `JSON query passes (comparing ${response} ${monitor.jsonPathOperator} ${monitor.expectedValue})`; } else { throw new Error(`JSON query does not pass (comparing ${response} ${monitor.jsonPathOperator} ${monitor.expectedValue})`); } } finally { if (session) { session.close(); } } } } module.exports = { SNMPMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/smtp.js
server/monitor-types/smtp.js
const { MonitorType } = require("./monitor-type"); const { UP } = require("../../src/util"); const nodemailer = require("nodemailer"); class SMTPMonitorType extends MonitorType { name = "smtp"; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { let options = { port: monitor.port || 25, host: monitor.hostname, secure: monitor.smtpSecurity === "secure", // use SMTPS (not STARTTLS) ignoreTLS: monitor.smtpSecurity === "nostarttls", // don't use STARTTLS even if it's available requireTLS: monitor.smtpSecurity === "starttls", // use STARTTLS or fail }; let transporter = nodemailer.createTransport(options); try { await transporter.verify(); heartbeat.status = UP; heartbeat.msg = "SMTP connection verifies successfully"; } catch (e) { throw new Error(`SMTP connection doesn't verify: ${e}`); } finally { transporter.close(); } } } module.exports = { SMTPMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/monitor-types/tcp.js
server/monitor-types/tcp.js
const { MonitorType } = require("./monitor-type"); const { UP, PING_GLOBAL_TIMEOUT_DEFAULT: TIMEOUT, log } = require("../../src/util"); const { checkCertificate } = require("../util-server"); const tls = require("tls"); const net = require("net"); const tcpp = require("tcp-ping"); /** * Send TCP request to specified hostname and port * @param {string} hostname Hostname / address of machine * @param {number} port TCP port to test * @returns {Promise<number>} Maximum time in ms rounded to nearest integer */ const tcping = (hostname, port) => { return new Promise((resolve, reject) => { tcpp.ping( { address: hostname, port: port, attempts: 1, }, (err, data) => { if (err) { reject(err); } if (data.results.length >= 1 && data.results[0].err) { reject(data.results[0].err); } resolve(Math.round(data.max)); } ); }); }; class TCPMonitorType extends MonitorType { name = "port"; /** * @inheritdoc */ async check(monitor, heartbeat, _server) { try { const resp = await tcping(monitor.hostname, monitor.port); heartbeat.ping = resp; heartbeat.msg = `${resp} ms`; heartbeat.status = UP; } catch { throw new Error("Connection failed"); } let socket_; const preTLS = () => new Promise((resolve, reject) => { let dialogTimeout; let bannerTimeout; socket_ = net.connect(monitor.port, monitor.hostname); const onTimeout = () => { log.debug(this.name, `[${monitor.name}] Pre-TLS connection timed out`); doReject("Connection timed out"); }; const onBannerTimeout = () => { log.debug(this.name, `[${monitor.name}] Pre-TLS timed out waiting for banner`); // No banner. Could be a XMPP server? socket_.write(`<stream:stream to='${monitor.hostname}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>`); }; const doResolve = () => { dialogTimeout && clearTimeout(dialogTimeout); bannerTimeout && clearTimeout(bannerTimeout); resolve({ socket: socket_ }); }; const doReject = (error) => { dialogTimeout && clearTimeout(dialogTimeout); bannerTimeout && clearTimeout(bannerTimeout); socket_.end(); reject(error); }; socket_.on("connect", () => { log.debug(this.name, `[${monitor.name}] Pre-TLS connection: ${JSON.stringify(socket_)}`); }); socket_.on("data", data => { const response = data.toString(); const response_ = response.toLowerCase(); log.debug(this.name, `[${monitor.name}] Pre-TLS response: ${response}`); clearTimeout(bannerTimeout); switch (true) { case response_.includes("start tls") || response_.includes("begin tls"): doResolve(); break; case response.startsWith("* OK") || response.match(/CAPABILITY.+STARTTLS/): socket_.write("a001 STARTTLS\r\n"); break; case response.startsWith("220") || response.includes("ESMTP"): socket_.write(`EHLO ${monitor.hostname}\r\n`); break; case response.includes("250-STARTTLS"): socket_.write("STARTTLS\r\n"); break; case response_.includes("<proceed"): doResolve(); break; case response_.includes("<starttls"): socket_.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>"); break; case response_.includes("<stream:stream") || response_.includes("</stream:stream>"): break; default: doReject(`Unexpected response: ${response}`); } }); socket_.on("error", error => { log.debug(this.name, `[${monitor.name}] ${error.toString()}`); reject(error); }); socket_.setTimeout(1000 * TIMEOUT, onTimeout); dialogTimeout = setTimeout(onTimeout, 1000 * TIMEOUT); bannerTimeout = setTimeout(onBannerTimeout, 1000 * 1.5); }); const reuseSocket = monitor.smtpSecurity === "starttls" ? await preTLS() : {}; if ([ "secure", "starttls" ].includes(monitor.smtpSecurity) && monitor.isEnabledExpiryNotification()) { let socket = null; try { const options = { host: monitor.hostname, port: monitor.port, servername: monitor.hostname, ...reuseSocket, }; const tlsInfoObject = await new Promise((resolve, reject) => { socket = tls.connect(options); socket.on("secureConnect", () => { try { const info = checkCertificate(socket); resolve(info); } catch (error) { reject(error); } }); socket.on("error", error => { reject(error); }); socket.setTimeout(1000 * TIMEOUT, () => { reject(new Error("Connection timed out")); }); }); await monitor.handleTlsInfo(tlsInfoObject); if (!tlsInfoObject.valid) { throw new Error("Certificate is invalid"); } } catch (error) { const message = error instanceof Error ? error.message : "Unknown error"; throw new Error(`TLS Connection failed: ${message}`); } finally { if (socket && !socket.destroyed) { socket.end(); } } } if (socket_ && !socket_.destroyed) { socket_.end(); } } } module.exports = { TCPMonitorType, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/analytics/google-analytics.js
server/analytics/google-analytics.js
const jsesc = require("jsesc"); const { escape } = require("html-escaper"); /** * Returns a string that represents the javascript that is required to insert the Google Analytics scripts * into a webpage. * @param {string} tagId Google UA/G/AW/DC Property ID to use with the Google Analytics script. * @returns {string} HTML script tags to inject into page */ function getGoogleAnalyticsScript(tagId) { let escapedTagIdJS = jsesc(tagId, { isScriptContext: true }); if (escapedTagIdJS) { escapedTagIdJS = escapedTagIdJS.trim(); } // Escape the tag ID for use in an HTML attribute. let escapedTagIdHTMLAttribute = escape(tagId); return ` <script async src="https://www.googletagmanager.com/gtag/js?id=${escapedTagIdHTMLAttribute}"></script> <script>window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date());gtag('config', '${escapedTagIdJS}'); </script> `; } module.exports = { getGoogleAnalyticsScript, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/analytics/matomo-analytics.js
server/analytics/matomo-analytics.js
const jsesc = require("jsesc"); const { escape } = require("html-escaper"); /** * Returns a string that represents the javascript that is required to insert the Matomo Analytics script * into a webpage. * @param {string} matomoUrl Domain name with tld to use with the Matomo Analytics script. * @param {string} siteId Site ID to use with the Matomo Analytics script. * @returns {string} HTML script tags to inject into page */ function getMatomoAnalyticsScript(matomoUrl, siteId) { let escapedMatomoUrlJS = jsesc(matomoUrl, { isScriptContext: true }); let escapedSiteIdJS = jsesc(siteId, { isScriptContext: true }); if (escapedMatomoUrlJS) { escapedMatomoUrlJS = escapedMatomoUrlJS.trim(); } if (escapedSiteIdJS) { escapedSiteIdJS = escapedSiteIdJS.trim(); } // Escape the domain url for use in an HTML attribute. let escapedMatomoUrlHTMLAttribute = escape(escapedMatomoUrlJS); // Escape the website id for use in an HTML attribute. let escapedSiteIdHTMLAttribute = escape(escapedSiteIdJS); return ` <script type="text/javascript"> var _paq = window._paq = window._paq || []; _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="//${escapedMatomoUrlHTMLAttribute}/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', ${escapedSiteIdHTMLAttribute}]); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); })(); </script> `; } module.exports = { getMatomoAnalyticsScript, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/analytics/analytics.js
server/analytics/analytics.js
const googleAnalytics = require("./google-analytics"); const umamiAnalytics = require("./umami-analytics"); const plausibleAnalytics = require("./plausible-analytics"); const matomoAnalytics = require("./matomo-analytics"); /** * Returns a string that represents the javascript that is required to insert the selected Analytics' script * into a webpage. * @param {typeof import("../model/status_page").StatusPage} statusPage Status page populate HTML with * @returns {string} HTML script tags to inject into page */ function getAnalyticsScript(statusPage) { switch (statusPage.analyticsType) { case "google": return googleAnalytics.getGoogleAnalyticsScript(statusPage.analyticsId); case "umami": return umamiAnalytics.getUmamiAnalyticsScript(statusPage.analyticsScriptUrl, statusPage.analyticsId); case "plausible": return plausibleAnalytics.getPlausibleAnalyticsScript(statusPage.analyticsScriptUrl, statusPage.analyticsId); case "matomo": return matomoAnalytics.getMatomoAnalyticsScript(statusPage.analyticsScriptUrl, statusPage.analyticsId); default: return null; } } /** * Function that checks wether the selected analytics has been configured properly * @param {typeof import("../model/status_page").StatusPage} statusPage Status page populate HTML with * @returns {boolean} Boolean defining if the analytics config is valid */ function isValidAnalyticsConfig(statusPage) { switch (statusPage.analyticsType) { case "google": return statusPage.analyticsId != null; case "umami": case "plausible": case "matomo": return statusPage.analyticsId != null && statusPage.analyticsScriptUrl != null; default: return false; } } module.exports = { getAnalyticsScript, isValidAnalyticsConfig };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/analytics/plausible-analytics.js
server/analytics/plausible-analytics.js
const jsesc = require("jsesc"); const { escape } = require("html-escaper"); /** * Returns a string that represents the javascript that is required to insert the Plausible Analytics script * into a webpage. * @param {string} scriptUrl the Plausible Analytics script url. * @param {string} domainsToMonitor Domains to track seperated by a ',' to add Plausible Analytics script. * @returns {string} HTML script tags to inject into page */ function getPlausibleAnalyticsScript(scriptUrl, domainsToMonitor) { let escapedScriptUrlJS = jsesc(scriptUrl, { isScriptContext: true }); let escapedWebsiteIdJS = jsesc(domainsToMonitor, { isScriptContext: true }); if (escapedScriptUrlJS) { escapedScriptUrlJS = escapedScriptUrlJS.trim(); } if (escapedWebsiteIdJS) { escapedWebsiteIdJS = escapedWebsiteIdJS.trim(); } // Escape the domain url for use in an HTML attribute. let escapedScriptUrlHTMLAttribute = escape(escapedScriptUrlJS); // Escape the website id for use in an HTML attribute. let escapedWebsiteIdHTMLAttribute = escape(escapedWebsiteIdJS); return ` <script defer src="${escapedScriptUrlHTMLAttribute}" data-domain="${escapedWebsiteIdHTMLAttribute}"></script> `; } module.exports = { getPlausibleAnalyticsScript };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/analytics/umami-analytics.js
server/analytics/umami-analytics.js
const jsesc = require("jsesc"); const { escape } = require("html-escaper"); /** * Returns a string that represents the javascript that is required to insert the Umami Analytics script * into a webpage. * @param {string} scriptUrl the Umami Analytics script url. * @param {string} websiteId Website ID to use with the Umami Analytics script. * @returns {string} HTML script tags to inject into page */ function getUmamiAnalyticsScript(scriptUrl, websiteId) { let escapedScriptUrlJS = jsesc(scriptUrl, { isScriptContext: true }); let escapedWebsiteIdJS = jsesc(websiteId, { isScriptContext: true }); if (escapedScriptUrlJS) { escapedScriptUrlJS = escapedScriptUrlJS.trim(); } if (escapedWebsiteIdJS) { escapedWebsiteIdJS = escapedWebsiteIdJS.trim(); } // Escape the Script url for use in an HTML attribute. let escapedScriptUrlHTMLAttribute = escape(escapedScriptUrlJS); // Escape the website id for use in an HTML attribute. let escapedWebsiteIdHTMLAttribute = escape(escapedWebsiteIdJS); return ` <script defer src="${escapedScriptUrlHTMLAttribute}" data-website-id="${escapedWebsiteIdHTMLAttribute}"></script> `; } module.exports = { getUmamiAnalyticsScript, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/routers/status-page-router.js
server/routers/status-page-router.js
let express = require("express"); const apicache = require("../modules/apicache"); const { UptimeKumaServer } = require("../uptime-kuma-server"); const StatusPage = require("../model/status_page"); const { allowDevAllOrigin, sendHttpError } = require("../util-server"); const { R } = require("redbean-node"); const { badgeConstants } = require("../../src/util"); const { makeBadge } = require("badge-maker"); const { UptimeCalculator } = require("../uptime-calculator"); let router = express.Router(); let cache = apicache.middleware; const server = UptimeKumaServer.getInstance(); router.get("/status/:slug", cache("5 minutes"), async (request, response) => { let slug = request.params.slug; slug = slug.toLowerCase(); await StatusPage.handleStatusPageResponse(response, server.indexHTML, slug); }); router.get("/status/:slug/rss", cache("5 minutes"), async (request, response) => { let slug = request.params.slug; slug = slug.toLowerCase(); await StatusPage.handleStatusPageRSSResponse(response, slug); }); router.get("/status", cache("5 minutes"), async (request, response) => { let slug = "default"; await StatusPage.handleStatusPageResponse(response, server.indexHTML, slug); }); router.get("/status-page", cache("5 minutes"), async (request, response) => { let slug = "default"; await StatusPage.handleStatusPageResponse(response, server.indexHTML, slug); }); // Status page config, incident, monitor list router.get("/api/status-page/:slug", cache("5 minutes"), async (request, response) => { allowDevAllOrigin(response); let slug = request.params.slug; slug = slug.toLowerCase(); try { // Get Status Page let statusPage = await R.findOne("status_page", " slug = ? ", [ slug ]); if (!statusPage) { sendHttpError(response, "Status Page Not Found"); return null; } let statusPageData = await StatusPage.getStatusPageData(statusPage); // Response response.json(statusPageData); } catch (error) { sendHttpError(response, error.message); } }); // Status Page Polling Data // Can fetch only if published router.get("/api/status-page/heartbeat/:slug", cache("1 minutes"), async (request, response) => { allowDevAllOrigin(response); try { let heartbeatList = {}; let uptimeList = {}; let slug = request.params.slug; slug = slug.toLowerCase(); let statusPageID = await StatusPage.slugToID(slug); let monitorIDList = await R.getCol(` SELECT monitor_group.monitor_id FROM monitor_group, \`group\` WHERE monitor_group.group_id = \`group\`.id AND public = 1 AND \`group\`.status_page_id = ? `, [ statusPageID ]); for (let monitorID of monitorIDList) { let list = await R.getAll(` SELECT * FROM heartbeat WHERE monitor_id = ? ORDER BY time DESC LIMIT 100 `, [ monitorID, ]); list = R.convertToBeans("heartbeat", list); heartbeatList[monitorID] = list.reverse().map(row => row.toPublicJSON()); const uptimeCalculator = await UptimeCalculator.getUptimeCalculator(monitorID); uptimeList[`${monitorID}_24`] = uptimeCalculator.get24Hour().uptime; } response.json({ heartbeatList, uptimeList }); } catch (error) { sendHttpError(response, error.message); } }); // Status page's manifest.json router.get("/api/status-page/:slug/manifest.json", cache("1440 minutes"), async (request, response) => { allowDevAllOrigin(response); let slug = request.params.slug; slug = slug.toLowerCase(); try { // Get Status Page let statusPage = await R.findOne("status_page", " slug = ? ", [ slug ]); if (!statusPage) { sendHttpError(response, "Not Found"); return; } // Response response.json({ "name": statusPage.title, "start_url": "/status/" + statusPage.slug, "display": "standalone", "icons": [ { "src": statusPage.icon, "sizes": "128x128", "type": "image/png" } ] }); } catch (error) { sendHttpError(response, error.message); } }); // overall status-page status badge router.get("/api/status-page/:slug/badge", cache("5 minutes"), async (request, response) => { allowDevAllOrigin(response); let slug = request.params.slug; slug = slug.toLowerCase(); const statusPageID = await StatusPage.slugToID(slug); const { label, upColor = badgeConstants.defaultUpColor, downColor = badgeConstants.defaultDownColor, partialColor = "#F6BE00", maintenanceColor = "#808080", style = badgeConstants.defaultStyle } = request.query; try { let monitorIDList = await R.getCol(` SELECT monitor_group.monitor_id FROM monitor_group, \`group\` WHERE monitor_group.group_id = \`group\`.id AND public = 1 AND \`group\`.status_page_id = ? `, [ statusPageID ]); let hasUp = false; let hasDown = false; let hasMaintenance = false; for (let monitorID of monitorIDList) { // retrieve the latest heartbeat let beat = await R.getAll(` SELECT * FROM heartbeat WHERE monitor_id = ? ORDER BY time DESC LIMIT 1 `, [ monitorID, ]); // to be sure, when corresponding monitor not found if (beat.length === 0) { continue; } // handle status of beat if (beat[0].status === 3) { hasMaintenance = true; } else if (beat[0].status === 2) { // ignored } else if (beat[0].status === 1) { hasUp = true; } else { hasDown = true; } } const badgeValues = { style }; if (!hasUp && !hasDown && !hasMaintenance) { // return a "N/A" badge in naColor (grey), if monitor is not public / not available / non exsitant badgeValues.message = "N/A"; badgeValues.color = badgeConstants.naColor; } else { if (hasMaintenance) { badgeValues.label = label ? label : ""; badgeValues.color = maintenanceColor; badgeValues.message = "Maintenance"; } else if (hasUp && !hasDown) { badgeValues.label = label ? label : ""; badgeValues.color = upColor; badgeValues.message = "Up"; } else if (hasUp && hasDown) { badgeValues.label = label ? label : ""; badgeValues.color = partialColor; badgeValues.message = "Degraded"; } else { badgeValues.label = label ? label : ""; badgeValues.color = downColor; badgeValues.message = "Down"; } } // build the svg based on given values const svg = makeBadge(badgeValues); response.type("image/svg+xml"); response.send(svg); } catch (error) { sendHttpError(response, error.message); } }); module.exports = router;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/server/routers/api-router.js
server/routers/api-router.js
let express = require("express"); const { setting, allowDevAllOrigin, allowAllOrigin, percentageToColor, filterAndJoin, sendHttpError, } = require("../util-server"); const { R } = require("redbean-node"); const apicache = require("../modules/apicache"); const Monitor = require("../model/monitor"); const dayjs = require("dayjs"); const { UP, MAINTENANCE, DOWN, PENDING, flipStatus, log, badgeConstants } = require("../../src/util"); const StatusPage = require("../model/status_page"); const { UptimeKumaServer } = require("../uptime-kuma-server"); const { makeBadge } = require("badge-maker"); const { Prometheus } = require("../prometheus"); const Database = require("../database"); const { UptimeCalculator } = require("../uptime-calculator"); let router = express.Router(); let cache = apicache.middleware; const server = UptimeKumaServer.getInstance(); let io = server.io; router.get("/api/entry-page", async (request, response) => { allowDevAllOrigin(response); let result = { }; let hostname = request.hostname; if ((await setting("trustProxy")) && request.headers["x-forwarded-host"]) { hostname = request.headers["x-forwarded-host"]; } if (hostname in StatusPage.domainMappingList) { result.type = "statusPageMatchedDomain"; result.statusPageSlug = StatusPage.domainMappingList[hostname]; } else { result.type = "entryPage"; result.entryPage = server.entryPage; } response.json(result); }); router.all("/api/push/:pushToken", async (request, response) => { try { let pushToken = request.params.pushToken; let msg = request.query.msg || "OK"; let ping = parseFloat(request.query.ping) || null; let statusString = request.query.status || "up"; const statusFromParam = (statusString === "up") ? UP : DOWN; let monitor = await R.findOne("monitor", " push_token = ? AND active = 1 ", [ pushToken ]); if (! monitor) { throw new Error("Monitor not found or not active."); } const previousHeartbeat = await Monitor.getPreviousHeartbeat(monitor.id); let isFirstBeat = true; let bean = R.dispense("heartbeat"); bean.time = R.isoDateTimeMillis(dayjs.utc()); bean.monitor_id = monitor.id; bean.ping = ping; bean.msg = msg; bean.downCount = previousHeartbeat?.downCount || 0; if (previousHeartbeat) { isFirstBeat = false; bean.duration = dayjs(bean.time).diff(dayjs(previousHeartbeat.time), "second"); } if (await Monitor.isUnderMaintenance(monitor.id)) { msg = "Monitor under maintenance"; bean.status = MAINTENANCE; } else { determineStatus(statusFromParam, previousHeartbeat, monitor.maxretries, monitor.isUpsideDown(), bean); } // Calculate uptime let uptimeCalculator = await UptimeCalculator.getUptimeCalculator(monitor.id); let endTimeDayjs = await uptimeCalculator.update(bean.status, parseFloat(bean.ping)); bean.end_time = R.isoDateTimeMillis(endTimeDayjs); log.debug("router", `/api/push/ called at ${dayjs().format("YYYY-MM-DD HH:mm:ss.SSS")}`); log.debug("router", "PreviousStatus: " + previousHeartbeat?.status); log.debug("router", "Current Status: " + bean.status); bean.important = Monitor.isImportantBeat(isFirstBeat, previousHeartbeat?.status, bean.status); if (Monitor.isImportantForNotification(isFirstBeat, previousHeartbeat?.status, bean.status)) { // Reset down count bean.downCount = 0; log.debug("monitor", `[${monitor.name}] sendNotification`); await Monitor.sendNotification(isFirstBeat, monitor, bean); } else { if (bean.status === DOWN && monitor.resendInterval > 0) { ++bean.downCount; if (bean.downCount >= monitor.resendInterval) { // Send notification again, because we are still DOWN log.debug("monitor", `[${monitor.name}] sendNotification again: Down Count: ${bean.downCount} | Resend Interval: ${monitor.resendInterval}`); await Monitor.sendNotification(isFirstBeat, monitor, bean); // Reset down count bean.downCount = 0; } } } await R.store(bean); io.to(monitor.user_id).emit("heartbeat", bean.toJSON()); Monitor.sendStats(io, monitor.id, monitor.user_id); try { new Prometheus(monitor, []).update(bean, undefined); } catch (e) { log.error("prometheus", "Please submit an issue to our GitHub repo. Prometheus update error: ", e.message); } response.json({ ok: true, }); } catch (e) { response.status(404).json({ ok: false, msg: e.message }); } }); router.get("/api/badge/:id/status", cache("5 minutes"), async (request, response) => { allowAllOrigin(response); const { label, upLabel = "Up", downLabel = "Down", pendingLabel = "Pending", maintenanceLabel = "Maintenance", upColor = badgeConstants.defaultUpColor, downColor = badgeConstants.defaultDownColor, pendingColor = badgeConstants.defaultPendingColor, maintenanceColor = badgeConstants.defaultMaintenanceColor, style = badgeConstants.defaultStyle, value, // for demo purpose only } = request.query; try { const requestedMonitorId = parseInt(request.params.id, 10); const overrideValue = value !== undefined ? parseInt(value) : undefined; let publicMonitor = await R.getRow(` SELECT monitor_group.monitor_id FROM monitor_group, \`group\` WHERE monitor_group.group_id = \`group\`.id AND monitor_group.monitor_id = ? AND public = 1 `, [ requestedMonitorId ] ); const badgeValues = { style }; if (!publicMonitor) { // return a "N/A" badge in naColor (grey), if monitor is not public / not available / non exsitant badgeValues.message = "N/A"; badgeValues.color = badgeConstants.naColor; } else { const heartbeat = await Monitor.getPreviousHeartbeat(requestedMonitorId); const state = overrideValue !== undefined ? overrideValue : heartbeat.status; if (label === undefined) { badgeValues.label = "Status"; } else { badgeValues.label = label; } switch (state) { case DOWN: badgeValues.color = downColor; badgeValues.message = downLabel; break; case UP: badgeValues.color = upColor; badgeValues.message = upLabel; break; case PENDING: badgeValues.color = pendingColor; badgeValues.message = pendingLabel; break; case MAINTENANCE: badgeValues.color = maintenanceColor; badgeValues.message = maintenanceLabel; break; default: badgeValues.color = badgeConstants.naColor; badgeValues.message = "N/A"; } } // build the svg based on given values const svg = makeBadge(badgeValues); response.type("image/svg+xml"); response.send(svg); } catch (error) { sendHttpError(response, error.message); } }); router.get("/api/badge/:id/uptime/:duration?", cache("5 minutes"), async (request, response) => { allowAllOrigin(response); const { label, labelPrefix, labelSuffix = badgeConstants.defaultUptimeLabelSuffix, prefix, suffix = badgeConstants.defaultUptimeValueSuffix, color, labelColor, style = badgeConstants.defaultStyle, value, // for demo purpose only } = request.query; try { const requestedMonitorId = parseInt(request.params.id, 10); // if no duration is given, set value to 24 (h) let requestedDuration = request.params.duration !== undefined ? request.params.duration : "24h"; const overrideValue = value && parseFloat(value); if (/^[0-9]+$/.test(requestedDuration)) { requestedDuration = `${requestedDuration}h`; } let publicMonitor = await R.getRow(` SELECT monitor_group.monitor_id FROM monitor_group, \`group\` WHERE monitor_group.group_id = \`group\`.id AND monitor_group.monitor_id = ? AND public = 1 `, [ requestedMonitorId ] ); const badgeValues = { style }; if (!publicMonitor) { // return a "N/A" badge in naColor (grey), if monitor is not public / not available / non existent badgeValues.message = "N/A"; badgeValues.color = badgeConstants.naColor; } else { const uptimeCalculator = await UptimeCalculator.getUptimeCalculator(requestedMonitorId); const uptime = overrideValue ?? uptimeCalculator.getDataByDuration(requestedDuration).uptime; // limit the displayed uptime percentage to four (two, when displayed as percent) decimal digits const cleanUptime = (uptime * 100).toPrecision(4); // use a given, custom color or calculate one based on the uptime value badgeValues.color = color ?? percentageToColor(uptime); // use a given, custom labelColor or use the default badge label color (defined by badge-maker) badgeValues.labelColor = labelColor ?? ""; // build a label string. If a custom label is given, override the default one (requestedDuration) badgeValues.label = filterAndJoin([ labelPrefix, label ?? `Uptime (${requestedDuration.slice(0, -1)}${labelSuffix})`, ]); badgeValues.message = filterAndJoin([ prefix, cleanUptime, suffix ]); } // build the SVG based on given values const svg = makeBadge(badgeValues); response.type("image/svg+xml"); response.send(svg); } catch (error) { sendHttpError(response, error.message); } }); router.get("/api/badge/:id/ping/:duration?", cache("5 minutes"), async (request, response) => { allowAllOrigin(response); const { label, labelPrefix, labelSuffix = badgeConstants.defaultPingLabelSuffix, prefix, suffix = badgeConstants.defaultPingValueSuffix, color = badgeConstants.defaultPingColor, labelColor, style = badgeConstants.defaultStyle, value, // for demo purpose only } = request.query; try { const requestedMonitorId = parseInt(request.params.id, 10); // Default duration is 24 (h) if not defined in queryParam, limited to 720h (30d) let requestedDuration = request.params.duration !== undefined ? request.params.duration : "24h"; const overrideValue = value && parseFloat(value); if (/^[0-9]+$/.test(requestedDuration)) { requestedDuration = `${requestedDuration}h`; } // Check if monitor is public const uptimeCalculator = await UptimeCalculator.getUptimeCalculator(requestedMonitorId); const publicAvgPing = uptimeCalculator.getDataByDuration(requestedDuration).avgPing; const badgeValues = { style }; if (!publicAvgPing) { // return a "N/A" badge in naColor (grey), if monitor is not public / not available / non exsitant badgeValues.message = "N/A"; badgeValues.color = badgeConstants.naColor; } else { const avgPing = parseInt(overrideValue ?? publicAvgPing); badgeValues.color = color; // use a given, custom labelColor or use the default badge label color (defined by badge-maker) badgeValues.labelColor = labelColor ?? ""; // build a lable string. If a custom label is given, override the default one (requestedDuration) badgeValues.label = filterAndJoin([ labelPrefix, label ?? `Avg. Ping (${requestedDuration.slice(0, -1)}${labelSuffix})` ]); badgeValues.message = filterAndJoin([ prefix, avgPing, suffix ]); } // build the SVG based on given values const svg = makeBadge(badgeValues); response.type("image/svg+xml"); response.send(svg); } catch (error) { sendHttpError(response, error.message); } }); router.get("/api/badge/:id/avg-response/:duration?", cache("5 minutes"), async (request, response) => { allowAllOrigin(response); const { label, labelPrefix, labelSuffix, prefix, suffix = badgeConstants.defaultPingValueSuffix, color = badgeConstants.defaultPingColor, labelColor, style = badgeConstants.defaultStyle, value, // for demo purpose only } = request.query; try { const requestedMonitorId = parseInt(request.params.id, 10); // Default duration is 24 (h) if not defined in queryParam, limited to 720h (30d) const requestedDuration = Math.min( request.params.duration ? parseInt(request.params.duration, 10) : 24, 720 ); const overrideValue = value && parseFloat(value); const sqlHourOffset = Database.sqlHourOffset(); const publicAvgPing = parseInt(await R.getCell(` SELECT AVG(ping) FROM monitor_group, \`group\`, heartbeat WHERE monitor_group.group_id = \`group\`.id AND heartbeat.time > ${sqlHourOffset} AND heartbeat.ping IS NOT NULL AND public = 1 AND heartbeat.monitor_id = ? `, [ -requestedDuration, requestedMonitorId ] )); const badgeValues = { style }; if (!publicAvgPing) { // return a "N/A" badge in naColor (grey), if monitor is not public / not available / non existent badgeValues.message = "N/A"; badgeValues.color = badgeConstants.naColor; } else { const avgPing = parseInt(overrideValue ?? publicAvgPing); badgeValues.color = color; // use a given, custom labelColor or use the default badge label color (defined by badge-maker) badgeValues.labelColor = labelColor ?? ""; // build a label string. If a custom label is given, override the default one (requestedDuration) badgeValues.label = filterAndJoin([ labelPrefix, label ?? `Avg. Response (${requestedDuration}h)`, labelSuffix, ]); badgeValues.message = filterAndJoin([ prefix, avgPing, suffix ]); } // build the SVG based on given values const svg = makeBadge(badgeValues); response.type("image/svg+xml"); response.send(svg); } catch (error) { sendHttpError(response, error.message); } }); router.get("/api/badge/:id/cert-exp", cache("5 minutes"), async (request, response) => { allowAllOrigin(response); const date = request.query.date; const { label, labelPrefix, labelSuffix, prefix, suffix = date ? "" : badgeConstants.defaultCertExpValueSuffix, upColor = badgeConstants.defaultUpColor, warnColor = badgeConstants.defaultWarnColor, downColor = badgeConstants.defaultDownColor, warnDays = badgeConstants.defaultCertExpireWarnDays, downDays = badgeConstants.defaultCertExpireDownDays, labelColor, style = badgeConstants.defaultStyle, value, // for demo purpose only } = request.query; try { const requestedMonitorId = parseInt(request.params.id, 10); const overrideValue = value && parseFloat(value); let publicMonitor = await R.getRow(` SELECT monitor_group.monitor_id FROM monitor_group, \`group\` WHERE monitor_group.group_id = \`group\`.id AND monitor_group.monitor_id = ? AND public = 1 `, [ requestedMonitorId ] ); const badgeValues = { style }; if (!publicMonitor) { // return a "N/A" badge in naColor (grey), if monitor is not public / not available / non existent badgeValues.message = "N/A"; badgeValues.color = badgeConstants.naColor; } else { const tlsInfoBean = await R.findOne("monitor_tls_info", "monitor_id = ?", [ requestedMonitorId, ]); if (!tlsInfoBean) { // return a "No/Bad Cert" badge in naColor (grey), if no cert saved (does not save bad certs?) badgeValues.message = "No/Bad Cert"; badgeValues.color = badgeConstants.naColor; } else { const tlsInfo = JSON.parse(tlsInfoBean.info_json); if (!tlsInfo.valid) { // return a "Bad Cert" badge in naColor (grey), when cert is not valid badgeValues.message = "Bad Cert"; badgeValues.color = downColor; } else { const daysRemaining = parseInt(overrideValue ?? tlsInfo.certInfo.daysRemaining); if (daysRemaining > warnDays) { badgeValues.color = upColor; } else if (daysRemaining > downDays) { badgeValues.color = warnColor; } else { badgeValues.color = downColor; } // use a given, custom labelColor or use the default badge label color (defined by badge-maker) badgeValues.labelColor = labelColor ?? ""; // build a label string. If a custom label is given, override the default one badgeValues.label = filterAndJoin([ labelPrefix, label ?? "Cert Exp.", labelSuffix, ]); badgeValues.message = filterAndJoin([ prefix, date ? tlsInfo.certInfo.validTo : daysRemaining, suffix ]); } } } // build the SVG based on given values const svg = makeBadge(badgeValues); response.type("image/svg+xml"); response.send(svg); } catch (error) { sendHttpError(response, error.message); } }); router.get("/api/badge/:id/response", cache("5 minutes"), async (request, response) => { allowAllOrigin(response); const { label, labelPrefix, labelSuffix, prefix, suffix = badgeConstants.defaultPingValueSuffix, color = badgeConstants.defaultPingColor, labelColor, style = badgeConstants.defaultStyle, value, // for demo purpose only } = request.query; try { const requestedMonitorId = parseInt(request.params.id, 10); const overrideValue = value && parseFloat(value); let publicMonitor = await R.getRow(` SELECT monitor_group.monitor_id FROM monitor_group, \`group\` WHERE monitor_group.group_id = \`group\`.id AND monitor_group.monitor_id = ? AND public = 1 `, [ requestedMonitorId ] ); const badgeValues = { style }; if (!publicMonitor) { // return a "N/A" badge in naColor (grey), if monitor is not public / not available / non existent badgeValues.message = "N/A"; badgeValues.color = badgeConstants.naColor; } else { const heartbeat = await Monitor.getPreviousHeartbeat( requestedMonitorId ); if (!heartbeat.ping) { // return a "N/A" badge in naColor (grey), if previous heartbeat has no ping badgeValues.message = "N/A"; badgeValues.color = badgeConstants.naColor; } else { const ping = parseInt(overrideValue ?? heartbeat.ping); badgeValues.color = color; // use a given, custom labelColor or use the default badge label color (defined by badge-maker) badgeValues.labelColor = labelColor ?? ""; // build a label string. If a custom label is given, override the default one badgeValues.label = filterAndJoin([ labelPrefix, label ?? "Response", labelSuffix, ]); badgeValues.message = filterAndJoin([ prefix, ping, suffix ]); } } // build the SVG based on given values const svg = makeBadge(badgeValues); response.type("image/svg+xml"); response.send(svg); } catch (error) { sendHttpError(response, error.message); } }); /** * Determines the status of the next beat in the push route handling. * @param {string} status - The reported new status. * @param {object} previousHeartbeat - The previous heartbeat object. * @param {number} maxretries - The maximum number of retries allowed. * @param {boolean} isUpsideDown - Indicates if the monitor is upside down. * @param {object} bean - The new heartbeat object. * @returns {void} */ function determineStatus(status, previousHeartbeat, maxretries, isUpsideDown, bean) { if (isUpsideDown) { status = flipStatus(status); } if (previousHeartbeat) { if (previousHeartbeat.status === UP && status === DOWN) { // Going Down if ((maxretries > 0) && (previousHeartbeat.retries < maxretries)) { // Retries available bean.retries = previousHeartbeat.retries + 1; bean.status = PENDING; } else { // No more retries bean.retries = 0; bean.status = DOWN; } } else if (previousHeartbeat.status === PENDING && status === DOWN && previousHeartbeat.retries < maxretries) { // Retries available bean.retries = previousHeartbeat.retries + 1; bean.status = PENDING; } else { // No more retries or not pending if (status === DOWN) { bean.retries = previousHeartbeat.retries + 1; bean.status = status; } else { bean.retries = 0; bean.status = status; } } } else { // First beat? if (status === DOWN && maxretries > 0) { // Retries available bean.retries = 1; bean.status = PENDING; } else { // Retires not enabled bean.retries = 0; bean.status = status; } } } module.exports = router;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/config/playwright.config.js
config/playwright.config.js
import { defineConfig, devices } from "@playwright/test"; const port = 30001; export const url = `http://localhost:${port}`; export default defineConfig({ // Look for test files in the "tests" directory, relative to this configuration file. testDir: "../test/e2e/specs", outputDir: "../private/playwright-test-results", fullyParallel: false, locale: "en-US", // Fail the build on CI if you accidentally left test.only in the source code. forbidOnly: !!process.env.CI, // Retry on CI only. retries: process.env.CI ? 2 : 0, // Opt out of parallel tests on CI. workers: 1, // Reporter to use reporter: [ [ "html", { outputFolder: "../private/playwright-report", open: "never", } ], ], use: { // Base URL to use in actions like `await page.goto('/')`. baseURL: url, // Collect trace when retrying the failed test. trace: "on-first-retry", }, // Configure projects for major browsers. projects: [ { name: "run-once setup", testMatch: /setup-process\.once\.js/, use: { ...devices["Desktop Chrome"] }, }, { name: "specs", use: { ...devices["Desktop Chrome"] }, dependencies: [ "run-once setup" ], }, /* { name: "firefox", use: { browserName: "firefox" } },*/ ], // Run your local dev server before starting the tests. webServer: { command: `node extra/remove-playwright-test-data.js && cross-env NODE_ENV=development node server/server.js --port=${port} --data-dir=./data/playwright-test`, url, reuseExistingServer: false, cwd: "../", }, });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/config/jest-backend.config.js
config/jest-backend.config.js
module.exports = { "rootDir": "..", "testRegex": "./test/backend.spec.js", };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/config/vite.config.js
config/vite.config.js
import vue from "@vitejs/plugin-vue"; import { defineConfig } from "vite"; import visualizer from "rollup-plugin-visualizer"; import viteCompression from "vite-plugin-compression"; import { VitePWA } from "vite-plugin-pwa"; const postCssScss = require("postcss-scss"); const postcssRTLCSS = require("postcss-rtlcss"); const viteCompressionFilter = /\.(js|mjs|json|css|html|svg)$/i; // https://vitejs.dev/config/ export default defineConfig({ server: { port: 3000, }, define: { "FRONTEND_VERSION": JSON.stringify(process.env.npm_package_version), "process.env": {}, }, plugins: [ vue(), visualizer({ filename: "tmp/dist-stats.html" }), viteCompression({ algorithm: "gzip", filter: viteCompressionFilter, }), viteCompression({ algorithm: "brotliCompress", filter: viteCompressionFilter, }), VitePWA({ registerType: null, srcDir: "src", filename: "serviceWorker.ts", strategies: "injectManifest", }), ], css: { postcss: { "parser": postCssScss, "map": false, "plugins": [ postcssRTLCSS ] } }, build: { commonjsOptions: { include: [ /.js$/ ], }, rollupOptions: { output: { manualChunks(id, { getModuleInfo, getModuleIds }) { } } }, } });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/gulpfile.js
gulpfile.js
const fs = require('fs'); const pkg = require('./package.json') const glob = require('glob') const yargs = require('yargs') const through = require('through2'); const qunit = require('node-qunit-puppeteer') const {rollup} = require('rollup') const terser = require('@rollup/plugin-terser') const babel = require('@rollup/plugin-babel').default const commonjs = require('@rollup/plugin-commonjs') const resolve = require('@rollup/plugin-node-resolve').default const sass = require('sass') const gulp = require('gulp') const zip = require('gulp-zip') const header = require('gulp-header-comment') const eslint = require('gulp-eslint') const minify = require('gulp-clean-css') const connect = require('gulp-connect') const autoprefixer = require('gulp-autoprefixer') const root = yargs.argv.root || '.' const port = yargs.argv.port || 8000 const host = yargs.argv.host || 'localhost' const cssLicense = ` reveal.js ${pkg.version} ${pkg.homepage} MIT licensed Copyright (C) 2011-2024 Hakim El Hattab, https://hakim.se `; const jsLicense = `/*! * reveal.js ${pkg.version} * ${pkg.homepage} * MIT licensed * * Copyright (C) 2011-2024 Hakim El Hattab, https://hakim.se */\n`; // Prevents warnings from opening too many test pages process.setMaxListeners(20); const babelConfig = { babelHelpers: 'bundled', ignore: ['node_modules'], compact: false, extensions: ['.js', '.html'], plugins: [ 'transform-html-import-to-string' ], presets: [[ '@babel/preset-env', { corejs: 3, useBuiltIns: 'usage', modules: false } ]] }; // Our ES module bundle only targets newer browsers with // module support. Browsers are targeted explicitly instead // of using the "esmodule: true" target since that leads to // polyfilling older browsers and a larger bundle. const babelConfigESM = JSON.parse( JSON.stringify( babelConfig ) ); babelConfigESM.presets[0][1].targets = { browsers: [ 'last 2 Chrome versions', 'last 2 Safari versions', 'last 2 iOS versions', 'last 2 Firefox versions', 'last 2 Edge versions', ] }; let cache = {}; // Creates a bundle with broad browser support, exposed // as UMD gulp.task('js-es5', () => { return rollup({ cache: cache.umd, input: 'js/index.js', plugins: [ resolve(), commonjs(), babel( babelConfig ), terser() ] }).then( bundle => { cache.umd = bundle.cache; return bundle.write({ name: 'Reveal', file: './dist/reveal.js', format: 'umd', banner: jsLicense, sourcemap: true }); }); }) // Creates an ES module bundle gulp.task('js-es6', () => { return rollup({ cache: cache.esm, input: 'js/index.js', plugins: [ resolve(), commonjs(), babel( babelConfigESM ), terser() ] }).then( bundle => { cache.esm = bundle.cache; return bundle.write({ file: './dist/reveal.esm.js', format: 'es', banner: jsLicense, sourcemap: true }); }); }) gulp.task('js', gulp.parallel('js-es5', 'js-es6')); // Creates a UMD and ES module bundle for each of our // built-in plugins gulp.task('plugins', () => { return Promise.all([ { name: 'RevealHighlight', input: './plugin/highlight/plugin.js', output: './plugin/highlight/highlight' }, { name: 'RevealMarkdown', input: './plugin/markdown/plugin.js', output: './plugin/markdown/markdown' }, { name: 'RevealSearch', input: './plugin/search/plugin.js', output: './plugin/search/search' }, { name: 'RevealNotes', input: './plugin/notes/plugin.js', output: './plugin/notes/notes' }, { name: 'RevealZoom', input: './plugin/zoom/plugin.js', output: './plugin/zoom/zoom' }, { name: 'RevealMath', input: './plugin/math/plugin.js', output: './plugin/math/math' }, ].map( plugin => { return rollup({ cache: cache[plugin.input], input: plugin.input, plugins: [ resolve(), commonjs(), babel({ ...babelConfig, ignore: [/node_modules\/(?!(highlight\.js|marked)\/).*/], }), terser() ] }).then( bundle => { cache[plugin.input] = bundle.cache; bundle.write({ file: plugin.output + '.esm.js', name: plugin.name, format: 'es' }) bundle.write({ file: plugin.output + '.js', name: plugin.name, format: 'umd' }) }); } )); }) // a custom pipeable step to transform Sass to CSS function compileSass() { return through.obj( ( vinylFile, encoding, callback ) => { const transformedFile = vinylFile.clone(); sass.render({ silenceDeprecations: ['legacy-js-api'], data: transformedFile.contents.toString(), file: transformedFile.path, }, ( err, result ) => { if( err ) { callback(err); } else { transformedFile.extname = '.css'; transformedFile.contents = result.css; callback( null, transformedFile ); } }); }); } gulp.task('css-themes', () => gulp.src(['./css/theme/source/*.{sass,scss}']) .pipe(compileSass()) .pipe(gulp.dest('./dist/theme'))) gulp.task('css-core', () => gulp.src(['css/reveal.scss']) .pipe(compileSass()) .pipe(autoprefixer()) .pipe(minify({compatibility: 'ie9'})) .pipe(header(cssLicense)) .pipe(gulp.dest('./dist'))) gulp.task('css', gulp.parallel('css-themes', 'css-core')) gulp.task('qunit', () => { let serverConfig = { root, port: 8009, host: 'localhost', name: 'test-server' } let server = connect.server( serverConfig ) let testFiles = glob.sync('test/*.html' ) let totalTests = 0; let failingTests = 0; let tests = Promise.all( testFiles.map( filename => { return new Promise( ( resolve, reject ) => { qunit.runQunitPuppeteer({ targetUrl: `http://${serverConfig.host}:${serverConfig.port}/${filename}`, timeout: 20000, redirectConsole: false, puppeteerArgs: ['--allow-file-access-from-files', '--no-sandbox'] }) .then(result => { if( result.stats.failed > 0 ) { console.log(`${'!'} ${filename} [${result.stats.passed}/${result.stats.total}] in ${result.stats.runtime}ms`.red); // qunit.printResultSummary(result, console); qunit.printFailedTests(result, console); } else { console.log(`${'✔'} ${filename} [${result.stats.passed}/${result.stats.total}] in ${result.stats.runtime}ms`.green); } totalTests += result.stats.total; failingTests += result.stats.failed; resolve(); }) .catch(error => { console.error(error); reject(); }); } ) } ) ); return new Promise( ( resolve, reject ) => { tests.then( () => { if( failingTests > 0 ) { reject( new Error(`${failingTests}/${totalTests} tests failed`.red) ); } else { console.log(`${'✔'} Passed ${totalTests} tests`.green.bold); resolve(); } } ) .catch( () => { reject(); } ) .finally( () => { server.close(); } ); } ); } ) gulp.task('eslint', () => gulp.src(['./js/**', 'gulpfile.js']) .pipe(eslint()) .pipe(eslint.format())) gulp.task('test', gulp.series( 'eslint', 'qunit' )) gulp.task('default', gulp.series(gulp.parallel('js', 'css', 'plugins'), 'test')) gulp.task('build', gulp.parallel('js', 'css', 'plugins')) gulp.task('package', gulp.series(async () => { let dirs = [ './index.html', './dist/**', './plugin/**', './*/*.md' ]; if (fs.existsSync('./lib')) dirs.push('./lib/**'); if (fs.existsSync('./images')) dirs.push('./images/**'); if (fs.existsSync('./slides')) dirs.push('./slides/**'); return gulp.src( dirs, { base: './', encoding: false } ) .pipe(zip('reveal-js-presentation.zip')).pipe(gulp.dest('./')) })) gulp.task('reload', () => gulp.src(['index.html']) .pipe(connect.reload())); gulp.task('serve', () => { connect.server({ root: root, port: port, host: host, livereload: true }) const slidesRoot = root.endsWith('/') ? root : root + '/' gulp.watch([ slidesRoot + '**/*.html', slidesRoot + '**/*.md', `!${slidesRoot}**/node_modules/**`, // ignore node_modules ], gulp.series('reload')) gulp.watch(['js/**'], gulp.series('js', 'reload', 'eslint')) gulp.watch(['plugin/**/plugin.js', 'plugin/**/*.html'], gulp.series('plugins', 'reload')) gulp.watch([ 'css/theme/source/**/*.{sass,scss}', 'css/theme/template/*.{sass,scss}', ], gulp.series('css-themes', 'reload')) gulp.watch([ 'css/*.scss', 'css/print/*.{sass,scss,css}' ], gulp.series('css-core', 'reload')) gulp.watch(['test/*.html'], gulp.series('test')) })
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/math/math.esm.js
plugin/math/math.esm.js
const t=()=>{let t,e={messageStyle:"none",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]],skipTags:["script","noscript","style","textarea","pre","code"]},skipStartupTypeset:!0};return{id:"mathjax2",init:function(a){t=a;let n=t.getConfig().mathjax2||t.getConfig().math||{},i={...e,...n},s=(i.mathjax||"https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js")+"?config="+(i.config||"TeX-AMS_HTML-full");i.tex2jax={...e.tex2jax,...n.tex2jax},i.mathjax=i.config=null,function(t,e){let a=document.querySelector("head"),n=document.createElement("script");n.type="text/javascript",n.src=t;let i=()=>{"function"==typeof e&&(e.call(),e=null)};n.onload=i,n.onreadystatechange=()=>{"loaded"===this.readyState&&i()},a.appendChild(n)}(s,(function(){MathJax.Hub.Config(i),MathJax.Hub.Queue(["Typeset",MathJax.Hub,t.getRevealElement()]),MathJax.Hub.Queue(t.layout),t.on("slidechanged",(function(t){MathJax.Hub.Queue(["Typeset",MathJax.Hub,t.currentSlide])}))}))}}},e=t; /*! * This plugin is a wrapper for the MathJax2, * MathJax3 and KaTeX typesetter plugins. */ var a=Plugin=Object.assign(e(),{KaTeX:()=>{let t,e={version:"latest",delimiters:[{left:"$$",right:"$$",display:!0},{left:"$",right:"$",display:!1},{left:"\\(",right:"\\)",display:!1},{left:"\\[",right:"\\]",display:!0}],ignoredTags:["script","noscript","style","textarea","pre","code"]};const a=t=>new Promise(((e,a)=>{const n=document.createElement("script");n.type="text/javascript",n.onload=e,n.onerror=a,n.src=t,document.head.append(n)}));return{id:"katex",init:function(n){t=n;let i=t.getConfig().katex||{},s={...e,...i};const{local:o,version:l,extensions:r,...c}=s;let d=s.local||"https://cdn.jsdelivr.net/npm/katex",p=s.local?"":"@"+s.version,u=d+p+"/dist/katex.min.css",h=d+p+"/dist/contrib/mhchem.min.js",x=d+p+"/dist/contrib/auto-render.min.js",m=[d+p+"/dist/katex.min.js"];s.extensions&&s.extensions.includes("mhchem")&&m.push(h),m.push(x);const f=()=>{renderMathInElement(n.getSlidesElement(),c),t.layout()};(t=>{let e=document.createElement("link");e.rel="stylesheet",e.href=t,document.head.appendChild(e)})(u),async function(t){for(const e of t)await a(e)}(m).then((()=>{t.isReady()?f():t.on("ready",f.bind(this))}))}}},MathJax2:t,MathJax3:()=>{let t,e={tex:{inlineMath:[["$","$"],["\\(","\\)"]]},options:{skipHtmlTags:["script","noscript","style","textarea","pre","code"]},startup:{ready:()=>{MathJax.startup.defaultReady(),MathJax.startup.promise.then((()=>{t.layout()}))}}};return{id:"mathjax3",init:function(a){t=a;let n=t.getConfig().mathjax3||{},i={...e,...n};i.tex={...e.tex,...n.tex},i.options={...e.options,...n.options},i.startup={...e.startup,...n.startup};let s=i.mathjax||"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js";i.mathjax=null,window.MathJax=i,function(t,e){let a=document.createElement("script");a.type="text/javascript",a.id="MathJax-script",a.src=t,a.async=!0,a.onload=()=>{"function"==typeof e&&(e.call(),e=null)},document.head.appendChild(a)}(s,(function(){t.addEventListener("slidechanged",(function(t){MathJax.typeset()}))}))}}}});export{a as default};
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/math/plugin.js
plugin/math/plugin.js
import {KaTeX} from "./katex"; import {MathJax2} from "./mathjax2"; import {MathJax3} from "./mathjax3"; const defaultTypesetter = MathJax2; /*! * This plugin is a wrapper for the MathJax2, * MathJax3 and KaTeX typesetter plugins. */ export default Plugin = Object.assign( defaultTypesetter(), { KaTeX, MathJax2, MathJax3 } );
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/math/math.js
plugin/math/math.js
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).RevealMath=e()}(this,(function(){"use strict";const t=()=>{let t,e={messageStyle:"none",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]],skipTags:["script","noscript","style","textarea","pre","code"]},skipStartupTypeset:!0};return{id:"mathjax2",init:function(n){t=n;let a=t.getConfig().mathjax2||t.getConfig().math||{},i={...e,...a},s=(i.mathjax||"https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js")+"?config="+(i.config||"TeX-AMS_HTML-full");i.tex2jax={...e.tex2jax,...a.tex2jax},i.mathjax=i.config=null,function(t,e){let n=document.querySelector("head"),a=document.createElement("script");a.type="text/javascript",a.src=t;let i=()=>{"function"==typeof e&&(e.call(),e=null)};a.onload=i,a.onreadystatechange=()=>{"loaded"===this.readyState&&i()},n.appendChild(a)}(s,(function(){MathJax.Hub.Config(i),MathJax.Hub.Queue(["Typeset",MathJax.Hub,t.getRevealElement()]),MathJax.Hub.Queue(t.layout),t.on("slidechanged",(function(t){MathJax.Hub.Queue(["Typeset",MathJax.Hub,t.currentSlide])}))}))}}},e=t;return Plugin=Object.assign(e(),{KaTeX:()=>{let t,e={version:"latest",delimiters:[{left:"$$",right:"$$",display:!0},{left:"$",right:"$",display:!1},{left:"\\(",right:"\\)",display:!1},{left:"\\[",right:"\\]",display:!0}],ignoredTags:["script","noscript","style","textarea","pre","code"]};const n=t=>new Promise(((e,n)=>{const a=document.createElement("script");a.type="text/javascript",a.onload=e,a.onerror=n,a.src=t,document.head.append(a)}));return{id:"katex",init:function(a){t=a;let i=t.getConfig().katex||{},s={...e,...i};const{local:o,version:l,extensions:c,...r}=s;let d=s.local||"https://cdn.jsdelivr.net/npm/katex",u=s.local?"":"@"+s.version,p=d+u+"/dist/katex.min.css",h=d+u+"/dist/contrib/mhchem.min.js",x=d+u+"/dist/contrib/auto-render.min.js",m=[d+u+"/dist/katex.min.js"];s.extensions&&s.extensions.includes("mhchem")&&m.push(h),m.push(x);const f=()=>{renderMathInElement(a.getSlidesElement(),r),t.layout()};(t=>{let e=document.createElement("link");e.rel="stylesheet",e.href=t,document.head.appendChild(e)})(p),async function(t){for(const e of t)await n(e)}(m).then((()=>{t.isReady()?f():t.on("ready",f.bind(this))}))}}},MathJax2:t,MathJax3:()=>{let t,e={tex:{inlineMath:[["$","$"],["\\(","\\)"]]},options:{skipHtmlTags:["script","noscript","style","textarea","pre","code"]},startup:{ready:()=>{MathJax.startup.defaultReady(),MathJax.startup.promise.then((()=>{t.layout()}))}}};return{id:"mathjax3",init:function(n){t=n;let a=t.getConfig().mathjax3||{},i={...e,...a};i.tex={...e.tex,...a.tex},i.options={...e.options,...a.options},i.startup={...e.startup,...a.startup};let s=i.mathjax||"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js";i.mathjax=null,window.MathJax=i,function(t,e){let n=document.createElement("script");n.type="text/javascript",n.id="MathJax-script",n.src=t,n.async=!0,n.onload=()=>{"function"==typeof e&&(e.call(),e=null)},document.head.appendChild(n)}(s,(function(){t.addEventListener("slidechanged",(function(t){MathJax.typeset()}))}))}}}})}));
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/math/katex.js
plugin/math/katex.js
/** * A plugin which enables rendering of math equations inside * of reveal.js slides. Essentially a thin wrapper for KaTeX. * * @author Hakim El Hattab * @author Gerhard Burger */ export const KaTeX = () => { let deck; let defaultOptions = { version: 'latest', delimiters: [ {left: '$$', right: '$$', display: true}, // Note: $$ has to come before $ {left: '$', right: '$', display: false}, {left: '\\(', right: '\\)', display: false}, {left: '\\[', right: '\\]', display: true} ], ignoredTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'] } const loadCss = src => { let link = document.createElement('link'); link.rel = 'stylesheet'; link.href = src; document.head.appendChild(link); }; /** * Loads a JavaScript file and returns a Promise for when it is loaded * Credits: https://aaronsmith.online/easily-load-an-external-script-using-javascript/ */ const loadScript = src => { return new Promise((resolve, reject) => { const script = document.createElement('script') script.type = 'text/javascript' script.onload = resolve script.onerror = reject script.src = src document.head.append(script) }) }; async function loadScripts(urls) { for(const url of urls) { await loadScript(url); } } return { id: 'katex', init: function (reveal) { deck = reveal; let revealOptions = deck.getConfig().katex || {}; let options = {...defaultOptions, ...revealOptions}; const {local, version, extensions, ...katexOptions} = options; let baseUrl = options.local || 'https://cdn.jsdelivr.net/npm/katex'; let versionString = options.local ? '' : '@' + options.version; let cssUrl = baseUrl + versionString + '/dist/katex.min.css'; let katexUrl = baseUrl + versionString + '/dist/katex.min.js'; let mhchemUrl = baseUrl + versionString + '/dist/contrib/mhchem.min.js' let karUrl = baseUrl + versionString + '/dist/contrib/auto-render.min.js'; let katexScripts = [katexUrl]; if(options.extensions && options.extensions.includes("mhchem")) { katexScripts.push(mhchemUrl); } katexScripts.push(karUrl); const renderMath = () => { renderMathInElement(reveal.getSlidesElement(), katexOptions); deck.layout(); } loadCss(cssUrl); // For some reason dynamically loading with defer attribute doesn't result in the expected behavior, the below code does loadScripts(katexScripts).then(() => { if( deck.isReady() ) { renderMath(); } else { deck.on( 'ready', renderMath.bind( this ) ); } }); } } };
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/math/mathjax2.js
plugin/math/mathjax2.js
/** * A plugin which enables rendering of math equations inside * of reveal.js slides. Essentially a thin wrapper for MathJax. * * @author Hakim El Hattab */ export const MathJax2 = () => { // The reveal.js instance this plugin is attached to let deck; let defaultOptions = { messageStyle: 'none', tex2jax: { inlineMath: [ [ '$', '$' ], [ '\\(', '\\)' ] ], skipTags: [ 'script', 'noscript', 'style', 'textarea', 'pre', 'code' ] }, skipStartupTypeset: true }; function loadScript( url, callback ) { let head = document.querySelector( 'head' ); let script = document.createElement( 'script' ); script.type = 'text/javascript'; script.src = url; // Wrapper for callback to make sure it only fires once let finish = () => { if( typeof callback === 'function' ) { callback.call(); callback = null; } } script.onload = finish; // IE script.onreadystatechange = () => { if ( this.readyState === 'loaded' ) { finish(); } } // Normal browsers head.appendChild( script ); } return { id: 'mathjax2', init: function( reveal ) { deck = reveal; let revealOptions = deck.getConfig().mathjax2 || deck.getConfig().math || {}; let options = { ...defaultOptions, ...revealOptions }; let mathjax = options.mathjax || 'https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js'; let config = options.config || 'TeX-AMS_HTML-full'; let url = mathjax + '?config=' + config; options.tex2jax = { ...defaultOptions.tex2jax, ...revealOptions.tex2jax }; options.mathjax = options.config = null; loadScript( url, function() { MathJax.Hub.Config( options ); // Typeset followed by an immediate reveal.js layout since // the typesetting process could affect slide height MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub, deck.getRevealElement() ] ); MathJax.Hub.Queue( deck.layout ); // Reprocess equations in slides when they turn visible deck.on( 'slidechanged', function( event ) { MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub, event.currentSlide ] ); } ); } ); } } };
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/math/mathjax3.js
plugin/math/mathjax3.js
/** * A plugin which enables rendering of math equations inside * of reveal.js slides. Essentially a thin wrapper for MathJax 3 * * @author Hakim El Hattab * @author Gerhard Burger */ export const MathJax3 = () => { // The reveal.js instance this plugin is attached to let deck; let defaultOptions = { tex: { inlineMath: [ [ '$', '$' ], [ '\\(', '\\)' ] ] }, options: { skipHtmlTags: [ 'script', 'noscript', 'style', 'textarea', 'pre', 'code' ] }, startup: { ready: () => { MathJax.startup.defaultReady(); MathJax.startup.promise.then(() => { deck.layout(); }); } } }; function loadScript( url, callback ) { let script = document.createElement( 'script' ); script.type = "text/javascript" script.id = "MathJax-script" script.src = url; script.async = true // Wrapper for callback to make sure it only fires once script.onload = () => { if (typeof callback === 'function') { callback.call(); callback = null; } }; document.head.appendChild( script ); } return { id: 'mathjax3', init: function(reveal) { deck = reveal; let revealOptions = deck.getConfig().mathjax3 || {}; let options = {...defaultOptions, ...revealOptions}; options.tex = {...defaultOptions.tex, ...revealOptions.tex} options.options = {...defaultOptions.options, ...revealOptions.options} options.startup = {...defaultOptions.startup, ...revealOptions.startup} let url = options.mathjax || 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'; options.mathjax = null; window.MathJax = options; loadScript( url, function() { // Reprocess equations in slides when they turn visible deck.addEventListener( 'slidechanged', function( event ) { MathJax.typeset(); } ); } ); } } };
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/zoom/zoom.esm.js
plugin/zoom/zoom.esm.js
/*! * reveal.js Zoom plugin */ const e={id:"zoom",init:function(e){e.getRevealElement().addEventListener("mousedown",(function(t){var n=/Linux/.test(window.navigator.platform)?"ctrl":"alt",i=(e.getConfig().zoomKey?e.getConfig().zoomKey:n)+"Key",d=e.getConfig().zoomLevel?e.getConfig().zoomLevel:2;t[i]&&!e.isOverview()&&(t.preventDefault(),o.to({x:t.clientX,y:t.clientY,scale:d,pan:!1}))}))},destroy:()=>{o.reset()}};var t=()=>e,o=function(){var e=1,t=0,n=0,i=-1,d=-1,l="transform"in document.body.style;function s(t,o){var n=r();if(t.width=t.width||1,t.height=t.height||1,t.x-=(window.innerWidth-t.width*o)/2,t.y-=(window.innerHeight-t.height*o)/2,l)if(1===o)document.body.style.transform="";else{var i=n.x+"px "+n.y+"px",d="translate("+-t.x+"px,"+-t.y+"px) scale("+o+")";document.body.style.transformOrigin=i,document.body.style.transform=d}else 1===o?(document.body.style.position="",document.body.style.left="",document.body.style.top="",document.body.style.width="",document.body.style.height="",document.body.style.zoom=""):(document.body.style.position="relative",document.body.style.left=-(n.x+t.x)/o+"px",document.body.style.top=-(n.y+t.y)/o+"px",document.body.style.width=100*o+"%",document.body.style.height=100*o+"%",document.body.style.zoom=o);e=o,document.documentElement.classList&&(1!==e?document.documentElement.classList.add("zoomed"):document.documentElement.classList.remove("zoomed"))}function c(){var o=.12*window.innerWidth,i=.12*window.innerHeight,d=r();n<i?window.scroll(d.x,d.y-14/e*(1-n/i)):n>window.innerHeight-i&&window.scroll(d.x,d.y+(1-(window.innerHeight-n)/i)*(14/e)),t<o?window.scroll(d.x-14/e*(1-t/o),d.y):t>window.innerWidth-o&&window.scroll(d.x+(1-(window.innerWidth-t)/o)*(14/e),d.y)}function r(){return{x:void 0!==window.scrollX?window.scrollX:window.pageXOffset,y:void 0!==window.scrollY?window.scrollY:window.pageYOffset}}return l&&(document.body.style.transition="transform 0.8s ease"),document.addEventListener("keyup",(function(t){1!==e&&27===t.keyCode&&o.out()})),document.addEventListener("mousemove",(function(o){1!==e&&(t=o.clientX,n=o.clientY)})),{to:function(t){if(1!==e)o.out();else{if(t.x=t.x||0,t.y=t.y||0,t.element){var n=t.element.getBoundingClientRect();t.x=n.left-20,t.y=n.top-20,t.width=n.width+40,t.height=n.height+40}void 0!==t.width&&void 0!==t.height&&(t.scale=Math.max(Math.min(window.innerWidth/t.width,window.innerHeight/t.height),1)),t.scale>1&&(t.x*=t.scale,t.y*=t.scale,s(t,t.scale),!1!==t.pan&&(i=setTimeout((function(){d=setInterval(c,1e3/60)}),800)))}},out:function(){clearTimeout(i),clearInterval(d),s({x:0,y:0},1),e=1},magnify:function(e){this.to(e)},reset:function(){this.out()},zoomLevel:function(){return e}}}(); /*! * zoom.js 0.3 (modified for use with reveal.js) * http://lab.hakim.se/zoom-js * MIT licensed * * Copyright (C) 2011-2014 Hakim El Hattab, http://hakim.se */export{t as default};
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/zoom/plugin.js
plugin/zoom/plugin.js
/*! * reveal.js Zoom plugin */ const Plugin = { id: 'zoom', init: function( reveal ) { reveal.getRevealElement().addEventListener( 'mousedown', function( event ) { var defaultModifier = /Linux/.test( window.navigator.platform ) ? 'ctrl' : 'alt'; var modifier = ( reveal.getConfig().zoomKey ? reveal.getConfig().zoomKey : defaultModifier ) + 'Key'; var zoomLevel = ( reveal.getConfig().zoomLevel ? reveal.getConfig().zoomLevel : 2 ); if( event[ modifier ] && !reveal.isOverview() ) { event.preventDefault(); zoom.to({ x: event.clientX, y: event.clientY, scale: zoomLevel, pan: false }); } } ); }, destroy: () => { zoom.reset(); } }; export default () => Plugin; /*! * zoom.js 0.3 (modified for use with reveal.js) * http://lab.hakim.se/zoom-js * MIT licensed * * Copyright (C) 2011-2014 Hakim El Hattab, http://hakim.se */ var zoom = (function(){ // The current zoom level (scale) var level = 1; // The current mouse position, used for panning var mouseX = 0, mouseY = 0; // Timeout before pan is activated var panEngageTimeout = -1, panUpdateInterval = -1; // Check for transform support so that we can fallback otherwise var supportsTransforms = 'transform' in document.body.style; if( supportsTransforms ) { // The easing that will be applied when we zoom in/out document.body.style.transition = 'transform 0.8s ease'; } // Zoom out if the user hits escape document.addEventListener( 'keyup', function( event ) { if( level !== 1 && event.keyCode === 27 ) { zoom.out(); } } ); // Monitor mouse movement for panning document.addEventListener( 'mousemove', function( event ) { if( level !== 1 ) { mouseX = event.clientX; mouseY = event.clientY; } } ); /** * Applies the CSS required to zoom in, prefers the use of CSS3 * transforms but falls back on zoom for IE. * * @param {Object} rect * @param {Number} scale */ function magnify( rect, scale ) { var scrollOffset = getScrollOffset(); // Ensure a width/height is set rect.width = rect.width || 1; rect.height = rect.height || 1; // Center the rect within the zoomed viewport rect.x -= ( window.innerWidth - ( rect.width * scale ) ) / 2; rect.y -= ( window.innerHeight - ( rect.height * scale ) ) / 2; if( supportsTransforms ) { // Reset if( scale === 1 ) { document.body.style.transform = ''; } // Scale else { var origin = scrollOffset.x +'px '+ scrollOffset.y +'px', transform = 'translate('+ -rect.x +'px,'+ -rect.y +'px) scale('+ scale +')'; document.body.style.transformOrigin = origin; document.body.style.transform = transform; } } else { // Reset if( scale === 1 ) { document.body.style.position = ''; document.body.style.left = ''; document.body.style.top = ''; document.body.style.width = ''; document.body.style.height = ''; document.body.style.zoom = ''; } // Scale else { document.body.style.position = 'relative'; document.body.style.left = ( - ( scrollOffset.x + rect.x ) / scale ) + 'px'; document.body.style.top = ( - ( scrollOffset.y + rect.y ) / scale ) + 'px'; document.body.style.width = ( scale * 100 ) + '%'; document.body.style.height = ( scale * 100 ) + '%'; document.body.style.zoom = scale; } } level = scale; if( document.documentElement.classList ) { if( level !== 1 ) { document.documentElement.classList.add( 'zoomed' ); } else { document.documentElement.classList.remove( 'zoomed' ); } } } /** * Pan the document when the mouse cursor approaches the edges * of the window. */ function pan() { var range = 0.12, rangeX = window.innerWidth * range, rangeY = window.innerHeight * range, scrollOffset = getScrollOffset(); // Up if( mouseY < rangeY ) { window.scroll( scrollOffset.x, scrollOffset.y - ( 1 - ( mouseY / rangeY ) ) * ( 14 / level ) ); } // Down else if( mouseY > window.innerHeight - rangeY ) { window.scroll( scrollOffset.x, scrollOffset.y + ( 1 - ( window.innerHeight - mouseY ) / rangeY ) * ( 14 / level ) ); } // Left if( mouseX < rangeX ) { window.scroll( scrollOffset.x - ( 1 - ( mouseX / rangeX ) ) * ( 14 / level ), scrollOffset.y ); } // Right else if( mouseX > window.innerWidth - rangeX ) { window.scroll( scrollOffset.x + ( 1 - ( window.innerWidth - mouseX ) / rangeX ) * ( 14 / level ), scrollOffset.y ); } } function getScrollOffset() { return { x: window.scrollX !== undefined ? window.scrollX : window.pageXOffset, y: window.scrollY !== undefined ? window.scrollY : window.pageYOffset } } return { /** * Zooms in on either a rectangle or HTML element. * * @param {Object} options * - element: HTML element to zoom in on * OR * - x/y: coordinates in non-transformed space to zoom in on * - width/height: the portion of the screen to zoom in on * - scale: can be used instead of width/height to explicitly set scale */ to: function( options ) { // Due to an implementation limitation we can't zoom in // to another element without zooming out first if( level !== 1 ) { zoom.out(); } else { options.x = options.x || 0; options.y = options.y || 0; // If an element is set, that takes precedence if( !!options.element ) { // Space around the zoomed in element to leave on screen var padding = 20; var bounds = options.element.getBoundingClientRect(); options.x = bounds.left - padding; options.y = bounds.top - padding; options.width = bounds.width + ( padding * 2 ); options.height = bounds.height + ( padding * 2 ); } // If width/height values are set, calculate scale from those values if( options.width !== undefined && options.height !== undefined ) { options.scale = Math.max( Math.min( window.innerWidth / options.width, window.innerHeight / options.height ), 1 ); } if( options.scale > 1 ) { options.x *= options.scale; options.y *= options.scale; magnify( options, options.scale ); if( options.pan !== false ) { // Wait with engaging panning as it may conflict with the // zoom transition panEngageTimeout = setTimeout( function() { panUpdateInterval = setInterval( pan, 1000 / 60 ); }, 800 ); } } } }, /** * Resets the document zoom state to its default. */ out: function() { clearTimeout( panEngageTimeout ); clearInterval( panUpdateInterval ); magnify( { x: 0, y: 0 }, 1 ); level = 1; }, // Alias magnify: function( options ) { this.to( options ) }, reset: function() { this.out() }, zoomLevel: function() { return level; } } })();
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/zoom/zoom.js
plugin/zoom/zoom.js
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).RevealZoom=t()}(this,(function(){"use strict"; /*! * reveal.js Zoom plugin */const e={id:"zoom",init:function(e){e.getRevealElement().addEventListener("mousedown",(function(o){var n=/Linux/.test(window.navigator.platform)?"ctrl":"alt",i=(e.getConfig().zoomKey?e.getConfig().zoomKey:n)+"Key",d=e.getConfig().zoomLevel?e.getConfig().zoomLevel:2;o[i]&&!e.isOverview()&&(o.preventDefault(),t.to({x:o.clientX,y:o.clientY,scale:d,pan:!1}))}))},destroy:()=>{t.reset()}};var t=function(){var e=1,o=0,n=0,i=-1,d=-1,l="transform"in document.body.style;function s(t,o){var n=r();if(t.width=t.width||1,t.height=t.height||1,t.x-=(window.innerWidth-t.width*o)/2,t.y-=(window.innerHeight-t.height*o)/2,l)if(1===o)document.body.style.transform="";else{var i=n.x+"px "+n.y+"px",d="translate("+-t.x+"px,"+-t.y+"px) scale("+o+")";document.body.style.transformOrigin=i,document.body.style.transform=d}else 1===o?(document.body.style.position="",document.body.style.left="",document.body.style.top="",document.body.style.width="",document.body.style.height="",document.body.style.zoom=""):(document.body.style.position="relative",document.body.style.left=-(n.x+t.x)/o+"px",document.body.style.top=-(n.y+t.y)/o+"px",document.body.style.width=100*o+"%",document.body.style.height=100*o+"%",document.body.style.zoom=o);e=o,document.documentElement.classList&&(1!==e?document.documentElement.classList.add("zoomed"):document.documentElement.classList.remove("zoomed"))}function c(){var t=.12*window.innerWidth,i=.12*window.innerHeight,d=r();n<i?window.scroll(d.x,d.y-14/e*(1-n/i)):n>window.innerHeight-i&&window.scroll(d.x,d.y+(1-(window.innerHeight-n)/i)*(14/e)),o<t?window.scroll(d.x-14/e*(1-o/t),d.y):o>window.innerWidth-t&&window.scroll(d.x+(1-(window.innerWidth-o)/t)*(14/e),d.y)}function r(){return{x:void 0!==window.scrollX?window.scrollX:window.pageXOffset,y:void 0!==window.scrollY?window.scrollY:window.pageYOffset}}return l&&(document.body.style.transition="transform 0.8s ease"),document.addEventListener("keyup",(function(o){1!==e&&27===o.keyCode&&t.out()})),document.addEventListener("mousemove",(function(t){1!==e&&(o=t.clientX,n=t.clientY)})),{to:function(o){if(1!==e)t.out();else{if(o.x=o.x||0,o.y=o.y||0,o.element){var n=o.element.getBoundingClientRect();o.x=n.left-20,o.y=n.top-20,o.width=n.width+40,o.height=n.height+40}void 0!==o.width&&void 0!==o.height&&(o.scale=Math.max(Math.min(window.innerWidth/o.width,window.innerHeight/o.height),1)),o.scale>1&&(o.x*=o.scale,o.y*=o.scale,s(o,o.scale),!1!==o.pan&&(i=setTimeout((function(){d=setInterval(c,1e3/60)}),800)))}},out:function(){clearTimeout(i),clearInterval(d),s({x:0,y:0},1),e=1},magnify:function(e){this.to(e)},reset:function(){this.out()},zoomLevel:function(){return e}}}(); /*! * zoom.js 0.3 (modified for use with reveal.js) * http://lab.hakim.se/zoom-js * MIT licensed * * Copyright (C) 2011-2014 Hakim El Hattab, http://hakim.se */return()=>e}));
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/search/plugin.js
plugin/search/plugin.js
/*! * Handles finding a text string anywhere in the slides and showing the next occurrence to the user * by navigatating to that slide and highlighting it. * * @author Jon Snyder <snyder.jon@gmail.com>, February 2013 */ const Plugin = () => { // The reveal.js instance this plugin is attached to let deck; let searchElement; let searchButton; let searchInput; let matchedSlides; let currentMatchedIndex; let searchboxDirty; let hilitor; function render() { searchElement = document.createElement( 'div' ); searchElement.classList.add( 'searchbox' ); searchElement.style.position = 'absolute'; searchElement.style.top = '10px'; searchElement.style.right = '10px'; searchElement.style.zIndex = 10; //embedded base64 search icon Designed by Sketchdock - http://www.sketchdock.com/: searchElement.innerHTML = `<input type="search" class="searchinput" placeholder="Search..." style="vertical-align: top;"/> </span>`; searchInput = searchElement.querySelector( '.searchinput' ); searchInput.style.width = '240px'; searchInput.style.fontSize = '14px'; searchInput.style.padding = '4px 6px'; searchInput.style.color = '#000'; searchInput.style.background = '#fff'; searchInput.style.borderRadius = '2px'; searchInput.style.border = '0'; searchInput.style.outline = '0'; searchInput.style.boxShadow = '0 2px 18px rgba(0, 0, 0, 0.2)'; searchInput.style['-webkit-appearance'] = 'none'; deck.getRevealElement().appendChild( searchElement ); // searchButton.addEventListener( 'click', function(event) { // doSearch(); // }, false ); searchInput.addEventListener( 'keyup', function( event ) { switch (event.keyCode) { case 13: event.preventDefault(); doSearch(); searchboxDirty = false; break; default: searchboxDirty = true; } }, false ); closeSearch(); } function openSearch() { if( !searchElement ) render(); searchElement.style.display = 'inline'; searchInput.focus(); searchInput.select(); } function closeSearch() { if( !searchElement ) render(); searchElement.style.display = 'none'; if(hilitor) hilitor.remove(); } function toggleSearch() { if( !searchElement ) render(); if (searchElement.style.display !== 'inline') { openSearch(); } else { closeSearch(); } } function doSearch() { //if there's been a change in the search term, perform a new search: if (searchboxDirty) { var searchstring = searchInput.value; if (searchstring === '') { if(hilitor) hilitor.remove(); matchedSlides = null; } else { //find the keyword amongst the slides hilitor = new Hilitor("slidecontent"); matchedSlides = hilitor.apply(searchstring); currentMatchedIndex = 0; } } if (matchedSlides) { //navigate to the next slide that has the keyword, wrapping to the first if necessary if (matchedSlides.length && (matchedSlides.length <= currentMatchedIndex)) { currentMatchedIndex = 0; } if (matchedSlides.length > currentMatchedIndex) { deck.slide(matchedSlides[currentMatchedIndex].h, matchedSlides[currentMatchedIndex].v); currentMatchedIndex++; } } } // Original JavaScript code by Chirp Internet: www.chirp.com.au // Please acknowledge use of this code by including this header. // 2/2013 jon: modified regex to display any match, not restricted to word boundaries. function Hilitor(id, tag) { var targetNode = document.getElementById(id) || document.body; var hiliteTag = tag || "EM"; var skipTags = new RegExp("^(?:" + hiliteTag + "|SCRIPT|FORM)$"); var colors = ["#ff6", "#a0ffff", "#9f9", "#f99", "#f6f"]; var wordColor = []; var colorIdx = 0; var matchRegex = ""; var matchingSlides = []; this.setRegex = function(input) { input = input.trim(); matchRegex = new RegExp("(" + input + ")","i"); } this.getRegex = function() { return matchRegex.toString().replace(/^\/\\b\(|\)\\b\/i$/g, "").replace(/\|/g, " "); } // recursively apply word highlighting this.hiliteWords = function(node) { if(node == undefined || !node) return; if(!matchRegex) return; if(skipTags.test(node.nodeName)) return; if(node.hasChildNodes()) { for(var i=0; i < node.childNodes.length; i++) this.hiliteWords(node.childNodes[i]); } if(node.nodeType == 3) { // NODE_TEXT var nv, regs; if((nv = node.nodeValue) && (regs = matchRegex.exec(nv))) { //find the slide's section element and save it in our list of matching slides var secnode = node; while (secnode != null && secnode.nodeName != 'SECTION') { secnode = secnode.parentNode; } var slideIndex = deck.getIndices(secnode); var slidelen = matchingSlides.length; var alreadyAdded = false; for (var i=0; i < slidelen; i++) { if ( (matchingSlides[i].h === slideIndex.h) && (matchingSlides[i].v === slideIndex.v) ) { alreadyAdded = true; } } if (! alreadyAdded) { matchingSlides.push(slideIndex); } if(!wordColor[regs[0].toLowerCase()]) { wordColor[regs[0].toLowerCase()] = colors[colorIdx++ % colors.length]; } var match = document.createElement(hiliteTag); match.appendChild(document.createTextNode(regs[0])); match.style.backgroundColor = wordColor[regs[0].toLowerCase()]; match.style.fontStyle = "inherit"; match.style.color = "#000"; var after = node.splitText(regs.index); after.nodeValue = after.nodeValue.substring(regs[0].length); node.parentNode.insertBefore(match, after); } } }; // remove highlighting this.remove = function() { var arr = document.getElementsByTagName(hiliteTag); var el; while(arr.length && (el = arr[0])) { el.parentNode.replaceChild(el.firstChild, el); } }; // start highlighting at target node this.apply = function(input) { if(input == undefined || !input) return; this.remove(); this.setRegex(input); this.hiliteWords(targetNode); return matchingSlides; }; } return { id: 'search', init: reveal => { deck = reveal; deck.registerKeyboardShortcut( 'CTRL + Shift + F', 'Search' ); document.addEventListener( 'keydown', function( event ) { if( event.key == "F" && (event.ctrlKey || event.metaKey) ) { //Control+Shift+f event.preventDefault(); toggleSearch(); } }, false ); }, open: openSearch, close: closeSearch, toggle: toggleSearch } }; export default Plugin;
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/search/search.js
plugin/search/search.js
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).RevealSearch=t()}(this,(function(){"use strict"; /*! * Handles finding a text string anywhere in the slides and showing the next occurrence to the user * by navigatating to that slide and highlighting it. * * @author Jon Snyder <snyder.jon@gmail.com>, February 2013 */return()=>{let e,t,n,o,i,l,s;function r(){t=document.createElement("div"),t.classList.add("searchbox"),t.style.position="absolute",t.style.top="10px",t.style.right="10px",t.style.zIndex=10,t.innerHTML='<input type="search" class="searchinput" placeholder="Search..." style="vertical-align: top;"/>\n\t\t</span>',n=t.querySelector(".searchinput"),n.style.width="240px",n.style.fontSize="14px",n.style.padding="4px 6px",n.style.color="#000",n.style.background="#fff",n.style.borderRadius="2px",n.style.border="0",n.style.outline="0",n.style.boxShadow="0 2px 18px rgba(0, 0, 0, 0.2)",n.style["-webkit-appearance"]="none",e.getRevealElement().appendChild(t),n.addEventListener("keyup",(function(t){if(13===t.keyCode)t.preventDefault(),function(){if(l){var t=n.value;""===t?(s&&s.remove(),o=null):(s=new f("slidecontent"),o=s.apply(t),i=0)}o&&(o.length&&o.length<=i&&(i=0),o.length>i&&(e.slide(o[i].h,o[i].v),i++))}(),l=!1;else l=!0}),!1),d()}function a(){t||r(),t.style.display="inline",n.focus(),n.select()}function d(){t||r(),t.style.display="none",s&&s.remove()}function c(){t||r(),"inline"!==t.style.display?a():d()}function f(t,n){var o=document.getElementById(t)||document.body,i=n||"EM",l=new RegExp("^(?:"+i+"|SCRIPT|FORM)$"),s=["#ff6","#a0ffff","#9f9","#f99","#f6f"],r=[],a=0,d="",c=[];this.setRegex=function(e){e=e.trim(),d=new RegExp("("+e+")","i")},this.getRegex=function(){return d.toString().replace(/^\/\\b\(|\)\\b\/i$/g,"").replace(/\|/g," ")},this.hiliteWords=function(t){if(null!=t&&t&&d&&!l.test(t.nodeName)){if(t.hasChildNodes())for(var n=0;n<t.childNodes.length;n++)this.hiliteWords(t.childNodes[n]);var o,f;if(3==t.nodeType)if((o=t.nodeValue)&&(f=d.exec(o))){for(var u=t;null!=u&&"SECTION"!=u.nodeName;)u=u.parentNode;var p=e.getIndices(u),h=c.length,y=!1;for(n=0;n<h;n++)c[n].h===p.h&&c[n].v===p.v&&(y=!0);y||c.push(p),r[f[0].toLowerCase()]||(r[f[0].toLowerCase()]=s[a++%s.length]);var g=document.createElement(i);g.appendChild(document.createTextNode(f[0])),g.style.backgroundColor=r[f[0].toLowerCase()],g.style.fontStyle="inherit",g.style.color="#000";var v=t.splitText(f.index);v.nodeValue=v.nodeValue.substring(f[0].length),t.parentNode.insertBefore(g,v)}}},this.remove=function(){for(var e,t=document.getElementsByTagName(i);t.length&&(e=t[0]);)e.parentNode.replaceChild(e.firstChild,e)},this.apply=function(e){if(null!=e&&e)return this.remove(),this.setRegex(e),this.hiliteWords(o),c}}return{id:"search",init:t=>{e=t,e.registerKeyboardShortcut("CTRL + Shift + F","Search"),document.addEventListener("keydown",(function(e){"F"==e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),c())}),!1)},open:a,close:d,toggle:c}}}));
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/search/search.esm.js
plugin/search/search.esm.js
/*! * Handles finding a text string anywhere in the slides and showing the next occurrence to the user * by navigatating to that slide and highlighting it. * * @author Jon Snyder <snyder.jon@gmail.com>, February 2013 */ const e=()=>{let e,t,n,l,o,i,r;function s(){t=document.createElement("div"),t.classList.add("searchbox"),t.style.position="absolute",t.style.top="10px",t.style.right="10px",t.style.zIndex=10,t.innerHTML='<input type="search" class="searchinput" placeholder="Search..." style="vertical-align: top;"/>\n\t\t</span>',n=t.querySelector(".searchinput"),n.style.width="240px",n.style.fontSize="14px",n.style.padding="4px 6px",n.style.color="#000",n.style.background="#fff",n.style.borderRadius="2px",n.style.border="0",n.style.outline="0",n.style.boxShadow="0 2px 18px rgba(0, 0, 0, 0.2)",n.style["-webkit-appearance"]="none",e.getRevealElement().appendChild(t),n.addEventListener("keyup",(function(t){if(13===t.keyCode)t.preventDefault(),function(){if(i){var t=n.value;""===t?(r&&r.remove(),l=null):(r=new p("slidecontent"),l=r.apply(t),o=0)}l&&(l.length&&l.length<=o&&(o=0),l.length>o&&(e.slide(l[o].h,l[o].v),o++))}(),i=!1;else i=!0}),!1),d()}function a(){t||s(),t.style.display="inline",n.focus(),n.select()}function d(){t||s(),t.style.display="none",r&&r.remove()}function c(){t||s(),"inline"!==t.style.display?a():d()}function p(t,n){var l=document.getElementById(t)||document.body,o=n||"EM",i=new RegExp("^(?:"+o+"|SCRIPT|FORM)$"),r=["#ff6","#a0ffff","#9f9","#f99","#f6f"],s=[],a=0,d="",c=[];this.setRegex=function(e){e=e.trim(),d=new RegExp("("+e+")","i")},this.getRegex=function(){return d.toString().replace(/^\/\\b\(|\)\\b\/i$/g,"").replace(/\|/g," ")},this.hiliteWords=function(t){if(null!=t&&t&&d&&!i.test(t.nodeName)){if(t.hasChildNodes())for(var n=0;n<t.childNodes.length;n++)this.hiliteWords(t.childNodes[n]);var l,p;if(3==t.nodeType)if((l=t.nodeValue)&&(p=d.exec(l))){for(var u=t;null!=u&&"SECTION"!=u.nodeName;)u=u.parentNode;var f=e.getIndices(u),h=c.length,y=!1;for(n=0;n<h;n++)c[n].h===f.h&&c[n].v===f.v&&(y=!0);y||c.push(f),s[p[0].toLowerCase()]||(s[p[0].toLowerCase()]=r[a++%r.length]);var g=document.createElement(o);g.appendChild(document.createTextNode(p[0])),g.style.backgroundColor=s[p[0].toLowerCase()],g.style.fontStyle="inherit",g.style.color="#000";var v=t.splitText(p.index);v.nodeValue=v.nodeValue.substring(p[0].length),t.parentNode.insertBefore(g,v)}}},this.remove=function(){for(var e,t=document.getElementsByTagName(o);t.length&&(e=t[0]);)e.parentNode.replaceChild(e.firstChild,e)},this.apply=function(e){if(null!=e&&e)return this.remove(),this.setRegex(e),this.hiliteWords(l),c}}return{id:"search",init:t=>{e=t,e.registerKeyboardShortcut("CTRL + Shift + F","Search"),document.addEventListener("keydown",(function(e){"F"==e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),c())}),!1)},open:a,close:d,toggle:c}};export{e as default};
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/highlight/plugin.js
plugin/highlight/plugin.js
import hljs from 'highlight.js'; /* highlightjs-line-numbers.js 2.8.0 | (C) 2018 Yauheni Pakala | MIT License | github.com/wcoder/highlightjs-line-numbers.js */ !function(r,o){"use strict";var e,i="hljs-ln",l="hljs-ln-line",h="hljs-ln-code",s="hljs-ln-numbers",c="hljs-ln-n",m="data-line-number",a=/\r\n|\r|\n/g;function u(e){for(var n=e.toString(),t=e.anchorNode;"TD"!==t.nodeName;)t=t.parentNode;for(var r=e.focusNode;"TD"!==r.nodeName;)r=r.parentNode;var o=parseInt(t.dataset.lineNumber),a=parseInt(r.dataset.lineNumber);if(o==a)return n;var i,l=t.textContent,s=r.textContent;for(a<o&&(i=o,o=a,a=i,i=l,l=s,s=i);0!==n.indexOf(l);)l=l.slice(1);for(;-1===n.lastIndexOf(s);)s=s.slice(0,-1);for(var c=l,u=function(e){for(var n=e;"TABLE"!==n.nodeName;)n=n.parentNode;return n}(t),d=o+1;d<a;++d){var f=p('.{0}[{1}="{2}"]',[h,m,d]);c+="\n"+u.querySelector(f).textContent}return c+="\n"+s}function n(e){try{var n=o.querySelectorAll("code.hljs,code.nohighlight");for(var t in n)n.hasOwnProperty(t)&&(n[t].classList.contains("nohljsln")||d(n[t],e))}catch(e){r.console.error("LineNumbers error: ",e)}}function d(e,n){if("object"==typeof e)e.innerHTML=f(e,n)}function f(e,n){var t,r,o=(t=e,{singleLine:function(e){return!!e.singleLine&&e.singleLine}(r=(r=n)||{}),startFrom:function(e,n){var t=1;isFinite(n.startFrom)&&(t=n.startFrom);var r=function(e,n){return e.hasAttribute(n)?e.getAttribute(n):null}(e,"data-ln-start-from");return null!==r&&(t=function(e,n){if(!e)return n;var t=Number(e);return isFinite(t)?t:n}(r,1)),t}(t,r)});return function e(n){var t=n.childNodes;for(var r in t){var o;t.hasOwnProperty(r)&&(o=t[r],0<(o.textContent.trim().match(a)||[]).length&&(0<o.childNodes.length?e(o):v(o.parentNode)))}}(e),function(e,n){var t=g(e);""===t[t.length-1].trim()&&t.pop();if(1<t.length||n.singleLine){for(var r="",o=0,a=t.length;o<a;o++)r+=p('<tr><td class="{0} {1}" {3}="{5}"><div class="{2}" {3}="{5}"></div></td><td class="{0} {4}" {3}="{5}">{6}</td></tr>',[l,s,c,m,h,o+n.startFrom,0<t[o].length?t[o]:" "]);return p('<table class="{0}">{1}</table>',[i,r])}return e}(e.innerHTML,o)}function v(e){var n=e.className;if(/hljs-/.test(n)){for(var t=g(e.innerHTML),r=0,o="";r<t.length;r++){o+=p('<span class="{0}">{1}</span>\n',[n,0<t[r].length?t[r]:" "])}e.innerHTML=o.trim()}}function g(e){return 0===e.length?[]:e.split(a)}function p(e,t){return e.replace(/\{(\d+)\}/g,function(e,n){return void 0!==t[n]?t[n]:e})}hljs?(hljs.initLineNumbersOnLoad=function(e){"interactive"===o.readyState||"complete"===o.readyState?n(e):r.addEventListener("DOMContentLoaded",function(){n(e)})},hljs.lineNumbersBlock=d,hljs.lineNumbersValue=function(e,n){if("string"!=typeof e)return;var t=document.createElement("code");return t.innerHTML=e,f(t,n)},(e=o.createElement("style")).type="text/css",e.innerHTML=p(".{0}{border-collapse:collapse}.{0} td{padding:0}.{1}:before{content:attr({2})}",[i,c,m]),o.getElementsByTagName("head")[0].appendChild(e)):r.console.error("highlight.js not detected!"),document.addEventListener("copy",function(e){var n,t=window.getSelection();!function(e){for(var n=e;n;){if(n.className&&-1!==n.className.indexOf("hljs-ln-code"))return 1;n=n.parentNode}}(t.anchorNode)||(n=-1!==window.navigator.userAgent.indexOf("Edge")?u(t):t.toString(),e.clipboardData.setData("text/plain",n),e.preventDefault())})}(window,document); /*! * reveal.js plugin that adds syntax highlight support. */ const Plugin = { id: 'highlight', HIGHLIGHT_STEP_DELIMITER: '|', HIGHLIGHT_LINE_DELIMITER: ',', HIGHLIGHT_LINE_RANGE_DELIMITER: '-', hljs, /** * Highlights code blocks within the given deck. * * Note that this can be called multiple times if * there are multiple presentations on one page. * * @param {Reveal} reveal the reveal.js instance */ init: function( reveal ) { // Read the plugin config options and provide fallbacks let config = reveal.getConfig().highlight || {}; config.highlightOnLoad = typeof config.highlightOnLoad === 'boolean' ? config.highlightOnLoad : true; config.escapeHTML = typeof config.escapeHTML === 'boolean' ? config.escapeHTML : true; Array.from( reveal.getRevealElement().querySelectorAll( 'pre code' ) ).forEach( block => { block.parentNode.classList.add('code-wrapper'); // Code can optionally be wrapped in script template to avoid // HTML being parsed by the browser (i.e. when you need to // include <, > or & in your code). let substitute = block.querySelector( 'script[type="text/template"]' ); if( substitute ) { // textContent handles the HTML entity escapes for us block.textContent = substitute.innerHTML; } // Trim whitespace if the "data-trim" attribute is present if( block.hasAttribute( 'data-trim' ) && typeof block.innerHTML.trim === 'function' ) { block.innerHTML = betterTrim( block ); } // Escape HTML tags unless the "data-noescape" attribute is present if( config.escapeHTML && !block.hasAttribute( 'data-noescape' )) { block.innerHTML = block.innerHTML.replace( /</g,"&lt;").replace(/>/g, '&gt;' ); } // Re-highlight when focus is lost (for contenteditable code) block.addEventListener( 'focusout', function( event ) { hljs.highlightElement( event.currentTarget ); }, false ); } ); // Triggers a callback function before we trigger highlighting if( typeof config.beforeHighlight === 'function' ) { config.beforeHighlight( hljs ); } // Run initial highlighting for all code if( config.highlightOnLoad ) { Array.from( reveal.getRevealElement().querySelectorAll( 'pre code' ) ).forEach( block => { Plugin.highlightBlock( block ); } ); } // If we're printing to PDF, scroll the code highlights of // all blocks in the deck into view at once reveal.on( 'pdf-ready', function() { [].slice.call( reveal.getRevealElement().querySelectorAll( 'pre code[data-line-numbers].current-fragment' ) ).forEach( function( block ) { Plugin.scrollHighlightedLineIntoView( block, {}, true ); } ); } ); }, /** * Highlights a code block. If the <code> node has the * 'data-line-numbers' attribute we also generate slide * numbers. * * If the block contains multiple line highlight steps, * we clone the block and create a fragment for each step. */ highlightBlock: function( block ) { hljs.highlightElement( block ); // Don't generate line numbers for empty code blocks if( block.innerHTML.trim().length === 0 ) return; if( block.hasAttribute( 'data-line-numbers' ) ) { hljs.lineNumbersBlock( block, { singleLine: true } ); var scrollState = { currentBlock: block }; // If there is more than one highlight step, generate // fragments var highlightSteps = Plugin.deserializeHighlightSteps( block.getAttribute( 'data-line-numbers' ) ); if( highlightSteps.length > 1 ) { // If the original code block has a fragment-index, // each clone should follow in an incremental sequence var fragmentIndex = parseInt( block.getAttribute( 'data-fragment-index' ), 10 ); if( typeof fragmentIndex !== 'number' || isNaN( fragmentIndex ) ) { fragmentIndex = null; } // Generate fragments for all steps except the original block highlightSteps.slice(1).forEach( function( highlight ) { var fragmentBlock = block.cloneNode( true ); fragmentBlock.setAttribute( 'data-line-numbers', Plugin.serializeHighlightSteps( [ highlight ] ) ); fragmentBlock.classList.add( 'fragment' ); block.parentNode.appendChild( fragmentBlock ); Plugin.highlightLines( fragmentBlock ); if( typeof fragmentIndex === 'number' ) { fragmentBlock.setAttribute( 'data-fragment-index', fragmentIndex ); fragmentIndex += 1; } else { fragmentBlock.removeAttribute( 'data-fragment-index' ); } // Scroll highlights into view as we step through them fragmentBlock.addEventListener( 'visible', Plugin.scrollHighlightedLineIntoView.bind( Plugin, fragmentBlock, scrollState ) ); fragmentBlock.addEventListener( 'hidden', Plugin.scrollHighlightedLineIntoView.bind( Plugin, fragmentBlock.previousElementSibling, scrollState ) ); } ); block.removeAttribute( 'data-fragment-index' ); block.setAttribute( 'data-line-numbers', Plugin.serializeHighlightSteps( [ highlightSteps[0] ] ) ); } // Scroll the first highlight into view when the slide // becomes visible. Note supported in IE11 since it lacks // support for Element.closest. var slide = typeof block.closest === 'function' ? block.closest( 'section:not(.stack)' ) : null; if( slide ) { var scrollFirstHighlightIntoView = function() { Plugin.scrollHighlightedLineIntoView( block, scrollState, true ); slide.removeEventListener( 'visible', scrollFirstHighlightIntoView ); } slide.addEventListener( 'visible', scrollFirstHighlightIntoView ); } Plugin.highlightLines( block ); } }, /** * Animates scrolling to the first highlighted line * in the given code block. */ scrollHighlightedLineIntoView: function( block, scrollState, skipAnimation ) { cancelAnimationFrame( scrollState.animationFrameID ); // Match the scroll position of the currently visible // code block if( scrollState.currentBlock ) { block.scrollTop = scrollState.currentBlock.scrollTop; } // Remember the current code block so that we can match // its scroll position when showing/hiding fragments scrollState.currentBlock = block; var highlightBounds = this.getHighlightedLineBounds( block ) var viewportHeight = block.offsetHeight; // Subtract padding from the viewport height var blockStyles = getComputedStyle( block ); viewportHeight -= parseInt( blockStyles.paddingTop ) + parseInt( blockStyles.paddingBottom ); // Scroll position which centers all highlights var startTop = block.scrollTop; var targetTop = highlightBounds.top + ( Math.min( highlightBounds.bottom - highlightBounds.top, viewportHeight ) - viewportHeight ) / 2; // Account for offsets in position applied to the // <table> that holds our lines of code var lineTable = block.querySelector( '.hljs-ln' ); if( lineTable ) targetTop += lineTable.offsetTop - parseInt( blockStyles.paddingTop ); // Make sure the scroll target is within bounds targetTop = Math.max( Math.min( targetTop, block.scrollHeight - viewportHeight ), 0 ); if( skipAnimation === true || startTop === targetTop ) { block.scrollTop = targetTop; } else { // Don't attempt to scroll if there is no overflow if( block.scrollHeight <= viewportHeight ) return; var time = 0; var animate = function() { time = Math.min( time + 0.02, 1 ); // Update our eased scroll position block.scrollTop = startTop + ( targetTop - startTop ) * Plugin.easeInOutQuart( time ); // Keep animating unless we've reached the end if( time < 1 ) { scrollState.animationFrameID = requestAnimationFrame( animate ); } }; animate(); } }, /** * The easing function used when scrolling. */ easeInOutQuart: function( t ) { // easeInOutQuart return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t; }, getHighlightedLineBounds: function( block ) { var highlightedLines = block.querySelectorAll( '.highlight-line' ); if( highlightedLines.length === 0 ) { return { top: 0, bottom: 0 }; } else { var firstHighlight = highlightedLines[0]; var lastHighlight = highlightedLines[ highlightedLines.length -1 ]; return { top: firstHighlight.offsetTop, bottom: lastHighlight.offsetTop + lastHighlight.offsetHeight } } }, /** * Visually emphasize specific lines within a code block. * This only works on blocks with line numbering turned on. * * @param {HTMLElement} block a <code> block * @param {String} [linesToHighlight] The lines that should be * highlighted in this format: * "1" = highlights line 1 * "2,5" = highlights lines 2 & 5 * "2,5-7" = highlights lines 2, 5, 6 & 7 */ highlightLines: function( block, linesToHighlight ) { var highlightSteps = Plugin.deserializeHighlightSteps( linesToHighlight || block.getAttribute( 'data-line-numbers' ) ); if( highlightSteps.length ) { highlightSteps[0].forEach( function( highlight ) { var elementsToHighlight = []; // Highlight a range if( typeof highlight.end === 'number' ) { elementsToHighlight = [].slice.call( block.querySelectorAll( 'table tr:nth-child(n+'+highlight.start+'):nth-child(-n+'+highlight.end+')' ) ); } // Highlight a single line else if( typeof highlight.start === 'number' ) { elementsToHighlight = [].slice.call( block.querySelectorAll( 'table tr:nth-child('+highlight.start+')' ) ); } if( elementsToHighlight.length ) { elementsToHighlight.forEach( function( lineElement ) { lineElement.classList.add( 'highlight-line' ); } ); block.classList.add( 'has-highlights' ); } } ); } }, /** * Parses and formats a user-defined string of line * numbers to highlight. * * @example * Plugin.deserializeHighlightSteps( '1,2|3,5-10' ) * // [ * // [ { start: 1 }, { start: 2 } ], * // [ { start: 3 }, { start: 5, end: 10 } ] * // ] */ deserializeHighlightSteps: function( highlightSteps ) { // Remove whitespace highlightSteps = highlightSteps.replace( /\s/g, '' ); // Divide up our line number groups highlightSteps = highlightSteps.split( Plugin.HIGHLIGHT_STEP_DELIMITER ); return highlightSteps.map( function( highlights ) { return highlights.split( Plugin.HIGHLIGHT_LINE_DELIMITER ).map( function( highlight ) { // Parse valid line numbers if( /^[\d-]+$/.test( highlight ) ) { highlight = highlight.split( Plugin.HIGHLIGHT_LINE_RANGE_DELIMITER ); var lineStart = parseInt( highlight[0], 10 ), lineEnd = parseInt( highlight[1], 10 ); if( isNaN( lineEnd ) ) { return { start: lineStart }; } else { return { start: lineStart, end: lineEnd }; } } // If no line numbers are provided, no code will be highlighted else { return {}; } } ); } ); }, /** * Serializes parsed line number data into a string so * that we can store it in the DOM. */ serializeHighlightSteps: function( highlightSteps ) { return highlightSteps.map( function( highlights ) { return highlights.map( function( highlight ) { // Line range if( typeof highlight.end === 'number' ) { return highlight.start + Plugin.HIGHLIGHT_LINE_RANGE_DELIMITER + highlight.end; } // Single line else if( typeof highlight.start === 'number' ) { return highlight.start; } // All lines else { return ''; } } ).join( Plugin.HIGHLIGHT_LINE_DELIMITER ); } ).join( Plugin.HIGHLIGHT_STEP_DELIMITER ); } } // Function to perform a better "data-trim" on code snippets // Will slice an indentation amount on each line of the snippet (amount based on the line having the lowest indentation length) function betterTrim(snippetEl) { // Helper functions function trimLeft(val) { // Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill return val.replace(/^[\s\uFEFF\xA0]+/g, ''); } function trimLineBreaks(input) { var lines = input.split('\n'); // Trim line-breaks from the beginning for (var i = 0; i < lines.length; i++) { if (lines[i].trim() === '') { lines.splice(i--, 1); } else break; } // Trim line-breaks from the end for (var i = lines.length-1; i >= 0; i--) { if (lines[i].trim() === '') { lines.splice(i, 1); } else break; } return lines.join('\n'); } // Main function for betterTrim() return (function(snippetEl) { var content = trimLineBreaks(snippetEl.innerHTML); var lines = content.split('\n'); // Calculate the minimum amount to remove on each line start of the snippet (can be 0) var pad = lines.reduce(function(acc, line) { if (line.length > 0 && trimLeft(line).length > 0 && acc > line.length - trimLeft(line).length) { return line.length - trimLeft(line).length; } return acc; }, Number.POSITIVE_INFINITY); // Slice each line with this amount return lines.map(function(line, index) { return line.slice(pad); }) .join('\n'); })(snippetEl); } export default () => Plugin;
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/highlight/highlight.esm.js
plugin/highlight/highlight.esm.js
function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function t(e){return e instanceof Map?e.clear=e.delete=e.set=function(){throw new Error("map is read-only")}:e instanceof Set&&(e.add=e.clear=e.delete=function(){throw new Error("set is read-only")}),Object.freeze(e),Object.getOwnPropertyNames(e).forEach((a=>{const n=e[a],i=typeof n;"object"!==i&&"function"!==i||Object.isFrozen(n)||t(n)})),e}class a{constructor(e){void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function n(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}function i(e,...t){const a=Object.create(null);for(const t in e)a[t]=e[t];return t.forEach((function(e){for(const t in e)a[t]=e[t]})),a}const r=e=>!!e.scope;class o{constructor(e,t){this.buffer="",this.classPrefix=t.classPrefix,e.walk(this)}addText(e){this.buffer+=n(e)}openNode(e){if(!r(e))return;const t=((e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){const a=e.split(".");return[`${t}${a.shift()}`,...a.map(((e,t)=>`${e}${"_".repeat(t+1)}`))].join(" ")}return`${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){r(e)&&(this.buffer+="</span>")}value(){return this.buffer}span(e){this.buffer+=`<span class="${e}">`}}const s=(e={})=>{const t={children:[]};return Object.assign(t,e),t};class l{constructor(){this.rootNode=s(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){const t=s({scope:e});this.add(t),this.stack.push(t)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){return"string"==typeof t?e.addText(t):t.children&&(e.openNode(t),t.children.forEach((t=>this._walk(e,t))),e.closeNode(t)),e}static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every((e=>"string"==typeof e))?e.children=[e.children.join("")]:e.children.forEach((e=>{l._collapse(e)})))}}class c extends l{constructor(e){super(),this.options=e}addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){this.closeNode()}__addSublanguage(e,t){const a=e.root;t&&(a.scope=`language:${t}`),this.add(a)}toHTML(){return new o(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function _(e){return e?"string"==typeof e?e:e.source:null}function d(e){return u("(?=",e,")")}function m(e){return u("(?:",e,")*")}function p(e){return u("(?:",e,")?")}function u(...e){return e.map((e=>_(e))).join("")}function g(...e){const t=function(e){const t=e[e.length-1];return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return"("+(t.capture?"":"?:")+e.map((e=>_(e))).join("|")+")"}function E(e){return new RegExp(e.toString()+"|").exec("").length-1}const S=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function b(e,{joinWith:t}){let a=0;return e.map((e=>{a+=1;const t=a;let n=_(e),i="";for(;n.length>0;){const e=S.exec(n);if(!e){i+=n;break}i+=n.substring(0,e.index),n=n.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?i+="\\"+String(Number(e[1])+t):(i+=e[0],"("===e[0]&&a++)}return i})).map((e=>`(${e})`)).join(t)}const T="[a-zA-Z]\\w*",C="[a-zA-Z_]\\w*",f="\\b\\d+(\\.\\d+)?",R="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",N="\\b(0b[01]+)",O={begin:"\\\\[\\s\\S]",relevance:0},h={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[O]},v={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[O]},I=function(e,t,a={}){const n=i({scope:"comment",begin:e,end:t,contains:[]},a);n.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const r=g("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return n.contains.push({begin:u(/[ ]+/,"(",r,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),n},A=I("//","$"),y=I("/\\*","\\*/"),D=I("#","$"),M={scope:"number",begin:f,relevance:0},L={scope:"number",begin:R,relevance:0},x={scope:"number",begin:N,relevance:0},w={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[O,{begin:/\[/,end:/\]/,relevance:0,contains:[O]}]},P={scope:"title",begin:T,relevance:0},k={scope:"title",begin:C,relevance:0},U={begin:"\\.\\s*"+C,relevance:0};var F=Object.freeze({__proto__:null,APOS_STRING_MODE:h,BACKSLASH_ESCAPE:O,BINARY_NUMBER_MODE:x,BINARY_NUMBER_RE:N,COMMENT:I,C_BLOCK_COMMENT_MODE:y,C_LINE_COMMENT_MODE:A,C_NUMBER_MODE:L,C_NUMBER_RE:R,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}})},HASH_COMMENT_MODE:D,IDENT_RE:T,MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:U,NUMBER_MODE:M,NUMBER_RE:f,PHRASAL_WORDS_MODE:{begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},QUOTE_STRING_MODE:v,REGEXP_MODE:w,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const t=/^#![ ]*\//;return e.binary&&(e.begin=u(t,/.*\b/,e.binary,/\b.*/)),i({scope:"meta",begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch()}},e)},TITLE_MODE:P,UNDERSCORE_IDENT_RE:C,UNDERSCORE_TITLE_MODE:k});function B(e,t){"."===e.input[e.index-1]&&t.ignoreMatch()}function G(e,t){void 0!==e.className&&(e.scope=e.className,delete e.className)}function Y(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=B,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,void 0===e.relevance&&(e.relevance=0))}function H(e,t){Array.isArray(e.illegal)&&(e.illegal=g(...e.illegal))}function V(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match}}function q(e,t){void 0===e.relevance&&(e.relevance=1)}const z=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");const a=Object.assign({},e);Object.keys(e).forEach((t=>{delete e[t]})),e.keywords=a.keywords,e.begin=u(a.beforeMatch,d(a.begin)),e.starts={relevance:0,contains:[Object.assign(a,{endsParent:!0})]},e.relevance=0,delete a.beforeMatch},$=["of","and","for","in","not","or","if","then","parent","list","value"],W="keyword";function Q(e,t,a=W){const n=Object.create(null);return"string"==typeof e?i(a,e.split(" ")):Array.isArray(e)?i(a,e):Object.keys(e).forEach((function(a){Object.assign(n,Q(e[a],t,a))})),n;function i(e,a){t&&(a=a.map((e=>e.toLowerCase()))),a.forEach((function(t){const a=t.split("|");n[a[0]]=[e,K(a[0],a[1])]}))}}function K(e,t){return t?Number(t):function(e){return $.includes(e.toLowerCase())}(e)?0:1}const j={},X=e=>{console.error(e)},Z=(e,...t)=>{console.log(`WARN: ${e}`,...t)},J=(e,t)=>{j[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),j[`${e}/${t}`]=!0)},ee=new Error;function te(e,t,{key:a}){let n=0;const i=e[a],r={},o={};for(let e=1;e<=t.length;e++)o[e+n]=i[e],r[e+n]=!0,n+=E(t[e-1]);e[a]=o,e[a]._emit=r,e[a]._multi=!0}function ae(e){!function(e){e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,delete e.scope)}(e),"string"==typeof e.beginScope&&(e.beginScope={_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope}),function(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw X("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),ee;if("object"!=typeof e.beginScope||null===e.beginScope)throw X("beginScope must be object"),ee;te(e,e.begin,{key:"beginScope"}),e.begin=b(e.begin,{joinWith:""})}}(e),function(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw X("skip, excludeEnd, returnEnd not compatible with endScope: {}"),ee;if("object"!=typeof e.endScope||null===e.endScope)throw X("endScope must be object"),ee;te(e,e.end,{key:"endScope"}),e.end=b(e.end,{joinWith:""})}}(e)}function ne(e){function t(t,a){return new RegExp(_(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(a?"g":""))}class a{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=E(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map((e=>e[1]));this.matcherRe=t(b(e,{joinWith:"|"}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;const t=this.matcherRe.exec(e);if(!t)return null;const a=t.findIndex(((e,t)=>t>0&&void 0!==e)),n=this.matchIndexes[a];return t.splice(0,a),Object.assign(t,n)}}class n{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const t=new a;return this.rules.slice(e).forEach((([e,a])=>t.addRule(e,a))),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,t){this.rules.push([e,t]),"begin"===t.type&&this.count++}exec(e){const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let a=t.exec(e);if(this.resumingScanAtSamePosition())if(a&&a.index===this.lastIndex);else{const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,a=t.exec(e)}return a&&(this.regexIndex+=a.position+1,this.regexIndex===this.count&&this.considerAll()),a}}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=i(e.classNameAliases||{}),function a(r,o){const s=r;if(r.isCompiled)return s;[G,V,ae,z].forEach((e=>e(r,o))),e.compilerExtensions.forEach((e=>e(r,o))),r.__beforeBegin=null,[Y,H,q].forEach((e=>e(r,o))),r.isCompiled=!0;let l=null;return"object"==typeof r.keywords&&r.keywords.$pattern&&(r.keywords=Object.assign({},r.keywords),l=r.keywords.$pattern,delete r.keywords.$pattern),l=l||/\w+/,r.keywords&&(r.keywords=Q(r.keywords,e.case_insensitive)),s.keywordPatternRe=t(l,!0),o&&(r.begin||(r.begin=/\B|\b/),s.beginRe=t(s.begin),r.end||r.endsWithParent||(r.end=/\B|\b/),r.end&&(s.endRe=t(s.end)),s.terminatorEnd=_(s.end)||"",r.endsWithParent&&o.terminatorEnd&&(s.terminatorEnd+=(r.end?"|":"")+o.terminatorEnd)),r.illegal&&(s.illegalRe=t(r.illegal)),r.contains||(r.contains=[]),r.contains=[].concat(...r.contains.map((function(e){return function(e){e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map((function(t){return i(e,{variants:null},t)})));if(e.cachedVariants)return e.cachedVariants;if(ie(e))return i(e,{starts:e.starts?i(e.starts):null});if(Object.isFrozen(e))return i(e);return e}("self"===e?r:e)}))),r.contains.forEach((function(e){a(e,s)})),r.starts&&a(r.starts,o),s.matcher=function(e){const t=new n;return e.contains.forEach((e=>t.addRule(e.begin,{rule:e,type:"begin"}))),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t}(s),s}(e)}function ie(e){return!!e&&(e.endsWithParent||ie(e.starts))}class re extends Error{constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t}}const oe=n,se=i,le=Symbol("nomatch"),ce=function(e){const n=Object.create(null),i=Object.create(null),r=[];let o=!0;const s="Could not find the language '{}', did you forget to load/include a language module?",l={disableAutodetect:!0,name:"Plain text",contains:[]};let _={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:c};function E(e){return _.noHighlightRe.test(e)}function S(e,t,a){let n="",i="";"object"==typeof t?(n=e,a=t.ignoreIllegals,i=t.language):(J("10.7.0","highlight(lang, code, ...args) has been deprecated."),J("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),i=e,n=t),void 0===a&&(a=!0);const r={code:n,language:i};v("before:highlight",r);const o=r.result?r.result:b(r.language,r.code,a);return o.code=r.code,v("after:highlight",o),o}function b(e,t,i,r){const l=Object.create(null);function c(){if(!v.keywords)return void A.addText(y);let e=0;v.keywordPatternRe.lastIndex=0;let t=v.keywordPatternRe.exec(y),a="";for(;t;){a+=y.substring(e,t.index);const i=R.case_insensitive?t[0].toLowerCase():t[0],r=(n=i,v.keywords[n]);if(r){const[e,n]=r;if(A.addText(a),a="",l[i]=(l[i]||0)+1,l[i]<=7&&(D+=n),e.startsWith("_"))a+=t[0];else{const a=R.classNameAliases[e]||e;m(t[0],a)}}else a+=t[0];e=v.keywordPatternRe.lastIndex,t=v.keywordPatternRe.exec(y)}var n;a+=y.substring(e),A.addText(a)}function d(){null!=v.subLanguage?function(){if(""===y)return;let e=null;if("string"==typeof v.subLanguage){if(!n[v.subLanguage])return void A.addText(y);e=b(v.subLanguage,y,!0,I[v.subLanguage]),I[v.subLanguage]=e._top}else e=T(y,v.subLanguage.length?v.subLanguage:null);v.relevance>0&&(D+=e.relevance),A.__addSublanguage(e._emitter,e.language)}():c(),y=""}function m(e,t){""!==e&&(A.startScope(t),A.addText(e),A.endScope())}function p(e,t){let a=1;const n=t.length-1;for(;a<=n;){if(!e._emit[a]){a++;continue}const n=R.classNameAliases[e[a]]||e[a],i=t[a];n?m(i,n):(y=i,c(),y=""),a++}}function u(e,t){return e.scope&&"string"==typeof e.scope&&A.openNode(R.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(m(y,R.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),y=""):e.beginScope._multi&&(p(e.beginScope,t),y="")),v=Object.create(e,{parent:{value:v}}),v}function g(e,t,n){let i=function(e,t){const a=e&&e.exec(t);return a&&0===a.index}(e.endRe,n);if(i){if(e["on:end"]){const n=new a(e);e["on:end"](t,n),n.isMatchIgnored&&(i=!1)}if(i){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return g(e.parent,t,n)}function E(e){return 0===v.matcher.regexIndex?(y+=e[0],1):(x=!0,0)}function S(e){const a=e[0],n=t.substring(e.index),i=g(v,e,n);if(!i)return le;const r=v;v.endScope&&v.endScope._wrap?(d(),m(a,v.endScope._wrap)):v.endScope&&v.endScope._multi?(d(),p(v.endScope,e)):r.skip?y+=a:(r.returnEnd||r.excludeEnd||(y+=a),d(),r.excludeEnd&&(y=a));do{v.scope&&A.closeNode(),v.skip||v.subLanguage||(D+=v.relevance),v=v.parent}while(v!==i.parent);return i.starts&&u(i.starts,e),r.returnEnd?0:a.length}let C={};function f(n,r){const s=r&&r[0];if(y+=n,null==s)return d(),0;if("begin"===C.type&&"end"===r.type&&C.index===r.index&&""===s){if(y+=t.slice(r.index,r.index+1),!o){const t=new Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=C.rule,t}return 1}if(C=r,"begin"===r.type)return function(e){const t=e[0],n=e.rule,i=new a(n),r=[n.__beforeBegin,n["on:begin"]];for(const a of r)if(a&&(a(e,i),i.isMatchIgnored))return E(t);return n.skip?y+=t:(n.excludeBegin&&(y+=t),d(),n.returnBegin||n.excludeBegin||(y=t)),u(n,e),n.returnBegin?0:t.length}(r);if("illegal"===r.type&&!i){const e=new Error('Illegal lexeme "'+s+'" for mode "'+(v.scope||"<unnamed>")+'"');throw e.mode=v,e}if("end"===r.type){const e=S(r);if(e!==le)return e}if("illegal"===r.type&&""===s)return 1;if(L>1e5&&L>3*r.index){throw new Error("potential infinite loop, way more iterations than matches")}return y+=s,s.length}const R=N(e);if(!R)throw X(s.replace("{}",e)),new Error('Unknown language: "'+e+'"');const O=ne(R);let h="",v=r||O;const I={},A=new _.__emitter(_);!function(){const e=[];for(let t=v;t!==R;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach((e=>A.openNode(e)))}();let y="",D=0,M=0,L=0,x=!1;try{if(R.__emitTokens)R.__emitTokens(t,A);else{for(v.matcher.considerAll();;){L++,x?x=!1:v.matcher.considerAll(),v.matcher.lastIndex=M;const e=v.matcher.exec(t);if(!e)break;const a=f(t.substring(M,e.index),e);M=e.index+a}f(t.substring(M))}return A.finalize(),h=A.toHTML(),{language:e,value:h,relevance:D,illegal:!1,_emitter:A,_top:v}}catch(a){if(a.message&&a.message.includes("Illegal"))return{language:e,value:oe(t),illegal:!0,relevance:0,_illegalBy:{message:a.message,index:M,context:t.slice(M-100,M+100),mode:a.mode,resultSoFar:h},_emitter:A};if(o)return{language:e,value:oe(t),illegal:!1,relevance:0,errorRaised:a,_emitter:A,_top:v};throw a}}function T(e,t){t=t||_.languages||Object.keys(n);const a=function(e){const t={value:oe(e),illegal:!1,relevance:0,_top:l,_emitter:new _.__emitter(_)};return t._emitter.addText(e),t}(e),i=t.filter(N).filter(h).map((t=>b(t,e,!1)));i.unshift(a);const r=i.sort(((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(N(e.language).supersetOf===t.language)return 1;if(N(t.language).supersetOf===e.language)return-1}return 0})),[o,s]=r,c=o;return c.secondBest=s,c}function C(e){let t=null;const a=function(e){let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"";const a=_.languageDetectRe.exec(t);if(a){const t=N(a[1]);return t||(Z(s.replace("{}",a[1])),Z("Falling back to no-highlight mode for this block.",e)),t?a[1]:"no-highlight"}return t.split(/\s+/).find((e=>E(e)||N(e)))}(e);if(E(a))return;if(v("before:highlightElement",{el:e,language:a}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);if(e.children.length>0&&(_.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(e)),_.throwUnescapedHTML)){throw new re("One of your code blocks includes unescaped HTML.",e.innerHTML)}t=e;const n=t.textContent,r=a?S(n,{language:a,ignoreIllegals:!0}):T(n);e.innerHTML=r.value,e.dataset.highlighted="yes",function(e,t,a){const n=t&&i[t]||a;e.classList.add("hljs"),e.classList.add(`language-${n}`)}(e,a,r.language),e.result={language:r.language,re:r.relevance,relevance:r.relevance},r.secondBest&&(e.secondBest={language:r.secondBest.language,relevance:r.secondBest.relevance}),v("after:highlightElement",{el:e,result:r,text:n})}let f=!1;function R(){if("loading"===document.readyState)return void(f=!0);document.querySelectorAll(_.cssSelector).forEach(C)}function N(e){return e=(e||"").toLowerCase(),n[e]||n[i[e]]}function O(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach((e=>{i[e.toLowerCase()]=t}))}function h(e){const t=N(e);return t&&!t.disableAutodetect}function v(e,t){const a=e;r.forEach((function(e){e[a]&&e[a](t)}))}"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("DOMContentLoaded",(function(){f&&R()}),!1),Object.assign(e,{highlight:S,highlightAuto:T,highlightAll:R,highlightElement:C,highlightBlock:function(e){return J("10.7.0","highlightBlock will be removed entirely in v12.0"),J("10.7.0","Please use highlightElement now."),C(e)},configure:function(e){_=se(_,e)},initHighlighting:()=>{R(),J("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")},initHighlightingOnLoad:function(){R(),J("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")},registerLanguage:function(t,a){let i=null;try{i=a(e)}catch(e){if(X("Language definition for '{}' could not be registered.".replace("{}",t)),!o)throw e;X(e),i=l}i.name||(i.name=t),n[t]=i,i.rawDefinition=a.bind(null,e),i.aliases&&O(i.aliases,{languageName:t})},unregisterLanguage:function(e){delete n[e];for(const t of Object.keys(i))i[t]===e&&delete i[t]},listLanguages:function(){return Object.keys(n)},getLanguage:N,registerAliases:O,autoDetection:h,inherit:se,addPlugin:function(e){!function(e){e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{e["before:highlightBlock"](Object.assign({block:t.el},t))}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{e["after:highlightBlock"](Object.assign({block:t.el},t))})}(e),r.push(e)},removePlugin:function(e){const t=r.indexOf(e);-1!==t&&r.splice(t,1)}}),e.debugMode=function(){o=!1},e.safeMode=function(){o=!0},e.versionString="11.9.0",e.regex={concat:u,lookahead:d,either:g,optional:p,anyNumberOfTimes:m};for(const e in F)"object"==typeof F[e]&&t(F[e]);return Object.assign(e,F),e},_e=ce({});_e.newInstance=()=>ce({});var de,me,pe,ue,ge,Ee,Se,be,Te,Ce,fe,Re,Ne,Oe,he,ve,Ie,Ae,ye,De,Me,Le,xe,we,Pe,ke,Ue,Fe,Be,Ge,Ye,He,Ve,qe,ze,$e,We,Qe,Ke,je,Xe,Ze,Je,et,tt,at,nt,it,rt,ot,st,lt,ct,_t,dt,mt,pt,ut,gt,Et,St,bt,Tt,Ct,ft,Rt,Nt,Ot,ht,vt,It,At,yt,Dt,Mt,Lt,xt,wt,Pt,kt,Ut,Ft,Bt,Gt,Yt,Ht,Vt,qt,zt,$t,Wt,Qt,Kt,jt,Xt,Zt,Jt,ea,ta,aa,na,ia,ra,oa,sa,la,ca,_a,da,ma,pa,ua,ga,Ea,Sa,ba,Ta,Ca,fa,Ra,Na,Oa,ha,va,Ia,Aa,ya,Da,Ma,La,xa,wa,Pa,ka,Ua,Fa,Ba,Ga,Ya,Ha,Va,qa,za,$a,Wa,Qa,Ka,ja,Xa,Za,Ja,en,tn,an,nn,rn,on,sn,ln,cn,_n,dn,mn,pn,un,gn,En,Sn,bn,Tn,Cn,fn,Rn,Nn,On,hn,vn,In,An,yn,Dn,Mn,Ln,xn,wn,Pn,kn,Un,Fn,Bn,Gn,Yn,Hn,Vn,qn,zn,$n,Wn,Qn,Kn,jn,Xn,Zn,Jn,ei,ti,ai,ni,ii,ri,oi,si,li,ci,_i,di,mi,pi,ui,gi,Ei,Si,bi,Ti,Ci,fi,Ri,Ni,Oi,hi,vi,Ii,Ai,yi,Di,Mi,Li,xi,wi,Pi,ki,Ui,Fi,Bi,Gi,Yi,Hi,Vi,qi,zi,$i,Wi,Qi,Ki,ji,Xi,Zi,Ji,er,tr,ar,nr,ir,rr,or,sr,lr,cr,_r,dr,mr,pr,ur,gr,Er,Sr,br,Tr,Cr,fr,Rr,Nr,Or,hr,vr,Ir,Ar,yr,Dr,Mr,Lr,xr,wr,Pr,kr,Ur,Fr,Br,Gr,Yr,Hr,Vr,qr,zr,$r,Wr,Qr,Kr,jr,Xr,Zr,Jr,eo,to,ao,no,io,ro,oo,so,lo,co,_o,mo,po,uo,go,Eo,So,bo,To,Co,fo,Ro,No,Oo,ho,vo,Io,Ao,yo,Do,Mo,Lo,xo,wo,Po,ko,Uo,Fo,Bo,Go,Yo,Ho,Vo,qo,zo,$o,Wo,Qo,Ko,jo,Xo,Zo,Jo,es,ts,as,ns,is,rs,os,ss,ls,cs,_s,ds,ms,ps,us,gs,Es,Ss,bs,Ts=_e;_e.HighlightJS=_e,_e.default=_e;var Cs=Ts;Cs.registerLanguage("1c",(me||(me=1,de=function(e){const t="[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]+",a="далее возврат вызватьисключение выполнить для если и из или иначе иначеесли исключение каждого конецесли конецпопытки конеццикла не новый перейти перем по пока попытка прервать продолжить тогда цикл экспорт ",n="null истина ложь неопределено",i=e.inherit(e.NUMBER_MODE),r={className:"string",begin:'"|\\|',end:'"|$',contains:[{begin:'""'}]},o={begin:"'",end:"'",excludeBegin:!0,excludeEnd:!0,contains:[{className:"number",begin:"\\d{4}([\\.\\\\/:-]?\\d{2}){0,5}"}]},s=e.inherit(e.C_LINE_COMMENT_MODE);return{name:"1C:Enterprise",case_insensitive:!0,keywords:{$pattern:t,keyword:a,built_in:"разделительстраниц разделительстрок символтабуляции ansitooem oemtoansi ввестивидсубконто ввестиперечисление ввестипериод ввестиплансчетов выбранныйплансчетов датагод датамесяц датачисло заголовоксистемы значениевстроку значениеизстроки каталогиб каталогпользователя кодсимв конгода конецпериодаби конецрассчитанногопериодаби конецстандартногоинтервала конквартала конмесяца коннедели лог лог10 максимальноеколичествосубконто названиеинтерфейса названиенабораправ назначитьвид назначитьсчет найтиссылки началопериодаби началостандартногоинтервала начгода начквартала начмесяца начнедели номерднягода номерднянедели номернеделигода обработкаожидания основнойжурналрасчетов основнойплансчетов основнойязык очиститьокносообщений периодстр получитьвремята получитьдатута получитьдокументта получитьзначенияотбора получитьпозициюта получитьпустоезначение получитьта префиксавтонумерации пропись пустоезначение разм разобратьпозициюдокумента рассчитатьрегистрына рассчитатьрегистрыпо симв создатьобъект статусвозврата стрколичествострок сформироватьпозициюдокумента счетпокоду текущеевремя типзначения типзначениястр установитьтана установитьтапо фиксшаблон шаблон acos asin atan base64значение base64строка cos exp log log10 pow sin sqrt tan xmlзначение xmlстрока xmlтип xmlтипзнч активноеокно безопасныйрежим безопасныйрежимразделенияданных булево ввестидату ввестизначение ввестистроку ввестичисло возможностьчтенияxml вопрос восстановитьзначение врег выгрузитьжурналрегистрации выполнитьобработкуоповещения выполнитьпроверкуправдоступа вычислить год данныеформывзначение дата день деньгода деньнедели добавитьмесяц заблокироватьданныедляредактирования заблокироватьработупользователя завершитьработусистемы загрузитьвнешнююкомпоненту закрытьсправку записатьjson записатьxml записатьдатуjson записьжурналарегистрации заполнитьзначениясвойств запроситьразрешениепользователя запуститьприложение запуститьсистему зафиксироватьтранзакцию значениевданныеформы значениевстрокувнутр значениевфайл значениезаполнено значениеизстрокивнутр значениеизфайла изxmlтипа импортмоделиxdto имякомпьютера имяпользователя инициализироватьпредопределенныеданные информацияобошибке каталогбиблиотекимобильногоустройства каталогвременныхфайлов каталогдокументов каталогпрограммы кодироватьстроку кодлокализацииинформационнойбазы кодсимвола командасистемы конецгода конецдня конецквартала конецмесяца конецминуты конецнедели конецчаса конфигурациябазыданныхизмененадинамически конфигурацияизменена копироватьданныеформы копироватьфайл краткоепредставлениеошибки лев макс местноевремя месяц мин минута монопольныйрежим найти найтинедопустимыесимволыxml найтиокнопонавигационнойссылке найтипомеченныенаудаление найтипоссылкам найтифайлы началогода началодня началоквартала началомесяца началоминуты началонедели началочаса начатьзапросразрешенияпользователя начатьзапускприложения начатькопированиефайла начатьперемещениефайла начатьподключениевнешнейкомпоненты начатьподключениерасширенияработыскриптографией начатьподключениерасширенияработысфайлами начатьпоискфайлов начатьполучениекаталогавременныхфайлов начатьполучениекаталогадокументов начатьполучениерабочегокаталогаданныхпользователя начатьполучениефайлов начатьпомещениефайла начатьпомещениефайлов начатьсозданиедвоичныхданныхизфайла начатьсозданиекаталога начатьтранзакцию начатьудалениефайлов начатьустановкувнешнейкомпоненты начатьустановкурасширенияработыскриптографией начатьустановкурасширенияработысфайлами неделягода необходимостьзавершениясоединения номерсеансаинформационнойбазы номерсоединенияинформационнойбазы нрег нстр обновитьинтерфейс обновитьнумерациюобъектов обновитьповторноиспользуемыезначения обработкапрерыванияпользователя объединитьфайлы окр описаниеошибки оповестить оповеститьобизменении отключитьобработчикзапросанастроекклиенталицензирования отключитьобработчикожидания отключитьобработчикоповещения открытьзначение открытьиндекссправки открытьсодержаниесправки открытьсправку открытьформу открытьформумодально отменитьтранзакцию очиститьжурналрегистрации очиститьнастройкипользователя очиститьсообщения параметрыдоступа перейтипонавигационнойссылке переместитьфайл подключитьвнешнююкомпоненту подключитьобработчикзапросанастроекклиенталицензирования подключитьобработчикожидания подключитьобработчикоповещения подключитьрасширениеработыскриптографией подключитьрасширениеработысфайлами подробноепредставлениеошибки показатьвводдаты показатьвводзначения показатьвводстроки показатьвводчисла показатьвопрос показатьзначение показатьинформациюобошибке показатьнакарте показатьоповещениепользователя показатьпредупреждение полноеимяпользователя получитьcomобъект получитьxmlтип получитьадреспоместоположению получитьблокировкусеансов получитьвремязавершенияспящегосеанса получитьвремязасыпанияпассивногосеанса получитьвремяожиданияблокировкиданных получитьданныевыбора получитьдополнительныйпараметрклиенталицензирования получитьдопустимыекодылокализации получитьдопустимыечасовыепояса получитьзаголовокклиентскогоприложения получитьзаголовоксистемы получитьзначенияотборажурналарегистрации получитьидентификаторконфигурации получитьизвременногохранилища получитьимявременногофайла получитьимяклиенталицензирования получитьинформациюэкрановклиента получитьиспользованиежурн
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
true
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/highlight/highlight.js
plugin/highlight/highlight.js
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).RevealHighlight=t()}(this,(function(){"use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function t(e){return e instanceof Map?e.clear=e.delete=e.set=function(){throw new Error("map is read-only")}:e instanceof Set&&(e.add=e.clear=e.delete=function(){throw new Error("set is read-only")}),Object.freeze(e),Object.getOwnPropertyNames(e).forEach((a=>{const n=e[a],i=typeof n;"object"!==i&&"function"!==i||Object.isFrozen(n)||t(n)})),e}class a{constructor(e){void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function n(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}function i(e,...t){const a=Object.create(null);for(const t in e)a[t]=e[t];return t.forEach((function(e){for(const t in e)a[t]=e[t]})),a}const r=e=>!!e.scope;class o{constructor(e,t){this.buffer="",this.classPrefix=t.classPrefix,e.walk(this)}addText(e){this.buffer+=n(e)}openNode(e){if(!r(e))return;const t=((e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){const a=e.split(".");return[`${t}${a.shift()}`,...a.map(((e,t)=>`${e}${"_".repeat(t+1)}`))].join(" ")}return`${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){r(e)&&(this.buffer+="</span>")}value(){return this.buffer}span(e){this.buffer+=`<span class="${e}">`}}const s=(e={})=>{const t={children:[]};return Object.assign(t,e),t};class l{constructor(){this.rootNode=s(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){const t=s({scope:e});this.add(t),this.stack.push(t)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){return"string"==typeof t?e.addText(t):t.children&&(e.openNode(t),t.children.forEach((t=>this._walk(e,t))),e.closeNode(t)),e}static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every((e=>"string"==typeof e))?e.children=[e.children.join("")]:e.children.forEach((e=>{l._collapse(e)})))}}class c extends l{constructor(e){super(),this.options=e}addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){this.closeNode()}__addSublanguage(e,t){const a=e.root;t&&(a.scope=`language:${t}`),this.add(a)}toHTML(){return new o(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function _(e){return e?"string"==typeof e?e:e.source:null}function d(e){return u("(?=",e,")")}function m(e){return u("(?:",e,")*")}function p(e){return u("(?:",e,")?")}function u(...e){return e.map((e=>_(e))).join("")}function g(...e){const t=function(e){const t=e[e.length-1];return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return"("+(t.capture?"":"?:")+e.map((e=>_(e))).join("|")+")"}function E(e){return new RegExp(e.toString()+"|").exec("").length-1}const S=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function b(e,{joinWith:t}){let a=0;return e.map((e=>{a+=1;const t=a;let n=_(e),i="";for(;n.length>0;){const e=S.exec(n);if(!e){i+=n;break}i+=n.substring(0,e.index),n=n.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?i+="\\"+String(Number(e[1])+t):(i+=e[0],"("===e[0]&&a++)}return i})).map((e=>`(${e})`)).join(t)}const T="[a-zA-Z]\\w*",C="[a-zA-Z_]\\w*",f="\\b\\d+(\\.\\d+)?",R="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",N="\\b(0b[01]+)",O={begin:"\\\\[\\s\\S]",relevance:0},h={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[O]},v={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[O]},I=function(e,t,a={}){const n=i({scope:"comment",begin:e,end:t,contains:[]},a);n.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const r=g("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return n.contains.push({begin:u(/[ ]+/,"(",r,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),n},A=I("//","$"),y=I("/\\*","\\*/"),D=I("#","$"),M={scope:"number",begin:f,relevance:0},L={scope:"number",begin:R,relevance:0},x={scope:"number",begin:N,relevance:0},w={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[O,{begin:/\[/,end:/\]/,relevance:0,contains:[O]}]},P={scope:"title",begin:T,relevance:0},k={scope:"title",begin:C,relevance:0},U={begin:"\\.\\s*"+C,relevance:0};var F=Object.freeze({__proto__:null,APOS_STRING_MODE:h,BACKSLASH_ESCAPE:O,BINARY_NUMBER_MODE:x,BINARY_NUMBER_RE:N,COMMENT:I,C_BLOCK_COMMENT_MODE:y,C_LINE_COMMENT_MODE:A,C_NUMBER_MODE:L,C_NUMBER_RE:R,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}})},HASH_COMMENT_MODE:D,IDENT_RE:T,MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:U,NUMBER_MODE:M,NUMBER_RE:f,PHRASAL_WORDS_MODE:{begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},QUOTE_STRING_MODE:v,REGEXP_MODE:w,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const t=/^#![ ]*\//;return e.binary&&(e.begin=u(t,/.*\b/,e.binary,/\b.*/)),i({scope:"meta",begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch()}},e)},TITLE_MODE:P,UNDERSCORE_IDENT_RE:C,UNDERSCORE_TITLE_MODE:k});function B(e,t){"."===e.input[e.index-1]&&t.ignoreMatch()}function G(e,t){void 0!==e.className&&(e.scope=e.className,delete e.className)}function Y(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=B,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,void 0===e.relevance&&(e.relevance=0))}function H(e,t){Array.isArray(e.illegal)&&(e.illegal=g(...e.illegal))}function V(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match}}function q(e,t){void 0===e.relevance&&(e.relevance=1)}const z=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");const a=Object.assign({},e);Object.keys(e).forEach((t=>{delete e[t]})),e.keywords=a.keywords,e.begin=u(a.beforeMatch,d(a.begin)),e.starts={relevance:0,contains:[Object.assign(a,{endsParent:!0})]},e.relevance=0,delete a.beforeMatch},$=["of","and","for","in","not","or","if","then","parent","list","value"],W="keyword";function Q(e,t,a=W){const n=Object.create(null);return"string"==typeof e?i(a,e.split(" ")):Array.isArray(e)?i(a,e):Object.keys(e).forEach((function(a){Object.assign(n,Q(e[a],t,a))})),n;function i(e,a){t&&(a=a.map((e=>e.toLowerCase()))),a.forEach((function(t){const a=t.split("|");n[a[0]]=[e,K(a[0],a[1])]}))}}function K(e,t){return t?Number(t):function(e){return $.includes(e.toLowerCase())}(e)?0:1}const j={},X=e=>{console.error(e)},Z=(e,...t)=>{console.log(`WARN: ${e}`,...t)},J=(e,t)=>{j[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),j[`${e}/${t}`]=!0)},ee=new Error;function te(e,t,{key:a}){let n=0;const i=e[a],r={},o={};for(let e=1;e<=t.length;e++)o[e+n]=i[e],r[e+n]=!0,n+=E(t[e-1]);e[a]=o,e[a]._emit=r,e[a]._multi=!0}function ae(e){!function(e){e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,delete e.scope)}(e),"string"==typeof e.beginScope&&(e.beginScope={_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope}),function(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw X("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),ee;if("object"!=typeof e.beginScope||null===e.beginScope)throw X("beginScope must be object"),ee;te(e,e.begin,{key:"beginScope"}),e.begin=b(e.begin,{joinWith:""})}}(e),function(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw X("skip, excludeEnd, returnEnd not compatible with endScope: {}"),ee;if("object"!=typeof e.endScope||null===e.endScope)throw X("endScope must be object"),ee;te(e,e.end,{key:"endScope"}),e.end=b(e.end,{joinWith:""})}}(e)}function ne(e){function t(t,a){return new RegExp(_(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(a?"g":""))}class a{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=E(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map((e=>e[1]));this.matcherRe=t(b(e,{joinWith:"|"}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;const t=this.matcherRe.exec(e);if(!t)return null;const a=t.findIndex(((e,t)=>t>0&&void 0!==e)),n=this.matchIndexes[a];return t.splice(0,a),Object.assign(t,n)}}class n{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const t=new a;return this.rules.slice(e).forEach((([e,a])=>t.addRule(e,a))),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,t){this.rules.push([e,t]),"begin"===t.type&&this.count++}exec(e){const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let a=t.exec(e);if(this.resumingScanAtSamePosition())if(a&&a.index===this.lastIndex);else{const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,a=t.exec(e)}return a&&(this.regexIndex+=a.position+1,this.regexIndex===this.count&&this.considerAll()),a}}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=i(e.classNameAliases||{}),function a(r,o){const s=r;if(r.isCompiled)return s;[G,V,ae,z].forEach((e=>e(r,o))),e.compilerExtensions.forEach((e=>e(r,o))),r.__beforeBegin=null,[Y,H,q].forEach((e=>e(r,o))),r.isCompiled=!0;let l=null;return"object"==typeof r.keywords&&r.keywords.$pattern&&(r.keywords=Object.assign({},r.keywords),l=r.keywords.$pattern,delete r.keywords.$pattern),l=l||/\w+/,r.keywords&&(r.keywords=Q(r.keywords,e.case_insensitive)),s.keywordPatternRe=t(l,!0),o&&(r.begin||(r.begin=/\B|\b/),s.beginRe=t(s.begin),r.end||r.endsWithParent||(r.end=/\B|\b/),r.end&&(s.endRe=t(s.end)),s.terminatorEnd=_(s.end)||"",r.endsWithParent&&o.terminatorEnd&&(s.terminatorEnd+=(r.end?"|":"")+o.terminatorEnd)),r.illegal&&(s.illegalRe=t(r.illegal)),r.contains||(r.contains=[]),r.contains=[].concat(...r.contains.map((function(e){return function(e){e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map((function(t){return i(e,{variants:null},t)})));if(e.cachedVariants)return e.cachedVariants;if(ie(e))return i(e,{starts:e.starts?i(e.starts):null});if(Object.isFrozen(e))return i(e);return e}("self"===e?r:e)}))),r.contains.forEach((function(e){a(e,s)})),r.starts&&a(r.starts,o),s.matcher=function(e){const t=new n;return e.contains.forEach((e=>t.addRule(e.begin,{rule:e,type:"begin"}))),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t}(s),s}(e)}function ie(e){return!!e&&(e.endsWithParent||ie(e.starts))}class re extends Error{constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t}}const oe=n,se=i,le=Symbol("nomatch"),ce=function(e){const n=Object.create(null),i=Object.create(null),r=[];let o=!0;const s="Could not find the language '{}', did you forget to load/include a language module?",l={disableAutodetect:!0,name:"Plain text",contains:[]};let _={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:c};function E(e){return _.noHighlightRe.test(e)}function S(e,t,a){let n="",i="";"object"==typeof t?(n=e,a=t.ignoreIllegals,i=t.language):(J("10.7.0","highlight(lang, code, ...args) has been deprecated."),J("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),i=e,n=t),void 0===a&&(a=!0);const r={code:n,language:i};v("before:highlight",r);const o=r.result?r.result:b(r.language,r.code,a);return o.code=r.code,v("after:highlight",o),o}function b(e,t,i,r){const l=Object.create(null);function c(){if(!v.keywords)return void A.addText(y);let e=0;v.keywordPatternRe.lastIndex=0;let t=v.keywordPatternRe.exec(y),a="";for(;t;){a+=y.substring(e,t.index);const i=R.case_insensitive?t[0].toLowerCase():t[0],r=(n=i,v.keywords[n]);if(r){const[e,n]=r;if(A.addText(a),a="",l[i]=(l[i]||0)+1,l[i]<=7&&(D+=n),e.startsWith("_"))a+=t[0];else{const a=R.classNameAliases[e]||e;m(t[0],a)}}else a+=t[0];e=v.keywordPatternRe.lastIndex,t=v.keywordPatternRe.exec(y)}var n;a+=y.substring(e),A.addText(a)}function d(){null!=v.subLanguage?function(){if(""===y)return;let e=null;if("string"==typeof v.subLanguage){if(!n[v.subLanguage])return void A.addText(y);e=b(v.subLanguage,y,!0,I[v.subLanguage]),I[v.subLanguage]=e._top}else e=T(y,v.subLanguage.length?v.subLanguage:null);v.relevance>0&&(D+=e.relevance),A.__addSublanguage(e._emitter,e.language)}():c(),y=""}function m(e,t){""!==e&&(A.startScope(t),A.addText(e),A.endScope())}function p(e,t){let a=1;const n=t.length-1;for(;a<=n;){if(!e._emit[a]){a++;continue}const n=R.classNameAliases[e[a]]||e[a],i=t[a];n?m(i,n):(y=i,c(),y=""),a++}}function u(e,t){return e.scope&&"string"==typeof e.scope&&A.openNode(R.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(m(y,R.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),y=""):e.beginScope._multi&&(p(e.beginScope,t),y="")),v=Object.create(e,{parent:{value:v}}),v}function g(e,t,n){let i=function(e,t){const a=e&&e.exec(t);return a&&0===a.index}(e.endRe,n);if(i){if(e["on:end"]){const n=new a(e);e["on:end"](t,n),n.isMatchIgnored&&(i=!1)}if(i){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return g(e.parent,t,n)}function E(e){return 0===v.matcher.regexIndex?(y+=e[0],1):(x=!0,0)}function S(e){const a=e[0],n=t.substring(e.index),i=g(v,e,n);if(!i)return le;const r=v;v.endScope&&v.endScope._wrap?(d(),m(a,v.endScope._wrap)):v.endScope&&v.endScope._multi?(d(),p(v.endScope,e)):r.skip?y+=a:(r.returnEnd||r.excludeEnd||(y+=a),d(),r.excludeEnd&&(y=a));do{v.scope&&A.closeNode(),v.skip||v.subLanguage||(D+=v.relevance),v=v.parent}while(v!==i.parent);return i.starts&&u(i.starts,e),r.returnEnd?0:a.length}let C={};function f(n,r){const s=r&&r[0];if(y+=n,null==s)return d(),0;if("begin"===C.type&&"end"===r.type&&C.index===r.index&&""===s){if(y+=t.slice(r.index,r.index+1),!o){const t=new Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=C.rule,t}return 1}if(C=r,"begin"===r.type)return function(e){const t=e[0],n=e.rule,i=new a(n),r=[n.__beforeBegin,n["on:begin"]];for(const a of r)if(a&&(a(e,i),i.isMatchIgnored))return E(t);return n.skip?y+=t:(n.excludeBegin&&(y+=t),d(),n.returnBegin||n.excludeBegin||(y=t)),u(n,e),n.returnBegin?0:t.length}(r);if("illegal"===r.type&&!i){const e=new Error('Illegal lexeme "'+s+'" for mode "'+(v.scope||"<unnamed>")+'"');throw e.mode=v,e}if("end"===r.type){const e=S(r);if(e!==le)return e}if("illegal"===r.type&&""===s)return 1;if(L>1e5&&L>3*r.index){throw new Error("potential infinite loop, way more iterations than matches")}return y+=s,s.length}const R=N(e);if(!R)throw X(s.replace("{}",e)),new Error('Unknown language: "'+e+'"');const O=ne(R);let h="",v=r||O;const I={},A=new _.__emitter(_);!function(){const e=[];for(let t=v;t!==R;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach((e=>A.openNode(e)))}();let y="",D=0,M=0,L=0,x=!1;try{if(R.__emitTokens)R.__emitTokens(t,A);else{for(v.matcher.considerAll();;){L++,x?x=!1:v.matcher.considerAll(),v.matcher.lastIndex=M;const e=v.matcher.exec(t);if(!e)break;const a=f(t.substring(M,e.index),e);M=e.index+a}f(t.substring(M))}return A.finalize(),h=A.toHTML(),{language:e,value:h,relevance:D,illegal:!1,_emitter:A,_top:v}}catch(a){if(a.message&&a.message.includes("Illegal"))return{language:e,value:oe(t),illegal:!0,relevance:0,_illegalBy:{message:a.message,index:M,context:t.slice(M-100,M+100),mode:a.mode,resultSoFar:h},_emitter:A};if(o)return{language:e,value:oe(t),illegal:!1,relevance:0,errorRaised:a,_emitter:A,_top:v};throw a}}function T(e,t){t=t||_.languages||Object.keys(n);const a=function(e){const t={value:oe(e),illegal:!1,relevance:0,_top:l,_emitter:new _.__emitter(_)};return t._emitter.addText(e),t}(e),i=t.filter(N).filter(h).map((t=>b(t,e,!1)));i.unshift(a);const r=i.sort(((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(N(e.language).supersetOf===t.language)return 1;if(N(t.language).supersetOf===e.language)return-1}return 0})),[o,s]=r,c=o;return c.secondBest=s,c}function C(e){let t=null;const a=function(e){let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"";const a=_.languageDetectRe.exec(t);if(a){const t=N(a[1]);return t||(Z(s.replace("{}",a[1])),Z("Falling back to no-highlight mode for this block.",e)),t?a[1]:"no-highlight"}return t.split(/\s+/).find((e=>E(e)||N(e)))}(e);if(E(a))return;if(v("before:highlightElement",{el:e,language:a}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);if(e.children.length>0&&(_.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(e)),_.throwUnescapedHTML)){throw new re("One of your code blocks includes unescaped HTML.",e.innerHTML)}t=e;const n=t.textContent,r=a?S(n,{language:a,ignoreIllegals:!0}):T(n);e.innerHTML=r.value,e.dataset.highlighted="yes",function(e,t,a){const n=t&&i[t]||a;e.classList.add("hljs"),e.classList.add(`language-${n}`)}(e,a,r.language),e.result={language:r.language,re:r.relevance,relevance:r.relevance},r.secondBest&&(e.secondBest={language:r.secondBest.language,relevance:r.secondBest.relevance}),v("after:highlightElement",{el:e,result:r,text:n})}let f=!1;function R(){if("loading"===document.readyState)return void(f=!0);document.querySelectorAll(_.cssSelector).forEach(C)}function N(e){return e=(e||"").toLowerCase(),n[e]||n[i[e]]}function O(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach((e=>{i[e.toLowerCase()]=t}))}function h(e){const t=N(e);return t&&!t.disableAutodetect}function v(e,t){const a=e;r.forEach((function(e){e[a]&&e[a](t)}))}"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("DOMContentLoaded",(function(){f&&R()}),!1),Object.assign(e,{highlight:S,highlightAuto:T,highlightAll:R,highlightElement:C,highlightBlock:function(e){return J("10.7.0","highlightBlock will be removed entirely in v12.0"),J("10.7.0","Please use highlightElement now."),C(e)},configure:function(e){_=se(_,e)},initHighlighting:()=>{R(),J("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")},initHighlightingOnLoad:function(){R(),J("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")},registerLanguage:function(t,a){let i=null;try{i=a(e)}catch(e){if(X("Language definition for '{}' could not be registered.".replace("{}",t)),!o)throw e;X(e),i=l}i.name||(i.name=t),n[t]=i,i.rawDefinition=a.bind(null,e),i.aliases&&O(i.aliases,{languageName:t})},unregisterLanguage:function(e){delete n[e];for(const t of Object.keys(i))i[t]===e&&delete i[t]},listLanguages:function(){return Object.keys(n)},getLanguage:N,registerAliases:O,autoDetection:h,inherit:se,addPlugin:function(e){!function(e){e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{e["before:highlightBlock"](Object.assign({block:t.el},t))}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{e["after:highlightBlock"](Object.assign({block:t.el},t))})}(e),r.push(e)},removePlugin:function(e){const t=r.indexOf(e);-1!==t&&r.splice(t,1)}}),e.debugMode=function(){o=!1},e.safeMode=function(){o=!0},e.versionString="11.9.0",e.regex={concat:u,lookahead:d,either:g,optional:p,anyNumberOfTimes:m};for(const e in F)"object"==typeof F[e]&&t(F[e]);return Object.assign(e,F),e},_e=ce({});_e.newInstance=()=>ce({});var de,me,pe,ue,ge,Ee,Se,be,Te,Ce,fe,Re,Ne,Oe,he,ve,Ie,Ae,ye,De,Me,Le,xe,we,Pe,ke,Ue,Fe,Be,Ge,Ye,He,Ve,qe,ze,$e,We,Qe,Ke,je,Xe,Ze,Je,et,tt,at,nt,it,rt,ot,st,lt,ct,_t,dt,mt,pt,ut,gt,Et,St,bt,Tt,Ct,ft,Rt,Nt,Ot,ht,vt,It,At,yt,Dt,Mt,Lt,xt,wt,Pt,kt,Ut,Ft,Bt,Gt,Yt,Ht,Vt,qt,zt,$t,Wt,Qt,Kt,jt,Xt,Zt,Jt,ea,ta,aa,na,ia,ra,oa,sa,la,ca,_a,da,ma,pa,ua,ga,Ea,Sa,ba,Ta,Ca,fa,Ra,Na,Oa,ha,va,Ia,Aa,ya,Da,Ma,La,xa,wa,Pa,ka,Ua,Fa,Ba,Ga,Ya,Ha,Va,qa,za,$a,Wa,Qa,Ka,ja,Xa,Za,Ja,en,tn,an,nn,rn,on,sn,ln,cn,_n,dn,mn,pn,un,gn,En,Sn,bn,Tn,Cn,fn,Rn,Nn,On,hn,vn,In,An,yn,Dn,Mn,Ln,xn,wn,Pn,kn,Un,Fn,Bn,Gn,Yn,Hn,Vn,qn,zn,$n,Wn,Qn,Kn,jn,Xn,Zn,Jn,ei,ti,ai,ni,ii,ri,oi,si,li,ci,_i,di,mi,pi,ui,gi,Ei,Si,bi,Ti,Ci,fi,Ri,Ni,Oi,hi,vi,Ii,Ai,yi,Di,Mi,Li,xi,wi,Pi,ki,Ui,Fi,Bi,Gi,Yi,Hi,Vi,qi,zi,$i,Wi,Qi,Ki,ji,Xi,Zi,Ji,er,tr,ar,nr,ir,rr,or,sr,lr,cr,_r,dr,mr,pr,ur,gr,Er,Sr,br,Tr,Cr,fr,Rr,Nr,Or,hr,vr,Ir,Ar,yr,Dr,Mr,Lr,xr,wr,Pr,kr,Ur,Fr,Br,Gr,Yr,Hr,Vr,qr,zr,$r,Wr,Qr,Kr,jr,Xr,Zr,Jr,eo,to,ao,no,io,ro,oo,so,lo,co,_o,mo,po,uo,go,Eo,So,bo,To,Co,fo,Ro,No,Oo,ho,vo,Io,Ao,yo,Do,Mo,Lo,xo,wo,Po,ko,Uo,Fo,Bo,Go,Yo,Ho,Vo,qo,zo,$o,Wo,Qo,Ko,jo,Xo,Zo,Jo,es,ts,as,ns,is,rs,os,ss,ls,cs,_s,ds,ms,ps,us,gs,Es,Ss,bs,Ts=_e;_e.HighlightJS=_e,_e.default=_e;var Cs=Ts;Cs.registerLanguage("1c",(me||(me=1,de=function(e){const t="[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]+",a="далее возврат вызватьисключение выполнить для если и из или иначе иначеесли исключение каждого конецесли конецпопытки конеццикла не новый перейти перем по пока попытка прервать продолжить тогда цикл экспорт ",n="null истина ложь неопределено",i=e.inherit(e.NUMBER_MODE),r={className:"string",begin:'"|\\|',end:'"|$',contains:[{begin:'""'}]},o={begin:"'",end:"'",excludeBegin:!0,excludeEnd:!0,contains:[{className:"number",begin:"\\d{4}([\\.\\\\/:-]?\\d{2}){0,5}"}]},s=e.inherit(e.C_LINE_COMMENT_MODE);return{name:"1C:Enterprise",case_insensitive:!0,keywords:{$pattern:t,keyword:a,built_in:"разделительстраниц разделительстрок символтабуляции ansitooem oemtoansi ввестивидсубконто ввестиперечисление ввестипериод ввестиплансчетов выбранныйплансчетов датагод датамесяц датачисло заголовоксистемы значениевстроку значениеизстроки каталогиб каталогпользователя кодсимв конгода конецпериодаби конецрассчитанногопериодаби конецстандартногоинтервала конквартала конмесяца коннедели лог лог10 максимальноеколичествосубконто названиеинтерфейса названиенабораправ назначитьвид назначитьсчет найтиссылки началопериодаби началостандартногоинтервала начгода начквартала начмесяца начнедели номерднягода номерднянедели номернеделигода обработкаожидания основнойжурналрасчетов основнойплансчетов основнойязык очиститьокносообщений периодстр получитьвремята получитьдатута получитьдокументта получитьзначенияотбора получитьпозициюта получитьпустоезначение получитьта префиксавтонумерации пропись пустоезначение разм разобратьпозициюдокумента рассчитатьрегистрына рассчитатьрегистрыпо симв создатьобъект статусвозврата стрколичествострок сформироватьпозициюдокумента счетпокоду текущеевремя типзначения типзначениястр установитьтана установитьтапо фиксшаблон шаблон acos asin atan base64значение base64строка cos exp log log10 pow sin sqrt tan xmlзначение xmlстрока xmlтип xmlтипзнч активноеокно безопасныйрежим безопасныйрежимразделенияданных булево ввестидату ввестизначение ввестистроку ввестичисло возможностьчтенияxml вопрос восстановитьзначение врег выгрузитьжурналрегистрации выполнитьобработкуоповещения выполнитьпроверкуправдоступа вычислить год данныеформывзначение дата день деньгода деньнедели добавитьмесяц заблокироватьданныедляредактирования заблокироватьработупользователя завершитьработусистемы загрузитьвнешнююкомпоненту закрытьсправку записатьjson записатьxml записатьдатуjson записьжурналарегистрации заполнитьзначениясвойств запроситьразрешениепользователя запуститьприложение запуститьсистему зафиксироватьтранзакцию значениевданныеформы значениевстрокувнутр значениевфайл значениезаполнено значениеизстрокивнутр значениеизфайла изxmlтипа импортмоделиxdto имякомпьютера имяпользователя инициализироватьпредопределенныеданные информацияобошибке каталогбиблиотекимобильногоустройства каталогвременныхфайлов каталогдокументов каталогпрограммы кодироватьстроку кодлокализацииинформационнойбазы кодсимвола командасистемы конецгода конецдня конецквартала конецмесяца конецминуты конецнедели конецчаса конфигурациябазыданныхизмененадинамически конфигурацияизменена копироватьданныеформы копироватьфайл краткоепредставлениеошибки лев макс местноевремя месяц мин минута монопольныйрежим найти найтинедопустимыесимволыxml найтиокнопонавигационнойссылке найтипомеченныенаудаление найтипоссылкам найтифайлы началогода началодня началоквартала началомесяца началоминуты началонедели началочаса начатьзапросразрешенияпользователя начатьзапускприложения начатькопированиефайла начатьперемещениефайла начатьподключениевнешнейкомпоненты начатьподключениерасширенияработыскриптографией начатьподключениерасширенияработысфайлами начатьпоискфайлов начатьполучениекаталогавременныхфайлов начатьполучениекаталогадокументов начатьполучениерабочегокаталогаданныхпользователя начатьполучениефайлов начатьпомещениефайла начатьпомещениефайлов начатьсозданиедвоичныхданныхизфайла начатьсозданиекаталога начатьтранзакцию начатьудалениефайлов начатьустановкувнешнейкомпоненты начатьустановкурасширенияработыскриптографией начатьустановкурасширенияработысфайлами неделягода необходимостьзавершениясоединения номерсеансаинформационнойбазы номерсоединенияинформационнойбазы нрег нстр обновитьинтерфейс обновитьнумерациюобъектов обновитьповторноиспользуемыезначения обработкапрерыванияпользователя объединитьфайлы окр описаниеошибки оповестить оповеститьобизменении отключитьобработчикзапросанастроекклиенталицензирования отключитьобработчикожидания отключитьобработчикоповещения открытьзначение открытьиндекссправки открытьсодержаниесправки открытьсправку открытьформу открытьформумодально отменитьтранзакцию очиститьжурналрегистрации очиститьнастройкипользователя очиститьсообщения параметрыдоступа перейтипонавигационнойссылке переместитьфайл подключитьвнешнююкомпоненту подключитьобработчикзапросанастроекклиенталицензирования подключитьобработчикожидания подключитьобработчикоповещения подключитьрасширениеработыскриптографией подключитьрасширениеработысфайлами подробноепредставлениеошибки показатьвводдаты показатьвводзначения показатьвводстроки показатьвводчисла показатьвопрос показатьзначение показатьинформациюобошибке показатьнакарте показатьоповещениепользователя показатьпредупреждение полноеимяпользователя получитьcomобъект получитьxmlтип получитьадреспоместоположению получитьблокировкусеансов получитьвремязавершенияспящегосеанса получитьвремязасыпанияпассивногосеанса получитьвремяожиданияблокировкиданных получитьданныевыбора получитьдополнительныйпараметрклиенталицензирования получитьдопустимыекодылокализации получитьдопустимыечасовыепояса получитьзаголовокклиентскогоприложения получитьзаголовоксистемы получитьзначенияотборажурналарегистрации получитьидентификаторконфигурации получитьизвременногохранил
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
true
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/markdown/plugin.js
plugin/markdown/plugin.js
/*! * The reveal.js markdown plugin. Handles parsing of * markdown inside of presentations as well as loading * of external markdown documents. */ import { marked } from 'marked'; const DEFAULT_SLIDE_SEPARATOR = '\r?\n---\r?\n', DEFAULT_VERTICAL_SEPARATOR = null, DEFAULT_NOTES_SEPARATOR = '^\s*notes?:', DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$', DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$'; const SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__'; // match an optional line number offset and highlight line numbers // [<line numbers>] or [<offset>: <line numbers>] const CODE_LINE_NUMBER_REGEX = /\[\s*((\d*):)?\s*([\s\d,|-]*)\]/; const HTML_ESCAPE_MAP = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; const Plugin = () => { // The reveal.js instance this plugin is attached to let deck; /** * Retrieves the markdown contents of a slide section * element. Normalizes leading tabs/whitespace. */ function getMarkdownFromSlide( section ) { // look for a <script> or <textarea data-template> wrapper const template = section.querySelector( '[data-template]' ) || section.querySelector( 'script' ); // strip leading whitespace so it isn't evaluated as code let text = ( template || section ).textContent; // restore script end tags text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' ); const leadingWs = text.match( /^\n?(\s*)/ )[1].length, leadingTabs = text.match( /^\n?(\t*)/ )[1].length; if( leadingTabs > 0 ) { text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}(.*)','g'), function(m, p1) { return '\n' + p1 ; } ); } else if( leadingWs > 1 ) { text = text.replace( new RegExp('\\n? {' + leadingWs + '}(.*)', 'g'), function(m, p1) { return '\n' + p1 ; } ); } return text; } /** * Given a markdown slide section element, this will * return all arguments that aren't related to markdown * parsing. Used to forward any other user-defined arguments * to the output markdown slide. */ function getForwardedAttributes( section ) { const attributes = section.attributes; const result = []; for( let i = 0, len = attributes.length; i < len; i++ ) { const name = attributes[i].name, value = attributes[i].value; // disregard attributes that are used for markdown loading/parsing if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue; if( value ) { result.push( name + '="' + value + '"' ); } else { result.push( name ); } } return result.join( ' ' ); } /** * Inspects the given options and fills out default * values for what's not defined. */ function getSlidifyOptions( options ) { const markdownConfig = deck?.getConfig?.().markdown; options = options || {}; options.separator = options.separator || markdownConfig?.separator || DEFAULT_SLIDE_SEPARATOR; options.verticalSeparator = options.verticalSeparator || markdownConfig?.verticalSeparator || DEFAULT_VERTICAL_SEPARATOR; options.notesSeparator = options.notesSeparator || markdownConfig?.notesSeparator || DEFAULT_NOTES_SEPARATOR; options.attributes = options.attributes || ''; return options; } /** * Helper function for constructing a markdown slide. */ function createMarkdownSlide( content, options ) { options = getSlidifyOptions( options ); const notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) ); if( notesMatch.length === 2 ) { content = notesMatch[0] + '<aside class="notes">' + marked(notesMatch[1].trim()) + '</aside>'; } // prevent script end tags in the content from interfering // with parsing content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER ); return '<script type="text/template">' + content + '</script>'; } /** * Parses a data string into multiple slides based * on the passed in separator arguments. */ function slidify( markdown, options ) { options = getSlidifyOptions( options ); const separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ), horizontalSeparatorRegex = new RegExp( options.separator ); let matches, lastIndex = 0, isHorizontal, wasHorizontal = true, content, sectionStack = []; // iterate until all blocks between separators are stacked up while( matches = separatorRegex.exec( markdown ) ) { const notes = null; // determine direction (horizontal by default) isHorizontal = horizontalSeparatorRegex.test( matches[0] ); if( !isHorizontal && wasHorizontal ) { // create vertical stack sectionStack.push( [] ); } // pluck slide content from markdown input content = markdown.substring( lastIndex, matches.index ); if( isHorizontal && wasHorizontal ) { // add to horizontal stack sectionStack.push( content ); } else { // add to vertical stack sectionStack[sectionStack.length-1].push( content ); } lastIndex = separatorRegex.lastIndex; wasHorizontal = isHorizontal; } // add the remaining slide ( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) ); let markdownSections = ''; // flatten the hierarchical stack, and insert <section data-markdown> tags for( let i = 0, len = sectionStack.length; i < len; i++ ) { // vertical if( sectionStack[i] instanceof Array ) { markdownSections += '<section '+ options.attributes +'>'; sectionStack[i].forEach( function( child ) { markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>'; } ); markdownSections += '</section>'; } else { markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>'; } } return markdownSections; } /** * Parses any current data-markdown slides, splits * multi-slide markdown into separate sections and * handles loading of external markdown. */ function processSlides( scope ) { return new Promise( function( resolve ) { const externalPromises = []; [].slice.call( scope.querySelectorAll( 'section[data-markdown]:not([data-markdown-parsed])') ).forEach( function( section, i ) { if( section.getAttribute( 'data-markdown' ).length ) { externalPromises.push( loadExternalMarkdown( section ).then( // Finished loading external file function( xhr, url ) { section.outerHTML = slidify( xhr.responseText, { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-separator-vertical' ), notesSeparator: section.getAttribute( 'data-separator-notes' ), attributes: getForwardedAttributes( section ) }); }, // Failed to load markdown function( xhr, url ) { section.outerHTML = '<section data-state="alert">' + 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' + 'Check your browser\'s JavaScript console for more details.' + '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' + '</section>'; } ) ); } else { section.outerHTML = slidify( getMarkdownFromSlide( section ), { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-separator-vertical' ), notesSeparator: section.getAttribute( 'data-separator-notes' ), attributes: getForwardedAttributes( section ) }); } }); Promise.all( externalPromises ).then( resolve ); } ); } function loadExternalMarkdown( section ) { return new Promise( function( resolve, reject ) { const xhr = new XMLHttpRequest(), url = section.getAttribute( 'data-markdown' ); const datacharset = section.getAttribute( 'data-charset' ); // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes if( datacharset !== null && datacharset !== '' ) { xhr.overrideMimeType( 'text/html; charset=' + datacharset ); } xhr.onreadystatechange = function( section, xhr ) { if( xhr.readyState === 4 ) { // file protocol yields status code 0 (useful for local debug, mobile applications etc.) if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) { resolve( xhr, url ); } else { reject( xhr, url ); } } }.bind( this, section, xhr ); xhr.open( 'GET', url, true ); try { xhr.send(); } catch ( e ) { console.warn( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e ); resolve( xhr, url ); } } ); } /** * Check if a node value has the attributes pattern. * If yes, extract it and add that value as one or several attributes * to the target element. * * You need Cache Killer on Chrome to see the effect on any FOM transformation * directly on refresh (F5) * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277 */ function addAttributeInElement( node, elementTarget, separator ) { const markdownClassesInElementsRegex = new RegExp( separator, 'mg' ); const markdownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"]+?)\"|(data-[^\"= ]+?)(?=[\" ])", 'mg' ); let nodeValue = node.nodeValue; let matches, matchesClass; if( matches = markdownClassesInElementsRegex.exec( nodeValue ) ) { const classes = matches[1]; nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( markdownClassesInElementsRegex.lastIndex ); node.nodeValue = nodeValue; while( matchesClass = markdownClassRegex.exec( classes ) ) { if( matchesClass[2] ) { elementTarget.setAttribute( matchesClass[1], matchesClass[2] ); } else { elementTarget.setAttribute( matchesClass[3], "" ); } } return true; } return false; } /** * Add attributes to the parent element of a text node, * or the element of an attribute node. */ function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) { if ( element !== null && element.childNodes !== undefined && element.childNodes.length > 0 ) { let previousParentElement = element; for( let i = 0; i < element.childNodes.length; i++ ) { const childElement = element.childNodes[i]; if ( i > 0 ) { let j = i - 1; while ( j >= 0 ) { const aPreviousChildElement = element.childNodes[j]; if ( typeof aPreviousChildElement.setAttribute === 'function' && aPreviousChildElement.tagName !== "BR" ) { previousParentElement = aPreviousChildElement; break; } j = j - 1; } } let parentSection = section; if( childElement.nodeName === "section" ) { parentSection = childElement ; previousParentElement = childElement ; } if ( typeof childElement.setAttribute === 'function' || childElement.nodeType === Node.COMMENT_NODE ) { addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes ); } } } if ( element.nodeType === Node.COMMENT_NODE ) { if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) === false ) { addAttributeInElement( element, section, separatorSectionAttributes ); } } } /** * Converts any current data-markdown slides in the * DOM to HTML. */ function convertSlides() { const sections = deck.getRevealElement().querySelectorAll( '[data-markdown]:not([data-markdown-parsed])'); [].slice.call( sections ).forEach( function( section ) { section.setAttribute( 'data-markdown-parsed', true ) const notes = section.querySelector( 'aside.notes' ); const markdown = getMarkdownFromSlide( section ); section.innerHTML = marked( markdown ); addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) || section.parentNode.getAttribute( 'data-element-attributes' ) || DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR, section.getAttribute( 'data-attributes' ) || section.parentNode.getAttribute( 'data-attributes' ) || DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR); // If there were notes, we need to re-add them after // having overwritten the section's HTML if( notes ) { section.appendChild( notes ); } } ); return Promise.resolve(); } function escapeForHTML( input ) { return input.replace( /([&<>'"])/g, char => HTML_ESCAPE_MAP[char] ); } return { id: 'markdown', /** * Starts processing and converting Markdown within the * current reveal.js deck. */ init: function( reveal ) { deck = reveal; let { renderer, animateLists, ...markedOptions } = deck.getConfig().markdown || {}; if( !renderer ) { renderer = new marked.Renderer(); renderer.code = ( code, language ) => { // Off by default let lineNumberOffset = ''; let lineNumbers = ''; // Users can opt in to show line numbers and highlight // specific lines. // ```javascript [] show line numbers // ```javascript [1,4-8] highlights lines 1 and 4-8 // optional line number offset: // ```javascript [25: 1,4-8] start line numbering at 25, // highlights lines 1 (numbered as 25) and 4-8 (numbered as 28-32) if( CODE_LINE_NUMBER_REGEX.test( language ) ) { let lineNumberOffsetMatch = language.match( CODE_LINE_NUMBER_REGEX )[2]; if (lineNumberOffsetMatch){ lineNumberOffset = `data-ln-start-from="${lineNumberOffsetMatch.trim()}"`; } lineNumbers = language.match( CODE_LINE_NUMBER_REGEX )[3].trim(); lineNumbers = `data-line-numbers="${lineNumbers}"`; language = language.replace( CODE_LINE_NUMBER_REGEX, '' ).trim(); } // Escape before this gets injected into the DOM to // avoid having the HTML parser alter our code before // highlight.js is able to read it code = escapeForHTML( code ); // return `<pre><code ${lineNumbers} class="${language}">${code}</code></pre>`; return `<pre><code ${lineNumbers} ${lineNumberOffset} class="${language}">${code}</code></pre>`; }; } if( animateLists === true ) { renderer.listitem = text => `<li class="fragment">${text}</li>`; } marked.setOptions( { renderer, ...markedOptions } ); return processSlides( deck.getRevealElement() ).then( convertSlides ); }, // TODO: Do these belong in the API? processSlides: processSlides, convertSlides: convertSlides, slidify: slidify, marked: marked } }; export default Plugin;
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/markdown/markdown.js
plugin/markdown/markdown.js
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).RevealMarkdown=t()}(this,(function(){"use strict";function e(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let t={async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1};const n=/[&<>"']/,s=new RegExp(n.source,"g"),r=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,i=new RegExp(r.source,"g"),l={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},o=e=>l[e];function a(e,t){if(t){if(n.test(e))return e.replace(s,o)}else if(r.test(e))return e.replace(i,o);return e}const c=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function h(e){return e.replace(c,((e,t)=>"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}const p=/(^|[^\[])\^/g;function u(e,t){e="string"==typeof e?e:e.source,t=t||"";const n={replace:(t,s)=>(s=(s=s.source||s).replace(p,"$1"),e=e.replace(t,s),n),getRegex:()=>new RegExp(e,t)};return n}const g=/[^\w:]/g,d=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function f(e,t,n){if(e){let e;try{e=decodeURIComponent(h(n)).replace(g,"").toLowerCase()}catch(e){return null}if(0===e.indexOf("javascript:")||0===e.indexOf("vbscript:")||0===e.indexOf("data:"))return null}t&&!d.test(n)&&(n=function(e,t){k[" "+e]||(x.test(e)?k[" "+e]=e+"/":k[" "+e]=_(e,"/",!0));e=k[" "+e];const n=-1===e.indexOf(":");return"//"===t.substring(0,2)?n?t:e.replace(m,"$1")+t:"/"===t.charAt(0)?n?t:e.replace(b,"$1")+t:e+t}(t,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch(e){return null}return n}const k={},x=/^[^:]+:\/*[^/]*$/,m=/^([^:]+:)[\s\S]*$/,b=/^([^:]+:\/*[^/]*)[\s\S]*$/;const w={exec:function(){}};function y(e,t){const n=e.replace(/\|/g,((e,t,n)=>{let s=!1,r=t;for(;--r>=0&&"\\"===n[r];)s=!s;return s?"|":" |"})).split(/ \|/);let s=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(/\\\|/g,"|");return n}function _(e,t,n){const s=e.length;if(0===s)return"";let r=0;for(;r<s;){const i=e.charAt(s-r-1);if(i!==t||n){if(i===t||!n)break;r++}else r++}return e.slice(0,s-r)}function $(e,t){if(t<1)return"";let n="";for(;t>1;)1&t&&(n+=e),t>>=1,e+=e;return n+e}function z(e,t,n,s){const r=t.href,i=t.title?a(t.title):null,l=e[1].replace(/\\([\[\]])/g,"$1");if("!"!==e[0].charAt(0)){s.state.inLink=!0;const e={type:"link",raw:n,href:r,title:i,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,e}return{type:"image",raw:n,href:r,title:i,text:a(l)}}class S{constructor(e){this.options=e||t}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:_(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t){const n=e.match(/^(\s+)(?:```)/);if(null===n)return t;const s=n[1];return t.split("\n").map((e=>{const t=e.match(/^\s+/);if(null===t)return e;const[n]=t;return n.length>=s.length?e.slice(s.length):e})).join("\n")}(e,t[3]||"");return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline._escapes,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(/#$/.test(e)){const t=_(e,"#");this.options.pedantic?e=t.trim():t&&!/ $/.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){const e=t[0].replace(/^ *>[ \t]?/gm,""),n=this.lexer.state.top;this.lexer.state.top=!0;const s=this.lexer.blockTokens(e);return this.lexer.state.top=n,{type:"blockquote",raw:t[0],tokens:s,text:e}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n,s,r,i,l,o,a,c,h,p,u,g,d=t[1].trim();const f=d.length>1,k={type:"list",raw:"",ordered:f,start:f?+d.slice(0,-1):"",loose:!1,items:[]};d=f?`\\d{1,9}\\${d.slice(-1)}`:`\\${d}`,this.options.pedantic&&(d=f?d:"[*+-]");const x=new RegExp(`^( {0,3}${d})((?:[\t ][^\\n]*)?(?:\\n|$))`);for(;e&&(g=!1,t=x.exec(e))&&!this.rules.block.hr.test(e);){if(n=t[0],e=e.substring(n.length),c=t[2].split("\n",1)[0].replace(/^\t+/,(e=>" ".repeat(3*e.length))),h=e.split("\n",1)[0],this.options.pedantic?(i=2,u=c.trimLeft()):(i=t[2].search(/[^ ]/),i=i>4?1:i,u=c.slice(i),i+=t[1].length),o=!1,!c&&/^ *$/.test(h)&&(n+=h+"\n",e=e.substring(h.length+1),g=!0),!g){const t=new RegExp(`^ {0,${Math.min(3,i-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),s=new RegExp(`^ {0,${Math.min(3,i-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),r=new RegExp(`^ {0,${Math.min(3,i-1)}}(?:\`\`\`|~~~)`),l=new RegExp(`^ {0,${Math.min(3,i-1)}}#`);for(;e&&(p=e.split("\n",1)[0],h=p,this.options.pedantic&&(h=h.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),!r.test(h))&&!l.test(h)&&!t.test(h)&&!s.test(e);){if(h.search(/[^ ]/)>=i||!h.trim())u+="\n"+h.slice(i);else{if(o)break;if(c.search(/[^ ]/)>=4)break;if(r.test(c))break;if(l.test(c))break;if(s.test(c))break;u+="\n"+h}o||h.trim()||(o=!0),n+=p+"\n",e=e.substring(p.length+1),c=h.slice(i)}}k.loose||(a?k.loose=!0:/\n *\n *$/.test(n)&&(a=!0)),this.options.gfm&&(s=/^\[[ xX]\] /.exec(u),s&&(r="[ ] "!==s[0],u=u.replace(/^\[[ xX]\] +/,""))),k.items.push({type:"list_item",raw:n,task:!!s,checked:r,loose:!1,text:u}),k.raw+=n}k.items[k.items.length-1].raw=n.trimRight(),k.items[k.items.length-1].text=u.trimRight(),k.raw=k.raw.trimRight();const m=k.items.length;for(l=0;l<m;l++)if(this.lexer.state.top=!1,k.items[l].tokens=this.lexer.blockTokens(k.items[l].text,[]),!k.loose){const e=k.items[l].tokens.filter((e=>"space"===e.type)),t=e.length>0&&e.some((e=>/\n.*\n/.test(e.raw)));k.loose=t}if(k.loose)for(l=0;l<m;l++)k.items[l].loose=!0;return k}}html(e){const t=this.rules.block.html.exec(e);if(t){const e={type:"html",raw:t[0],pre:!this.options.sanitizer&&("pre"===t[1]||"script"===t[1]||"style"===t[1]),text:t[0]};if(this.options.sanitize){const n=this.options.sanitizer?this.options.sanitizer(t[0]):a(t[0]);e.type="paragraph",e.text=n,e.tokens=this.lexer.inline(n)}return e}}def(e){const t=this.rules.block.def.exec(e);if(t){const e=t[1].toLowerCase().replace(/\s+/g," "),n=t[2]?t[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline._escapes,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline._escapes,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:s}}}table(e){const t=this.rules.block.table.exec(e);if(t){const e={type:"table",header:y(t[1]).map((e=>({text:e}))),align:t[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split("\n"):[]};if(e.header.length===e.align.length){e.raw=t[0];let n,s,r,i,l=e.align.length;for(n=0;n<l;n++)/^ *-+: *$/.test(e.align[n])?e.align[n]="right":/^ *:-+: *$/.test(e.align[n])?e.align[n]="center":/^ *:-+ *$/.test(e.align[n])?e.align[n]="left":e.align[n]=null;for(l=e.rows.length,n=0;n<l;n++)e.rows[n]=y(e.rows[n],e.header.length).map((e=>({text:e})));for(l=e.header.length,s=0;s<l;s++)e.header[s].tokens=this.lexer.inline(e.header[s].text);for(l=e.rows.length,s=0;s<l;s++)for(i=e.rows[s],r=0;r<i.length;r++)i[r].tokens=this.lexer.inline(i[r].text);return e}}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:a(t[1])}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^<a /i.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(t[0]):a(t[0]):t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&/^</.test(e)){if(!/>$/.test(e))return;const t=_(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;const n=e.length;let s=0,r=0;for(;r<n;r++)if("\\"===e[r])r++;else if(e[r]===t[0])s++;else if(e[r]===t[1]&&(s--,s<0))return r;return-1}(t[2],"()");if(e>-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){const e=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);e&&(n=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^</.test(n)&&(n=this.options.pedantic&&!/>$/.test(e)?n.slice(1):n.slice(1,-1)),z(t,{href:n?n.replace(this.rules.inline._escapes,"$1"):n,title:s?s.replace(this.rules.inline._escapes,"$1"):s},t[0],this.lexer)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=(n[2]||n[1]).replace(/\s+/g," ");if(e=t[e.toLowerCase()],!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return z(n,e,n[0],this.lexer)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrong.lDelim.exec(e);if(!s)return;if(s[3]&&n.match(/[\p{L}\p{N}]/u))return;const r=s[1]||s[2]||"";if(!r||r&&(""===n||this.rules.inline.punctuation.exec(n))){const n=s[0].length-1;let r,i,l=n,o=0;const a="*"===s[0][0]?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(a.lastIndex=0,t=t.slice(-1*e.length+n);null!=(s=a.exec(t));){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(i=r.length,s[3]||s[4]){l+=i;continue}if((s[5]||s[6])&&n%3&&!((n+i)%3)){o+=i;continue}if(l-=i,l>0)continue;i=Math.min(i,i+l+o);const t=e.slice(0,n+s.index+(s[0].length-r.length)+i);if(Math.min(n,i)%2){const e=t.slice(1,-1);return{type:"em",raw:t,text:e,tokens:this.lexer.inlineTokens(e)}}const a=t.slice(2,-2);return{type:"strong",raw:t,text:a,tokens:this.lexer.inlineTokens(a)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(/\n/g," ");const n=/[^ ]/.test(e),s=/^ /.test(e)&&/ $/.test(e);return n&&s&&(e=e.substring(1,e.length-1)),e=a(e,!0),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e,t){const n=this.rules.inline.autolink.exec(e);if(n){let e,s;return"@"===n[2]?(e=a(this.options.mangle?t(n[1]):n[1]),s="mailto:"+e):(e=a(n[1]),s=e),{type:"link",raw:n[0],text:e,href:s,tokens:[{type:"text",raw:e,text:e}]}}}url(e,t){let n;if(n=this.rules.inline.url.exec(e)){let e,s;if("@"===n[2])e=a(this.options.mangle?t(n[0]):n[0]),s="mailto:"+e;else{let t;do{t=n[0],n[0]=this.rules.inline._backpedal.exec(n[0])[0]}while(t!==n[0]);e=a(n[0]),s="www."===n[1]?"http://"+n[0]:n[0]}return{type:"link",raw:n[0],text:e,href:s,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e,t){const n=this.rules.inline.text.exec(e);if(n){let e;return e=this.lexer.state.inRawBlock?this.options.sanitize?this.options.sanitizer?this.options.sanitizer(n[0]):a(n[0]):n[0]:a(this.options.smartypants?t(n[0]):n[0]),{type:"text",raw:n[0],text:e}}}}const T={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:w,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/,_label:/(?!\s*\])(?:\\.|[^\[\]\\])+/,_title:/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/};T.def=u(T.def).replace("label",T._label).replace("title",T._title).getRegex(),T.bullet=/(?:[*+-]|\d{1,9}[.)])/,T.listItemStart=u(/^( *)(bull) */).replace("bull",T.bullet).getRegex(),T.list=u(T.list).replace(/bull/g,T.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+T.def.source+")").getRegex(),T._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",T._comment=/<!--(?!-?>)[\s\S]*?(?:-->|$)/,T.html=u(T.html,"i").replace("comment",T._comment).replace("tag",T._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),T.paragraph=u(T._paragraph).replace("hr",T.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",T._tag).getRegex(),T.blockquote=u(T.blockquote).replace("paragraph",T.paragraph).getRegex(),T.normal={...T},T.gfm={...T.normal,table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"},T.gfm.table=u(T.gfm.table).replace("hr",T.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",T._tag).getRegex(),T.gfm.paragraph=u(T._paragraph).replace("hr",T.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",T.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",T._tag).getRegex(),T.pedantic={...T.normal,html:u("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",T._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:w,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:u(T.normal._paragraph).replace("hr",T.hr).replace("heading"," *#{1,6} *[^\n]").replace("lheading",T.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const R={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:w,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:w,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^([\spunctuation])/};function A(e){return e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")}function E(e){let t,n,s="";const r=e.length;for(t=0;t<r;t++)n=e.charCodeAt(t),Math.random()>.5&&(n="x"+n.toString(16)),s+="&#"+n+";";return s}R._punctuation="!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~",R.punctuation=u(R.punctuation).replace(/punctuation/g,R._punctuation).getRegex(),R.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,R.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g,R._comment=u(T._comment).replace("(?:--\x3e|$)","--\x3e").getRegex(),R.emStrong.lDelim=u(R.emStrong.lDelim).replace(/punct/g,R._punctuation).getRegex(),R.emStrong.rDelimAst=u(R.emStrong.rDelimAst,"g").replace(/punct/g,R._punctuation).getRegex(),R.emStrong.rDelimUnd=u(R.emStrong.rDelimUnd,"g").replace(/punct/g,R._punctuation).getRegex(),R._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,R._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,R._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,R.autolink=u(R.autolink).replace("scheme",R._scheme).replace("email",R._email).getRegex(),R._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,R.tag=u(R.tag).replace("comment",R._comment).replace("attribute",R._attribute).getRegex(),R._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,R._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,R._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,R.link=u(R.link).replace("label",R._label).replace("href",R._href).replace("title",R._title).getRegex(),R.reflink=u(R.reflink).replace("label",R._label).replace("ref",T._label).getRegex(),R.nolink=u(R.nolink).replace("ref",T._label).getRegex(),R.reflinkSearch=u(R.reflinkSearch,"g").replace("reflink",R.reflink).replace("nolink",R.nolink).getRegex(),R.normal={...R},R.pedantic={...R.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:u(/^!?\[(label)\]\((.*?)\)/).replace("label",R._label).getRegex(),reflink:u(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",R._label).getRegex()},R.gfm={...R.normal,escape:u(R.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},R.gfm.url=u(R.gfm.url,"i").replace("email",R.gfm._extended_email).getRegex(),R.breaks={...R.gfm,br:u(R.br).replace("{2,}","*").getRegex(),text:u(R.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};class v{constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||t,this.options.tokenizer=this.options.tokenizer||new S,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:T.normal,inline:R.normal};this.options.pedantic?(n.block=T.pedantic,n.inline=R.pedantic):this.options.gfm&&(n.block=T.gfm,this.options.breaks?n.inline=R.breaks:n.inline=R.gfm),this.tokenizer.rules=n}static get rules(){return{block:T,inline:R}}static lex(e,t){return new v(t).lex(e)}static lexInline(e,t){return new v(t).inlineTokens(e)}lex(e){let t;for(e=e.replace(/\r\n|\r/g,"\n"),this.blockTokens(e,this.tokens);t=this.inlineQueue.shift();)this.inlineTokens(t.src,t.tokens);return this.tokens}blockTokens(e,t=[]){let n,s,r,i;for(e=this.options.pedantic?e.replace(/\t/g," ").replace(/^ +$/gm,""):e.replace(/^( *)(\t+)/gm,((e,t,n)=>t+" ".repeat(n.length)));e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.space(e))e=e.substring(n.raw.length),1===n.raw.length&&t.length>0?t[t.length-1].raw+="\n":t.push(n);else if(n=this.tokenizer.code(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?t.push(n):(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.fences(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.heading(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.hr(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.blockquote(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.list(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.html(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.def(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title}):(s.raw+="\n"+n.raw,s.text+="\n"+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.table(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.lheading(e))e=e.substring(n.raw.length),t.push(n);else{if(r=e,this.options.extensions&&this.options.extensions.startBlock){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startBlock.forEach((function(e){s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(this.state.top&&(n=this.tokenizer.paragraph(r)))s=t[t.length-1],i&&"paragraph"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n),i=r.length!==e.length,e=e.substring(n.raw.length);else if(n=this.tokenizer.text(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,s,r,i,l,o,a=e;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(a));)e.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+$("a",i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(a));)a=a.slice(0,i.index)+"["+$("a",i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.escapedEmSt.exec(a));)a=a.slice(0,i.index+i[0].length-2)+"++"+a.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex),this.tokenizer.rules.inline.escapedEmSt.lastIndex--;for(;e;)if(l||(o=""),l=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.escape(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.tag(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.link(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.reflink(e,this.tokens.links))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.emStrong(e,a,o))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.codespan(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.br(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.del(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.autolink(e,E))e=e.substring(n.raw.length),t.push(n);else if(this.state.inLink||!(n=this.tokenizer.url(e,E))){if(r=e,this.options.extensions&&this.options.extensions.startInline){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startInline.forEach((function(e){s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(n=this.tokenizer.inlineText(r,A))e=e.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),l=!0,s=t[t.length-1],s&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}else e=e.substring(n.raw.length),t.push(n);return t}}class I{constructor(e){this.options=e||t}code(e,t,n){const s=(t||"").match(/\S*/)[0];if(this.options.highlight){const t=this.options.highlight(e,s);null!=t&&t!==e&&(n=!0,e=t)}return e=e.replace(/\n$/,"")+"\n",s?'<pre><code class="'+this.options.langPrefix+a(s)+'">'+(n?e:a(e,!0))+"</code></pre>\n":"<pre><code>"+(n?e:a(e,!0))+"</code></pre>\n"}blockquote(e){return`<blockquote>\n${e}</blockquote>\n`}html(e){return e}heading(e,t,n,s){if(this.options.headerIds){return`<h${t} id="${this.options.headerPrefix+s.slug(n)}">${e}</h${t}>\n`}return`<h${t}>${e}</h${t}>\n`}hr(){return this.options.xhtml?"<hr/>\n":"<hr>\n"}list(e,t,n){const s=t?"ol":"ul";return"<"+s+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"</"+s+">\n"}listitem(e){return`<li>${e}</li>\n`}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"'+(this.options.xhtml?" /":"")+"> "}paragraph(e){return`<p>${e}</p>\n`}table(e,t){return t&&(t=`<tbody>${t}</tbody>`),"<table>\n<thead>\n"+e+"</thead>\n"+t+"</table>\n"}tablerow(e){return`<tr>\n${e}</tr>\n`}tablecell(e,t){const n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>\n`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(e){return`<del>${e}</del>`}link(e,t,n){if(null===(e=f(this.options.sanitize,this.options.baseUrl,e)))return n;let s='<a href="'+e+'"';return t&&(s+=' title="'+t+'"'),s+=">"+n+"</a>",s}image(e,t,n){if(null===(e=f(this.options.sanitize,this.options.baseUrl,e)))return n;let s=`<img src="${e}" alt="${n}"`;return t&&(s+=` title="${t}"`),s+=this.options.xhtml?"/>":">",s}text(e){return e}}class q{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,n){return""+n}image(e,t,n){return""+n}br(){return""}}class L{constructor(){this.seen={}}serialize(e){return e.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(e,t){let n=e,s=0;if(this.seen.hasOwnProperty(n)){s=this.seen[e];do{s++,n=e+"-"+s}while(this.seen.hasOwnProperty(n))}return t||(this.seen[e]=s,this.seen[n]=0),n}slug(e,t={}){const n=this.serialize(e);return this.getNextSafeSlug(n,t.dryrun)}}class C{constructor(e){this.options=e||t,this.options.renderer=this.options.renderer||new I,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new q,this.slugger=new L}static parse(e,t){return new C(t).parse(e)}static parseInline(e,t){return new C(t).parseInline(e)}parse(e,t=!0){let n,s,r,i,l,o,a,c,p,u,g,d,f,k,x,m,b,w,y,_="";const $=e.length;for(n=0;n<$;n++)if(u=e[n],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[u.type]&&(y=this.options.extensions.renderers[u.type].call({parser:this},u),!1!==y||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(u.type)))_+=y||"";else switch(u.type){case"space":continue;case"hr":_+=this.renderer.hr();continue;case"heading":_+=this.renderer.heading(this.parseInline(u.tokens),u.depth,h(this.parseInline(u.tokens,this.textRenderer)),this.slugger);continue;case"code":_+=this.renderer.code(u.text,u.lang,u.escaped);continue;case"table":for(c="",a="",i=u.header.length,s=0;s<i;s++)a+=this.renderer.tablecell(this.parseInline(u.header[s].tokens),{header:!0,align:u.align[s]});for(c+=this.renderer.tablerow(a),p="",i=u.rows.length,s=0;s<i;s++){for(o=u.rows[s],a="",l=o.length,r=0;r<l;r++)a+=this.renderer.tablecell(this.parseInline(o[r].tokens),{header:!1,align:u.align[r]});p+=this.renderer.tablerow(a)}_+=this.renderer.table(c,p);continue;case"blockquote":p=this.parse(u.tokens),_+=this.renderer.blockquote(p);continue;case"list":for(g=u.ordered,d=u.start,f=u.loose,i=u.items.length,p="",s=0;s<i;s++)x=u.items[s],m=x.checked,b=x.task,k="",x.task&&(w=this.renderer.checkbox(m),f?x.tokens.length>0&&"paragraph"===x.tokens[0].type?(x.tokens[0].text=w+" "+x.tokens[0].text,x.tokens[0].tokens&&x.tokens[0].tokens.length>0&&"text"===x.tokens[0].tokens[0].type&&(x.tokens[0].tokens[0].text=w+" "+x.tokens[0].tokens[0].text)):x.tokens.unshift({type:"text",text:w}):k+=w),k+=this.parse(x.tokens,f),p+=this.renderer.listitem(k,b,m);_+=this.renderer.list(p,g,d);continue;case"html":_+=this.renderer.html(u.text);continue;case"paragraph":_+=this.renderer.paragraph(this.parseInline(u.tokens));continue;case"text":for(p=u.tokens?this.parseInline(u.tokens):u.text;n+1<$&&"text"===e[n+1].type;)u=e[++n],p+="\n"+(u.tokens?this.parseInline(u.tokens):u.text);_+=t?this.renderer.paragraph(p):p;continue;default:{const e='Token with "'+u.type+'" type was not found.';if(this.options.silent)return void console.error(e);throw new Error(e)}}return _}parseInline(e,t){t=t||this.renderer;let n,s,r,i="";const l=e.length;for(n=0;n<l;n++)if(s=e[n],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]&&(r=this.options.extensions.renderers[s.type].call({parser:this},s),!1!==r||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)))i+=r||"";else switch(s.type){case"escape":case"text":i+=t.text(s.text);break;case"html":i+=t.html(s.text);break;case"link":i+=t.link(s.href,s.title,this.parseInline(s.tokens,t));break;case"image":i+=t.image(s.href,s.title,s.text);break;case"strong":i+=t.strong(this.parseInline(s.tokens,t));break;case"em":i+=t.em(this.parseInline(s.tokens,t));break;case"codespan":i+=t.codespan(s.text);break;case"br":i+=t.br();break;case"del":i+=t.del(this.parseInline(s.tokens,t));break;default:{const e='Token with "'+s.type+'"
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
true
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/markdown/markdown.esm.js
plugin/markdown/markdown.esm.js
function e(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let t={async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1};const n=/[&<>"']/,s=new RegExp(n.source,"g"),r=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,i=new RegExp(r.source,"g"),l={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},o=e=>l[e];function a(e,t){if(t){if(n.test(e))return e.replace(s,o)}else if(r.test(e))return e.replace(i,o);return e}const c=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function h(e){return e.replace(c,((e,t)=>"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}const p=/(^|[^\[])\^/g;function u(e,t){e="string"==typeof e?e:e.source,t=t||"";const n={replace:(t,s)=>(s=(s=s.source||s).replace(p,"$1"),e=e.replace(t,s),n),getRegex:()=>new RegExp(e,t)};return n}const g=/[^\w:]/g,d=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function f(e,t,n){if(e){let e;try{e=decodeURIComponent(h(n)).replace(g,"").toLowerCase()}catch(e){return null}if(0===e.indexOf("javascript:")||0===e.indexOf("vbscript:")||0===e.indexOf("data:"))return null}t&&!d.test(n)&&(n=function(e,t){k[" "+e]||(x.test(e)?k[" "+e]=e+"/":k[" "+e]=y(e,"/",!0));e=k[" "+e];const n=-1===e.indexOf(":");return"//"===t.substring(0,2)?n?t:e.replace(m,"$1")+t:"/"===t.charAt(0)?n?t:e.replace(b,"$1")+t:e+t}(t,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch(e){return null}return n}const k={},x=/^[^:]+:\/*[^/]*$/,m=/^([^:]+:)[\s\S]*$/,b=/^([^:]+:\/*[^/]*)[\s\S]*$/;const w={exec:function(){}};function _(e,t){const n=e.replace(/\|/g,((e,t,n)=>{let s=!1,r=t;for(;--r>=0&&"\\"===n[r];)s=!s;return s?"|":" |"})).split(/ \|/);let s=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(/\\\|/g,"|");return n}function y(e,t,n){const s=e.length;if(0===s)return"";let r=0;for(;r<s;){const i=e.charAt(s-r-1);if(i!==t||n){if(i===t||!n)break;r++}else r++}return e.slice(0,s-r)}function $(e,t){if(t<1)return"";let n="";for(;t>1;)1&t&&(n+=e),t>>=1,e+=e;return n+e}function z(e,t,n,s){const r=t.href,i=t.title?a(t.title):null,l=e[1].replace(/\\([\[\]])/g,"$1");if("!"!==e[0].charAt(0)){s.state.inLink=!0;const e={type:"link",raw:n,href:r,title:i,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,e}return{type:"image",raw:n,href:r,title:i,text:a(l)}}class S{constructor(e){this.options=e||t}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:y(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t){const n=e.match(/^(\s+)(?:```)/);if(null===n)return t;const s=n[1];return t.split("\n").map((e=>{const t=e.match(/^\s+/);if(null===t)return e;const[n]=t;return n.length>=s.length?e.slice(s.length):e})).join("\n")}(e,t[3]||"");return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline._escapes,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(/#$/.test(e)){const t=y(e,"#");this.options.pedantic?e=t.trim():t&&!/ $/.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){const e=t[0].replace(/^ *>[ \t]?/gm,""),n=this.lexer.state.top;this.lexer.state.top=!0;const s=this.lexer.blockTokens(e);return this.lexer.state.top=n,{type:"blockquote",raw:t[0],tokens:s,text:e}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n,s,r,i,l,o,a,c,h,p,u,g,d=t[1].trim();const f=d.length>1,k={type:"list",raw:"",ordered:f,start:f?+d.slice(0,-1):"",loose:!1,items:[]};d=f?`\\d{1,9}\\${d.slice(-1)}`:`\\${d}`,this.options.pedantic&&(d=f?d:"[*+-]");const x=new RegExp(`^( {0,3}${d})((?:[\t ][^\\n]*)?(?:\\n|$))`);for(;e&&(g=!1,t=x.exec(e))&&!this.rules.block.hr.test(e);){if(n=t[0],e=e.substring(n.length),c=t[2].split("\n",1)[0].replace(/^\t+/,(e=>" ".repeat(3*e.length))),h=e.split("\n",1)[0],this.options.pedantic?(i=2,u=c.trimLeft()):(i=t[2].search(/[^ ]/),i=i>4?1:i,u=c.slice(i),i+=t[1].length),o=!1,!c&&/^ *$/.test(h)&&(n+=h+"\n",e=e.substring(h.length+1),g=!0),!g){const t=new RegExp(`^ {0,${Math.min(3,i-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),s=new RegExp(`^ {0,${Math.min(3,i-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),r=new RegExp(`^ {0,${Math.min(3,i-1)}}(?:\`\`\`|~~~)`),l=new RegExp(`^ {0,${Math.min(3,i-1)}}#`);for(;e&&(p=e.split("\n",1)[0],h=p,this.options.pedantic&&(h=h.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),!r.test(h))&&!l.test(h)&&!t.test(h)&&!s.test(e);){if(h.search(/[^ ]/)>=i||!h.trim())u+="\n"+h.slice(i);else{if(o)break;if(c.search(/[^ ]/)>=4)break;if(r.test(c))break;if(l.test(c))break;if(s.test(c))break;u+="\n"+h}o||h.trim()||(o=!0),n+=p+"\n",e=e.substring(p.length+1),c=h.slice(i)}}k.loose||(a?k.loose=!0:/\n *\n *$/.test(n)&&(a=!0)),this.options.gfm&&(s=/^\[[ xX]\] /.exec(u),s&&(r="[ ] "!==s[0],u=u.replace(/^\[[ xX]\] +/,""))),k.items.push({type:"list_item",raw:n,task:!!s,checked:r,loose:!1,text:u}),k.raw+=n}k.items[k.items.length-1].raw=n.trimRight(),k.items[k.items.length-1].text=u.trimRight(),k.raw=k.raw.trimRight();const m=k.items.length;for(l=0;l<m;l++)if(this.lexer.state.top=!1,k.items[l].tokens=this.lexer.blockTokens(k.items[l].text,[]),!k.loose){const e=k.items[l].tokens.filter((e=>"space"===e.type)),t=e.length>0&&e.some((e=>/\n.*\n/.test(e.raw)));k.loose=t}if(k.loose)for(l=0;l<m;l++)k.items[l].loose=!0;return k}}html(e){const t=this.rules.block.html.exec(e);if(t){const e={type:"html",raw:t[0],pre:!this.options.sanitizer&&("pre"===t[1]||"script"===t[1]||"style"===t[1]),text:t[0]};if(this.options.sanitize){const n=this.options.sanitizer?this.options.sanitizer(t[0]):a(t[0]);e.type="paragraph",e.text=n,e.tokens=this.lexer.inline(n)}return e}}def(e){const t=this.rules.block.def.exec(e);if(t){const e=t[1].toLowerCase().replace(/\s+/g," "),n=t[2]?t[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline._escapes,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline._escapes,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:s}}}table(e){const t=this.rules.block.table.exec(e);if(t){const e={type:"table",header:_(t[1]).map((e=>({text:e}))),align:t[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split("\n"):[]};if(e.header.length===e.align.length){e.raw=t[0];let n,s,r,i,l=e.align.length;for(n=0;n<l;n++)/^ *-+: *$/.test(e.align[n])?e.align[n]="right":/^ *:-+: *$/.test(e.align[n])?e.align[n]="center":/^ *:-+ *$/.test(e.align[n])?e.align[n]="left":e.align[n]=null;for(l=e.rows.length,n=0;n<l;n++)e.rows[n]=_(e.rows[n],e.header.length).map((e=>({text:e})));for(l=e.header.length,s=0;s<l;s++)e.header[s].tokens=this.lexer.inline(e.header[s].text);for(l=e.rows.length,s=0;s<l;s++)for(i=e.rows[s],r=0;r<i.length;r++)i[r].tokens=this.lexer.inline(i[r].text);return e}}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:a(t[1])}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^<a /i.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(t[0]):a(t[0]):t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&/^</.test(e)){if(!/>$/.test(e))return;const t=y(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;const n=e.length;let s=0,r=0;for(;r<n;r++)if("\\"===e[r])r++;else if(e[r]===t[0])s++;else if(e[r]===t[1]&&(s--,s<0))return r;return-1}(t[2],"()");if(e>-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){const e=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);e&&(n=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^</.test(n)&&(n=this.options.pedantic&&!/>$/.test(e)?n.slice(1):n.slice(1,-1)),z(t,{href:n?n.replace(this.rules.inline._escapes,"$1"):n,title:s?s.replace(this.rules.inline._escapes,"$1"):s},t[0],this.lexer)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=(n[2]||n[1]).replace(/\s+/g," ");if(e=t[e.toLowerCase()],!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return z(n,e,n[0],this.lexer)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrong.lDelim.exec(e);if(!s)return;if(s[3]&&n.match(/[\p{L}\p{N}]/u))return;const r=s[1]||s[2]||"";if(!r||r&&(""===n||this.rules.inline.punctuation.exec(n))){const n=s[0].length-1;let r,i,l=n,o=0;const a="*"===s[0][0]?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(a.lastIndex=0,t=t.slice(-1*e.length+n);null!=(s=a.exec(t));){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(i=r.length,s[3]||s[4]){l+=i;continue}if((s[5]||s[6])&&n%3&&!((n+i)%3)){o+=i;continue}if(l-=i,l>0)continue;i=Math.min(i,i+l+o);const t=e.slice(0,n+s.index+(s[0].length-r.length)+i);if(Math.min(n,i)%2){const e=t.slice(1,-1);return{type:"em",raw:t,text:e,tokens:this.lexer.inlineTokens(e)}}const a=t.slice(2,-2);return{type:"strong",raw:t,text:a,tokens:this.lexer.inlineTokens(a)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(/\n/g," ");const n=/[^ ]/.test(e),s=/^ /.test(e)&&/ $/.test(e);return n&&s&&(e=e.substring(1,e.length-1)),e=a(e,!0),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e,t){const n=this.rules.inline.autolink.exec(e);if(n){let e,s;return"@"===n[2]?(e=a(this.options.mangle?t(n[1]):n[1]),s="mailto:"+e):(e=a(n[1]),s=e),{type:"link",raw:n[0],text:e,href:s,tokens:[{type:"text",raw:e,text:e}]}}}url(e,t){let n;if(n=this.rules.inline.url.exec(e)){let e,s;if("@"===n[2])e=a(this.options.mangle?t(n[0]):n[0]),s="mailto:"+e;else{let t;do{t=n[0],n[0]=this.rules.inline._backpedal.exec(n[0])[0]}while(t!==n[0]);e=a(n[0]),s="www."===n[1]?"http://"+n[0]:n[0]}return{type:"link",raw:n[0],text:e,href:s,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e,t){const n=this.rules.inline.text.exec(e);if(n){let e;return e=this.lexer.state.inRawBlock?this.options.sanitize?this.options.sanitizer?this.options.sanitizer(n[0]):a(n[0]):n[0]:a(this.options.smartypants?t(n[0]):n[0]),{type:"text",raw:n[0],text:e}}}}const R={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:w,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/,_label:/(?!\s*\])(?:\\.|[^\[\]\\])+/,_title:/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/};R.def=u(R.def).replace("label",R._label).replace("title",R._title).getRegex(),R.bullet=/(?:[*+-]|\d{1,9}[.)])/,R.listItemStart=u(/^( *)(bull) */).replace("bull",R.bullet).getRegex(),R.list=u(R.list).replace(/bull/g,R.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+R.def.source+")").getRegex(),R._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",R._comment=/<!--(?!-?>)[\s\S]*?(?:-->|$)/,R.html=u(R.html,"i").replace("comment",R._comment).replace("tag",R._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),R.paragraph=u(R._paragraph).replace("hr",R.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",R._tag).getRegex(),R.blockquote=u(R.blockquote).replace("paragraph",R.paragraph).getRegex(),R.normal={...R},R.gfm={...R.normal,table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"},R.gfm.table=u(R.gfm.table).replace("hr",R.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",R._tag).getRegex(),R.gfm.paragraph=u(R._paragraph).replace("hr",R.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",R.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",R._tag).getRegex(),R.pedantic={...R.normal,html:u("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",R._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:w,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:u(R.normal._paragraph).replace("hr",R.hr).replace("heading"," *#{1,6} *[^\n]").replace("lheading",R.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const T={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:w,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:w,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^([\spunctuation])/};function A(e){return e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")}function E(e){let t,n,s="";const r=e.length;for(t=0;t<r;t++)n=e.charCodeAt(t),Math.random()>.5&&(n="x"+n.toString(16)),s+="&#"+n+";";return s}T._punctuation="!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~",T.punctuation=u(T.punctuation).replace(/punctuation/g,T._punctuation).getRegex(),T.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,T.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g,T._comment=u(R._comment).replace("(?:--\x3e|$)","--\x3e").getRegex(),T.emStrong.lDelim=u(T.emStrong.lDelim).replace(/punct/g,T._punctuation).getRegex(),T.emStrong.rDelimAst=u(T.emStrong.rDelimAst,"g").replace(/punct/g,T._punctuation).getRegex(),T.emStrong.rDelimUnd=u(T.emStrong.rDelimUnd,"g").replace(/punct/g,T._punctuation).getRegex(),T._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,T._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,T._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,T.autolink=u(T.autolink).replace("scheme",T._scheme).replace("email",T._email).getRegex(),T._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,T.tag=u(T.tag).replace("comment",T._comment).replace("attribute",T._attribute).getRegex(),T._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,T._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,T._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,T.link=u(T.link).replace("label",T._label).replace("href",T._href).replace("title",T._title).getRegex(),T.reflink=u(T.reflink).replace("label",T._label).replace("ref",R._label).getRegex(),T.nolink=u(T.nolink).replace("ref",R._label).getRegex(),T.reflinkSearch=u(T.reflinkSearch,"g").replace("reflink",T.reflink).replace("nolink",T.nolink).getRegex(),T.normal={...T},T.pedantic={...T.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:u(/^!?\[(label)\]\((.*?)\)/).replace("label",T._label).getRegex(),reflink:u(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",T._label).getRegex()},T.gfm={...T.normal,escape:u(T.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},T.gfm.url=u(T.gfm.url,"i").replace("email",T.gfm._extended_email).getRegex(),T.breaks={...T.gfm,br:u(T.br).replace("{2,}","*").getRegex(),text:u(T.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};class v{constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||t,this.options.tokenizer=this.options.tokenizer||new S,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:R.normal,inline:T.normal};this.options.pedantic?(n.block=R.pedantic,n.inline=T.pedantic):this.options.gfm&&(n.block=R.gfm,this.options.breaks?n.inline=T.breaks:n.inline=T.gfm),this.tokenizer.rules=n}static get rules(){return{block:R,inline:T}}static lex(e,t){return new v(t).lex(e)}static lexInline(e,t){return new v(t).inlineTokens(e)}lex(e){let t;for(e=e.replace(/\r\n|\r/g,"\n"),this.blockTokens(e,this.tokens);t=this.inlineQueue.shift();)this.inlineTokens(t.src,t.tokens);return this.tokens}blockTokens(e,t=[]){let n,s,r,i;for(e=this.options.pedantic?e.replace(/\t/g," ").replace(/^ +$/gm,""):e.replace(/^( *)(\t+)/gm,((e,t,n)=>t+" ".repeat(n.length)));e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.space(e))e=e.substring(n.raw.length),1===n.raw.length&&t.length>0?t[t.length-1].raw+="\n":t.push(n);else if(n=this.tokenizer.code(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?t.push(n):(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.fences(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.heading(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.hr(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.blockquote(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.list(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.html(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.def(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title}):(s.raw+="\n"+n.raw,s.text+="\n"+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.table(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.lheading(e))e=e.substring(n.raw.length),t.push(n);else{if(r=e,this.options.extensions&&this.options.extensions.startBlock){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startBlock.forEach((function(e){s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(this.state.top&&(n=this.tokenizer.paragraph(r)))s=t[t.length-1],i&&"paragraph"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n),i=r.length!==e.length,e=e.substring(n.raw.length);else if(n=this.tokenizer.text(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,s,r,i,l,o,a=e;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(a));)e.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+$("a",i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(a));)a=a.slice(0,i.index)+"["+$("a",i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.escapedEmSt.exec(a));)a=a.slice(0,i.index+i[0].length-2)+"++"+a.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex),this.tokenizer.rules.inline.escapedEmSt.lastIndex--;for(;e;)if(l||(o=""),l=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.escape(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.tag(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.link(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.reflink(e,this.tokens.links))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.emStrong(e,a,o))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.codespan(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.br(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.del(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.autolink(e,E))e=e.substring(n.raw.length),t.push(n);else if(this.state.inLink||!(n=this.tokenizer.url(e,E))){if(r=e,this.options.extensions&&this.options.extensions.startInline){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startInline.forEach((function(e){s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(n=this.tokenizer.inlineText(r,A))e=e.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),l=!0,s=t[t.length-1],s&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}else e=e.substring(n.raw.length),t.push(n);return t}}class I{constructor(e){this.options=e||t}code(e,t,n){const s=(t||"").match(/\S*/)[0];if(this.options.highlight){const t=this.options.highlight(e,s);null!=t&&t!==e&&(n=!0,e=t)}return e=e.replace(/\n$/,"")+"\n",s?'<pre><code class="'+this.options.langPrefix+a(s)+'">'+(n?e:a(e,!0))+"</code></pre>\n":"<pre><code>"+(n?e:a(e,!0))+"</code></pre>\n"}blockquote(e){return`<blockquote>\n${e}</blockquote>\n`}html(e){return e}heading(e,t,n,s){if(this.options.headerIds){return`<h${t} id="${this.options.headerPrefix+s.slug(n)}">${e}</h${t}>\n`}return`<h${t}>${e}</h${t}>\n`}hr(){return this.options.xhtml?"<hr/>\n":"<hr>\n"}list(e,t,n){const s=t?"ol":"ul";return"<"+s+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"</"+s+">\n"}listitem(e){return`<li>${e}</li>\n`}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"'+(this.options.xhtml?" /":"")+"> "}paragraph(e){return`<p>${e}</p>\n`}table(e,t){return t&&(t=`<tbody>${t}</tbody>`),"<table>\n<thead>\n"+e+"</thead>\n"+t+"</table>\n"}tablerow(e){return`<tr>\n${e}</tr>\n`}tablecell(e,t){const n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>\n`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(e){return`<del>${e}</del>`}link(e,t,n){if(null===(e=f(this.options.sanitize,this.options.baseUrl,e)))return n;let s='<a href="'+e+'"';return t&&(s+=' title="'+t+'"'),s+=">"+n+"</a>",s}image(e,t,n){if(null===(e=f(this.options.sanitize,this.options.baseUrl,e)))return n;let s=`<img src="${e}" alt="${n}"`;return t&&(s+=` title="${t}"`),s+=this.options.xhtml?"/>":">",s}text(e){return e}}class q{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,n){return""+n}image(e,t,n){return""+n}br(){return""}}class L{constructor(){this.seen={}}serialize(e){return e.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(e,t){let n=e,s=0;if(this.seen.hasOwnProperty(n)){s=this.seen[e];do{s++,n=e+"-"+s}while(this.seen.hasOwnProperty(n))}return t||(this.seen[e]=s,this.seen[n]=0),n}slug(e,t={}){const n=this.serialize(e);return this.getNextSafeSlug(n,t.dryrun)}}class C{constructor(e){this.options=e||t,this.options.renderer=this.options.renderer||new I,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new q,this.slugger=new L}static parse(e,t){return new C(t).parse(e)}static parseInline(e,t){return new C(t).parseInline(e)}parse(e,t=!0){let n,s,r,i,l,o,a,c,p,u,g,d,f,k,x,m,b,w,_,y="";const $=e.length;for(n=0;n<$;n++)if(u=e[n],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[u.type]&&(_=this.options.extensions.renderers[u.type].call({parser:this},u),!1!==_||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(u.type)))y+=_||"";else switch(u.type){case"space":continue;case"hr":y+=this.renderer.hr();continue;case"heading":y+=this.renderer.heading(this.parseInline(u.tokens),u.depth,h(this.parseInline(u.tokens,this.textRenderer)),this.slugger);continue;case"code":y+=this.renderer.code(u.text,u.lang,u.escaped);continue;case"table":for(c="",a="",i=u.header.length,s=0;s<i;s++)a+=this.renderer.tablecell(this.parseInline(u.header[s].tokens),{header:!0,align:u.align[s]});for(c+=this.renderer.tablerow(a),p="",i=u.rows.length,s=0;s<i;s++){for(o=u.rows[s],a="",l=o.length,r=0;r<l;r++)a+=this.renderer.tablecell(this.parseInline(o[r].tokens),{header:!1,align:u.align[r]});p+=this.renderer.tablerow(a)}y+=this.renderer.table(c,p);continue;case"blockquote":p=this.parse(u.tokens),y+=this.renderer.blockquote(p);continue;case"list":for(g=u.ordered,d=u.start,f=u.loose,i=u.items.length,p="",s=0;s<i;s++)x=u.items[s],m=x.checked,b=x.task,k="",x.task&&(w=this.renderer.checkbox(m),f?x.tokens.length>0&&"paragraph"===x.tokens[0].type?(x.tokens[0].text=w+" "+x.tokens[0].text,x.tokens[0].tokens&&x.tokens[0].tokens.length>0&&"text"===x.tokens[0].tokens[0].type&&(x.tokens[0].tokens[0].text=w+" "+x.tokens[0].tokens[0].text)):x.tokens.unshift({type:"text",text:w}):k+=w),k+=this.parse(x.tokens,f),p+=this.renderer.listitem(k,b,m);y+=this.renderer.list(p,g,d);continue;case"html":y+=this.renderer.html(u.text);continue;case"paragraph":y+=this.renderer.paragraph(this.parseInline(u.tokens));continue;case"text":for(p=u.tokens?this.parseInline(u.tokens):u.text;n+1<$&&"text"===e[n+1].type;)u=e[++n],p+="\n"+(u.tokens?this.parseInline(u.tokens):u.text);y+=t?this.renderer.paragraph(p):p;continue;default:{const e='Token with "'+u.type+'" type was not found.';if(this.options.silent)return void console.error(e);throw new Error(e)}}return y}parseInline(e,t){t=t||this.renderer;let n,s,r,i="";const l=e.length;for(n=0;n<l;n++)if(s=e[n],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]&&(r=this.options.extensions.renderers[s.type].call({parser:this},s),!1!==r||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)))i+=r||"";else switch(s.type){case"escape":case"text":i+=t.text(s.text);break;case"html":i+=t.html(s.text);break;case"link":i+=t.link(s.href,s.title,this.parseInline(s.tokens,t));break;case"image":i+=t.image(s.href,s.title,s.text);break;case"strong":i+=t.strong(this.parseInline(s.tokens,t));break;case"em":i+=t.em(this.parseInline(s.tokens,t));break;case"codespan":i+=t.codespan(s.text);break;case"br":i+=t.br();break;case"del":i+=t.del(this.parseInline(s.tokens,t));break;default:{const e='Token with "'+s.type+'" type was not found.';if(this.options.silent)return void console.error(e);throw new Error(e)}}return i}}class Z{constructor(e){this.options=e||t}static passThroughHooks=new Set(["preprocess","postprocess"]);preprocess(e){return e}postproces
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
true
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/notes/plugin.js
plugin/notes/plugin.js
import speakerViewHTML from './speaker-view.html' import { marked } from 'marked'; /** * Handles opening of and synchronization with the reveal.js * notes window. * * Handshake process: * 1. This window posts 'connect' to notes window * - Includes URL of presentation to show * 2. Notes window responds with 'connected' when it is available * 3. This window proceeds to send the current presentation state * to the notes window */ const Plugin = () => { let connectInterval; let speakerWindow = null; let deck; /** * Opens a new speaker view window. */ function openSpeakerWindow() { // If a window is already open, focus it if( speakerWindow && !speakerWindow.closed ) { speakerWindow.focus(); } else { speakerWindow = window.open( 'about:blank', 'reveal.js - Notes', 'width=1100,height=700' ); speakerWindow.marked = marked; speakerWindow.document.write( speakerViewHTML ); if( !speakerWindow ) { alert( 'Speaker view popup failed to open. Please make sure popups are allowed and reopen the speaker view.' ); return; } connect(); } } /** * Reconnect with an existing speaker view window. */ function reconnectSpeakerWindow( reconnectWindow ) { if( speakerWindow && !speakerWindow.closed ) { speakerWindow.focus(); } else { speakerWindow = reconnectWindow; window.addEventListener( 'message', onPostMessage ); onConnected(); } } /** * Connect to the notes window through a postmessage handshake. * Using postmessage enables us to work in situations where the * origins differ, such as a presentation being opened from the * file system. */ function connect() { const presentationURL = deck.getConfig().url; const url = typeof presentationURL === 'string' ? presentationURL : window.location.protocol + '//' + window.location.host + window.location.pathname + window.location.search; // Keep trying to connect until we get a 'connected' message back connectInterval = setInterval( function() { speakerWindow.postMessage( JSON.stringify( { namespace: 'reveal-notes', type: 'connect', state: deck.getState(), url } ), '*' ); }, 500 ); window.addEventListener( 'message', onPostMessage ); } /** * Calls the specified Reveal.js method with the provided argument * and then pushes the result to the notes frame. */ function callRevealApi( methodName, methodArguments, callId ) { let result = deck[methodName].apply( deck, methodArguments ); speakerWindow.postMessage( JSON.stringify( { namespace: 'reveal-notes', type: 'return', result, callId } ), '*' ); } /** * Posts the current slide data to the notes window. */ function post( event ) { let slideElement = deck.getCurrentSlide(), notesElements = slideElement.querySelectorAll( 'aside.notes' ), fragmentElement = slideElement.querySelector( '.current-fragment' ); let messageData = { namespace: 'reveal-notes', type: 'state', notes: '', markdown: false, whitespace: 'normal', state: deck.getState() }; // Look for notes defined in a slide attribute if( slideElement.hasAttribute( 'data-notes' ) ) { messageData.notes = slideElement.getAttribute( 'data-notes' ); messageData.whitespace = 'pre-wrap'; } // Look for notes defined in a fragment if( fragmentElement ) { let fragmentNotes = fragmentElement.querySelector( 'aside.notes' ); if( fragmentNotes ) { messageData.notes = fragmentNotes.innerHTML; messageData.markdown = typeof fragmentNotes.getAttribute( 'data-markdown' ) === 'string'; // Ignore other slide notes notesElements = null; } else if( fragmentElement.hasAttribute( 'data-notes' ) ) { messageData.notes = fragmentElement.getAttribute( 'data-notes' ); messageData.whitespace = 'pre-wrap'; // In case there are slide notes notesElements = null; } } // Look for notes defined in an aside element if( notesElements && notesElements.length ) { // Ignore notes inside of fragments since those are shown // individually when stepping through fragments notesElements = Array.from( notesElements ).filter( notesElement => notesElement.closest( '.fragment' ) === null ); messageData.notes = notesElements.map( notesElement => notesElement.innerHTML ).join( '\n' ); messageData.markdown = notesElements[0] && typeof notesElements[0].getAttribute( 'data-markdown' ) === 'string'; } speakerWindow.postMessage( JSON.stringify( messageData ), '*' ); } /** * Check if the given event is from the same origin as the * current window. */ function isSameOriginEvent( event ) { try { return window.location.origin === event.source.location.origin; } catch ( error ) { return false; } } function onPostMessage( event ) { // Only allow same-origin messages // (added 12/5/22 as a XSS safeguard) if( isSameOriginEvent( event ) ) { try { let data = JSON.parse( event.data ); if( data && data.namespace === 'reveal-notes' && data.type === 'connected' ) { clearInterval( connectInterval ); onConnected(); } else if( data && data.namespace === 'reveal-notes' && data.type === 'call' ) { callRevealApi( data.methodName, data.arguments, data.callId ); } } catch (e) {} } } /** * Called once we have established a connection to the notes * window. */ function onConnected() { // Monitor events that trigger a change in state deck.on( 'slidechanged', post ); deck.on( 'fragmentshown', post ); deck.on( 'fragmenthidden', post ); deck.on( 'overviewhidden', post ); deck.on( 'overviewshown', post ); deck.on( 'paused', post ); deck.on( 'resumed', post ); deck.on( 'previewiframe', post ); deck.on( 'previewimage', post ); deck.on( 'previewvideo', post ); deck.on( 'closeoverlay', post ); // Post the initial state post(); } return { id: 'notes', init: function( reveal ) { deck = reveal; if( !/receiver/i.test( window.location.search ) ) { // If the there's a 'notes' query set, open directly if( window.location.search.match( /(\?|\&)notes/gi ) !== null ) { openSpeakerWindow(); } else { // Keep listening for speaker view heartbeats. If we receive a // heartbeat from an orphaned window, reconnect it. This ensures // that we remain connected to the notes even if the presentation // is reloaded. window.addEventListener( 'message', event => { if( !speakerWindow && typeof event.data === 'string' ) { let data; try { data = JSON.parse( event.data ); } catch( error ) {} if( data && data.namespace === 'reveal-notes' && data.type === 'heartbeat' ) { reconnectSpeakerWindow( event.source ); } } }); } // Open the notes when the 's' key is hit deck.addKeyBinding({keyCode: 83, key: 'S', description: 'Speaker notes view'}, function() { openSpeakerWindow(); } ); } }, open: openSpeakerWindow }; }; export default Plugin;
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/notes/notes.esm.js
plugin/notes/notes.esm.js
function t(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let e={async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1};const n=/[&<>"']/,i=new RegExp(n.source,"g"),s=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,r=new RegExp(s.source,"g"),a={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},o=t=>a[t];function l(t,e){if(e){if(n.test(t))return t.replace(i,o)}else if(s.test(t))return t.replace(r,o);return t}const c=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function p(t){return t.replace(c,((t,e)=>"colon"===(e=e.toLowerCase())?":":"#"===e.charAt(0)?"x"===e.charAt(1)?String.fromCharCode(parseInt(e.substring(2),16)):String.fromCharCode(+e.substring(1)):""))}const u=/(^|[^\[])\^/g;function d(t,e){t="string"==typeof t?t:t.source,e=e||"";const n={replace:(e,i)=>(i=(i=i.source||i).replace(u,"$1"),t=t.replace(e,i),n),getRegex:()=>new RegExp(t,e)};return n}const h=/[^\w:]/g,g=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function m(t,e,n){if(t){let t;try{t=decodeURIComponent(p(n)).replace(h,"").toLowerCase()}catch(t){return null}if(0===t.indexOf("javascript:")||0===t.indexOf("vbscript:")||0===t.indexOf("data:"))return null}e&&!g.test(n)&&(n=function(t,e){f[" "+t]||(k.test(t)?f[" "+t]=t+"/":f[" "+t]=v(t,"/",!0));t=f[" "+t];const n=-1===t.indexOf(":");return"//"===e.substring(0,2)?n?e:t.replace(w,"$1")+e:"/"===e.charAt(0)?n?e:t.replace(x,"$1")+e:t+e}(e,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch(t){return null}return n}const f={},k=/^[^:]+:\/*[^/]*$/,w=/^([^:]+:)[\s\S]*$/,x=/^([^:]+:\/*[^/]*)[\s\S]*$/;const b={exec:function(){}};function y(t,e){const n=t.replace(/\|/g,((t,e,n)=>{let i=!1,s=e;for(;--s>=0&&"\\"===n[s];)i=!i;return i?"|":" |"})).split(/ \|/);let i=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(/\\\|/g,"|");return n}function v(t,e,n){const i=t.length;if(0===i)return"";let s=0;for(;s<i;){const r=t.charAt(i-s-1);if(r!==e||n){if(r===e||!n)break;s++}else s++}return t.slice(0,i-s)}function S(t,e){if(e<1)return"";let n="";for(;e>1;)1&e&&(n+=t),e>>=1,t+=t;return n+t}function T(t,e,n,i){const s=e.href,r=e.title?l(e.title):null,a=t[1].replace(/\\([\[\]])/g,"$1");if("!"!==t[0].charAt(0)){i.state.inLink=!0;const t={type:"link",raw:n,href:s,title:r,text:a,tokens:i.inlineTokens(a)};return i.state.inLink=!1,t}return{type:"image",raw:n,href:s,title:r,text:l(a)}}class _{constructor(t){this.options=t||e}space(t){const e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){const e=this.rules.block.code.exec(t);if(e){const t=e[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?t:v(t,"\n")}}}fences(t){const e=this.rules.block.fences.exec(t);if(e){const t=e[0],n=function(t,e){const n=t.match(/^(\s+)(?:```)/);if(null===n)return e;const i=n[1];return e.split("\n").map((t=>{const e=t.match(/^\s+/);if(null===e)return t;const[n]=e;return n.length>=i.length?t.slice(i.length):t})).join("\n")}(t,e[3]||"");return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline._escapes,"$1"):e[2],text:n}}}heading(t){const e=this.rules.block.heading.exec(t);if(e){let t=e[2].trim();if(/#$/.test(t)){const e=v(t,"#");this.options.pedantic?t=e.trim():e&&!/ $/.test(e)||(t=e.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(t){const e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:e[0]}}blockquote(t){const e=this.rules.block.blockquote.exec(t);if(e){const t=e[0].replace(/^ *>[ \t]?/gm,""),n=this.lexer.state.top;this.lexer.state.top=!0;const i=this.lexer.blockTokens(t);return this.lexer.state.top=n,{type:"blockquote",raw:e[0],tokens:i,text:t}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n,i,s,r,a,o,l,c,p,u,d,h,g=e[1].trim();const m=g.length>1,f={type:"list",raw:"",ordered:m,start:m?+g.slice(0,-1):"",loose:!1,items:[]};g=m?`\\d{1,9}\\${g.slice(-1)}`:`\\${g}`,this.options.pedantic&&(g=m?g:"[*+-]");const k=new RegExp(`^( {0,3}${g})((?:[\t ][^\\n]*)?(?:\\n|$))`);for(;t&&(h=!1,e=k.exec(t))&&!this.rules.block.hr.test(t);){if(n=e[0],t=t.substring(n.length),c=e[2].split("\n",1)[0].replace(/^\t+/,(t=>" ".repeat(3*t.length))),p=t.split("\n",1)[0],this.options.pedantic?(r=2,d=c.trimLeft()):(r=e[2].search(/[^ ]/),r=r>4?1:r,d=c.slice(r),r+=e[1].length),o=!1,!c&&/^ *$/.test(p)&&(n+=p+"\n",t=t.substring(p.length+1),h=!0),!h){const e=new RegExp(`^ {0,${Math.min(3,r-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),i=new RegExp(`^ {0,${Math.min(3,r-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),s=new RegExp(`^ {0,${Math.min(3,r-1)}}(?:\`\`\`|~~~)`),a=new RegExp(`^ {0,${Math.min(3,r-1)}}#`);for(;t&&(u=t.split("\n",1)[0],p=u,this.options.pedantic&&(p=p.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),!s.test(p))&&!a.test(p)&&!e.test(p)&&!i.test(t);){if(p.search(/[^ ]/)>=r||!p.trim())d+="\n"+p.slice(r);else{if(o)break;if(c.search(/[^ ]/)>=4)break;if(s.test(c))break;if(a.test(c))break;if(i.test(c))break;d+="\n"+p}o||p.trim()||(o=!0),n+=u+"\n",t=t.substring(u.length+1),c=p.slice(r)}}f.loose||(l?f.loose=!0:/\n *\n *$/.test(n)&&(l=!0)),this.options.gfm&&(i=/^\[[ xX]\] /.exec(d),i&&(s="[ ] "!==i[0],d=d.replace(/^\[[ xX]\] +/,""))),f.items.push({type:"list_item",raw:n,task:!!i,checked:s,loose:!1,text:d}),f.raw+=n}f.items[f.items.length-1].raw=n.trimRight(),f.items[f.items.length-1].text=d.trimRight(),f.raw=f.raw.trimRight();const w=f.items.length;for(a=0;a<w;a++)if(this.lexer.state.top=!1,f.items[a].tokens=this.lexer.blockTokens(f.items[a].text,[]),!f.loose){const t=f.items[a].tokens.filter((t=>"space"===t.type)),e=t.length>0&&t.some((t=>/\n.*\n/.test(t.raw)));f.loose=e}if(f.loose)for(a=0;a<w;a++)f.items[a].loose=!0;return f}}html(t){const e=this.rules.block.html.exec(t);if(e){const t={type:"html",raw:e[0],pre:!this.options.sanitizer&&("pre"===e[1]||"script"===e[1]||"style"===e[1]),text:e[0]};if(this.options.sanitize){const n=this.options.sanitizer?this.options.sanitizer(e[0]):l(e[0]);t.type="paragraph",t.text=n,t.tokens=this.lexer.inline(n)}return t}}def(t){const e=this.rules.block.def.exec(t);if(e){const t=e[1].toLowerCase().replace(/\s+/g," "),n=e[2]?e[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline._escapes,"$1"):"",i=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline._escapes,"$1"):e[3];return{type:"def",tag:t,raw:e[0],href:n,title:i}}}table(t){const e=this.rules.block.table.exec(t);if(e){const t={type:"table",header:y(e[1]).map((t=>({text:t}))),align:e[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:e[3]&&e[3].trim()?e[3].replace(/\n[ \t]*$/,"").split("\n"):[]};if(t.header.length===t.align.length){t.raw=e[0];let n,i,s,r,a=t.align.length;for(n=0;n<a;n++)/^ *-+: *$/.test(t.align[n])?t.align[n]="right":/^ *:-+: *$/.test(t.align[n])?t.align[n]="center":/^ *:-+ *$/.test(t.align[n])?t.align[n]="left":t.align[n]=null;for(a=t.rows.length,n=0;n<a;n++)t.rows[n]=y(t.rows[n],t.header.length).map((t=>({text:t})));for(a=t.header.length,i=0;i<a;i++)t.header[i].tokens=this.lexer.inline(t.header[i].text);for(a=t.rows.length,i=0;i<a;i++)for(r=t.rows[i],s=0;s<r.length;s++)r[s].tokens=this.lexer.inline(r[s].text);return t}}}lheading(t){const e=this.rules.block.lheading.exec(t);if(e)return{type:"heading",raw:e[0],depth:"="===e[2].charAt(0)?1:2,text:e[1],tokens:this.lexer.inline(e[1])}}paragraph(t){const e=this.rules.block.paragraph.exec(t);if(e){const t="\n"===e[1].charAt(e[1].length-1)?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(t){const e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){const e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:l(e[1])}}tag(t){const e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&/^<a /i.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(e[0]):l(e[0]):e[0]}}link(t){const e=this.rules.inline.link.exec(t);if(e){const t=e[2].trim();if(!this.options.pedantic&&/^</.test(t)){if(!/>$/.test(t))return;const e=v(t.slice(0,-1),"\\");if((t.length-e.length)%2==0)return}else{const t=function(t,e){if(-1===t.indexOf(e[1]))return-1;const n=t.length;let i=0,s=0;for(;s<n;s++)if("\\"===t[s])s++;else if(t[s]===e[0])i++;else if(t[s]===e[1]&&(i--,i<0))return s;return-1}(e[2],"()");if(t>-1){const n=(0===e[0].indexOf("!")?5:4)+e[1].length+t;e[2]=e[2].substring(0,t),e[0]=e[0].substring(0,n).trim(),e[3]=""}}let n=e[2],i="";if(this.options.pedantic){const t=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);t&&(n=t[1],i=t[3])}else i=e[3]?e[3].slice(1,-1):"";return n=n.trim(),/^</.test(n)&&(n=this.options.pedantic&&!/>$/.test(t)?n.slice(1):n.slice(1,-1)),T(e,{href:n?n.replace(this.rules.inline._escapes,"$1"):n,title:i?i.replace(this.rules.inline._escapes,"$1"):i},e[0],this.lexer)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let t=(n[2]||n[1]).replace(/\s+/g," ");if(t=e[t.toLowerCase()],!t){const t=n[0].charAt(0);return{type:"text",raw:t,text:t}}return T(n,t,n[0],this.lexer)}}emStrong(t,e,n=""){let i=this.rules.inline.emStrong.lDelim.exec(t);if(!i)return;if(i[3]&&n.match(/[\p{L}\p{N}]/u))return;const s=i[1]||i[2]||"";if(!s||s&&(""===n||this.rules.inline.punctuation.exec(n))){const n=i[0].length-1;let s,r,a=n,o=0;const l="*"===i[0][0]?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(l.lastIndex=0,e=e.slice(-1*t.length+n);null!=(i=l.exec(e));){if(s=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!s)continue;if(r=s.length,i[3]||i[4]){a+=r;continue}if((i[5]||i[6])&&n%3&&!((n+r)%3)){o+=r;continue}if(a-=r,a>0)continue;r=Math.min(r,r+a+o);const e=t.slice(0,n+i.index+(i[0].length-s.length)+r);if(Math.min(n,r)%2){const t=e.slice(1,-1);return{type:"em",raw:e,text:t,tokens:this.lexer.inlineTokens(t)}}const l=e.slice(2,-2);return{type:"strong",raw:e,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(t){const e=this.rules.inline.code.exec(t);if(e){let t=e[2].replace(/\n/g," ");const n=/[^ ]/.test(t),i=/^ /.test(t)&&/ $/.test(t);return n&&i&&(t=t.substring(1,t.length-1)),t=l(t,!0),{type:"codespan",raw:e[0],text:t}}}br(t){const e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t){const e=this.rules.inline.del.exec(t);if(e)return{type:"del",raw:e[0],text:e[2],tokens:this.lexer.inlineTokens(e[2])}}autolink(t,e){const n=this.rules.inline.autolink.exec(t);if(n){let t,i;return"@"===n[2]?(t=l(this.options.mangle?e(n[1]):n[1]),i="mailto:"+t):(t=l(n[1]),i=t),{type:"link",raw:n[0],text:t,href:i,tokens:[{type:"text",raw:t,text:t}]}}}url(t,e){let n;if(n=this.rules.inline.url.exec(t)){let t,i;if("@"===n[2])t=l(this.options.mangle?e(n[0]):n[0]),i="mailto:"+t;else{let e;do{e=n[0],n[0]=this.rules.inline._backpedal.exec(n[0])[0]}while(e!==n[0]);t=l(n[0]),i="www."===n[1]?"http://"+n[0]:n[0]}return{type:"link",raw:n[0],text:t,href:i,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(t,e){const n=this.rules.inline.text.exec(t);if(n){let t;return t=this.lexer.state.inRawBlock?this.options.sanitize?this.options.sanitizer?this.options.sanitizer(n[0]):l(n[0]):n[0]:l(this.options.smartypants?e(n[0]):n[0]),{type:"text",raw:n[0],text:t}}}}const z={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:b,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/,_label:/(?!\s*\])(?:\\.|[^\[\]\\])+/,_title:/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/};z.def=d(z.def).replace("label",z._label).replace("title",z._title).getRegex(),z.bullet=/(?:[*+-]|\d{1,9}[.)])/,z.listItemStart=d(/^( *)(bull) */).replace("bull",z.bullet).getRegex(),z.list=d(z.list).replace(/bull/g,z.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+z.def.source+")").getRegex(),z._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",z._comment=/<!--(?!-?>)[\s\S]*?(?:-->|$)/,z.html=d(z.html,"i").replace("comment",z._comment).replace("tag",z._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),z.paragraph=d(z._paragraph).replace("hr",z.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",z._tag).getRegex(),z.blockquote=d(z.blockquote).replace("paragraph",z.paragraph).getRegex(),z.normal={...z},z.gfm={...z.normal,table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"},z.gfm.table=d(z.gfm.table).replace("hr",z.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",z._tag).getRegex(),z.gfm.paragraph=d(z._paragraph).replace("hr",z.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",z.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",z._tag).getRegex(),z.pedantic={...z.normal,html:d("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",z._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:b,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(z.normal._paragraph).replace("hr",z.hr).replace("heading"," *#{1,6} *[^\n]").replace("lheading",z.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const $={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:b,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:b,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^([\spunctuation])/};function E(t){return t.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")}function A(t){let e,n,i="";const s=t.length;for(e=0;e<s;e++)n=t.charCodeAt(e),Math.random()>.5&&(n="x"+n.toString(16)),i+="&#"+n+";";return i}$._punctuation="!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~",$.punctuation=d($.punctuation).replace(/punctuation/g,$._punctuation).getRegex(),$.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,$.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g,$._comment=d(z._comment).replace("(?:--\x3e|$)","--\x3e").getRegex(),$.emStrong.lDelim=d($.emStrong.lDelim).replace(/punct/g,$._punctuation).getRegex(),$.emStrong.rDelimAst=d($.emStrong.rDelimAst,"g").replace(/punct/g,$._punctuation).getRegex(),$.emStrong.rDelimUnd=d($.emStrong.rDelimUnd,"g").replace(/punct/g,$._punctuation).getRegex(),$._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,$._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,$._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,$.autolink=d($.autolink).replace("scheme",$._scheme).replace("email",$._email).getRegex(),$._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,$.tag=d($.tag).replace("comment",$._comment).replace("attribute",$._attribute).getRegex(),$._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,$._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,$._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,$.link=d($.link).replace("label",$._label).replace("href",$._href).replace("title",$._title).getRegex(),$.reflink=d($.reflink).replace("label",$._label).replace("ref",z._label).getRegex(),$.nolink=d($.nolink).replace("ref",z._label).getRegex(),$.reflinkSearch=d($.reflinkSearch,"g").replace("reflink",$.reflink).replace("nolink",$.nolink).getRegex(),$.normal={...$},$.pedantic={...$.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:d(/^!?\[(label)\]\((.*?)\)/).replace("label",$._label).getRegex(),reflink:d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",$._label).getRegex()},$.gfm={...$.normal,escape:d($.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},$.gfm.url=d($.gfm.url,"i").replace("email",$.gfm._extended_email).getRegex(),$.breaks={...$.gfm,br:d($.br).replace("{2,}","*").getRegex(),text:d($.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};class R{constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||e,this.options.tokenizer=this.options.tokenizer||new _,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:z.normal,inline:$.normal};this.options.pedantic?(n.block=z.pedantic,n.inline=$.pedantic):this.options.gfm&&(n.block=z.gfm,this.options.breaks?n.inline=$.breaks:n.inline=$.gfm),this.tokenizer.rules=n}static get rules(){return{block:z,inline:$}}static lex(t,e){return new R(e).lex(t)}static lexInline(t,e){return new R(e).inlineTokens(t)}lex(t){let e;for(t=t.replace(/\r\n|\r/g,"\n"),this.blockTokens(t,this.tokens);e=this.inlineQueue.shift();)this.inlineTokens(e.src,e.tokens);return this.tokens}blockTokens(t,e=[]){let n,i,s,r;for(t=this.options.pedantic?t.replace(/\t/g," ").replace(/^ +$/gm,""):t.replace(/^( *)(\t+)/gm,((t,e,n)=>e+" ".repeat(n.length)));t;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some((i=>!!(n=i.call({lexer:this},t,e))&&(t=t.substring(n.raw.length),e.push(n),!0)))))if(n=this.tokenizer.space(t))t=t.substring(n.raw.length),1===n.raw.length&&e.length>0?e[e.length-1].raw+="\n":e.push(n);else if(n=this.tokenizer.code(t))t=t.substring(n.raw.length),i=e[e.length-1],!i||"paragraph"!==i.type&&"text"!==i.type?e.push(n):(i.raw+="\n"+n.raw,i.text+="\n"+n.text,this.inlineQueue[this.inlineQueue.length-1].src=i.text);else if(n=this.tokenizer.fences(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.heading(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.hr(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.blockquote(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.list(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.html(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.def(t))t=t.substring(n.raw.length),i=e[e.length-1],!i||"paragraph"!==i.type&&"text"!==i.type?this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title}):(i.raw+="\n"+n.raw,i.text+="\n"+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=i.text);else if(n=this.tokenizer.table(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.lheading(t))t=t.substring(n.raw.length),e.push(n);else{if(s=t,this.options.extensions&&this.options.extensions.startBlock){let e=1/0;const n=t.slice(1);let i;this.options.extensions.startBlock.forEach((function(t){i=t.call({lexer:this},n),"number"==typeof i&&i>=0&&(e=Math.min(e,i))})),e<1/0&&e>=0&&(s=t.substring(0,e+1))}if(this.state.top&&(n=this.tokenizer.paragraph(s)))i=e[e.length-1],r&&"paragraph"===i.type?(i.raw+="\n"+n.raw,i.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=i.text):e.push(n),r=s.length!==t.length,t=t.substring(n.raw.length);else if(n=this.tokenizer.text(t))t=t.substring(n.raw.length),i=e[e.length-1],i&&"text"===i.type?(i.raw+="\n"+n.raw,i.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=i.text):e.push(n);else if(t){const e="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(e);break}throw new Error(e)}}return this.state.top=!0,e}inline(t,e=[]){return this.inlineQueue.push({src:t,tokens:e}),e}inlineTokens(t,e=[]){let n,i,s,r,a,o,l=t;if(this.tokens.links){const t=Object.keys(this.tokens.links);if(t.length>0)for(;null!=(r=this.tokenizer.rules.inline.reflinkSearch.exec(l));)t.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(l=l.slice(0,r.index)+"["+S("a",r[0].length-2)+"]"+l.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(r=this.tokenizer.rules.inline.blockSkip.exec(l));)l=l.slice(0,r.index)+"["+S("a",r[0].length-2)+"]"+l.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(r=this.tokenizer.rules.inline.escapedEmSt.exec(l));)l=l.slice(0,r.index+r[0].length-2)+"++"+l.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex),this.tokenizer.rules.inline.escapedEmSt.lastIndex--;for(;t;)if(a||(o=""),a=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some((i=>!!(n=i.call({lexer:this},t,e))&&(t=t.substring(n.raw.length),e.push(n),!0)))))if(n=this.tokenizer.escape(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.tag(t))t=t.substring(n.raw.length),i=e[e.length-1],i&&"text"===n.type&&"text"===i.type?(i.raw+=n.raw,i.text+=n.text):e.push(n);else if(n=this.tokenizer.link(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.reflink(t,this.tokens.links))t=t.substring(n.raw.length),i=e[e.length-1],i&&"text"===n.type&&"text"===i.type?(i.raw+=n.raw,i.text+=n.text):e.push(n);else if(n=this.tokenizer.emStrong(t,l,o))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.codespan(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.br(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.del(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.autolink(t,A))t=t.substring(n.raw.length),e.push(n);else if(this.state.inLink||!(n=this.tokenizer.url(t,A))){if(s=t,this.options.extensions&&this.options.extensions.startInline){let e=1/0;const n=t.slice(1);let i;this.options.extensions.startInline.forEach((function(t){i=t.call({lexer:this},n),"number"==typeof i&&i>=0&&(e=Math.min(e,i))})),e<1/0&&e>=0&&(s=t.substring(0,e+1))}if(n=this.tokenizer.inlineText(s,E))t=t.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),a=!0,i=e[e.length-1],i&&"text"===i.type?(i.raw+=n.raw,i.text+=n.text):e.push(n);else if(t){const e="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(e);break}throw new Error(e)}}else t=t.substring(n.raw.length),e.push(n);return e}}class L{constructor(t){this.options=t||e}code(t,e,n){const i=(e||"").match(/\S*/)[0];if(this.options.highlight){const e=this.options.highlight(t,i);null!=e&&e!==t&&(n=!0,t=e)}return t=t.replace(/\n$/,"")+"\n",i?'<pre><code class="'+this.options.langPrefix+l(i)+'">'+(n?t:l(t,!0))+"</code></pre>\n":"<pre><code>"+(n?t:l(t,!0))+"</code></pre>\n"}blockquote(t){return`<blockquote>\n${t}</blockquote>\n`}html(t){return t}heading(t,e,n,i){if(this.options.headerIds){return`<h${e} id="${this.options.headerPrefix+i.slug(n)}">${t}</h${e}>\n`}return`<h${e}>${t}</h${e}>\n`}hr(){return this.options.xhtml?"<hr/>\n":"<hr>\n"}list(t,e,n){const i=e?"ol":"ul";return"<"+i+(e&&1!==n?' start="'+n+'"':"")+">\n"+t+"</"+i+">\n"}listitem(t){return`<li>${t}</li>\n`}checkbox(t){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"'+(this.options.xhtml?" /":"")+"> "}paragraph(t){return`<p>${t}</p>\n`}table(t,e){return e&&(e=`<tbody>${e}</tbody>`),"<table>\n<thead>\n"+t+"</thead>\n"+e+"</table>\n"}tablerow(t){return`<tr>\n${t}</tr>\n`}tablecell(t,e){const n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>\n`}strong(t){return`<strong>${t}</strong>`}em(t){return`<em>${t}</em>`}codespan(t){return`<code>${t}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(t){return`<del>${t}</del>`}link(t,e,n){if(null===(t=m(this.options.sanitize,this.options.baseUrl,t)))return n;let i='<a href="'+t+'"';return e&&(i+=' title="'+e+'"'),i+=">"+n+"</a>",i}image(t,e,n){if(null===(t=m(this.options.sanitize,this.options.baseUrl,t)))return n;let i=`<img src="${t}" alt="${n}"`;return e&&(i+=` title="${e}"`),i+=this.options.xhtml?"/>":">",i}text(t){return t}}class I{strong(t){return t}em(t){return t}codespan(t){return t}del(t){return t}html(t){return t}text(t){return t}link(t,e,n){return""+n}image(t,e,n){return""+n}br(){return""}}class M{constructor(){this.seen={}}serialize(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(t,e){let n=t,i=0;if(this.seen.hasOwnProperty(n)){i=this.seen[t];do{i++,n=t+"-"+i}while(this.seen.hasOwnProperty(n))}return e||(this.seen[t]=i,this.seen[n]=0),n}slug(t,e={}){const n=this.serialize(t);return this.getNextSafeSlug(n,e.dryrun)}}class C{constructor(t){this.options=t||e,this.options.renderer=this.options.renderer||new L,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new I,this.slugger=new M}static parse(t,e){return new C(e).parse(t)}static parseInline(t,e){return new C(e).parseInline(t)}parse(t,e=!0){let n,i,s,r,a,o,l,c,u,d,h,g,m,f,k,w,x,b,y,v="";const S=t.length;for(n=0;n<S;n++)if(d=t[n],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[d.type]&&(y=this.options.extensions.renderers[d.type].call({parser:this},d),!1!==y||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(d.type)))v+=y||"";else switch(d.type){case"space":continue;case"hr":v+=this.renderer.hr();continue;case"heading":v+=this.renderer.heading(this.parseInline(d.tokens),d.depth,p(this.parseInline(d.tokens,this.textRenderer)),this.slugger);continue;case"code":v+=this.renderer.code(d.text,d.lang,d.escaped);continue;case"table":for(c="",l="",r=d.header.length,i=0;i<r;i++)l+=this.renderer.tablecell(this.parseInline(d.header[i].tokens),{header:!0,align:d.align[i]});for(c+=this.renderer.tablerow(l),u="",r=d.rows.length,i=0;i<r;i++){for(o=d.rows[i],l="",a=o.length,s=0;s<a;s++)l+=this.renderer.tablecell(this.parseInline(o[s].tokens),{header:!1,align:d.align[s]});u+=this.renderer.tablerow(l)}v+=this.renderer.table(c,u);continue;case"blockquote":u=this.parse(d.tokens),v+=this.renderer.blockquote(u);continue;case"list":for(h=d.ordered,g=d.start,m=d.loose,r=d.items.length,u="",i=0;i<r;i++)k=d.items[i],w=k.checked,x=k.task,f="",k.task&&(b=this.renderer.checkbox(w),m?k.tokens.length>0&&"paragraph"===k.tokens[0].type?(k.tokens[0].text=b+" "+k.tokens[0].text,k.tokens[0].tokens&&k.tokens[0].tokens.length>0&&"text"===k.tokens[0].tokens[0].type&&(k.tokens[0].tokens[0].text=b+" "+k.tokens[0].tokens[0].text)):k.tokens.unshift({type:"text",text:b}):f+=b),f+=this.parse(k.tokens,m),u+=this.renderer.listitem(f,x,w);v+=this.renderer.list(u,h,g);continue;case"html":v+=this.renderer.html(d.text);continue;case"paragraph":v+=this.renderer.paragraph(this.parseInline(d.tokens));continue;case"text":for(u=d.tokens?this.parseInline(d.tokens):d.text;n+1<S&&"text"===t[n+1].type;)d=t[++n],u+="\n"+(d.tokens?this.parseInline(d.tokens):d.text);v+=e?this.renderer.paragraph(u):u;continue;default:{const t='Token with "'+d.type+'" type was not found.';if(this.options.silent)return void console.error(t);throw new Error(t)}}return v}parseInline(t,e){e=e||this.renderer;let n,i,s,r="";const a=t.length;for(n=0;n<a;n++)if(i=t[n],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[i.type]&&(s=this.options.extensions.renderers[i.type].call({parser:this},i),!1!==s||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)))r+=s||"";else switch(i.type){case"escape":case"text":r+=e.text(i.text);break;case"html":r+=e.html(i.text);break;case"link":r+=e.link(i.href,i.title,this.parseInline(i.tokens,e));break;case"image":r+=e.image(i.href,i.title,i.text);break;case"strong":r+=e.strong(this.parseInline(i.tokens,e));break;case"em":r+=e.em(this.parseInline(i.tokens,e));break;case"codespan":r+=e.codespan(i.text);break;case"br":r+=e.br();break;case"del":r+=e.del(this.parseInline(i.tokens,e));break;default:{const t='Token with "'+i.type+'" type was not found.';if(this.options.silent)return void console.error(t);throw new Error(t)}}return r}}class q{constructor(t){this.options=t||e}static passThroughHooks=new Set(["preprocess","postprocess"]);preprocess(t){return t}postproces
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
true
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/plugin/notes/notes.js
plugin/notes/notes.js
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).RevealNotes=e()}(this,(function(){"use strict";function t(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let e={async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1};const n=/[&<>"']/,i=new RegExp(n.source,"g"),s=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,r=new RegExp(s.source,"g"),a={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},o=t=>a[t];function l(t,e){if(e){if(n.test(t))return t.replace(i,o)}else if(s.test(t))return t.replace(r,o);return t}const c=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function p(t){return t.replace(c,((t,e)=>"colon"===(e=e.toLowerCase())?":":"#"===e.charAt(0)?"x"===e.charAt(1)?String.fromCharCode(parseInt(e.substring(2),16)):String.fromCharCode(+e.substring(1)):""))}const u=/(^|[^\[])\^/g;function d(t,e){t="string"==typeof t?t:t.source,e=e||"";const n={replace:(e,i)=>(i=(i=i.source||i).replace(u,"$1"),t=t.replace(e,i),n),getRegex:()=>new RegExp(t,e)};return n}const h=/[^\w:]/g,g=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function m(t,e,n){if(t){let t;try{t=decodeURIComponent(p(n)).replace(h,"").toLowerCase()}catch(t){return null}if(0===t.indexOf("javascript:")||0===t.indexOf("vbscript:")||0===t.indexOf("data:"))return null}e&&!g.test(n)&&(n=function(t,e){f[" "+t]||(k.test(t)?f[" "+t]=t+"/":f[" "+t]=v(t,"/",!0));t=f[" "+t];const n=-1===t.indexOf(":");return"//"===e.substring(0,2)?n?e:t.replace(w,"$1")+e:"/"===e.charAt(0)?n?e:t.replace(x,"$1")+e:t+e}(e,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch(t){return null}return n}const f={},k=/^[^:]+:\/*[^/]*$/,w=/^([^:]+:)[\s\S]*$/,x=/^([^:]+:\/*[^/]*)[\s\S]*$/;const b={exec:function(){}};function y(t,e){const n=t.replace(/\|/g,((t,e,n)=>{let i=!1,s=e;for(;--s>=0&&"\\"===n[s];)i=!i;return i?"|":" |"})).split(/ \|/);let i=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(/\\\|/g,"|");return n}function v(t,e,n){const i=t.length;if(0===i)return"";let s=0;for(;s<i;){const r=t.charAt(i-s-1);if(r!==e||n){if(r===e||!n)break;s++}else s++}return t.slice(0,i-s)}function S(t,e){if(e<1)return"";let n="";for(;e>1;)1&e&&(n+=t),e>>=1,t+=t;return n+t}function T(t,e,n,i){const s=e.href,r=e.title?l(e.title):null,a=t[1].replace(/\\([\[\]])/g,"$1");if("!"!==t[0].charAt(0)){i.state.inLink=!0;const t={type:"link",raw:n,href:s,title:r,text:a,tokens:i.inlineTokens(a)};return i.state.inLink=!1,t}return{type:"image",raw:n,href:s,title:r,text:l(a)}}class _{constructor(t){this.options=t||e}space(t){const e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){const e=this.rules.block.code.exec(t);if(e){const t=e[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?t:v(t,"\n")}}}fences(t){const e=this.rules.block.fences.exec(t);if(e){const t=e[0],n=function(t,e){const n=t.match(/^(\s+)(?:```)/);if(null===n)return e;const i=n[1];return e.split("\n").map((t=>{const e=t.match(/^\s+/);if(null===e)return t;const[n]=e;return n.length>=i.length?t.slice(i.length):t})).join("\n")}(t,e[3]||"");return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline._escapes,"$1"):e[2],text:n}}}heading(t){const e=this.rules.block.heading.exec(t);if(e){let t=e[2].trim();if(/#$/.test(t)){const e=v(t,"#");this.options.pedantic?t=e.trim():e&&!/ $/.test(e)||(t=e.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(t){const e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:e[0]}}blockquote(t){const e=this.rules.block.blockquote.exec(t);if(e){const t=e[0].replace(/^ *>[ \t]?/gm,""),n=this.lexer.state.top;this.lexer.state.top=!0;const i=this.lexer.blockTokens(t);return this.lexer.state.top=n,{type:"blockquote",raw:e[0],tokens:i,text:t}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n,i,s,r,a,o,l,c,p,u,d,h,g=e[1].trim();const m=g.length>1,f={type:"list",raw:"",ordered:m,start:m?+g.slice(0,-1):"",loose:!1,items:[]};g=m?`\\d{1,9}\\${g.slice(-1)}`:`\\${g}`,this.options.pedantic&&(g=m?g:"[*+-]");const k=new RegExp(`^( {0,3}${g})((?:[\t ][^\\n]*)?(?:\\n|$))`);for(;t&&(h=!1,e=k.exec(t))&&!this.rules.block.hr.test(t);){if(n=e[0],t=t.substring(n.length),c=e[2].split("\n",1)[0].replace(/^\t+/,(t=>" ".repeat(3*t.length))),p=t.split("\n",1)[0],this.options.pedantic?(r=2,d=c.trimLeft()):(r=e[2].search(/[^ ]/),r=r>4?1:r,d=c.slice(r),r+=e[1].length),o=!1,!c&&/^ *$/.test(p)&&(n+=p+"\n",t=t.substring(p.length+1),h=!0),!h){const e=new RegExp(`^ {0,${Math.min(3,r-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),i=new RegExp(`^ {0,${Math.min(3,r-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),s=new RegExp(`^ {0,${Math.min(3,r-1)}}(?:\`\`\`|~~~)`),a=new RegExp(`^ {0,${Math.min(3,r-1)}}#`);for(;t&&(u=t.split("\n",1)[0],p=u,this.options.pedantic&&(p=p.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),!s.test(p))&&!a.test(p)&&!e.test(p)&&!i.test(t);){if(p.search(/[^ ]/)>=r||!p.trim())d+="\n"+p.slice(r);else{if(o)break;if(c.search(/[^ ]/)>=4)break;if(s.test(c))break;if(a.test(c))break;if(i.test(c))break;d+="\n"+p}o||p.trim()||(o=!0),n+=u+"\n",t=t.substring(u.length+1),c=p.slice(r)}}f.loose||(l?f.loose=!0:/\n *\n *$/.test(n)&&(l=!0)),this.options.gfm&&(i=/^\[[ xX]\] /.exec(d),i&&(s="[ ] "!==i[0],d=d.replace(/^\[[ xX]\] +/,""))),f.items.push({type:"list_item",raw:n,task:!!i,checked:s,loose:!1,text:d}),f.raw+=n}f.items[f.items.length-1].raw=n.trimRight(),f.items[f.items.length-1].text=d.trimRight(),f.raw=f.raw.trimRight();const w=f.items.length;for(a=0;a<w;a++)if(this.lexer.state.top=!1,f.items[a].tokens=this.lexer.blockTokens(f.items[a].text,[]),!f.loose){const t=f.items[a].tokens.filter((t=>"space"===t.type)),e=t.length>0&&t.some((t=>/\n.*\n/.test(t.raw)));f.loose=e}if(f.loose)for(a=0;a<w;a++)f.items[a].loose=!0;return f}}html(t){const e=this.rules.block.html.exec(t);if(e){const t={type:"html",raw:e[0],pre:!this.options.sanitizer&&("pre"===e[1]||"script"===e[1]||"style"===e[1]),text:e[0]};if(this.options.sanitize){const n=this.options.sanitizer?this.options.sanitizer(e[0]):l(e[0]);t.type="paragraph",t.text=n,t.tokens=this.lexer.inline(n)}return t}}def(t){const e=this.rules.block.def.exec(t);if(e){const t=e[1].toLowerCase().replace(/\s+/g," "),n=e[2]?e[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline._escapes,"$1"):"",i=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline._escapes,"$1"):e[3];return{type:"def",tag:t,raw:e[0],href:n,title:i}}}table(t){const e=this.rules.block.table.exec(t);if(e){const t={type:"table",header:y(e[1]).map((t=>({text:t}))),align:e[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:e[3]&&e[3].trim()?e[3].replace(/\n[ \t]*$/,"").split("\n"):[]};if(t.header.length===t.align.length){t.raw=e[0];let n,i,s,r,a=t.align.length;for(n=0;n<a;n++)/^ *-+: *$/.test(t.align[n])?t.align[n]="right":/^ *:-+: *$/.test(t.align[n])?t.align[n]="center":/^ *:-+ *$/.test(t.align[n])?t.align[n]="left":t.align[n]=null;for(a=t.rows.length,n=0;n<a;n++)t.rows[n]=y(t.rows[n],t.header.length).map((t=>({text:t})));for(a=t.header.length,i=0;i<a;i++)t.header[i].tokens=this.lexer.inline(t.header[i].text);for(a=t.rows.length,i=0;i<a;i++)for(r=t.rows[i],s=0;s<r.length;s++)r[s].tokens=this.lexer.inline(r[s].text);return t}}}lheading(t){const e=this.rules.block.lheading.exec(t);if(e)return{type:"heading",raw:e[0],depth:"="===e[2].charAt(0)?1:2,text:e[1],tokens:this.lexer.inline(e[1])}}paragraph(t){const e=this.rules.block.paragraph.exec(t);if(e){const t="\n"===e[1].charAt(e[1].length-1)?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(t){const e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){const e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:l(e[1])}}tag(t){const e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&/^<a /i.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(e[0]):l(e[0]):e[0]}}link(t){const e=this.rules.inline.link.exec(t);if(e){const t=e[2].trim();if(!this.options.pedantic&&/^</.test(t)){if(!/>$/.test(t))return;const e=v(t.slice(0,-1),"\\");if((t.length-e.length)%2==0)return}else{const t=function(t,e){if(-1===t.indexOf(e[1]))return-1;const n=t.length;let i=0,s=0;for(;s<n;s++)if("\\"===t[s])s++;else if(t[s]===e[0])i++;else if(t[s]===e[1]&&(i--,i<0))return s;return-1}(e[2],"()");if(t>-1){const n=(0===e[0].indexOf("!")?5:4)+e[1].length+t;e[2]=e[2].substring(0,t),e[0]=e[0].substring(0,n).trim(),e[3]=""}}let n=e[2],i="";if(this.options.pedantic){const t=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);t&&(n=t[1],i=t[3])}else i=e[3]?e[3].slice(1,-1):"";return n=n.trim(),/^</.test(n)&&(n=this.options.pedantic&&!/>$/.test(t)?n.slice(1):n.slice(1,-1)),T(e,{href:n?n.replace(this.rules.inline._escapes,"$1"):n,title:i?i.replace(this.rules.inline._escapes,"$1"):i},e[0],this.lexer)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let t=(n[2]||n[1]).replace(/\s+/g," ");if(t=e[t.toLowerCase()],!t){const t=n[0].charAt(0);return{type:"text",raw:t,text:t}}return T(n,t,n[0],this.lexer)}}emStrong(t,e,n=""){let i=this.rules.inline.emStrong.lDelim.exec(t);if(!i)return;if(i[3]&&n.match(/[\p{L}\p{N}]/u))return;const s=i[1]||i[2]||"";if(!s||s&&(""===n||this.rules.inline.punctuation.exec(n))){const n=i[0].length-1;let s,r,a=n,o=0;const l="*"===i[0][0]?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(l.lastIndex=0,e=e.slice(-1*t.length+n);null!=(i=l.exec(e));){if(s=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!s)continue;if(r=s.length,i[3]||i[4]){a+=r;continue}if((i[5]||i[6])&&n%3&&!((n+r)%3)){o+=r;continue}if(a-=r,a>0)continue;r=Math.min(r,r+a+o);const e=t.slice(0,n+i.index+(i[0].length-s.length)+r);if(Math.min(n,r)%2){const t=e.slice(1,-1);return{type:"em",raw:e,text:t,tokens:this.lexer.inlineTokens(t)}}const l=e.slice(2,-2);return{type:"strong",raw:e,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(t){const e=this.rules.inline.code.exec(t);if(e){let t=e[2].replace(/\n/g," ");const n=/[^ ]/.test(t),i=/^ /.test(t)&&/ $/.test(t);return n&&i&&(t=t.substring(1,t.length-1)),t=l(t,!0),{type:"codespan",raw:e[0],text:t}}}br(t){const e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t){const e=this.rules.inline.del.exec(t);if(e)return{type:"del",raw:e[0],text:e[2],tokens:this.lexer.inlineTokens(e[2])}}autolink(t,e){const n=this.rules.inline.autolink.exec(t);if(n){let t,i;return"@"===n[2]?(t=l(this.options.mangle?e(n[1]):n[1]),i="mailto:"+t):(t=l(n[1]),i=t),{type:"link",raw:n[0],text:t,href:i,tokens:[{type:"text",raw:t,text:t}]}}}url(t,e){let n;if(n=this.rules.inline.url.exec(t)){let t,i;if("@"===n[2])t=l(this.options.mangle?e(n[0]):n[0]),i="mailto:"+t;else{let e;do{e=n[0],n[0]=this.rules.inline._backpedal.exec(n[0])[0]}while(e!==n[0]);t=l(n[0]),i="www."===n[1]?"http://"+n[0]:n[0]}return{type:"link",raw:n[0],text:t,href:i,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(t,e){const n=this.rules.inline.text.exec(t);if(n){let t;return t=this.lexer.state.inRawBlock?this.options.sanitize?this.options.sanitizer?this.options.sanitizer(n[0]):l(n[0]):n[0]:l(this.options.smartypants?e(n[0]):n[0]),{type:"text",raw:n[0],text:t}}}}const z={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:b,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/,_label:/(?!\s*\])(?:\\.|[^\[\]\\])+/,_title:/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/};z.def=d(z.def).replace("label",z._label).replace("title",z._title).getRegex(),z.bullet=/(?:[*+-]|\d{1,9}[.)])/,z.listItemStart=d(/^( *)(bull) */).replace("bull",z.bullet).getRegex(),z.list=d(z.list).replace(/bull/g,z.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+z.def.source+")").getRegex(),z._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",z._comment=/<!--(?!-?>)[\s\S]*?(?:-->|$)/,z.html=d(z.html,"i").replace("comment",z._comment).replace("tag",z._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),z.paragraph=d(z._paragraph).replace("hr",z.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",z._tag).getRegex(),z.blockquote=d(z.blockquote).replace("paragraph",z.paragraph).getRegex(),z.normal={...z},z.gfm={...z.normal,table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"},z.gfm.table=d(z.gfm.table).replace("hr",z.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",z._tag).getRegex(),z.gfm.paragraph=d(z._paragraph).replace("hr",z.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",z.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",z._tag).getRegex(),z.pedantic={...z.normal,html:d("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",z._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:b,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(z.normal._paragraph).replace("hr",z.hr).replace("heading"," *#{1,6} *[^\n]").replace("lheading",z.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const $={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:b,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:b,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^([\spunctuation])/};function E(t){return t.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")}function A(t){let e,n,i="";const s=t.length;for(e=0;e<s;e++)n=t.charCodeAt(e),Math.random()>.5&&(n="x"+n.toString(16)),i+="&#"+n+";";return i}$._punctuation="!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~",$.punctuation=d($.punctuation).replace(/punctuation/g,$._punctuation).getRegex(),$.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,$.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g,$._comment=d(z._comment).replace("(?:--\x3e|$)","--\x3e").getRegex(),$.emStrong.lDelim=d($.emStrong.lDelim).replace(/punct/g,$._punctuation).getRegex(),$.emStrong.rDelimAst=d($.emStrong.rDelimAst,"g").replace(/punct/g,$._punctuation).getRegex(),$.emStrong.rDelimUnd=d($.emStrong.rDelimUnd,"g").replace(/punct/g,$._punctuation).getRegex(),$._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,$._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,$._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,$.autolink=d($.autolink).replace("scheme",$._scheme).replace("email",$._email).getRegex(),$._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,$.tag=d($.tag).replace("comment",$._comment).replace("attribute",$._attribute).getRegex(),$._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,$._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,$._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,$.link=d($.link).replace("label",$._label).replace("href",$._href).replace("title",$._title).getRegex(),$.reflink=d($.reflink).replace("label",$._label).replace("ref",z._label).getRegex(),$.nolink=d($.nolink).replace("ref",z._label).getRegex(),$.reflinkSearch=d($.reflinkSearch,"g").replace("reflink",$.reflink).replace("nolink",$.nolink).getRegex(),$.normal={...$},$.pedantic={...$.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:d(/^!?\[(label)\]\((.*?)\)/).replace("label",$._label).getRegex(),reflink:d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",$._label).getRegex()},$.gfm={...$.normal,escape:d($.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},$.gfm.url=d($.gfm.url,"i").replace("email",$.gfm._extended_email).getRegex(),$.breaks={...$.gfm,br:d($.br).replace("{2,}","*").getRegex(),text:d($.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};class R{constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||e,this.options.tokenizer=this.options.tokenizer||new _,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:z.normal,inline:$.normal};this.options.pedantic?(n.block=z.pedantic,n.inline=$.pedantic):this.options.gfm&&(n.block=z.gfm,this.options.breaks?n.inline=$.breaks:n.inline=$.gfm),this.tokenizer.rules=n}static get rules(){return{block:z,inline:$}}static lex(t,e){return new R(e).lex(t)}static lexInline(t,e){return new R(e).inlineTokens(t)}lex(t){let e;for(t=t.replace(/\r\n|\r/g,"\n"),this.blockTokens(t,this.tokens);e=this.inlineQueue.shift();)this.inlineTokens(e.src,e.tokens);return this.tokens}blockTokens(t,e=[]){let n,i,s,r;for(t=this.options.pedantic?t.replace(/\t/g," ").replace(/^ +$/gm,""):t.replace(/^( *)(\t+)/gm,((t,e,n)=>e+" ".repeat(n.length)));t;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some((i=>!!(n=i.call({lexer:this},t,e))&&(t=t.substring(n.raw.length),e.push(n),!0)))))if(n=this.tokenizer.space(t))t=t.substring(n.raw.length),1===n.raw.length&&e.length>0?e[e.length-1].raw+="\n":e.push(n);else if(n=this.tokenizer.code(t))t=t.substring(n.raw.length),i=e[e.length-1],!i||"paragraph"!==i.type&&"text"!==i.type?e.push(n):(i.raw+="\n"+n.raw,i.text+="\n"+n.text,this.inlineQueue[this.inlineQueue.length-1].src=i.text);else if(n=this.tokenizer.fences(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.heading(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.hr(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.blockquote(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.list(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.html(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.def(t))t=t.substring(n.raw.length),i=e[e.length-1],!i||"paragraph"!==i.type&&"text"!==i.type?this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title}):(i.raw+="\n"+n.raw,i.text+="\n"+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=i.text);else if(n=this.tokenizer.table(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.lheading(t))t=t.substring(n.raw.length),e.push(n);else{if(s=t,this.options.extensions&&this.options.extensions.startBlock){let e=1/0;const n=t.slice(1);let i;this.options.extensions.startBlock.forEach((function(t){i=t.call({lexer:this},n),"number"==typeof i&&i>=0&&(e=Math.min(e,i))})),e<1/0&&e>=0&&(s=t.substring(0,e+1))}if(this.state.top&&(n=this.tokenizer.paragraph(s)))i=e[e.length-1],r&&"paragraph"===i.type?(i.raw+="\n"+n.raw,i.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=i.text):e.push(n),r=s.length!==t.length,t=t.substring(n.raw.length);else if(n=this.tokenizer.text(t))t=t.substring(n.raw.length),i=e[e.length-1],i&&"text"===i.type?(i.raw+="\n"+n.raw,i.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=i.text):e.push(n);else if(t){const e="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(e);break}throw new Error(e)}}return this.state.top=!0,e}inline(t,e=[]){return this.inlineQueue.push({src:t,tokens:e}),e}inlineTokens(t,e=[]){let n,i,s,r,a,o,l=t;if(this.tokens.links){const t=Object.keys(this.tokens.links);if(t.length>0)for(;null!=(r=this.tokenizer.rules.inline.reflinkSearch.exec(l));)t.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(l=l.slice(0,r.index)+"["+S("a",r[0].length-2)+"]"+l.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(r=this.tokenizer.rules.inline.blockSkip.exec(l));)l=l.slice(0,r.index)+"["+S("a",r[0].length-2)+"]"+l.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(r=this.tokenizer.rules.inline.escapedEmSt.exec(l));)l=l.slice(0,r.index+r[0].length-2)+"++"+l.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex),this.tokenizer.rules.inline.escapedEmSt.lastIndex--;for(;t;)if(a||(o=""),a=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some((i=>!!(n=i.call({lexer:this},t,e))&&(t=t.substring(n.raw.length),e.push(n),!0)))))if(n=this.tokenizer.escape(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.tag(t))t=t.substring(n.raw.length),i=e[e.length-1],i&&"text"===n.type&&"text"===i.type?(i.raw+=n.raw,i.text+=n.text):e.push(n);else if(n=this.tokenizer.link(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.reflink(t,this.tokens.links))t=t.substring(n.raw.length),i=e[e.length-1],i&&"text"===n.type&&"text"===i.type?(i.raw+=n.raw,i.text+=n.text):e.push(n);else if(n=this.tokenizer.emStrong(t,l,o))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.codespan(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.br(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.del(t))t=t.substring(n.raw.length),e.push(n);else if(n=this.tokenizer.autolink(t,A))t=t.substring(n.raw.length),e.push(n);else if(this.state.inLink||!(n=this.tokenizer.url(t,A))){if(s=t,this.options.extensions&&this.options.extensions.startInline){let e=1/0;const n=t.slice(1);let i;this.options.extensions.startInline.forEach((function(t){i=t.call({lexer:this},n),"number"==typeof i&&i>=0&&(e=Math.min(e,i))})),e<1/0&&e>=0&&(s=t.substring(0,e+1))}if(n=this.tokenizer.inlineText(s,E))t=t.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),a=!0,i=e[e.length-1],i&&"text"===i.type?(i.raw+=n.raw,i.text+=n.text):e.push(n);else if(t){const e="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(e);break}throw new Error(e)}}else t=t.substring(n.raw.length),e.push(n);return e}}class L{constructor(t){this.options=t||e}code(t,e,n){const i=(e||"").match(/\S*/)[0];if(this.options.highlight){const e=this.options.highlight(t,i);null!=e&&e!==t&&(n=!0,t=e)}return t=t.replace(/\n$/,"")+"\n",i?'<pre><code class="'+this.options.langPrefix+l(i)+'">'+(n?t:l(t,!0))+"</code></pre>\n":"<pre><code>"+(n?t:l(t,!0))+"</code></pre>\n"}blockquote(t){return`<blockquote>\n${t}</blockquote>\n`}html(t){return t}heading(t,e,n,i){if(this.options.headerIds){return`<h${e} id="${this.options.headerPrefix+i.slug(n)}">${t}</h${e}>\n`}return`<h${e}>${t}</h${e}>\n`}hr(){return this.options.xhtml?"<hr/>\n":"<hr>\n"}list(t,e,n){const i=e?"ol":"ul";return"<"+i+(e&&1!==n?' start="'+n+'"':"")+">\n"+t+"</"+i+">\n"}listitem(t){return`<li>${t}</li>\n`}checkbox(t){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"'+(this.options.xhtml?" /":"")+"> "}paragraph(t){return`<p>${t}</p>\n`}table(t,e){return e&&(e=`<tbody>${e}</tbody>`),"<table>\n<thead>\n"+t+"</thead>\n"+e+"</table>\n"}tablerow(t){return`<tr>\n${t}</tr>\n`}tablecell(t,e){const n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>\n`}strong(t){return`<strong>${t}</strong>`}em(t){return`<em>${t}</em>`}codespan(t){return`<code>${t}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(t){return`<del>${t}</del>`}link(t,e,n){if(null===(t=m(this.options.sanitize,this.options.baseUrl,t)))return n;let i='<a href="'+t+'"';return e&&(i+=' title="'+e+'"'),i+=">"+n+"</a>",i}image(t,e,n){if(null===(t=m(this.options.sanitize,this.options.baseUrl,t)))return n;let i=`<img src="${t}" alt="${n}"`;return e&&(i+=` title="${e}"`),i+=this.options.xhtml?"/>":">",i}text(t){return t}}class I{strong(t){return t}em(t){return t}codespan(t){return t}del(t){return t}html(t){return t}text(t){return t}link(t,e,n){return""+n}image(t,e,n){return""+n}br(){return""}}class M{constructor(){this.seen={}}serialize(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(t,e){let n=t,i=0;if(this.seen.hasOwnProperty(n)){i=this.seen[t];do{i++,n=t+"-"+i}while(this.seen.hasOwnProperty(n))}return e||(this.seen[t]=i,this.seen[n]=0),n}slug(t,e={}){const n=this.serialize(t);return this.getNextSafeSlug(n,e.dryrun)}}class C{constructor(t){this.options=t||e,this.options.renderer=this.options.renderer||new L,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new I,this.slugger=new M}static parse(t,e){return new C(e).parse(t)}static parseInline(t,e){return new C(e).parseInline(t)}parse(t,e=!0){let n,i,s,r,a,o,l,c,u,d,h,g,m,f,k,w,x,b,y,v="";const S=t.length;for(n=0;n<S;n++)if(d=t[n],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[d.type]&&(y=this.options.extensions.renderers[d.type].call({parser:this},d),!1!==y||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(d.type)))v+=y||"";else switch(d.type){case"space":continue;case"hr":v+=this.renderer.hr();continue;case"heading":v+=this.renderer.heading(this.parseInline(d.tokens),d.depth,p(this.parseInline(d.tokens,this.textRenderer)),this.slugger);continue;case"code":v+=this.renderer.code(d.text,d.lang,d.escaped);continue;case"table":for(c="",l="",r=d.header.length,i=0;i<r;i++)l+=this.renderer.tablecell(this.parseInline(d.header[i].tokens),{header:!0,align:d.align[i]});for(c+=this.renderer.tablerow(l),u="",r=d.rows.length,i=0;i<r;i++){for(o=d.rows[i],l="",a=o.length,s=0;s<a;s++)l+=this.renderer.tablecell(this.parseInline(o[s].tokens),{header:!1,align:d.align[s]});u+=this.renderer.tablerow(l)}v+=this.renderer.table(c,u);continue;case"blockquote":u=this.parse(d.tokens),v+=this.renderer.blockquote(u);continue;case"list":for(h=d.ordered,g=d.start,m=d.loose,r=d.items.length,u="",i=0;i<r;i++)k=d.items[i],w=k.checked,x=k.task,f="",k.task&&(b=this.renderer.checkbox(w),m?k.tokens.length>0&&"paragraph"===k.tokens[0].type?(k.tokens[0].text=b+" "+k.tokens[0].text,k.tokens[0].tokens&&k.tokens[0].tokens.length>0&&"text"===k.tokens[0].tokens[0].type&&(k.tokens[0].tokens[0].text=b+" "+k.tokens[0].tokens[0].text)):k.tokens.unshift({type:"text",text:b}):f+=b),f+=this.parse(k.tokens,m),u+=this.renderer.listitem(f,x,w);v+=this.renderer.list(u,h,g);continue;case"html":v+=this.renderer.html(d.text);continue;case"paragraph":v+=this.renderer.paragraph(this.parseInline(d.tokens));continue;case"text":for(u=d.tokens?this.parseInline(d.tokens):d.text;n+1<S&&"text"===t[n+1].type;)d=t[++n],u+="\n"+(d.tokens?this.parseInline(d.tokens):d.text);v+=e?this.renderer.paragraph(u):u;continue;default:{const t='Token with "'+d.type+'" type was not found.';if(this.options.silent)return void console.error(t);throw new Error(t)}}return v}parseInline(t,e){e=e||this.renderer;let n,i,s,r="";const a=t.length;for(n=0;n<a;n++)if(i=t[n],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[i.type]&&(s=this.options.extensions.renderers[i.type].call({parser:this},i),!1!==s||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)))r+=s||"";else switch(i.type){case"escape":case"text":r+=e.text(i.text);break;case"html":r+=e.html(i.text);break;case"link":r+=e.link(i.href,i.title,this.parseInline(i.tokens,e));break;case"image":r+=e.image(i.href,i.title,i.text);break;case"strong":r+=e.strong(this.parseInline(i.tokens,e));break;case"em":r+=e.em(this.parseInline(i.tokens,e));break;case"codespan":r+=e.codespan(i.text);break;case"br":r+=e.br();break;case"del":r+=e.del(this.parseInline(i.tokens,e));break;default:{const t='Token with "'+i.type+'" typ
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
true
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/test/assets/external-script-d.js
test/assets/external-script-d.js
window.externalScriptSequence += 'D';
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/test/assets/external-script-a.js
test/assets/external-script-a.js
window.externalScriptSequence += 'A';
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/test/assets/external-script-b.js
test/assets/external-script-b.js
window.externalScriptSequence += 'B';
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/test/assets/external-script-c.js
test/assets/external-script-c.js
window.externalScriptSequence += 'C';
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/index.js
js/index.js
import Deck, { VERSION } from './reveal.js' /** * Expose the Reveal class to the window. To create a * new instance: * let deck = new Reveal( document.querySelector( '.reveal' ), { * controls: false * } ); * deck.initialize().then(() => { * // reveal.js is ready * }); */ let Reveal = Deck; /** * The below is a thin shell that mimics the pre 4.0 * reveal.js API and ensures backwards compatibility. * This API only allows for one Reveal instance per * page, whereas the new API above lets you run many * presentations on the same page. * * Reveal.initialize( { controls: false } ).then(() => { * // reveal.js is ready * }); */ let enqueuedAPICalls = []; Reveal.initialize = options => { // Create our singleton reveal.js instance Object.assign( Reveal, new Deck( document.querySelector( '.reveal' ), options ) ); // Invoke any enqueued API calls enqueuedAPICalls.map( method => method( Reveal ) ); return Reveal.initialize(); } /** * The pre 4.0 API let you add event listener before * initializing. We maintain the same behavior by * queuing up premature API calls and invoking all * of them when Reveal.initialize is called. */ [ 'configure', 'on', 'off', 'addEventListener', 'removeEventListener', 'registerPlugin' ].forEach( method => { Reveal[method] = ( ...args ) => { enqueuedAPICalls.push( deck => deck[method].call( null, ...args ) ); } } ); Reveal.isReady = () => false; Reveal.VERSION = VERSION; export default Reveal;
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/config.js
js/config.js
/** * The default reveal.js config object. */ export default { // The "normal" size of the presentation, aspect ratio will be preserved // when the presentation is scaled to fit different resolutions width: 960, height: 700, // Factor of the display size that should remain empty around the content margin: 0.04, // Bounds for smallest/largest possible scale to apply to content minScale: 0.2, maxScale: 2.0, // Display presentation control arrows. // - true: Display controls on all screens // - false: Hide controls on all screens // - "speaker-only": Only display controls in the speaker view controls: true, // Help the user learn the controls by providing hints, for example by // bouncing the down arrow when they first encounter a vertical slide controlsTutorial: true, // Determines where controls appear, "edges" or "bottom-right" controlsLayout: 'bottom-right', // Visibility rule for backwards navigation arrows; "faded", "hidden" // or "visible" controlsBackArrows: 'faded', // Display a presentation progress bar progress: true, // Display the page number of the current slide // - true: Show slide number // - false: Hide slide number // // Can optionally be set as a string that specifies the number formatting: // - "h.v": Horizontal . vertical slide number (default) // - "h/v": Horizontal / vertical slide number // - "c": Flattened slide number // - "c/t": Flattened slide number / total slides // // Alternatively, you can provide a function that returns the slide // number for the current slide. The function should take in a slide // object and return an array with one string [slideNumber] or // three strings [n1,delimiter,n2]. See #formatSlideNumber(). slideNumber: false, // Can be used to limit the contexts in which the slide number appears // - "all": Always show the slide number // - "print": Only when printing to PDF // - "speaker": Only in the speaker view showSlideNumber: 'all', // Use 1 based indexing for # links to match slide number (default is zero // based) hashOneBasedIndex: false, // Add the current slide number to the URL hash so that reloading the // page/copying the URL will return you to the same slide hash: false, // Flags if we should monitor the hash and change slides accordingly respondToHashChanges: true, // Enable support for jump-to-slide navigation shortcuts jumpToSlide: true, // Push each slide change to the browser history. Implies `hash: true` history: false, // Enable keyboard shortcuts for navigation keyboard: true, // Optional function that blocks keyboard events when returning false // // If you set this to 'focused', we will only capture keyboard events // for embedded decks when they are in focus keyboardCondition: null, // Disables the default reveal.js slide layout (scaling and centering) // so that you can use custom CSS layout disableLayout: false, // Enable the slide overview mode overview: true, // Vertical centering of slides center: true, // Enables touch navigation on devices with touch input touch: true, // Loop the presentation loop: false, // Change the presentation direction to be RTL rtl: false, // Changes the behavior of our navigation directions. // // "default" // Left/right arrow keys step between horizontal slides, up/down // arrow keys step between vertical slides. Space key steps through // all slides (both horizontal and vertical). // // "linear" // Removes the up/down arrows. Left/right arrows step through all // slides (both horizontal and vertical). // // "grid" // When this is enabled, stepping left/right from a vertical stack // to an adjacent vertical stack will land you at the same vertical // index. // // Consider a deck with six slides ordered in two vertical stacks: // 1.1 2.1 // 1.2 2.2 // 1.3 2.3 // // If you're on slide 1.3 and navigate right, you will normally move // from 1.3 -> 2.1. If "grid" is used, the same navigation takes you // from 1.3 -> 2.3. navigationMode: 'default', // Randomizes the order of slides each time the presentation loads shuffle: false, // Turns fragments on and off globally fragments: true, // Flags whether to include the current fragment in the URL, // so that reloading brings you to the same fragment position fragmentInURL: true, // Flags if the presentation is running in an embedded mode, // i.e. contained within a limited portion of the screen embedded: false, // Flags if we should show a help overlay when the question-mark // key is pressed help: true, // Flags if it should be possible to pause the presentation (blackout) pause: true, // Flags if speaker notes should be visible to all viewers showNotes: false, // Flags if slides with data-visibility="hidden" should be kep visible showHiddenSlides: false, // Global override for autoplaying embedded media (video/audio/iframe) // - null: Media will only autoplay if data-autoplay is present // - true: All media will autoplay, regardless of individual setting // - false: No media will autoplay, regardless of individual setting autoPlayMedia: null, // Global override for preloading lazy-loaded iframes // - null: Iframes with data-src AND data-preload will be loaded when within // the viewDistance, iframes with only data-src will be loaded when visible // - true: All iframes with data-src will be loaded when within the viewDistance // - false: All iframes with data-src will be loaded only when visible preloadIframes: null, // Prevent embedded iframes from automatically focusing on themselves preventIframeAutoFocus: true, // Can be used to globally disable auto-animation autoAnimate: true, // Optionally provide a custom element matcher that will be // used to dictate which elements we can animate between. autoAnimateMatcher: null, // Default settings for our auto-animate transitions, can be // overridden per-slide or per-element via data arguments autoAnimateEasing: 'ease', autoAnimateDuration: 1.0, autoAnimateUnmatched: true, // CSS properties that can be auto-animated. Position & scale // is matched separately so there's no need to include styles // like top/right/bottom/left, width/height or margin. autoAnimateStyles: [ 'opacity', 'color', 'background-color', 'padding', 'font-size', 'line-height', 'letter-spacing', 'border-width', 'border-color', 'border-radius', 'outline', 'outline-offset' ], // Controls automatic progression to the next slide // - 0: Auto-sliding only happens if the data-autoslide HTML attribute // is present on the current slide or fragment // - 1+: All slides will progress automatically at the given interval // - false: No auto-sliding, even if data-autoslide is present autoSlide: 0, // Stop auto-sliding after user input autoSlideStoppable: true, // Use this method for navigation when auto-sliding (defaults to navigateNext) autoSlideMethod: null, // Specify the average time in seconds that you think you will spend // presenting each slide. This is used to show a pacing timer in the // speaker view defaultTiming: null, // Enable slide navigation via mouse wheel mouseWheel: false, // Opens links in an iframe preview overlay // Add `data-preview-link` and `data-preview-link="false"` to customise each link // individually previewLinks: false, // Exposes the reveal.js API through window.postMessage postMessage: true, // Dispatches all reveal.js events to the parent window through postMessage postMessageEvents: false, // Focuses body when page changes visibility to ensure keyboard shortcuts work focusBodyOnPageVisibilityChange: true, // Transition style transition: 'slide', // none/fade/slide/convex/concave/zoom // Transition speed transitionSpeed: 'default', // default/fast/slow // Transition style for full page slide backgrounds backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom // Parallax background image parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg" // Parallax background size parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px" // Parallax background repeat parallaxBackgroundRepeat: '', // repeat/repeat-x/repeat-y/no-repeat/initial/inherit // Parallax background position parallaxBackgroundPosition: '', // CSS syntax, e.g. "top left" // Amount of pixels to move the parallax background per slide step parallaxBackgroundHorizontal: null, parallaxBackgroundVertical: null, // Can be used to initialize reveal.js in one of the following views: // - print: Render the presentation so that it can be printed to PDF // - scroll: Show the presentation as a tall scrollable page with scroll // triggered animations view: null, // Adjusts the height of each slide in the scroll view. // - full: Each slide is as tall as the viewport // - compact: Slides are as small as possible, allowing multiple slides // to be visible in parallel on tall devices scrollLayout: 'full', // Control how scroll snapping works in the scroll view. // - false: No snapping, scrolling is continuous // - proximity: Snap when close to a slide // - mandatory: Always snap to the closest slide // // Only applies to presentations in scroll view. scrollSnap: 'mandatory', // Enables and configure the scroll view progress bar. // - 'auto': Show the scrollbar while scrolling, hide while idle // - true: Always show the scrollbar // - false: Never show the scrollbar scrollProgress: 'auto', // Automatically activate the scroll view when we the viewport falls // below the given width. scrollActivationWidth: 435, // The maximum number of pages a single slide can expand onto when printing // to PDF, unlimited by default pdfMaxPagesPerSlide: Number.POSITIVE_INFINITY, // Prints each fragment on a separate slide pdfSeparateFragments: true, // Offset used to reduce the height of content within exported PDF pages. // This exists to account for environment differences based on how you // print to PDF. CLI printing options, like phantomjs and wkpdf, can end // on precisely the total height of the document whereas in-browser // printing has to end one pixel before. pdfPageHeightOffset: -1, // Number of slides away from the current that are visible viewDistance: 3, // Number of slides away from the current that are visible on mobile // devices. It is advisable to set this to a lower number than // viewDistance in order to save resources. mobileViewDistance: 2, // The display mode that will be used to show slides display: 'block', // Hide cursor if inactive hideInactiveCursor: true, // Time before the cursor is hidden (in ms) hideCursorTime: 5000, // Should we automatically sort and set indices for fragments // at each sync? (See Reveal.sync) sortFragmentsOnSync: true, // Script dependencies to load dependencies: [], // Plugin objects to register and use for this presentation plugins: [] }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/reveal.js
js/reveal.js
import SlideContent from './controllers/slidecontent.js' import SlideNumber from './controllers/slidenumber.js' import JumpToSlide from './controllers/jumptoslide.js' import Backgrounds from './controllers/backgrounds.js' import AutoAnimate from './controllers/autoanimate.js' import ScrollView from './controllers/scrollview.js' import PrintView from './controllers/printview.js' import Fragments from './controllers/fragments.js' import Overview from './controllers/overview.js' import Keyboard from './controllers/keyboard.js' import Location from './controllers/location.js' import Controls from './controllers/controls.js' import Progress from './controllers/progress.js' import Pointer from './controllers/pointer.js' import Plugins from './controllers/plugins.js' import Overlay from './controllers/overlay.js' import Touch from './controllers/touch.js' import Focus from './controllers/focus.js' import Notes from './controllers/notes.js' import Playback from './components/playback.js' import defaultConfig from './config.js' import * as Util from './utils/util.js' import * as Device from './utils/device.js' import { SLIDES_SELECTOR, HORIZONTAL_SLIDES_SELECTOR, VERTICAL_SLIDES_SELECTOR, POST_MESSAGE_METHOD_BLACKLIST } from './utils/constants.js' // The reveal.js version export const VERSION = '5.2.1'; /** * reveal.js * https://revealjs.com * MIT licensed * * Copyright (C) 2011-2022 Hakim El Hattab, https://hakim.se */ export default function( revealElement, options ) { // Support initialization with no args, one arg // [options] or two args [revealElement, options] if( arguments.length < 2 ) { options = arguments[0]; revealElement = document.querySelector( '.reveal' ); } const Reveal = {}; // Configuration defaults, can be overridden at initialization time let config = {}, // Flags if initialize() has been invoked for this reveal instance initialized = false, // Flags if reveal.js is loaded (has dispatched the 'ready' event) ready = false, // The horizontal and vertical index of the currently active slide indexh, indexv, // The previous and current slide HTML elements previousSlide, currentSlide, // Remember which directions that the user has navigated towards navigationHistory = { hasNavigatedHorizontally: false, hasNavigatedVertically: false }, // Slides may have a data-state attribute which we pick up and apply // as a class to the body. This list contains the combined state of // all current slides. state = [], // The current scale of the presentation (see width/height config) scale = 1, // CSS transform that is currently applied to the slides container, // split into two groups slidesTransform = { layout: '', overview: '' }, // Cached references to DOM elements dom = {}, // Flags if the interaction event listeners are bound eventsAreBound = false, // The current slide transition state; idle or running transition = 'idle', // The current auto-slide duration autoSlide = 0, // Auto slide properties autoSlidePlayer, autoSlideTimeout = 0, autoSlideStartTime = -1, autoSlidePaused = false, // Controllers for different aspects of our presentation. They're // all given direct references to this Reveal instance since there // may be multiple presentations running in parallel. slideContent = new SlideContent( Reveal ), slideNumber = new SlideNumber( Reveal ), jumpToSlide = new JumpToSlide( Reveal ), autoAnimate = new AutoAnimate( Reveal ), backgrounds = new Backgrounds( Reveal ), scrollView = new ScrollView( Reveal ), printView = new PrintView( Reveal ), fragments = new Fragments( Reveal ), overview = new Overview( Reveal ), keyboard = new Keyboard( Reveal ), location = new Location( Reveal ), controls = new Controls( Reveal ), progress = new Progress( Reveal ), pointer = new Pointer( Reveal ), plugins = new Plugins( Reveal ), overlay = new Overlay( Reveal ), focus = new Focus( Reveal ), touch = new Touch( Reveal ), notes = new Notes( Reveal ); /** * Starts up the presentation. */ function initialize( initOptions ) { if( !revealElement ) throw 'Unable to find presentation root (<div class="reveal">).'; if( initialized ) throw 'Reveal.js has already been initialized.'; initialized = true; // Cache references to key DOM elements dom.wrapper = revealElement; dom.slides = revealElement.querySelector( '.slides' ); if( !dom.slides ) throw 'Unable to find slides container (<div class="slides">).'; // Compose our config object in order of increasing precedence: // 1. Default reveal.js options // 2. Options provided via Reveal.configure() prior to // initialization // 3. Options passed to the Reveal constructor // 4. Options passed to Reveal.initialize // 5. Query params config = { ...defaultConfig, ...config, ...options, ...initOptions, ...Util.getQueryHash() }; // Legacy support for the ?print-pdf query if( /print-pdf/gi.test( window.location.search ) ) { config.view = 'print'; } setViewport(); // Force a layout when the whole page, incl fonts, has loaded window.addEventListener( 'load', layout, false ); // Register plugins and load dependencies, then move on to #start() plugins.load( config.plugins, config.dependencies ).then( start ); return new Promise( resolve => Reveal.on( 'ready', resolve ) ); } /** * Encase the presentation in a reveal.js viewport. The * extent of the viewport differs based on configuration. */ function setViewport() { // Embedded decks use the reveal element as their viewport if( config.embedded === true ) { dom.viewport = Util.closest( revealElement, '.reveal-viewport' ) || revealElement; } // Full-page decks use the body as their viewport else { dom.viewport = document.body; document.documentElement.classList.add( 'reveal-full-page' ); } dom.viewport.classList.add( 'reveal-viewport' ); } /** * Starts up reveal.js by binding input events and navigating * to the current URL deeplink if there is one. */ function start() { // Don't proceed if this instance has been destroyed if( initialized === false ) return; ready = true; // Remove slides hidden with data-visibility removeHiddenSlides(); // Make sure we've got all the DOM elements we need setupDOM(); // Listen to messages posted to this window setupPostMessage(); // Prevent the slides from being scrolled out of view setupScrollPrevention(); // Adds bindings for fullscreen mode setupFullscreen(); // Resets all vertical slides so that only the first is visible resetVerticalSlides(); // Updates the presentation to match the current configuration values configure(); // Create slide backgrounds backgrounds.update( true ); // Activate the print/scroll view if configured activateInitialView(); // Read the initial hash location.readURL(); // Notify listeners that the presentation is ready but use a 1ms // timeout to ensure it's not fired synchronously after #initialize() setTimeout( () => { // Enable transitions now that we're loaded dom.slides.classList.remove( 'no-transition' ); dom.wrapper.classList.add( 'ready' ); dispatchEvent({ type: 'ready', data: { indexh, indexv, currentSlide } }); }, 1 ); } /** * Activates the correct reveal.js view based on our config. * This is only invoked once during initialization. */ function activateInitialView() { const activatePrintView = config.view === 'print'; const activateScrollView = config.view === 'scroll' || config.view === 'reader'; if( activatePrintView || activateScrollView ) { if( activatePrintView ) { removeEventListeners(); } else { touch.unbind(); } // Avoid content flickering during layout dom.viewport.classList.add( 'loading-scroll-mode' ); if( activatePrintView ) { // The document needs to have loaded for the PDF layout // measurements to be accurate if( document.readyState === 'complete' ) { printView.activate(); } else { window.addEventListener( 'load', () => printView.activate() ); } } else { scrollView.activate(); } } } /** * Removes all slides with data-visibility="hidden". This * is done right before the rest of the presentation is * initialized. * * If you want to show all hidden slides, initialize * reveal.js with showHiddenSlides set to true. */ function removeHiddenSlides() { if( !config.showHiddenSlides ) { Util.queryAll( dom.wrapper, 'section[data-visibility="hidden"]' ).forEach( slide => { const parent = slide.parentNode; // If this slide is part of a stack and that stack will be // empty after removing the hidden slide, remove the entire // stack if( parent.childElementCount === 1 && /section/i.test( parent.nodeName ) ) { parent.remove(); } else { slide.remove(); } } ); } } /** * Finds and stores references to DOM elements which are * required by the presentation. If a required element is * not found, it is created. */ function setupDOM() { // Prevent transitions while we're loading dom.slides.classList.add( 'no-transition' ); if( Device.isMobile ) { dom.wrapper.classList.add( 'no-hover' ); } else { dom.wrapper.classList.remove( 'no-hover' ); } backgrounds.render(); slideNumber.render(); jumpToSlide.render(); controls.render(); progress.render(); notes.render(); // Overlay graphic which is displayed during the paused mode dom.pauseOverlay = Util.createSingletonNode( dom.wrapper, 'div', 'pause-overlay', config.controls ? '<button class="resume-button">Resume presentation</button>' : null ); dom.statusElement = createStatusElement(); dom.wrapper.setAttribute( 'role', 'application' ); } /** * Creates a hidden div with role aria-live to announce the * current slide content. Hide the div off-screen to make it * available only to Assistive Technologies. * * @return {HTMLElement} */ function createStatusElement() { let statusElement = dom.wrapper.querySelector( '.aria-status' ); if( !statusElement ) { statusElement = document.createElement( 'div' ); statusElement.style.position = 'absolute'; statusElement.style.height = '1px'; statusElement.style.width = '1px'; statusElement.style.overflow = 'hidden'; statusElement.style.clip = 'rect( 1px, 1px, 1px, 1px )'; statusElement.classList.add( 'aria-status' ); statusElement.setAttribute( 'aria-live', 'polite' ); statusElement.setAttribute( 'aria-atomic','true' ); dom.wrapper.appendChild( statusElement ); } return statusElement; } /** * Announces the given text to screen readers. */ function announceStatus( value ) { dom.statusElement.textContent = value; } /** * Converts the given HTML element into a string of text * that can be announced to a screen reader. Hidden * elements are excluded. */ function getStatusText( node ) { let text = ''; // Text node if( node.nodeType === 3 ) { text += node.textContent.trim(); } // Element node else if( node.nodeType === 1 ) { let isAriaHidden = node.getAttribute( 'aria-hidden' ); let isDisplayHidden = window.getComputedStyle( node )['display'] === 'none'; if( isAriaHidden !== 'true' && !isDisplayHidden ) { // Capture alt text from img and video elements if( node.tagName === 'IMG' || node.tagName === 'VIDEO' ) { let altText = node.getAttribute( 'alt' ); if( altText ) { text += ensurePunctuation( altText ); } } Array.from( node.childNodes ).forEach( child => { text += getStatusText( child ); } ); // Add period after block-level text elements to improve // screen reader experience const textElements = ['P', 'DIV', 'UL', 'OL', 'LI', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'BLOCKQUOTE']; if( textElements.includes( node.tagName ) && text.trim() !== '' ) { text = ensurePunctuation( text ); } } } text = text.trim(); return text === '' ? '' : text + ' '; } /** * Ensures text ends with proper punctuation by adding a period * if it doesn't already end with punctuation. */ function ensurePunctuation( text ) { const trimmedText = text.trim(); if( trimmedText === '' ) { return text; } return !/[.!?]$/.test(trimmedText) ? trimmedText + '.' : trimmedText; } /** * This is an unfortunate necessity. Some actions – such as * an input field being focused in an iframe or using the * keyboard to expand text selection beyond the bounds of * a slide – can trigger our content to be pushed out of view. * This scrolling can not be prevented by hiding overflow in * CSS (we already do) so we have to resort to repeatedly * checking if the slides have been offset :( */ function setupScrollPrevention() { setInterval( () => { if( !scrollView.isActive() && dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0 ) { dom.wrapper.scrollTop = 0; dom.wrapper.scrollLeft = 0; } }, 1000 ); } /** * After entering fullscreen we need to force a layout to * get our presentations to scale correctly. This behavior * is inconsistent across browsers but a force layout seems * to normalize it. */ function setupFullscreen() { document.addEventListener( 'fullscreenchange', onFullscreenChange ); document.addEventListener( 'webkitfullscreenchange', onFullscreenChange ); } /** * Registers a listener to postMessage events, this makes it * possible to call all reveal.js API methods from another * window. For example: * * revealWindow.postMessage( JSON.stringify({ * method: 'slide', * args: [ 2 ] * }), '*' ); */ function setupPostMessage() { if( config.postMessage ) { window.addEventListener( 'message', onPostMessage, false ); } } /** * Applies the configuration settings from the config * object. May be called multiple times. * * @param {object} options */ function configure( options ) { const oldConfig = { ...config } // New config options may be passed when this method // is invoked through the API after initialization if( typeof options === 'object' ) Util.extend( config, options ); // Abort if reveal.js hasn't finished loading, config // changes will be applied automatically once ready if( Reveal.isReady() === false ) return; const numberOfSlides = dom.wrapper.querySelectorAll( SLIDES_SELECTOR ).length; // The transition is added as a class on the .reveal element dom.wrapper.classList.remove( oldConfig.transition ); dom.wrapper.classList.add( config.transition ); dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed ); dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition ); // Expose our configured slide dimensions as custom props dom.viewport.style.setProperty( '--slide-width', typeof config.width === 'string' ? config.width : config.width + 'px' ); dom.viewport.style.setProperty( '--slide-height', typeof config.height === 'string' ? config.height : config.height + 'px' ); if( config.shuffle ) { shuffle(); } Util.toggleClass( dom.wrapper, 'embedded', config.embedded ); Util.toggleClass( dom.wrapper, 'rtl', config.rtl ); Util.toggleClass( dom.wrapper, 'center', config.center ); // Exit the paused mode if it was configured off if( config.pause === false ) { resume(); } // Reset all changes made by auto-animations autoAnimate.reset(); // Remove existing auto-slide controls if( autoSlidePlayer ) { autoSlidePlayer.destroy(); autoSlidePlayer = null; } // Generate auto-slide controls if needed if( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable ) { autoSlidePlayer = new Playback( dom.wrapper, () => { return Math.min( Math.max( ( Date.now() - autoSlideStartTime ) / autoSlide, 0 ), 1 ); } ); autoSlidePlayer.on( 'click', onAutoSlidePlayerClick ); autoSlidePaused = false; } // Add the navigation mode to the DOM so we can adjust styling if( config.navigationMode !== 'default' ) { dom.wrapper.setAttribute( 'data-navigation-mode', config.navigationMode ); } else { dom.wrapper.removeAttribute( 'data-navigation-mode' ); } notes.configure( config, oldConfig ); focus.configure( config, oldConfig ); pointer.configure( config, oldConfig ); controls.configure( config, oldConfig ); progress.configure( config, oldConfig ); keyboard.configure( config, oldConfig ); fragments.configure( config, oldConfig ); slideNumber.configure( config, oldConfig ); sync(); } /** * Binds all event listeners. */ function addEventListeners() { eventsAreBound = true; window.addEventListener( 'resize', onWindowResize, false ); if( config.touch ) touch.bind(); if( config.keyboard ) keyboard.bind(); if( config.progress ) progress.bind(); if( config.respondToHashChanges ) location.bind(); controls.bind(); focus.bind(); dom.slides.addEventListener( 'click', onSlidesClicked, false ); dom.slides.addEventListener( 'transitionend', onTransitionEnd, false ); dom.pauseOverlay.addEventListener( 'click', resume, false ); if( config.focusBodyOnPageVisibilityChange ) { document.addEventListener( 'visibilitychange', onPageVisibilityChange, false ); } } /** * Unbinds all event listeners. */ function removeEventListeners() { eventsAreBound = false; touch.unbind(); focus.unbind(); keyboard.unbind(); controls.unbind(); progress.unbind(); location.unbind(); window.removeEventListener( 'resize', onWindowResize, false ); dom.slides.removeEventListener( 'click', onSlidesClicked, false ); dom.slides.removeEventListener( 'transitionend', onTransitionEnd, false ); dom.pauseOverlay.removeEventListener( 'click', resume, false ); } /** * Uninitializes reveal.js by undoing changes made to the * DOM and removing all event listeners. */ function destroy() { initialized = false; // There's nothing to destroy if this instance hasn't finished // initializing if( ready === false ) return; removeEventListeners(); cancelAutoSlide(); // Destroy controllers notes.destroy(); focus.destroy(); overlay.destroy(); plugins.destroy(); pointer.destroy(); controls.destroy(); progress.destroy(); backgrounds.destroy(); slideNumber.destroy(); jumpToSlide.destroy(); // Remove event listeners document.removeEventListener( 'fullscreenchange', onFullscreenChange ); document.removeEventListener( 'webkitfullscreenchange', onFullscreenChange ); document.removeEventListener( 'visibilitychange', onPageVisibilityChange, false ); window.removeEventListener( 'message', onPostMessage, false ); window.removeEventListener( 'load', layout, false ); // Undo DOM changes if( dom.pauseOverlay ) dom.pauseOverlay.remove(); if( dom.statusElement ) dom.statusElement.remove(); document.documentElement.classList.remove( 'reveal-full-page' ); dom.wrapper.classList.remove( 'ready', 'center', 'has-horizontal-slides', 'has-vertical-slides' ); dom.wrapper.removeAttribute( 'data-transition-speed' ); dom.wrapper.removeAttribute( 'data-background-transition' ); dom.viewport.classList.remove( 'reveal-viewport' ); dom.viewport.style.removeProperty( '--slide-width' ); dom.viewport.style.removeProperty( '--slide-height' ); dom.slides.style.removeProperty( 'width' ); dom.slides.style.removeProperty( 'height' ); dom.slides.style.removeProperty( 'zoom' ); dom.slides.style.removeProperty( 'left' ); dom.slides.style.removeProperty( 'top' ); dom.slides.style.removeProperty( 'bottom' ); dom.slides.style.removeProperty( 'right' ); dom.slides.style.removeProperty( 'transform' ); Array.from( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( slide => { slide.style.removeProperty( 'display' ); slide.style.removeProperty( 'top' ); slide.removeAttribute( 'hidden' ); slide.removeAttribute( 'aria-hidden' ); } ); } /** * Adds a listener to one of our custom reveal.js events, * like slidechanged. */ function on( type, listener, useCapture ) { revealElement.addEventListener( type, listener, useCapture ); } /** * Unsubscribes from a reveal.js event. */ function off( type, listener, useCapture ) { revealElement.removeEventListener( type, listener, useCapture ); } /** * Applies CSS transforms to the slides container. The container * is transformed from two separate sources: layout and the overview * mode. * * @param {object} transforms */ function transformSlides( transforms ) { // Pick up new transforms from arguments if( typeof transforms.layout === 'string' ) slidesTransform.layout = transforms.layout; if( typeof transforms.overview === 'string' ) slidesTransform.overview = transforms.overview; // Apply the transforms to the slides container if( slidesTransform.layout ) { Util.transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview ); } else { Util.transformElement( dom.slides, slidesTransform.overview ); } } /** * Dispatches an event of the specified type from the * reveal DOM element. */ function dispatchEvent({ target=dom.wrapper, type, data, bubbles=true }) { let event = document.createEvent( 'HTMLEvents', 1, 2 ); event.initEvent( type, bubbles, true ); Util.extend( event, data ); target.dispatchEvent( event ); if( target === dom.wrapper ) { // If we're in an iframe, post each reveal.js event to the // parent window. Used by the notes plugin dispatchPostMessage( type ); } return event; } /** * Dispatches a slidechanged event. * * @param {string} origin Used to identify multiplex clients */ function dispatchSlideChanged( origin ) { dispatchEvent({ type: 'slidechanged', data: { indexh, indexv, previousSlide, currentSlide, origin } }); } /** * Dispatched a postMessage of the given type from our window. */ function dispatchPostMessage( type, data ) { if( config.postMessageEvents && window.parent !== window.self ) { let message = { namespace: 'reveal', eventName: type, state: getState() }; Util.extend( message, data ); window.parent.postMessage( JSON.stringify( message ), '*' ); } } /** * Applies JavaScript-controlled layout rules to the * presentation. */ function layout() { if( dom.wrapper && !printView.isActive() ) { const viewportWidth = dom.viewport.offsetWidth; const viewportHeight = dom.viewport.offsetHeight; if( !config.disableLayout ) { // On some mobile devices '100vh' is taller than the visible // viewport which leads to part of the presentation being // cut off. To work around this we define our own '--vh' custom // property where 100x adds up to the correct height. // // https://css-tricks.com/the-trick-to-viewport-units-on-mobile/ if( Device.isMobile && !config.embedded ) { document.documentElement.style.setProperty( '--vh', ( window.innerHeight * 0.01 ) + 'px' ); } const size = scrollView.isActive() ? getComputedSlideSize( viewportWidth, viewportHeight ) : getComputedSlideSize(); const oldScale = scale; // Layout the contents of the slides layoutSlideContents( config.width, config.height ); dom.slides.style.width = size.width + 'px'; dom.slides.style.height = size.height + 'px'; // Determine scale of content to fit within available space scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height ); // Respect max/min scale settings scale = Math.max( scale, config.minScale ); scale = Math.min( scale, config.maxScale ); // Don't apply any scaling styles if scale is 1 or we're // in the scroll view if( scale === 1 || scrollView.isActive() ) { dom.slides.style.zoom = ''; dom.slides.style.left = ''; dom.slides.style.top = ''; dom.slides.style.bottom = ''; dom.slides.style.right = ''; transformSlides( { layout: '' } ); } else { dom.slides.style.zoom = ''; dom.slides.style.left = '50%'; dom.slides.style.top = '50%'; dom.slides.style.bottom = 'auto'; dom.slides.style.right = 'auto'; transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } ); } // Select all slides, vertical and horizontal const slides = Array.from( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ); for( let i = 0, len = slides.length; i < len; i++ ) { const slide = slides[ i ]; // Don't bother updating invisible slides if( slide.style.display === 'none' ) { continue; } if( ( config.center || slide.classList.contains( 'center' ) ) ) { // Vertical stacks are not centred since their section // children will be if( slide.classList.contains( 'stack' ) ) { slide.style.top = 0; } else { slide.style.top = Math.max( ( size.height - slide.scrollHeight ) / 2, 0 ) + 'px'; } } else { slide.style.top = ''; } } if( oldScale !== scale ) { dispatchEvent({ type: 'resize', data: { oldScale, scale, size } }); } } checkResponsiveScrollView(); dom.viewport.style.setProperty( '--slide-scale', scale ); dom.viewport.style.setProperty( '--viewport-width', viewportWidth + 'px' ); dom.viewport.style.setProperty( '--viewport-height', viewportHeight + 'px' ); scrollView.layout(); progress.update(); backgrounds.updateParallax(); if( overview.isActive() ) { overview.update(); } } } /** * Applies layout logic to the contents of all slides in * the presentation. * * @param {string|number} width * @param {string|number} height */ function layoutSlideContents( width, height ) { // Handle sizing of elements with the 'r-stretch' class Util.queryAll( dom.slides, 'section > .stretch, section > .r-stretch' ).forEach( element => { // Determine how much vertical space we can use let remainingHeight = Util.getRemainingHeight( element, height ); // Consider the aspect ratio of media elements if( /(img|video)/gi.test( element.nodeName ) ) { const nw = element.naturalWidth || element.videoWidth, nh = element.naturalHeight || element.videoHeight; const es = Math.min( width / nw, remainingHeight / nh ); element.style.width = ( nw * es ) + 'px'; element.style.height = ( nh * es ) + 'px'; } else { element.style.width = width + 'px'; element.style.height = remainingHeight + 'px'; } } ); } /** * Responsively activates the scroll mode when we reach the configured * activation width. */ function checkResponsiveScrollView() { // Only proceed if... // 1. The DOM is ready // 2. Layouts aren't disabled via config // 3. We're not currently printing // 4. There is a scrollActivationWidth set // 5. The deck isn't configured to always use the scroll view if( dom.wrapper && !config.disableLayout && !printView.isActive() && typeof config.scrollActivationWidth === 'number' && config.view !== 'scroll' ) { const size = getComputedSlideSize(); if( size.presentationWidth > 0 && size.presentationWidth <= config.scrollActivationWidth ) { if( !scrollView.isActive() ) { backgrounds.create(); scrollView.activate() }; } else { if( scrollView.isActive() ) scrollView.deactivate(); } } } /** * Calculates the computed pixel size of our slides. These * values are based on the width and height configuration * options. * * @param {number} [presentationWidth=dom.wrapper.offsetWidth] * @param {number} [presentationHeight=dom.wrapper.offsetHeight] */ function getComputedSlideSize( presentationWidth, presentationHeight ) { let width = config.width; let height = config.height; if( config.disableLayout ) { width = dom.slides.offsetWidth; height = dom.slides.offsetHeight; } const size = { // Slide size width: width, height: height, // Presentation size presentationWidth: presentationWidth || dom.wrapper.offsetWidth, presentationHeight: presentationHeight || dom.wrapper.offsetHeight }; // Reduce available space by margin size.presentationWidth -= ( size.presentationWidth * config.margin ); size.presentationHeight -= ( size.presentationHeight * config.margin ); // Slide width may be a percentage of available width if( typeof size.width === 'string' && /%$/.test( size.width ) ) { size.width = parseInt( size.width, 10 ) / 100 * size.presentationWidth; } // Slide height may be a percentage of available height if( typeof size.height === 'string' && /%$/.test( size.height ) ) { size.height = parseInt( size.height, 10 ) / 100 * size.presentationHeight; } return size; } /** * Stores the vertical index of a stack so that the same * vertical slide can be selected when navigating to and * from the stack. * * @param {HTMLElement} stack The vertical stack element * @param {string|number} [v=0] Index to memorize */ function setPreviousVerticalIndex( stack, v ) { if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) { stack.setAttribute( 'data-previous-indexv', v || 0 ); } } /** * Retrieves the vertical index which was stored using * #setPreviousVerticalIndex() or 0 if no previous index * exists. * * @param {HTMLElement} stack The vertical stack element */ function getPreviousVerticalIndex( stack ) { if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) { // Prefer manually defined start-indexv const attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv'; return parseInt( stack.getAttribute( attributeName ) || 0, 10 ); } return 0; } /** * Checks if the current or specified slide is vertical * (nested within another slide). * * @param {HTMLElement} [slide=currentSlide] The slide to check * orientation of * @return {Boolean} */ function isVerticalSlide( slide = currentSlide ) { return slide && slide.parentNode && !!slide.parentNode.nodeName.match( /section/i ); } /** * Checks if the current or specified slide is a stack containing * vertical slides. * * @param {HTMLElement} [slide=currentSlide] * @return {Boolean} */ function isVerticalStack( slide = currentSlide ) { return slide.classList.contains( '.stack' ) || slide.querySelector( 'section' ) !== null; } /** * Returns true if we're on the last slide in the current * vertical stack. */ function isLastVerticalSlide() { if( currentSlide && isVerticalSlide( currentSlide ) ) { // Does this slide have a next sibling? if( currentSlide.nextElementSibling ) return false; return true; } return false; } /** * Returns true if we're currently on the first slide in * the presentation. */ function isFirstSlide() { return indexh === 0 && indexv === 0; } /** * Returns true if we're currently on the last slide in * the presentation. If the last slide is a stack, we only * consider this the last slide if it's at the end of the * stack. */ function isLastSlide() { if( currentSlide ) { // Does this slide have a next sibling? if( currentSlide.nextElementSibling ) return false; // If it's vertical, does its parent have a next sibling? if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false; return true; } return false; } /** * Enters the paused mode which fades everything on screen to * black. */ function pause() { if( config.pause ) { const wasPaused = dom.wrapper.classList.contains( 'paused' ); cancelAutoSlide(); dom.wrapper.classList.add( 'paused' ); if( wasPaused === false ) { dispatchEvent({ type: 'paused' }); } } } /** * Exits from the paused mode. */ function resume() { const wasPaused = dom.wrapper.classList.contains( 'paused' ); dom.wrapper.classList.remove( 'paused' ); cueAutoSlide(); if( wasPaused ) { dispatchEvent({ type: 'resumed' }); } } /** * Toggles the paused mode on and off. */ function togglePause( override ) { if( typeof override === 'boolean' ) { override ? pause() : resume(); } else { isPaused() ? resume() : pause(); } } /** * Checks if we are currently in the paused mode. *
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
true
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/controls.js
js/controllers/controls.js
import { queryAll, enterFullscreen } from '../utils/util.js' import { isAndroid } from '../utils/device.js' /** * Manages our presentation controls. This includes both * the built-in control arrows as well as event monitoring * of any elements within the presentation with either of the * following helper classes: * - .navigate-up * - .navigate-right * - .navigate-down * - .navigate-left * - .navigate-next * - .navigate-prev * - .enter-fullscreen */ export default class Controls { constructor( Reveal ) { this.Reveal = Reveal; this.onNavigateLeftClicked = this.onNavigateLeftClicked.bind( this ); this.onNavigateRightClicked = this.onNavigateRightClicked.bind( this ); this.onNavigateUpClicked = this.onNavigateUpClicked.bind( this ); this.onNavigateDownClicked = this.onNavigateDownClicked.bind( this ); this.onNavigatePrevClicked = this.onNavigatePrevClicked.bind( this ); this.onNavigateNextClicked = this.onNavigateNextClicked.bind( this ); this.onEnterFullscreen = this.onEnterFullscreen.bind( this ); } render() { const rtl = this.Reveal.getConfig().rtl; const revealElement = this.Reveal.getRevealElement(); this.element = document.createElement( 'aside' ); this.element.className = 'controls'; this.element.innerHTML = `<button class="navigate-left" aria-label="${ rtl ? 'next slide' : 'previous slide' }"><div class="controls-arrow"></div></button> <button class="navigate-right" aria-label="${ rtl ? 'previous slide' : 'next slide' }"><div class="controls-arrow"></div></button> <button class="navigate-up" aria-label="above slide"><div class="controls-arrow"></div></button> <button class="navigate-down" aria-label="below slide"><div class="controls-arrow"></div></button>`; this.Reveal.getRevealElement().appendChild( this.element ); // There can be multiple instances of controls throughout the page this.controlsLeft = queryAll( revealElement, '.navigate-left' ); this.controlsRight = queryAll( revealElement, '.navigate-right' ); this.controlsUp = queryAll( revealElement, '.navigate-up' ); this.controlsDown = queryAll( revealElement, '.navigate-down' ); this.controlsPrev = queryAll( revealElement, '.navigate-prev' ); this.controlsNext = queryAll( revealElement, '.navigate-next' ); this.controlsFullscreen = queryAll( revealElement, '.enter-fullscreen' ); // The left, right and down arrows in the standard reveal.js controls this.controlsRightArrow = this.element.querySelector( '.navigate-right' ); this.controlsLeftArrow = this.element.querySelector( '.navigate-left' ); this.controlsDownArrow = this.element.querySelector( '.navigate-down' ); } /** * Called when the reveal.js config is updated. */ configure( config, oldConfig ) { this.element.style.display = ( config.controls && (config.controls !== 'speaker-only' || this.Reveal.isSpeakerNotes()) ) ? 'block' : 'none'; this.element.setAttribute( 'data-controls-layout', config.controlsLayout ); this.element.setAttribute( 'data-controls-back-arrows', config.controlsBackArrows ); } bind() { // Listen to both touch and click events, in case the device // supports both let pointerEvents = [ 'touchstart', 'click' ]; // Only support touch for Android, fixes double navigations in // stock browser. Use touchend for it to be considered a valid // user interaction (so we're allowed to autoplay media). if( isAndroid ) { pointerEvents = [ 'touchend' ]; } pointerEvents.forEach( eventName => { this.controlsLeft.forEach( el => el.addEventListener( eventName, this.onNavigateLeftClicked, false ) ); this.controlsRight.forEach( el => el.addEventListener( eventName, this.onNavigateRightClicked, false ) ); this.controlsUp.forEach( el => el.addEventListener( eventName, this.onNavigateUpClicked, false ) ); this.controlsDown.forEach( el => el.addEventListener( eventName, this.onNavigateDownClicked, false ) ); this.controlsPrev.forEach( el => el.addEventListener( eventName, this.onNavigatePrevClicked, false ) ); this.controlsNext.forEach( el => el.addEventListener( eventName, this.onNavigateNextClicked, false ) ); this.controlsFullscreen.forEach( el => el.addEventListener( eventName, this.onEnterFullscreen, false ) ); } ); } unbind() { [ 'touchstart', 'touchend', 'click' ].forEach( eventName => { this.controlsLeft.forEach( el => el.removeEventListener( eventName, this.onNavigateLeftClicked, false ) ); this.controlsRight.forEach( el => el.removeEventListener( eventName, this.onNavigateRightClicked, false ) ); this.controlsUp.forEach( el => el.removeEventListener( eventName, this.onNavigateUpClicked, false ) ); this.controlsDown.forEach( el => el.removeEventListener( eventName, this.onNavigateDownClicked, false ) ); this.controlsPrev.forEach( el => el.removeEventListener( eventName, this.onNavigatePrevClicked, false ) ); this.controlsNext.forEach( el => el.removeEventListener( eventName, this.onNavigateNextClicked, false ) ); this.controlsFullscreen.forEach( el => el.removeEventListener( eventName, this.onEnterFullscreen, false ) ); } ); } /** * Updates the state of all control/navigation arrows. */ update() { let routes = this.Reveal.availableRoutes(); // Remove the 'enabled' class from all directions [...this.controlsLeft, ...this.controlsRight, ...this.controlsUp, ...this.controlsDown, ...this.controlsPrev, ...this.controlsNext].forEach( node => { node.classList.remove( 'enabled', 'fragmented' ); // Set 'disabled' attribute on all directions node.setAttribute( 'disabled', 'disabled' ); } ); // Add the 'enabled' class to the available routes; remove 'disabled' attribute to enable buttons if( routes.left ) this.controlsLeft.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( routes.right ) this.controlsRight.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( routes.up ) this.controlsUp.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( routes.down ) this.controlsDown.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); // Prev/next buttons if( routes.left || routes.up ) this.controlsPrev.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( routes.right || routes.down ) this.controlsNext.forEach( el => { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } ); // Highlight fragment directions let currentSlide = this.Reveal.getCurrentSlide(); if( currentSlide ) { let fragmentsRoutes = this.Reveal.fragments.availableRoutes(); // Always apply fragment decorator to prev/next buttons if( fragmentsRoutes.prev ) this.controlsPrev.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( fragmentsRoutes.next ) this.controlsNext.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); const isVerticalStack = this.Reveal.isVerticalSlide( currentSlide ); const hasVerticalSiblings = isVerticalStack && currentSlide.parentElement && currentSlide.parentElement.querySelectorAll( ':scope > section' ).length > 1; // Apply fragment decorators to directional buttons based on // what slide axis they are in if( isVerticalStack && hasVerticalSiblings ) { if( fragmentsRoutes.prev ) this.controlsUp.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( fragmentsRoutes.next ) this.controlsDown.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); } else { if( fragmentsRoutes.prev ) this.controlsLeft.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); if( fragmentsRoutes.next ) this.controlsRight.forEach( el => { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } ); } } if( this.Reveal.getConfig().controlsTutorial ) { let indices = this.Reveal.getIndices(); // Highlight control arrows with an animation to ensure // that the viewer knows how to navigate if( !this.Reveal.hasNavigatedVertically() && routes.down ) { this.controlsDownArrow.classList.add( 'highlight' ); } else { this.controlsDownArrow.classList.remove( 'highlight' ); if( this.Reveal.getConfig().rtl ) { if( !this.Reveal.hasNavigatedHorizontally() && routes.left && indices.v === 0 ) { this.controlsLeftArrow.classList.add( 'highlight' ); } else { this.controlsLeftArrow.classList.remove( 'highlight' ); } } else { if( !this.Reveal.hasNavigatedHorizontally() && routes.right && indices.v === 0 ) { this.controlsRightArrow.classList.add( 'highlight' ); } else { this.controlsRightArrow.classList.remove( 'highlight' ); } } } } } destroy() { this.unbind(); this.element.remove(); } /** * Event handlers for navigation control buttons. */ onNavigateLeftClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); if( this.Reveal.getConfig().navigationMode === 'linear' ) { this.Reveal.prev(); } else { this.Reveal.left(); } } onNavigateRightClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); if( this.Reveal.getConfig().navigationMode === 'linear' ) { this.Reveal.next(); } else { this.Reveal.right(); } } onNavigateUpClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); this.Reveal.up(); } onNavigateDownClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); this.Reveal.down(); } onNavigatePrevClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); this.Reveal.prev(); } onNavigateNextClicked( event ) { event.preventDefault(); this.Reveal.onUserInput(); this.Reveal.next(); } onEnterFullscreen( event ) { const config = this.Reveal.getConfig(); const viewport = this.Reveal.getViewportElement(); enterFullscreen( config.embedded ? viewport : viewport.parentElement ); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/overview.js
js/controllers/overview.js
import { SLIDES_SELECTOR } from '../utils/constants.js' import { extend, queryAll, transformElement } from '../utils/util.js' /** * Handles all logic related to the overview mode * (birds-eye view of all slides). */ export default class Overview { constructor( Reveal ) { this.Reveal = Reveal; this.active = false; this.onSlideClicked = this.onSlideClicked.bind( this ); } /** * Displays the overview of slides (quick nav) by scaling * down and arranging all slide elements. */ activate() { // Only proceed if enabled in config if( this.Reveal.getConfig().overview && !this.Reveal.isScrollView() && !this.isActive() ) { this.active = true; this.Reveal.getRevealElement().classList.add( 'overview' ); // Don't auto-slide while in overview mode this.Reveal.cancelAutoSlide(); // Move the backgrounds element into the slide container to // that the same scaling is applied this.Reveal.getSlidesElement().appendChild( this.Reveal.getBackgroundsElement() ); // Clicking on an overview slide navigates to it queryAll( this.Reveal.getRevealElement(), SLIDES_SELECTOR ).forEach( slide => { if( !slide.classList.contains( 'stack' ) ) { slide.addEventListener( 'click', this.onSlideClicked, true ); } } ); // Calculate slide sizes const margin = 70; const slideSize = this.Reveal.getComputedSlideSize(); this.overviewSlideWidth = slideSize.width + margin; this.overviewSlideHeight = slideSize.height + margin; // Reverse in RTL mode if( this.Reveal.getConfig().rtl ) { this.overviewSlideWidth = -this.overviewSlideWidth; } this.Reveal.updateSlidesVisibility(); this.layout(); this.update(); this.Reveal.layout(); const indices = this.Reveal.getIndices(); // Notify observers of the overview showing this.Reveal.dispatchEvent({ type: 'overviewshown', data: { 'indexh': indices.h, 'indexv': indices.v, 'currentSlide': this.Reveal.getCurrentSlide() } }); } } /** * Uses CSS transforms to position all slides in a grid for * display inside of the overview mode. */ layout() { // Layout slides this.Reveal.getHorizontalSlides().forEach( ( hslide, h ) => { hslide.setAttribute( 'data-index-h', h ); transformElement( hslide, 'translate3d(' + ( h * this.overviewSlideWidth ) + 'px, 0, 0)' ); if( hslide.classList.contains( 'stack' ) ) { queryAll( hslide, 'section' ).forEach( ( vslide, v ) => { vslide.setAttribute( 'data-index-h', h ); vslide.setAttribute( 'data-index-v', v ); transformElement( vslide, 'translate3d(0, ' + ( v * this.overviewSlideHeight ) + 'px, 0)' ); } ); } } ); // Layout slide backgrounds Array.from( this.Reveal.getBackgroundsElement().childNodes ).forEach( ( hbackground, h ) => { transformElement( hbackground, 'translate3d(' + ( h * this.overviewSlideWidth ) + 'px, 0, 0)' ); queryAll( hbackground, '.slide-background' ).forEach( ( vbackground, v ) => { transformElement( vbackground, 'translate3d(0, ' + ( v * this.overviewSlideHeight ) + 'px, 0)' ); } ); } ); } /** * Moves the overview viewport to the current slides. * Called each time the current slide changes. */ update() { const vmin = Math.min( window.innerWidth, window.innerHeight ); const scale = Math.max( vmin / 5, 150 ) / vmin; const indices = this.Reveal.getIndices(); this.Reveal.transformSlides( { overview: [ 'scale('+ scale +')', 'translateX('+ ( -indices.h * this.overviewSlideWidth ) +'px)', 'translateY('+ ( -indices.v * this.overviewSlideHeight ) +'px)' ].join( ' ' ) } ); } /** * Exits the slide overview and enters the currently * active slide. */ deactivate() { // Only proceed if enabled in config if( this.Reveal.getConfig().overview ) { this.active = false; this.Reveal.getRevealElement().classList.remove( 'overview' ); // Temporarily add a class so that transitions can do different things // depending on whether they are exiting/entering overview, or just // moving from slide to slide this.Reveal.getRevealElement().classList.add( 'overview-deactivating' ); setTimeout( () => { this.Reveal.getRevealElement().classList.remove( 'overview-deactivating' ); }, 1 ); // Move the background element back out this.Reveal.getRevealElement().appendChild( this.Reveal.getBackgroundsElement() ); // Clean up changes made to slides queryAll( this.Reveal.getRevealElement(), SLIDES_SELECTOR ).forEach( slide => { transformElement( slide, '' ); slide.removeEventListener( 'click', this.onSlideClicked, true ); } ); // Clean up changes made to backgrounds queryAll( this.Reveal.getBackgroundsElement(), '.slide-background' ).forEach( background => { transformElement( background, '' ); } ); this.Reveal.transformSlides( { overview: '' } ); const indices = this.Reveal.getIndices(); this.Reveal.slide( indices.h, indices.v ); this.Reveal.layout(); this.Reveal.cueAutoSlide(); // Notify observers of the overview hiding this.Reveal.dispatchEvent({ type: 'overviewhidden', data: { 'indexh': indices.h, 'indexv': indices.v, 'currentSlide': this.Reveal.getCurrentSlide() } }); } } /** * Toggles the slide overview mode on and off. * * @param {Boolean} [override] Flag which overrides the * toggle logic and forcibly sets the desired state. True means * overview is open, false means it's closed. */ toggle( override ) { if( typeof override === 'boolean' ) { override ? this.activate() : this.deactivate(); } else { this.isActive() ? this.deactivate() : this.activate(); } } /** * Checks if the overview is currently active. * * @return {Boolean} true if the overview is active, * false otherwise */ isActive() { return this.active; } /** * Invoked when a slide is and we're in the overview. * * @param {object} event */ onSlideClicked( event ) { if( this.isActive() ) { event.preventDefault(); let element = event.target; while( element && !element.nodeName.match( /section/gi ) ) { element = element.parentNode; } if( element && !element.classList.contains( 'disabled' ) ) { this.deactivate(); if( element.nodeName.match( /section/gi ) ) { let h = parseInt( element.getAttribute( 'data-index-h' ), 10 ), v = parseInt( element.getAttribute( 'data-index-v' ), 10 ); this.Reveal.slide( h, v ); } } } } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/plugins.js
js/controllers/plugins.js
import { loadScript } from '../utils/loader.js' /** * Manages loading and registering of reveal.js plugins. */ export default class Plugins { constructor( reveal ) { this.Reveal = reveal; // Flags our current state (idle -> loading -> loaded) this.state = 'idle'; // An id:instance map of currently registered plugins this.registeredPlugins = {}; this.asyncDependencies = []; } /** * Loads reveal.js dependencies, registers and * initializes plugins. * * Plugins are direct references to a reveal.js plugin * object that we register and initialize after any * synchronous dependencies have loaded. * * Dependencies are defined via the 'dependencies' config * option and will be loaded prior to starting reveal.js. * Some dependencies may have an 'async' flag, if so they * will load after reveal.js has been started up. */ load( plugins, dependencies ) { this.state = 'loading'; plugins.forEach( this.registerPlugin.bind( this ) ); return new Promise( resolve => { let scripts = [], scriptsToLoad = 0; dependencies.forEach( s => { // Load if there's no condition or the condition is truthy if( !s.condition || s.condition() ) { if( s.async ) { this.asyncDependencies.push( s ); } else { scripts.push( s ); } } } ); if( scripts.length ) { scriptsToLoad = scripts.length; const scriptLoadedCallback = (s) => { if( s && typeof s.callback === 'function' ) s.callback(); if( --scriptsToLoad === 0 ) { this.initPlugins().then( resolve ); } }; // Load synchronous scripts scripts.forEach( s => { if( typeof s.id === 'string' ) { this.registerPlugin( s ); scriptLoadedCallback( s ); } else if( typeof s.src === 'string' ) { loadScript( s.src, () => scriptLoadedCallback(s) ); } else { console.warn( 'Unrecognized plugin format', s ); scriptLoadedCallback(); } } ); } else { this.initPlugins().then( resolve ); } } ); } /** * Initializes our plugins and waits for them to be ready * before proceeding. */ initPlugins() { return new Promise( resolve => { let pluginValues = Object.values( this.registeredPlugins ); let pluginsToInitialize = pluginValues.length; // If there are no plugins, skip this step if( pluginsToInitialize === 0 ) { this.loadAsync().then( resolve ); } // ... otherwise initialize plugins else { let initNextPlugin; let afterPlugInitialized = () => { if( --pluginsToInitialize === 0 ) { this.loadAsync().then( resolve ); } else { initNextPlugin(); } }; let i = 0; // Initialize plugins serially initNextPlugin = () => { let plugin = pluginValues[i++]; // If the plugin has an 'init' method, invoke it if( typeof plugin.init === 'function' ) { let promise = plugin.init( this.Reveal ); // If the plugin returned a Promise, wait for it if( promise && typeof promise.then === 'function' ) { promise.then( afterPlugInitialized ); } else { afterPlugInitialized(); } } else { afterPlugInitialized(); } } initNextPlugin(); } } ) } /** * Loads all async reveal.js dependencies. */ loadAsync() { this.state = 'loaded'; if( this.asyncDependencies.length ) { this.asyncDependencies.forEach( s => { loadScript( s.src, s.callback ); } ); } return Promise.resolve(); } /** * Registers a new plugin with this reveal.js instance. * * reveal.js waits for all registered plugins to initialize * before considering itself ready, as long as the plugin * is registered before calling `Reveal.initialize()`. */ registerPlugin( plugin ) { // Backwards compatibility to make reveal.js ~3.9.0 // plugins work with reveal.js 4.0.0 if( arguments.length === 2 && typeof arguments[0] === 'string' ) { plugin = arguments[1]; plugin.id = arguments[0]; } // Plugin can optionally be a function which we call // to create an instance of the plugin else if( typeof plugin === 'function' ) { plugin = plugin(); } let id = plugin.id; if( typeof id !== 'string' ) { console.warn( 'Unrecognized plugin format; can\'t find plugin.id', plugin ); } else if( this.registeredPlugins[id] === undefined ) { this.registeredPlugins[id] = plugin; // If a plugin is registered after reveal.js is loaded, // initialize it right away if( this.state === 'loaded' && typeof plugin.init === 'function' ) { plugin.init( this.Reveal ); } } else { console.warn( 'reveal.js: "'+ id +'" plugin has already been registered' ); } } /** * Checks if a specific plugin has been registered. * * @param {String} id Unique plugin identifier */ hasPlugin( id ) { return !!this.registeredPlugins[id]; } /** * Returns the specific plugin instance, if a plugin * with the given ID has been registered. * * @param {String} id Unique plugin identifier */ getPlugin( id ) { return this.registeredPlugins[id]; } getRegisteredPlugins() { return this.registeredPlugins; } destroy() { Object.values( this.registeredPlugins ).forEach( plugin => { if( typeof plugin.destroy === 'function' ) { plugin.destroy(); } } ); this.registeredPlugins = {}; this.asyncDependencies = []; } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/progress.js
js/controllers/progress.js
/** * Creates a visual progress bar for the presentation. */ export default class Progress { constructor( Reveal ) { this.Reveal = Reveal; this.onProgressClicked = this.onProgressClicked.bind( this ); } render() { this.element = document.createElement( 'div' ); this.element.className = 'progress'; this.Reveal.getRevealElement().appendChild( this.element ); this.bar = document.createElement( 'span' ); this.element.appendChild( this.bar ); } /** * Called when the reveal.js config is updated. */ configure( config, oldConfig ) { this.element.style.display = config.progress ? 'block' : 'none'; } bind() { if( this.Reveal.getConfig().progress && this.element ) { this.element.addEventListener( 'click', this.onProgressClicked, false ); } } unbind() { if ( this.Reveal.getConfig().progress && this.element ) { this.element.removeEventListener( 'click', this.onProgressClicked, false ); } } /** * Updates the progress bar to reflect the current slide. */ update() { // Update progress if enabled if( this.Reveal.getConfig().progress && this.bar ) { let scale = this.Reveal.getProgress(); // Don't fill the progress bar if there's only one slide if( this.Reveal.getTotalSlides() < 2 ) { scale = 0; } this.bar.style.transform = 'scaleX('+ scale +')'; } } getMaxWidth() { return this.Reveal.getRevealElement().offsetWidth; } /** * Clicking on the progress bar results in a navigation to the * closest approximate horizontal slide using this equation: * * ( clickX / presentationWidth ) * numberOfSlides * * @param {object} event */ onProgressClicked( event ) { this.Reveal.onUserInput( event ); event.preventDefault(); let slides = this.Reveal.getSlides(); let slidesTotal = slides.length; let slideIndex = Math.floor( ( event.clientX / this.getMaxWidth() ) * slidesTotal ); if( this.Reveal.getConfig().rtl ) { slideIndex = slidesTotal - slideIndex; } let targetIndices = this.Reveal.getIndices(slides[slideIndex]); this.Reveal.slide( targetIndices.h, targetIndices.v ); } destroy() { this.element.remove(); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/autoanimate.js
js/controllers/autoanimate.js
import { queryAll, extend, createStyleSheet, matches, closest } from '../utils/util.js' import { FRAGMENT_STYLE_REGEX } from '../utils/constants.js' // Counter used to generate unique IDs for auto-animated elements let autoAnimateCounter = 0; /** * Automatically animates matching elements across * slides with the [data-auto-animate] attribute. */ export default class AutoAnimate { constructor( Reveal ) { this.Reveal = Reveal; } /** * Runs an auto-animation between the given slides. * * @param {HTMLElement} fromSlide * @param {HTMLElement} toSlide */ run( fromSlide, toSlide ) { // Clean up after prior animations this.reset(); let allSlides = this.Reveal.getSlides(); let toSlideIndex = allSlides.indexOf( toSlide ); let fromSlideIndex = allSlides.indexOf( fromSlide ); // Ensure that; // 1. Both slides exist. // 2. Both slides are auto-animate targets with the same // data-auto-animate-id value (including null if absent on both). // 3. data-auto-animate-restart isn't set on the physically latter // slide (independent of slide direction). if( fromSlide && toSlide && fromSlide.hasAttribute( 'data-auto-animate' ) && toSlide.hasAttribute( 'data-auto-animate' ) && fromSlide.getAttribute( 'data-auto-animate-id' ) === toSlide.getAttribute( 'data-auto-animate-id' ) && !( toSlideIndex > fromSlideIndex ? toSlide : fromSlide ).hasAttribute( 'data-auto-animate-restart' ) ) { // Create a new auto-animate sheet this.autoAnimateStyleSheet = this.autoAnimateStyleSheet || createStyleSheet(); let animationOptions = this.getAutoAnimateOptions( toSlide ); // Set our starting state fromSlide.dataset.autoAnimate = 'pending'; toSlide.dataset.autoAnimate = 'pending'; // Flag the navigation direction, needed for fragment buildup animationOptions.slideDirection = toSlideIndex > fromSlideIndex ? 'forward' : 'backward'; // If the from-slide is hidden because it has moved outside // the view distance, we need to temporarily show it while // measuring let fromSlideIsHidden = fromSlide.style.display === 'none'; if( fromSlideIsHidden ) fromSlide.style.display = this.Reveal.getConfig().display; // Inject our auto-animate styles for this transition let css = this.getAutoAnimatableElements( fromSlide, toSlide ).map( elements => { return this.autoAnimateElements( elements.from, elements.to, elements.options || {}, animationOptions, autoAnimateCounter++ ); } ); if( fromSlideIsHidden ) fromSlide.style.display = 'none'; // Animate unmatched elements, if enabled if( toSlide.dataset.autoAnimateUnmatched !== 'false' && this.Reveal.getConfig().autoAnimateUnmatched === true ) { // Our default timings for unmatched elements let defaultUnmatchedDuration = animationOptions.duration * 0.8, defaultUnmatchedDelay = animationOptions.duration * 0.2; this.getUnmatchedAutoAnimateElements( toSlide ).forEach( unmatchedElement => { let unmatchedOptions = this.getAutoAnimateOptions( unmatchedElement, animationOptions ); let id = 'unmatched'; // If there is a duration or delay set specifically for this // element our unmatched elements should adhere to those if( unmatchedOptions.duration !== animationOptions.duration || unmatchedOptions.delay !== animationOptions.delay ) { id = 'unmatched-' + autoAnimateCounter++; css.push( `[data-auto-animate="running"] [data-auto-animate-target="${id}"] { transition: opacity ${unmatchedOptions.duration}s ease ${unmatchedOptions.delay}s; }` ); } unmatchedElement.dataset.autoAnimateTarget = id; }, this ); // Our default transition for unmatched elements css.push( `[data-auto-animate="running"] [data-auto-animate-target="unmatched"] { transition: opacity ${defaultUnmatchedDuration}s ease ${defaultUnmatchedDelay}s; }` ); } // Setting the whole chunk of CSS at once is the most // efficient way to do this. Using sheet.insertRule // is multiple factors slower. this.autoAnimateStyleSheet.innerHTML = css.join( '' ); // Start the animation next cycle requestAnimationFrame( () => { if( this.autoAnimateStyleSheet ) { // This forces our newly injected styles to be applied in Firefox getComputedStyle( this.autoAnimateStyleSheet ).fontWeight; toSlide.dataset.autoAnimate = 'running'; } } ); this.Reveal.dispatchEvent({ type: 'autoanimate', data: { fromSlide, toSlide, sheet: this.autoAnimateStyleSheet } }); } } /** * Rolls back all changes that we've made to the DOM so * that as part of animating. */ reset() { // Reset slides queryAll( this.Reveal.getRevealElement(), '[data-auto-animate]:not([data-auto-animate=""])' ).forEach( element => { element.dataset.autoAnimate = ''; } ); // Reset elements queryAll( this.Reveal.getRevealElement(), '[data-auto-animate-target]' ).forEach( element => { delete element.dataset.autoAnimateTarget; } ); // Remove the animation sheet if( this.autoAnimateStyleSheet && this.autoAnimateStyleSheet.parentNode ) { this.autoAnimateStyleSheet.parentNode.removeChild( this.autoAnimateStyleSheet ); this.autoAnimateStyleSheet = null; } } /** * Creates a FLIP animation where the `to` element starts out * in the `from` element position and animates to its original * state. * * @param {HTMLElement} from * @param {HTMLElement} to * @param {Object} elementOptions Options for this element pair * @param {Object} animationOptions Options set at the slide level * @param {String} id Unique ID that we can use to identify this * auto-animate element in the DOM */ autoAnimateElements( from, to, elementOptions, animationOptions, id ) { // 'from' elements are given a data-auto-animate-target with no value, // 'to' elements are are given a data-auto-animate-target with an ID from.dataset.autoAnimateTarget = ''; to.dataset.autoAnimateTarget = id; // Each element may override any of the auto-animate options // like transition easing, duration and delay via data-attributes let options = this.getAutoAnimateOptions( to, animationOptions ); // If we're using a custom element matcher the element options // may contain additional transition overrides if( typeof elementOptions.delay !== 'undefined' ) options.delay = elementOptions.delay; if( typeof elementOptions.duration !== 'undefined' ) options.duration = elementOptions.duration; if( typeof elementOptions.easing !== 'undefined' ) options.easing = elementOptions.easing; let fromProps = this.getAutoAnimatableProperties( 'from', from, elementOptions ), toProps = this.getAutoAnimatableProperties( 'to', to, elementOptions ); if( to.classList.contains( 'fragment' ) ) { // Don't auto-animate the opacity of fragments to avoid // conflicts with fragment animations delete toProps.styles['opacity']; } // If translation and/or scaling are enabled, css transform // the 'to' element so that it matches the position and size // of the 'from' element if( elementOptions.translate !== false || elementOptions.scale !== false ) { let presentationScale = this.Reveal.getScale(); let delta = { x: ( fromProps.x - toProps.x ) / presentationScale, y: ( fromProps.y - toProps.y ) / presentationScale, scaleX: fromProps.width / toProps.width, scaleY: fromProps.height / toProps.height }; // Limit decimal points to avoid 0.0001px blur and stutter delta.x = Math.round( delta.x * 1000 ) / 1000; delta.y = Math.round( delta.y * 1000 ) / 1000; delta.scaleX = Math.round( delta.scaleX * 1000 ) / 1000; delta.scaleX = Math.round( delta.scaleX * 1000 ) / 1000; let translate = elementOptions.translate !== false && ( delta.x !== 0 || delta.y !== 0 ), scale = elementOptions.scale !== false && ( delta.scaleX !== 0 || delta.scaleY !== 0 ); // No need to transform if nothing's changed if( translate || scale ) { let transform = []; if( translate ) transform.push( `translate(${delta.x}px, ${delta.y}px)` ); if( scale ) transform.push( `scale(${delta.scaleX}, ${delta.scaleY})` ); fromProps.styles['transform'] = transform.join( ' ' ); fromProps.styles['transform-origin'] = 'top left'; toProps.styles['transform'] = 'none'; } } // Delete all unchanged 'to' styles for( let propertyName in toProps.styles ) { const toValue = toProps.styles[propertyName]; const fromValue = fromProps.styles[propertyName]; if( toValue === fromValue ) { delete toProps.styles[propertyName]; } else { // If these property values were set via a custom matcher providing // an explicit 'from' and/or 'to' value, we always inject those values. if( toValue.explicitValue === true ) { toProps.styles[propertyName] = toValue.value; } if( fromValue.explicitValue === true ) { fromProps.styles[propertyName] = fromValue.value; } } } let css = ''; let toStyleProperties = Object.keys( toProps.styles ); // Only create animate this element IF at least one style // property has changed if( toStyleProperties.length > 0 ) { // Instantly move to the 'from' state fromProps.styles['transition'] = 'none'; // Animate towards the 'to' state toProps.styles['transition'] = `all ${options.duration}s ${options.easing} ${options.delay}s`; toProps.styles['transition-property'] = toStyleProperties.join( ', ' ); toProps.styles['will-change'] = toStyleProperties.join( ', ' ); // Build up our custom CSS. We need to override inline styles // so we need to make our styles vErY IMPORTANT!1!! let fromCSS = Object.keys( fromProps.styles ).map( propertyName => { return propertyName + ': ' + fromProps.styles[propertyName] + ' !important;'; } ).join( '' ); let toCSS = Object.keys( toProps.styles ).map( propertyName => { return propertyName + ': ' + toProps.styles[propertyName] + ' !important;'; } ).join( '' ); css = '[data-auto-animate-target="'+ id +'"] {'+ fromCSS +'}' + '[data-auto-animate="running"] [data-auto-animate-target="'+ id +'"] {'+ toCSS +'}'; } return css; } /** * Returns the auto-animate options for the given element. * * @param {HTMLElement} element Element to pick up options * from, either a slide or an animation target * @param {Object} [inheritedOptions] Optional set of existing * options */ getAutoAnimateOptions( element, inheritedOptions ) { let options = { easing: this.Reveal.getConfig().autoAnimateEasing, duration: this.Reveal.getConfig().autoAnimateDuration, delay: 0 }; options = extend( options, inheritedOptions ); // Inherit options from parent elements if( element.parentNode ) { let autoAnimatedParent = closest( element.parentNode, '[data-auto-animate-target]' ); if( autoAnimatedParent ) { options = this.getAutoAnimateOptions( autoAnimatedParent, options ); } } if( element.dataset.autoAnimateEasing ) { options.easing = element.dataset.autoAnimateEasing; } if( element.dataset.autoAnimateDuration ) { options.duration = parseFloat( element.dataset.autoAnimateDuration ); } if( element.dataset.autoAnimateDelay ) { options.delay = parseFloat( element.dataset.autoAnimateDelay ); } return options; } /** * Returns an object containing all of the properties * that can be auto-animated for the given element and * their current computed values. * * @param {String} direction 'from' or 'to' */ getAutoAnimatableProperties( direction, element, elementOptions ) { let config = this.Reveal.getConfig(); let properties = { styles: [] }; // Position and size if( elementOptions.translate !== false || elementOptions.scale !== false ) { let bounds; // Custom auto-animate may optionally return a custom tailored // measurement function if( typeof elementOptions.measure === 'function' ) { bounds = elementOptions.measure( element ); } else { if( config.center ) { // More precise, but breaks when used in combination // with zoom for scaling the deck ¯\_(ツ)_/¯ bounds = element.getBoundingClientRect(); } else { let scale = this.Reveal.getScale(); bounds = { x: element.offsetLeft * scale, y: element.offsetTop * scale, width: element.offsetWidth * scale, height: element.offsetHeight * scale }; } } properties.x = bounds.x; properties.y = bounds.y; properties.width = bounds.width; properties.height = bounds.height; } const computedStyles = getComputedStyle( element ); // CSS styles ( elementOptions.styles || config.autoAnimateStyles ).forEach( style => { let value; // `style` is either the property name directly, or an object // definition of a style property if( typeof style === 'string' ) style = { property: style }; if( typeof style.from !== 'undefined' && direction === 'from' ) { value = { value: style.from, explicitValue: true }; } else if( typeof style.to !== 'undefined' && direction === 'to' ) { value = { value: style.to, explicitValue: true }; } else { // Use a unitless value for line-height so that it inherits properly if( style.property === 'line-height' ) { value = parseFloat( computedStyles['line-height'] ) / parseFloat( computedStyles['font-size'] ); } if( isNaN(value) ) { value = computedStyles[style.property]; } } if( value !== '' ) { properties.styles[style.property] = value; } } ); return properties; } /** * Get a list of all element pairs that we can animate * between the given slides. * * @param {HTMLElement} fromSlide * @param {HTMLElement} toSlide * * @return {Array} Each value is an array where [0] is * the element we're animating from and [1] is the * element we're animating to */ getAutoAnimatableElements( fromSlide, toSlide ) { let matcher = typeof this.Reveal.getConfig().autoAnimateMatcher === 'function' ? this.Reveal.getConfig().autoAnimateMatcher : this.getAutoAnimatePairs; let pairs = matcher.call( this, fromSlide, toSlide ); let reserved = []; // Remove duplicate pairs return pairs.filter( ( pair, index ) => { if( reserved.indexOf( pair.to ) === -1 ) { reserved.push( pair.to ); return true; } } ); } /** * Identifies matching elements between slides. * * You can specify a custom matcher function by using * the `autoAnimateMatcher` config option. */ getAutoAnimatePairs( fromSlide, toSlide ) { let pairs = []; const codeNodes = 'pre'; const textNodes = 'h1, h2, h3, h4, h5, h6, p, li'; const mediaNodes = 'img, video, iframe'; // Explicit matches via data-id this.findAutoAnimateMatches( pairs, fromSlide, toSlide, '[data-id]', node => { return node.nodeName + ':::' + node.getAttribute( 'data-id' ); } ); // Text this.findAutoAnimateMatches( pairs, fromSlide, toSlide, textNodes, node => { return node.nodeName + ':::' + node.textContent.trim(); } ); // Media this.findAutoAnimateMatches( pairs, fromSlide, toSlide, mediaNodes, node => { return node.nodeName + ':::' + ( node.getAttribute( 'src' ) || node.getAttribute( 'data-src' ) ); } ); // Code this.findAutoAnimateMatches( pairs, fromSlide, toSlide, codeNodes, node => { return node.nodeName + ':::' + node.textContent.trim(); } ); pairs.forEach( pair => { // Disable scale transformations on text nodes, we transition // each individual text property instead if( matches( pair.from, textNodes ) ) { pair.options = { scale: false }; } // Animate individual lines of code else if( matches( pair.from, codeNodes ) ) { // Transition the code block's width and height instead of scaling // to prevent its content from being squished pair.options = { scale: false, styles: [ 'width', 'height' ] }; // Lines of code this.findAutoAnimateMatches( pairs, pair.from, pair.to, '.hljs .hljs-ln-code', node => { return node.textContent; }, { scale: false, styles: [], measure: this.getLocalBoundingBox.bind( this ) } ); // Line numbers this.findAutoAnimateMatches( pairs, pair.from, pair.to, '.hljs .hljs-ln-numbers[data-line-number]', node => { return node.getAttribute( 'data-line-number' ); }, { scale: false, styles: [ 'width' ], measure: this.getLocalBoundingBox.bind( this ) } ); } }, this ); return pairs; } /** * Helper method which returns a bounding box based on * the given elements offset coordinates. * * @param {HTMLElement} element * @return {Object} x, y, width, height */ getLocalBoundingBox( element ) { const presentationScale = this.Reveal.getScale(); return { x: Math.round( ( element.offsetLeft * presentationScale ) * 100 ) / 100, y: Math.round( ( element.offsetTop * presentationScale ) * 100 ) / 100, width: Math.round( ( element.offsetWidth * presentationScale ) * 100 ) / 100, height: Math.round( ( element.offsetHeight * presentationScale ) * 100 ) / 100 }; } /** * Finds matching elements between two slides. * * @param {Array} pairs List of pairs to push matches to * @param {HTMLElement} fromScope Scope within the from element exists * @param {HTMLElement} toScope Scope within the to element exists * @param {String} selector CSS selector of the element to match * @param {Function} serializer A function that accepts an element and returns * a stringified ID based on its contents * @param {Object} animationOptions Optional config options for this pair */ findAutoAnimateMatches( pairs, fromScope, toScope, selector, serializer, animationOptions ) { let fromMatches = {}; let toMatches = {}; [].slice.call( fromScope.querySelectorAll( selector ) ).forEach( ( element, i ) => { const key = serializer( element ); if( typeof key === 'string' && key.length ) { fromMatches[key] = fromMatches[key] || []; fromMatches[key].push( element ); } } ); [].slice.call( toScope.querySelectorAll( selector ) ).forEach( ( element, i ) => { const key = serializer( element ); toMatches[key] = toMatches[key] || []; toMatches[key].push( element ); let fromElement; // Retrieve the 'from' element if( fromMatches[key] ) { const primaryIndex = toMatches[key].length - 1; const secondaryIndex = fromMatches[key].length - 1; // If there are multiple identical from elements, retrieve // the one at the same index as our to-element. if( fromMatches[key][ primaryIndex ] ) { fromElement = fromMatches[key][ primaryIndex ]; fromMatches[key][ primaryIndex ] = null; } // If there are no matching from-elements at the same index, // use the last one. else if( fromMatches[key][ secondaryIndex ] ) { fromElement = fromMatches[key][ secondaryIndex ]; fromMatches[key][ secondaryIndex ] = null; } } // If we've got a matching pair, push it to the list of pairs if( fromElement ) { pairs.push({ from: fromElement, to: element, options: animationOptions }); } } ); } /** * Returns a all elements within the given scope that should * be considered unmatched in an auto-animate transition. If * fading of unmatched elements is turned on, these elements * will fade when going between auto-animate slides. * * Note that parents of auto-animate targets are NOT considered * unmatched since fading them would break the auto-animation. * * @param {HTMLElement} rootElement * @return {Array} */ getUnmatchedAutoAnimateElements( rootElement ) { return [].slice.call( rootElement.children ).reduce( ( result, element ) => { const containsAnimatedElements = element.querySelector( '[data-auto-animate-target]' ); // The element is unmatched if // - It is not an auto-animate target // - It does not contain any auto-animate targets if( !element.hasAttribute( 'data-auto-animate-target' ) && !containsAnimatedElements ) { result.push( element ); } if( element.querySelector( '[data-auto-animate-target]' ) ) { result = result.concat( this.getUnmatchedAutoAnimateElements( element ) ); } return result; }, [] ); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/pointer.js
js/controllers/pointer.js
/** * Handles hiding of the pointer/cursor when inactive. */ export default class Pointer { constructor( Reveal ) { this.Reveal = Reveal; // Throttles mouse wheel navigation this.lastMouseWheelStep = 0; // Is the mouse pointer currently hidden from view this.cursorHidden = false; // Timeout used to determine when the cursor is inactive this.cursorInactiveTimeout = 0; this.onDocumentCursorActive = this.onDocumentCursorActive.bind( this ); this.onDocumentMouseScroll = this.onDocumentMouseScroll.bind( this ); } /** * Called when the reveal.js config is updated. */ configure( config, oldConfig ) { if( config.mouseWheel ) { document.addEventListener( 'wheel', this.onDocumentMouseScroll, false ); } else { document.removeEventListener( 'wheel', this.onDocumentMouseScroll, false ); } // Auto-hide the mouse pointer when its inactive if( config.hideInactiveCursor ) { document.addEventListener( 'mousemove', this.onDocumentCursorActive, false ); document.addEventListener( 'mousedown', this.onDocumentCursorActive, false ); } else { this.showCursor(); document.removeEventListener( 'mousemove', this.onDocumentCursorActive, false ); document.removeEventListener( 'mousedown', this.onDocumentCursorActive, false ); } } /** * Shows the mouse pointer after it has been hidden with * #hideCursor. */ showCursor() { if( this.cursorHidden ) { this.cursorHidden = false; this.Reveal.getRevealElement().style.cursor = ''; } } /** * Hides the mouse pointer when it's on top of the .reveal * container. */ hideCursor() { if( this.cursorHidden === false ) { this.cursorHidden = true; this.Reveal.getRevealElement().style.cursor = 'none'; } } destroy() { this.showCursor(); document.removeEventListener( 'wheel', this.onDocumentMouseScroll, false ); document.removeEventListener( 'mousemove', this.onDocumentCursorActive, false ); document.removeEventListener( 'mousedown', this.onDocumentCursorActive, false ); } /** * Called whenever there is mouse input at the document level * to determine if the cursor is active or not. * * @param {object} event */ onDocumentCursorActive( event ) { this.showCursor(); clearTimeout( this.cursorInactiveTimeout ); this.cursorInactiveTimeout = setTimeout( this.hideCursor.bind( this ), this.Reveal.getConfig().hideCursorTime ); } /** * Handles mouse wheel scrolling, throttled to avoid skipping * multiple slides. * * @param {object} event */ onDocumentMouseScroll( event ) { if( Date.now() - this.lastMouseWheelStep > 1000 ) { this.lastMouseWheelStep = Date.now(); let delta = event.detail || -event.wheelDelta; if( delta > 0 ) { this.Reveal.next(); } else if( delta < 0 ) { this.Reveal.prev(); } } } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/focus.js
js/controllers/focus.js
import { closest } from '../utils/util.js' /** * Manages focus when a presentation is embedded. This * helps us only capture keyboard from the presentation * a user is currently interacting with in a page where * multiple presentations are embedded. */ const STATE_FOCUS = 'focus'; const STATE_BLUR = 'blur'; export default class Focus { constructor( Reveal ) { this.Reveal = Reveal; this.onRevealPointerDown = this.onRevealPointerDown.bind( this ); this.onDocumentPointerDown = this.onDocumentPointerDown.bind( this ); } /** * Called when the reveal.js config is updated. */ configure( config, oldConfig ) { if( config.embedded ) { this.blur(); } else { this.focus(); this.unbind(); } } bind() { if( this.Reveal.getConfig().embedded ) { this.Reveal.getRevealElement().addEventListener( 'pointerdown', this.onRevealPointerDown, false ); } } unbind() { this.Reveal.getRevealElement().removeEventListener( 'pointerdown', this.onRevealPointerDown, false ); document.removeEventListener( 'pointerdown', this.onDocumentPointerDown, false ); } focus() { if( this.state !== STATE_FOCUS ) { this.Reveal.getRevealElement().classList.add( 'focused' ); document.addEventListener( 'pointerdown', this.onDocumentPointerDown, false ); } this.state = STATE_FOCUS; } blur() { if( this.state !== STATE_BLUR ) { this.Reveal.getRevealElement().classList.remove( 'focused' ); document.removeEventListener( 'pointerdown', this.onDocumentPointerDown, false ); } this.state = STATE_BLUR; } isFocused() { return this.state === STATE_FOCUS; } destroy() { this.Reveal.getRevealElement().classList.remove( 'focused' ); } onRevealPointerDown( event ) { this.focus(); } onDocumentPointerDown( event ) { let revealElement = closest( event.target, '.reveal' ); if( !revealElement || revealElement !== this.Reveal.getRevealElement() ) { this.blur(); } } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/overlay.js
js/controllers/overlay.js
/** * Handles the display of reveal.js' overlay elements used * to preview iframes, images & videos. */ export default class Overlay { constructor( Reveal ) { this.Reveal = Reveal; this.onSlidesClicked = this.onSlidesClicked.bind( this ); this.iframeTriggerSelector = null; this.mediaTriggerSelector = '[data-preview-image], [data-preview-video]'; this.stateProps = ['previewIframe', 'previewImage', 'previewVideo', 'previewFit']; this.state = {}; } update() { // Enable link previews globally if( this.Reveal.getConfig().previewLinks ) { this.iframeTriggerSelector = 'a[href]:not([data-preview-link=false]), [data-preview-link]:not(a):not([data-preview-link=false])'; } // Enable link previews for individual elements else { this.iframeTriggerSelector = '[data-preview-link]:not([data-preview-link=false])'; } const hasLinkPreviews = this.Reveal.getSlidesElement().querySelectorAll( this.iframeTriggerSelector ).length > 0; const hasMediaPreviews = this.Reveal.getSlidesElement().querySelectorAll( this.mediaTriggerSelector ).length > 0; // Only add the listener when there are previewable elements in the slides if( hasLinkPreviews || hasMediaPreviews ) { this.Reveal.getSlidesElement().addEventListener( 'click', this.onSlidesClicked, false ); } else { this.Reveal.getSlidesElement().removeEventListener( 'click', this.onSlidesClicked, false ); } } createOverlay( className ) { this.dom = document.createElement( 'div' ); this.dom.classList.add( 'r-overlay' ); this.dom.classList.add( className ); this.viewport = document.createElement( 'div' ); this.viewport.classList.add( 'r-overlay-viewport' ); this.dom.appendChild( this.viewport ); this.Reveal.getRevealElement().appendChild( this.dom ); } /** * Opens a lightbox that previews the target URL. * * @param {string} url - url for lightbox iframe src */ previewIframe( url ) { this.close(); this.state = { previewIframe: url }; this.createOverlay( 'r-overlay-preview' ); this.dom.dataset.state = 'loading'; this.viewport.innerHTML = `<header class="r-overlay-header"> <a class="r-overlay-header-button r-overlay-external" href="${url}" target="_blank"><span class="icon"></span></a> <button class="r-overlay-header-button r-overlay-close"><span class="icon"></span></button> </header> <div class="r-overlay-spinner"></div> <div class="r-overlay-content"> <iframe src="${url}"></iframe> <small class="r-overlay-content-inner"> <span class="r-overlay-error x-frame-error">Unable to load iframe. This is likely due to the site's policy (x-frame-options).</span> </small> </div>`; this.dom.querySelector( 'iframe' ).addEventListener( 'load', event => { this.dom.dataset.state = 'loaded'; }, false ); this.dom.querySelector( '.r-overlay-close' ).addEventListener( 'click', event => { this.close(); event.preventDefault(); }, false ); this.dom.querySelector( '.r-overlay-external' ).addEventListener( 'click', event => { this.close(); }, false ); this.Reveal.dispatchEvent({ type: 'previewiframe', data: { url } }); } /** * Opens a lightbox window that provides a larger view of the * given image/video. * * @param {string} url - url to the image/video to preview * @param {image|video} mediaType * @param {string} [fitMode] - the fit mode to use for the preview */ previewMedia( url, mediaType, fitMode ) { if( mediaType !== 'image' && mediaType !== 'video' ) { console.warn( 'Please specify a valid media type to preview (image|video)' ); return; } this.close(); fitMode = fitMode || 'scale-down'; this.createOverlay( 'r-overlay-preview' ); this.dom.dataset.state = 'loading'; this.dom.dataset.previewFit = fitMode; this.viewport.innerHTML = `<header class="r-overlay-header"> <button class="r-overlay-header-button r-overlay-close">Esc <span class="icon"></span></button> </header> <div class="r-overlay-spinner"></div> <div class="r-overlay-content"></div>`; const contentElement = this.dom.querySelector( '.r-overlay-content' ); if( mediaType === 'image' ) { this.state = { previewImage: url, previewFit: fitMode } const img = document.createElement( 'img', {} ); img.src = url; contentElement.appendChild( img ); img.addEventListener( 'load', () => { this.dom.dataset.state = 'loaded'; }, false ); img.addEventListener( 'error', () => { this.dom.dataset.state = 'error'; contentElement.innerHTML = `<span class="r-overlay-error">Unable to load image.</span>` }, false ); // Hide image overlays when clicking outside the overlay this.dom.style.cursor = 'zoom-out'; this.dom.addEventListener( 'click', ( event ) => { this.close(); }, false ); this.Reveal.dispatchEvent({ type: 'previewimage', data: { url } }); } else if( mediaType === 'video' ) { this.state = { previewVideo: url, previewFit: fitMode } const video = document.createElement( 'video' ); video.autoplay = this.dom.dataset.previewAutoplay === 'false' ? false : true; video.controls = this.dom.dataset.previewControls === 'false' ? false : true; video.loop = this.dom.dataset.previewLoop === 'true' ? true : false; video.muted = this.dom.dataset.previewMuted === 'true' ? true : false; video.playsInline = true; video.src = url; contentElement.appendChild( video ); video.addEventListener( 'loadeddata', () => { this.dom.dataset.state = 'loaded'; }, false ); video.addEventListener( 'error', () => { this.dom.dataset.state = 'error'; contentElement.innerHTML = `<span class="r-overlay-error">Unable to load video.</span>`; }, false ); this.Reveal.dispatchEvent({ type: 'previewvideo', data: { url } }); } else { throw new Error( 'Please specify a valid media type to preview' ); } this.dom.querySelector( '.r-overlay-close' ).addEventListener( 'click', ( event ) => { this.close(); event.preventDefault(); }, false ); } previewImage( url, fitMode ) { this.previewMedia( url, 'image', fitMode ); } previewVideo( url, fitMode ) { this.previewMedia( url, 'video', fitMode ); } /** * Open or close help overlay window. * * @param {Boolean} [override] Flag which overrides the * toggle logic and forcibly sets the desired state. True means * help is open, false means it's closed. */ toggleHelp( override ) { if( typeof override === 'boolean' ) { override ? this.showHelp() : this.close(); } else { if( this.dom ) { this.close(); } else { this.showHelp(); } } } /** * Opens an overlay window with help material. */ showHelp() { if( this.Reveal.getConfig().help ) { this.close(); this.createOverlay( 'r-overlay-help' ); let html = '<p class="title">Keyboard Shortcuts</p>'; let shortcuts = this.Reveal.keyboard.getShortcuts(), bindings = this.Reveal.keyboard.getBindings(); html += '<table><th>KEY</th><th>ACTION</th>'; for( let key in shortcuts ) { html += `<tr><td>${key}</td><td>${shortcuts[ key ]}</td></tr>`; } // Add custom key bindings that have associated descriptions for( let binding in bindings ) { if( bindings[binding].key && bindings[binding].description ) { html += `<tr><td>${bindings[binding].key}</td><td>${bindings[binding].description}</td></tr>`; } } html += '</table>'; this.viewport.innerHTML = ` <header class="r-overlay-header"> <button class="r-overlay-header-button r-overlay-close">Esc <span class="icon"></span></button> </header> <div class="r-overlay-content"> <div class="r-overlay-help-content">${html}</div> </div> `; this.dom.querySelector( '.r-overlay-close' ).addEventListener( 'click', event => { this.close(); event.preventDefault(); }, false ); this.Reveal.dispatchEvent({ type: 'showhelp' }); } } isOpen() { return !!this.dom; } /** * Closes any currently open overlay. */ close() { if( this.dom ) { this.dom.remove(); this.dom = null; this.state = {}; this.Reveal.dispatchEvent({ type: 'closeoverlay' }); return true; } return false; } getState() { return this.state; } setState( state ) { // Ignore the incoming state if none of the preview related // props have changed if( this.stateProps.every( key => this.state[ key ] === state[ key ] ) ) { return; } if( state.previewIframe ) { this.previewIframe( state.previewIframe ); } else if( state.previewImage ) { this.previewImage( state.previewImage, state.previewFit ); } else if( state.previewVideo ) { this.previewVideo( state.previewVideo, state.previewFit ); } else { this.close(); } } onSlidesClicked( event ) { const target = event.target; const linkTarget = target.closest( this.iframeTriggerSelector ); const mediaTarget = target.closest( this.mediaTriggerSelector ); // Was an iframe lightbox trigger clicked? if( linkTarget ) { if( event.metaKey || event.shiftKey || event.altKey ) { // Let the browser handle meta keys naturally so users can cmd+click return; } let url = linkTarget.getAttribute( 'href' ) || linkTarget.getAttribute( 'data-preview-link' ); if( url ) { this.previewIframe( url ); event.preventDefault(); } } // Was a media lightbox trigger clicked? else if( mediaTarget ) { if( mediaTarget.hasAttribute( 'data-preview-image' ) ) { let url = mediaTarget.dataset.previewImage || mediaTarget.getAttribute( 'src' ); if( url ) { this.previewImage( url, mediaTarget.dataset.previewFit ); event.preventDefault(); } } else if( mediaTarget.hasAttribute( 'data-preview-video' ) ) { let url = mediaTarget.dataset.previewVideo || mediaTarget.getAttribute( 'src' ); if( !url ) { let source = mediaTarget.querySelector( 'source' ); if( source ) { url = source.getAttribute( 'src' ); } } if( url ) { this.previewVideo( url, mediaTarget.dataset.previewFit ); event.preventDefault(); } } } } destroy() { this.close(); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/backgrounds.js
js/controllers/backgrounds.js
import { queryAll } from '../utils/util.js' import { colorToRgb, colorBrightness } from '../utils/color.js' /** * Creates and updates slide backgrounds. */ export default class Backgrounds { constructor( Reveal ) { this.Reveal = Reveal; } render() { this.element = document.createElement( 'div' ); this.element.className = 'backgrounds'; this.Reveal.getRevealElement().appendChild( this.element ); } /** * Creates the slide background elements and appends them * to the background container. One element is created per * slide no matter if the given slide has visible background. */ create() { // Clear prior backgrounds this.element.innerHTML = ''; this.element.classList.add( 'no-transition' ); // Iterate over all horizontal slides this.Reveal.getHorizontalSlides().forEach( slideh => { let backgroundStack = this.createBackground( slideh, this.element ); // Iterate over all vertical slides queryAll( slideh, 'section' ).forEach( slidev => { this.createBackground( slidev, backgroundStack ); backgroundStack.classList.add( 'stack' ); } ); } ); // Add parallax background if specified if( this.Reveal.getConfig().parallaxBackgroundImage ) { this.element.style.backgroundImage = 'url("' + this.Reveal.getConfig().parallaxBackgroundImage + '")'; this.element.style.backgroundSize = this.Reveal.getConfig().parallaxBackgroundSize; this.element.style.backgroundRepeat = this.Reveal.getConfig().parallaxBackgroundRepeat; this.element.style.backgroundPosition = this.Reveal.getConfig().parallaxBackgroundPosition; // Make sure the below properties are set on the element - these properties are // needed for proper transitions to be set on the element via CSS. To remove // annoying background slide-in effect when the presentation starts, apply // these properties after short time delay setTimeout( () => { this.Reveal.getRevealElement().classList.add( 'has-parallax-background' ); }, 1 ); } else { this.element.style.backgroundImage = ''; this.Reveal.getRevealElement().classList.remove( 'has-parallax-background' ); } } /** * Creates a background for the given slide. * * @param {HTMLElement} slide * @param {HTMLElement} container The element that the background * should be appended to * @return {HTMLElement} New background div */ createBackground( slide, container ) { // Main slide background element let element = document.createElement( 'div' ); element.className = 'slide-background ' + slide.className.replace( /present|past|future/, '' ); // Inner background element that wraps images/videos/iframes let contentElement = document.createElement( 'div' ); contentElement.className = 'slide-background-content'; element.appendChild( contentElement ); container.appendChild( element ); slide.slideBackgroundElement = element; slide.slideBackgroundContentElement = contentElement; // Syncs the background to reflect all current background settings this.sync( slide ); return element; } /** * Renders all of the visual properties of a slide background * based on the various background attributes. * * @param {HTMLElement} slide */ sync( slide ) { const element = slide.slideBackgroundElement, contentElement = slide.slideBackgroundContentElement; const data = { background: slide.getAttribute( 'data-background' ), backgroundSize: slide.getAttribute( 'data-background-size' ), backgroundImage: slide.getAttribute( 'data-background-image' ), backgroundVideo: slide.getAttribute( 'data-background-video' ), backgroundIframe: slide.getAttribute( 'data-background-iframe' ), backgroundColor: slide.getAttribute( 'data-background-color' ), backgroundGradient: slide.getAttribute( 'data-background-gradient' ), backgroundRepeat: slide.getAttribute( 'data-background-repeat' ), backgroundPosition: slide.getAttribute( 'data-background-position' ), backgroundTransition: slide.getAttribute( 'data-background-transition' ), backgroundOpacity: slide.getAttribute( 'data-background-opacity' ), }; const dataPreload = slide.hasAttribute( 'data-preload' ); // Reset the prior background state in case this is not the // initial sync slide.classList.remove( 'has-dark-background' ); slide.classList.remove( 'has-light-background' ); element.removeAttribute( 'data-loaded' ); element.removeAttribute( 'data-background-hash' ); element.removeAttribute( 'data-background-size' ); element.removeAttribute( 'data-background-transition' ); element.style.backgroundColor = ''; contentElement.style.backgroundSize = ''; contentElement.style.backgroundRepeat = ''; contentElement.style.backgroundPosition = ''; contentElement.style.backgroundImage = ''; contentElement.style.opacity = ''; contentElement.innerHTML = ''; if( data.background ) { // Auto-wrap image urls in url(...) if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp|webp)([?#\s]|$)/gi.test( data.background ) ) { slide.setAttribute( 'data-background-image', data.background ); } else { element.style.background = data.background; } } // Create a hash for this combination of background settings. // This is used to determine when two slide backgrounds are // the same. if( data.background || data.backgroundColor || data.backgroundGradient || data.backgroundImage || data.backgroundVideo || data.backgroundIframe ) { element.setAttribute( 'data-background-hash', data.background + data.backgroundSize + data.backgroundImage + data.backgroundVideo + data.backgroundIframe + data.backgroundColor + data.backgroundGradient + data.backgroundRepeat + data.backgroundPosition + data.backgroundTransition + data.backgroundOpacity ); } // Additional and optional background properties if( data.backgroundSize ) element.setAttribute( 'data-background-size', data.backgroundSize ); if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor; if( data.backgroundGradient ) element.style.backgroundImage = data.backgroundGradient; if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition ); if( dataPreload ) element.setAttribute( 'data-preload', '' ); // Background image options are set on the content wrapper if( data.backgroundSize ) contentElement.style.backgroundSize = data.backgroundSize; if( data.backgroundRepeat ) contentElement.style.backgroundRepeat = data.backgroundRepeat; if( data.backgroundPosition ) contentElement.style.backgroundPosition = data.backgroundPosition; if( data.backgroundOpacity ) contentElement.style.opacity = data.backgroundOpacity; const contrastClass = this.getContrastClass( slide ); if( typeof contrastClass === 'string' ) { slide.classList.add( contrastClass ); } } /** * Returns a class name that can be applied to a slide to indicate * if it has a light or dark background. * * @param {*} slide * * @returns {string|null} */ getContrastClass( slide ) { const element = slide.slideBackgroundElement; // If this slide has a background color, we add a class that // signals if it is light or dark. If the slide has no background // color, no class will be added let contrastColor = slide.getAttribute( 'data-background-color' ); // If no bg color was found, or it cannot be converted by colorToRgb, check the computed background if( !contrastColor || !colorToRgb( contrastColor ) ) { let computedBackgroundStyle = window.getComputedStyle( element ); if( computedBackgroundStyle && computedBackgroundStyle.backgroundColor ) { contrastColor = computedBackgroundStyle.backgroundColor; } } if( contrastColor ) { const rgb = colorToRgb( contrastColor ); // Ignore fully transparent backgrounds. Some browsers return // rgba(0,0,0,0) when reading the computed background color of // an element with no background if( rgb && rgb.a !== 0 ) { if( colorBrightness( contrastColor ) < 128 ) { return 'has-dark-background'; } else { return 'has-light-background'; } } } return null; } /** * Bubble the 'has-light-background'/'has-dark-background' classes. */ bubbleSlideContrastClassToElement( slide, target ) { [ 'has-light-background', 'has-dark-background' ].forEach( classToBubble => { if( slide.classList.contains( classToBubble ) ) { target.classList.add( classToBubble ); } else { target.classList.remove( classToBubble ); } }, this ); } /** * Updates the background elements to reflect the current * slide. * * @param {boolean} includeAll If true, the backgrounds of * all vertical slides (not just the present) will be updated. */ update( includeAll = false ) { let config = this.Reveal.getConfig(); let currentSlide = this.Reveal.getCurrentSlide(); let indices = this.Reveal.getIndices(); let currentBackground = null; // Reverse past/future classes when in RTL mode let horizontalPast = config.rtl ? 'future' : 'past', horizontalFuture = config.rtl ? 'past' : 'future'; // Update the classes of all backgrounds to match the // states of their slides (past/present/future) Array.from( this.element.childNodes ).forEach( ( backgroundh, h ) => { backgroundh.classList.remove( 'past', 'present', 'future' ); if( h < indices.h ) { backgroundh.classList.add( horizontalPast ); } else if ( h > indices.h ) { backgroundh.classList.add( horizontalFuture ); } else { backgroundh.classList.add( 'present' ); // Store a reference to the current background element currentBackground = backgroundh; } if( includeAll || h === indices.h ) { queryAll( backgroundh, '.slide-background' ).forEach( ( backgroundv, v ) => { backgroundv.classList.remove( 'past', 'present', 'future' ); const indexv = typeof indices.v === 'number' ? indices.v : 0; if( v < indexv ) { backgroundv.classList.add( 'past' ); } else if ( v > indexv ) { backgroundv.classList.add( 'future' ); } else { backgroundv.classList.add( 'present' ); // Only if this is the present horizontal and vertical slide if( h === indices.h ) currentBackground = backgroundv; } } ); } } ); // The previous background may refer to a DOM element that has // been removed after a presentation is synced & bgs are recreated if( this.previousBackground && !this.previousBackground.closest( 'body' ) ) { this.previousBackground = null; } if( currentBackground && this.previousBackground ) { // Don't transition between identical backgrounds. This // prevents unwanted flicker. let previousBackgroundHash = this.previousBackground.getAttribute( 'data-background-hash' ); let currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' ); if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== this.previousBackground ) { this.element.classList.add( 'no-transition' ); // If multiple slides have the same background video, carry // the <video> element forward so that it plays continuously // across multiple slides const currentVideo = currentBackground.querySelector( 'video' ); const previousVideo = this.previousBackground.querySelector( 'video' ); if( currentVideo && previousVideo ) { const currentVideoParent = currentVideo.parentNode; const previousVideoParent = previousVideo.parentNode; // Swap the two videos previousVideoParent.appendChild( currentVideo ); currentVideoParent.appendChild( previousVideo ); } } } const backgroundChanged = currentBackground !== this.previousBackground; // Stop content inside of previous backgrounds if( backgroundChanged && this.previousBackground ) { this.Reveal.slideContent.stopEmbeddedContent( this.previousBackground, { unloadIframes: !this.Reveal.slideContent.shouldPreload( this.previousBackground ) } ); } // Start content in the current background if( backgroundChanged && currentBackground ) { this.Reveal.slideContent.startEmbeddedContent( currentBackground ); let currentBackgroundContent = currentBackground.querySelector( '.slide-background-content' ); if( currentBackgroundContent ) { let backgroundImageURL = currentBackgroundContent.style.backgroundImage || ''; // Restart GIFs (doesn't work in Firefox) if( /\.gif/i.test( backgroundImageURL ) ) { currentBackgroundContent.style.backgroundImage = ''; window.getComputedStyle( currentBackgroundContent ).opacity; currentBackgroundContent.style.backgroundImage = backgroundImageURL; } } this.previousBackground = currentBackground; } // If there's a background brightness flag for this slide, // bubble it to the .reveal container if( currentSlide ) { this.bubbleSlideContrastClassToElement( currentSlide, this.Reveal.getRevealElement() ); } // Allow the first background to apply without transition setTimeout( () => { this.element.classList.remove( 'no-transition' ); }, 10 ); } /** * Updates the position of the parallax background based * on the current slide index. */ updateParallax() { let indices = this.Reveal.getIndices(); if( this.Reveal.getConfig().parallaxBackgroundImage ) { let horizontalSlides = this.Reveal.getHorizontalSlides(), verticalSlides = this.Reveal.getVerticalSlides(); let backgroundSize = this.element.style.backgroundSize.split( ' ' ), backgroundWidth, backgroundHeight; if( backgroundSize.length === 1 ) { backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 ); } else { backgroundWidth = parseInt( backgroundSize[0], 10 ); backgroundHeight = parseInt( backgroundSize[1], 10 ); } let slideWidth = this.element.offsetWidth, horizontalSlideCount = horizontalSlides.length, horizontalOffsetMultiplier, horizontalOffset; if( typeof this.Reveal.getConfig().parallaxBackgroundHorizontal === 'number' ) { horizontalOffsetMultiplier = this.Reveal.getConfig().parallaxBackgroundHorizontal; } else { horizontalOffsetMultiplier = horizontalSlideCount > 1 ? ( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) : 0; } horizontalOffset = horizontalOffsetMultiplier * indices.h * -1; let slideHeight = this.element.offsetHeight, verticalSlideCount = verticalSlides.length, verticalOffsetMultiplier, verticalOffset; if( typeof this.Reveal.getConfig().parallaxBackgroundVertical === 'number' ) { verticalOffsetMultiplier = this.Reveal.getConfig().parallaxBackgroundVertical; } else { verticalOffsetMultiplier = ( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 ); } verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indices.v : 0; this.element.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px'; } } destroy() { this.element.remove(); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/location.js
js/controllers/location.js
/** * Reads and writes the URL based on reveal.js' current state. */ export default class Location { // The minimum number of milliseconds that must pass between // calls to history.replaceState MAX_REPLACE_STATE_FREQUENCY = 1000 constructor( Reveal ) { this.Reveal = Reveal; // Delays updates to the URL due to a Chrome thumbnailer bug this.writeURLTimeout = 0; this.replaceStateTimestamp = 0; this.onWindowHashChange = this.onWindowHashChange.bind( this ); } bind() { window.addEventListener( 'hashchange', this.onWindowHashChange, false ); } unbind() { window.removeEventListener( 'hashchange', this.onWindowHashChange, false ); } /** * Returns the slide indices for the given hash link. * * @param {string} [hash] the hash string that we want to * find the indices for * * @returns slide indices or null */ getIndicesFromHash( hash=window.location.hash, options={} ) { // Attempt to parse the hash as either an index or name let name = hash.replace( /^#\/?/, '' ); let bits = name.split( '/' ); // If the first bit is not fully numeric and there is a name we // can assume that this is a named link if( !/^[0-9]*$/.test( bits[0] ) && name.length ) { let slide; let f; // Parse named links with fragments (#/named-link/2) if( /\/[-\d]+$/g.test( name ) ) { f = parseInt( name.split( '/' ).pop(), 10 ); f = isNaN(f) ? undefined : f; name = name.split( '/' ).shift(); } // Ensure the named link is a valid HTML id or data-id attribute try { const decodedName = decodeURIComponent( name ); slide = ( document.getElementById( decodedName ) || document.querySelector( `[data-id="${decodedName}"]` ) ).closest('.slides section'); } catch ( error ) { } if( slide ) { return { ...this.Reveal.getIndices( slide ), f }; } } else { const config = this.Reveal.getConfig(); let hashIndexBase = config.hashOneBasedIndex || options.oneBasedIndex ? 1 : 0; // Read the index components of the hash let h = ( parseInt( bits[0], 10 ) - hashIndexBase ) || 0, v = ( parseInt( bits[1], 10 ) - hashIndexBase ) || 0, f; if( config.fragmentInURL ) { f = parseInt( bits[2], 10 ); if( isNaN( f ) ) { f = undefined; } } return { h, v, f }; } // The hash couldn't be parsed or no matching named link was found return null } /** * Reads the current URL (hash) and navigates accordingly. */ readURL() { const currentIndices = this.Reveal.getIndices(); const newIndices = this.getIndicesFromHash(); if( newIndices ) { if( ( newIndices.h !== currentIndices.h || newIndices.v !== currentIndices.v || newIndices.f !== undefined ) ) { this.Reveal.slide( newIndices.h, newIndices.v, newIndices.f ); } } // If no new indices are available, we're trying to navigate to // a slide hash that does not exist else { this.Reveal.slide( currentIndices.h || 0, currentIndices.v || 0 ); } } /** * Updates the page URL (hash) to reflect the current * state. * * @param {number} delay The time in ms to wait before * writing the hash */ writeURL( delay ) { let config = this.Reveal.getConfig(); let currentSlide = this.Reveal.getCurrentSlide(); // Make sure there's never more than one timeout running clearTimeout( this.writeURLTimeout ); // If a delay is specified, timeout this call if( typeof delay === 'number' ) { this.writeURLTimeout = setTimeout( this.writeURL, delay ); } else if( currentSlide ) { let hash = this.getHash(); // If we're configured to push to history OR the history // API is not available. if( config.history ) { window.location.hash = hash; } // If we're configured to reflect the current slide in the // URL without pushing to history. else if( config.hash ) { // If the hash is empty, don't add it to the URL if( hash === '/' ) { this.debouncedReplaceState( window.location.pathname + window.location.search ); } else { this.debouncedReplaceState( '#' + hash ); } } // UPDATE: The below nuking of all hash changes breaks // anchors on pages where reveal.js is running. Removed // in 4.0. Why was it here in the first place? ¯\_(ツ)_/¯ // // If history and hash are both disabled, a hash may still // be added to the URL by clicking on a href with a hash // target. Counter this by always removing the hash. // else { // window.history.replaceState( null, null, window.location.pathname + window.location.search ); // } } } replaceState( url ) { window.history.replaceState( null, null, url ); this.replaceStateTimestamp = Date.now(); } debouncedReplaceState( url ) { clearTimeout( this.replaceStateTimeout ); if( Date.now() - this.replaceStateTimestamp > this.MAX_REPLACE_STATE_FREQUENCY ) { this.replaceState( url ); } else { this.replaceStateTimeout = setTimeout( () => this.replaceState( url ), this.MAX_REPLACE_STATE_FREQUENCY ); } } /** * Return a hash URL that will resolve to the given slide location. * * @param {HTMLElement} [slide=currentSlide] The slide to link to */ getHash( slide ) { let url = '/'; // Attempt to create a named link based on the slide's ID let s = slide || this.Reveal.getCurrentSlide(); let id = s ? s.getAttribute( 'id' ) : null; if( id ) { id = encodeURIComponent( id ); } let index = this.Reveal.getIndices( slide ); if( !this.Reveal.getConfig().fragmentInURL ) { index.f = undefined; } // If the current slide has an ID, use that as a named link, // but we don't support named links with a fragment index if( typeof id === 'string' && id.length ) { url = '/' + id; // If there is also a fragment, append that at the end // of the named link, like: #/named-link/2 if( index.f >= 0 ) url += '/' + index.f; } // Otherwise use the /h/v index else { let hashIndexBase = this.Reveal.getConfig().hashOneBasedIndex ? 1 : 0; if( index.h > 0 || index.v > 0 || index.f >= 0 ) url += index.h + hashIndexBase; if( index.v > 0 || index.f >= 0 ) url += '/' + (index.v + hashIndexBase ); if( index.f >= 0 ) url += '/' + index.f; } return url; } /** * Handler for the window level 'hashchange' event. * * @param {object} [event] */ onWindowHashChange( event ) { this.readURL(); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/printview.js
js/controllers/printview.js
import { SLIDES_SELECTOR } from '../utils/constants.js' import { queryAll, createStyleSheet } from '../utils/util.js' /** * Setups up our presentation for printing/exporting to PDF. */ export default class PrintView { constructor( Reveal ) { this.Reveal = Reveal; } /** * Configures the presentation for printing to a static * PDF. */ async activate() { const config = this.Reveal.getConfig(); const slides = queryAll( this.Reveal.getRevealElement(), SLIDES_SELECTOR ) // Compute slide numbers now, before we start duplicating slides const injectPageNumbers = config.slideNumber && /all|print/i.test( config.showSlideNumber ); const slideSize = this.Reveal.getComputedSlideSize( window.innerWidth, window.innerHeight ); // Dimensions of the PDF pages const pageWidth = Math.floor( slideSize.width * ( 1 + config.margin ) ), pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) ); // Dimensions of slides within the pages const slideWidth = slideSize.width, slideHeight = slideSize.height; await new Promise( requestAnimationFrame ); // Let the browser know what page size we want to print createStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0px;}' ); // Limit the size of certain elements to the dimensions of the slide createStyleSheet( '.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: '+ slideWidth +'px; max-height:'+ slideHeight +'px}' ); document.documentElement.classList.add( 'reveal-print', 'print-pdf' ); document.body.style.width = pageWidth + 'px'; document.body.style.height = pageHeight + 'px'; const viewportElement = this.Reveal.getViewportElement(); let presentationBackground; if( viewportElement ) { const viewportStyles = window.getComputedStyle( viewportElement ); if( viewportStyles && viewportStyles.background ) { presentationBackground = viewportStyles.background; } } // Make sure stretch elements fit on slide await new Promise( requestAnimationFrame ); this.Reveal.layoutSlideContents( slideWidth, slideHeight ); // Batch scrollHeight access to prevent layout thrashing await new Promise( requestAnimationFrame ); const slideScrollHeights = slides.map( slide => slide.scrollHeight ); const pages = []; const pageContainer = slides[0].parentNode; let slideNumber = 1; // Slide and slide background layout slides.forEach( function( slide, index ) { // Vertical stacks are not centred since their section // children will be if( slide.classList.contains( 'stack' ) === false ) { // Center the slide inside of the page, giving the slide some margin let left = ( pageWidth - slideWidth ) / 2; let top = ( pageHeight - slideHeight ) / 2; const contentHeight = slideScrollHeights[ index ]; let numberOfPages = Math.max( Math.ceil( contentHeight / pageHeight ), 1 ); // Adhere to configured pages per slide limit numberOfPages = Math.min( numberOfPages, config.pdfMaxPagesPerSlide ); // Center slides vertically if( numberOfPages === 1 && config.center || slide.classList.contains( 'center' ) ) { top = Math.max( ( pageHeight - contentHeight ) / 2, 0 ); } // Wrap the slide in a page element and hide its overflow // so that no page ever flows onto another const page = document.createElement( 'div' ); pages.push( page ); page.className = 'pdf-page'; page.style.height = ( ( pageHeight + config.pdfPageHeightOffset ) * numberOfPages ) + 'px'; // Copy the presentation-wide background to each individual // page when printing if( presentationBackground ) { page.style.background = presentationBackground; } page.appendChild( slide ); // Position the slide inside of the page slide.style.left = left + 'px'; slide.style.top = top + 'px'; slide.style.width = slideWidth + 'px'; this.Reveal.slideContent.layout( slide ); if( slide.slideBackgroundElement ) { page.insertBefore( slide.slideBackgroundElement, slide ); } // Inject notes if `showNotes` is enabled if( config.showNotes ) { // Are there notes for this slide? const notes = this.Reveal.getSlideNotes( slide ); if( notes ) { const notesSpacing = 8; const notesLayout = typeof config.showNotes === 'string' ? config.showNotes : 'inline'; const notesElement = document.createElement( 'div' ); notesElement.classList.add( 'speaker-notes' ); notesElement.classList.add( 'speaker-notes-pdf' ); notesElement.setAttribute( 'data-layout', notesLayout ); notesElement.innerHTML = notes; if( notesLayout === 'separate-page' ) { pages.push( notesElement ); } else { notesElement.style.left = notesSpacing + 'px'; notesElement.style.bottom = notesSpacing + 'px'; notesElement.style.width = ( pageWidth - notesSpacing*2 ) + 'px'; page.appendChild( notesElement ); } } } // Inject page numbers if `slideNumbers` are enabled if( injectPageNumbers ) { const numberElement = document.createElement( 'div' ); numberElement.classList.add( 'slide-number' ); numberElement.classList.add( 'slide-number-pdf' ); numberElement.innerHTML = slideNumber++; page.appendChild( numberElement ); } // Copy page and show fragments one after another if( config.pdfSeparateFragments ) { // Each fragment 'group' is an array containing one or more // fragments. Multiple fragments that appear at the same time // are part of the same group. const fragmentGroups = this.Reveal.fragments.sort( page.querySelectorAll( '.fragment' ), true ); let previousFragmentStep; fragmentGroups.forEach( function( fragments, index ) { // Remove 'current-fragment' from the previous group if( previousFragmentStep ) { previousFragmentStep.forEach( function( fragment ) { fragment.classList.remove( 'current-fragment' ); } ); } // Show the fragments for the current index fragments.forEach( function( fragment ) { fragment.classList.add( 'visible', 'current-fragment' ); }, this ); // Create a separate page for the current fragment state const clonedPage = page.cloneNode( true ); // Inject unique page numbers for fragments if( injectPageNumbers ) { const numberElement = clonedPage.querySelector( '.slide-number-pdf' ); const fragmentNumber = index + 1; numberElement.innerHTML += '.' + fragmentNumber; } pages.push( clonedPage ); previousFragmentStep = fragments; }, this ); // Reset the first/original page so that all fragments are hidden fragmentGroups.forEach( function( fragments ) { fragments.forEach( function( fragment ) { fragment.classList.remove( 'visible', 'current-fragment' ); } ); } ); } // Show all fragments else { queryAll( page, '.fragment:not(.fade-out)' ).forEach( function( fragment ) { fragment.classList.add( 'visible' ); } ); } } }, this ); await new Promise( requestAnimationFrame ); pages.forEach( page => pageContainer.appendChild( page ) ); // Re-run JS-based content layout after the slide is added to page DOM this.Reveal.slideContent.layout( this.Reveal.getSlidesElement() ); // Notify subscribers that the PDF layout is good to go this.Reveal.dispatchEvent({ type: 'pdf-ready' }); viewportElement.classList.remove( 'loading-scroll-mode' ); } /** * Checks if the print mode is/should be activated. */ isActive() { return this.Reveal.getConfig().view === 'print'; } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/scrollview.js
js/controllers/scrollview.js
import { HORIZONTAL_SLIDES_SELECTOR, HORIZONTAL_BACKGROUNDS_SELECTOR } from '../utils/constants.js' import { queryAll } from '../utils/util.js' const HIDE_SCROLLBAR_TIMEOUT = 500; const MAX_PROGRESS_SPACING = 4; const MIN_PROGRESS_SEGMENT_HEIGHT = 6; const MIN_PLAYHEAD_HEIGHT = 8; /** * The scroll view lets you read a reveal.js presentation * as a linear scrollable page. */ export default class ScrollView { constructor( Reveal ) { this.Reveal = Reveal; this.active = false; this.activatedCallbacks = []; this.onScroll = this.onScroll.bind( this ); } /** * Activates the scroll view. This rearranges the presentation DOM * by—among other things—wrapping each slide in a page element. */ activate() { if( this.active ) return; const stateBeforeActivation = this.Reveal.getState(); this.active = true; // Store the full presentation HTML so that we can restore it // when/if the scroll view is deactivated this.slideHTMLBeforeActivation = this.Reveal.getSlidesElement().innerHTML; const horizontalSlides = queryAll( this.Reveal.getRevealElement(), HORIZONTAL_SLIDES_SELECTOR ); const horizontalBackgrounds = queryAll( this.Reveal.getRevealElement(), HORIZONTAL_BACKGROUNDS_SELECTOR ); this.viewportElement.classList.add( 'loading-scroll-mode', 'reveal-scroll' ); let presentationBackground; const viewportStyles = window.getComputedStyle( this.viewportElement ); if( viewportStyles && viewportStyles.background ) { presentationBackground = viewportStyles.background; } const pageElements = []; const pageContainer = horizontalSlides[0].parentNode; let previousSlide; // Creates a new page element and appends the given slide/bg // to it. const createPageElement = ( slide, h, v, isVertical ) => { let contentContainer; // If this slide is part of an auto-animation sequence, we // group it under the same page element as the previous slide if( previousSlide && this.Reveal.shouldAutoAnimateBetween( previousSlide, slide ) ) { contentContainer = document.createElement( 'div' ); contentContainer.className = 'scroll-page-content scroll-auto-animate-page'; contentContainer.style.display = 'none'; previousSlide.closest( '.scroll-page-content' ).parentNode.appendChild( contentContainer ); } else { // Wrap the slide in a page element and hide its overflow // so that no page ever flows onto another const page = document.createElement( 'div' ); page.className = 'scroll-page'; pageElements.push( page ); // This transfers over the background of the vertical stack containing // the slide if it exists. Otherwise, it uses the presentation-wide // background. if( isVertical && horizontalBackgrounds.length > h ) { const slideBackground = horizontalBackgrounds[h]; const pageBackground = window.getComputedStyle( slideBackground ); if( pageBackground && pageBackground.background ) { page.style.background = pageBackground.background; } else if( presentationBackground ) { page.style.background = presentationBackground; } } else if( presentationBackground ) { page.style.background = presentationBackground; } const stickyContainer = document.createElement( 'div' ); stickyContainer.className = 'scroll-page-sticky'; page.appendChild( stickyContainer ); contentContainer = document.createElement( 'div' ); contentContainer.className = 'scroll-page-content'; stickyContainer.appendChild( contentContainer ); } contentContainer.appendChild( slide ); slide.classList.remove( 'past', 'future' ); slide.setAttribute( 'data-index-h', h ); slide.setAttribute( 'data-index-v', v ); if( slide.slideBackgroundElement ) { slide.slideBackgroundElement.remove( 'past', 'future' ); contentContainer.insertBefore( slide.slideBackgroundElement, slide ); } previousSlide = slide; } // Slide and slide background layout horizontalSlides.forEach( ( horizontalSlide, h ) => { if( this.Reveal.isVerticalStack( horizontalSlide ) ) { horizontalSlide.querySelectorAll( 'section' ).forEach( ( verticalSlide, v ) => { createPageElement( verticalSlide, h, v, true ); }); } else { createPageElement( horizontalSlide, h, 0 ); } }, this ); this.createProgressBar(); // Remove leftover stacks queryAll( this.Reveal.getRevealElement(), '.stack' ).forEach( stack => stack.remove() ); // Add our newly created pages to the DOM pageElements.forEach( page => pageContainer.appendChild( page ) ); // Re-run JS-based content layout after the slide is added to page DOM this.Reveal.slideContent.layout( this.Reveal.getSlidesElement() ); this.Reveal.layout(); this.Reveal.setState( stateBeforeActivation ); this.activatedCallbacks.forEach( callback => callback() ); this.activatedCallbacks = []; this.restoreScrollPosition(); this.viewportElement.classList.remove( 'loading-scroll-mode' ); this.viewportElement.addEventListener( 'scroll', this.onScroll, { passive: true } ); } /** * Deactivates the scroll view and restores the standard slide-based * presentation. */ deactivate() { if( !this.active ) return; const stateBeforeDeactivation = this.Reveal.getState(); this.active = false; this.viewportElement.removeEventListener( 'scroll', this.onScroll ); this.viewportElement.classList.remove( 'reveal-scroll' ); this.removeProgressBar(); this.Reveal.getSlidesElement().innerHTML = this.slideHTMLBeforeActivation; this.Reveal.sync(); this.Reveal.setState( stateBeforeDeactivation ); this.slideHTMLBeforeActivation = null; } toggle( override ) { if( typeof override === 'boolean' ) { override ? this.activate() : this.deactivate(); } else { this.isActive() ? this.deactivate() : this.activate(); } } /** * Checks if the scroll view is currently active. */ isActive() { return this.active; } /** * Renders the progress bar component. */ createProgressBar() { this.progressBar = document.createElement( 'div' ); this.progressBar.className = 'scrollbar'; this.progressBarInner = document.createElement( 'div' ); this.progressBarInner.className = 'scrollbar-inner'; this.progressBar.appendChild( this.progressBarInner ); this.progressBarPlayhead = document.createElement( 'div' ); this.progressBarPlayhead.className = 'scrollbar-playhead'; this.progressBarInner.appendChild( this.progressBarPlayhead ); this.viewportElement.insertBefore( this.progressBar, this.viewportElement.firstChild ); const handleDocumentMouseMove = ( event ) => { let progress = ( event.clientY - this.progressBarInner.getBoundingClientRect().top ) / this.progressBarHeight; progress = Math.max( Math.min( progress, 1 ), 0 ); this.viewportElement.scrollTop = progress * ( this.viewportElement.scrollHeight - this.viewportElement.offsetHeight ); }; const handleDocumentMouseUp = ( event ) => { this.draggingProgressBar = false; this.showProgressBar(); document.removeEventListener( 'mousemove', handleDocumentMouseMove ); document.removeEventListener( 'mouseup', handleDocumentMouseUp ); }; const handleMouseDown = ( event ) => { event.preventDefault(); this.draggingProgressBar = true; document.addEventListener( 'mousemove', handleDocumentMouseMove ); document.addEventListener( 'mouseup', handleDocumentMouseUp ); handleDocumentMouseMove( event ); }; this.progressBarInner.addEventListener( 'mousedown', handleMouseDown ); } removeProgressBar() { if( this.progressBar ) { this.progressBar.remove(); this.progressBar = null; } } layout() { if( this.isActive() ) { this.syncPages(); this.syncScrollPosition(); } } /** * Updates our pages to match the latest configuration and * presentation size. */ syncPages() { const config = this.Reveal.getConfig(); const slideSize = this.Reveal.getComputedSlideSize( window.innerWidth, window.innerHeight ); const scale = this.Reveal.getScale(); const useCompactLayout = config.scrollLayout === 'compact'; const viewportHeight = this.viewportElement.offsetHeight; const compactHeight = slideSize.height * scale; const pageHeight = useCompactLayout ? compactHeight : viewportHeight; // The height that needs to be scrolled between scroll triggers this.scrollTriggerHeight = useCompactLayout ? compactHeight : viewportHeight; this.viewportElement.style.setProperty( '--page-height', pageHeight + 'px' ); this.viewportElement.style.scrollSnapType = typeof config.scrollSnap === 'string' ? `y ${config.scrollSnap}` : ''; // This will hold all scroll triggers used to show/hide slides this.slideTriggers = []; const pageElements = Array.from( this.Reveal.getRevealElement().querySelectorAll( '.scroll-page' ) ); this.pages = pageElements.map( pageElement => { const page = this.createPage({ pageElement, slideElement: pageElement.querySelector( 'section' ), stickyElement: pageElement.querySelector( '.scroll-page-sticky' ), contentElement: pageElement.querySelector( '.scroll-page-content' ), backgroundElement: pageElement.querySelector( '.slide-background' ), autoAnimateElements: pageElement.querySelectorAll( '.scroll-auto-animate-page' ), autoAnimatePages: [] }); page.pageElement.style.setProperty( '--slide-height', config.center === true ? 'auto' : slideSize.height + 'px' ); this.slideTriggers.push({ page: page, activate: () => this.activatePage( page ), deactivate: () => this.deactivatePage( page ) }); // Create scroll triggers that show/hide fragments this.createFragmentTriggersForPage( page ); // Create scroll triggers for triggering auto-animate steps if( page.autoAnimateElements.length > 0 ) { this.createAutoAnimateTriggersForPage( page ); } let totalScrollTriggerCount = Math.max( page.scrollTriggers.length - 1, 0 ); // Each auto-animate step may include its own scroll triggers // for fragments, ensure we count those as well totalScrollTriggerCount += page.autoAnimatePages.reduce( ( total, page ) => { return total + Math.max( page.scrollTriggers.length - 1, 0 ); }, page.autoAnimatePages.length ); // Clean up from previous renders page.pageElement.querySelectorAll( '.scroll-snap-point' ).forEach( el => el.remove() ); // Create snap points for all scroll triggers // - Can't be absolute in FF // - Can't be 0-height in Safari // - Can't use snap-align on parent in Safari because then // inner triggers won't work for( let i = 0; i < totalScrollTriggerCount + 1; i++ ) { const triggerStick = document.createElement( 'div' ); triggerStick.className = 'scroll-snap-point'; triggerStick.style.height = this.scrollTriggerHeight + 'px'; triggerStick.style.scrollSnapAlign = useCompactLayout ? 'center' : 'start'; page.pageElement.appendChild( triggerStick ); if( i === 0 ) { triggerStick.style.marginTop = -this.scrollTriggerHeight + 'px'; } } // In the compact layout, only slides with scroll triggers cover the // full viewport height. This helps avoid empty gaps before or after // a sticky slide. if( useCompactLayout && page.scrollTriggers.length > 0 ) { page.pageHeight = viewportHeight; page.pageElement.style.setProperty( '--page-height', viewportHeight + 'px' ); } else { page.pageHeight = pageHeight; page.pageElement.style.removeProperty( '--page-height' ); } // Add scroll padding based on how many scroll triggers we have page.scrollPadding = this.scrollTriggerHeight * totalScrollTriggerCount; // The total height including scrollable space page.totalHeight = page.pageHeight + page.scrollPadding; // This is used to pad the height of our page in CSS page.pageElement.style.setProperty( '--page-scroll-padding', page.scrollPadding + 'px' ); // If this is a sticky page, stick it to the vertical center if( totalScrollTriggerCount > 0 ) { page.stickyElement.style.position = 'sticky'; page.stickyElement.style.top = Math.max( ( viewportHeight - page.pageHeight ) / 2, 0 ) + 'px'; } else { page.stickyElement.style.position = 'relative'; page.pageElement.style.scrollSnapAlign = page.pageHeight < viewportHeight ? 'center' : 'start'; } return page; } ); this.setTriggerRanges(); /* console.log(this.slideTriggers.map( t => { return { range: `${t.range[0].toFixed(2)}-${t.range[1].toFixed(2)}`, triggers: t.page.scrollTriggers.map( t => { return `${t.range[0].toFixed(2)}-${t.range[1].toFixed(2)}` }).join( ', ' ), } })) */ this.viewportElement.setAttribute( 'data-scrollbar', config.scrollProgress ); if( config.scrollProgress && this.totalScrollTriggerCount > 1 ) { // Create the progress bar if it doesn't already exist if( !this.progressBar ) this.createProgressBar(); this.syncProgressBar(); } else { this.removeProgressBar(); } } /** * Calculates and sets the scroll range for all of our scroll * triggers. */ setTriggerRanges() { // Calculate the total number of scroll triggers this.totalScrollTriggerCount = this.slideTriggers.reduce( ( total, trigger ) => { return total + Math.max( trigger.page.scrollTriggers.length, 1 ); }, 0 ); let rangeStart = 0; // Calculate the scroll range of each scroll trigger on a scale // of 0-1 this.slideTriggers.forEach( ( trigger, i ) => { trigger.range = [ rangeStart, rangeStart + Math.max( trigger.page.scrollTriggers.length, 1 ) / this.totalScrollTriggerCount ]; const scrollTriggerSegmentSize = ( trigger.range[1] - trigger.range[0] ) / trigger.page.scrollTriggers.length; // Set the range for each inner scroll trigger trigger.page.scrollTriggers.forEach( ( scrollTrigger, i ) => { scrollTrigger.range = [ rangeStart + i * scrollTriggerSegmentSize, rangeStart + ( i + 1 ) * scrollTriggerSegmentSize ]; } ); rangeStart = trigger.range[1]; } ); // Ensure the last trigger extends to the end of the page, otherwise // rounding errors can cause the last trigger to end at 0.999999... this.slideTriggers[this.slideTriggers.length - 1].range[1] = 1; } /** * Creates one scroll trigger for each fragments in the given page. * * @param {*} page */ createFragmentTriggersForPage( page, slideElement ) { slideElement = slideElement || page.slideElement; // Each fragment 'group' is an array containing one or more // fragments. Multiple fragments that appear at the same time // are part of the same group. const fragmentGroups = this.Reveal.fragments.sort( slideElement.querySelectorAll( '.fragment' ), true ); // Create scroll triggers that show/hide fragments if( fragmentGroups.length ) { page.fragments = this.Reveal.fragments.sort( slideElement.querySelectorAll( '.fragment:not(.disabled)' ) ); page.scrollTriggers.push( // Trigger for the initial state with no fragments visible { activate: () => { this.Reveal.fragments.update( -1, page.fragments, slideElement ); } } ); // Triggers for each fragment group fragmentGroups.forEach( ( fragments, i ) => { page.scrollTriggers.push({ activate: () => { this.Reveal.fragments.update( i, page.fragments, slideElement ); } }); } ); } return page.scrollTriggers.length; } /** * Creates scroll triggers for the auto-animate steps in the * given page. * * @param {*} page */ createAutoAnimateTriggersForPage( page ) { if( page.autoAnimateElements.length > 0 ) { // Triggers for each subsequent auto-animate slide this.slideTriggers.push( ...Array.from( page.autoAnimateElements ).map( ( autoAnimateElement, i ) => { let autoAnimatePage = this.createPage({ slideElement: autoAnimateElement.querySelector( 'section' ), contentElement: autoAnimateElement, backgroundElement: autoAnimateElement.querySelector( '.slide-background' ) }); // Create fragment scroll triggers for the auto-animate slide this.createFragmentTriggersForPage( autoAnimatePage, autoAnimatePage.slideElement ); page.autoAnimatePages.push( autoAnimatePage ); // Return our slide trigger return { page: autoAnimatePage, activate: () => this.activatePage( autoAnimatePage ), deactivate: () => this.deactivatePage( autoAnimatePage ) }; })); } } /** * Helper method for creating a page definition and adding * required fields. A "page" is a slide or auto-animate step. */ createPage( page ) { page.scrollTriggers = []; page.indexh = parseInt( page.slideElement.getAttribute( 'data-index-h' ), 10 ); page.indexv = parseInt( page.slideElement.getAttribute( 'data-index-v' ), 10 ); return page; } /** * Rerenders progress bar segments so that they match the current * reveal.js config and size. */ syncProgressBar() { this.progressBarInner.querySelectorAll( '.scrollbar-slide' ).forEach( slide => slide.remove() ); const scrollHeight = this.viewportElement.scrollHeight; const viewportHeight = this.viewportElement.offsetHeight; const viewportHeightFactor = viewportHeight / scrollHeight; this.progressBarHeight = this.progressBarInner.offsetHeight; this.playheadHeight = Math.max( viewportHeightFactor * this.progressBarHeight, MIN_PLAYHEAD_HEIGHT ); this.progressBarScrollableHeight = this.progressBarHeight - this.playheadHeight; const progressSegmentHeight = viewportHeight / scrollHeight * this.progressBarHeight; const spacing = Math.min( progressSegmentHeight / 8, MAX_PROGRESS_SPACING ); this.progressBarPlayhead.style.height = this.playheadHeight - spacing + 'px'; // Don't show individual segments if they're too small if( progressSegmentHeight > MIN_PROGRESS_SEGMENT_HEIGHT ) { this.slideTriggers.forEach( slideTrigger => { const { page } = slideTrigger; // Visual representation of a slide page.progressBarSlide = document.createElement( 'div' ); page.progressBarSlide.className = 'scrollbar-slide'; page.progressBarSlide.style.top = slideTrigger.range[0] * this.progressBarHeight + 'px'; page.progressBarSlide.style.height = ( slideTrigger.range[1] - slideTrigger.range[0] ) * this.progressBarHeight - spacing + 'px'; page.progressBarSlide.classList.toggle( 'has-triggers', page.scrollTriggers.length > 0 ); this.progressBarInner.appendChild( page.progressBarSlide ); // Visual representations of each scroll trigger page.scrollTriggerElements = page.scrollTriggers.map( ( trigger, i ) => { const triggerElement = document.createElement( 'div' ); triggerElement.className = 'scrollbar-trigger'; triggerElement.style.top = ( trigger.range[0] - slideTrigger.range[0] ) * this.progressBarHeight + 'px'; triggerElement.style.height = ( trigger.range[1] - trigger.range[0] ) * this.progressBarHeight - spacing + 'px'; page.progressBarSlide.appendChild( triggerElement ); if( i === 0 ) triggerElement.style.display = 'none'; return triggerElement; } ); } ); } else { this.pages.forEach( page => page.progressBarSlide = null ); } } /** * Reads the current scroll position and updates our active * trigger states accordingly. */ syncScrollPosition() { const viewportHeight = this.viewportElement.offsetHeight; const viewportHeightFactor = viewportHeight / this.viewportElement.scrollHeight; const scrollTop = this.viewportElement.scrollTop; const scrollHeight = this.viewportElement.scrollHeight - viewportHeight const scrollProgress = Math.max( Math.min( scrollTop / scrollHeight, 1 ), 0 ); const scrollProgressMid = Math.max( Math.min( ( scrollTop + viewportHeight / 2 ) / this.viewportElement.scrollHeight, 1 ), 0 ); let activePage; this.slideTriggers.forEach( ( trigger ) => { const { page } = trigger; const shouldPreload = scrollProgress >= trigger.range[0] - viewportHeightFactor*2 && scrollProgress <= trigger.range[1] + viewportHeightFactor*2; // Load slides that are within the preload range if( shouldPreload && !page.loaded ) { page.loaded = true; this.Reveal.slideContent.load( page.slideElement ); } else if( page.loaded ) { page.loaded = false; this.Reveal.slideContent.unload( page.slideElement ); } // If we're within this trigger range, activate it if( scrollProgress >= trigger.range[0] && scrollProgress <= trigger.range[1] ) { this.activateTrigger( trigger ); activePage = trigger.page; } // .. otherwise deactivate else if( trigger.active ) { this.deactivateTrigger( trigger ); } } ); // Each page can have its own scroll triggers, check if any of those // need to be activated/deactivated if( activePage ) { activePage.scrollTriggers.forEach( ( trigger ) => { if( scrollProgressMid >= trigger.range[0] && scrollProgressMid <= trigger.range[1] ) { this.activateTrigger( trigger ); } else if( trigger.active ) { this.deactivateTrigger( trigger ); } } ); } // Update our visual progress indication this.setProgressBarValue( scrollTop / ( this.viewportElement.scrollHeight - viewportHeight ) ); } /** * Moves the progress bar playhead to the specified position. * * @param {number} progress 0-1 */ setProgressBarValue( progress ) { if( this.progressBar ) { this.progressBarPlayhead.style.transform = `translateY(${progress * this.progressBarScrollableHeight}px)`; this.getAllPages() .filter( page => page.progressBarSlide ) .forEach( ( page ) => { page.progressBarSlide.classList.toggle( 'active', page.active === true ); page.scrollTriggers.forEach( ( trigger, i ) => { page.scrollTriggerElements[i].classList.toggle( 'active', page.active === true && trigger.active === true ); } ); } ); this.showProgressBar(); } } /** * Show the progress bar and, if configured, automatically hide * it after a delay. */ showProgressBar() { this.progressBar.classList.add( 'visible' ); clearTimeout( this.hideProgressBarTimeout ); if( this.Reveal.getConfig().scrollProgress === 'auto' && !this.draggingProgressBar ) { this.hideProgressBarTimeout = setTimeout( () => { if( this.progressBar ) { this.progressBar.classList.remove( 'visible' ); } }, HIDE_SCROLLBAR_TIMEOUT ); } } /** * Scroll to the previous page. */ prev() { this.viewportElement.scrollTop -= this.scrollTriggerHeight; } /** * Scroll to the next page. */ next() { this.viewportElement.scrollTop += this.scrollTriggerHeight; } /** * Scrolls the given slide element into view. * * @param {HTMLElement} slideElement */ scrollToSlide( slideElement ) { // If the scroll view isn't active yet, queue this action if( !this.active ) { this.activatedCallbacks.push( () => this.scrollToSlide( slideElement ) ); } else { // Find the trigger for this slide const trigger = this.getScrollTriggerBySlide( slideElement ); if( trigger ) { // Use the trigger's range to calculate the scroll position this.viewportElement.scrollTop = trigger.range[0] * ( this.viewportElement.scrollHeight - this.viewportElement.offsetHeight ); } } } /** * Persists the current scroll position to session storage * so that it can be restored. */ storeScrollPosition() { clearTimeout( this.storeScrollPositionTimeout ); this.storeScrollPositionTimeout = setTimeout( () => { sessionStorage.setItem( 'reveal-scroll-top', this.viewportElement.scrollTop ); sessionStorage.setItem( 'reveal-scroll-origin', location.origin + location.pathname ); this.storeScrollPositionTimeout = null; }, 50 ); } /** * Restores the scroll position when a deck is reloader. */ restoreScrollPosition() { const scrollPosition = sessionStorage.getItem( 'reveal-scroll-top' ); const scrollOrigin = sessionStorage.getItem( 'reveal-scroll-origin' ); if( scrollPosition && scrollOrigin === location.origin + location.pathname ) { this.viewportElement.scrollTop = parseInt( scrollPosition, 10 ); } } /** * Activates the given page and starts its embedded content * if there is any. * * @param {object} page */ activatePage( page ) { if( !page.active ) { page.active = true; const { slideElement, backgroundElement, contentElement, indexh, indexv } = page; contentElement.style.display = 'block'; slideElement.classList.add( 'present' ); if( backgroundElement ) { backgroundElement.classList.add( 'present' ); } this.Reveal.setCurrentScrollPage( slideElement, indexh, indexv ); this.Reveal.backgrounds.bubbleSlideContrastClassToElement( slideElement, this.viewportElement ); // If this page is part of an auto-animation there will be one // content element per auto-animated page. We need to show the // current page and hide all others. Array.from( contentElement.parentNode.querySelectorAll( '.scroll-page-content' ) ).forEach( sibling => { if( sibling !== contentElement ) { sibling.style.display = 'none'; } }); } } /** * Deactivates the page after it has been visible. * * @param {object} page */ deactivatePage( page ) { if( page.active ) { page.active = false; if( page.slideElement ) page.slideElement.classList.remove( 'present' ); if( page.backgroundElement ) page.backgroundElement.classList.remove( 'present' ); } } activateTrigger( trigger ) { if( !trigger.active ) { trigger.active = true; trigger.activate(); } } deactivateTrigger( trigger ) { if( trigger.active ) { trigger.active = false; if( trigger.deactivate ) { trigger.deactivate(); } } } /** * Retrieve a slide by its original h/v index (i.e. the indices the * slide had before being linearized). * * @param {number} h * @param {number} v * @returns {HTMLElement} */ getSlideByIndices( h, v ) { const page = this.getAllPages().find( page => { return page.indexh === h && page.indexv === v; } ); return page ? page.slideElement : null; } /** * Retrieve a list of all scroll triggers for the given slide * DOM element. * * @param {HTMLElement} slide * @returns {Array} */ getScrollTriggerBySlide( slide ) { return this.slideTriggers.find( trigger => trigger.page.slideElement === slide ); } /** * Get a list of all pages in the scroll view. This includes * both top-level slides and auto-animate steps. * * @returns {Array} */ getAllPages() { return this.pages.flatMap( page => [page, ...(page.autoAnimatePages || [])] ); } onScroll() { this.syncScrollPosition(); this.storeScrollPosition(); } get viewportElement() { return this.Reveal.getViewportElement(); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/slidenumber.js
js/controllers/slidenumber.js
import { SLIDE_NUMBER_FORMAT_CURRENT, SLIDE_NUMBER_FORMAT_CURRENT_SLASH_TOTAL, SLIDE_NUMBER_FORMAT_HORIZONTAL_DOT_VERTICAL, SLIDE_NUMBER_FORMAT_HORIZONTAL_SLASH_VERTICAL } from "../utils/constants"; /** * Handles the display of reveal.js' optional slide number. */ export default class SlideNumber { constructor( Reveal ) { this.Reveal = Reveal; } render() { this.element = document.createElement( 'div' ); this.element.className = 'slide-number'; this.Reveal.getRevealElement().appendChild( this.element ); } /** * Called when the reveal.js config is updated. */ configure( config, oldConfig ) { let slideNumberDisplay = 'none'; if( config.slideNumber && !this.Reveal.isPrintView() ) { if( config.showSlideNumber === 'all' ) { slideNumberDisplay = 'block'; } else if( config.showSlideNumber === 'speaker' && this.Reveal.isSpeakerNotes() ) { slideNumberDisplay = 'block'; } } this.element.style.display = slideNumberDisplay; } /** * Updates the slide number to match the current slide. */ update() { // Update slide number if enabled if( this.Reveal.getConfig().slideNumber && this.element ) { this.element.innerHTML = this.getSlideNumber(); } } /** * Returns the HTML string corresponding to the current slide * number, including formatting. */ getSlideNumber( slide = this.Reveal.getCurrentSlide() ) { let config = this.Reveal.getConfig(); let value; let format = SLIDE_NUMBER_FORMAT_HORIZONTAL_DOT_VERTICAL; if ( typeof config.slideNumber === 'function' ) { value = config.slideNumber( slide ); } else { // Check if a custom number format is available if( typeof config.slideNumber === 'string' ) { format = config.slideNumber; } // If there are ONLY vertical slides in this deck, always use // a flattened slide number if( !/c/.test( format ) && this.Reveal.getHorizontalSlides().length === 1 ) { format = SLIDE_NUMBER_FORMAT_CURRENT; } // Offset the current slide number by 1 to make it 1-indexed let horizontalOffset = slide && slide.dataset.visibility === 'uncounted' ? 0 : 1; value = []; switch( format ) { case SLIDE_NUMBER_FORMAT_CURRENT: value.push( this.Reveal.getSlidePastCount( slide ) + horizontalOffset ); break; case SLIDE_NUMBER_FORMAT_CURRENT_SLASH_TOTAL: value.push( this.Reveal.getSlidePastCount( slide ) + horizontalOffset, '/', this.Reveal.getTotalSlides() ); break; default: let indices = this.Reveal.getIndices( slide ); value.push( indices.h + horizontalOffset ); let sep = format === SLIDE_NUMBER_FORMAT_HORIZONTAL_SLASH_VERTICAL ? '/' : '.'; if( this.Reveal.isVerticalSlide( slide ) ) value.push( sep, indices.v + 1 ); } } let url = '#' + this.Reveal.location.getHash( slide ); return this.formatNumber( value[0], value[1], value[2], url ); } /** * Applies HTML formatting to a slide number before it's * written to the DOM. * * @param {number} a Current slide * @param {string} delimiter Character to separate slide numbers * @param {(number|*)} b Total slides * @param {HTMLElement} [url='#'+locationHash()] The url to link to * @return {string} HTML string fragment */ formatNumber( a, delimiter, b, url = '#' + this.Reveal.location.getHash() ) { if( typeof b === 'number' && !isNaN( b ) ) { return `<a href="${url}"> <span class="slide-number-a">${a}</span> <span class="slide-number-delimiter">${delimiter}</span> <span class="slide-number-b">${b}</span> </a>`; } else { return `<a href="${url}"> <span class="slide-number-a">${a}</span> </a>`; } } destroy() { this.element.remove(); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/touch.js
js/controllers/touch.js
import { isAndroid } from '../utils/device.js' import { matches } from '../utils/util.js' const SWIPE_THRESHOLD = 40; /** * Controls all touch interactions and navigations for * a presentation. */ export default class Touch { constructor( Reveal ) { this.Reveal = Reveal; // Holds information about the currently ongoing touch interaction this.touchStartX = 0; this.touchStartY = 0; this.touchStartCount = 0; this.touchCaptured = false; this.onPointerDown = this.onPointerDown.bind( this ); this.onPointerMove = this.onPointerMove.bind( this ); this.onPointerUp = this.onPointerUp.bind( this ); this.onTouchStart = this.onTouchStart.bind( this ); this.onTouchMove = this.onTouchMove.bind( this ); this.onTouchEnd = this.onTouchEnd.bind( this ); } /** * */ bind() { let revealElement = this.Reveal.getRevealElement(); if( 'onpointerdown' in window ) { // Use W3C pointer events revealElement.addEventListener( 'pointerdown', this.onPointerDown, false ); revealElement.addEventListener( 'pointermove', this.onPointerMove, false ); revealElement.addEventListener( 'pointerup', this.onPointerUp, false ); } else if( window.navigator.msPointerEnabled ) { // IE 10 uses prefixed version of pointer events revealElement.addEventListener( 'MSPointerDown', this.onPointerDown, false ); revealElement.addEventListener( 'MSPointerMove', this.onPointerMove, false ); revealElement.addEventListener( 'MSPointerUp', this.onPointerUp, false ); } else { // Fall back to touch events revealElement.addEventListener( 'touchstart', this.onTouchStart, false ); revealElement.addEventListener( 'touchmove', this.onTouchMove, false ); revealElement.addEventListener( 'touchend', this.onTouchEnd, false ); } } /** * */ unbind() { let revealElement = this.Reveal.getRevealElement(); revealElement.removeEventListener( 'pointerdown', this.onPointerDown, false ); revealElement.removeEventListener( 'pointermove', this.onPointerMove, false ); revealElement.removeEventListener( 'pointerup', this.onPointerUp, false ); revealElement.removeEventListener( 'MSPointerDown', this.onPointerDown, false ); revealElement.removeEventListener( 'MSPointerMove', this.onPointerMove, false ); revealElement.removeEventListener( 'MSPointerUp', this.onPointerUp, false ); revealElement.removeEventListener( 'touchstart', this.onTouchStart, false ); revealElement.removeEventListener( 'touchmove', this.onTouchMove, false ); revealElement.removeEventListener( 'touchend', this.onTouchEnd, false ); } /** * Checks if the target element prevents the triggering of * swipe navigation. */ isSwipePrevented( target ) { // Prevent accidental swipes when scrubbing timelines if( matches( target, 'video[controls], audio[controls]' ) ) return true; while( target && typeof target.hasAttribute === 'function' ) { if( target.hasAttribute( 'data-prevent-swipe' ) ) return true; target = target.parentNode; } return false; } /** * Handler for the 'touchstart' event, enables support for * swipe and pinch gestures. * * @param {object} event */ onTouchStart( event ) { this.touchCaptured = false; if( this.isSwipePrevented( event.target ) ) return true; this.touchStartX = event.touches[0].clientX; this.touchStartY = event.touches[0].clientY; this.touchStartCount = event.touches.length; } /** * Handler for the 'touchmove' event. * * @param {object} event */ onTouchMove( event ) { if( this.isSwipePrevented( event.target ) ) return true; let config = this.Reveal.getConfig(); // Each touch should only trigger one action if( !this.touchCaptured ) { this.Reveal.onUserInput( event ); let currentX = event.touches[0].clientX; let currentY = event.touches[0].clientY; // There was only one touch point, look for a swipe if( event.touches.length === 1 && this.touchStartCount !== 2 ) { let availableRoutes = this.Reveal.availableRoutes({ includeFragments: true }); let deltaX = currentX - this.touchStartX, deltaY = currentY - this.touchStartY; if( deltaX > SWIPE_THRESHOLD && Math.abs( deltaX ) > Math.abs( deltaY ) ) { this.touchCaptured = true; if( config.navigationMode === 'linear' ) { if( config.rtl ) { this.Reveal.next(); } else { this.Reveal.prev(); } } else { this.Reveal.left(); } } else if( deltaX < -SWIPE_THRESHOLD && Math.abs( deltaX ) > Math.abs( deltaY ) ) { this.touchCaptured = true; if( config.navigationMode === 'linear' ) { if( config.rtl ) { this.Reveal.prev(); } else { this.Reveal.next(); } } else { this.Reveal.right(); } } else if( deltaY > SWIPE_THRESHOLD && availableRoutes.up ) { this.touchCaptured = true; if( config.navigationMode === 'linear' ) { this.Reveal.prev(); } else { this.Reveal.up(); } } else if( deltaY < -SWIPE_THRESHOLD && availableRoutes.down ) { this.touchCaptured = true; if( config.navigationMode === 'linear' ) { this.Reveal.next(); } else { this.Reveal.down(); } } // If we're embedded, only block touch events if they have // triggered an action if( config.embedded ) { if( this.touchCaptured || this.Reveal.isVerticalSlide() ) { event.preventDefault(); } } // Not embedded? Block them all to avoid needless tossing // around of the viewport in iOS else { event.preventDefault(); } } } // There's a bug with swiping on some Android devices unless // the default action is always prevented else if( isAndroid ) { event.preventDefault(); } } /** * Handler for the 'touchend' event. * * @param {object} event */ onTouchEnd( event ) { // Media playback is only allowed as a direct result of a // user interaction. Some mobile devices do not consider a // 'touchmove' to be a direct user action. If this is the // case, we fall back to starting playback here instead. if( this.touchCaptured && !this.Reveal.slideContent.isAllowedToPlayAudio() ) { this.Reveal.startEmbeddedContent( this.Reveal.getCurrentSlide() ); } this.touchCaptured = false; } /** * Convert pointer down to touch start. * * @param {object} event */ onPointerDown( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; this.onTouchStart( event ); } } /** * Convert pointer move to touch move. * * @param {object} event */ onPointerMove( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; this.onTouchMove( event ); } } /** * Convert pointer up to touch end. * * @param {object} event */ onPointerUp( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; this.onTouchEnd( event ); } } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/jumptoslide.js
js/controllers/jumptoslide.js
import { SLIDE_NUMBER_FORMAT_CURRENT, SLIDE_NUMBER_FORMAT_CURRENT_SLASH_TOTAL } from "../utils/constants"; /** * Makes it possible to jump to a slide by entering its * slide number or id. */ export default class JumpToSlide { constructor( Reveal ) { this.Reveal = Reveal; this.onInput = this.onInput.bind( this ); this.onBlur = this.onBlur.bind( this ); this.onKeyDown = this.onKeyDown.bind( this ); } render() { this.element = document.createElement( 'div' ); this.element.className = 'jump-to-slide'; this.jumpInput = document.createElement( 'input' ); this.jumpInput.type = 'text'; this.jumpInput.className = 'jump-to-slide-input'; this.jumpInput.placeholder = 'Jump to slide'; this.jumpInput.addEventListener( 'input', this.onInput ); this.jumpInput.addEventListener( 'keydown', this.onKeyDown ); this.jumpInput.addEventListener( 'blur', this.onBlur ); this.element.appendChild( this.jumpInput ); } show() { this.indicesOnShow = this.Reveal.getIndices(); this.Reveal.getRevealElement().appendChild( this.element ); this.jumpInput.focus(); } hide() { if( this.isVisible() ) { this.element.remove(); this.jumpInput.value = ''; clearTimeout( this.jumpTimeout ); delete this.jumpTimeout; } } isVisible() { return !!this.element.parentNode; } /** * Parses the current input and jumps to the given slide. */ jump() { clearTimeout( this.jumpTimeout ); delete this.jumpTimeout; let query = this.jumpInput.value.trim( '' ); let indices; // When slide numbers are formatted to be a single linear number // (instead of showing a separate horizontal/vertical index) we // use the same format for slide jumps if( /^\d+$/.test( query ) ) { const slideNumberFormat = this.Reveal.getConfig().slideNumber; if( slideNumberFormat === SLIDE_NUMBER_FORMAT_CURRENT || slideNumberFormat === SLIDE_NUMBER_FORMAT_CURRENT_SLASH_TOTAL ) { const slide = this.Reveal.getSlides()[ parseInt( query, 10 ) - 1 ]; if( slide ) { indices = this.Reveal.getIndices( slide ); } } } if( !indices ) { // If the query uses "horizontal.vertical" format, convert to // "horizontal/vertical" so that our URL parser can understand if( /^\d+\.\d+$/.test( query ) ) { query = query.replace( '.', '/' ); } indices = this.Reveal.location.getIndicesFromHash( query, { oneBasedIndex: true } ); } // Still no valid index? Fall back on a text search if( !indices && /\S+/i.test( query ) && query.length > 1 ) { indices = this.search( query ); } if( indices && query !== '' ) { this.Reveal.slide( indices.h, indices.v, indices.f ); return true; } else { this.Reveal.slide( this.indicesOnShow.h, this.indicesOnShow.v, this.indicesOnShow.f ); return false; } } jumpAfter( delay ) { clearTimeout( this.jumpTimeout ); this.jumpTimeout = setTimeout( () => this.jump(), delay ); } /** * A lofi search that looks for the given query in all * of our slides and returns the first match. */ search( query ) { const regex = new RegExp( '\\b' + query.trim() + '\\b', 'i' ); const slide = this.Reveal.getSlides().find( ( slide ) => { return regex.test( slide.innerText ); } ); if( slide ) { return this.Reveal.getIndices( slide ); } else { return null; } } /** * Reverts back to the slide we were on when jump to slide was * invoked. */ cancel() { this.Reveal.slide( this.indicesOnShow.h, this.indicesOnShow.v, this.indicesOnShow.f ); this.hide(); } confirm() { this.jump(); this.hide(); } destroy() { this.jumpInput.removeEventListener( 'input', this.onInput ); this.jumpInput.removeEventListener( 'keydown', this.onKeyDown ); this.jumpInput.removeEventListener( 'blur', this.onBlur ); this.element.remove(); } onKeyDown( event ) { if( event.keyCode === 13 ) { this.confirm(); } else if( event.keyCode === 27 ) { this.cancel(); event.stopImmediatePropagation(); } } onInput( event ) { this.jumpAfter( 200 ); } onBlur() { setTimeout( () => this.hide(), 1 ); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/fragments.js
js/controllers/fragments.js
import { extend, queryAll } from '../utils/util.js' /** * Handles sorting and navigation of slide fragments. * Fragments are elements within a slide that are * revealed/animated incrementally. */ export default class Fragments { constructor( Reveal ) { this.Reveal = Reveal; } /** * Called when the reveal.js config is updated. */ configure( config, oldConfig ) { if( config.fragments === false ) { this.disable(); } else if( oldConfig.fragments === false ) { this.enable(); } } /** * If fragments are disabled in the deck, they should all be * visible rather than stepped through. */ disable() { queryAll( this.Reveal.getSlidesElement(), '.fragment' ).forEach( element => { element.classList.add( 'visible' ); element.classList.remove( 'current-fragment' ); } ); } /** * Reverse of #disable(). Only called if fragments have * previously been disabled. */ enable() { queryAll( this.Reveal.getSlidesElement(), '.fragment' ).forEach( element => { element.classList.remove( 'visible' ); element.classList.remove( 'current-fragment' ); } ); } /** * Returns an object describing the available fragment * directions. * * @return {{prev: boolean, next: boolean}} */ availableRoutes() { let currentSlide = this.Reveal.getCurrentSlide(); if( currentSlide && this.Reveal.getConfig().fragments ) { let fragments = currentSlide.querySelectorAll( '.fragment:not(.disabled)' ); let hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.disabled):not(.visible)' ); return { prev: fragments.length - hiddenFragments.length > 0, next: !!hiddenFragments.length }; } else { return { prev: false, next: false }; } } /** * Return a sorted fragments list, ordered by an increasing * "data-fragment-index" attribute. * * Fragments will be revealed in the order that they are returned by * this function, so you can use the index attributes to control the * order of fragment appearance. * * To maintain a sensible default fragment order, fragments are presumed * to be passed in document order. This function adds a "fragment-index" * attribute to each node if such an attribute is not already present, * and sets that attribute to an integer value which is the position of * the fragment within the fragments list. * * @param {object[]|*} fragments * @param {boolean} grouped If true the returned array will contain * nested arrays for all fragments with the same index * @return {object[]} sorted Sorted array of fragments */ sort( fragments, grouped = false ) { fragments = Array.from( fragments ); let ordered = [], unordered = [], sorted = []; // Group ordered and unordered elements fragments.forEach( fragment => { if( fragment.hasAttribute( 'data-fragment-index' ) ) { let index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 ); if( !ordered[index] ) { ordered[index] = []; } ordered[index].push( fragment ); } else { unordered.push( [ fragment ] ); } } ); // Append fragments without explicit indices in their // DOM order ordered = ordered.concat( unordered ); // Manually count the index up per group to ensure there // are no gaps let index = 0; // Push all fragments in their sorted order to an array, // this flattens the groups ordered.forEach( group => { group.forEach( fragment => { sorted.push( fragment ); fragment.setAttribute( 'data-fragment-index', index ); } ); index ++; } ); return grouped === true ? ordered : sorted; } /** * Sorts and formats all of fragments in the * presentation. */ sortAll() { this.Reveal.getHorizontalSlides().forEach( horizontalSlide => { let verticalSlides = queryAll( horizontalSlide, 'section' ); verticalSlides.forEach( ( verticalSlide, y ) => { this.sort( verticalSlide.querySelectorAll( '.fragment' ) ); }, this ); if( verticalSlides.length === 0 ) this.sort( horizontalSlide.querySelectorAll( '.fragment' ) ); } ); } /** * Refreshes the fragments on the current slide so that they * have the appropriate classes (.visible + .current-fragment). * * @param {number} [index] The index of the current fragment * @param {array} [fragments] Array containing all fragments * in the current slide * * @return {{shown: array, hidden: array}} */ update( index, fragments, slide = this.Reveal.getCurrentSlide() ) { let changedFragments = { shown: [], hidden: [] }; if( slide && this.Reveal.getConfig().fragments ) { fragments = fragments || this.sort( slide.querySelectorAll( '.fragment' ) ); if( fragments.length ) { let maxIndex = 0; if( typeof index !== 'number' ) { let currentFragment = this.sort( slide.querySelectorAll( '.fragment.visible' ) ).pop(); if( currentFragment ) { index = parseInt( currentFragment.getAttribute( 'data-fragment-index' ) || 0, 10 ); } } Array.from( fragments ).forEach( ( el, i ) => { if( el.hasAttribute( 'data-fragment-index' ) ) { i = parseInt( el.getAttribute( 'data-fragment-index' ), 10 ); } maxIndex = Math.max( maxIndex, i ); // Visible fragments if( i <= index ) { let wasVisible = el.classList.contains( 'visible' ) el.classList.add( 'visible' ); el.classList.remove( 'current-fragment' ); if( i === index ) { // Announce the fragments one by one to the Screen Reader this.Reveal.announceStatus( this.Reveal.getStatusText( el ) ); el.classList.add( 'current-fragment' ); this.Reveal.slideContent.startEmbeddedContent( el ); } if( !wasVisible ) { changedFragments.shown.push( el ) this.Reveal.dispatchEvent({ target: el, type: 'visible', bubbles: false }); } } // Hidden fragments else { let wasVisible = el.classList.contains( 'visible' ) el.classList.remove( 'visible' ); el.classList.remove( 'current-fragment' ); if( wasVisible ) { this.Reveal.slideContent.stopEmbeddedContent( el ); changedFragments.hidden.push( el ); this.Reveal.dispatchEvent({ target: el, type: 'hidden', bubbles: false }); } } } ); // Write the current fragment index to the slide <section>. // This can be used by end users to apply styles based on // the current fragment index. index = typeof index === 'number' ? index : -1; index = Math.max( Math.min( index, maxIndex ), -1 ); slide.setAttribute( 'data-fragment', index ); } } if( changedFragments.hidden.length ) { this.Reveal.dispatchEvent({ type: 'fragmenthidden', data: { fragment: changedFragments.hidden[0], fragments: changedFragments.hidden } }); } if( changedFragments.shown.length ) { this.Reveal.dispatchEvent({ type: 'fragmentshown', data: { fragment: changedFragments.shown[0], fragments: changedFragments.shown } }); } return changedFragments; } /** * Formats the fragments on the given slide so that they have * valid indices. Call this if fragments are changed in the DOM * after reveal.js has already initialized. * * @param {HTMLElement} slide * @return {Array} a list of the HTML fragments that were synced */ sync( slide = this.Reveal.getCurrentSlide() ) { return this.sort( slide.querySelectorAll( '.fragment' ) ); } /** * Navigate to the specified slide fragment. * * @param {?number} index The index of the fragment that * should be shown, -1 means all are invisible * @param {number} offset Integer offset to apply to the * fragment index * * @return {boolean} true if a change was made in any * fragments visibility as part of this call */ goto( index, offset = 0 ) { let currentSlide = this.Reveal.getCurrentSlide(); if( currentSlide && this.Reveal.getConfig().fragments ) { let fragments = this.sort( currentSlide.querySelectorAll( '.fragment:not(.disabled)' ) ); if( fragments.length ) { // If no index is specified, find the current if( typeof index !== 'number' ) { let lastVisibleFragment = this.sort( currentSlide.querySelectorAll( '.fragment:not(.disabled).visible' ) ).pop(); if( lastVisibleFragment ) { index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 ); } else { index = -1; } } // Apply the offset if there is one index += offset; let changedFragments = this.update( index, fragments ); this.Reveal.controls.update(); this.Reveal.progress.update(); if( this.Reveal.getConfig().fragmentInURL ) { this.Reveal.location.writeURL(); } return !!( changedFragments.shown.length || changedFragments.hidden.length ); } } return false; } /** * Navigate to the next slide fragment. * * @return {boolean} true if there was a next fragment, * false otherwise */ next() { return this.goto( null, 1 ); } /** * Navigate to the previous slide fragment. * * @return {boolean} true if there was a previous fragment, * false otherwise */ prev() { return this.goto( null, -1 ); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/slidecontent.js
js/controllers/slidecontent.js
import { extend, queryAll, closest, getMimeTypeFromFile, encodeRFC3986URI } from '../utils/util.js' import { isMobile } from '../utils/device.js' import fitty from 'fitty'; /** * Handles loading, unloading and playback of slide * content such as images, videos and iframes. */ export default class SlideContent { allowedToPlayAudio = null; constructor( Reveal ) { this.Reveal = Reveal; this.startEmbeddedMedia = this.startEmbeddedMedia.bind( this ); this.startEmbeddedIframe = this.startEmbeddedIframe.bind( this ); this.preventIframeAutoFocus = this.preventIframeAutoFocus.bind( this ); this.ensureMobileMediaPlaying = this.ensureMobileMediaPlaying.bind( this ); this.failedAudioPlaybackTargets = new Set(); this.failedVideoPlaybackTargets = new Set(); this.failedMutedVideoPlaybackTargets = new Set(); this.renderMediaPlayButton(); } renderMediaPlayButton() { this.mediaPlayButton = document.createElement( 'button' ); this.mediaPlayButton.className = 'r-overlay-button r-media-play-button'; this.mediaPlayButton.addEventListener( 'click', () => { this.resetTemporarilyMutedMedia(); const failedTargets = new Set( [ ...this.failedAudioPlaybackTargets, ...this.failedVideoPlaybackTargets, ...this.failedMutedVideoPlaybackTargets ] ); failedTargets.forEach( target => { this.startEmbeddedMedia( { target: target } ); } ); this.clearMediaPlaybackErrors(); } ); } /** * Should the given element be preloaded? * Decides based on local element attributes and global config. * * @param {HTMLElement} element */ shouldPreload( element ) { if( this.Reveal.isScrollView() ) { return true; } // Prefer an explicit global preload setting let preload = this.Reveal.getConfig().preloadIframes; // If no global setting is available, fall back on the element's // own preload setting if( typeof preload !== 'boolean' ) { preload = element.hasAttribute( 'data-preload' ); } return preload; } /** * Called when the given slide is within the configured view * distance. Shows the slide element and loads any content * that is set to load lazily (data-src). * * @param {HTMLElement} slide Slide to show */ load( slide, options = {} ) { // Show the slide element const displayValue = this.Reveal.getConfig().display; if( displayValue.includes('!important') ) { const value = displayValue.replace(/\s*!important\s*$/, '').trim(); slide.style.setProperty('display', value, 'important'); } else { slide.style.display = displayValue; } // Media and iframe elements with data-src attributes queryAll( slide, 'img[data-src], video[data-src], audio[data-src], iframe[data-src]' ).forEach( element => { const isIframe = element.tagName === 'IFRAME'; if( !isIframe || this.shouldPreload( element ) ) { element.setAttribute( 'src', element.getAttribute( 'data-src' ) ); element.setAttribute( 'data-lazy-loaded', '' ); element.removeAttribute( 'data-src' ); if( isIframe ) { element.addEventListener( 'load', this.preventIframeAutoFocus ); } } } ); // Media elements with <source> children queryAll( slide, 'video, audio' ).forEach( media => { let sources = 0; queryAll( media, 'source[data-src]' ).forEach( source => { source.setAttribute( 'src', source.getAttribute( 'data-src' ) ); source.removeAttribute( 'data-src' ); source.setAttribute( 'data-lazy-loaded', '' ); sources += 1; } ); // Enable inline video playback in mobile Safari if( isMobile && media.tagName === 'VIDEO' ) { media.setAttribute( 'playsinline', '' ); } // If we rewrote sources for this video/audio element, we need // to manually tell it to load from its new origin if( sources > 0 ) { media.load(); } } ); // Show the corresponding background element let background = slide.slideBackgroundElement; if( background ) { background.style.display = 'block'; let backgroundContent = slide.slideBackgroundContentElement; let backgroundIframe = slide.getAttribute( 'data-background-iframe' ); // If the background contains media, load it if( background.hasAttribute( 'data-loaded' ) === false ) { background.setAttribute( 'data-loaded', 'true' ); let backgroundImage = slide.getAttribute( 'data-background-image' ), backgroundVideo = slide.getAttribute( 'data-background-video' ), backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ), backgroundVideoMuted = slide.hasAttribute( 'data-background-video-muted' ); // Images if( backgroundImage ) { // base64 if( /^data:/.test( backgroundImage.trim() ) ) { backgroundContent.style.backgroundImage = `url(${backgroundImage.trim()})`; } // URL(s) else { backgroundContent.style.backgroundImage = backgroundImage.split( ',' ).map( background => { // Decode URL(s) that are already encoded first let decoded = decodeURI(background.trim()); return `url(${encodeRFC3986URI(decoded)})`; }).join( ',' ); } } // Videos else if ( backgroundVideo ) { let video = document.createElement( 'video' ); if( backgroundVideoLoop ) { video.setAttribute( 'loop', '' ); } if( backgroundVideoMuted || this.Reveal.isSpeakerNotes() ) { video.muted = true; } // Enable inline playback in mobile Safari if( isMobile ) { video.setAttribute( 'playsinline', '' ); } // Support comma separated lists of video sources backgroundVideo.split( ',' ).forEach( source => { const sourceElement = document.createElement( 'source' ); sourceElement.setAttribute( 'src', source ); let type = getMimeTypeFromFile( source ); if( type ) { sourceElement.setAttribute( 'type', type ); } video.appendChild( sourceElement ); } ); backgroundContent.appendChild( video ); } // Iframes else if( backgroundIframe && options.excludeIframes !== true ) { let iframe = document.createElement( 'iframe' ); iframe.setAttribute( 'allowfullscreen', '' ); iframe.setAttribute( 'mozallowfullscreen', '' ); iframe.setAttribute( 'webkitallowfullscreen', '' ); iframe.setAttribute( 'allow', 'autoplay' ); iframe.setAttribute( 'data-src', backgroundIframe ); iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.style.maxHeight = '100%'; iframe.style.maxWidth = '100%'; backgroundContent.appendChild( iframe ); } } // Start loading preloadable iframes let backgroundIframeElement = backgroundContent.querySelector( 'iframe[data-src]' ); if( backgroundIframeElement ) { // Check if this iframe is eligible to be preloaded if( this.shouldPreload( background ) && !/autoplay=(1|true|yes)/gi.test( backgroundIframe ) ) { if( backgroundIframeElement.getAttribute( 'src' ) !== backgroundIframe ) { backgroundIframeElement.setAttribute( 'src', backgroundIframe ); } } } } this.layout( slide ); } /** * Applies JS-dependent layout helpers for the scope. */ layout( scopeElement ) { // Autosize text with the r-fit-text class based on the // size of its container. This needs to happen after the // slide is visible in order to measure the text. Array.from( scopeElement.querySelectorAll( '.r-fit-text' ) ).forEach( element => { fitty( element, { minSize: 24, maxSize: this.Reveal.getConfig().height * 0.8, observeMutations: false, observeWindow: false } ); } ); } /** * Unloads and hides the given slide. This is called when the * slide is moved outside of the configured view distance. * * @param {HTMLElement} slide */ unload( slide ) { // Hide the slide element slide.style.display = 'none'; // Hide the corresponding background element let background = this.Reveal.getSlideBackground( slide ); if( background ) { background.style.display = 'none'; // Unload any background iframes queryAll( background, 'iframe[src]' ).forEach( element => { element.removeAttribute( 'src' ); } ); } // Reset lazy-loaded media elements with src attributes queryAll( slide, 'video[data-lazy-loaded][src], audio[data-lazy-loaded][src], iframe[data-lazy-loaded][src]' ).forEach( element => { element.setAttribute( 'data-src', element.getAttribute( 'src' ) ); element.removeAttribute( 'src' ); } ); // Reset lazy-loaded media elements with <source> children queryAll( slide, 'video[data-lazy-loaded] source[src], audio source[src]' ).forEach( source => { source.setAttribute( 'data-src', source.getAttribute( 'src' ) ); source.removeAttribute( 'src' ); } ); } /** * Enforces origin-specific format rules for embedded media. */ formatEmbeddedContent() { let _appendParamToIframeSource = ( sourceAttribute, sourceURL, param ) => { queryAll( this.Reveal.getSlidesElement(), 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ).forEach( el => { let src = el.getAttribute( sourceAttribute ); if( src && src.indexOf( param ) === -1 ) { el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param ); } }); }; // YouTube frames must include "?enablejsapi=1" _appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' ); _appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' ); // Vimeo frames must include "?api=1" _appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' ); _appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' ); } /** * Start playback of any embedded content inside of * the given element. * * @param {HTMLElement} element */ startEmbeddedContent( element ) { if( element ) { const isSpeakerNotesWindow = this.Reveal.isSpeakerNotes(); // Restart GIFs queryAll( element, 'img[src$=".gif"]' ).forEach( el => { // Setting the same unchanged source like this was confirmed // to work in Chrome, FF & Safari el.setAttribute( 'src', el.getAttribute( 'src' ) ); } ); // HTML5 media elements queryAll( element, 'video, audio' ).forEach( el => { if( closest( el, '.fragment' ) && !closest( el, '.fragment.visible' ) ) { return; } // Prefer an explicit global autoplay setting let autoplay = this.Reveal.getConfig().autoPlayMedia; // If no global setting is available, fall back on the element's // own autoplay setting if( typeof autoplay !== 'boolean' ) { autoplay = el.hasAttribute( 'data-autoplay' ) || !!closest( el, '.slide-background' ); } if( autoplay && typeof el.play === 'function' ) { // In the speaker view we only auto-play muted media if( isSpeakerNotesWindow && !el.muted ) return; // If the media is ready, start playback if( el.readyState > 1 ) { this.startEmbeddedMedia( { target: el } ); } // Mobile devices never fire a loaded event so instead // of waiting, we initiate playback else if( isMobile ) { el.addEventListener( 'canplay', this.ensureMobileMediaPlaying ); this.playMediaElement( el ); } // If the media isn't loaded, wait before playing else { el.removeEventListener( 'loadeddata', this.startEmbeddedMedia ); // remove first to avoid dupes el.addEventListener( 'loadeddata', this.startEmbeddedMedia ); } } } ); // Don't play iframe content in the speaker view since we can't // guarantee that it's muted if( !isSpeakerNotesWindow ) { // Normal iframes queryAll( element, 'iframe[src]' ).forEach( el => { if( closest( el, '.fragment' ) && !closest( el, '.fragment.visible' ) ) { return; } this.startEmbeddedIframe( { target: el } ); } ); // Lazy loading iframes queryAll( element, 'iframe[data-src]' ).forEach( el => { if( closest( el, '.fragment' ) && !closest( el, '.fragment.visible' ) ) { return; } if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) { el.removeEventListener( 'load', this.startEmbeddedIframe ); // remove first to avoid dupes el.addEventListener( 'load', this.startEmbeddedIframe ); el.setAttribute( 'src', el.getAttribute( 'data-src' ) ); } } ); } } } /** * Ensure that an HTMLMediaElement is playing on mobile devices. * * This is a workaround for a bug in mobile Safari where * the media fails to display if many videos are started * at the same moment. When this happens, Mobile Safari * reports the video is playing, and the current time * advances, but nothing is visible. * * @param {Event} event */ ensureMobileMediaPlaying( event ) { const el = event.target; // Ignore this check incompatible browsers if( typeof el.getVideoPlaybackQuality !== 'function' ) { return; } setTimeout( () => { const playing = el.paused === false; const totalFrames = el.getVideoPlaybackQuality().totalVideoFrames; if( playing && totalFrames === 0 ) { el.load(); el.play(); } }, 1000 ); } /** * Starts playing an embedded video/audio element after * it has finished loading. * * @param {object} event */ startEmbeddedMedia( event ) { let isAttachedToDOM = !!closest( event.target, 'html' ), isVisible = !!closest( event.target, '.present' ); if( isAttachedToDOM && isVisible ) { // Don't restart if media is already playing if( event.target.paused || event.target.ended ) { event.target.currentTime = 0; this.playMediaElement( event.target ); } } event.target.removeEventListener( 'loadeddata', this.startEmbeddedMedia ); } /** * Plays the given HTMLMediaElement and handles any playback * errors, such as the browser not allowing audio to play without * user action. * * @param {HTMLElement} mediaElement */ playMediaElement( mediaElement ) { const promise = mediaElement.play(); if( promise && typeof promise.catch === 'function' ) { promise .then( () => { if( !mediaElement.muted ) { this.allowedToPlayAudio = true; } } ) .catch( ( error ) => { if( error.name === 'NotAllowedError' ) { this.allowedToPlayAudio = false; // If this is a video, we record the error and try to play it // muted as a fallback. The user will be presented with an unmute // button. if( mediaElement.tagName === 'VIDEO' ) { this.onVideoPlaybackNotAllowed( mediaElement ); let isAttachedToDOM = !!closest( mediaElement, 'html' ), isVisible = !!closest( mediaElement, '.present' ), isMuted = mediaElement.muted; if( isAttachedToDOM && isVisible && !isMuted ) { mediaElement.setAttribute( 'data-muted-by-reveal', 'true' ); mediaElement.muted = true; mediaElement.play().catch(() => { this.onMutedVideoPlaybackNotAllowed( mediaElement ); }); } } else if( mediaElement.tagName === 'AUDIO' ) { this.onAudioPlaybackNotAllowed( mediaElement ); } } } ); } } /** * "Starts" the content of an embedded iframe using the * postMessage API. * * @param {object} event */ startEmbeddedIframe( event ) { let iframe = event.target; this.preventIframeAutoFocus( event ); if( iframe && iframe.contentWindow ) { let isAttachedToDOM = !!closest( event.target, 'html' ), isVisible = !!closest( event.target, '.present' ); if( isAttachedToDOM && isVisible ) { // Prefer an explicit global autoplay setting let autoplay = this.Reveal.getConfig().autoPlayMedia; // If no global setting is available, fall back on the element's // own autoplay setting if( typeof autoplay !== 'boolean' ) { autoplay = iframe.hasAttribute( 'data-autoplay' ) || !!closest( iframe, '.slide-background' ); } // YouTube postMessage API if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && autoplay ) { iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' ); } // Vimeo postMessage API else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && autoplay ) { iframe.contentWindow.postMessage( '{"method":"play"}', '*' ); } // Generic postMessage API else { iframe.contentWindow.postMessage( 'slide:start', '*' ); } } } } /** * Stop playback of any embedded content inside of * the targeted slide. * * @param {HTMLElement} element */ stopEmbeddedContent( element, options = {} ) { options = extend( { // Defaults unloadIframes: true }, options ); if( element && element.parentNode ) { // HTML5 media elements queryAll( element, 'video, audio' ).forEach( el => { if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) { el.setAttribute('data-paused-by-reveal', ''); el.pause(); if( isMobile ) { el.removeEventListener( 'canplay', this.ensureMobileMediaPlaying ); } } } ); // Generic postMessage API for non-lazy loaded iframes queryAll( element, 'iframe' ).forEach( el => { if( el.contentWindow ) el.contentWindow.postMessage( 'slide:stop', '*' ); el.removeEventListener( 'load', this.preventIframeAutoFocus ); el.removeEventListener( 'load', this.startEmbeddedIframe ); }); // YouTube postMessage API queryAll( element, 'iframe[src*="youtube.com/embed/"]' ).forEach( el => { if( !el.hasAttribute( 'data-ignore' ) && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) { el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' ); } }); // Vimeo postMessage API queryAll( element, 'iframe[src*="player.vimeo.com/"]' ).forEach( el => { if( !el.hasAttribute( 'data-ignore' ) && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) { el.contentWindow.postMessage( '{"method":"pause"}', '*' ); } }); if( options.unloadIframes === true ) { // Unload lazy-loaded iframes queryAll( element, 'iframe[data-src]' ).forEach( el => { // Only removing the src doesn't actually unload the frame // in all browsers (Firefox) so we set it to blank first el.setAttribute( 'src', 'about:blank' ); el.removeAttribute( 'src' ); } ); } } } /** * Checks whether media playback is blocked by the browser. This * typically happens when media playback is initiated without a * direct user interaction. */ isAllowedToPlayAudio() { return this.allowedToPlayAudio; } /** * Shows a manual button in situations where autoamtic media playback * is not allowed by the browser. */ showPlayOrUnmuteButton() { const audioTargets = this.failedAudioPlaybackTargets.size; const videoTargets = this.failedVideoPlaybackTargets.size; const mutedVideoTargets = this.failedMutedVideoPlaybackTargets.size; let label = 'Play media'; if( mutedVideoTargets > 0 ) { label = 'Play video'; } else if( videoTargets > 0 ) { label = 'Unmute video'; } else if( audioTargets > 0 ) { label = 'Play audio'; } this.mediaPlayButton.textContent = label; this.Reveal.getRevealElement().appendChild( this.mediaPlayButton ); } onAudioPlaybackNotAllowed( target ) { this.failedAudioPlaybackTargets.add( target ); this.showPlayOrUnmuteButton( target ); } onVideoPlaybackNotAllowed( target ) { this.failedVideoPlaybackTargets.add( target ); this.showPlayOrUnmuteButton(); } onMutedVideoPlaybackNotAllowed( target ) { this.failedMutedVideoPlaybackTargets.add( target ); this.showPlayOrUnmuteButton(); } /** * Videos may be temporarily muted by us to get around browser * restrictions on automatic playback. This method rolls back * all such temporary audio changes. */ resetTemporarilyMutedMedia() { const failedTargets = new Set( [ ...this.failedAudioPlaybackTargets, ...this.failedVideoPlaybackTargets, ...this.failedMutedVideoPlaybackTargets ] ); failedTargets.forEach( target => { if( target.hasAttribute( 'data-muted-by-reveal' ) ) { target.muted = false; target.removeAttribute( 'data-muted-by-reveal' ); } } ); } clearMediaPlaybackErrors() { this.resetTemporarilyMutedMedia(); this.failedAudioPlaybackTargets.clear(); this.failedVideoPlaybackTargets.clear(); this.failedMutedVideoPlaybackTargets.clear(); this.mediaPlayButton.remove(); } /** * Prevents iframes from automatically focusing themselves. * * @param {Event} event */ preventIframeAutoFocus( event ) { const iframe = event.target; if( iframe && this.Reveal.getConfig().preventIframeAutoFocus ) { let elapsed = 0; const interval = 100; const maxTime = 1000; const checkFocus = () => { if( document.activeElement === iframe ) { document.activeElement.blur(); } else if( elapsed < maxTime ) { elapsed += interval; setTimeout( checkFocus, interval ); } }; setTimeout( checkFocus, interval ); } } afterSlideChanged() { this.clearMediaPlaybackErrors(); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/keyboard.js
js/controllers/keyboard.js
import { enterFullscreen } from '../utils/util.js' /** * Handles all reveal.js keyboard interactions. */ export default class Keyboard { constructor( Reveal ) { this.Reveal = Reveal; // A key:value map of keyboard keys and descriptions of // the actions they trigger this.shortcuts = {}; // Holds custom key code mappings this.bindings = {}; this.onDocumentKeyDown = this.onDocumentKeyDown.bind( this ); } /** * Called when the reveal.js config is updated. */ configure( config, oldConfig ) { if( config.navigationMode === 'linear' ) { this.shortcuts['&#8594; , &#8595; , SPACE , N , L , J'] = 'Next slide'; this.shortcuts['&#8592; , &#8593; , P , H , K'] = 'Previous slide'; } else { this.shortcuts['N , SPACE'] = 'Next slide'; this.shortcuts['P , Shift SPACE'] = 'Previous slide'; this.shortcuts['&#8592; , H'] = 'Navigate left'; this.shortcuts['&#8594; , L'] = 'Navigate right'; this.shortcuts['&#8593; , K'] = 'Navigate up'; this.shortcuts['&#8595; , J'] = 'Navigate down'; } this.shortcuts['Alt + &#8592;/&#8593/&#8594;/&#8595;'] = 'Navigate without fragments'; this.shortcuts['Shift + &#8592;/&#8593/&#8594;/&#8595;'] = 'Jump to first/last slide'; this.shortcuts['B , .'] = 'Pause'; this.shortcuts['F'] = 'Fullscreen'; this.shortcuts['G'] = 'Jump to slide'; this.shortcuts['ESC, O'] = 'Slide overview'; } /** * Starts listening for keyboard events. */ bind() { document.addEventListener( 'keydown', this.onDocumentKeyDown, false ); } /** * Stops listening for keyboard events. */ unbind() { document.removeEventListener( 'keydown', this.onDocumentKeyDown, false ); } /** * Add a custom key binding with optional description to * be added to the help screen. */ addKeyBinding( binding, callback ) { if( typeof binding === 'object' && binding.keyCode ) { this.bindings[binding.keyCode] = { callback: callback, key: binding.key, description: binding.description }; } else { this.bindings[binding] = { callback: callback, key: null, description: null }; } } /** * Removes the specified custom key binding. */ removeKeyBinding( keyCode ) { delete this.bindings[keyCode]; } /** * Programmatically triggers a keyboard event * * @param {int} keyCode */ triggerKey( keyCode ) { this.onDocumentKeyDown( { keyCode } ); } /** * Registers a new shortcut to include in the help overlay * * @param {String} key * @param {String} value */ registerKeyboardShortcut( key, value ) { this.shortcuts[key] = value; } getShortcuts() { return this.shortcuts; } getBindings() { return this.bindings; } /** * Handler for the document level 'keydown' event. * * @param {object} event */ onDocumentKeyDown( event ) { let config = this.Reveal.getConfig(); // If there's a condition specified and it returns false, // ignore this event if( typeof config.keyboardCondition === 'function' && config.keyboardCondition(event) === false ) { return true; } // If keyboardCondition is set, only capture keyboard events // for embedded decks when they are focused if( config.keyboardCondition === 'focused' && !this.Reveal.isFocused() ) { return true; } // Shorthand let keyCode = event.keyCode; // Remember if auto-sliding was paused so we can toggle it let autoSlideWasPaused = !this.Reveal.isAutoSliding(); this.Reveal.onUserInput( event ); // Is there a focused element that could be using the keyboard? let activeElementIsCE = document.activeElement && document.activeElement.isContentEditable === true; let activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test( document.activeElement.tagName ); let activeElementIsNotes = document.activeElement && document.activeElement.className && /speaker-notes/i.test( document.activeElement.className); // Whitelist certain modifiers for slide navigation shortcuts let keyCodeUsesModifier = [32, 37, 38, 39, 40, 63, 78, 80, 191].indexOf( event.keyCode ) !== -1; // Prevent all other events when a modifier is pressed let unusedModifier = !( keyCodeUsesModifier && event.shiftKey || event.altKey ) && ( event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ); // Disregard the event if there's a focused element or a // keyboard modifier key is present if( activeElementIsCE || activeElementIsInput || activeElementIsNotes || unusedModifier ) return; // While paused only allow resume keyboard events; 'b', 'v', '.' let resumeKeyCodes = [66,86,190,191,112]; let key; // Custom key bindings for togglePause should be able to resume if( typeof config.keyboard === 'object' ) { for( key in config.keyboard ) { if( config.keyboard[key] === 'togglePause' ) { resumeKeyCodes.push( parseInt( key, 10 ) ); } } } if( this.Reveal.isOverlayOpen() && !["Escape", "f", "c", "b", "."].includes(event.key) ) { return false; } if( this.Reveal.isPaused() && resumeKeyCodes.indexOf( keyCode ) === -1 ) { return false; } // Use linear navigation if we're configured to OR if // the presentation is one-dimensional let useLinearMode = config.navigationMode === 'linear' || !this.Reveal.hasHorizontalSlides() || !this.Reveal.hasVerticalSlides(); let triggered = false; // 1. User defined key bindings if( typeof config.keyboard === 'object' ) { for( key in config.keyboard ) { // Check if this binding matches the pressed key if( parseInt( key, 10 ) === keyCode ) { let value = config.keyboard[ key ]; // Callback function if( typeof value === 'function' ) { value.apply( null, [ event ] ); } // String shortcuts to reveal.js API else if( typeof value === 'string' && typeof this.Reveal[ value ] === 'function' ) { this.Reveal[ value ].call(); } triggered = true; } } } // 2. Registered custom key bindings if( triggered === false ) { for( key in this.bindings ) { // Check if this binding matches the pressed key if( parseInt( key, 10 ) === keyCode ) { let action = this.bindings[ key ].callback; // Callback function if( typeof action === 'function' ) { action.apply( null, [ event ] ); } // String shortcuts to reveal.js API else if( typeof action === 'string' && typeof this.Reveal[ action ] === 'function' ) { this.Reveal[ action ].call(); } triggered = true; } } } // 3. System defined key bindings if( triggered === false ) { // Assume true and try to prove false triggered = true; // P, PAGE UP if( keyCode === 80 || keyCode === 33 ) { this.Reveal.prev({skipFragments: event.altKey}); } // N, PAGE DOWN else if( keyCode === 78 || keyCode === 34 ) { this.Reveal.next({skipFragments: event.altKey}); } // H, LEFT else if( keyCode === 72 || keyCode === 37 ) { if( event.shiftKey ) { this.Reveal.slide( 0 ); } else if( !this.Reveal.overview.isActive() && useLinearMode ) { if( config.rtl ) { this.Reveal.next({skipFragments: event.altKey}); } else { this.Reveal.prev({skipFragments: event.altKey}); } } else { this.Reveal.left({skipFragments: event.altKey}); } } // L, RIGHT else if( keyCode === 76 || keyCode === 39 ) { if( event.shiftKey ) { this.Reveal.slide( this.Reveal.getHorizontalSlides().length - 1 ); } else if( !this.Reveal.overview.isActive() && useLinearMode ) { if( config.rtl ) { this.Reveal.prev({skipFragments: event.altKey}); } else { this.Reveal.next({skipFragments: event.altKey}); } } else { this.Reveal.right({skipFragments: event.altKey}); } } // K, UP else if( keyCode === 75 || keyCode === 38 ) { if( event.shiftKey ) { this.Reveal.slide( undefined, 0 ); } else if( !this.Reveal.overview.isActive() && useLinearMode ) { this.Reveal.prev({skipFragments: event.altKey}); } else { this.Reveal.up({skipFragments: event.altKey}); } } // J, DOWN else if( keyCode === 74 || keyCode === 40 ) { if( event.shiftKey ) { this.Reveal.slide( undefined, Number.MAX_VALUE ); } else if( !this.Reveal.overview.isActive() && useLinearMode ) { this.Reveal.next({skipFragments: event.altKey}); } else { this.Reveal.down({skipFragments: event.altKey}); } } // HOME else if( keyCode === 36 ) { this.Reveal.slide( 0 ); } // END else if( keyCode === 35 ) { this.Reveal.slide( this.Reveal.getHorizontalSlides().length - 1 ); } // SPACE else if( keyCode === 32 ) { if( this.Reveal.overview.isActive() ) { this.Reveal.overview.deactivate(); } if( event.shiftKey ) { this.Reveal.prev({skipFragments: event.altKey}); } else { this.Reveal.next({skipFragments: event.altKey}); } } // TWO-SPOT, SEMICOLON, B, V, PERIOD, LOGITECH PRESENTER TOOLS "BLACK SCREEN" BUTTON else if( [58, 59, 66, 86, 190].includes( keyCode ) || ( keyCode === 191 && !event.shiftKey ) ) { this.Reveal.togglePause(); } // F else if( keyCode === 70 ) { enterFullscreen( config.embedded ? this.Reveal.getViewportElement() : document.documentElement ); } // A else if( keyCode === 65 ) { if( config.autoSlideStoppable ) { this.Reveal.toggleAutoSlide( autoSlideWasPaused ); } } // G else if( keyCode === 71 ) { if( config.jumpToSlide ) { this.Reveal.toggleJumpToSlide(); } } // C else if( keyCode === 67 && this.Reveal.isOverlayOpen() ) { this.Reveal.closeOverlay(); } // ? else if( ( keyCode === 63 || keyCode === 191 ) && event.shiftKey ) { this.Reveal.toggleHelp(); } // F1 else if( keyCode === 112 ) { this.Reveal.toggleHelp(); } else { triggered = false; } } // If the input resulted in a triggered action we should prevent // the browsers default behavior if( triggered ) { event.preventDefault && event.preventDefault(); } // ESC or O key else if( keyCode === 27 || keyCode === 79 ) { if( this.Reveal.closeOverlay() === false ) { this.Reveal.overview.toggle(); } event.preventDefault && event.preventDefault(); } // Enter to exit overview mode else if (keyCode === 13 && this.Reveal.overview.isActive()) { this.Reveal.overview.deactivate(); event.preventDefault && event.preventDefault(); } // If auto-sliding is enabled we need to cue up // another timeout this.Reveal.cueAutoSlide(); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/controllers/notes.js
js/controllers/notes.js
/** * Handles the showing of speaker notes */ export default class Notes { constructor( Reveal ) { this.Reveal = Reveal; } render() { this.element = document.createElement( 'div' ); this.element.className = 'speaker-notes'; this.element.setAttribute( 'data-prevent-swipe', '' ); this.element.setAttribute( 'tabindex', '0' ); this.Reveal.getRevealElement().appendChild( this.element ); } /** * Called when the reveal.js config is updated. */ configure( config, oldConfig ) { if( config.showNotes ) { this.element.setAttribute( 'data-layout', typeof config.showNotes === 'string' ? config.showNotes : 'inline' ); } } /** * Pick up notes from the current slide and display them * to the viewer. * * @see {@link config.showNotes} */ update() { if( this.Reveal.getConfig().showNotes && this.element && this.Reveal.getCurrentSlide() && !this.Reveal.isScrollView() && !this.Reveal.isPrintView() ) { this.element.innerHTML = this.getSlideNotes() || '<span class="notes-placeholder">No notes on this slide.</span>'; } } /** * Updates the visibility of the speaker notes sidebar that * is used to share annotated slides. The notes sidebar is * only visible if showNotes is true and there are notes on * one or more slides in the deck. */ updateVisibility() { if( this.Reveal.getConfig().showNotes && this.hasNotes() && !this.Reveal.isScrollView() && !this.Reveal.isPrintView() ) { this.Reveal.getRevealElement().classList.add( 'show-notes' ); } else { this.Reveal.getRevealElement().classList.remove( 'show-notes' ); } } /** * Checks if there are speaker notes for ANY slide in the * presentation. */ hasNotes() { return this.Reveal.getSlidesElement().querySelectorAll( '[data-notes], aside.notes' ).length > 0; } /** * Checks if this presentation is running inside of the * speaker notes window. * * @return {boolean} */ isSpeakerNotesWindow() { return !!window.location.search.match( /receiver/gi ); } /** * Retrieves the speaker notes from a slide. Notes can be * defined in two ways: * 1. As a data-notes attribute on the slide <section> * 2. With <aside class="notes"> elements inside the slide * * @param {HTMLElement} [slide=currentSlide] * @return {(string|null)} */ getSlideNotes( slide = this.Reveal.getCurrentSlide() ) { // Notes can be specified via the data-notes attribute... if( slide.hasAttribute( 'data-notes' ) ) { return slide.getAttribute( 'data-notes' ); } // ... or using <aside class="notes"> elements let notesElements = slide.querySelectorAll( 'aside.notes' ); if( notesElements ) { return Array.from(notesElements).map( notesElement => notesElement.innerHTML ).join( '\n' ); } return null; } destroy() { this.element.remove(); } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/components/playback.js
js/components/playback.js
/** * UI component that lets the use control auto-slide * playback via play/pause. */ export default class Playback { /** * @param {HTMLElement} container The component will append * itself to this * @param {function} progressCheck A method which will be * called frequently to get the current playback progress on * a range of 0-1 */ constructor( container, progressCheck ) { // Cosmetics this.diameter = 100; this.diameter2 = this.diameter/2; this.thickness = 6; // Flags if we are currently playing this.playing = false; // Current progress on a 0-1 range this.progress = 0; // Used to loop the animation smoothly this.progressOffset = 1; this.container = container; this.progressCheck = progressCheck; this.canvas = document.createElement( 'canvas' ); this.canvas.className = 'playback'; this.canvas.width = this.diameter; this.canvas.height = this.diameter; this.canvas.style.width = this.diameter2 + 'px'; this.canvas.style.height = this.diameter2 + 'px'; this.context = this.canvas.getContext( '2d' ); this.container.appendChild( this.canvas ); this.render(); } setPlaying( value ) { const wasPlaying = this.playing; this.playing = value; // Start repainting if we weren't already if( !wasPlaying && this.playing ) { this.animate(); } else { this.render(); } } animate() { const progressBefore = this.progress; this.progress = this.progressCheck(); // When we loop, offset the progress so that it eases // smoothly rather than immediately resetting if( progressBefore > 0.8 && this.progress < 0.2 ) { this.progressOffset = this.progress; } this.render(); if( this.playing ) { requestAnimationFrame( this.animate.bind( this ) ); } } /** * Renders the current progress and playback state. */ render() { let progress = this.playing ? this.progress : 0, radius = ( this.diameter2 ) - this.thickness, x = this.diameter2, y = this.diameter2, iconSize = 28; // Ease towards 1 this.progressOffset += ( 1 - this.progressOffset ) * 0.1; const endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) ); const startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) ); this.context.save(); this.context.clearRect( 0, 0, this.diameter, this.diameter ); // Solid background color this.context.beginPath(); this.context.arc( x, y, radius + 4, 0, Math.PI * 2, false ); this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )'; this.context.fill(); // Draw progress track this.context.beginPath(); this.context.arc( x, y, radius, 0, Math.PI * 2, false ); this.context.lineWidth = this.thickness; this.context.strokeStyle = 'rgba( 255, 255, 255, 0.2 )'; this.context.stroke(); if( this.playing ) { // Draw progress on top of track this.context.beginPath(); this.context.arc( x, y, radius, startAngle, endAngle, false ); this.context.lineWidth = this.thickness; this.context.strokeStyle = '#fff'; this.context.stroke(); } this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) ); // Draw play/pause icons if( this.playing ) { this.context.fillStyle = '#fff'; this.context.fillRect( 0, 0, iconSize / 2 - 4, iconSize ); this.context.fillRect( iconSize / 2 + 4, 0, iconSize / 2 - 4, iconSize ); } else { this.context.beginPath(); this.context.translate( 4, 0 ); this.context.moveTo( 0, 0 ); this.context.lineTo( iconSize - 4, iconSize / 2 ); this.context.lineTo( 0, iconSize ); this.context.fillStyle = '#fff'; this.context.fill(); } this.context.restore(); } on( type, listener ) { this.canvas.addEventListener( type, listener, false ); } off( type, listener ) { this.canvas.removeEventListener( type, listener, false ); } destroy() { this.playing = false; if( this.canvas.parentNode ) { this.container.removeChild( this.canvas ); } } }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/utils/loader.js
js/utils/loader.js
/** * Loads a JavaScript file from the given URL and executes it. * * @param {string} url Address of the .js file to load * @param {function} callback Method to invoke when the script * has loaded and executed */ export const loadScript = ( url, callback ) => { const script = document.createElement( 'script' ); script.type = 'text/javascript'; script.async = false; script.defer = false; script.src = url; if( typeof callback === 'function' ) { // Success callback script.onload = script.onreadystatechange = event => { if( event.type === 'load' || /loaded|complete/.test( script.readyState ) ) { // Kill event listeners script.onload = script.onreadystatechange = script.onerror = null; callback(); } }; // Error callback script.onerror = err => { // Kill event listeners script.onload = script.onreadystatechange = script.onerror = null; callback( new Error( 'Failed loading script: ' + script.src + '\n' + err ) ); }; } // Append the script at the end of <head> const head = document.querySelector( 'head' ); head.insertBefore( script, head.lastChild ); }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/utils/constants.js
js/utils/constants.js
export const SLIDES_SELECTOR = '.slides section'; export const HORIZONTAL_SLIDES_SELECTOR = '.slides>section'; export const VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section'; export const HORIZONTAL_BACKGROUNDS_SELECTOR = '.backgrounds>.slide-background'; // Methods that may not be invoked via the postMessage API export const POST_MESSAGE_METHOD_BLACKLIST = /registerPlugin|registerKeyboardShortcut|addKeyBinding|addEventListener|showPreview/; // Regex for retrieving the fragment style from a class attribute export const FRAGMENT_STYLE_REGEX = /fade-(down|up|right|left|out|in-then-out|in-then-semi-out)|semi-fade-out|current-visible|shrink|grow/; // Slide number formats export const SLIDE_NUMBER_FORMAT_HORIZONTAL_DOT_VERTICAL = 'h.v'; export const SLIDE_NUMBER_FORMAT_HORIZONTAL_SLASH_VERTICAL = 'h/v'; export const SLIDE_NUMBER_FORMAT_CURRENT = 'c'; export const SLIDE_NUMBER_FORMAT_CURRENT_SLASH_TOTAL = 'c/t';
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/utils/color.js
js/utils/color.js
/** * Converts various color input formats to an {r:0,g:0,b:0} object. * * @param {string} color The string representation of a color * @example * colorToRgb('#000'); * @example * colorToRgb('#000000'); * @example * colorToRgb('rgb(0,0,0)'); * @example * colorToRgb('rgba(0,0,0)'); * * @return {{r: number, g: number, b: number, [a]: number}|null} */ export const colorToRgb = ( color ) => { let hex3 = color.match( /^#([0-9a-f]{3})$/i ); if( hex3 && hex3[1] ) { hex3 = hex3[1]; return { r: parseInt( hex3.charAt( 0 ), 16 ) * 0x11, g: parseInt( hex3.charAt( 1 ), 16 ) * 0x11, b: parseInt( hex3.charAt( 2 ), 16 ) * 0x11 }; } let hex6 = color.match( /^#([0-9a-f]{6})$/i ); if( hex6 && hex6[1] ) { hex6 = hex6[1]; return { r: parseInt( hex6.slice( 0, 2 ), 16 ), g: parseInt( hex6.slice( 2, 4 ), 16 ), b: parseInt( hex6.slice( 4, 6 ), 16 ) }; } let rgb = color.match( /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i ); if( rgb ) { return { r: parseInt( rgb[1], 10 ), g: parseInt( rgb[2], 10 ), b: parseInt( rgb[3], 10 ) }; } let rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i ); if( rgba ) { return { r: parseInt( rgba[1], 10 ), g: parseInt( rgba[2], 10 ), b: parseInt( rgba[3], 10 ), a: parseFloat( rgba[4] ) }; } return null; } /** * Calculates brightness on a scale of 0-255. * * @param {string} color See colorToRgb for supported formats. * @see {@link colorToRgb} */ export const colorBrightness = ( color ) => { if( typeof color === 'string' ) color = colorToRgb( color ); if( color ) { return ( color.r * 299 + color.g * 587 + color.b * 114 ) / 1000; } return null; }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/utils/device.js
js/utils/device.js
const UA = navigator.userAgent; export const isMobile = /(iphone|ipod|ipad|android)/gi.test( UA ) || ( navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 ); // iPadOS export const isChrome = /chrome/i.test( UA ) && !/edge/i.test( UA ); export const isAndroid = /android/gi.test( UA );
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/js/utils/util.js
js/utils/util.js
/** * Extend object a with the properties of object b. * If there's a conflict, object b takes precedence. * * @param {object} a * @param {object} b */ export const extend = ( a, b ) => { for( let i in b ) { a[ i ] = b[ i ]; } return a; } /** * querySelectorAll but returns an Array. */ export const queryAll = ( el, selector ) => { return Array.from( el.querySelectorAll( selector ) ); } /** * classList.toggle() with cross browser support */ export const toggleClass = ( el, className, value ) => { if( value ) { el.classList.add( className ); } else { el.classList.remove( className ); } } /** * Utility for deserializing a value. * * @param {*} value * @return {*} */ export const deserialize = ( value ) => { if( typeof value === 'string' ) { if( value === 'null' ) return null; else if( value === 'true' ) return true; else if( value === 'false' ) return false; else if( value.match( /^-?[\d\.]+$/ ) ) return parseFloat( value ); } return value; } /** * Measures the distance in pixels between point a * and point b. * * @param {object} a point with x/y properties * @param {object} b point with x/y properties * * @return {number} */ export const distanceBetween = ( a, b ) => { let dx = a.x - b.x, dy = a.y - b.y; return Math.sqrt( dx*dx + dy*dy ); } /** * Applies a CSS transform to the target element. * * @param {HTMLElement} element * @param {string} transform */ export const transformElement = ( element, transform ) => { element.style.transform = transform; } /** * Element.matches with IE support. * * @param {HTMLElement} target The element to match * @param {String} selector The CSS selector to match * the element against * * @return {Boolean} */ export const matches = ( target, selector ) => { let matchesMethod = target.matches || target.matchesSelector || target.msMatchesSelector; return !!( matchesMethod && matchesMethod.call( target, selector ) ); } /** * Find the closest parent that matches the given * selector. * * @param {HTMLElement} target The child element * @param {String} selector The CSS selector to match * the parents against * * @return {HTMLElement} The matched parent or null * if no matching parent was found */ export const closest = ( target, selector ) => { // Native Element.closest if( typeof target.closest === 'function' ) { return target.closest( selector ); } // Polyfill while( target ) { if( matches( target, selector ) ) { return target; } // Keep searching target = target.parentNode; } return null; } /** * Handling the fullscreen functionality via the fullscreen API * * @see http://fullscreen.spec.whatwg.org/ * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode */ export const enterFullscreen = element => { element = element || document.documentElement; // Check which implementation is available let requestMethod = element.requestFullscreen || element.webkitRequestFullscreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullscreen; if( requestMethod ) { requestMethod.apply( element ); } } /** * Creates an HTML element and returns a reference to it. * If the element already exists the existing instance will * be returned. * * @param {HTMLElement} container * @param {string} tagname * @param {string} classname * @param {string} innerHTML * * @return {HTMLElement} */ export const createSingletonNode = ( container, tagname, classname, innerHTML='' ) => { // Find all nodes matching the description let nodes = container.querySelectorAll( '.' + classname ); // Check all matches to find one which is a direct child of // the specified container for( let i = 0; i < nodes.length; i++ ) { let testNode = nodes[i]; if( testNode.parentNode === container ) { return testNode; } } // If no node was found, create it now let node = document.createElement( tagname ); node.className = classname; node.innerHTML = innerHTML; container.appendChild( node ); return node; } /** * Injects the given CSS styles into the DOM. * * @param {string} value */ export const createStyleSheet = ( value ) => { let tag = document.createElement( 'style' ); tag.type = 'text/css'; if( value && value.length > 0 ) { if( tag.styleSheet ) { tag.styleSheet.cssText = value; } else { tag.appendChild( document.createTextNode( value ) ); } } document.head.appendChild( tag ); return tag; } /** * Returns a key:value hash of all query params. */ export const getQueryHash = () => { let query = {}; location.search.replace( /[A-Z0-9]+?=([\w\.%-]*)/gi, a => { query[ a.split( '=' ).shift() ] = a.split( '=' ).pop(); } ); // Basic deserialization for( let i in query ) { let value = query[ i ]; query[ i ] = deserialize( unescape( value ) ); } // Do not accept new dependencies via query config to avoid // the potential of malicious script injection if( typeof query['dependencies'] !== 'undefined' ) delete query['dependencies']; return query; } /** * Returns the remaining height within the parent of the * target element. * * remaining height = [ configured parent height ] - [ current parent height ] * * @param {HTMLElement} element * @param {number} [height] */ export const getRemainingHeight = ( element, height = 0 ) => { if( element ) { let newHeight, oldHeight = element.style.height; // Change the .stretch element height to 0 in order find the height of all // the other elements element.style.height = '0px'; // In Overview mode, the parent (.slide) height is set of 700px. // Restore it temporarily to its natural height. element.parentNode.style.height = 'auto'; newHeight = height - element.parentNode.offsetHeight; // Restore the old height, just in case element.style.height = oldHeight + 'px'; // Clear the parent (.slide) height. .removeProperty works in IE9+ element.parentNode.style.removeProperty('height'); return newHeight; } return height; } const fileExtensionToMimeMap = { 'mp4': 'video/mp4', 'm4a': 'video/mp4', 'ogv': 'video/ogg', 'mpeg': 'video/mpeg', 'webm': 'video/webm' } /** * Guess the MIME type for common file formats. */ export const getMimeTypeFromFile = ( filename='' ) => { return fileExtensionToMimeMap[filename.split('.').pop()] } /** * Encodes a string for RFC3986-compliant URL format. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI#encoding_for_rfc3986 * * @param {string} url */ export const encodeRFC3986URI = ( url='' ) => { return encodeURI(url) .replace(/%5B/g, "[") .replace(/%5D/g, "]") .replace( /[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}` ); }
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
false
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/dist/reveal.esm.js
dist/reveal.esm.js
/*! * reveal.js 5.2.1 * https://revealjs.com * MIT licensed * * Copyright (C) 2011-2024 Hakim El Hattab, https://hakim.se */
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
true
hakimel/reveal.js
https://github.com/hakimel/reveal.js/blob/33bfe3b233f1a840cd70e834b609ec6f04494a40/dist/reveal.js
dist/reveal.js
/*! * reveal.js 5.2.1 * https://revealjs.com * MIT licensed * * Copyright (C) 2011-2024 Hakim El Hattab, https://hakim.se */
javascript
MIT
33bfe3b233f1a840cd70e834b609ec6f04494a40
2026-01-04T14:56:49.642425Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/eslint.config.js
eslint.config.js
import jqueryConfig from "eslint-config-jquery"; import importPlugin from "eslint-plugin-import"; import globals from "globals"; export default [ { // Only global ignores will bypass the parser // and avoid JS parsing errors // See https://github.com/eslint/eslint/discussions/17412 ignores: [ "external", "tmp", "test/data/json_obj.js", "test/data/jquery-*.js" ] }, // Source { files: [ "src/**" ], plugins: { import: importPlugin }, languageOptions: { ecmaVersion: 2015, // The browser env is not enabled on purpose so that code takes // all browser-only globals from window instead of assuming // they're available as globals. This makes it possible to use // jQuery with tools like jsdom which provide a custom window // implementation. globals: { window: false } }, rules: { ...jqueryConfig.rules, "import/extensions": [ "error", "always" ], "import/no-cycle": "error", // TODO: Enable this rule when eslint-plugin-import supports // it when using flat config. // See https://github.com/import-js/eslint-plugin-import/issues/2556 // "import/no-unused-modules": [ // "error", // { // unusedExports: true, // // When run via WebStorm, the root path against which these paths // // are resolved is the path where this ESLint config file lies, // // i.e. `src`. When run via the command line, it's usually the root // // folder of the jQuery repository. This pattern intends to catch both. // // Note that we cannot specify two patterns here: // // [ "src/*.js", "*.js" ] // // as they're analyzed individually and the rule crashes if a pattern // // cannot be matched. // ignoreExports: [ "{src/,}*.js" ] // } // ], indent: [ "error", "tab" ], "no-implicit-globals": "error", "no-unused-vars": [ "error", { caughtErrorsIgnorePattern: "^_" } ], "one-var": [ "error", { var: "always" } ], strict: [ "error", "function" ] } }, { files: [ "src/wrapper.js", "src/wrapper-esm.js", "src/wrapper-factory.js", "src/wrapper-factory-esm.js" ], languageOptions: { globals: { jQuery: false } }, rules: { "no-unused-vars": "off", indent: [ "error", "tab", { // This makes it so code within the wrapper is not indented. ignoredNodes: [ "Program > FunctionDeclaration > *" ] } ] } }, { files: [ "src/wrapper.js", "src/wrapper-factory.js" ], languageOptions: { sourceType: "script", globals: { module: false } } }, { files: [ "src/wrapper.js" ], rules: { indent: [ "error", "tab", { // This makes it so code within the wrapper is not indented. ignoredNodes: [ "Program > ExpressionStatement > CallExpression > :last-child > *" ] } ] } }, { files: [ "src/exports/amd.js" ], languageOptions: { globals: { define: false } } }, // Tests { files: [ "test/*", "test/data/**", "test/integration/**", "test/unit/**" ], ignores: [ "test/data/badcall.js", "test/data/badjson.js", "test/data/support/csp.js", "test/data/support/getComputedSupport.js", "test/data/core/jquery-iterability-transpiled.js" ], languageOptions: { ecmaVersion: 5, sourceType: "script", globals: { ...globals.browser, require: false, Promise: false, Symbol: false, trustedTypes: false, QUnit: false, ajaxTest: false, testIframe: false, createDashboardXML: false, createWithFriesXML: false, createXMLFragment: false, includesModule: false, moduleTeardown: false, url: false, q: false, jQuery: false, $: false, sinon: false, amdDefined: false, fireNative: false, Globals: false, hasPHP: false, isLocal: false, supportjQuery: false, originaljQuery: false, original$: false, baseURL: false, externalHost: false } }, rules: { ...jqueryConfig.rules, "no-unused-vars": [ "error", { args: "after-used", argsIgnorePattern: "^_" } ], // Too many errors "max-len": "off", camelcase: "off" } }, { files: [ "test/unit/core.js" ], rules: { // Core has several cases where unused vars are expected "no-unused-vars": "off" } }, { files: [ "test/runner/**/*.js" ], languageOptions: { ecmaVersion: "latest", globals: { ...globals.node } }, rules: { ...jqueryConfig.rules } }, { files: [ "test/runner/listeners.js" ], languageOptions: { ecmaVersion: 5, sourceType: "script", globals: { ...globals.browser, QUnit: false, Symbol: false } } }, { files: [ "test/data/testinit.js", "test/data/testrunner.js", "test/data/core/jquery-iterability-transpiled-es6.js" ], languageOptions: { ecmaVersion: 2015, sourceType: "script", globals: { ...globals.browser } }, rules: { ...jqueryConfig.rules, strict: [ "error", "function" ] } }, { files: [ "test/data/testinit.js" ], rules: { strict: [ "error", "global" ] } }, { files: [ "test/unit/deferred.js" ], rules: { // Deferred tests set strict mode for certain tests strict: "off" } }, { files: [ "eslint.config.js", ".release-it.cjs", "build/**", "test/node_smoke_tests/**", "test/bundler_smoke_tests/**/*", "test/promises_aplus_adapters/**", "test/middleware-mockserver.cjs" ], languageOptions: { ecmaVersion: "latest", globals: { ...globals.browser, ...globals.node } }, rules: { ...jqueryConfig.rules, "no-implicit-globals": "error", "no-unused-vars": [ "error", { caughtErrorsIgnorePattern: "^_" } ], strict: [ "error", "global" ] } }, { files: [ "dist/jquery.js", "dist/jquery.slim.js", "dist/jquery.factory.js", "dist/jquery.factory.slim.js", "dist-module/jquery.module.js", "dist-module/jquery.slim.module.js", "dist-module/jquery.factory.module.js", "dist-module/jquery.factory.slim.module.js", "dist/wrappers/*.js", "dist-module/wrappers/*.js" ], languageOptions: { ecmaVersion: 2015, globals: { define: false, module: false, Symbol: false, window: false } }, rules: { ...jqueryConfig.rules, "no-implicit-globals": "error", // That is okay for the built version "no-multiple-empty-lines": "off", "no-unused-vars": [ "error", { caughtErrorsIgnorePattern: "^_" } ], // When custom compilation is used, the version string // can get large. Accept that in the built version. "max-len": "off", "one-var": "off" } }, { files: [ "dist/jquery.slim.js", "dist/jquery.factory.slim.js", "dist-module/jquery.slim.module.js", "dist-module/jquery.factory.slim.module.js" ], rules: { // Rollup is now smart enough to remove the use // of parameters if the argument is not passed // anywhere in the build. // The removal of effects in the slim build // results in some parameters not being used, // which can be safely ignored. "no-unused-vars": [ "error", { args: "none" } ] } }, { files: [ "src/wrapper.js", "src/wrapper-factory.js", "dist/jquery.factory.js", "dist/jquery.factory.slim.js", "test/middleware-mockserver.cjs" ], rules: { "no-implicit-globals": "off" } }, { files: [ "dist/**" ], languageOptions: { ecmaVersion: 5, sourceType: "script" } }, { files: [ "dist-module/**" ], languageOptions: { ecmaVersion: 2015, sourceType: "module" } }, { files: [ "dist/wrappers/*.js" ], languageOptions: { ecmaVersion: 2015, sourceType: "commonjs" } } ];
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/effects.js
src/effects.js
import { jQuery } from "./core.js"; import { document } from "./var/document.js"; import { rcssNum } from "./var/rcssNum.js"; import { rnothtmlwhite } from "./var/rnothtmlwhite.js"; import { cssExpand } from "./css/var/cssExpand.js"; import { isHiddenWithinTree } from "./css/var/isHiddenWithinTree.js"; import { adjustCSS } from "./css/adjustCSS.js"; import { cssCamelCase } from "./css/cssCamelCase.js"; import { dataPriv } from "./data/var/dataPriv.js"; import { showHide } from "./css/showHide.js"; import "./core/init.js"; import "./queue.js"; import "./deferred.js"; import "./traversing.js"; import "./manipulation.js"; import "./css.js"; import "./effects/Tween.js"; var fxNow, inProgress, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; function schedule() { if ( inProgress ) { if ( document.hidden === false && window.requestAnimationFrame ) { window.requestAnimationFrame( schedule ); } else { window.setTimeout( schedule, 13 ); } jQuery.fx.tick(); } } // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = Date.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree( elem ), dataShow = dataPriv.get( elem, "fxshow" ); // Queue-skipping animations hijack the fx hooks if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always( function() { // Ensure the complete handler is called before this completes anim.always( function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } } ); } ); } // Detect show/hide animations for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.test( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // Pretend to be hidden if this is a "show" and // there is still data from a stopped show/hide if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; // Ignore all other no-op show/hide data } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } // Bail out if this is a no-op like .hide().hide() propTween = !jQuery.isEmptyObject( props ); if ( !propTween && jQuery.isEmptyObject( orig ) ) { return; } // Restrict "overflow" and "display" styles during box animations if ( isBox && elem.nodeType === 1 ) { // Support: IE <=9 - 11+ // Record all 3 overflow attributes because IE does not infer the shorthand // from identically-valued overflowX and overflowY. opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Identify a display type, preferring old show/hide data over the CSS cascade restoreDisplay = dataShow && dataShow.display; if ( restoreDisplay == null ) { restoreDisplay = dataPriv.get( elem, "display" ); } display = jQuery.css( elem, "display" ); if ( display === "none" ) { if ( restoreDisplay ) { display = restoreDisplay; } else { // Get nonempty value(s) by temporarily forcing visibility showHide( [ elem ], true ); restoreDisplay = elem.style.display || restoreDisplay; display = jQuery.css( elem, "display" ); showHide( [ elem ] ); } } // Animate inline elements as inline-block if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { if ( jQuery.css( elem, "float" ) === "none" ) { // Restore the original display value at the end of pure show/hide animations if ( !propTween ) { anim.done( function() { style.display = restoreDisplay; } ); if ( restoreDisplay == null ) { display = style.display; restoreDisplay = display === "none" ? "" : display; } } style.display = "inline-block"; } } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always( function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; } ); } // Implement show/hide animations propTween = false; for ( prop in orig ) { // General show/hide setup for this element animation if ( !propTween ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.set( elem, "fxshow", { display: restoreDisplay } ); } // Store hidden/visible for toggle so `.stop().toggle()` "reverses" if ( toggle ) { dataShow.hidden = !hidden; } // Show elements before animating them if ( hidden ) { showHide( [ elem ], true ); } // eslint-disable-next-line no-loop-func anim.done( function() { // The final step of a "hide" animation is actually hiding the element if ( !hidden ) { showHide( [ elem ] ); } dataPriv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } } ); } // Per-property setup propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = propTween.start; if ( hidden ) { propTween.end = propTween.start; propTween.start = 0; } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = cssCamelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( Array.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; } ), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), percent = 1 - ( remaining / animation.duration || 0 ), index = 0, length = animation.tweens.length; for ( ; index < length; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ] ); // If there's more to do, yield if ( percent < 1 && length ) { return remaining; } // If this was an empty animation, synthesize a final progress notification if ( !length ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); } // Resolve the animation and report its conclusion deferred.resolveWith( elem, [ animation ] ); return false; }, animation = deferred.promise( { elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {}, easing: jQuery.easing._default }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } } ), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( typeof result.stop === "function" ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = result.stop.bind( result ); } return result; } } jQuery.map( props, createTween, animation ); if ( typeof animation.opts.start === "function" ) { animation.opts.start.call( elem, animation ); } // Attach callbacks from options animation .progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); return animation; } jQuery.Animation = jQuery.extend( Animation, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( typeof props === "function" ) { callback = props; props = [ "*" ]; } else { props = props.match( rnothtmlwhite ); } var prop, index = 0, length = props.length; for ( ; index < length; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.push( callback ); } } } ); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || easing || typeof speed === "function" && speed, duration: speed, easing: fn && easing || easing && typeof easing !== "function" && easing }; // Go to the end state if fx are off if ( jQuery.fx.off ) { opt.duration = 0; } else { if ( typeof opt.duration !== "number" ) { if ( opt.duration in jQuery.fx.speeds ) { opt.duration = jQuery.fx.speeds[ opt.duration ]; } else { opt.duration = jQuery.fx.speeds._default; } } } // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( typeof opt.old === "function" ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend( { fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate( { opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || dataPriv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue ) { this.queue( type || "fx", [] ); } return this.each( function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && ( type == null || timers[ index ].queue === type ) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } } ); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each( function() { var index, data = dataPriv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; } ); } } ); jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; } ); // Generate shortcuts for custom animations jQuery.each( { slideDown: genFx( "show" ), slideUp: genFx( "hide" ), slideToggle: genFx( "toggle" ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; } ); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = Date.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Run the timer and safely remove it when done (allowing for external removal) if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); jQuery.fx.start(); }; jQuery.fx.start = function() { if ( inProgress ) { return; } inProgress = true; schedule(); }; jQuery.fx.stop = function() { inProgress = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/css.js
src/css.js
import { jQuery } from "./core.js"; import { access } from "./core/access.js"; import { nodeName } from "./core/nodeName.js"; import { rcssNum } from "./var/rcssNum.js"; import { isIE } from "./var/isIE.js"; import { rnumnonpx } from "./css/var/rnumnonpx.js"; import { rcustomProp } from "./css/var/rcustomProp.js"; import { cssExpand } from "./css/var/cssExpand.js"; import { isAutoPx } from "./css/isAutoPx.js"; import { cssCamelCase } from "./css/cssCamelCase.js"; import { getStyles } from "./css/var/getStyles.js"; import { swap } from "./css/var/swap.js"; import { curCSS } from "./css/curCSS.js"; import { adjustCSS } from "./css/adjustCSS.js"; import { finalPropName } from "./css/finalPropName.js"; import { support } from "./css/support.js"; import "./core/init.js"; import "./core/ready.js"; var cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }; function setPositiveNumber( _elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { var i = dimension === "width" ? 1 : 0, extra = 0, delta = 0, marginDelta = 0; // Adjustment may not be necessary if ( box === ( isBorderBox ? "border" : "content" ) ) { return 0; } for ( ; i < 4; i += 2 ) { // Both box models exclude margin // Count margin delta separately to only add it after scroll gutter adjustment. // This is needed to make negative margins work with `outerHeight( true )` (gh-3982). if ( box === "margin" ) { marginDelta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); } // If we get here with a content-box, we're seeking "padding" or "border" or "margin" if ( !isBorderBox ) { // Add padding delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // For "border" or "margin", add border if ( box !== "padding" ) { delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); // But still keep track of it otherwise } else { extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } // If we get here with a border-box (content + padding + border), we're seeking "content" or // "padding" or "margin" } else { // For "content", subtract padding if ( box === "content" ) { delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // For "content" or "padding", subtract border if ( box !== "margin" ) { delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } // Account for positive content-box scroll gutter when requested by providing computedVal if ( !isBorderBox && computedVal >= 0 ) { // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border // Assuming integer scroll gutter, subtract the rest and round down delta += Math.max( 0, Math.ceil( elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - computedVal - delta - extra - 0.5 // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter // Use an explicit zero to avoid NaN (gh-3964) ) ) || 0; } return delta + marginDelta; } function getWidthOrHeight( elem, dimension, extra ) { // Start with computed style var styles = getStyles( elem ), // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). // Fake content-box until we know it's needed to know the true value. boxSizingNeeded = isIE || extra, isBorderBox = boxSizingNeeded && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", valueIsBorderBox = isBorderBox, val = curCSS( elem, dimension, styles ), offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); // Return a confounding non-pixel value or feign ignorance, as appropriate. if ( rnumnonpx.test( val ) ) { if ( !extra ) { return val; } val = "auto"; } if ( ( // Fall back to offsetWidth/offsetHeight when value is "auto" // This happens for inline elements with no explicit setting (gh-3571) val === "auto" || // Support: IE 9 - 11+ // Use offsetWidth/offsetHeight for when box sizing is unreliable. // In those cases, the computed value can be trusted to be border-box. ( isIE && isBorderBox ) || ( !support.reliableColDimensions() && nodeName( elem, "col" ) ) || ( !support.reliableTrDimensions() && nodeName( elem, "tr" ) ) ) && // Make sure the element is visible & connected elem.getClientRects().length ) { isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Where available, offsetWidth/offsetHeight approximate border box dimensions. // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the // retrieved value as a content box dimension. valueIsBorderBox = offsetProp in elem; if ( valueIsBorderBox ) { val = elem[ offsetProp ]; } } // Normalize "" and auto val = parseFloat( val ) || 0; // Adjust for the element's box model return ( val + boxModelAdjustment( elem, dimension, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles, // Provide the current computed size to request scroll gutter calculation (gh-3589) val ) ) + "px"; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: {}, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = cssCamelCase( name ), isCustomProp = rcustomProp.test( name ), style = elem.style; // Make sure that we're working with the right name. We don't // want to query the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (trac-7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug trac-9237 type = "number"; } // Make sure that null and NaN values aren't set (trac-7116) if ( value == null || value !== value ) { return; } // If the value is a number, add `px` for certain CSS properties if ( type === "number" ) { value += ret && ret[ 3 ] || ( isAutoPx( origName ) ? "px" : "" ); } // Support: IE <=9 - 11+ // background-* props of a cloned element affect the source element (trac-8908) if ( isIE && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { if ( isCustomProp ) { style.setProperty( name, value ); } else { style[ name ] = value; } } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = cssCamelCase( name ), isCustomProp = rcustomProp.test( name ); // Make sure that we're working with the right name. We don't // want to modify the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( _i, dimension ) { jQuery.cssHooks[ dimension ] = { get: function( elem, computed, extra ) { if ( computed ) { // Elements with `display: none` can have dimension info if // we invisibly show them. return jQuery.css( elem, "display" ) === "none" ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, dimension, extra ); } ) : getWidthOrHeight( elem, dimension, extra ); } }, set: function( elem, value, extra ) { var matches, styles = getStyles( elem ), // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) isBorderBox = extra && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", subtract = extra ? boxModelAdjustment( elem, dimension, extra, isBorderBox, styles ) : 0; // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ dimension ] = value; value = jQuery.css( elem, dimension ); } return setPositiveNumber( elem, value, subtract ); } }; } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( prefix !== "margin" ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( Array.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); } } ); export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/wrapper.js
src/wrapper.js
/*! * jQuery JavaScript Library v@VERSION * https://jquery.com/ * * Copyright OpenJS Foundation and other contributors * Released under the MIT license * https://jquery.com/license/ * * Date: @DATE */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. module.exports = factory( global, true ); } else { factory( global ); } // Pass this if window is not defined yet } )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { "use strict"; if ( !window.document ) { throw new Error( "jQuery requires a window with a document" ); } // @CODE // build.js inserts compiled jQuery here return jQuery; } );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core.js
src/core.js
import { arr } from "./var/arr.js"; import { getProto } from "./var/getProto.js"; import { slice } from "./var/slice.js"; import { flat } from "./var/flat.js"; import { push } from "./var/push.js"; import { indexOf } from "./var/indexOf.js"; import { class2type } from "./var/class2type.js"; import { toString } from "./var/toString.js"; import { hasOwn } from "./var/hasOwn.js"; import { fnToString } from "./var/fnToString.js"; import { ObjectFunctionString } from "./var/ObjectFunctionString.js"; import { support } from "./var/support.js"; import { isArrayLike } from "./core/isArrayLike.js"; import { DOMEval } from "./core/DOMEval.js"; var version = "@VERSION", rhtmlSuffix = /HTML$/i, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { // Return all the elements in a clean array if ( num == null ) { return slice.call( this ); } // Return just the one element from the set return num < 0 ? this[ num + this.length ] : this[ num ]; }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, even: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return ( i + 1 ) % 2; } ) ); }, odd: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return i % 2; } ) ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); } }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && typeof target !== "function" ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { copy = options[ name ]; // Prevent Object.prototype pollution // Prevent never-ending loop if ( name === "__proto__" || target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = Array.isArray( copy ) ) ) ) { src = target[ name ]; // Ensure proper type for the source value if ( copyIsArray && !Array.isArray( src ) ) { clone = []; } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { clone = {}; } else { clone = src; } copyIsArray = false; // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, // Evaluates a script in a provided context; falls back to the global one // if not specified. globalEval: function( code, options, doc ) { DOMEval( code, { nonce: options && options.nonce }, doc ); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // Retrieve the text value of an array of DOM nodes text: function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( ( node = elem[ i++ ] ) ) { // Do not traverse comment nodes ret += jQuery.text( node ); } } if ( nodeType === 1 || nodeType === 11 ) { return elem.textContent; } if ( nodeType === 9 ) { return elem.documentElement.textContent; } if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, isXMLDoc: function( elem ) { var namespace = elem && elem.namespaceURI, docElem = elem && ( elem.ownerDocument || elem ).documentElement; // Assume HTML when documentElement doesn't yet exist, such as inside // document fragments. return !rhtmlSuffix.test( namespace || docElem && docElem.nodeName || "HTML" ); }, // Note: an element does not contain itself contains: function( a, b ) { var bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( // Support: IE 9 - 11+ // IE doesn't have `contains` on SVG. a.contains ? a.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 ) ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return flat( ret ); }, // A global GUID counter for objects guid: 1, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( _i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/wrap.js
src/wrap.js
import { jQuery } from "./core.js"; import "./core/init.js"; import "./manipulation.js"; // clone import "./traversing.js"; // parent, contents jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( typeof html === "function" ) { html = html.call( this[ 0 ] ); } // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( typeof html === "function" ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var htmlIsFunction = typeof html === "function"; return this.each( function( i ) { jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); } ); }, unwrap: function( selector ) { this.parent( selector ).not( "body" ).each( function() { jQuery( this ).replaceWith( this.childNodes ); } ); return this; } } ); export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/callbacks.js
src/callbacks.js
import { jQuery } from "./core.js"; import { toType } from "./core/toType.js"; import { rnothtmlwhite } from "./var/rnothtmlwhite.js"; // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = locked || options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( typeof arg === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && toType( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory && !firing ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/selector-native.js
src/selector-native.js
/* * Optional limited selector module for custom builds. * * Note that this DOES NOT SUPPORT many documented jQuery * features in exchange for its smaller size: * * * Attribute not equal selector (!=) * * Positional selectors (:first; :eq(n); :odd; etc.) * * Type selectors (:input; :checkbox; :button; etc.) * * State-based selectors (:animated; :visible; :hidden; etc.) * * :has(selector) in browsers without native support * * :not(complex selector) in IE * * custom selectors via jQuery extensions * * Reliable functionality on XML fragments * * Matching against non-elements * * Reliable sorting of disconnected nodes * * querySelectorAll bug fixes (e.g., unreliable :focus on WebKit) * * If any of these are unacceptable tradeoffs, either use the full * selector engine or customize this stub for the project's specific * needs. */ import { jQuery } from "./core.js"; import { document } from "./var/document.js"; import { whitespace } from "./var/whitespace.js"; import { isIE } from "./var/isIE.js"; import { rleadingCombinator } from "./selector/var/rleadingCombinator.js"; import { rdescend } from "./selector/var/rdescend.js"; import { rsibling } from "./selector/var/rsibling.js"; import { matches } from "./selector/var/matches.js"; import { testContext } from "./selector/testContext.js"; import { filterMatchExpr } from "./selector/filterMatchExpr.js"; import { preFilter } from "./selector/preFilter.js"; import { tokenize } from "./selector/tokenize.js"; import { toSelector } from "./selector/toSelector.js"; // The following utils are attached directly to the jQuery object. import "./selector/escapeSelector.js"; import "./selector/uniqueSort.js"; var matchExpr = jQuery.extend( { needsContext: new RegExp( "^" + whitespace + "*[>+~]" ) }, filterMatchExpr ); jQuery.extend( { find: function( selector, context, results, seed ) { var elem, nid, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9, i = 0; results = results || []; context = context || document; // Same basic safeguard as in the full selector module if ( !selector || typeof selector !== "string" ) { return results; } // Early return if context is not an element, document or document fragment if ( nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return []; } if ( seed ) { while ( ( elem = seed[ i++ ] ) ) { if ( jQuery.find.matchesSelector( elem, selector ) ) { results.push( elem ); } } } else { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // The technique has to be used as well when a leading combinator is used // as such selectors are not recognized by querySelectorAll. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && ( rdescend.test( selector ) || rleadingCombinator.test( selector ) ) ) { // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; // Outside of IE, if we're not changing the context we can // use :scope instead of an ID. if ( newContext !== context || isIE ) { // Capture the context ID, setting it first if necessary if ( ( nid = context.getAttribute( "id" ) ) ) { nid = jQuery.escapeSelector( nid ); } else { context.setAttribute( "id", ( nid = jQuery.expando ) ); } } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + toSelector( groups[ i ] ); } newSelector = groups.join( "," ); } try { jQuery.merge( results, newContext.querySelectorAll( newSelector ) ); } finally { if ( nid === jQuery.expando ) { context.removeAttribute( "id" ); } } } return results; }, expr: { // Can be adjusted by the user cacheLength: 50, match: matchExpr, preFilter: preFilter } } ); jQuery.extend( jQuery.find, { matches: function( expr, elements ) { return jQuery.find( expr, null, null, elements ); }, matchesSelector: function( elem, expr ) { return matches.call( elem, expr ); }, tokenize: tokenize } ); export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/ajax.js
src/ajax.js
import { jQuery } from "./core.js"; import { document } from "./var/document.js"; import { rnothtmlwhite } from "./var/rnothtmlwhite.js"; import { location } from "./ajax/var/location.js"; import { nonce } from "./ajax/var/nonce.js"; import { rquery } from "./ajax/var/rquery.js"; import "./core/init.js"; import "./core/parseXML.js"; import "./event/trigger.js"; import "./deferred.js"; import "./serialize.js"; // jQuery.param var r20 = /%20/g, rhash = /#.*$/, rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // trac-7653, trac-8125, trac-8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (trac-10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; if ( typeof func === "function" ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === "+" ) { dataType = dataType.slice( 1 ) || "*"; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes trac-9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": JSON.parse, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // Request state (becomes false upon send and true upon completion) completed, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // uncached part of the url uncached, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( completed ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { // Support: IE 11+ // `getResponseHeader( key )` in IE doesn't combine all header // values for the provided key into a single result with values // joined by commas as other browsers do. Instead, it returns // them on separate lines. responseHeaders[ match[ 1 ].toLowerCase() + " " ] = ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) .concat( match[ 2 ] ); } } match = responseHeaders[ key.toLowerCase() + " " ]; } return match == null ? null : match.join( ", " ); }, // Raw string getAllResponseHeaders: function() { return completed ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { if ( completed == null ) { name = requestHeadersNames[ name.toLowerCase() ] = requestHeadersNames[ name.toLowerCase() ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( completed == null ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( completed ) { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } else { // Lazy-add the new callbacks in a way that preserves old ones for ( code in map ) { statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ); // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (trac-10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ) .replace( rprotocol, location.protocol + "//" ); // Alias method option to type as per ticket trac-12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; // A cross-domain request is in order when the origin doesn't match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); // Support: IE <=8 - 11+ // IE throws exception on accessing the href property if url is malformed, // e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE <=8 - 11+ // Anchor's host property isn't correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // If request was aborted inside a prefilter, stop there if ( completed ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an ESM-usage scenario (trac-15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on // Remove hash to simplify url manipulation cacheURL = s.url.replace( rhash, "" ); // More options handling for requests with no content if ( !s.hasContent ) { // Remember the hash so we can put it back uncached = s.url.slice( cacheURL.length ); // If data is available and should be processed, append data to url if ( s.data && ( s.processData || typeof s.data === "string" ) ) { cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; // trac-9682: remove data so that it's not used in an eventual retry delete s.data; } // Add or update anti-cache param if needed if ( s.cache === false ) { cacheURL = cacheURL.replace( rantiCache, "$1" ); uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + uncached; } // Put hash and anti-cache on the URL that will be requested (gh-1732) s.url = cacheURL + uncached; // Change '%20' to '+' if this is encoded form body content (gh-2658) } else if ( s.data && s.processData && ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { s.data = s.data.replace( r20, "+" ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds completeDeferred.add( s.complete ); jqXHR.done( s.success ); jqXHR.fail( s.error ); // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( completed ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( "timeout" ); }, s.timeout ); } try { completed = false; transport.send( requestHeaders, done ); } catch ( e ) { // Rethrow post-completion exceptions if ( completed ) { throw e; } // Propagate others as results done( -1, e ); } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Ignore repeat invocations if ( completed ) { return; } completed = true; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Use a noop converter for missing script but not if jsonp if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 && jQuery.inArray( "json", s.dataTypes ) < 0 ) { s.converters[ "text script" ] = function() {}; } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } } ); jQuery.each( [ "get", "post" ], function( _i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted. // Handle the null callback placeholder. if ( typeof data === "function" || data === null ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery.ajaxPrefilter( function( s ) { var i; for ( i in s.headers ) { if ( i.toLowerCase() === "content-type" ) { s.contentType = s.headers[ i ] || ""; } } } ); export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/data.js
src/data.js
import { jQuery } from "./core.js"; import { access } from "./core/access.js"; import { camelCase } from "./core/camelCase.js"; import { dataPriv } from "./data/var/dataPriv.js"; import { dataUser } from "./data/var/dataUser.js"; // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function getData( data ) { if ( data === "true" ) { return true; } if ( data === "false" ) { return false; } if ( data === "null" ) { return null; } // Only convert to a number if it doesn't change the string if ( data === +data + "" ) { return +data; } if ( rbrace.test( data ) ) { return JSON.parse( data ); } return data; } function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = getData( data ); } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE 11+ // The attrs elements can be null (trac-14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // The key will always be camelCased in Data data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each( function() { // We always store the camelCased key dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/attributes.js
src/attributes.js
import { jQuery } from "./core.js"; import "./attributes/attr.js"; import "./attributes/prop.js"; import "./attributes/classes.js"; import "./attributes/val.js"; // Return jQuery for attributes-only inclusion export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/wrapper-factory-esm.js
src/wrapper-factory-esm.js
/*! * jQuery JavaScript Library v@VERSION * https://jquery.com/ * * Copyright OpenJS Foundation and other contributors * Released under the MIT license * https://jquery.com/license/ * * Date: @DATE */ // Expose a factory as `jQueryFactory`. Aimed at environments without // a real `window` where an emulated window needs to be constructed. Example: // // import { jQueryFactory } from "jquery/factory"; // const jQuery = jQueryFactory( window ); // // See ticket trac-14549 for more info. function jQueryFactoryWrapper( window, noGlobal ) { if ( !window.document ) { throw new Error( "jQuery requires a window with a document" ); } // @CODE // build.js inserts compiled jQuery here return jQuery; } export function jQueryFactory( window ) { return jQueryFactoryWrapper( window, true ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/wrapper-esm.js
src/wrapper-esm.js
/*! * jQuery JavaScript Library v@VERSION * https://jquery.com/ * * Copyright OpenJS Foundation and other contributors * Released under the MIT license * https://jquery.com/license/ * * Date: @DATE */ // For ECMAScript module environments where a proper `window` // is present, execute the factory and get jQuery. function jQueryFactory( window, noGlobal ) { if ( typeof window === "undefined" || !window.document ) { throw new Error( "jQuery requires a window with a document" ); } // @CODE // build.js inserts compiled jQuery here return jQuery; } var jQuery = jQueryFactory( window, true ); export { jQuery, jQuery as $ }; export default jQuery;
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/offset.js
src/offset.js
import { jQuery } from "./core.js"; import { access } from "./core/access.js"; import { documentElement } from "./var/documentElement.js"; import { isWindow } from "./var/isWindow.js"; import "./core/init.js"; import "./css.js"; jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1; // Need to be able to calculate position if either // top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( typeof options === "function" ) { // Use jQuery.extend here to allow modification of coordinates argument (gh-1848) options = options.call( elem, i, jQuery.extend( {}, curOffset ) ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend( { // offset() relates an element's border box to the document origin offset: function( options ) { // Preserve chaining for setter if ( arguments.length ) { return options === undefined ? this : this.each( function( i ) { jQuery.offset.setOffset( this, options, i ); } ); } var rect, win, elem = this[ 0 ]; if ( !elem ) { return; } // Return zeros for disconnected and hidden (display: none) elements (gh-2310) // Support: IE <=11+ // Running getBoundingClientRect on a // disconnected node in IE throws an error if ( !elem.getClientRects().length ) { return { top: 0, left: 0 }; } // Get document-relative position by adding viewport scroll to viewport-relative gBCR rect = elem.getBoundingClientRect(); win = elem.ownerDocument.defaultView; return { top: rect.top + win.pageYOffset, left: rect.left + win.pageXOffset }; }, // position() relates an element's margin box to its offset parent's padding box // This corresponds to the behavior of CSS absolute positioning position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, doc, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // position:fixed elements are offset from the viewport, which itself always has zero offset if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume position:fixed implies availability of getBoundingClientRect offset = elem.getBoundingClientRect(); } else { offset = this.offset(); // Account for the *real* offset parent, which can be the document or its root element // when a statically positioned element is identified doc = elem.ownerDocument; offsetParent = elem.offsetParent || doc.documentElement; while ( offsetParent && offsetParent !== doc.documentElement && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.offsetParent || doc.documentElement; } if ( offsetParent && offsetParent !== elem && offsetParent.nodeType === 1 && jQuery.css( offsetParent, "position" ) !== "static" ) { // Incorporate borders into its offset, since they are outside its content origin parentOffset = jQuery( offsetParent ).offset(); parentOffset.top += jQuery.css( offsetParent, "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent, "borderLeftWidth", true ); } } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, // This method will return documentElement in the following cases: // 1) For the element inside the iframe without offsetParent, this method will return // documentElement of the parent window // 2) For the hidden or detached element // 3) For body or html element, i.e. in case of the html node - it will return itself // // but those exceptions were never presented as a real life use-cases // and might be considered as more preferable results. // // This logic, however, is not guaranteed and can change at any point in the future offsetParent: function() { return this.map( function() { var offsetParent = this.offsetParent; while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.offsetParent; } return offsetParent || documentElement; } ); } } ); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { // Coalesce documents and windows var win; if ( isWindow( elem ) ) { win = elem; } else if ( elem.nodeType === 9 ) { win = elem.defaultView; } if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : win.pageXOffset, top ? val : win.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length ); }; } ); export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/manipulation.js
src/manipulation.js
import { jQuery } from "./core.js"; import { isAttached } from "./core/isAttached.js"; import { isIE } from "./var/isIE.js"; import { push } from "./var/push.js"; import { access } from "./core/access.js"; import { rtagName } from "./manipulation/var/rtagName.js"; import { wrapMap } from "./manipulation/wrapMap.js"; import { getAll } from "./manipulation/getAll.js"; import { domManip } from "./manipulation/domManip.js"; import { setGlobalEval } from "./manipulation/setGlobalEval.js"; import { dataPriv } from "./data/var/dataPriv.js"; import { dataUser } from "./data/var/dataUser.js"; import { acceptData } from "./data/var/acceptData.js"; import { nodeName } from "./core/nodeName.js"; import "./core/init.js"; import "./traversing.js"; import "./event.js"; var // Support: IE <=10 - 11+ // In IE using regex groups here causes severe slowdowns. rnoInnerhtml = /<script|<style|<link/i; // Prefer a tbody over its parent table for containing new rows function manipulationTarget( elem, content ) { if ( nodeName( elem, "table" ) && nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return jQuery( elem ).children( "tbody" )[ 0 ] || elem; } return elem; } function cloneCopyEvent( src, dest ) { var type, i, l, events = dataPriv.get( src, "events" ); if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( events ) { dataPriv.remove( dest, "handle events" ); for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { dataUser.set( dest, jQuery.extend( {}, dataUser.get( src ) ) ); } } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && isAttached( node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html; }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = isAttached( elem ); // Fix IE cloning issues if ( isIE && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew jQuery#find here for performance reasons: // https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { // Support: IE <=11+ // IE fails to set the defaultValue to the correct value when // cloning textareas. if ( nodeName( destElements[ i ], "textarea" ) ) { destElements[ i ].defaultValue = srcElements[ i ].defaultValue; } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); push.apply( ret, elems ); } return this.pushStack( ret ); }; } ); export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/deprecated.js
src/deprecated.js
import { jQuery } from "./core.js"; import { slice } from "./var/slice.js"; import "./deprecated/ajax-event-alias.js"; import "./deprecated/event.js"; // Bind a function to a context, optionally partially applying any // arguments. // jQuery.proxy is deprecated to promote standards (specifically Function#bind) // However, it is not slated for removal any time soon jQuery.proxy = function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( typeof fn !== "function" ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }; jQuery.holdReady = function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }; jQuery.expr[ ":" ] = jQuery.expr.filters = jQuery.expr.pseudos; export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/dimensions.js
src/dimensions.js
import { jQuery } from "./core.js"; import { access } from "./core/access.js"; import { isWindow } from "./var/isWindow.js"; import "./css.js"; // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // Margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( isWindow( elem ) ) { // $( window ).outerWidth/Height return w/h including scrollbars (gh-1729) return funcName.indexOf( "outer" ) === 0 ? elem[ "inner" + name ] : elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable ); }; } ); } ); export { jQuery, jQuery as $ };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false