Debian Codegraph @

inst/www/shared/shiny.js

raw symbols SCIP
1 /*! shiny 1.13.0 | (c) 2012-2026 Posit Software, PBC. | License: MIT + file LICENSE */
2 "use strict";
3 (() => {
4 var __create = Object.create;
5 var __defProp = Object.defineProperty;
6 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7 var __getOwnPropNames = Object.getOwnPropertyNames;
8 var __getProtoOf = Object.getPrototypeOf;
9 var __hasOwnProp = Object.prototype.hasOwnProperty;
10 var __typeError = (msg) => {
11 throw TypeError(msg);
12 };
13 var __commonJS = (cb, mod) => function __require() {
14 return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15 };
16 var __copyProps = (to, from, except, desc) => {
17 if (from && typeof from === "object" || typeof from === "function") {
18 for (let key of __getOwnPropNames(from))
19 if (!__hasOwnProp.call(to, key) && key !== except)
20 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21 }
22 return to;
23 };
24 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25 // If the importer is in node compatibility mode or this is not an ESM
26 // file that has been converted to a CommonJS file using a Babel-
27 // compatible transform (i.e. "__esModule" has not been set), then set
28 // "default" to the CommonJS "module.exports" for node compatibility.
29 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30 mod
31 ));
32 var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
33 var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
34 var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
35 var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
36 var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
37
38 // globals:jquery
39 var require_jquery = __commonJS({
40 "globals:jquery"(exports, module) {
41 module.exports = window.jQuery;
42 }
43 });
44
45 // srcts/src/initialize/browser.ts
46 var import_jquery = __toESM(require_jquery());
47
48 // srcts/src/utils/browser.ts
49 var isQtVal = false;
50 var isIEVal = false;
51 var versionIE = -1;
52 function setIsQt(isQt2) {
53 isQtVal = isQt2;
54 }
55 function setIsIE(isIE2) {
56 isIEVal = isIE2;
57 }
58 function setIEVersion(versionIE_) {
59 versionIE = versionIE_;
60 }
61 function isQt() {
62 return isQtVal;
63 }
64 function isIE() {
65 return isIEVal;
66 }
67 function IEVersion() {
68 return versionIE;
69 }
70
71 // srcts/src/utils/userAgent.ts
72 var userAgent;
73 function setUserAgent(userAgent_) {
74 userAgent = userAgent_;
75 }
76
77 // srcts/src/initialize/browser.ts
78 function getIEVersion() {
79 const msie = userAgent.indexOf("MSIE ");
80 if (isIE() && msie > 0) {
81 return parseInt(
82 userAgent.substring(msie + 5, userAgent.indexOf(".", msie)),
83 10
84 );
85 }
86 const trident = userAgent.indexOf("Trident/");
87 if (trident > 0) {
88 const rv = userAgent.indexOf("rv:");
89 return parseInt(
90 userAgent.substring(rv + 3, userAgent.indexOf(".", rv)),
91 10
92 );
93 }
94 return -1;
95 }
96 function determineBrowserInfo() {
97 if (/\bQt\//.test(userAgent)) {
98 (0, import_jquery.default)(document.documentElement).addClass("qt");
99 setIsQt(true);
100 } else {
101 setIsQt(false);
102 }
103 if (/\bQt/.test(userAgent) && /\bMacintosh/.test(userAgent)) {
104 (0, import_jquery.default)(document.documentElement).addClass("qtmac");
105 }
106 if (/\bQt\/5/.test(userAgent) && /Linux/.test(userAgent)) {
107 (0, import_jquery.default)(document.documentElement).addClass("qt5");
108 }
109 setIsIE(/MSIE|Trident|Edge/.test(userAgent));
110 setIEVersion(getIEVersion());
111 }
112
113 // srcts/src/initialize/disableForm.ts
114 var import_jquery2 = __toESM(require_jquery());
115 function disableFormSubmission() {
116 (0, import_jquery2.default)(document).on("submit", "form:not([action])", function(e4) {
117 e4.preventDefault();
118 });
119 }
120
121 // srcts/src/initialize/history.ts
122 var import_jquery3 = __toESM(require_jquery());
123 function trackHistory() {
124 const origPushState = window.history.pushState;
125 window.history.pushState = function(...args) {
126 const result = origPushState.apply(this, args);
127 (0, import_jquery3.default)(document).trigger("pushstate");
128 return result;
129 };
130 }
131
132 // srcts/src/shiny/index.ts
133 var import_jquery40 = __toESM(require_jquery());
134
135 // srcts/src/utils/index.ts
136 var import_jquery6 = __toESM(require_jquery());
137
138 // srcts/src/shiny/render.ts
139 var import_jquery5 = __toESM(require_jquery());
140
141 // srcts/src/utils/object.ts
142 function hasOwnProperty(obj, prop) {
143 return Object.prototype.hasOwnProperty.call(obj, prop);
144 }
145 function hasDefinedProperty(obj, prop) {
146 return Object.prototype.hasOwnProperty.call(obj, prop) && obj[prop] !== void 0;
147 }
148 function ifUndefined(value, alternate) {
149 if (value === void 0) return alternate;
150 return value;
151 }
152 function asArray(value) {
153 if (value === null || value === void 0) return [];
154 if (Array.isArray(value)) return value;
155 return [value];
156 }
157
158 // srcts/src/shiny/initedMethods.ts
159 var fullShinyObj;
160 function setShinyObj(shiny) {
161 fullShinyObj = shiny;
162 }
163 function validateShinyHasBeenSet() {
164 if (typeof fullShinyObj === "undefined") {
165 throw "Shiny has not finish initialization yet. Please wait for the 'shiny-initialized' event.";
166 }
167 return fullShinyObj;
168 }
169 function shinySetInputValue(name, value, opts) {
170 validateShinyHasBeenSet().setInputValue(name, value, opts);
171 }
172 function shinyShinyApp() {
173 return validateShinyHasBeenSet().shinyapp;
174 }
175 function setShinyUser(user) {
176 validateShinyHasBeenSet().user = user;
177 }
178 function shinyForgetLastInputValue(name) {
179 validateShinyHasBeenSet().forgetLastInputValue(name);
180 }
181 async function shinyBindAll(scope) {
182 await validateShinyHasBeenSet().bindAll(scope);
183 }
184 function shinyUnbindAll(scope, includeSelf = false) {
185 validateShinyHasBeenSet().unbindAll(scope, includeSelf);
186 }
187 function shinyInitializeInputs(scope) {
188 validateShinyHasBeenSet().initializeInputs(scope);
189 }
190 async function shinyAppBindOutput(id, binding) {
191 await shinyShinyApp().bindOutput(id, binding);
192 }
193 function shinyAppUnbindOutput(id, binding) {
194 return shinyShinyApp().unbindOutput(id, binding);
195 }
196 function getShinyOnCustomMessage() {
197 return validateShinyHasBeenSet().oncustommessage;
198 }
199 var fileInputBinding;
200 function getFileInputBinding() {
201 return fileInputBinding;
202 }
203 function setFileInputBinding(fileInputBinding_) {
204 fileInputBinding = fileInputBinding_;
205 }
206 function getShinyCreateWebsocket() {
207 return validateShinyHasBeenSet().createSocket;
208 }
209
210 // srcts/src/time/debounce.ts
211 var Debouncer = class {
212 constructor(target, func, delayMs) {
213 this.target = target;
214 this.func = func;
215 this.delayMs = delayMs;
216 this.timerId = null;
217 this.args = null;
218 }
219 normalCall(...args) {
220 this.$clearTimer();
221 this.args = args;
222 this.timerId = setTimeout(() => {
223 if (this.timerId === null) return;
224 this.$clearTimer();
225 this.$invoke();
226 }, this.delayMs);
227 }
228 immediateCall(...args) {
229 this.$clearTimer();
230 this.args = args;
231 this.$invoke();
232 }
233 isPending() {
234 return this.timerId !== null;
235 }
236 $clearTimer() {
237 if (this.timerId !== null) {
238 clearTimeout(this.timerId);
239 this.timerId = null;
240 }
241 }
242 $invoke() {
243 if (this.args && this.args.length > 0) {
244 this.func.apply(this.target, this.args);
245 } else {
246 this.func.apply(this.target);
247 }
248 this.args = null;
249 }
250 };
251 function debounce(threshold, func) {
252 let timerId = null;
253 return function thisFunc(...args) {
254 if (timerId !== null) {
255 clearTimeout(timerId);
256 timerId = null;
257 }
258 timerId = setTimeout(() => {
259 if (timerId === null) return;
260 timerId = null;
261 func.apply(thisFunc, args);
262 }, threshold);
263 };
264 }
265
266 // srcts/src/time/invoke.ts
267 var Invoker = class {
268 constructor(target, func) {
269 this.target = target;
270 this.func = func;
271 }
272 // TODO-barret - Don't know how to define the method twice and still have access to "this"
273 normalCall(...args) {
274 this.func.apply(this.target, args);
275 }
276 immediateCall(...args) {
277 this.func.apply(this.target, args);
278 }
279 };
280
281 // srcts/src/time/throttle.ts
282 var Throttler = class {
283 constructor(target, func, delayMs) {
284 this.target = target;
285 this.func = func;
286 this.delayMs = delayMs;
287 this.timerId = null;
288 this.args = null;
289 }
290 // If no timer is currently running, immediately call the function and set the
291 // timer; if a timer is running out, just queue up the args for the call when
292 // the timer runs out. Later calls during the same timeout will overwrite
293 // earlier ones.
294 normalCall(...args) {
295 this.args = args;
296 if (this.timerId === null) {
297 this.$invoke();
298 }
299 }
300 // Reset the timer if active and call immediately
301 immediateCall(...args) {
302 this.$clearTimer();
303 this.args = args;
304 this.$invoke();
305 }
306 // Is there a call waiting to send?
307 isPending() {
308 return this.args !== null;
309 }
310 $clearTimer() {
311 if (this.timerId !== null) {
312 clearTimeout(this.timerId);
313 this.timerId = null;
314 }
315 }
316 // Invoke the throttled function with the currently-stored args and start the
317 // timer.
318 $invoke() {
319 if (this.args === null) {
320 return;
321 }
322 this.func.apply(this.target, this.args);
323 this.args = null;
324 this.timerId = setTimeout(() => {
325 if (this.timerId === null) return;
326 this.$clearTimer();
327 if (this.isPending()) {
328 this.$invoke();
329 }
330 }, this.delayMs);
331 }
332 };
333
334 // srcts/src/shiny/sendImageSize.ts
335 var SendImageSize = class {
336 setImageSend(inputBatchSender, doSendImageSize) {
337 const sendImageSizeDebouncer = new Debouncer(null, doSendImageSize, 0);
338 this.regular = function() {
339 sendImageSizeDebouncer.normalCall();
340 };
341 inputBatchSender.lastChanceCallback.push(function() {
342 if (sendImageSizeDebouncer.isPending())
343 sendImageSizeDebouncer.immediateCall();
344 });
345 this.transitioned = debounce(200, this.regular);
346 return sendImageSizeDebouncer;
347 }
348 };
349 var sendImageSizeFns = new SendImageSize();
350
351 // srcts/src/shiny/singletons.ts
352 var import_jquery4 = __toESM(require_jquery());
353 var reSingleton = /<!--(SHINY.SINGLETON\[([\w]+)\])-->([\s\S]*?)<!--\/\1-->/;
354 var reHead = /<head(?:\s[^>]*)?>([\s\S]*?)<\/head>/;
355 var knownSingletons = {};
356 function renderHtml(html, el, where) {
357 const processed = processHtml(html);
358 addToHead(processed.head);
359 register(processed.singletons);
360 switch (where.toLowerCase()) {
361 case "replace":
362 (0, import_jquery4.default)(el).html(processed.html);
363 break;
364 case "beforebegin":
365 (0, import_jquery4.default)(el).before(processed.html);
366 break;
367 case "afterbegin":
368 (0, import_jquery4.default)(el).prepend(processed.html);
369 break;
370 case "beforeend":
371 (0, import_jquery4.default)(el).append(processed.html);
372 break;
373 case "afterend":
374 (0, import_jquery4.default)(el).after(processed.html);
375 break;
376 default:
377 throw new Error("Unknown where position: " + where);
378 }
379 return processed;
380 }
381 function register(s4) {
382 import_jquery4.default.extend(knownSingletons, s4);
383 }
384 function registerNames(s4) {
385 if (typeof s4 === "string") {
386 knownSingletons[s4] = true;
387 } else if (s4 instanceof Array) {
388 for (let i5 = 0; i5 < s4.length; i5++) {
389 knownSingletons[s4[i5]] = true;
390 }
391 }
392 }
393 function addToHead(head) {
394 if (head.length > 0) {
395 const tempDiv = (0, import_jquery4.default)("<div>" + head + "</div>").get(0);
396 const $head = (0, import_jquery4.default)("head");
397 while (tempDiv.hasChildNodes()) {
398 $head.append(tempDiv.firstChild);
399 }
400 }
401 }
402 function processHtml(val) {
403 const newSingletons = {};
404 let newVal;
405 const findNewPayload = function(match, p1, sig, payload) {
406 if (knownSingletons[sig] || newSingletons[sig]) return "";
407 newSingletons[sig] = true;
408 return payload;
409 };
410 while (true) {
411 newVal = val.replace(reSingleton, findNewPayload);
412 if (val.length === newVal.length) break;
413 val = newVal;
414 }
415 const heads = [];
416 const headAddPayload = function(match, payload) {
417 heads.push(payload);
418 return "";
419 };
420 while (true) {
421 newVal = val.replace(reHead, headAddPayload);
422 if (val.length === newVal.length) break;
423 val = newVal;
424 }
425 return {
426 html: val,
427 head: heads.join("\n"),
428 singletons: newSingletons
429 };
430 }
431
432 // srcts/src/shiny/render.ts
433 async function renderContentAsync(el, content, where = "replace") {
434 if (where === "replace") {
435 shinyUnbindAll(el);
436 }
437 let html = "";
438 let dependencies = [];
439 if (content === null) {
440 html = "";
441 } else if (typeof content === "string") {
442 html = content;
443 } else if (typeof content === "object") {
444 html = content.html;
445 dependencies = content.deps || [];
446 }
447 await renderHtmlAsync(html, el, dependencies, where);
448 let scope = el;
449 if (where === "replace") {
450 shinyInitializeInputs(el);
451 await shinyBindAll(el);
452 } else {
453 const $parent = (0, import_jquery5.default)(el).parent();
454 if ($parent.length > 0) {
455 scope = $parent;
456 if (where === "beforeBegin" || where === "afterEnd") {
457 const $grandparent = $parent.parent();
458 if ($grandparent.length > 0) scope = $grandparent;
459 }
460 }
461 shinyInitializeInputs(scope);
462 await shinyBindAll(scope);
463 }
464 }
465 function renderContent(el, content, where = "replace") {
466 if (where === "replace") {
467 shinyUnbindAll(el);
468 }
469 let html = "";
470 let dependencies = [];
471 if (content === null) {
472 html = "";
473 } else if (typeof content === "string") {
474 html = content;
475 } else if (typeof content === "object") {
476 html = content.html;
477 dependencies = content.deps || [];
478 }
479 renderHtml2(html, el, dependencies, where);
480 let scope = el;
481 if (where === "replace") {
482 shinyInitializeInputs(el);
483 return shinyBindAll(el);
484 } else {
485 const $parent = (0, import_jquery5.default)(el).parent();
486 if ($parent.length > 0) {
487 scope = $parent;
488 if (where === "beforeBegin" || where === "afterEnd") {
489 const $grandparent = $parent.parent();
490 if ($grandparent.length > 0) scope = $grandparent;
491 }
492 }
493 shinyInitializeInputs(scope);
494 return shinyBindAll(scope);
495 }
496 }
497 async function renderHtmlAsync(html, el, dependencies, where = "replace") {
498 await renderDependenciesAsync(dependencies);
499 return renderHtml(html, el, where);
500 }
501 function renderHtml2(html, el, dependencies, where = "replace") {
502 renderDependencies(dependencies);
503 return renderHtml(html, el, where);
504 }
505 async function renderDependenciesAsync(dependencies) {
506 if (dependencies) {
507 for (const dep of dependencies) {
508 await renderDependencyAsync(dep);
509 }
510 }
511 }
512 function renderDependencies(dependencies) {
513 if (dependencies) {
514 for (const dep of dependencies) {
515 renderDependency(dep);
516 }
517 }
518 }
519 var htmlDependencies = {};
520 function registerDependency(name, version) {
521 htmlDependencies[name] = version;
522 }
523 function needsRestyle(dep) {
524 if (!dep.restyle) {
525 return false;
526 }
527 const names = Object.keys(htmlDependencies);
528 const idx = names.indexOf(dep.name);
529 if (idx === -1) {
530 return false;
531 }
532 return htmlDependencies[names[idx]] === dep.version;
533 }
534 function addStylesheetsAndRestyle(links) {
535 const $head = (0, import_jquery5.default)("head").first();
536 const refreshStyle = function(href, oldSheet) {
537 const xhr = new XMLHttpRequest();
538 xhr.open("GET", href);
539 xhr.onload = function() {
540 const id = "shiny_restyle_" + href.split("?restyle")[0].replace(/\W/g, "_");
541 const oldStyle = $head.find("style#" + id);
542 const newStyle = (0, import_jquery5.default)("<style>").attr("id", id).html(xhr.responseText);
543 $head.append(newStyle);
544 oldStyle.remove();
545 removeSheet(oldSheet);
546 sendImageSizeFns.transitioned();
547 };
548 xhr.send();
549 };
550 const findSheet = function(href) {
551 if (!href) return null;
552 for (let i5 = 0; i5 < document.styleSheets.length; i5++) {
553 const sheet = document.styleSheets[i5];
554 if (typeof sheet.href === "string" && sheet.href.indexOf(href) > -1) {
555 return sheet;
556 }
557 }
558 return null;
559 };
560 const removeSheet = function(sheet) {
561 if (!sheet) return;
562 sheet.disabled = true;
563 if (isIE()) sheet.cssText = "";
564 if (sheet.ownerNode instanceof Element) {
565 (0, import_jquery5.default)(sheet.ownerNode).remove();
566 }
567 };
568 links.map((link) => {
569 const $link = (0, import_jquery5.default)(link);
570 const oldSheet = findSheet($link.attr("href"));
571 const href = $link.attr("href") + "?restyle=" + (/* @__PURE__ */ new Date()).getTime();
572 if (isIE()) {
573 refreshStyle(href, oldSheet);
574 } else {
575 $link.attr("href", href);
576 $link.attr("onload", () => {
577 const $dummyEl = (0, import_jquery5.default)("<div>").css("transition", "0.1s all").css("position", "absolute").css("top", "-1000px").css("left", "0");
578 $dummyEl.one("transitionend", () => {
579 $dummyEl.remove();
580 removeSheet(oldSheet);
581 sendImageSizeFns.transitioned();
582 });
583 (0, import_jquery5.default)(document.body).append($dummyEl);
584 const color = "#" + Math.floor(Math.random() * 16777215).toString(16);
585 setTimeout(() => $dummyEl.css("color", color), 10);
586 });
587 $head.append(link);
588 }
589 });
590 }
591 function getStylesheetLinkTags(dep) {
592 return dep.stylesheet.map((x2) => {
593 if (x2.rel === void 0) x2.rel = "stylesheet";
594 if (x2.type === void 0) x2.type = "text/css";
595 const link = document.createElement("link");
596 Object.entries(x2).forEach(function([attr, val]) {
597 if (attr === "href") {
598 val = encodeURI(val);
599 }
600 link.setAttribute(attr, val ? val : "");
601 });
602 return link;
603 });
604 }
605 function appendStylesheetLinkTags(dep, $head) {
606 const stylesheetLinks = getStylesheetLinkTags(dep);
607 if (stylesheetLinks.length !== 0) {
608 $head.append(stylesheetLinks);
609 }
610 }
611 function appendScriptTags(dep, $head) {
612 dep.script.forEach((x2) => {
613 const script = document.createElement("script");
614 Object.entries(x2).forEach(function([attr, val]) {
615 if (attr === "src") {
616 val = encodeURI(val);
617 }
618 script.setAttribute(attr, val ? val : "");
619 });
620 $head.append(script);
621 });
622 }
623 async function appendScriptTagsAsync(dep) {
624 const scriptPromises = [];
625 dep.script.forEach((x2) => {
626 const script = document.createElement("script");
627 if (!hasDefinedProperty(x2, "async")) {
628 script.async = false;
629 }
630 Object.entries(x2).forEach(function([attr, val]) {
631 if (attr === "src") {
632 val = encodeURI(val);
633 }
634 script.setAttribute(attr, val ? val : "");
635 });
636 const p3 = new Promise((resolve, reject) => {
637 script.onload = (e4) => {
638 resolve(null);
639 };
640 script.onerror = (e4) => {
641 reject(e4);
642 };
643 });
644 scriptPromises.push(p3);
645 document.head.append(script);
646 });
647 await Promise.allSettled(scriptPromises);
648 }
649 function appendMetaTags(dep, $head) {
650 dep.meta.forEach((x2) => {
651 const meta = document.createElement("meta");
652 for (const [attr, val] of Object.entries(x2)) {
653 meta.setAttribute(attr, val);
654 }
655 $head.append(meta);
656 });
657 }
658 function appendAttachmentLinkTags(dep, $head) {
659 dep.attachment.forEach((x2) => {
660 const link = (0, import_jquery5.default)("<link rel='attachment'>").attr("id", dep.name + "-" + x2.key + "-attachment").attr("href", encodeURI(x2.href));
661 $head.append(link);
662 });
663 }
664 function appendExtraHeadContent(dep, $head) {
665 if (dep.head) {
666 const $newHead = (0, import_jquery5.default)("<head></head>");
667 $newHead.html(dep.head);
668 $head.append($newHead.children());
669 }
670 }
671 async function renderDependencyAsync(dep_) {
672 const dep = normalizeHtmlDependency(dep_);
673 if (needsRestyle(dep)) {
674 addStylesheetsAndRestyle(getStylesheetLinkTags(dep));
675 return true;
676 }
677 if (hasDefinedProperty(htmlDependencies, dep.name)) return false;
678 registerDependency(dep.name, dep.version);
679 const $head = (0, import_jquery5.default)("head").first();
680 appendMetaTags(dep, $head);
681 appendStylesheetLinkTags(dep, $head);
682 await appendScriptTagsAsync(dep);
683 appendAttachmentLinkTags(dep, $head);
684 appendExtraHeadContent(dep, $head);
685 return true;
686 }
687 function renderDependency(dep_) {
688 const dep = normalizeHtmlDependency(dep_);
689 if (needsRestyle(dep)) {
690 addStylesheetsAndRestyle(getStylesheetLinkTags(dep));
691 return true;
692 }
693 if (hasDefinedProperty(htmlDependencies, dep.name)) return false;
694 registerDependency(dep.name, dep.version);
695 const $head = (0, import_jquery5.default)("head").first();
696 appendMetaTags(dep, $head);
697 appendStylesheetLinkTags(dep, $head);
698 appendScriptTags(dep, $head);
699 appendAttachmentLinkTags(dep, $head);
700 appendExtraHeadContent(dep, $head);
701 return true;
702 }
703 function normalizeHtmlDependency(dep) {
704 const hrefPrefix = dep.src?.href;
705 const result = {
706 name: dep.name,
707 version: dep.version,
708 restyle: dep.restyle,
709 meta: [],
710 stylesheet: [],
711 script: [],
712 attachment: [],
713 head: dep.head
714 };
715 if (dep.meta) {
716 if (Array.isArray(dep.meta)) {
717 result.meta = dep.meta;
718 } else {
719 result.meta = Object.entries(dep.meta).map(function([attr, val]) {
720 return { name: attr, content: val };
721 });
722 }
723 }
724 result.stylesheet = asArray(dep.stylesheet).map((s4) => {
725 if (typeof s4 === "string") {
726 s4 = { href: s4 };
727 }
728 if (hrefPrefix) {
729 s4.href = hrefPrefix + "/" + s4.href;
730 }
731 return s4;
732 });
733 result.script = asArray(dep.script).map((s4) => {
734 if (typeof s4 === "string") {
735 s4 = { src: s4 };
736 }
737 if (hrefPrefix) {
738 s4.src = hrefPrefix + "/" + s4.src;
739 }
740 return s4;
741 });
742 let attachments = dep.attachment;
743 if (!attachments) attachments = [];
744 if (typeof attachments === "string") attachments = [attachments];
745 if (Array.isArray(attachments)) {
746 const tmp = attachments;
747 attachments = tmp.map((attachment, index) => {
748 if (typeof attachment === "string") {
749 return {
750 key: (index + 1).toString(),
751 href: attachment
752 };
753 } else {
754 return attachment;
755 }
756 });
757 } else {
758 attachments = Object.entries(attachments).map(function([attr, val]) {
759 return { key: attr, href: val };
760 });
761 }
762 result.attachment = attachments.map((s4) => {
763 if (hrefPrefix) {
764 s4.href = hrefPrefix + "/" + s4.href;
765 }
766 return s4;
767 });
768 return result;
769 }
770
771 // srcts/src/window/pixelRatio.ts
772 function windowDevicePixelRatio() {
773 return window.devicePixelRatio;
774 }
775
776 // srcts/src/utils/index.ts
777 function escapeHTML(str) {
778 const escaped = {
779 "&": "&amp;",
780 "<": "&lt;",
781 ">": "&gt;",
782 '"': "&quot;",
783 "'": "&#039;",
784 "/": "&#x2F;"
785 };
786 return str.replace(/[&<>'"/]/g, function(m2) {
787 return escaped[m2];
788 });
789 }
790 function randomId() {
791 return Math.floor(4294967296 + Math.random() * 64424509440).toString(16);
792 }
793 function strToBool(str) {
794 if (!str || !str.toLowerCase) return void 0;
795 switch (str.toLowerCase()) {
796 case "true":
797 return true;
798 case "false":
799 return false;
800 default:
801 return void 0;
802 }
803 }
804 function getStyle(el, styleProp) {
805 let x2 = void 0;
806 if ("currentStyle" in el) {
807 x2 = el.currentStyle[styleProp];
808 } else {
809 const style = document?.defaultView?.getComputedStyle(el, null);
810 if (style) x2 = style.getPropertyValue(styleProp);
811 }
812 return x2;
813 }
814 function padZeros(n4, digits) {
815 let str = n4.toString();
816 while (str.length < digits) str = "0" + str;
817 return str;
818 }
819 function roundSignif(x2, digits = 1) {
820 if (digits < 1) throw "Significant digits must be at least 1.";
821 return parseFloat(x2.toPrecision(digits));
822 }
823 function parseDate(dateString) {
824 let date = new Date(dateString);
825 if (date.toString() === "Invalid Date") {
826 date = new Date(dateString.replace(/-/g, "/"));
827 }
828 return date;
829 }
830 function formatDateUTC(date) {
831 if (date instanceof Date) {
832 return date.getUTCFullYear() + "-" + padZeros(date.getUTCMonth() + 1, 2) + "-" + padZeros(date.getUTCDate(), 2);
833 } else {
834 return null;
835 }
836 }
837 function makeResizeFilter(el, func) {
838 let lastSize = {};
839 return function() {
840 const rect = el.getBoundingClientRect();
841 const size = { w: rect.width, h: rect.height };
842 if (size.w === 0 && size.h === 0) return;
843 if (size.w === lastSize.w && size.h === lastSize.h) return;
844 lastSize = size;
845 func(size.w, size.h);
846 };
847 }
848 function pixelRatio() {
849 if (windowDevicePixelRatio()) {
850 return Math.round(windowDevicePixelRatio() * 100) / 100;
851 } else {
852 return 1;
853 }
854 }
855 function getBoundingClientSizeBeforeZoom(el) {
856 const rect = el.getBoundingClientRect();
857 const zoom = el.currentCSSZoom || 1;
858 return {
859 width: rect.width / zoom,
860 height: rect.height / zoom
861 };
862 }
863 function scopeExprToFunc(expr) {
864 const exprEscaped = expr.replace(/[\\"']/g, "\\$&").replace(/\u0000/g, "\\0").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/[\b]/g, "\\b");
865 let func;
866 try {
867 func = new Function(
868 `with (this) {
869 try {
870 return (${expr});
871 } catch (e) {
872 console.error('Error evaluating expression: ${exprEscaped}');
873 throw e;
874 }
875 }`
876 );
877 } catch (e4) {
878 console.error("Error parsing expression: " + expr);
879 throw e4;
880 }
881 return function(scope) {
882 return func.call(scope);
883 };
884 }
885 function mergeSort(list, sortfunc) {
886 function merge(a3, b3) {
887 let ia = 0;
888 let ib = 0;
889 const sorted = [];
890 while (ia < a3.length && ib < b3.length) {
891 if (Number(sortfunc(a3[ia], b3[ib])) <= 0) {
892 sorted.push(a3[ia++]);
893 } else {
894 sorted.push(b3[ib++]);
895 }
896 }
897 while (ia < a3.length) sorted.push(a3[ia++]);
898 while (ib < b3.length) sorted.push(b3[ib++]);
899 return sorted;
900 }
901 list = list.slice(0);
902 for (let chunkSize = 1; chunkSize < list.length; chunkSize *= 2) {
903 for (let i5 = 0; i5 < list.length; i5 += chunkSize * 2) {
904 const listA = list.slice(i5, i5 + chunkSize);
905 const listB = list.slice(i5 + chunkSize, i5 + chunkSize * 2);
906 const merged = merge(listA, listB);
907 const args = [i5, merged.length];
908 Array.prototype.push.apply(args, merged);
909 Array.prototype.splice.apply(list, args);
910 }
911 }
912 return list;
913 }
914 function $escape(val) {
915 if (typeof val === "undefined") return val;
916 return val.replace(/([!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g, "\\$1");
917 }
918 function mapValues(obj, f3) {
919 const newObj = {};
920 Object.keys(obj).forEach((key) => {
921 newObj[key] = f3(obj[key], key, obj);
922 });
923 return newObj;
924 }
925 function isnan(x2) {
926 return typeof x2 === "number" && isNaN(x2);
927 }
928 function _equal(x2, y3) {
929 if (import_jquery6.default.type(x2) === "object" && import_jquery6.default.type(y3) === "object") {
930 const xo = x2;
931 const yo = y3;
932 if (Object.keys(xo).length !== Object.keys(yo).length) return false;
933 for (const prop in xo) {
934 if (!hasOwnProperty(yo, prop) || !_equal(xo[prop], yo[prop]))
935 return false;
936 }
937 return true;
938 } else if (import_jquery6.default.type(x2) === "array" && import_jquery6.default.type(y3) === "array") {
939 const xa = x2;
940 const ya = y3;
941 if (xa.length !== ya.length) return false;
942 for (let i5 = 0; i5 < xa.length; i5++) if (!_equal(xa[i5], ya[i5])) return false;
943 return true;
944 } else {
945 return x2 === y3;
946 }
947 }
948 function equal(...args) {
949 if (args.length < 2)
950 throw new Error("equal requires at least two arguments.");
951 for (let i5 = 0; i5 < args.length - 1; i5++) {
952 if (!_equal(args[i5], args[i5 + 1])) return false;
953 }
954 return true;
955 }
956 var compareVersion = function(a3, op, b3) {
957 function versionParts(ver) {
958 return (ver + "").replace(/-/, ".").replace(/(\.0)+[^.]*$/, "").split(".");
959 }
960 function cmpVersion(a4, b4) {
961 const aParts = versionParts(a4);
962 const bParts = versionParts(b4);
963 const len = Math.min(aParts.length, bParts.length);
964 let cmp;
965 for (let i5 = 0; i5 < len; i5++) {
966 cmp = parseInt(aParts[i5], 10) - parseInt(bParts[i5], 10);
967 if (cmp !== 0) {
968 return cmp;
969 }
970 }
971 return aParts.length - bParts.length;
972 }
973 const diff = cmpVersion(a3, b3);
974 if (op === "==") return diff === 0;
975 else if (op === ">=") return diff >= 0;
976 else if (op === ">") return diff > 0;
977 else if (op === "<=") return diff <= 0;
978 else if (op === "<") return diff < 0;
979 else throw `Unknown operator: ${op}`;
980 };
981 async function updateLabel(labelContent, labelNode) {
982 if (typeof labelContent === "undefined") return;
983 if (labelNode.length !== 1) {
984 throw new Error("labelNode must be of length 1");
985 }
986 if (typeof labelContent === "string") {
987 labelContent = {
988 html: labelContent,
989 deps: []
990 };
991 }
992 if (labelContent.html === "") {
993 labelNode.addClass("shiny-label-null");
994 } else {
995 await renderContent(labelNode, labelContent);
996 labelNode.removeClass("shiny-label-null");
997 }
998 }
999 function getComputedLinkColor(el) {
1000 const a3 = document.createElement("a");
1001 a3.href = "/";
1002 const div = document.createElement("div");
1003 div.style.setProperty("position", "absolute", "important");
1004 div.style.setProperty("top", "-1000px", "important");
1005 div.style.setProperty("left", "0", "important");
1006 div.style.setProperty("width", "30px", "important");
1007 div.style.setProperty("height", "10px", "important");
1008 div.appendChild(a3);
1009 el.appendChild(div);
1010 const linkColor = window.getComputedStyle(a3).getPropertyValue("color");
1011 el.removeChild(div);
1012 return linkColor;
1013 }
1014 function isBS3() {
1015 return !window.bootstrap;
1016 }
1017 function isShinyInDevMode() {
1018 if ("__SHINY_DEV_MODE__" in window) return Boolean(window.__SHINY_DEV_MODE__);
1019 return false;
1020 }
1021
1022 // srcts/src/bindings/registry.ts
1023 var BindingRegistry = class {
1024 constructor() {
1025 this.bindings = [];
1026 this.bindingNames = {};
1027 }
1028 register(binding, bindingName, priority = 0) {
1029 const bindingObj = { binding, priority };
1030 this.bindings.unshift(bindingObj);
1031 if (bindingName) {
1032 this.bindingNames[bindingName] = bindingObj;
1033 binding.name = bindingName;
1034 }
1035 }
1036 setPriority(bindingName, priority) {
1037 const bindingObj = this.bindingNames[bindingName];
1038 if (!bindingObj)
1039 throw "Tried to set priority on unknown binding " + bindingName;
1040 bindingObj.priority = priority || 0;
1041 }
1042 getPriority(bindingName) {
1043 const bindingObj = this.bindingNames[bindingName];
1044 if (!bindingObj) return false;
1045 return bindingObj.priority;
1046 }
1047 getBindings() {
1048 return mergeSort(this.bindings, function(a3, b3) {
1049 return b3.priority - a3.priority;
1050 });
1051 }
1052 };
1053
1054 // srcts/src/bindings/input/inputBinding.ts
1055 var InputBinding = class {
1056 // Returns a jQuery object or element array that contains the
1057 // descendants of scope that match this binding
1058 find(scope) {
1059 throw "Not implemented";
1060 scope;
1061 }
1062 getId(el) {
1063 return el.getAttribute("data-input-id") || el.id;
1064 }
1065 // Gives the input a type in case the server needs to know it
1066 // to deserialize the JSON correctly
1067 getType(el) {
1068 return null;
1069 el;
1070 }
1071 getValue(el) {
1072 throw "Not implemented";
1073 el;
1074 }
1075 subscribe(el, callback) {
1076 return;
1077 el;
1078 callback;
1079 }
1080 unsubscribe(el) {
1081 return;
1082 el;
1083 }
1084 // This is used for receiving messages that tell the input object to do
1085 // things, such as setting values (including min, max, and others).
1086 // 'data' should be an object with elements corresponding to value, min,
1087 // max, etc., as appropriate for the type of input object. It also should
1088 // trigger a change event.
1089 receiveMessage(el, data) {
1090 throw "Not implemented";
1091 el;
1092 data;
1093 }
1094 getState(el) {
1095 throw "Not implemented";
1096 el;
1097 }
1098 getRatePolicy(el) {
1099 return null;
1100 el;
1101 }
1102 // Some input objects need initialization before being bound. This is
1103 // called when the document is ready (for statically-added input objects),
1104 // and when new input objects are added to the document with
1105 // htmlOutputBinding.renderValue() (for dynamically-added input objects).
1106 // This is called before the input is bound.
1107 initialize(el) {
1108 return;
1109 el;
1110 }
1111 // This is called after unbinding the output.
1112 dispose(el) {
1113 return;
1114 el;
1115 }
1116 };
1117
1118 // srcts/src/bindings/input/actionbutton.ts
1119 var import_jquery7 = __toESM(require_jquery());
1120 var ActionButtonInputBinding = class extends InputBinding {
1121 find(scope) {
1122 return (0, import_jquery7.default)(scope).find(".action-button");
1123 }
1124 getValue(el) {
1125 return (0, import_jquery7.default)(el).data("val") || 0;
1126 }
1127 setValue(el, value) {
1128 (0, import_jquery7.default)(el).data("val", value);
1129 }
1130 getType(el) {
1131 return "shiny.action";
1132 el;
1133 }
1134 subscribe(el, callback) {
1135 (0, import_jquery7.default)(el).on(
1136 "click.actionButtonInputBinding",
1137 // e: Event
1138 function() {
1139 const $el = (0, import_jquery7.default)(this);
1140 const val = $el.data("val") || 0;
1141 $el.data("val", val + 1);
1142 callback(false);
1143 }
1144 );
1145 }
1146 getState(el) {
1147 return { value: this.getValue(el) };
1148 }
1149 async receiveMessage(el, data) {
1150 if (hasDefinedProperty(data, "icon")) {
1151 let iconContainer = el.querySelector(
1152 ":scope > .action-icon"
1153 );
1154 if (!iconContainer) {
1155 iconContainer = document.createElement("span");
1156 iconContainer.className = "action-icon";
1157 el.prepend(iconContainer);
1158 }
1159 await renderContent(iconContainer, data.icon);
1160 }
1161 if (hasDefinedProperty(data, "label")) {
1162 let labelContainer = el.querySelector(
1163 ":scope > .action-label"
1164 );
1165 if (!labelContainer) {
1166 labelContainer = document.createElement("span");
1167 labelContainer.className = "action-label";
1168 el.appendChild(labelContainer);
1169 }
1170 await renderContent(labelContainer, data.label);
1171 }
1172 if (hasDefinedProperty(data, "disabled")) {
1173 if (data.disabled) {
1174 el.setAttribute("disabled", "");
1175 } else {
1176 el.removeAttribute("disabled");
1177 }
1178 }
1179 return;
1180 }
1181 unsubscribe(el) {
1182 (0, import_jquery7.default)(el).off(".actionButtonInputBinding");
1183 }
1184 };
1185 (0, import_jquery7.default)(document).on("click", "a.action-button", function(e4) {
1186 e4.preventDefault();
1187 });
1188
1189 // srcts/src/bindings/input/checkbox.ts
1190 var import_jquery8 = __toESM(require_jquery());
1191 var CheckboxInputBinding = class extends InputBinding {
1192 find(scope) {
1193 return (0, import_jquery8.default)(scope).find('input[type="checkbox"]');
1194 }
1195 getValue(el) {
1196 return el.checked;
1197 }
1198 setValue(el, value) {
1199 el.checked = value;
1200 }
1201 subscribe(el, callback) {
1202 (0, import_jquery8.default)(el).on("change.checkboxInputBinding", function() {
1203 callback(true);
1204 });
1205 }
1206 unsubscribe(el) {
1207 (0, import_jquery8.default)(el).off(".checkboxInputBinding");
1208 }
1209 getState(el) {
1210 return {
1211 label: (0, import_jquery8.default)(el).parent().find("span").text(),
1212 value: el.checked
1213 };
1214 }
1215 async receiveMessage(el, data) {
1216 if (hasDefinedProperty(data, "value")) {
1217 el.checked = data.value;
1218 }
1219 if (hasDefinedProperty(data, "label")) {
1220 const labelSpan = (0, import_jquery8.default)(el).parent().find("span");
1221 await renderContent(labelSpan, data.label);
1222 }
1223 (0, import_jquery8.default)(el).trigger("change");
1224 }
1225 };
1226
1227 // srcts/src/bindings/input/checkboxgroup.ts
1228 var import_jquery9 = __toESM(require_jquery());
1229 function getLabelNode(el) {
1230 return (0, import_jquery9.default)(el).find('label[for="' + $escape(el.id) + '"]');
1231 }
1232 function getLabel(obj) {
1233 const parentNode = obj.parentNode;
1234 if (parentNode.tagName === "LABEL") {
1235 return (0, import_jquery9.default)(parentNode).find("span").text().trim();
1236 }
1237 return null;
1238 }
1239 var CheckboxGroupInputBinding = class extends InputBinding {
1240 find(scope) {
1241 return (0, import_jquery9.default)(scope).find(".shiny-input-checkboxgroup");
1242 }
1243 getValue(el) {
1244 const $objs = (0, import_jquery9.default)('input:checkbox[name="' + $escape(el.id) + '"]:checked');
1245 const values = new Array($objs.length);
1246 for (let i5 = 0; i5 < $objs.length; i5++) {
1247 values[i5] = $objs[i5].value;
1248 }
1249 return values;
1250 }
1251 setValue(el, value) {
1252 value = value ?? [];
1253 (0, import_jquery9.default)('input:checkbox[name="' + $escape(el.id) + '"]').prop("checked", false);
1254 if (value instanceof Array) {
1255 for (let i5 = 0; i5 < value.length; i5++) {
1256 (0, import_jquery9.default)(
1257 'input:checkbox[name="' + $escape(el.id) + '"][value="' + $escape(value[i5]) + '"]'
1258 ).prop("checked", true);
1259 }
1260 } else {
1261 (0, import_jquery9.default)(
1262 'input:checkbox[name="' + $escape(el.id) + '"][value="' + $escape(value) + '"]'
1263 ).prop("checked", true);
1264 }
1265 }
1266 getState(el) {
1267 const $objs = (0, import_jquery9.default)(
1268 'input:checkbox[name="' + $escape(el.id) + '"]'
1269 );
1270 const options = new Array($objs.length);
1271 for (let i5 = 0; i5 < options.length; i5++) {
1272 options[i5] = { value: $objs[i5].value, label: getLabel($objs[i5]) };
1273 }
1274 return {
1275 label: getLabelNode(el).text(),
1276 value: this.getValue(el),
1277 options
1278 };
1279 }
1280 async receiveMessage(el, data) {
1281 const $el = (0, import_jquery9.default)(el);
1282 if (hasDefinedProperty(data, "options")) {
1283 $el.find("div.shiny-options-group").remove();
1284 $el.find("label.checkbox").remove();
1285 $el.append(data.options);
1286 }
1287 if (hasDefinedProperty(data, "value")) {
1288 this.setValue(el, data.value);
1289 }
1290 await updateLabel(data.label, getLabelNode(el));
1291 (0, import_jquery9.default)(el).trigger("change");
1292 }
1293 subscribe(el, callback) {
1294 (0, import_jquery9.default)(el).on("change.checkboxGroupInputBinding", function() {
1295 callback(false);
1296 });
1297 }
1298 unsubscribe(el) {
1299 (0, import_jquery9.default)(el).off(".checkboxGroupInputBinding");
1300 }
1301 };
1302
1303 // srcts/src/bindings/input/date.ts
1304 var import_jquery10 = __toESM(require_jquery());
1305 var DateInputBindingBase = class extends InputBinding {
1306 find(scope) {
1307 return (0, import_jquery10.default)(scope).find(".shiny-date-input");
1308 }
1309 getType(el) {
1310 return "shiny.date";
1311 el;
1312 }
1313 subscribe(el, callback) {
1314 (0, import_jquery10.default)(el).on(
1315 "changeDate.dateInputBinding change.dateInputBinding",
1316 // event: Event
1317 function() {
1318 callback(false);
1319 }
1320 );
1321 }
1322 unsubscribe(el) {
1323 (0, import_jquery10.default)(el).off(".dateInputBinding");
1324 }
1325 getRatePolicy() {
1326 return {
1327 policy: "debounce",
1328 delay: 250
1329 };
1330 }
1331 setValue(el, data) {
1332 throw "not implemented";
1333 el;
1334 data;
1335 }
1336 initialize(el) {
1337 const $input = (0, import_jquery10.default)(el).find("input");
1338 let date = $input.data("initial-date");
1339 if (date === void 0 || date === null) {
1340 date = this._floorDateTime(this._dateAsUTC(/* @__PURE__ */ new Date()));
1341 }
1342 this.setValue(el, date);
1343 if ($input.data("min-date") !== void 0) {
1344 this._setMin($input[0], $input.data("min-date"));
1345 }
1346 if ($input.data("max-date") !== void 0) {
1347 this._setMax($input[0], $input.data("max-date"));
1348 }
1349 }
1350 _getLabelNode(el) {
1351 return (0, import_jquery10.default)(el).find('label[for="' + $escape(el.id) + '"]');
1352 }
1353 // Given a format object from a date picker, return a string
1354 _formatToString(format) {
1355 let str = "";
1356 let i5;
1357 for (i5 = 0; i5 < format.parts.length; i5++) {
1358 str += format.separators[i5] + format.parts[i5];
1359 }
1360 str += format.separators[i5];
1361 return str;
1362 }
1363 // Given an unambiguous date string or a Date object, set the min (start) date.
1364 // null will unset. undefined will result in no change,
1365 _setMin(el, date) {
1366 if (date === null) {
1367 (0, import_jquery10.default)(el).bsDatepicker("setStartDate", null);
1368 return;
1369 }
1370 const parsedDate = this._newDate(date);
1371 if (parsedDate === null) return;
1372 date = parsedDate;
1373 if (isNaN(date.valueOf())) return;
1374 const curValue = (0, import_jquery10.default)(el).bsDatepicker("getUTCDate");
1375 (0, import_jquery10.default)(el).bsDatepicker("setStartDate", this._utcDateAsLocal(date));
1376 if (date && curValue && date.getTime() > curValue.getTime()) {
1377 (0, import_jquery10.default)(el).bsDatepicker("clearDates");
1378 } else {
1379 (0, import_jquery10.default)(el).bsDatepicker("setUTCDate", curValue);
1380 }
1381 }
1382 // Given an unambiguous date string or a Date object, set the max (end) date
1383 // null will unset.
1384 _setMax(el, date) {
1385 if (date === null) {
1386 (0, import_jquery10.default)(el).bsDatepicker("setEndDate", null);
1387 return;
1388 }
1389 const parsedDate = this._newDate(date);
1390 if (parsedDate === null) return;
1391 date = parsedDate;
1392 if (isNaN(date.valueOf())) return;
1393 const curValue = (0, import_jquery10.default)(el).bsDatepicker("getUTCDate");
1394 (0, import_jquery10.default)(el).bsDatepicker("setEndDate", this._utcDateAsLocal(date));
1395 if (date && curValue && date.getTime() < curValue.getTime()) {
1396 (0, import_jquery10.default)(el).bsDatepicker("clearDates");
1397 } else {
1398 (0, import_jquery10.default)(el).bsDatepicker("setUTCDate", curValue);
1399 }
1400 }
1401 // Given a date string of format yyyy-mm-dd, return a Date object with
1402 // that date at 12AM UTC.
1403 // If date is a Date object, return it unchanged.
1404 _newDate(date) {
1405 if (date instanceof Date) return date;
1406 if (!date) return null;
1407 const d3 = parseDate(date);
1408 if (isNaN(d3.valueOf())) return null;
1409 return d3;
1410 }
1411 // A Date can have any time during a day; this will return a new Date object
1412 // set to 00:00 in UTC.
1413 _floorDateTime(date) {
1414 date = new Date(date.getTime());
1415 date.setUTCHours(0, 0, 0, 0);
1416 return date;
1417 }
1418 // Given a Date object, return a Date object which has the same "clock time"
1419 // in UTC. For example, if input date is 2013-02-01 23:00:00 GMT-0600 (CST),
1420 // output will be 2013-02-01 23:00:00 UTC. Note that the JS console may
1421 // print this in local time, as "Sat Feb 02 2013 05:00:00 GMT-0600 (CST)".
1422 _dateAsUTC(date) {
1423 return new Date(date.getTime() - date.getTimezoneOffset() * 6e4);
1424 }
1425 // The inverse of _dateAsUTC. This is needed to adjust time zones because
1426 // some bootstrap-datepicker methods only take local dates as input, and not
1427 // UTC.
1428 _utcDateAsLocal(date) {
1429 return new Date(date.getTime() + date.getTimezoneOffset() * 6e4);
1430 }
1431 };
1432 var DateInputBinding = class extends DateInputBindingBase {
1433 // Return the date in an unambiguous format, yyyy-mm-dd (as opposed to a
1434 // format like mm/dd/yyyy)
1435 getValue(el) {
1436 const date = (0, import_jquery10.default)(el).find("input").bsDatepicker("getUTCDate");
1437 return formatDateUTC(date);
1438 }
1439 // value must be an unambiguous string like '2001-01-01', or a Date object.
1440 setValue(el, value) {
1441 if (value === null) {
1442 (0, import_jquery10.default)(el).find("input").val("").bsDatepicker("update");
1443 return;
1444 }
1445 const date = this._newDate(value);
1446 if (date === null) {
1447 return;
1448 }
1449 if (isNaN(date.valueOf())) return;
1450 (0, import_jquery10.default)(el).find("input").bsDatepicker("setUTCDate", date);
1451 }
1452 getState(el) {
1453 const $el = (0, import_jquery10.default)(el);
1454 const $input = $el.find("input");
1455 let min = $input.data("datepicker").startDate;
1456 let max = $input.data("datepicker").endDate;
1457 min = min === -Infinity ? null : formatDateUTC(min);
1458 max = max === Infinity ? null : formatDateUTC(max);
1459 let startview = $input.data("datepicker").startViewMode;
1460 if (startview === 2) startview = "decade";
1461 else if (startview === 1) startview = "year";
1462 else if (startview === 0) startview = "month";
1463 return {
1464 label: this._getLabelNode(el).text(),
1465 value: this.getValue(el),
1466 valueString: $input.val(),
1467 min,
1468 max,
1469 language: $input.data("datepicker").language,
1470 weekstart: $input.data("datepicker").weekStart,
1471 format: this._formatToString($input.data("datepicker").format),
1472 startview
1473 };
1474 }
1475 async receiveMessage(el, data) {
1476 const $input = (0, import_jquery10.default)(el).find("input");
1477 await updateLabel(data.label, this._getLabelNode(el));
1478 if (hasDefinedProperty(data, "min")) this._setMin($input[0], data.min);
1479 if (hasDefinedProperty(data, "max")) this._setMax($input[0], data.max);
1480 if (hasDefinedProperty(data, "value")) this.setValue(el, data.value);
1481 (0, import_jquery10.default)(el).trigger("change");
1482 }
1483 };
1484
1485 // srcts/src/bindings/input/daterange.ts
1486 var import_jquery11 = __toESM(require_jquery());
1487 function getLabelNode2(el) {
1488 return (0, import_jquery11.default)(el).find('label[for="' + $escape(el.id) + '"]');
1489 }
1490 var DateRangeInputBinding = class extends DateInputBindingBase {
1491 find(scope) {
1492 return (0, import_jquery11.default)(scope).find(".shiny-date-range-input");
1493 }
1494 // Return the date in an unambiguous format, yyyy-mm-dd (as opposed to a
1495 // format like mm/dd/yyyy)
1496 getValue(el) {
1497 const $inputs = (0, import_jquery11.default)(el).find("input");
1498 const start = $inputs.eq(0).bsDatepicker("getUTCDate");
1499 const end = $inputs.eq(1).bsDatepicker("getUTCDate");
1500 return [formatDateUTC(start), formatDateUTC(end)];
1501 }
1502 // value must be an object, with optional fields `start` and `end`. These
1503 // should be unambiguous strings like '2001-01-01', or Date objects.
1504 setValue(el, value) {
1505 if (!(value instanceof Object)) {
1506 return;
1507 }
1508 const $inputs = (0, import_jquery11.default)(el).find("input");
1509 if (value.start !== void 0) {
1510 if (value.start === null) {
1511 $inputs.eq(0).val("").bsDatepicker("update");
1512 } else {
1513 const start = this._newDate(value.start);
1514 $inputs.eq(0).bsDatepicker("setUTCDate", start);
1515 }
1516 }
1517 if (value.end !== void 0) {
1518 if (value.end === null) {
1519 $inputs.eq(1).val("").bsDatepicker("update");
1520 } else {
1521 const end = this._newDate(value.end);
1522 $inputs.eq(1).bsDatepicker("setUTCDate", end);
1523 }
1524 }
1525 }
1526 getState(el) {
1527 const $el = (0, import_jquery11.default)(el);
1528 const $inputs = $el.find("input");
1529 const $startinput = $inputs.eq(0);
1530 const $endinput = $inputs.eq(1);
1531 const min = $startinput.bsDatepicker("getStartDate");
1532 const max = $startinput.bsDatepicker("getEndDate");
1533 const minStr = min === -Infinity ? null : formatDateUTC(min);
1534 const maxStr = max === Infinity ? null : formatDateUTC(max);
1535 let startview = $startinput.data("datepicker").startView;
1536 if (startview === 2) startview = "decade";
1537 else if (startview === 1) startview = "year";
1538 else if (startview === 0) startview = "month";
1539 return {
1540 label: getLabelNode2(el).text(),
1541 value: this.getValue(el),
1542 valueString: [$startinput.val(), $endinput.val()],
1543 min: minStr,
1544 max: maxStr,
1545 weekstart: $startinput.data("datepicker").weekStart,
1546 format: this._formatToString($startinput.data("datepicker").format),
1547 language: $startinput.data("datepicker").language,
1548 startview
1549 };
1550 }
1551 async receiveMessage(el, data) {
1552 const $el = (0, import_jquery11.default)(el);
1553 const $inputs = $el.find("input");
1554 const $startinput = $inputs.eq(0);
1555 const $endinput = $inputs.eq(1);
1556 await updateLabel(data.label, getLabelNode2(el));
1557 if (hasDefinedProperty(data, "min")) {
1558 this._setMin($startinput[0], data.min);
1559 this._setMin($endinput[0], data.min);
1560 }
1561 if (hasDefinedProperty(data, "max")) {
1562 this._setMax($startinput[0], data.max);
1563 this._setMax($endinput[0], data.max);
1564 }
1565 if (hasDefinedProperty(data, "value")) {
1566 this.setValue(el, data.value);
1567 }
1568 $el.trigger("change");
1569 }
1570 initialize(el) {
1571 const $el = (0, import_jquery11.default)(el);
1572 const $inputs = $el.find("input");
1573 const $startinput = $inputs.eq(0);
1574 const $endinput = $inputs.eq(1);
1575 let start = $startinput.data("initial-date");
1576 let end = $endinput.data("initial-date");
1577 if (start === void 0 || start === null)
1578 start = this._dateAsUTC(/* @__PURE__ */ new Date());
1579 if (end === void 0 || end === null) end = this._dateAsUTC(/* @__PURE__ */ new Date());
1580 this.setValue(el, { start, end });
1581 this._setMin($startinput[0], $startinput.data("min-date"));
1582 this._setMin($endinput[0], $startinput.data("min-date"));
1583 this._setMax($startinput[0], $endinput.data("max-date"));
1584 this._setMax($endinput[0], $endinput.data("max-date"));
1585 }
1586 subscribe(el, callback) {
1587 (0, import_jquery11.default)(el).on(
1588 "changeDate.dateRangeInputBinding change.dateRangeInputBinding",
1589 // event: Event
1590 function() {
1591 callback(false);
1592 }
1593 );
1594 }
1595 unsubscribe(el) {
1596 (0, import_jquery11.default)(el).off(".dateRangeInputBinding");
1597 }
1598 };
1599
1600 // srcts/src/bindings/input/fileinput.ts
1601 var import_jquery14 = __toESM(require_jquery());
1602
1603 // srcts/src/file/fileProcessor.ts
1604 var import_jquery13 = __toESM(require_jquery());
1605
1606 // srcts/src/events/inputChanged.ts
1607 var import_jquery12 = __toESM(require_jquery());
1608 function triggerFileInputChanged(name, value, binding, el, inputType, onEl) {
1609 const evt = import_jquery12.default.Event("shiny:inputchanged");
1610 evt.name = name;
1611 evt.value = value;
1612 evt.binding = binding;
1613 evt.el = el;
1614 evt.inputType = inputType;
1615 (0, import_jquery12.default)(onEl).trigger(evt);
1616 return evt;
1617 }
1618
1619 // srcts/src/file/fileProcessor.ts
1620 var FileProcessor = class {
1621 constructor(files, exec$run = true) {
1622 this.fileIndex = -1;
1623 // Currently need to use small chunk size because R-Websockets can't
1624 // handle continuation frames
1625 this.aborted = false;
1626 this.completed = false;
1627 this.files = Array.from(files);
1628 if (exec$run) {
1629 this.$run();
1630 }
1631 }
1632 // Begin callbacks. Subclassers/cloners may override any or all of these.
1633 onBegin(files, cont) {
1634 setTimeout(cont, 0);
1635 return;
1636 files;
1637 }
1638 onFile(file, cont) {
1639 setTimeout(cont, 0);
1640 return;
1641 file;
1642 }
1643 onComplete() {
1644 return;
1645 }
1646 onAbort() {
1647 return;
1648 }
1649 // End callbacks
1650 // Aborts processing, unless it's already completed
1651 abort() {
1652 if (this.completed || this.aborted) return;
1653 this.aborted = true;
1654 this.onAbort();
1655 }
1656 // Returns a bound function that will call this.$run one time.
1657 $getRun() {
1658 let called = false;
1659 return () => {
1660 if (called) return;
1661 called = true;
1662 this.$run();
1663 };
1664 }
1665 // This function will be called multiple times to advance the process.
1666 // It relies on the state of the object's fields to know what to do next.
1667 $run() {
1668 if (this.aborted || this.completed) return;
1669 if (this.fileIndex < 0) {
1670 this.fileIndex = 0;
1671 this.onBegin(this.files, this.$getRun());
1672 return;
1673 }
1674 if (this.fileIndex === this.files.length) {
1675 this.completed = true;
1676 this.onComplete();
1677 return;
1678 }
1679 const file = this.files[this.fileIndex++];
1680 this.onFile(file, this.$getRun());
1681 }
1682 };
1683 var FileUploader = class extends FileProcessor {
1684 constructor(shinyapp, id, files, el) {
1685 super(files, false);
1686 this.shinyapp = shinyapp;
1687 this.id = id;
1688 this.el = el;
1689 this.$run();
1690 }
1691 makeRequest(method, args, onSuccess, onFailure, blobs) {
1692 this.shinyapp.makeRequest(method, args, onSuccess, onFailure, blobs);
1693 }
1694 onBegin(files, cont) {
1695 this.$setError(null);
1696 this.$setActive(true);
1697 this.$setVisible(true);
1698 this.onProgress(null, 0);
1699 this.totalBytes = 0;
1700 this.progressBytes = 0;
1701 import_jquery13.default.each(files, (i5, file) => {
1702 this.totalBytes += file.size;
1703 });
1704 const fileInfo = import_jquery13.default.map(files, function(file) {
1705 return {
1706 name: file.name,
1707 size: file.size,
1708 type: file.type
1709 };
1710 });
1711 this.makeRequest(
1712 "uploadInit",
1713 [fileInfo],
1714 (response) => {
1715 this.jobId = response.jobId;
1716 this.uploadUrl = response.uploadUrl;
1717 cont();
1718 },
1719 (error) => {
1720 this.onError(error);
1721 },
1722 void 0
1723 );
1724 }
1725 onFile(file, cont) {
1726 this.onProgress(file, 0);
1727 import_jquery13.default.ajax(this.uploadUrl, {
1728 type: "POST",
1729 cache: false,
1730 xhr: () => {
1731 if (typeof import_jquery13.default.ajaxSettings.xhr !== "function")
1732 throw "jQuery's XHR is not a function";
1733 const xhrVal = import_jquery13.default.ajaxSettings.xhr();
1734 if (xhrVal.upload) {
1735 xhrVal.upload.onprogress = (e4) => {
1736 if (e4.lengthComputable) {
1737 this.onProgress(
1738 file,
1739 (this.progressBytes + e4.loaded) / this.totalBytes
1740 );
1741 }
1742 };
1743 }
1744 return xhrVal;
1745 },
1746 data: file,
1747 contentType: "application/octet-stream",
1748 processData: false,
1749 success: () => {
1750 this.progressBytes += file.size;
1751 cont();
1752 },
1753 error: (jqXHR, textStatus, errorThrown) => {
1754 this.onError(jqXHR.responseText || textStatus);
1755 return;
1756 errorThrown;
1757 }
1758 });
1759 }
1760 onComplete() {
1761 const fileInfo = import_jquery13.default.map(this.files, function(file, i5) {
1762 return {
1763 name: file.name,
1764 size: file.size,
1765 type: file.type
1766 };
1767 i5;
1768 });
1769 const evt = triggerFileInputChanged(
1770 this.id,
1771 fileInfo,
1772 getFileInputBinding(),
1773 this.el,
1774 "shiny.fileupload",
1775 document
1776 );
1777 this.makeRequest(
1778 "uploadEnd",
1779 [this.jobId, this.id],
1780 () => {
1781 this.$setActive(false);
1782 this.onProgress(null, 1);
1783 this.$bar().text("Upload complete");
1784 (0, import_jquery13.default)(evt.el).val("");
1785 },
1786 (error) => {
1787 this.onError(error);
1788 },
1789 void 0
1790 );
1791 this.$bar().text("Finishing upload");
1792 }
1793 onError(message) {
1794 this.$setError(message || "");
1795 this.$setActive(false);
1796 }
1797 onAbort() {
1798 this.$setVisible(false);
1799 }
1800 onProgress(file, completed) {
1801 this.$bar().width(Math.round(completed * 100) + "%");
1802 this.$bar().text(file ? file.name : "");
1803 }
1804 $container() {
1805 return (0, import_jquery13.default)("#" + $escape(this.id) + "_progress.shiny-file-input-progress");
1806 }
1807 $bar() {
1808 return (0, import_jquery13.default)(
1809 "#" + $escape(this.id) + "_progress.shiny-file-input-progress .progress-bar"
1810 );
1811 }
1812 $setVisible(visible) {
1813 this.$container().css("visibility", visible ? "visible" : "hidden");
1814 }
1815 $setError(error) {
1816 this.$bar().toggleClass("progress-bar-danger", error !== null);
1817 if (error !== null) {
1818 this.onProgress(null, 1);
1819 this.$bar().text(error);
1820 }
1821 }
1822 $setActive(active) {
1823 this.$container().toggleClass("active", !!active);
1824 }
1825 };
1826
1827 // srcts/src/bindings/input/fileinput.ts
1828 var zoneActive = "shiny-file-input-active";
1829 var zoneOver = "shiny-file-input-over";
1830 function zoneOf(el) {
1831 return (0, import_jquery14.default)(el).closest("div.input-group");
1832 }
1833 function enableDraghover(el) {
1834 const $el = (0, import_jquery14.default)(el);
1835 let childCounter = 0;
1836 $el.on({
1837 "dragenter.draghover": (e4) => {
1838 if (childCounter++ === 0) {
1839 $el.trigger("draghover:enter", e4);
1840 }
1841 },
1842 "dragleave.draghover": (e4) => {
1843 if (--childCounter === 0) {
1844 $el.trigger("draghover:leave", e4);
1845 }
1846 if (childCounter < 0) {
1847 console.error("draghover childCounter is negative somehow");
1848 }
1849 },
1850 "dragover.draghover": (e4) => {
1851 e4.preventDefault();
1852 },
1853 "drop.draghover": (e4) => {
1854 childCounter = 0;
1855 $el.trigger("draghover:drop", e4);
1856 e4.preventDefault();
1857 }
1858 });
1859 return $el;
1860 }
1861 function disableDraghover(el) {
1862 return (0, import_jquery14.default)(el).off(".draghover");
1863 }
1864 function enableDocumentEvents() {
1865 const $doc = (0, import_jquery14.default)("html");
1866 enableDraghover($doc).on({
1867 "draghover:enter.draghover": (
1868 // e: Event
1869 () => {
1870 zoneOf($fileInputs).addClass(zoneActive);
1871 }
1872 ),
1873 "draghover:leave.draghover": (
1874 // e: Event
1875 () => {
1876 zoneOf($fileInputs).removeClass(zoneActive);
1877 }
1878 ),
1879 "draghover:drop.draghover": (
1880 // e: Event
1881 () => {
1882 zoneOf($fileInputs).removeClass(zoneOver).removeClass(zoneActive);
1883 }
1884 )
1885 });
1886 }
1887 function disableDocumentEvents() {
1888 const $doc = (0, import_jquery14.default)("html");
1889 $doc.off(".draghover");
1890 disableDraghover($doc);
1891 }
1892 function canSetFiles(fileList) {
1893 const testEl = document.createElement("input");
1894 testEl.type = "file";
1895 try {
1896 testEl.files = fileList;
1897 } catch (e4) {
1898 return false;
1899 e4;
1900 }
1901 return true;
1902 }
1903 function handleDrop(e4, el) {
1904 const files = e4.originalEvent?.dataTransfer?.files, $el = (0, import_jquery14.default)(el);
1905 if (files === void 0 || files === null) {
1906 console.log(
1907 "Dropping files is not supported on this browser. (no FileList)"
1908 );
1909 } else if (!canSetFiles(files)) {
1910 $el.val("");
1911 uploadDroppedFilesIE10Plus(el, files);
1912 } else {
1913 $el.val("");
1914 el.files = files;
1915 $el.trigger("change");
1916 }
1917 }
1918 function setFileText($el, files) {
1919 const $fileText = $el.closest("div.input-group").find("input[type=text]");
1920 if (files.length === 1) {
1921 $fileText.val(files[0].name);
1922 } else {
1923 $fileText.val(files.length + " files");
1924 }
1925 }
1926 function abortCurrentUpload($el) {
1927 const uploader = $el.data("currentUploader");
1928 if (uploader) uploader.abort();
1929 $el.removeAttr("data-restore");
1930 }
1931 function uploadDroppedFilesIE10Plus(el, files) {
1932 const $el = (0, import_jquery14.default)(el);
1933 abortCurrentUpload($el);
1934 setFileText($el, files);
1935 $el.data(
1936 "currentUploader",
1937 new FileUploader(shinyShinyApp(), fileInputBindingGetId(el), files, el)
1938 );
1939 }
1940 function uploadFiles(evt) {
1941 const $el = (0, import_jquery14.default)(evt.target);
1942 abortCurrentUpload($el);
1943 const files = evt.target.files;
1944 const id = fileInputBindingGetId(evt.target);
1945 if (files.length === 0) return;
1946 setFileText($el, files);
1947 $el.data(
1948 "currentUploader",
1949 new FileUploader(shinyShinyApp(), id, files, evt.target)
1950 );
1951 }
1952 var $fileInputs = (0, import_jquery14.default)();
1953 function fileInputBindingGetId(el) {
1954 return InputBinding.prototype.getId.call(this, el) || el.name;
1955 }
1956 var FileInputBinding = class extends InputBinding {
1957 find(scope) {
1958 return (0, import_jquery14.default)(scope).find('input[type="file"]');
1959 }
1960 getId(el) {
1961 return fileInputBindingGetId(el);
1962 }
1963 getValue(el) {
1964 const data = (0, import_jquery14.default)(el).attr("data-restore");
1965 if (data) {
1966 const dataParsed = JSON.parse(data);
1967 const $fileText = (0, import_jquery14.default)(el).closest("div.input-group").find("input[type=text]");
1968 if (dataParsed.name.length === 1) {
1969 $fileText.val(dataParsed.name[0]);
1970 } else {
1971 $fileText.val(dataParsed.name.length + " files");
1972 }
1973 const $progress = (0, import_jquery14.default)(el).closest("div.form-group").find(".progress");
1974 const $bar = $progress.find(".progress-bar");
1975 $progress.removeClass("active");
1976 $bar.width("100%");
1977 $bar.css("visibility", "visible");
1978 return dataParsed;
1979 } else {
1980 return null;
1981 }
1982 }
1983 setValue(el, value) {
1984 return;
1985 el;
1986 value;
1987 }
1988 getType(el) {
1989 return "shiny.file";
1990 el;
1991 }
1992 subscribe(el, callback) {
1993 callback;
1994 (0, import_jquery14.default)(el).on("change.fileInputBinding", uploadFiles);
1995 if ($fileInputs.length === 0) enableDocumentEvents();
1996 $fileInputs = $fileInputs.add(el);
1997 const $zone = zoneOf(el);
1998 enableDraghover($zone).on({
1999 "draghover:enter.draghover": (e4) => {
2000 $zone.addClass(zoneOver);
2001 return;
2002 e4;
2003 },
2004 "draghover:leave.draghover": (e4) => {
2005 $zone.removeClass(zoneOver);
2006 e4.stopPropagation();
2007 },
2008 "draghover:drop.draghover": (e4, dropEvent) => {
2009 handleDrop(dropEvent, el);
2010 return;
2011 e4;
2012 }
2013 });
2014 }
2015 unsubscribe(el) {
2016 const $el = (0, import_jquery14.default)(el), $zone = zoneOf(el);
2017 $zone.removeClass(zoneOver).removeClass(zoneActive);
2018 disableDraghover($zone);
2019 $el.off(".fileInputBinding");
2020 $zone.off(".draghover");
2021 $fileInputs = $fileInputs.not(el);
2022 if ($fileInputs.length === 0) disableDocumentEvents();
2023 }
2024 };
2025
2026 // srcts/src/bindings/input/number.ts
2027 var import_jquery16 = __toESM(require_jquery());
2028
2029 // srcts/src/bindings/input/text.ts
2030 var import_jquery15 = __toESM(require_jquery());
2031 function getLabelNode3(el) {
2032 return (0, import_jquery15.default)(el).parent().find('label[for="' + $escape(el.id) + '"]');
2033 }
2034 var TextInputBindingBase = class extends InputBinding {
2035 find(scope) {
2036 const $inputs = (0, import_jquery15.default)(scope).find(
2037 'input[type="text"], input[type="search"], input[type="url"], input[type="email"]'
2038 );
2039 return $inputs.not('input[type="text"][id$="-selectized"]');
2040 }
2041 getId(el) {
2042 return super.getId(el) || el.name;
2043 }
2044 getValue(el) {
2045 throw "not implemented";
2046 el;
2047 }
2048 setValue(el, value) {
2049 throw "not implemented";
2050 el;
2051 value;
2052 }
2053 subscribe(el, callback) {
2054 const $el = (0, import_jquery15.default)(el);
2055 const updateOn = $el.data("update-on") || "change";
2056 if (updateOn === "change") {
2057 $el.on(
2058 "keyup.textInputBinding input.textInputBinding",
2059 // event: Event
2060 function() {
2061 callback(true);
2062 }
2063 );
2064 } else if (updateOn === "blur") {
2065 $el.on("blur.textInputBinding", function() {
2066 callback(false);
2067 });
2068 $el.on("keydown.textInputBinding", function(event) {
2069 if (event.key !== "Enter") return;
2070 if ($el.is("textarea")) {
2071 if (!(event.ctrlKey || event.metaKey)) return;
2072 }
2073 callback(false);
2074 });
2075 }
2076 $el.on("change.textInputBinding", function() {
2077 if (updateOn === "blur" && $el.is(":focus")) {
2078 return;
2079 }
2080 callback(false);
2081 });
2082 }
2083 unsubscribe(el) {
2084 (0, import_jquery15.default)(el).off(".textInputBinding");
2085 }
2086 receiveMessage(el, data) {
2087 throw "not implemented";
2088 el;
2089 data;
2090 }
2091 getState(el) {
2092 throw "not implemented";
2093 el;
2094 }
2095 getRatePolicy(el) {
2096 return {
2097 policy: "debounce",
2098 delay: 250
2099 };
2100 el;
2101 }
2102 };
2103 var TextInputBinding = class extends TextInputBindingBase {
2104 setValue(el, value) {
2105 el.value = value;
2106 }
2107 getValue(el) {
2108 return el.value;
2109 }
2110 getState(el) {
2111 return {
2112 label: getLabelNode3(el).text(),
2113 value: el.value,
2114 placeholder: el.placeholder
2115 };
2116 }
2117 async receiveMessage(el, data) {
2118 if (hasDefinedProperty(data, "value")) this.setValue(el, data.value);
2119 await updateLabel(data.label, getLabelNode3(el));
2120 if (hasDefinedProperty(data, "placeholder")) {
2121 el.placeholder = data.placeholder;
2122 }
2123 (0, import_jquery15.default)(el).trigger("change");
2124 }
2125 };
2126
2127 // srcts/src/bindings/input/number.ts
2128 function getLabelNode4(el) {
2129 return (0, import_jquery16.default)(el).parent().find('label[for="' + $escape(el.id) + '"]');
2130 }
2131 var NumberInputBinding = class extends TextInputBindingBase {
2132 find(scope) {
2133 return (0, import_jquery16.default)(scope).find('input[type="number"]');
2134 }
2135 getValue(el) {
2136 const numberVal = (0, import_jquery16.default)(el).val();
2137 if (typeof numberVal == "string") {
2138 if (/^\s*$/.test(numberVal))
2139 return null;
2140 }
2141 const numberValue = Number(numberVal);
2142 if (!isNaN(numberValue)) {
2143 return numberValue;
2144 }
2145 return numberVal;
2146 }
2147 setValue(el, value) {
2148 el.value = "" + value;
2149 }
2150 getType(el) {
2151 return "shiny.number";
2152 el;
2153 }
2154 async receiveMessage(el, data) {
2155 if (hasDefinedProperty(data, "value")) el.value = data.value ?? "";
2156 if (hasDefinedProperty(data, "min")) el.min = data.min ?? "";
2157 if (hasDefinedProperty(data, "max")) el.max = data.max ?? "";
2158 if (hasDefinedProperty(data, "step")) el.step = data.step ?? "";
2159 await updateLabel(data.label, getLabelNode4(el));
2160 (0, import_jquery16.default)(el).trigger("change");
2161 }
2162 getState(el) {
2163 return {
2164 label: getLabelNode4(el).text(),
2165 value: this.getValue(el),
2166 min: Number(el.min),
2167 max: Number(el.max),
2168 step: Number(el.step)
2169 };
2170 }
2171 };
2172
2173 // srcts/src/bindings/input/password.ts
2174 var import_jquery17 = __toESM(require_jquery());
2175 var PasswordInputBinding = class extends TextInputBinding {
2176 find(scope) {
2177 return (0, import_jquery17.default)(scope).find('input[type="password"]');
2178 }
2179 getType(el) {
2180 return "shiny.password";
2181 el;
2182 }
2183 };
2184
2185 // srcts/src/bindings/input/radio.ts
2186 var import_jquery18 = __toESM(require_jquery());
2187 function getLabelNode5(el) {
2188 return (0, import_jquery18.default)(el).parent().find('label[for="' + $escape(el.id) + '"]');
2189 }
2190 function getLabel2(obj) {
2191 const parentNode = obj.parentNode;
2192 if (parentNode.tagName === "LABEL") {
2193 return (0, import_jquery18.default)(parentNode).find("span").text().trim();
2194 }
2195 return null;
2196 }
2197 var RadioInputBinding = class extends InputBinding {
2198 find(scope) {
2199 return (0, import_jquery18.default)(scope).find(".shiny-input-radiogroup");
2200 }
2201 getValue(el) {
2202 const checkedItems = (0, import_jquery18.default)(
2203 'input:radio[name="' + $escape(el.id) + '"]:checked'
2204 );
2205 if (checkedItems.length === 0) {
2206 return null;
2207 }
2208 return checkedItems.val();
2209 }
2210 setValue(el, value) {
2211 if (Array.isArray(value) && value.length === 0) {
2212 (0, import_jquery18.default)('input:radio[name="' + $escape(el.id) + '"]').prop("checked", false);
2213 } else {
2214 (0, import_jquery18.default)(
2215 'input:radio[name="' + $escape(el.id) + '"][value="' + $escape(value) + '"]'
2216 ).prop("checked", true);
2217 }
2218 }
2219 getState(el) {
2220 const $objs = (0, import_jquery18.default)(
2221 'input:radio[name="' + $escape(el.id) + '"]'
2222 );
2223 const options = new Array($objs.length);
2224 for (let i5 = 0; i5 < options.length; i5++) {
2225 options[i5] = { value: $objs[i5].value, label: getLabel2($objs[i5]) };
2226 }
2227 return {
2228 label: getLabelNode5(el).text(),
2229 value: this.getValue(el),
2230 options
2231 };
2232 }
2233 async receiveMessage(el, data) {
2234 const $el = (0, import_jquery18.default)(el);
2235 if (hasDefinedProperty(data, "options")) {
2236 $el.find("div.shiny-options-group").remove();
2237 $el.find("label.radio").remove();
2238 $el.append(data.options);
2239 }
2240 if (hasDefinedProperty(data, "value")) {
2241 this.setValue(el, data.value);
2242 }
2243 await updateLabel(data.label, getLabelNode5(el));
2244 (0, import_jquery18.default)(el).trigger("change");
2245 }
2246 subscribe(el, callback) {
2247 (0, import_jquery18.default)(el).on("change.radioInputBinding", function() {
2248 callback(false);
2249 });
2250 }
2251 unsubscribe(el) {
2252 (0, import_jquery18.default)(el).off(".radioInputBinding");
2253 }
2254 };
2255
2256 // srcts/src/bindings/input/selectInput.ts
2257 var import_jquery19 = __toESM(require_jquery());
2258
2259 // srcts/src/utils/eval.ts
2260 var indirectEval = eval;
2261
2262 // srcts/src/bindings/input/selectInput.ts
2263 function getLabelNode6(el) {
2264 let escapedId = $escape(el.id);
2265 if (isSelectize(el)) {
2266 escapedId += "-selectized";
2267 }
2268 return (0, import_jquery19.default)(el).parent().parent().find('label[for="' + escapedId + '"]');
2269 }
2270 function isSelectize(el) {
2271 const config = (0, import_jquery19.default)(el).parent().find('script[data-for="' + $escape(el.id) + '"]');
2272 return config.length > 0;
2273 }
2274 var SelectInputBinding = class extends InputBinding {
2275 find(scope) {
2276 return (0, import_jquery19.default)(scope).find("select");
2277 }
2278 getType(el) {
2279 const $el = (0, import_jquery19.default)(el);
2280 if (!$el.hasClass("symbol")) {
2281 return null;
2282 }
2283 if ($el.attr("multiple") === "multiple") {
2284 return "shiny.symbolList";
2285 } else {
2286 return "shiny.symbol";
2287 }
2288 }
2289 getId(el) {
2290 return InputBinding.prototype.getId.call(this, el) || el.name;
2291 }
2292 getValue(el) {
2293 if (!isSelectize(el)) {
2294 return (0, import_jquery19.default)(el).val();
2295 } else {
2296 const selectize = this._selectize(el);
2297 return selectize?.getValue();
2298 }
2299 }
2300 setValue(el, value) {
2301 if (!isSelectize(el)) {
2302 (0, import_jquery19.default)(el).val(value);
2303 } else {
2304 const selectize = this._selectize(el);
2305 selectize?.setValue(value);
2306 }
2307 }
2308 getState(el) {
2309 const options = new Array(
2310 el.length
2311 );
2312 for (let i5 = 0; i5 < el.length; i5++) {
2313 options[i5] = {
2314 // TODO-barret; Is this a safe assumption?; Are there no Option Groups?
2315 value: el[i5].value,
2316 label: el[i5].label
2317 };
2318 }
2319 return {
2320 label: getLabelNode6(el),
2321 value: this.getValue(el),
2322 options
2323 };
2324 }
2325 async receiveMessage(el, data) {
2326 const $el = (0, import_jquery19.default)(el);
2327 if (hasDefinedProperty(data, "options")) {
2328 const selectize = this._selectize(el);
2329 selectize?.destroy();
2330 $el.empty().append(data.options);
2331 this._selectize(el);
2332 }
2333 if (hasDefinedProperty(data, "config")) {
2334 $el.parent().find('script[data-for="' + $escape(el.id) + '"]').replaceWith(data.config);
2335 this._selectize(el, true);
2336 }
2337 if (hasDefinedProperty(data, "url")) {
2338 const selectize = this._selectize(el);
2339 selectize.clear();
2340 selectize.clearOptions();
2341 let loaded = false;
2342 selectize.settings.load = function(query, callback) {
2343 const settings = selectize.settings;
2344 import_jquery19.default.ajax({
2345 url: data.url,
2346 data: {
2347 query,
2348 field: JSON.stringify([settings.searchField]),
2349 value: settings.valueField,
2350 conju: settings.searchConjunction,
2351 maxop: settings.maxOptions
2352 },
2353 type: "GET",
2354 error: function() {
2355 callback();
2356 },
2357 success: function(res) {
2358 import_jquery19.default.each(res, function(index, elem) {
2359 const optgroupId = elem[settings.optgroupField || "optgroup"];
2360 const optgroup = {};
2361 optgroup[settings.optgroupLabelField || "label"] = optgroupId;
2362 optgroup[settings.optgroupValueField || "value"] = optgroupId;
2363 selectize.addOptionGroup(optgroupId, optgroup);
2364 });
2365 callback(res);
2366 if (!loaded) {
2367 if (hasDefinedProperty(data, "value")) {
2368 selectize.setValue(data.value);
2369 } else if (settings.maxItems === 1) {
2370 selectize.setValue(res[0].value);
2371 }
2372 }
2373 loaded = true;
2374 }
2375 });
2376 };
2377 selectize.load(function(callback) {
2378 selectize.settings.load.apply(selectize, ["", callback]);
2379 });
2380 } else if (hasDefinedProperty(data, "value")) {
2381 this.setValue(el, data.value);
2382 }
2383 await updateLabel(data.label, getLabelNode6(el));
2384 (0, import_jquery19.default)(el).trigger("change");
2385 }
2386 subscribe(el, callback) {
2387 (0, import_jquery19.default)(el).on(
2388 "change.selectInputBinding",
2389 // event: Event
2390 () => {
2391 if (el.nonempty && this.getValue(el) === "") {
2392 return;
2393 }
2394 callback(false);
2395 }
2396 );
2397 }
2398 unsubscribe(el) {
2399 (0, import_jquery19.default)(el).off(".selectInputBinding");
2400 }
2401 initialize(el) {
2402 this._selectize(el);
2403 }
2404 _selectize(el, update = false) {
2405 if (!import_jquery19.default.fn.selectize) return void 0;
2406 const $el = (0, import_jquery19.default)(el);
2407 const config = $el.parent().find('script[data-for="' + $escape(el.id) + '"]');
2408 if (config.length === 0) return void 0;
2409 let options = import_jquery19.default.extend(
2410 {
2411 labelField: "label",
2412 valueField: "value",
2413 searchField: ["label"]
2414 },
2415 JSON.parse(config.html())
2416 );
2417 options = this._addShinyRemoveButton(options, el.hasAttribute("multiple"));
2418 if (typeof config.data("nonempty") !== "undefined") {
2419 el.nonempty = true;
2420 options = import_jquery19.default.extend(options, {
2421 onItemRemove: function(value) {
2422 if (this.getValue() === "")
2423 (0, import_jquery19.default)("select#" + $escape(el.id)).empty().append(
2424 (0, import_jquery19.default)("<option/>", {
2425 value,
2426 selected: true
2427 })
2428 ).trigger("change");
2429 },
2430 onDropdownClose: (
2431 // $dropdown: any
2432 function() {
2433 if (this.getValue() === "") {
2434 this.setValue((0, import_jquery19.default)("select#" + $escape(el.id)).val());
2435 }
2436 }
2437 )
2438 });
2439 } else {
2440 el.nonempty = false;
2441 }
2442 if (config.data("eval") instanceof Array)
2443 import_jquery19.default.each(config.data("eval"), function(i5, x2) {
2444 options[x2] = indirectEval("(" + options[x2] + ")");
2445 });
2446 let control = $el.selectize(options)[0].selectize;
2447 if (update) {
2448 const settings = import_jquery19.default.extend(control.settings, options);
2449 control.destroy();
2450 control = $el.selectize(settings)[0].selectize;
2451 }
2452 return control;
2453 }
2454 // Translate shinyRemoveButton option into selectize plugins
2455 _addShinyRemoveButton(options, multiple) {
2456 let removeButton = options.shinyRemoveButton;
2457 if (removeButton === void 0) {
2458 return options;
2459 }
2460 if (removeButton === "none") {
2461 removeButton = multiple ? "true" : "false";
2462 }
2463 if (removeButton === "false") {
2464 return options;
2465 }
2466 const plugins = [];
2467 if (removeButton === "both") {
2468 plugins.push("remove_button", "clear_button");
2469 } else if (removeButton === "true") {
2470 plugins.push(multiple ? "remove_button" : "clear_button");
2471 }
2472 return {
2473 ...options,
2474 plugins: Array.from(
2475 /* @__PURE__ */ new Set([
2476 ...Array.isArray(options.plugins) ? options.plugins : [],
2477 ...plugins
2478 ])
2479 )
2480 };
2481 }
2482 };
2483
2484 // srcts/src/bindings/input/slider.ts
2485 var import_jquery20 = __toESM(require_jquery());
2486 function forceIonSliderUpdate(slider) {
2487 if (slider.$cache && slider.$cache.input)
2488 slider.$cache.input.trigger("change");
2489 else console.log("Couldn't force ion slider to update");
2490 }
2491 function getTypePrettifyer(dataType, timeFormat, timezone) {
2492 let timeFormatter;
2493 let prettify;
2494 if (dataType === "date") {
2495 timeFormatter = window.strftime.utc();
2496 prettify = function(num) {
2497 return timeFormatter(timeFormat, new Date(num));
2498 };
2499 } else if (dataType === "datetime") {
2500 if (timezone) timeFormatter = window.strftime.timezone(timezone);
2501 else timeFormatter = window.strftime;
2502 prettify = function(num) {
2503 return timeFormatter(timeFormat, new Date(num));
2504 };
2505 } else {
2506 prettify = function(num) {
2507 return formatNumber(num, this.prettify_separator);
2508 };
2509 }
2510 return prettify;
2511 }
2512 function getLabelNode7(el) {
2513 return (0, import_jquery20.default)(el).parent().find('label[for="' + $escape(el.id) + '"]');
2514 }
2515 function numValues(el) {
2516 if ((0, import_jquery20.default)(el).data("ionRangeSlider").options.type === "double") return 2;
2517 else return 1;
2518 }
2519 var SliderInputBinding = class extends TextInputBindingBase {
2520 find(scope) {
2521 if (!import_jquery20.default.fn.ionRangeSlider) {
2522 return (0, import_jquery20.default)();
2523 }
2524 return (0, import_jquery20.default)(scope).find("input.js-range-slider");
2525 }
2526 getType(el) {
2527 const dataType = (0, import_jquery20.default)(el).data("data-type");
2528 if (dataType === "date") return "shiny.date";
2529 else if (dataType === "datetime") return "shiny.datetime";
2530 else return null;
2531 }
2532 getValue(el) {
2533 const $el = (0, import_jquery20.default)(el);
2534 const result = (0, import_jquery20.default)(el).data("ionRangeSlider").result;
2535 let convert;
2536 const dataType = $el.data("data-type");
2537 if (dataType === "date") {
2538 convert = function(val) {
2539 return formatDateUTC(new Date(Number(val)));
2540 };
2541 } else if (dataType === "datetime") {
2542 convert = function(val) {
2543 return Number(val) / 1e3;
2544 };
2545 } else {
2546 convert = function(val) {
2547 return Number(val);
2548 };
2549 }
2550 if (numValues(el) === 2) {
2551 return [convert(result.from), convert(result.to)];
2552 } else {
2553 return convert(result.from);
2554 }
2555 }
2556 setValue(el, value) {
2557 const $el = (0, import_jquery20.default)(el);
2558 const slider = $el.data("ionRangeSlider");
2559 $el.data("immediate", true);
2560 try {
2561 if (numValues(el) === 2 && value instanceof Array) {
2562 slider.update({ from: value[0], to: value[1] });
2563 } else {
2564 slider.update({ from: value });
2565 }
2566 forceIonSliderUpdate(slider);
2567 } finally {
2568 $el.data("immediate", false);
2569 }
2570 }
2571 subscribe(el, callback) {
2572 (0, import_jquery20.default)(el).on("change.sliderInputBinding", function() {
2573 callback(!(0, import_jquery20.default)(el).data("immediate") && !(0, import_jquery20.default)(el).data("animating"));
2574 });
2575 }
2576 unsubscribe(el) {
2577 (0, import_jquery20.default)(el).off(".sliderInputBinding");
2578 }
2579 async receiveMessage(el, data) {
2580 const $el = (0, import_jquery20.default)(el);
2581 const slider = $el.data("ionRangeSlider");
2582 const msg = {};
2583 if (hasDefinedProperty(data, "value")) {
2584 if (numValues(el) === 2 && data.value instanceof Array) {
2585 msg.from = data.value[0];
2586 msg.to = data.value[1];
2587 } else {
2588 if (Array.isArray(data.value)) {
2589 const errorReason = [
2590 "an empty array.",
2591 "a single-value array.",
2592 "an array with more than two values."
2593 ];
2594 throw "Slider requires two values to update with an array, but message value was " + errorReason[Math.min(data.value.length, 2)];
2595 }
2596 msg.from = data.value;
2597 }
2598 }
2599 const sliderFeatures = [
2600 "min",
2601 "max",
2602 "step"
2603 ];
2604 for (let i5 = 0; i5 < sliderFeatures.length; i5++) {
2605 const feats = sliderFeatures[i5];
2606 if (hasDefinedProperty(data, feats)) {
2607 msg[feats] = data[feats];
2608 }
2609 }
2610 await updateLabel(data.label, getLabelNode7(el));
2611 const domElements = [
2612 "data-type",
2613 "time-format",
2614 "timezone"
2615 ];
2616 for (let i5 = 0; i5 < domElements.length; i5++) {
2617 const elem = domElements[i5];
2618 if (hasDefinedProperty(data, elem)) {
2619 $el.data(elem, data[elem]);
2620 }
2621 }
2622 const dataType = $el.data("data-type");
2623 const timeFormat = $el.data("time-format");
2624 const timezone = $el.data("timezone");
2625 msg.prettify = getTypePrettifyer(dataType, timeFormat, timezone);
2626 $el.data("immediate", true);
2627 try {
2628 slider.update(msg);
2629 forceIonSliderUpdate(slider);
2630 } finally {
2631 $el.data("immediate", false);
2632 }
2633 }
2634 getRatePolicy(el) {
2635 return {
2636 policy: "debounce",
2637 delay: 250
2638 };
2639 el;
2640 }
2641 // TODO-barret Why not implemented?
2642 getState(el) {
2643 return;
2644 el;
2645 }
2646 initialize(el) {
2647 const $el = (0, import_jquery20.default)(el);
2648 const dataType = $el.data("data-type");
2649 const timeFormat = $el.data("time-format");
2650 const timezone = $el.data("timezone");
2651 const opts = {
2652 prettify: getTypePrettifyer(dataType, timeFormat, timezone)
2653 };
2654 $el.ionRangeSlider(opts);
2655 }
2656 };
2657 function formatNumber(num, thousandSep = ",", decimalSep = ".") {
2658 const parts = num.toString().split(".");
2659 parts[0] = parts[0].replace(
2660 /(\d{1,3}(?=(?:\d\d\d)+(?!\d)))/g,
2661 "$1" + thousandSep
2662 );
2663 if (parts.length === 1) return parts[0];
2664 else if (parts.length === 2) return parts[0] + decimalSep + parts[1];
2665 else return "";
2666 }
2667 (0, import_jquery20.default)(document).on("click", ".slider-animate-button", function(evt) {
2668 evt.preventDefault();
2669 const self = (0, import_jquery20.default)(this);
2670 const target = (0, import_jquery20.default)("#" + $escape(self.attr("data-target-id")));
2671 const startLabel = "Play";
2672 const stopLabel = "Pause";
2673 const loop = self.attr("data-loop") !== void 0 && !/^\s*false\s*$/i.test(self.attr("data-loop"));
2674 let animInterval = self.attr("data-interval");
2675 if (isNaN(animInterval)) animInterval = 1500;
2676 else animInterval = Number(animInterval);
2677 if (!target.data("animTimer")) {
2678 let timer;
2679 if (target.hasClass("jslider")) {
2680 const slider = target.slider();
2681 if (!slider.canStepNext()) slider.resetToStart();
2682 timer = setInterval(function() {
2683 if (loop && !slider.canStepNext()) {
2684 slider.resetToStart();
2685 } else {
2686 slider.stepNext();
2687 if (!loop && !slider.canStepNext()) {
2688 self.click();
2689 }
2690 }
2691 }, animInterval);
2692 } else {
2693 const slider = target.data("ionRangeSlider");
2694 const sliderCanStep = function() {
2695 if (slider.options.type === "double")
2696 return slider.result.to < slider.result.max;
2697 else return slider.result.from < slider.result.max;
2698 };
2699 const sliderReset = function() {
2700 const val = { from: slider.result.min };
2701 if (slider.options.type === "double")
2702 val.to = val.from + (slider.result.to - slider.result.from);
2703 slider.update(val);
2704 forceIonSliderUpdate(slider);
2705 };
2706 const sliderStep = function() {
2707 const val = {
2708 from: Math.min(
2709 slider.result.max,
2710 slider.result.from + slider.options.step
2711 )
2712 };
2713 if (slider.options.type === "double")
2714 val.to = Math.min(
2715 slider.result.max,
2716 slider.result.to + slider.options.step
2717 );
2718 slider.update(val);
2719 forceIonSliderUpdate(slider);
2720 };
2721 if (!sliderCanStep()) sliderReset();
2722 timer = setInterval(function() {
2723 if (loop && !sliderCanStep()) {
2724 sliderReset();
2725 } else {
2726 sliderStep();
2727 if (!loop && !sliderCanStep()) {
2728 self.click();
2729 }
2730 }
2731 }, animInterval);
2732 }
2733 target.data("animTimer", timer);
2734 self.attr("title", stopLabel);
2735 self.addClass("playing");
2736 target.data("animating", true);
2737 } else {
2738 clearTimeout(target.data("animTimer"));
2739 target.removeData("animTimer");
2740 self.attr("title", startLabel);
2741 self.removeClass("playing");
2742 target.removeData("animating");
2743 }
2744 });
2745
2746 // srcts/src/bindings/input/tabinput.ts
2747 var import_jquery21 = __toESM(require_jquery());
2748 function getTabName(anchor) {
2749 return anchor.attr("data-value") || anchor.text();
2750 }
2751 var BootstrapTabInputBinding = class extends InputBinding {
2752 find(scope) {
2753 return (0, import_jquery21.default)(scope).find("ul.nav.shiny-tab-input");
2754 }
2755 getValue(el) {
2756 const anchor = isBS3() ? (0, import_jquery21.default)(el).find("li:not(.dropdown).active > a") : (0, import_jquery21.default)(el).find(
2757 ".nav-link:not(.dropdown-toggle).active, .dropdown-menu .dropdown-item.active"
2758 );
2759 if (anchor.length === 1) return getTabName(anchor);
2760 return null;
2761 }
2762 setValue(el, value) {
2763 let success = false;
2764 if (value) {
2765 const anchors = isBS3() ? (0, import_jquery21.default)(el).find("li:not(.dropdown) > a") : (0, import_jquery21.default)(el).find(
2766 ".nav-link:not(.dropdown-toggle), .dropdown-menu .dropdown-item"
2767 );
2768 anchors.each(function() {
2769 if (getTabName((0, import_jquery21.default)(this)) === value) {
2770 (0, import_jquery21.default)(this).tab("show");
2771 success = true;
2772 return false;
2773 }
2774 return;
2775 });
2776 }
2777 if (!success) {
2778 (0, import_jquery21.default)(el).trigger("change");
2779 }
2780 }
2781 getState(el) {
2782 return { value: this.getValue(el) };
2783 }
2784 receiveMessage(el, data) {
2785 if (hasDefinedProperty(data, "value")) this.setValue(el, data.value);
2786 (0, import_jquery21.default)(el).trigger("change");
2787 }
2788 subscribe(el, callback) {
2789 (0, import_jquery21.default)(el).on(
2790 "change shown.bootstrapTabInputBinding shown.bs.tab.bootstrapTabInputBinding",
2791 // event: Event
2792 function() {
2793 callback(false);
2794 }
2795 );
2796 }
2797 unsubscribe(el) {
2798 (0, import_jquery21.default)(el).off(".bootstrapTabInputBinding");
2799 }
2800 };
2801
2802 // srcts/src/bindings/input/textarea.ts
2803 var import_jquery22 = __toESM(require_jquery());
2804 var intersectObserver = new IntersectionObserver((entries) => {
2805 entries.forEach((entry) => {
2806 if (entry.isIntersecting) {
2807 updateHeight(entry.target);
2808 }
2809 });
2810 });
2811 var _inputHandler;
2812 var TextareaInputBinding = class extends TextInputBinding {
2813 constructor() {
2814 super(...arguments);
2815 __privateAdd(this, _inputHandler, null);
2816 }
2817 find(scope) {
2818 return (0, import_jquery22.default)(scope).find("textarea");
2819 }
2820 initialize(el) {
2821 super.initialize(el);
2822 updateHeight(el);
2823 }
2824 subscribe(el, callback) {
2825 super.subscribe(el, callback);
2826 __privateSet(this, _inputHandler, (e4) => updateHeight(e4.target));
2827 el.addEventListener("input", __privateGet(this, _inputHandler));
2828 intersectObserver.observe(el);
2829 }
2830 unsubscribe(el) {
2831 super.unsubscribe(el);
2832 if (__privateGet(this, _inputHandler)) el.removeEventListener("input", __privateGet(this, _inputHandler));
2833 intersectObserver.unobserve(el);
2834 }
2835 };
2836 _inputHandler = new WeakMap();
2837 function updateHeight(el) {
2838 if (!el.classList.contains("textarea-autoresize")) {
2839 return;
2840 }
2841 if (el.scrollHeight == 0) {
2842 return;
2843 }
2844 el.style.height = "auto";
2845 el.style.height = el.scrollHeight + "px";
2846 }
2847
2848 // srcts/src/bindings/input/index.ts
2849 function initInputBindings() {
2850 const inputBindings = new BindingRegistry();
2851 inputBindings.register(new TextInputBinding(), "shiny.textInput");
2852 inputBindings.register(new TextareaInputBinding(), "shiny.textareaInput");
2853 inputBindings.register(new PasswordInputBinding(), "shiny.passwordInput");
2854 inputBindings.register(new NumberInputBinding(), "shiny.numberInput");
2855 inputBindings.register(new CheckboxInputBinding(), "shiny.checkboxInput");
2856 inputBindings.register(
2857 new CheckboxGroupInputBinding(),
2858 "shiny.checkboxGroupInput"
2859 );
2860 inputBindings.register(new RadioInputBinding(), "shiny.radioInput");
2861 inputBindings.register(new SliderInputBinding(), "shiny.sliderInput");
2862 inputBindings.register(new DateInputBinding(), "shiny.dateInput");
2863 inputBindings.register(new DateRangeInputBinding(), "shiny.dateRangeInput");
2864 inputBindings.register(new SelectInputBinding(), "shiny.selectInput");
2865 inputBindings.register(
2866 new ActionButtonInputBinding(),
2867 "shiny.actionButtonInput"
2868 );
2869 inputBindings.register(
2870 new BootstrapTabInputBinding(),
2871 "shiny.bootstrapTabInput"
2872 );
2873 const fileInputBinding2 = new FileInputBinding();
2874 inputBindings.register(fileInputBinding2, "shiny.fileInputBinding");
2875 return { inputBindings, fileInputBinding: fileInputBinding2 };
2876 }
2877
2878 // srcts/src/bindings/output/datatable.ts
2879 var import_jquery24 = __toESM(require_jquery());
2880
2881 // srcts/src/bindings/output/outputBinding.ts
2882 var import_jquery23 = __toESM(require_jquery());
2883 var OutputBinding = class {
2884 // Returns a jQuery object or element array that contains the
2885 // descendants of scope that match this binding
2886 find(scope) {
2887 throw "Not implemented";
2888 scope;
2889 }
2890 renderValue(el, data) {
2891 throw "Not implemented";
2892 el;
2893 data;
2894 }
2895 getId(el) {
2896 return el.getAttribute("data-input-id") || el.id;
2897 }
2898 async onValueChange(el, data) {
2899 this.clearError(el);
2900 await this.renderValue(el, data);
2901 }
2902 onValueError(el, err) {
2903 this.renderError(el, err);
2904 }
2905 renderError(el, err) {
2906 this.clearError(el);
2907 if (err.message === "") {
2908 (0, import_jquery23.default)(el).empty();
2909 return;
2910 }
2911 let errClass = "shiny-output-error";
2912 if (err.type !== null) {
2913 errClass = errClass + " " + import_jquery23.default.map(asArray(err.type), function(type) {
2914 return errClass + "-" + type;
2915 }).join(" ");
2916 }
2917 (0, import_jquery23.default)(el).addClass(errClass).text(err.message);
2918 }
2919 clearError(el) {
2920 (0, import_jquery23.default)(el).attr("class", function(i5, c4) {
2921 return c4.replace(/(^|\s)shiny-output-error\S*/g, "");
2922 });
2923 }
2924 showProgress(el, show3) {
2925 const recalcClass = "recalculating";
2926 if (show3) (0, import_jquery23.default)(el).addClass(recalcClass);
2927 else (0, import_jquery23.default)(el).removeClass(recalcClass);
2928 }
2929 };
2930
2931 // srcts/src/bindings/output/datatable.ts
2932 var DatatableOutputBinding = class extends OutputBinding {
2933 find(scope) {
2934 return (0, import_jquery24.default)(scope).find(".shiny-datatable-output");
2935 }
2936 onValueError(el, err) {
2937 shinyUnbindAll(el);
2938 this.renderError(el, err);
2939 }
2940 renderValue(el, data) {
2941 const $el = (0, import_jquery24.default)(el).empty();
2942 if (!data || !data.colnames) return;
2943 const colnames = import_jquery24.default.makeArray(data.colnames);
2944 let header = import_jquery24.default.map(colnames, function(x2) {
2945 return "<th>" + x2 + "</th>";
2946 }).join("");
2947 header = "<thead><tr>" + header + "</tr></thead>";
2948 let footer = "";
2949 if (data.options?.searching ?? true) {
2950 footer = import_jquery24.default.map(colnames, function(x2) {
2951 return '<th><input type="text" placeholder="' + escapeHTML(x2.replace(/(<([^>]+)>)/gi, "")) + '" /></th>';
2952 }).join("");
2953 footer = "<tfoot>" + footer + "</tfoot>";
2954 }
2955 const content = '<table class="table table-striped table-hover">' + header + footer + "</table>";
2956 $el.append(content);
2957 if (data.evalOptions) {
2958 import_jquery24.default.each(data.evalOptions, function(i5, x2) {
2959 data.options[x2] = indirectEval("(" + data.options[x2] + ")");
2960 });
2961 }
2962 const searchCI = data.options?.search?.caseInsensitive !== false;
2963 const oTable = (0, import_jquery24.default)(el).children("table").DataTable(
2964 import_jquery24.default.extend(
2965 {
2966 processing: true,
2967 serverSide: true,
2968 order: [],
2969 orderClasses: false,
2970 pageLength: 25,
2971 ajax: {
2972 url: data.action,
2973 type: "POST",
2974 data: function(d3) {
2975 if (!d3.search) {
2976 d3.search = {};
2977 }
2978 d3.search.caseInsensitive = searchCI;
2979 d3.escape = data.escape;
2980 }
2981 }
2982 },
2983 data.options
2984 )
2985 );
2986 if (typeof data.callback === "string") {
2987 const callback = indirectEval("(" + data.callback + ")");
2988 if (typeof callback === "function") callback(oTable);
2989 }
2990 $el.find("label input").first().unbind("keyup").keyup(
2991 debounce(data.searchDelay, function() {
2992 oTable.search(this.value).draw();
2993 })
2994 );
2995 const searchInputs = $el.find("tfoot input");
2996 if (searchInputs.length > 0) {
2997 import_jquery24.default.each(oTable.settings()[0].aoColumns, function(i5, x2) {
2998 if (!x2.bSearchable) searchInputs.eq(i5).hide();
2999 });
3000 searchInputs.keyup(
3001 debounce(data.searchDelay, function() {
3002 oTable.column(searchInputs.index(this)).search(this.value).draw();
3003 })
3004 );
3005 }
3006 $el.parents(".tab-content").css("overflow", "visible");
3007 }
3008 };
3009
3010 // srcts/src/bindings/output/downloadlink.ts
3011 var import_jquery25 = __toESM(require_jquery());
3012 var DownloadLinkOutputBinding = class extends OutputBinding {
3013 find(scope) {
3014 return (0, import_jquery25.default)(scope).find("a.shiny-download-link");
3015 }
3016 renderValue(el, data) {
3017 el.setAttribute("href", data);
3018 el.classList.remove("disabled");
3019 el.removeAttribute("aria-disabled");
3020 el.removeAttribute("tabindex");
3021 }
3022 // Progress shouldn't be shown on the download button
3023 // (progress will be shown as a page level pulse instead)
3024 showProgress(el, show3) {
3025 return;
3026 el;
3027 show3;
3028 }
3029 };
3030 (0, import_jquery25.default)(document).on(
3031 "click.shinyDownloadLink",
3032 "a.shiny-download-link",
3033 function(e4) {
3034 const evt = import_jquery25.default.Event("shiny:filedownload");
3035 evt.name = this.id;
3036 evt.href = this.href;
3037 (0, import_jquery25.default)(document).trigger(evt);
3038 return;
3039 e4;
3040 }
3041 );
3042
3043 // srcts/src/bindings/output/html.ts
3044 var import_jquery26 = __toESM(require_jquery());
3045 var HtmlOutputBinding = class extends OutputBinding {
3046 find(scope) {
3047 return (0, import_jquery26.default)(scope).find(".shiny-html-output");
3048 }
3049 onValueError(el, err) {
3050 shinyUnbindAll(el);
3051 this.renderError(el, err);
3052 }
3053 async renderValue(el, data) {
3054 await renderContentAsync(el, data);
3055 }
3056 };
3057
3058 // srcts/src/bindings/output/image.ts
3059 var import_jquery32 = __toESM(require_jquery());
3060
3061 // srcts/src/imageutils/createBrush.ts
3062 var import_jquery28 = __toESM(require_jquery());
3063
3064 // srcts/src/imageutils/initCoordmap.ts
3065 var import_jquery27 = __toESM(require_jquery());
3066
3067 // srcts/src/imageutils/initPanelScales.ts
3068 function mapLinear(x2, domainMin, domainMax, rangeMin, rangeMax, clip = true) {
3069 clip = clip || true;
3070 const factor = (rangeMax - rangeMin) / (domainMax - domainMin);
3071 const val = x2 - domainMin;
3072 let newval = val * factor + rangeMin;
3073 if (clip) {
3074 const max = Math.max(rangeMax, rangeMin);
3075 const min = Math.min(rangeMax, rangeMin);
3076 if (newval > max) newval = max;
3077 else if (newval < min) newval = min;
3078 }
3079 return newval;
3080 }
3081 function scaler1D(domainMin, domainMax, rangeMin, rangeMax, logbase) {
3082 return {
3083 scale: function(val, clip) {
3084 if (logbase) val = Math.log(val) / Math.log(logbase);
3085 return mapLinear(val, domainMin, domainMax, rangeMin, rangeMax, clip);
3086 },
3087 scaleInv: function(val, clip) {
3088 let res = mapLinear(val, rangeMin, rangeMax, domainMin, domainMax, clip);
3089 if (logbase) res = Math.pow(logbase, res);
3090 return res;
3091 }
3092 };
3093 }
3094 function addScaleFuns(panel_) {
3095 const panel = panel_;
3096 const d3 = panel.domain;
3097 const r4 = panel.range;
3098 const xlog = panel.log && panel.log.x ? panel.log.x : null;
3099 const ylog = panel.log && panel.log.y ? panel.log.y : null;
3100 const xscaler = scaler1D(d3.left, d3.right, r4.left, r4.right, xlog);
3101 const yscaler = scaler1D(d3.bottom, d3.top, r4.bottom, r4.top, ylog);
3102 function scaleDataToImg(val, clip) {
3103 return mapValues(val, (value, key) => {
3104 const prefix = key.substring(0, 1);
3105 if (prefix === "x") {
3106 return xscaler.scale(value, clip);
3107 } else if (prefix === "y") {
3108 return yscaler.scale(value, clip);
3109 }
3110 return null;
3111 });
3112 }
3113 panel.scaleDataToImg = scaleDataToImg;
3114 function scaleImgToData(val, clip) {
3115 return mapValues(val, (value, key) => {
3116 const prefix = key.substring(0, 1);
3117 if (prefix === "x") {
3118 return xscaler.scaleInv(value, clip);
3119 } else if (prefix === "y") {
3120 return yscaler.scaleInv(value, clip);
3121 }
3122 return null;
3123 });
3124 }
3125 panel.scaleImgToData = scaleImgToData;
3126 panel.clipImg = function(offsetImg) {
3127 const newOffset = {
3128 x: offsetImg.x,
3129 y: offsetImg.y
3130 };
3131 const bounds = panel.range;
3132 if (offsetImg.x > bounds.right) newOffset.x = bounds.right;
3133 else if (offsetImg.x < bounds.left) newOffset.x = bounds.left;
3134 if (offsetImg.y > bounds.bottom) newOffset.y = bounds.bottom;
3135 else if (offsetImg.y < bounds.top) newOffset.y = bounds.top;
3136 return newOffset;
3137 };
3138 return panel;
3139 }
3140 function initPanelScales(panels) {
3141 return panels.map((panel) => addScaleFuns(panel));
3142 }
3143
3144 // srcts/src/imageutils/initCoordmap.ts
3145 function findScalingRatio($el) {
3146 const boundingRect = $el[0].getBoundingClientRect();
3147 return {
3148 x: boundingRect.width / $el.outerWidth(),
3149 y: boundingRect.height / $el.outerHeight()
3150 };
3151 }
3152 function findOrigin($el) {
3153 const offset = $el.offset();
3154 const scalingRatio = findScalingRatio($el);
3155 const paddingBorder = {
3156 left: parseInt($el.css("border-left-width")) + parseInt($el.css("padding-left")),
3157 top: parseInt($el.css("border-top-width")) + parseInt($el.css("padding-top"))
3158 };
3159 return {
3160 x: offset.left + scalingRatio.x * paddingBorder.left,
3161 y: offset.top + scalingRatio.y * paddingBorder.top
3162 };
3163 }
3164 function findDims($el) {
3165 const contentRatio = {
3166 x: $el.width() / $el.outerWidth(),
3167 y: $el.height() / $el.outerHeight()
3168 };
3169 const boundingRect = $el[0].getBoundingClientRect();
3170 return {
3171 x: contentRatio.x * boundingRect.width,
3172 y: contentRatio.y * boundingRect.height
3173 };
3174 }
3175 function initCoordmap($el, coordmap_) {
3176 const $img = $el.find("img");
3177 const img = $img[0];
3178 if (coordmap_.panels.length === 0) {
3179 const bounds = {
3180 top: 0,
3181 left: 0,
3182 right: img.naturalWidth - 1,
3183 bottom: img.naturalHeight - 1
3184 };
3185 coordmap_.panels[0] = {
3186 domain: bounds,
3187 range: bounds,
3188 mapping: {}
3189 };
3190 }
3191 const coordmap = coordmap_;
3192 coordmap.dims.height = coordmap.dims.height || img.naturalHeight;
3193 coordmap.dims.width = coordmap.dims.width || img.naturalWidth;
3194 coordmap.panels = initPanelScales(coordmap_.panels);
3195 coordmap.mouseOffsetCss = function(mouseEvent) {
3196 const imgOrigin = findOrigin($img);
3197 return {
3198 x: mouseEvent.pageX - imgOrigin.x,
3199 y: mouseEvent.pageY - imgOrigin.y
3200 };
3201 };
3202 function scaleCssToImg(offsetCss) {
3203 const pixelScaling = coordmap.imgToCssScalingRatio();
3204 const result = mapValues(offsetCss, (value, key) => {
3205 const prefix = key.substring(0, 1);
3206 if (prefix === "x") {
3207 return offsetCss[key] / pixelScaling.x;
3208 } else if (prefix === "y") {
3209 return offsetCss[key] / pixelScaling.y;
3210 }
3211 return null;
3212 });
3213 return result;
3214 }
3215 coordmap.scaleCssToImg = scaleCssToImg;
3216 function scaleImgToCss(offsetImg) {
3217 const pixelScaling = coordmap.imgToCssScalingRatio();
3218 const result = mapValues(offsetImg, (value, key) => {
3219 const prefix = key.substring(0, 1);
3220 if (prefix === "x") {
3221 return offsetImg[key] * pixelScaling.x;
3222 } else if (prefix === "y") {
3223 return offsetImg[key] * pixelScaling.y;
3224 }
3225 return null;
3226 });
3227 return result;
3228 }
3229 coordmap.scaleImgToCss = scaleImgToCss;
3230 coordmap.imgToCssScalingRatio = function() {
3231 const imgDims = findDims($img);
3232 return {
3233 x: imgDims.x / coordmap.dims.width,
3234 y: imgDims.y / coordmap.dims.height
3235 };
3236 };
3237 coordmap.cssToImgScalingRatio = function() {
3238 const res = coordmap.imgToCssScalingRatio();
3239 return {
3240 x: 1 / res.x,
3241 y: 1 / res.y
3242 };
3243 };
3244 coordmap.getPanelCss = function(offsetCss, expand = 0) {
3245 const offsetImg = coordmap.scaleCssToImg(offsetCss);
3246 const x2 = offsetImg.x;
3247 const y3 = offsetImg.y;
3248 const cssToImgRatio = coordmap.cssToImgScalingRatio();
3249 const expandImg = {
3250 x: expand * cssToImgRatio.x,
3251 y: expand * cssToImgRatio.y
3252 };
3253 const matches = [];
3254 const dists = [];
3255 let i5;
3256 for (i5 = 0; i5 < coordmap.panels.length; i5++) {
3257 const b3 = coordmap.panels[i5].range;
3258 if (x2 <= b3.right + expandImg.x && x2 >= b3.left - expandImg.x && y3 <= b3.bottom + expandImg.y && y3 >= b3.top - expandImg.y) {
3259 matches.push(coordmap.panels[i5]);
3260 let xdist = 0;
3261 let ydist = 0;
3262 if (x2 > b3.right && x2 <= b3.right + expandImg.x) {
3263 xdist = x2 - b3.right;
3264 } else if (x2 < b3.left && x2 >= b3.left - expandImg.x) {
3265 xdist = x2 - b3.left;
3266 }
3267 if (y3 > b3.bottom && y3 <= b3.bottom + expandImg.y) {
3268 ydist = y3 - b3.bottom;
3269 } else if (y3 < b3.top && y3 >= b3.top - expandImg.y) {
3270 ydist = y3 - b3.top;
3271 }
3272 dists.push(Math.sqrt(Math.pow(xdist, 2) + Math.pow(ydist, 2)));
3273 }
3274 }
3275 if (matches.length) {
3276 const minDist = Math.min.apply(null, dists);
3277 for (i5 = 0; i5 < matches.length; i5++) {
3278 if (dists[i5] === minDist) {
3279 return matches[i5];
3280 }
3281 }
3282 }
3283 return null;
3284 };
3285 coordmap.isInPanelCss = function(offsetCss, expand = 0) {
3286 if (coordmap.getPanelCss(offsetCss, expand)) return true;
3287 return false;
3288 };
3289 coordmap.mouseCoordinateSender = function(inputId, clip = true, nullOutside = false) {
3290 return function(e4) {
3291 if (e4 === null) {
3292 shinySetInputValue(inputId, null);
3293 return;
3294 }
3295 const coordsCss = coordmap.mouseOffsetCss(e4);
3296 if (!coordmap.isInPanelCss(coordsCss)) {
3297 if (nullOutside) {
3298 shinySetInputValue(inputId, null);
3299 return;
3300 }
3301 if (clip) return;
3302 const coords2 = {
3303 // eslint-disable-next-line @typescript-eslint/naming-convention
3304 coords_css: coordsCss,
3305 // eslint-disable-next-line @typescript-eslint/naming-convention
3306 coords_img: coordmap.scaleCssToImg(coordsCss)
3307 };
3308 shinySetInputValue(inputId, coords2, { priority: "event" });
3309 return;
3310 }
3311 const panel = coordmap.getPanelCss(coordsCss);
3312 const coordsImg = coordmap.scaleCssToImg(coordsCss);
3313 const coordsData = panel.scaleImgToData(coordsImg);
3314 const coords = {
3315 x: coordsData?.x,
3316 y: coordsData?.y,
3317 // eslint-disable-next-line @typescript-eslint/naming-convention
3318 coords_css: coordsCss,
3319 // eslint-disable-next-line @typescript-eslint/naming-convention
3320 coords_img: coordsImg,
3321 // eslint-disable-next-line @typescript-eslint/naming-convention
3322 img_css_ratio: coordmap.cssToImgScalingRatio()
3323 };
3324 import_jquery27.default.extend(coords, panel.panel_vars);
3325 coords.mapping = panel.mapping;
3326 coords.domain = panel.domain;
3327 coords.range = panel.range;
3328 coords.log = panel.log;
3329 shinySetInputValue(inputId, coords, { priority: "event" });
3330 };
3331 };
3332 return coordmap;
3333 }
3334
3335 // srcts/src/imageutils/findbox.ts
3336 function findBox(offset1, offset2) {
3337 return {
3338 xmin: Math.min(offset1.x, offset2.x),
3339 xmax: Math.max(offset1.x, offset2.x),
3340 ymin: Math.min(offset1.y, offset2.y),
3341 ymax: Math.max(offset1.y, offset2.y)
3342 };
3343 }
3344
3345 // srcts/src/imageutils/shiftToRange.ts
3346 function shiftToRange(vals, min, max) {
3347 if (!(vals instanceof Array)) vals = [vals];
3348 const maxval = Math.max.apply(null, vals);
3349 const minval = Math.min.apply(null, vals);
3350 let shiftAmount = 0;
3351 if (maxval > max) {
3352 shiftAmount = max - maxval;
3353 } else if (minval < min) {
3354 shiftAmount = min - minval;
3355 }
3356 const newvals = [];
3357 for (let i5 = 0; i5 < vals.length; i5++) {
3358 newvals[i5] = vals[i5] + shiftAmount;
3359 }
3360 return newvals;
3361 }
3362
3363 // srcts/src/imageutils/createBrush.ts
3364 function createBrush($el, opts, coordmap, expandPixels) {
3365 const resizeExpand = 10;
3366 const el = $el[0];
3367 let $div = null;
3368 const state = {};
3369 const cssToImg = coordmap.scaleCssToImg;
3370 const imgToCss = coordmap.scaleImgToCss;
3371 reset();
3372 function reset() {
3373 state.brushing = false;
3374 state.dragging = false;
3375 state.resizing = false;
3376 state.down = { x: NaN, y: NaN };
3377 state.up = { x: NaN, y: NaN };
3378 state.resizeSides = {
3379 left: false,
3380 right: false,
3381 top: false,
3382 bottom: false
3383 };
3384 state.boundsCss = {
3385 xmin: NaN,
3386 xmax: NaN,
3387 ymin: NaN,
3388 ymax: NaN
3389 };
3390 state.boundsData = {
3391 xmin: NaN,
3392 xmax: NaN,
3393 ymin: NaN,
3394 ymax: NaN
3395 };
3396 state.panel = null;
3397 state.changeStartBounds = {
3398 xmin: NaN,
3399 xmax: NaN,
3400 ymin: NaN,
3401 ymax: NaN
3402 };
3403 if ($div) $div.remove();
3404 }
3405 function hasOldBrush() {
3406 const oldDiv = $el.find("#" + el.id + "_brush");
3407 return oldDiv.length > 0;
3408 }
3409 function importOldBrush() {
3410 const oldDiv = $el.find("#" + el.id + "_brush");
3411 if (oldDiv.length === 0) return;
3412 const oldBoundsData = oldDiv.data("bounds-data");
3413 const oldPanel = oldDiv.data("panel");
3414 if (!oldBoundsData || !oldPanel) return;
3415 for (let i5 = 0; i5 < coordmap.panels.length; i5++) {
3416 const curPanel = coordmap.panels[i5];
3417 if (equal(oldPanel.mapping, curPanel.mapping) && equal(oldPanel.panel_vars, curPanel.panel_vars)) {
3418 state.panel = coordmap.panels[i5];
3419 break;
3420 }
3421 }
3422 if (state.panel === null) {
3423 oldDiv.remove();
3424 return;
3425 }
3426 $div = oldDiv;
3427 boundsData(oldBoundsData);
3428 updateDiv();
3429 }
3430 function onResize() {
3431 const boundsDataVal = boundsData();
3432 if (Object.values(boundsDataVal).some(isnan)) return;
3433 boundsData(boundsDataVal);
3434 updateDiv();
3435 }
3436 function isInsideBrush(offsetCss) {
3437 const bounds = state.boundsCss;
3438 return offsetCss.x <= bounds.xmax && offsetCss.x >= bounds.xmin && offsetCss.y <= bounds.ymax && offsetCss.y >= bounds.ymin;
3439 }
3440 function isInResizeArea(offsetCss) {
3441 const sides = whichResizeSides(offsetCss);
3442 return sides.left || sides.right || sides.top || sides.bottom;
3443 }
3444 function whichResizeSides(offsetCss) {
3445 const b3 = state.boundsCss;
3446 const e4 = {
3447 xmin: b3.xmin - resizeExpand,
3448 xmax: b3.xmax + resizeExpand,
3449 ymin: b3.ymin - resizeExpand,
3450 ymax: b3.ymax + resizeExpand
3451 };
3452 const res = {
3453 left: false,
3454 right: false,
3455 top: false,
3456 bottom: false
3457 };
3458 if ((opts.brushDirection === "xy" || opts.brushDirection === "x") && offsetCss.y <= e4.ymax && offsetCss.y >= e4.ymin) {
3459 if (offsetCss.x < b3.xmin && offsetCss.x >= e4.xmin) res.left = true;
3460 else if (offsetCss.x > b3.xmax && offsetCss.x <= e4.xmax) res.right = true;
3461 }
3462 if ((opts.brushDirection === "xy" || opts.brushDirection === "y") && offsetCss.x <= e4.xmax && offsetCss.x >= e4.xmin) {
3463 if (offsetCss.y < b3.ymin && offsetCss.y >= e4.ymin) res.top = true;
3464 else if (offsetCss.y > b3.ymax && offsetCss.y <= e4.ymax) res.bottom = true;
3465 }
3466 return res;
3467 }
3468 function boundsCss(boxCss) {
3469 if (boxCss === void 0) {
3470 return { ...state.boundsCss };
3471 }
3472 let minCss = { x: boxCss.xmin, y: boxCss.ymin };
3473 let maxCss = { x: boxCss.xmax, y: boxCss.ymax };
3474 const panel = state.panel;
3475 const panelBoundsImg = panel.range;
3476 if (opts.brushClip) {
3477 minCss = imgToCss(panel.clipImg(cssToImg(minCss)));
3478 maxCss = imgToCss(panel.clipImg(cssToImg(maxCss)));
3479 }
3480 if (opts.brushDirection === "xy") {
3481 } else if (opts.brushDirection === "x") {
3482 minCss.y = imgToCss({ y: panelBoundsImg.top }).y;
3483 maxCss.y = imgToCss({ y: panelBoundsImg.bottom }).y;
3484 } else if (opts.brushDirection === "y") {
3485 minCss.x = imgToCss({ x: panelBoundsImg.left }).x;
3486 maxCss.x = imgToCss({ x: panelBoundsImg.right }).x;
3487 }
3488 state.boundsCss = {
3489 xmin: minCss.x,
3490 xmax: maxCss.x,
3491 ymin: minCss.y,
3492 ymax: maxCss.y
3493 };
3494 const minData = panel.scaleImgToData(cssToImg(minCss));
3495 const maxData = panel.scaleImgToData(cssToImg(maxCss));
3496 state.boundsData = findBox(minData, maxData);
3497 state.boundsData = mapValues(
3498 state.boundsData,
3499 (val) => roundSignif(val, 14)
3500 );
3501 $div.data("bounds-data", state.boundsData);
3502 $div.data("panel", state.panel);
3503 return void 0;
3504 }
3505 function boundsData(boxData) {
3506 if (typeof boxData === "undefined") {
3507 return { ...state.boundsData };
3508 }
3509 let boxCss = imgToCss(state.panel.scaleDataToImg(boxData));
3510 boxCss = mapValues(boxCss, (val) => roundSignif(val, 13));
3511 boundsCss({
3512 xmin: Math.min(boxCss.xmin, boxCss.xmax),
3513 xmax: Math.max(boxCss.xmin, boxCss.xmax),
3514 ymin: Math.min(boxCss.ymin, boxCss.ymax),
3515 ymax: Math.max(boxCss.ymin, boxCss.ymax)
3516 });
3517 return void 0;
3518 }
3519 function getPanel2() {
3520 return state.panel;
3521 }
3522 function addDiv() {
3523 if ($div) $div.remove();
3524 $div = (0, import_jquery28.default)(document.createElement("div")).attr("id", el.id + "_brush").css({
3525 "background-color": opts.brushFill,
3526 opacity: opts.brushOpacity,
3527 "pointer-events": "none",
3528 position: "absolute"
3529 }).hide();
3530 const borderStyle = "1px solid " + opts.brushStroke;
3531 if (opts.brushDirection === "xy") {
3532 $div.css({
3533 border: borderStyle
3534 });
3535 } else if (opts.brushDirection === "x") {
3536 $div.css({
3537 "border-left": borderStyle,
3538 "border-right": borderStyle
3539 });
3540 } else if (opts.brushDirection === "y") {
3541 $div.css({
3542 "border-top": borderStyle,
3543 "border-bottom": borderStyle
3544 });
3545 }
3546 $el.append($div);
3547 $div.offset(
3548 // @ts-expect-error; This is a jQuery Typing issue
3549 { x: 0, y: 0 }
3550 ).width(0).outerHeight(0);
3551 }
3552 function updateDiv() {
3553 const imgOffsetCss = findOrigin($el.find("img"));
3554 const b3 = state.boundsCss;
3555 $div.offset({
3556 top: imgOffsetCss.y + b3.ymin,
3557 left: imgOffsetCss.x + b3.xmin
3558 }).outerWidth(b3.xmax - b3.xmin + 1).outerHeight(b3.ymax - b3.ymin + 1);
3559 }
3560 function down(offsetCss) {
3561 if (offsetCss === void 0) return state.down;
3562 state.down = offsetCss;
3563 return void 0;
3564 }
3565 function up(offsetCss) {
3566 if (offsetCss === void 0) return state.up;
3567 state.up = offsetCss;
3568 return void 0;
3569 }
3570 function isBrushing() {
3571 return state.brushing;
3572 }
3573 function startBrushing() {
3574 state.brushing = true;
3575 addDiv();
3576 state.panel = coordmap.getPanelCss(state.down, expandPixels);
3577 boundsCss(findBox(state.down, state.down));
3578 updateDiv();
3579 }
3580 function brushTo(offsetCss) {
3581 boundsCss(findBox(state.down, offsetCss));
3582 $div.show();
3583 updateDiv();
3584 }
3585 function stopBrushing() {
3586 state.brushing = false;
3587 boundsCss(findBox(state.down, state.up));
3588 }
3589 function isDragging() {
3590 return state.dragging;
3591 }
3592 function startDragging() {
3593 state.dragging = true;
3594 state.changeStartBounds = { ...state.boundsCss };
3595 }
3596 function dragTo(offsetCss) {
3597 const dx = offsetCss.x - state.down.x;
3598 const dy = offsetCss.y - state.down.y;
3599 const start = state.changeStartBounds;
3600 let newBoundsCss = {
3601 xmin: start.xmin + dx,
3602 xmax: start.xmax + dx,
3603 ymin: start.ymin + dy,
3604 ymax: start.ymax + dy
3605 };
3606 if (opts.brushClip) {
3607 const panel = state.panel;
3608 const panelBoundsImg = panel.range;
3609 const newBoundsImg = cssToImg(newBoundsCss);
3610 let xvalsImg = [newBoundsImg.xmin, newBoundsImg.xmax];
3611 let yvalsImg = [newBoundsImg.ymin, newBoundsImg.ymax];
3612 xvalsImg = shiftToRange(
3613 xvalsImg,
3614 panelBoundsImg.left,
3615 panelBoundsImg.right
3616 );
3617 yvalsImg = shiftToRange(
3618 yvalsImg,
3619 panelBoundsImg.top,
3620 panelBoundsImg.bottom
3621 );
3622 newBoundsCss = imgToCss({
3623 xmin: xvalsImg[0],
3624 xmax: xvalsImg[1],
3625 ymin: yvalsImg[0],
3626 ymax: yvalsImg[1]
3627 });
3628 }
3629 boundsCss(newBoundsCss);
3630 updateDiv();
3631 }
3632 function stopDragging() {
3633 state.dragging = false;
3634 }
3635 function isResizing() {
3636 return state.resizing;
3637 }
3638 function startResizing() {
3639 state.resizing = true;
3640 state.changeStartBounds = { ...state.boundsCss };
3641 state.resizeSides = whichResizeSides(state.down);
3642 }
3643 function resizeTo(offsetCss) {
3644 const dCss = {
3645 x: offsetCss.x - state.down.x,
3646 y: offsetCss.y - state.down.y
3647 };
3648 const dImg = cssToImg(dCss);
3649 const bImg = cssToImg(state.changeStartBounds);
3650 const panel = state.panel;
3651 const panelBoundsImg = panel.range;
3652 if (state.resizeSides.left) {
3653 const xminImg = shiftToRange(
3654 bImg.xmin + dImg.x,
3655 panelBoundsImg.left,
3656 bImg.xmax
3657 )[0];
3658 bImg.xmin = xminImg;
3659 } else if (state.resizeSides.right) {
3660 const xmaxImg = shiftToRange(
3661 bImg.xmax + dImg.x,
3662 bImg.xmin,
3663 panelBoundsImg.right
3664 )[0];
3665 bImg.xmax = xmaxImg;
3666 }
3667 if (state.resizeSides.top) {
3668 const yminImg = shiftToRange(
3669 bImg.ymin + dImg.y,
3670 panelBoundsImg.top,
3671 bImg.ymax
3672 )[0];
3673 bImg.ymin = yminImg;
3674 } else if (state.resizeSides.bottom) {
3675 const ymaxImg = shiftToRange(
3676 bImg.ymax + dImg.y,
3677 bImg.ymin,
3678 panelBoundsImg.bottom
3679 )[0];
3680 bImg.ymax = ymaxImg;
3681 }
3682 boundsCss(imgToCss(bImg));
3683 updateDiv();
3684 }
3685 function stopResizing() {
3686 state.resizing = false;
3687 }
3688 return {
3689 reset,
3690 hasOldBrush,
3691 importOldBrush,
3692 isInsideBrush,
3693 isInResizeArea,
3694 whichResizeSides,
3695 onResize,
3696 // A callback when the wrapper div or img is resized.
3697 boundsCss,
3698 boundsData,
3699 getPanel: getPanel2,
3700 down,
3701 up,
3702 isBrushing,
3703 startBrushing,
3704 brushTo,
3705 stopBrushing,
3706 isDragging,
3707 startDragging,
3708 dragTo,
3709 stopDragging,
3710 isResizing,
3711 startResizing,
3712 resizeTo,
3713 stopResizing
3714 };
3715 }
3716
3717 // srcts/src/imageutils/createClickInfo.ts
3718 var import_jquery29 = __toESM(require_jquery());
3719 function createClickInfo($el, dblclickId, dblclickDelay) {
3720 let clickTimer = void 0;
3721 let pendingE = null;
3722 function triggerEvent(newEventType, e4) {
3723 const e22 = import_jquery29.default.Event(newEventType, {
3724 which: e4.which,
3725 pageX: e4.pageX,
3726 pageY: e4.pageY
3727 });
3728 $el.trigger(e22);
3729 }
3730 function triggerPendingMousedown2() {
3731 if (pendingE) {
3732 triggerEvent("mousedown2", pendingE);
3733 pendingE = null;
3734 }
3735 }
3736 function scheduleMousedown2(e4) {
3737 pendingE = e4;
3738 clickTimer = window.setTimeout(function() {
3739 triggerPendingMousedown2();
3740 }, dblclickDelay);
3741 }
3742 function mousedown(e4) {
3743 if (e4.which !== 1) return;
3744 if (!dblclickId) {
3745 triggerEvent("mousedown2", e4);
3746 return;
3747 }
3748 if (pendingE === null) {
3749 scheduleMousedown2(e4);
3750 } else {
3751 clearTimeout(clickTimer);
3752 if (pendingE && Math.abs(pendingE.pageX - e4.pageX) > 2 || Math.abs(pendingE.pageY - e4.pageY) > 2) {
3753 triggerPendingMousedown2();
3754 scheduleMousedown2(e4);
3755 } else {
3756 pendingE = null;
3757 triggerEvent("dblclick2", e4);
3758 }
3759 }
3760 }
3761 function dblclickIE8(e4) {
3762 e4.which = 1;
3763 triggerEvent("dblclick2", e4);
3764 }
3765 return {
3766 mousedown,
3767 dblclickIE8
3768 };
3769 }
3770
3771 // srcts/src/imageutils/createHandlers.ts
3772 var import_jquery31 = __toESM(require_jquery());
3773
3774 // srcts/src/imageutils/imageBindingUtils.ts
3775 var import_jquery30 = __toESM(require_jquery());
3776 function findImageOutputs(scope = document.documentElement) {
3777 return (0, import_jquery30.default)(scope).find(".shiny-image-output, .shiny-plot-output");
3778 }
3779
3780 // srcts/src/imageutils/createHandlers.ts
3781 function createClickHandler(inputId, clip, coordmap) {
3782 const clickInfoSender = coordmap.mouseCoordinateSender(inputId, clip);
3783 clickInfoSender(null);
3784 return {
3785 mousedown: function(e4) {
3786 if (e4.which !== 1) return;
3787 clickInfoSender(e4);
3788 },
3789 onResetImg: function() {
3790 clickInfoSender(null);
3791 },
3792 onResize: null
3793 };
3794 }
3795 function createHoverHandler(inputId, delay, delayType, clip, nullOutside, coordmap) {
3796 const sendHoverInfo = coordmap.mouseCoordinateSender(
3797 inputId,
3798 clip,
3799 nullOutside
3800 );
3801 let hoverInfoSender;
3802 if (delayType === "throttle")
3803 hoverInfoSender = new Throttler(null, sendHoverInfo, delay);
3804 else hoverInfoSender = new Debouncer(null, sendHoverInfo, delay);
3805 hoverInfoSender.immediateCall(null);
3806 let mouseout;
3807 if (nullOutside)
3808 mouseout = function() {
3809 hoverInfoSender.normalCall(null);
3810 };
3811 else
3812 mouseout = function() {
3813 };
3814 return {
3815 mousemove: function(e4) {
3816 hoverInfoSender.normalCall(e4);
3817 },
3818 mouseout,
3819 onResetImg: function() {
3820 hoverInfoSender.immediateCall(null);
3821 },
3822 onResize: null
3823 };
3824 }
3825 function createBrushHandler(inputId, $el, opts, coordmap, outputId) {
3826 const expandPixels = 20;
3827 const brush = createBrush($el, opts, coordmap, expandPixels);
3828 $el.on("shiny-internal:brushed.image_output", function(e4, coords) {
3829 if (coords.brushId === inputId && coords.outputId !== outputId) {
3830 $el.data("mostRecentBrush", false);
3831 brush.reset();
3832 }
3833 });
3834 function setCursorStyle(style) {
3835 $el.removeClass(
3836 "crosshair grabbable grabbing ns-resize ew-resize nesw-resize nwse-resize"
3837 );
3838 if (style) $el.addClass(style);
3839 }
3840 function sendBrushInfo() {
3841 const coords = brush.boundsData();
3842 if (isNaN(coords.xmin)) {
3843 shinySetInputValue(inputId, null);
3844 findImageOutputs(document.documentElement).trigger(
3845 "shiny-internal:brushed",
3846 {
3847 brushId: inputId,
3848 outputId: null
3849 }
3850 );
3851 return;
3852 }
3853 const panel = brush.getPanel();
3854 import_jquery31.default.extend(coords, panel.panel_vars);
3855 coords.coords_css = brush.boundsCss();
3856 coords.coords_img = coordmap.scaleCssToImg(coords.coords_css);
3857 coords.img_css_ratio = coordmap.cssToImgScalingRatio();
3858 coords.mapping = panel.mapping;
3859 coords.domain = panel.domain;
3860 coords.range = panel.range;
3861 coords.log = panel.log;
3862 coords.direction = opts.brushDirection;
3863 coords.brushId = inputId;
3864 coords.outputId = outputId;
3865 shinySetInputValue(inputId, coords);
3866 $el.data("mostRecentBrush", true);
3867 findImageOutputs(document.documentElement).trigger(
3868 "shiny-internal:brushed",
3869 coords
3870 );
3871 }
3872 let brushInfoSender;
3873 if (opts.brushDelayType === "throttle") {
3874 brushInfoSender = new Throttler(null, sendBrushInfo, opts.brushDelay);
3875 } else {
3876 brushInfoSender = new Debouncer(null, sendBrushInfo, opts.brushDelay);
3877 }
3878 if (!brush.hasOldBrush()) {
3879 brushInfoSender.immediateCall();
3880 }
3881 function mousedown(e4) {
3882 if (brush.isBrushing() || brush.isDragging() || brush.isResizing()) return;
3883 if (e4.which !== 1) return;
3884 const offsetCss = coordmap.mouseOffsetCss(e4);
3885 if (opts.brushClip && !coordmap.isInPanelCss(offsetCss, expandPixels))
3886 return;
3887 brush.up({ x: NaN, y: NaN });
3888 brush.down(offsetCss);
3889 if (brush.isInResizeArea(offsetCss)) {
3890 brush.startResizing(offsetCss);
3891 (0, import_jquery31.default)(document).on("mousemove.image_brush", mousemoveResizing).on("mouseup.image_brush", mouseupResizing);
3892 } else if (brush.isInsideBrush(offsetCss)) {
3893 brush.startDragging(offsetCss);
3894 setCursorStyle("grabbing");
3895 (0, import_jquery31.default)(document).on("mousemove.image_brush", mousemoveDragging).on("mouseup.image_brush", mouseupDragging);
3896 } else {
3897 const panel = coordmap.getPanelCss(offsetCss, expandPixels);
3898 brush.startBrushing(panel.clipImg(coordmap.scaleCssToImg(offsetCss)));
3899 (0, import_jquery31.default)(document).on("mousemove.image_brush", mousemoveBrushing).on("mouseup.image_brush", mouseupBrushing);
3900 }
3901 }
3902 function mousemove(e4) {
3903 const offsetCss = coordmap.mouseOffsetCss(e4);
3904 if (!(brush.isBrushing() || brush.isDragging() || brush.isResizing())) {
3905 if (brush.isInResizeArea(offsetCss)) {
3906 const r4 = brush.whichResizeSides(offsetCss);
3907 if (r4.left && r4.top || r4.right && r4.bottom) {
3908 setCursorStyle("nwse-resize");
3909 } else if (r4.left && r4.bottom || r4.right && r4.top) {
3910 setCursorStyle("nesw-resize");
3911 } else if (r4.left || r4.right) {
3912 setCursorStyle("ew-resize");
3913 } else if (r4.top || r4.bottom) {
3914 setCursorStyle("ns-resize");
3915 }
3916 } else if (brush.isInsideBrush(offsetCss)) {
3917 setCursorStyle("grabbable");
3918 } else if (coordmap.isInPanelCss(offsetCss, expandPixels)) {
3919 setCursorStyle("crosshair");
3920 } else {
3921 setCursorStyle(null);
3922 }
3923 }
3924 }
3925 function mousemoveBrushing(e4) {
3926 brush.brushTo(coordmap.mouseOffsetCss(e4));
3927 brushInfoSender.normalCall();
3928 }
3929 function mousemoveDragging(e4) {
3930 brush.dragTo(coordmap.mouseOffsetCss(e4));
3931 brushInfoSender.normalCall();
3932 }
3933 function mousemoveResizing(e4) {
3934 brush.resizeTo(coordmap.mouseOffsetCss(e4));
3935 brushInfoSender.normalCall();
3936 }
3937 function mouseupBrushing(e4) {
3938 if (e4.which !== 1) return;
3939 (0, import_jquery31.default)(document).off("mousemove.image_brush").off("mouseup.image_brush");
3940 brush.up(coordmap.mouseOffsetCss(e4));
3941 brush.stopBrushing();
3942 setCursorStyle("crosshair");
3943 if (brush.down().x === brush.up().x && brush.down().y === brush.up().y) {
3944 brush.reset();
3945 brushInfoSender.immediateCall();
3946 return;
3947 }
3948 if (brushInfoSender.isPending()) brushInfoSender.immediateCall();
3949 }
3950 function mouseupDragging(e4) {
3951 if (e4.which !== 1) return;
3952 (0, import_jquery31.default)(document).off("mousemove.image_brush").off("mouseup.image_brush");
3953 brush.up(coordmap.mouseOffsetCss(e4));
3954 brush.stopDragging();
3955 setCursorStyle("grabbable");
3956 if (brushInfoSender.isPending()) brushInfoSender.immediateCall();
3957 }
3958 function mouseupResizing(e4) {
3959 if (e4.which !== 1) return;
3960 (0, import_jquery31.default)(document).off("mousemove.image_brush").off("mouseup.image_brush");
3961 brush.up(coordmap.mouseOffsetCss(e4));
3962 brush.stopResizing();
3963 if (brushInfoSender.isPending()) brushInfoSender.immediateCall();
3964 }
3965 function onResetImg() {
3966 if (opts.brushResetOnNew) {
3967 if ($el.data("mostRecentBrush")) {
3968 brush.reset();
3969 brushInfoSender.immediateCall();
3970 }
3971 }
3972 }
3973 if (!opts.brushResetOnNew) {
3974 if ($el.data("mostRecentBrush")) {
3975 brush.importOldBrush();
3976 brushInfoSender.immediateCall();
3977 }
3978 }
3979 function onResize() {
3980 brush.onResize();
3981 brushInfoSender.immediateCall();
3982 }
3983 return {
3984 mousedown,
3985 mousemove,
3986 onResetImg,
3987 onResize
3988 };
3989 }
3990
3991 // srcts/src/imageutils/disableDrag.ts
3992 function disableDrag($el, $img) {
3993 $img.css("-webkit-user-drag", "none");
3994 $img.off("dragstart.image_output");
3995 $img.on("dragstart.image_output", function() {
3996 return false;
3997 });
3998 $el.off("selectstart.image_output");
3999 $el.on("selectstart.image_output", function() {
4000 return false;
4001 });
4002 }
4003
4004 // srcts/src/bindings/output/image.ts
4005 var ImageOutputBinding = class extends OutputBinding {
4006 find(scope) {
4007 return findImageOutputs(scope);
4008 }
4009 renderValue(el, data) {
4010 const outputId = this.getId(el);
4011 const $el = (0, import_jquery32.default)(el);
4012 let img;
4013 let $img = $el.find("img");
4014 if ($img.length === 0) {
4015 img = document.createElement("img");
4016 $el.append(img);
4017 $img = (0, import_jquery32.default)(img);
4018 } else {
4019 img = $img[0];
4020 $img.trigger("reset");
4021 }
4022 if (!data) {
4023 $el.empty();
4024 return;
4025 }
4026 const opts = {
4027 clickId: $el.data("click-id"),
4028 clickClip: ifUndefined(strToBool($el.data("click-clip")), true),
4029 dblclickId: $el.data("dblclick-id"),
4030 dblclickClip: ifUndefined(strToBool($el.data("dblclick-clip")), true),
4031 dblclickDelay: ifUndefined($el.data("dblclick-delay"), 400),
4032 hoverId: $el.data("hover-id"),
4033 hoverClip: ifUndefined(strToBool($el.data("hover-clip")), true),
4034 hoverDelayType: ifUndefined($el.data("hover-delay-type"), "debounce"),
4035 hoverDelay: ifUndefined($el.data("hover-delay"), 300),
4036 hoverNullOutside: ifUndefined(
4037 strToBool($el.data("hover-null-outside")),
4038 false
4039 ),
4040 brushId: $el.data("brush-id"),
4041 brushClip: ifUndefined(strToBool($el.data("brush-clip")), true),
4042 brushDelayType: ifUndefined($el.data("brush-delay-type"), "debounce"),
4043 brushDelay: ifUndefined($el.data("brush-delay"), 300),
4044 brushFill: ifUndefined($el.data("brush-fill"), "#666"),
4045 brushStroke: ifUndefined($el.data("brush-stroke"), "#000"),
4046 brushOpacity: ifUndefined($el.data("brush-opacity"), 0.3),
4047 brushDirection: ifUndefined($el.data("brush-direction"), "xy"),
4048 brushResetOnNew: ifUndefined(
4049 strToBool($el.data("brush-reset-on-new")),
4050 false
4051 ),
4052 coordmap: data.coordmap
4053 };
4054 if (opts.brushFill === "auto") {
4055 opts.brushFill = getComputedLinkColor($el[0]);
4056 }
4057 if (opts.brushStroke === "auto") {
4058 opts.brushStroke = getStyle($el[0], "color");
4059 }
4060 import_jquery32.default.each(data, function(key, value) {
4061 if (value === null || key === "coordmap") {
4062 return;
4063 }
4064 if (key === "src" && value === img.getAttribute("src")) {
4065 img.removeAttribute("src");
4066 }
4067 img.setAttribute(key, value);
4068 });
4069 for (let i5 = 0; i5 < img.attributes.length; i5++) {
4070 const attrib = img.attributes[i5];
4071 if (attrib.specified && !hasOwnProperty(data, attrib.name)) {
4072 img.removeAttribute(attrib.name);
4073 }
4074 }
4075 if (!opts.coordmap) {
4076 opts.coordmap = {
4077 panels: [],
4078 dims: {
4079 // These values be set to the naturalWidth and naturalHeight once the image has loaded
4080 height: null,
4081 width: null
4082 }
4083 };
4084 }
4085 $el.off(".image_output");
4086 $img.off(".image_output");
4087 $img.off("load.shiny_image_interaction");
4088 $img.one("load.shiny_image_interaction", function() {
4089 const optsCoordmap = opts.coordmap = initCoordmap($el, opts.coordmap);
4090 const clickInfo = createClickInfo(
4091 $el,
4092 opts.dblclickId,
4093 opts.dblclickDelay
4094 );
4095 $el.on("mousedown.image_output", clickInfo.mousedown);
4096 if (isIE() && IEVersion() === 8) {
4097 $el.on("dblclick.image_output", clickInfo.dblclickIE8);
4098 }
4099 if (opts.clickId) {
4100 disableDrag($el, $img);
4101 const clickHandler = createClickHandler(
4102 opts.clickId,
4103 opts.clickClip,
4104 optsCoordmap
4105 );
4106 $el.on("mousedown2.image_output", clickHandler.mousedown);
4107 $el.on("resize.image_output", clickHandler.onResize);
4108 $img.on("reset.image_output", clickHandler.onResetImg);
4109 }
4110 if (opts.dblclickId) {
4111 disableDrag($el, $img);
4112 const dblclickHandler = createClickHandler(
4113 opts.dblclickId,
4114 opts.clickClip,
4115 optsCoordmap
4116 );
4117 $el.on("dblclick2.image_output", dblclickHandler.mousedown);
4118 $el.on("resize.image_output", dblclickHandler.onResize);
4119 $img.on("reset.image_output", dblclickHandler.onResetImg);
4120 }
4121 if (opts.hoverId) {
4122 disableDrag($el, $img);
4123 const hoverHandler = createHoverHandler(
4124 opts.hoverId,
4125 opts.hoverDelay,
4126 opts.hoverDelayType,
4127 opts.hoverClip,
4128 opts.hoverNullOutside,
4129 optsCoordmap
4130 );
4131 $el.on("mousemove.image_output", hoverHandler.mousemove);
4132 $el.on("mouseout.image_output", hoverHandler.mouseout);
4133 $el.on("resize.image_output", hoverHandler.onResize);
4134 $img.on("reset.image_output", hoverHandler.onResetImg);
4135 }
4136 if (opts.brushId) {
4137 disableDrag($el, $img);
4138 const brushHandler = createBrushHandler(
4139 opts.brushId,
4140 $el,
4141 opts,
4142 optsCoordmap,
4143 outputId
4144 );
4145 $el.on("mousedown.image_output", brushHandler.mousedown);
4146 $el.on("mousemove.image_output", brushHandler.mousemove);
4147 $el.on("resize.image_output", brushHandler.onResize);
4148 $img.on("reset.image_output", brushHandler.onResetImg);
4149 }
4150 if (opts.clickId || opts.dblclickId || opts.hoverId || opts.brushId) {
4151 $el.addClass("crosshair");
4152 }
4153 if (data.error)
4154 console.log("Error on server extracting coordmap: " + data.error);
4155 });
4156 }
4157 renderError(el, err) {
4158 (0, import_jquery32.default)(el).find("img").trigger("reset");
4159 OutputBinding.prototype.renderError.call(this, el, err);
4160 }
4161 clearError(el) {
4162 (0, import_jquery32.default)(el).contents().filter(function() {
4163 return !(this instanceof HTMLElement && (this.tagName === "IMG" || this.id === el.id + "_brush"));
4164 }).remove();
4165 OutputBinding.prototype.clearError.call(this, el);
4166 }
4167 resize(el, width, height) {
4168 (0, import_jquery32.default)(el).find("img").trigger("resize");
4169 return;
4170 width;
4171 height;
4172 }
4173 };
4174 var imageOutputBinding = new ImageOutputBinding();
4175
4176 // srcts/src/bindings/output/text.ts
4177 var import_jquery33 = __toESM(require_jquery());
4178 var TextOutputBinding = class extends OutputBinding {
4179 find(scope) {
4180 return (0, import_jquery33.default)(scope).find(".shiny-text-output");
4181 }
4182 renderValue(el, data) {
4183 (0, import_jquery33.default)(el).text(data);
4184 }
4185 };
4186
4187 // srcts/src/bindings/output/index.ts
4188 function initOutputBindings() {
4189 const outputBindings = new BindingRegistry();
4190 outputBindings.register(new TextOutputBinding(), "shiny.textOutput");
4191 outputBindings.register(
4192 new DownloadLinkOutputBinding(),
4193 "shiny.downloadLink"
4194 );
4195 outputBindings.register(
4196 new DatatableOutputBinding(),
4197 "shiny.datatableOutput"
4198 );
4199 outputBindings.register(new HtmlOutputBinding(), "shiny.htmlOutput");
4200 outputBindings.register(imageOutputBinding, "shiny.imageOutput");
4201 return { outputBindings };
4202 }
4203
4204 // node_modules/@lit/reactive-element/css-tag.js
4205 var t = globalThis;
4206 var e = t.ShadowRoot && (void 0 === t.ShadyCSS || t.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype;
4207 var s = Symbol();
4208 var o = /* @__PURE__ */ new WeakMap();
4209 var n = class {
4210 constructor(t3, e4, o5) {
4211 if (this._$cssResult$ = true, o5 !== s) throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");
4212 this.cssText = t3, this.t = e4;
4213 }
4214 get styleSheet() {
4215 let t3 = this.o;
4216 const s4 = this.t;
4217 if (e && void 0 === t3) {
4218 const e4 = void 0 !== s4 && 1 === s4.length;
4219 e4 && (t3 = o.get(s4)), void 0 === t3 && ((this.o = t3 = new CSSStyleSheet()).replaceSync(this.cssText), e4 && o.set(s4, t3));
4220 }
4221 return t3;
4222 }
4223 toString() {
4224 return this.cssText;
4225 }
4226 };
4227 var r = (t3) => new n("string" == typeof t3 ? t3 : t3 + "", void 0, s);
4228 var i = (t3, ...e4) => {
4229 const o5 = 1 === t3.length ? t3[0] : e4.reduce((e5, s4, o6) => e5 + ((t4) => {
4230 if (true === t4._$cssResult$) return t4.cssText;
4231 if ("number" == typeof t4) return t4;
4232 throw Error("Value passed to 'css' function must be a 'css' function result: " + t4 + ". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.");
4233 })(s4) + t3[o6 + 1], t3[0]);
4234 return new n(o5, t3, s);
4235 };
4236 var S = (s4, o5) => {
4237 if (e) s4.adoptedStyleSheets = o5.map((t3) => t3 instanceof CSSStyleSheet ? t3 : t3.styleSheet);
4238 else for (const e4 of o5) {
4239 const o6 = document.createElement("style"), n4 = t.litNonce;
4240 void 0 !== n4 && o6.setAttribute("nonce", n4), o6.textContent = e4.cssText, s4.appendChild(o6);
4241 }
4242 };
4243 var c = e ? (t3) => t3 : (t3) => t3 instanceof CSSStyleSheet ? ((t4) => {
4244 let e4 = "";
4245 for (const s4 of t4.cssRules) e4 += s4.cssText;
4246 return r(e4);
4247 })(t3) : t3;
4248
4249 // node_modules/@lit/reactive-element/reactive-element.js
4250 var { is: i2, defineProperty: e2, getOwnPropertyDescriptor: h, getOwnPropertyNames: r2, getOwnPropertySymbols: o2, getPrototypeOf: n2 } = Object;
4251 var a = globalThis;
4252 var c2 = a.trustedTypes;
4253 var l = c2 ? c2.emptyScript : "";
4254 var p = a.reactiveElementPolyfillSupport;
4255 var d = (t3, s4) => t3;
4256 var u = { toAttribute(t3, s4) {
4257 switch (s4) {
4258 case Boolean:
4259 t3 = t3 ? l : null;
4260 break;
4261 case Object:
4262 case Array:
4263 t3 = null == t3 ? t3 : JSON.stringify(t3);
4264 }
4265 return t3;
4266 }, fromAttribute(t3, s4) {
4267 let i5 = t3;
4268 switch (s4) {
4269 case Boolean:
4270 i5 = null !== t3;
4271 break;
4272 case Number:
4273 i5 = null === t3 ? null : Number(t3);
4274 break;
4275 case Object:
4276 case Array:
4277 try {
4278 i5 = JSON.parse(t3);
4279 } catch (t4) {
4280 i5 = null;
4281 }
4282 }
4283 return i5;
4284 } };
4285 var f = (t3, s4) => !i2(t3, s4);
4286 var b = { attribute: true, type: String, converter: u, reflect: false, useDefault: false, hasChanged: f };
4287 Symbol.metadata ??= Symbol("metadata"), a.litPropertyMetadata ??= /* @__PURE__ */ new WeakMap();
4288 var y = class extends HTMLElement {
4289 static addInitializer(t3) {
4290 this._$Ei(), (this.l ??= []).push(t3);
4291 }
4292 static get observedAttributes() {
4293 return this.finalize(), this._$Eh && [...this._$Eh.keys()];
4294 }
4295 static createProperty(t3, s4 = b) {
4296 if (s4.state && (s4.attribute = false), this._$Ei(), this.prototype.hasOwnProperty(t3) && ((s4 = Object.create(s4)).wrapped = true), this.elementProperties.set(t3, s4), !s4.noAccessor) {
4297 const i5 = Symbol(), h3 = this.getPropertyDescriptor(t3, i5, s4);
4298 void 0 !== h3 && e2(this.prototype, t3, h3);
4299 }
4300 }
4301 static getPropertyDescriptor(t3, s4, i5) {
4302 const { get: e4, set: r4 } = h(this.prototype, t3) ?? { get() {
4303 return this[s4];
4304 }, set(t4) {
4305 this[s4] = t4;
4306 } };
4307 return { get: e4, set(s5) {
4308 const h3 = e4?.call(this);
4309 r4?.call(this, s5), this.requestUpdate(t3, h3, i5);
4310 }, configurable: true, enumerable: true };
4311 }
4312 static getPropertyOptions(t3) {
4313 return this.elementProperties.get(t3) ?? b;
4314 }
4315 static _$Ei() {
4316 if (this.hasOwnProperty(d("elementProperties"))) return;
4317 const t3 = n2(this);
4318 t3.finalize(), void 0 !== t3.l && (this.l = [...t3.l]), this.elementProperties = new Map(t3.elementProperties);
4319 }
4320 static finalize() {
4321 if (this.hasOwnProperty(d("finalized"))) return;
4322 if (this.finalized = true, this._$Ei(), this.hasOwnProperty(d("properties"))) {
4323 const t4 = this.properties, s4 = [...r2(t4), ...o2(t4)];
4324 for (const i5 of s4) this.createProperty(i5, t4[i5]);
4325 }
4326 const t3 = this[Symbol.metadata];
4327 if (null !== t3) {
4328 const s4 = litPropertyMetadata.get(t3);
4329 if (void 0 !== s4) for (const [t4, i5] of s4) this.elementProperties.set(t4, i5);
4330 }
4331 this._$Eh = /* @__PURE__ */ new Map();
4332 for (const [t4, s4] of this.elementProperties) {
4333 const i5 = this._$Eu(t4, s4);
4334 void 0 !== i5 && this._$Eh.set(i5, t4);
4335 }
4336 this.elementStyles = this.finalizeStyles(this.styles);
4337 }
4338 static finalizeStyles(s4) {
4339 const i5 = [];
4340 if (Array.isArray(s4)) {
4341 const e4 = new Set(s4.flat(1 / 0).reverse());
4342 for (const s5 of e4) i5.unshift(c(s5));
4343 } else void 0 !== s4 && i5.push(c(s4));
4344 return i5;
4345 }
4346 static _$Eu(t3, s4) {
4347 const i5 = s4.attribute;
4348 return false === i5 ? void 0 : "string" == typeof i5 ? i5 : "string" == typeof t3 ? t3.toLowerCase() : void 0;
4349 }
4350 constructor() {
4351 super(), this._$Ep = void 0, this.isUpdatePending = false, this.hasUpdated = false, this._$Em = null, this._$Ev();
4352 }
4353 _$Ev() {
4354 this._$ES = new Promise((t3) => this.enableUpdating = t3), this._$AL = /* @__PURE__ */ new Map(), this._$E_(), this.requestUpdate(), this.constructor.l?.forEach((t3) => t3(this));
4355 }
4356 addController(t3) {
4357 (this._$EO ??= /* @__PURE__ */ new Set()).add(t3), void 0 !== this.renderRoot && this.isConnected && t3.hostConnected?.();
4358 }
4359 removeController(t3) {
4360 this._$EO?.delete(t3);
4361 }
4362 _$E_() {
4363 const t3 = /* @__PURE__ */ new Map(), s4 = this.constructor.elementProperties;
4364 for (const i5 of s4.keys()) this.hasOwnProperty(i5) && (t3.set(i5, this[i5]), delete this[i5]);
4365 t3.size > 0 && (this._$Ep = t3);
4366 }
4367 createRenderRoot() {
4368 const t3 = this.shadowRoot ?? this.attachShadow(this.constructor.shadowRootOptions);
4369 return S(t3, this.constructor.elementStyles), t3;
4370 }
4371 connectedCallback() {
4372 this.renderRoot ??= this.createRenderRoot(), this.enableUpdating(true), this._$EO?.forEach((t3) => t3.hostConnected?.());
4373 }
4374 enableUpdating(t3) {
4375 }
4376 disconnectedCallback() {
4377 this._$EO?.forEach((t3) => t3.hostDisconnected?.());
4378 }
4379 attributeChangedCallback(t3, s4, i5) {
4380 this._$AK(t3, i5);
4381 }
4382 _$ET(t3, s4) {
4383 const i5 = this.constructor.elementProperties.get(t3), e4 = this.constructor._$Eu(t3, i5);
4384 if (void 0 !== e4 && true === i5.reflect) {
4385 const h3 = (void 0 !== i5.converter?.toAttribute ? i5.converter : u).toAttribute(s4, i5.type);
4386 this._$Em = t3, null == h3 ? this.removeAttribute(e4) : this.setAttribute(e4, h3), this._$Em = null;
4387 }
4388 }
4389 _$AK(t3, s4) {
4390 const i5 = this.constructor, e4 = i5._$Eh.get(t3);
4391 if (void 0 !== e4 && this._$Em !== e4) {
4392 const t4 = i5.getPropertyOptions(e4), h3 = "function" == typeof t4.converter ? { fromAttribute: t4.converter } : void 0 !== t4.converter?.fromAttribute ? t4.converter : u;
4393 this._$Em = e4;
4394 const r4 = h3.fromAttribute(s4, t4.type);
4395 this[e4] = r4 ?? this._$Ej?.get(e4) ?? r4, this._$Em = null;
4396 }
4397 }
4398 requestUpdate(t3, s4, i5) {
4399 if (void 0 !== t3) {
4400 const e4 = this.constructor, h3 = this[t3];
4401 if (i5 ??= e4.getPropertyOptions(t3), !((i5.hasChanged ?? f)(h3, s4) || i5.useDefault && i5.reflect && h3 === this._$Ej?.get(t3) && !this.hasAttribute(e4._$Eu(t3, i5)))) return;
4402 this.C(t3, s4, i5);
4403 }
4404 false === this.isUpdatePending && (this._$ES = this._$EP());
4405 }
4406 C(t3, s4, { useDefault: i5, reflect: e4, wrapped: h3 }, r4) {
4407 i5 && !(this._$Ej ??= /* @__PURE__ */ new Map()).has(t3) && (this._$Ej.set(t3, r4 ?? s4 ?? this[t3]), true !== h3 || void 0 !== r4) || (this._$AL.has(t3) || (this.hasUpdated || i5 || (s4 = void 0), this._$AL.set(t3, s4)), true === e4 && this._$Em !== t3 && (this._$Eq ??= /* @__PURE__ */ new Set()).add(t3));
4408 }
4409 async _$EP() {
4410 this.isUpdatePending = true;
4411 try {
4412 await this._$ES;
4413 } catch (t4) {
4414 Promise.reject(t4);
4415 }
4416 const t3 = this.scheduleUpdate();
4417 return null != t3 && await t3, !this.isUpdatePending;
4418 }
4419 scheduleUpdate() {
4420 return this.performUpdate();
4421 }
4422 performUpdate() {
4423 if (!this.isUpdatePending) return;
4424 if (!this.hasUpdated) {
4425 if (this.renderRoot ??= this.createRenderRoot(), this._$Ep) {
4426 for (const [t5, s5] of this._$Ep) this[t5] = s5;
4427 this._$Ep = void 0;
4428 }
4429 const t4 = this.constructor.elementProperties;
4430 if (t4.size > 0) for (const [s5, i5] of t4) {
4431 const { wrapped: t5 } = i5, e4 = this[s5];
4432 true !== t5 || this._$AL.has(s5) || void 0 === e4 || this.C(s5, void 0, i5, e4);
4433 }
4434 }
4435 let t3 = false;
4436 const s4 = this._$AL;
4437 try {
4438 t3 = this.shouldUpdate(s4), t3 ? (this.willUpdate(s4), this._$EO?.forEach((t4) => t4.hostUpdate?.()), this.update(s4)) : this._$EM();
4439 } catch (s5) {
4440 throw t3 = false, this._$EM(), s5;
4441 }
4442 t3 && this._$AE(s4);
4443 }
4444 willUpdate(t3) {
4445 }
4446 _$AE(t3) {
4447 this._$EO?.forEach((t4) => t4.hostUpdated?.()), this.hasUpdated || (this.hasUpdated = true, this.firstUpdated(t3)), this.updated(t3);
4448 }
4449 _$EM() {
4450 this._$AL = /* @__PURE__ */ new Map(), this.isUpdatePending = false;
4451 }
4452 get updateComplete() {
4453 return this.getUpdateComplete();
4454 }
4455 getUpdateComplete() {
4456 return this._$ES;
4457 }
4458 shouldUpdate(t3) {
4459 return true;
4460 }
4461 update(t3) {
4462 this._$Eq &&= this._$Eq.forEach((t4) => this._$ET(t4, this[t4])), this._$EM();
4463 }
4464 updated(t3) {
4465 }
4466 firstUpdated(t3) {
4467 }
4468 };
4469 y.elementStyles = [], y.shadowRootOptions = { mode: "open" }, y[d("elementProperties")] = /* @__PURE__ */ new Map(), y[d("finalized")] = /* @__PURE__ */ new Map(), p?.({ ReactiveElement: y }), (a.reactiveElementVersions ??= []).push("2.1.1");
4470
4471 // node_modules/lit-html/lit-html.js
4472 var t2 = globalThis;
4473 var i3 = t2.trustedTypes;
4474 var s2 = i3 ? i3.createPolicy("lit-html", { createHTML: (t3) => t3 }) : void 0;
4475 var e3 = "$lit$";
4476 var h2 = `lit$${Math.random().toFixed(9).slice(2)}$`;
4477 var o3 = "?" + h2;
4478 var n3 = `<${o3}>`;
4479 var r3 = document;
4480 var l2 = () => r3.createComment("");
4481 var c3 = (t3) => null === t3 || "object" != typeof t3 && "function" != typeof t3;
4482 var a2 = Array.isArray;
4483 var u2 = (t3) => a2(t3) || "function" == typeof t3?.[Symbol.iterator];
4484 var d2 = "[ \n\f\r]";
4485 var f2 = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g;
4486 var v = /-->/g;
4487 var _ = />/g;
4488 var m = RegExp(`>|${d2}(?:([^\\s"'>=/]+)(${d2}*=${d2}*(?:[^
4489 \f\r"'\`<>=]|("|')|))|$)`, "g");
4490 var p2 = /'/g;
4491 var g = /"/g;
4492 var $34 = /^(?:script|style|textarea|title)$/i;
4493 var y2 = (t3) => (i5, ...s4) => ({ _$litType$: t3, strings: i5, values: s4 });
4494 var x = y2(1);
4495 var b2 = y2(2);
4496 var w = y2(3);
4497 var T = Symbol.for("lit-noChange");
4498 var E = Symbol.for("lit-nothing");
4499 var A = /* @__PURE__ */ new WeakMap();
4500 var C = r3.createTreeWalker(r3, 129);
4501 function P(t3, i5) {
4502 if (!a2(t3) || !t3.hasOwnProperty("raw")) throw Error("invalid template strings array");
4503 return void 0 !== s2 ? s2.createHTML(i5) : i5;
4504 }
4505 var V = (t3, i5) => {
4506 const s4 = t3.length - 1, o5 = [];
4507 let r4, l3 = 2 === i5 ? "<svg>" : 3 === i5 ? "<math>" : "", c4 = f2;
4508 for (let i6 = 0; i6 < s4; i6++) {
4509 const s5 = t3[i6];
4510 let a3, u3, d3 = -1, y3 = 0;
4511 for (; y3 < s5.length && (c4.lastIndex = y3, u3 = c4.exec(s5), null !== u3); ) y3 = c4.lastIndex, c4 === f2 ? "!--" === u3[1] ? c4 = v : void 0 !== u3[1] ? c4 = _ : void 0 !== u3[2] ? ($34.test(u3[2]) && (r4 = RegExp("</" + u3[2], "g")), c4 = m) : void 0 !== u3[3] && (c4 = m) : c4 === m ? ">" === u3[0] ? (c4 = r4 ?? f2, d3 = -1) : void 0 === u3[1] ? d3 = -2 : (d3 = c4.lastIndex - u3[2].length, a3 = u3[1], c4 = void 0 === u3[3] ? m : '"' === u3[3] ? g : p2) : c4 === g || c4 === p2 ? c4 = m : c4 === v || c4 === _ ? c4 = f2 : (c4 = m, r4 = void 0);
4512 const x2 = c4 === m && t3[i6 + 1].startsWith("/>") ? " " : "";
4513 l3 += c4 === f2 ? s5 + n3 : d3 >= 0 ? (o5.push(a3), s5.slice(0, d3) + e3 + s5.slice(d3) + h2 + x2) : s5 + h2 + (-2 === d3 ? i6 : x2);
4514 }
4515 return [P(t3, l3 + (t3[s4] || "<?>") + (2 === i5 ? "</svg>" : 3 === i5 ? "</math>" : "")), o5];
4516 };
4517 var N = class _N {
4518 constructor({ strings: t3, _$litType$: s4 }, n4) {
4519 let r4;
4520 this.parts = [];
4521 let c4 = 0, a3 = 0;
4522 const u3 = t3.length - 1, d3 = this.parts, [f3, v2] = V(t3, s4);
4523 if (this.el = _N.createElement(f3, n4), C.currentNode = this.el.content, 2 === s4 || 3 === s4) {
4524 const t4 = this.el.content.firstChild;
4525 t4.replaceWith(...t4.childNodes);
4526 }
4527 for (; null !== (r4 = C.nextNode()) && d3.length < u3; ) {
4528 if (1 === r4.nodeType) {
4529 if (r4.hasAttributes()) for (const t4 of r4.getAttributeNames()) if (t4.endsWith(e3)) {
4530 const i5 = v2[a3++], s5 = r4.getAttribute(t4).split(h2), e4 = /([.?@])?(.*)/.exec(i5);
4531 d3.push({ type: 1, index: c4, name: e4[2], strings: s5, ctor: "." === e4[1] ? H : "?" === e4[1] ? I : "@" === e4[1] ? L : k }), r4.removeAttribute(t4);
4532 } else t4.startsWith(h2) && (d3.push({ type: 6, index: c4 }), r4.removeAttribute(t4));
4533 if ($34.test(r4.tagName)) {
4534 const t4 = r4.textContent.split(h2), s5 = t4.length - 1;
4535 if (s5 > 0) {
4536 r4.textContent = i3 ? i3.emptyScript : "";
4537 for (let i5 = 0; i5 < s5; i5++) r4.append(t4[i5], l2()), C.nextNode(), d3.push({ type: 2, index: ++c4 });
4538 r4.append(t4[s5], l2());
4539 }
4540 }
4541 } else if (8 === r4.nodeType) if (r4.data === o3) d3.push({ type: 2, index: c4 });
4542 else {
4543 let t4 = -1;
4544 for (; -1 !== (t4 = r4.data.indexOf(h2, t4 + 1)); ) d3.push({ type: 7, index: c4 }), t4 += h2.length - 1;
4545 }
4546 c4++;
4547 }
4548 }
4549 static createElement(t3, i5) {
4550 const s4 = r3.createElement("template");
4551 return s4.innerHTML = t3, s4;
4552 }
4553 };
4554 function S2(t3, i5, s4 = t3, e4) {
4555 if (i5 === T) return i5;
4556 let h3 = void 0 !== e4 ? s4._$Co?.[e4] : s4._$Cl;
4557 const o5 = c3(i5) ? void 0 : i5._$litDirective$;
4558 return h3?.constructor !== o5 && (h3?._$AO?.(false), void 0 === o5 ? h3 = void 0 : (h3 = new o5(t3), h3._$AT(t3, s4, e4)), void 0 !== e4 ? (s4._$Co ??= [])[e4] = h3 : s4._$Cl = h3), void 0 !== h3 && (i5 = S2(t3, h3._$AS(t3, i5.values), h3, e4)), i5;
4559 }
4560 var M = class {
4561 constructor(t3, i5) {
4562 this._$AV = [], this._$AN = void 0, this._$AD = t3, this._$AM = i5;
4563 }
4564 get parentNode() {
4565 return this._$AM.parentNode;
4566 }
4567 get _$AU() {
4568 return this._$AM._$AU;
4569 }
4570 u(t3) {
4571 const { el: { content: i5 }, parts: s4 } = this._$AD, e4 = (t3?.creationScope ?? r3).importNode(i5, true);
4572 C.currentNode = e4;
4573 let h3 = C.nextNode(), o5 = 0, n4 = 0, l3 = s4[0];
4574 for (; void 0 !== l3; ) {
4575 if (o5 === l3.index) {
4576 let i6;
4577 2 === l3.type ? i6 = new R(h3, h3.nextSibling, this, t3) : 1 === l3.type ? i6 = new l3.ctor(h3, l3.name, l3.strings, this, t3) : 6 === l3.type && (i6 = new z(h3, this, t3)), this._$AV.push(i6), l3 = s4[++n4];
4578 }
4579 o5 !== l3?.index && (h3 = C.nextNode(), o5++);
4580 }
4581 return C.currentNode = r3, e4;
4582 }
4583 p(t3) {
4584 let i5 = 0;
4585 for (const s4 of this._$AV) void 0 !== s4 && (void 0 !== s4.strings ? (s4._$AI(t3, s4, i5), i5 += s4.strings.length - 2) : s4._$AI(t3[i5])), i5++;
4586 }
4587 };
4588 var R = class _R {
4589 get _$AU() {
4590 return this._$AM?._$AU ?? this._$Cv;
4591 }
4592 constructor(t3, i5, s4, e4) {
4593 this.type = 2, this._$AH = E, this._$AN = void 0, this._$AA = t3, this._$AB = i5, this._$AM = s4, this.options = e4, this._$Cv = e4?.isConnected ?? true;
4594 }
4595 get parentNode() {
4596 let t3 = this._$AA.parentNode;
4597 const i5 = this._$AM;
4598 return void 0 !== i5 && 11 === t3?.nodeType && (t3 = i5.parentNode), t3;
4599 }
4600 get startNode() {
4601 return this._$AA;
4602 }
4603 get endNode() {
4604 return this._$AB;
4605 }
4606 _$AI(t3, i5 = this) {
4607 t3 = S2(this, t3, i5), c3(t3) ? t3 === E || null == t3 || "" === t3 ? (this._$AH !== E && this._$AR(), this._$AH = E) : t3 !== this._$AH && t3 !== T && this._(t3) : void 0 !== t3._$litType$ ? this.$(t3) : void 0 !== t3.nodeType ? this.T(t3) : u2(t3) ? this.k(t3) : this._(t3);
4608 }
4609 O(t3) {
4610 return this._$AA.parentNode.insertBefore(t3, this._$AB);
4611 }
4612 T(t3) {
4613 this._$AH !== t3 && (this._$AR(), this._$AH = this.O(t3));
4614 }
4615 _(t3) {
4616 this._$AH !== E && c3(this._$AH) ? this._$AA.nextSibling.data = t3 : this.T(r3.createTextNode(t3)), this._$AH = t3;
4617 }
4618 $(t3) {
4619 const { values: i5, _$litType$: s4 } = t3, e4 = "number" == typeof s4 ? this._$AC(t3) : (void 0 === s4.el && (s4.el = N.createElement(P(s4.h, s4.h[0]), this.options)), s4);
4620 if (this._$AH?._$AD === e4) this._$AH.p(i5);
4621 else {
4622 const t4 = new M(e4, this), s5 = t4.u(this.options);
4623 t4.p(i5), this.T(s5), this._$AH = t4;
4624 }
4625 }
4626 _$AC(t3) {
4627 let i5 = A.get(t3.strings);
4628 return void 0 === i5 && A.set(t3.strings, i5 = new N(t3)), i5;
4629 }
4630 k(t3) {
4631 a2(this._$AH) || (this._$AH = [], this._$AR());
4632 const i5 = this._$AH;
4633 let s4, e4 = 0;
4634 for (const h3 of t3) e4 === i5.length ? i5.push(s4 = new _R(this.O(l2()), this.O(l2()), this, this.options)) : s4 = i5[e4], s4._$AI(h3), e4++;
4635 e4 < i5.length && (this._$AR(s4 && s4._$AB.nextSibling, e4), i5.length = e4);
4636 }
4637 _$AR(t3 = this._$AA.nextSibling, i5) {
4638 for (this._$AP?.(false, true, i5); t3 !== this._$AB; ) {
4639 const i6 = t3.nextSibling;
4640 t3.remove(), t3 = i6;
4641 }
4642 }
4643 setConnected(t3) {
4644 void 0 === this._$AM && (this._$Cv = t3, this._$AP?.(t3));
4645 }
4646 };
4647 var k = class {
4648 get tagName() {
4649 return this.element.tagName;
4650 }
4651 get _$AU() {
4652 return this._$AM._$AU;
4653 }
4654 constructor(t3, i5, s4, e4, h3) {
4655 this.type = 1, this._$AH = E, this._$AN = void 0, this.element = t3, this.name = i5, this._$AM = e4, this.options = h3, s4.length > 2 || "" !== s4[0] || "" !== s4[1] ? (this._$AH = Array(s4.length - 1).fill(new String()), this.strings = s4) : this._$AH = E;
4656 }
4657 _$AI(t3, i5 = this, s4, e4) {
4658 const h3 = this.strings;
4659 let o5 = false;
4660 if (void 0 === h3) t3 = S2(this, t3, i5, 0), o5 = !c3(t3) || t3 !== this._$AH && t3 !== T, o5 && (this._$AH = t3);
4661 else {
4662 const e5 = t3;
4663 let n4, r4;
4664 for (t3 = h3[0], n4 = 0; n4 < h3.length - 1; n4++) r4 = S2(this, e5[s4 + n4], i5, n4), r4 === T && (r4 = this._$AH[n4]), o5 ||= !c3(r4) || r4 !== this._$AH[n4], r4 === E ? t3 = E : t3 !== E && (t3 += (r4 ?? "") + h3[n4 + 1]), this._$AH[n4] = r4;
4665 }
4666 o5 && !e4 && this.j(t3);
4667 }
4668 j(t3) {
4669 t3 === E ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, t3 ?? "");
4670 }
4671 };
4672 var H = class extends k {
4673 constructor() {
4674 super(...arguments), this.type = 3;
4675 }
4676 j(t3) {
4677 this.element[this.name] = t3 === E ? void 0 : t3;
4678 }
4679 };
4680 var I = class extends k {
4681 constructor() {
4682 super(...arguments), this.type = 4;
4683 }
4684 j(t3) {
4685 this.element.toggleAttribute(this.name, !!t3 && t3 !== E);
4686 }
4687 };
4688 var L = class extends k {
4689 constructor(t3, i5, s4, e4, h3) {
4690 super(t3, i5, s4, e4, h3), this.type = 5;
4691 }
4692 _$AI(t3, i5 = this) {
4693 if ((t3 = S2(this, t3, i5, 0) ?? E) === T) return;
4694 const s4 = this._$AH, e4 = t3 === E && s4 !== E || t3.capture !== s4.capture || t3.once !== s4.once || t3.passive !== s4.passive, h3 = t3 !== E && (s4 === E || e4);
4695 e4 && this.element.removeEventListener(this.name, this, s4), h3 && this.element.addEventListener(this.name, this, t3), this._$AH = t3;
4696 }
4697 handleEvent(t3) {
4698 "function" == typeof this._$AH ? this._$AH.call(this.options?.host ?? this.element, t3) : this._$AH.handleEvent(t3);
4699 }
4700 };
4701 var z = class {
4702 constructor(t3, i5, s4) {
4703 this.element = t3, this.type = 6, this._$AN = void 0, this._$AM = i5, this.options = s4;
4704 }
4705 get _$AU() {
4706 return this._$AM._$AU;
4707 }
4708 _$AI(t3) {
4709 S2(this, t3);
4710 }
4711 };
4712 var j = t2.litHtmlPolyfillSupport;
4713 j?.(N, R), (t2.litHtmlVersions ??= []).push("3.3.1");
4714 var B = (t3, i5, s4) => {
4715 const e4 = s4?.renderBefore ?? i5;
4716 let h3 = e4._$litPart$;
4717 if (void 0 === h3) {
4718 const t4 = s4?.renderBefore ?? null;
4719 e4._$litPart$ = h3 = new R(i5.insertBefore(l2(), t4), t4, void 0, s4 ?? {});
4720 }
4721 return h3._$AI(t3), h3;
4722 };
4723
4724 // node_modules/lit-element/lit-element.js
4725 var s3 = globalThis;
4726 var i4 = class extends y {
4727 constructor() {
4728 super(...arguments), this.renderOptions = { host: this }, this._$Do = void 0;
4729 }
4730 createRenderRoot() {
4731 const t3 = super.createRenderRoot();
4732 return this.renderOptions.renderBefore ??= t3.firstChild, t3;
4733 }
4734 update(t3) {
4735 const r4 = this.render();
4736 this.hasUpdated || (this.renderOptions.isConnected = this.isConnected), super.update(t3), this._$Do = B(r4, this.renderRoot, this.renderOptions);
4737 }
4738 connectedCallback() {
4739 super.connectedCallback(), this._$Do?.setConnected(true);
4740 }
4741 disconnectedCallback() {
4742 super.disconnectedCallback(), this._$Do?.setConnected(false);
4743 }
4744 render() {
4745 return T;
4746 }
4747 };
4748 i4._$litElement$ = true, i4["finalized"] = true, s3.litElementHydrateSupport?.({ LitElement: i4 });
4749 var o4 = s3.litElementPolyfillSupport;
4750 o4?.({ LitElement: i4 });
4751 (s3.litElementVersions ??= []).push("4.2.1");
4752
4753 // srcts/src/shiny/error.ts
4754 var ShinyClientError = class extends Error {
4755 constructor({ headline, message }) {
4756 super(message);
4757 this.name = "ShinyClientError";
4758 this.headline = headline;
4759 }
4760 };
4761
4762 // srcts/src/components/errorConsole.ts
4763 var buttonStyles = i`
4764 button {
4765 background-color: transparent;
4766 outline: none;
4767 border-style: none;
4768 padding: var(--space-3);
4769 border-radius: var(--space-1);
4770 font-size: var(--font-lg);
4771 background-color: inherit;
4772 display: block;
4773 }
4774
4775 button > svg {
4776 display: block;
4777 }
4778 `;
4779 var _ShinyErrorConsole = class _ShinyErrorConsole extends i4 {
4780 toggleCollapsed() {
4781 this.classList.toggle("collapsed");
4782 this.querySelector(".toggle-button")?.blur();
4783 }
4784 handleDismissAll() {
4785 this.classList.add("leaving");
4786 this.addEventListener("animationend", () => {
4787 this.remove();
4788 });
4789 }
4790 static createClientMessageElement({ headline, message }) {
4791 const msg = document.createElement("shiny-error-message");
4792 msg.setAttribute("headline", headline || "");
4793 msg.setAttribute("message", message);
4794 return msg;
4795 }
4796 appendConsoleMessage({ headline, message }) {
4797 const content = this.shadowRoot?.querySelector("slot.content");
4798 if (content) {
4799 const nodeKey = (node) => {
4800 const headline2 = node.getAttribute("headline") || "";
4801 const message2 = node.getAttribute("message") || "";
4802 return `${headline2}::${message2}`;
4803 };
4804 const newKey = `${headline}::${message}`;
4805 for (const node of content.assignedElements()) {
4806 if (node.tagName.toLowerCase() === "shiny-error-message") {
4807 if (nodeKey(node) === newKey) {
4808 return;
4809 }
4810 }
4811 }
4812 }
4813 this.appendChild(
4814 _ShinyErrorConsole.createClientMessageElement({ headline, message })
4815 );
4816 return;
4817 }
4818 render() {
4819 return x` <div class="header">
4820 <span class="title"> Shiny Client Errors </span>
4821 <button
4822 class="close-button"
4823 @click=${this.handleDismissAll}
4824 title="Dismiss all console messages and close console"
4825 >
4826 <svg
4827 xmlns="http://www.w3.org/2000/svg"
4828 fill="none"
4829 viewBox="0 0 24 24"
4830 stroke-width="1.5"
4831 height="1em"
4832 width="1em"
4833 stroke="currentColor"
4834 class="close-icon"
4835 >
4836 <path
4837 stroke-linecap="round"
4838 stroke-linejoin="round"
4839 d="M6 18L18 6M6 6l12 12"
4840 />
4841 </svg>
4842 Dismiss all
4843 </button>
4844 <button class="toggle-button" @click=${this.toggleCollapsed}>
4845 <svg
4846 xmlns="http://www.w3.org/2000/svg"
4847 fill="none"
4848 viewBox="0 0 24 24"
4849 stroke-width="1.5"
4850 height="1em"
4851 width="1em"
4852 stroke="currentColor"
4853 class="toggle-icon"
4854 >
4855 <path
4856 class="collapse"
4857 stroke-linecap="round"
4858 stroke-linejoin="round"
4859 d="M4.5 19.5l15-15m0 0H8.25m11.25 0v11.25"
4860 />
4861 </svg>
4862 </button>
4863 </div>
4864 <slot class="content"></slot>`;
4865 }
4866 };
4867 _ShinyErrorConsole.styles = [
4868 i`
4869 :host {
4870 /* We declare hard pixel values here to avoid body font size changes
4871 messing up the size of the console. This was an issue with bslib setting
4872 the body font-size at 16px relative to base shiny's 14px. */
4873 --font-md: 14px;
4874 --font-lg: 16px;
4875 --font-xl: 18px;
4876
4877 /* These are all taken from open-props */
4878 --space-1: 6px;
4879 --space-2: calc(var(--space-1) * 2);
4880 --space-3: calc(var(--space-1) * 3);
4881 --space-4: calc(var(--space-1) * 4);
4882 --space-8: calc(var(--space-1) * 8);
4883
4884 --red-2: #ffc9c9;
4885 --red-6: #fa5252;
4886 --red-7: #f03e3e;
4887 --red-8: #e03131;
4888 --red-10: #b02525;
4889 --red-11: #962020;
4890 --red-12: #7d1a1a;
4891
4892 --gray-1: #f8f9fa;
4893 --gray-2: #e9ecef;
4894 --gray-3: #dee2e6;
4895 --gray-4: #ced4da;
4896 --gray-6: #868e96;
4897 --gray-8: #6c757d;
4898
4899 --green-8: #51cf66;
4900
4901 --shadow-color: 220 3% 15%;
4902 --shadow-strength: 1%;
4903 --shadow-3:
4904 0 -1px 3px 0
4905 hsl(var(--shadow-color) / calc(var(--shadow-strength) + 2%)),
4906 0 1px 2px -5px
4907 hsl(var(--shadow-color) / calc(var(--shadow-strength) + 2%)),
4908 0 2px 5px -5px
4909 hsl(var(--shadow-color) / calc(var(--shadow-strength) + 4%)),
4910 0 4px 12px -5px
4911 hsl(var(--shadow-color) / calc(var(--shadow-strength) + 5%)),
4912 0 12px 15px -5px
4913 hsl(var(--shadow-color) / calc(var(--shadow-strength) + 7%));
4914
4915 --ring-shadow: 0 0 0 1px var(--gray-2);
4916
4917 /* How fast should the message pop in and out of the screen? */
4918 --animation-speed: 500ms;
4919
4920 /* Taken from open-props */
4921 --ease-3: cubic-bezier(0.25, 0, 0.3, 1);
4922 --animation-slide-in-left: slide-in-left var(--animation-speed)
4923 var(--ease-3);
4924
4925 --animation-slide-out-left: slide-out-left var(--animation-speed)
4926 var(--ease-3);
4927 --modal-bg-color: white;
4928
4929 position: fixed;
4930 top: var(--space-1);
4931 right: var(--space-1);
4932 z-index: 1000;
4933
4934 display: flex;
4935 flex-direction: column;
4936
4937 background-color: var(--modal-bg-color);
4938 border-radius: var(--space-1);
4939
4940 animation: var(--animation-slide-in-left);
4941 box-shadow: var(--shadow-3), var(--ring-shadow);
4942
4943 /* Dont let the error console burst out of the viewport */
4944 max-height: calc(100vh - 2 * var(--space-1));
4945 }
4946
4947 @keyframes slide-in-left {
4948 from {
4949 transform: translateX(100%);
4950 }
4951 }
4952 @keyframes slide-out-left {
4953 to {
4954 transform: translateX(100%);
4955 }
4956 }
4957
4958 :host(.leaving) {
4959 animation: var(--animation-slide-out-left);
4960 }
4961
4962 .header {
4963 display: flex;
4964 justify-content: flex-end;
4965 align-items: flex-start;
4966 gap: var(--space-2);
4967 }
4968
4969 .title {
4970 font-size: var(--font-xl);
4971 margin-right: auto;
4972 padding: var(--space-3);
4973 line-height: 1;
4974 font-weight: 600;
4975 color: var(--red-12);
4976 }
4977
4978 ${buttonStyles}
4979
4980 button:hover {
4981 background-color: var(--gray-2);
4982 }
4983
4984 .toggle-button {
4985 width: fit-content;
4986 border: none;
4987 aspect-ratio: 1;
4988 border-color: var(--gray-4);
4989 }
4990
4991 .close-button {
4992 display: flex;
4993 align-items: center;
4994 color: var(--red-11);
4995 }
4996
4997 .close-button > svg {
4998 margin-right: 3px;
4999 }
5000
5001 .toggle-button:focus {
5002 outline: 1px solid black;
5003 }
5004
5005 .toggle-icon {
5006 transition: transform var(--animation-speed) ease-in-out;
5007 }
5008
5009 :host(.collapsed) .toggle-icon {
5010 transform: scaleX(-1) scaleY(-1);
5011 }
5012
5013 :host(.collapsed) .close-button {
5014 display: none;
5015 }
5016
5017 .content {
5018 display: block;
5019 padding-inline: var(--space-4);
5020 padding-block-start: 0;
5021 padding-block-end: var(--space-4);
5022 max-height: 100%;
5023 overflow: auto;
5024 }
5025
5026 :host(.collapsed) .content {
5027 display: none;
5028 }
5029 `
5030 ];
5031 var ShinyErrorConsole = _ShinyErrorConsole;
5032 customElements.define("shiny-error-console", ShinyErrorConsole);
5033 var ShinyErrorMessage = class extends i4 {
5034 constructor() {
5035 super(...arguments);
5036 this.headline = "";
5037 this.message = "";
5038 }
5039 async copyErrorToClipboard() {
5040 await navigator.clipboard.writeText(this.message);
5041 this.classList.add("copy-success");
5042 setTimeout(() => {
5043 this.classList.remove("copy-success");
5044 }, 1e3);
5045 }
5046 // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
5047 render() {
5048 return x`
5049 <div class="container">
5050 <div class="decoration-container">
5051 <div class="vertical-line"></div>
5052 <div class="dot"></div>
5053 </div>
5054 <div class="contents">
5055 <h3>${this.headline}</h3>
5056 <pre class="error-message">${this.message}</pre>
5057 </div>
5058
5059 <div class="actions">
5060 <button
5061 class="copy-button"
5062 @click=${this.copyErrorToClipboard}
5063 title="Copy error to clipboard"
5064 >
5065 <div class="copy-button-inner">
5066 <svg
5067 class="front"
5068 xmlns="http://www.w3.org/2000/svg"
5069 fill="none"
5070 viewBox="0 0 24 24"
5071 stroke-width="1.5"
5072 stroke="currentColor"
5073 height="1em"
5074 width="1em"
5075 >
5076 <path
5077 stroke-linecap="round"
5078 stroke-linejoin="round"
5079 d="M15.666 3.888A2.25 2.25 0 0013.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 01-.75.75H9a.75.75 0 01-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 01-2.25 2.25H6.75A2.25 2.25 0 014.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 011.927-.184"
5080 />
5081 </svg>
5082
5083 <svg
5084 class="back"
5085 xmlns="http://www.w3.org/2000/svg"
5086 fill="none"
5087 viewBox="0 0 24 24"
5088 stroke-width="1.5"
5089 stroke="currentColor"
5090 height="1em"
5091 width="1em"
5092 >
5093 <path
5094 stroke-linecap="round"
5095 stroke-linejoin="round"
5096 d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
5097 />
5098 </svg>
5099 </div>
5100 </button>
5101 </div>
5102 </div>
5103 `;
5104 }
5105 };
5106 ShinyErrorMessage.properties = {
5107 headline: {},
5108 message: {}
5109 };
5110 ShinyErrorMessage.styles = [
5111 i`
5112 :host {
5113 color: var(--red-11);
5114 display: block;
5115 font-size: var(--font-md);
5116
5117 position: relative;
5118 --icon-size: var(--font-lg) /* Reset box sizing */
5119 box-sizing: border-box;
5120 }
5121
5122 .container {
5123 display: flex;
5124 gap: var(--space-2);
5125 }
5126
5127 .contents {
5128 width: 40ch;
5129 display: flex;
5130 flex-direction: column;
5131 gap: var(--space-1);
5132 padding-block-start: 0;
5133 padding-block-end: var(--space-3);
5134 overflow: auto;
5135 }
5136
5137 :host(:last-of-type) .contents {
5138 padding-block-end: var(--space-1);
5139 }
5140
5141 .contents > h3 {
5142 font-size: 1em;
5143 font-weight: 500;
5144 color: var(--red-12);
5145 }
5146
5147 .contents > * {
5148 margin-block: 0;
5149 }
5150
5151 .error-message {
5152 font-family: "Courier New", Courier, monospace;
5153 white-space: pre-wrap;
5154 }
5155
5156 .decoration-container {
5157 flex-shrink: 0;
5158 position: relative;
5159
5160 --line-w: 2px;
5161 --dot-size: 11px;
5162 }
5163
5164 :host(:hover) .decoration-container {
5165 --scale: 1.25;
5166 }
5167
5168 .vertical-line {
5169 margin-inline: auto;
5170 width: var(--line-w);
5171 height: 100%;
5172
5173 background-color: var(--red-10);
5174 }
5175
5176 :host(:first-of-type) .vertical-line {
5177 height: calc(100% - var(--dot-size));
5178 margin-top: var(--dot-size);
5179 }
5180
5181 .dot {
5182 position: absolute;
5183 width: var(--dot-size);
5184 height: var(--dot-size);
5185 top: calc(-1px + var(--dot-size) / 2);
5186 left: calc(50% - var(--dot-size) / 2);
5187 border-radius: 100%;
5188 transform: scale(var(--scale, 1));
5189
5190 color: var(--red-6);
5191 background-color: var(--red-10);
5192 }
5193
5194 .actions {
5195 transform: scaleX(0);
5196 transition: transform calc(var(--animation-speed) / 2) ease-in-out;
5197 display: flex;
5198 justify-content: center;
5199 flex-direction: column;
5200 }
5201
5202 /* Delay transition on mouseout so the buttons don't jump away if the user
5203 overshoots them with their mouse */
5204 :host(:not(:hover)) .actions {
5205 transition-delay: 0.15s;
5206 }
5207
5208 :host(:hover) .actions {
5209 transform: scaleX(1);
5210 }
5211
5212 ${buttonStyles}
5213
5214 .copy-button {
5215 padding: 0;
5216 width: var(--space-8);
5217 height: var(--space-8);
5218 position: relative;
5219 --pad: var(--space-2);
5220 }
5221
5222 .copy-button-inner {
5223 position: relative;
5224 width: 100%;
5225 height: 100%;
5226 border-radius: inherit;
5227 transition: transform 0.5s;
5228 transform-style: preserve-3d;
5229 }
5230
5231 /* Animate flipping to the other side when the .copy-success class is
5232 added to the host */
5233 :host(.copy-success) .copy-button-inner {
5234 transform: rotateY(180deg);
5235 }
5236
5237 /* Position the front and back side */
5238 .copy-button .front,
5239 .copy-button .back {
5240 --side: calc(100% - 2 * var(--pad));
5241 position: absolute;
5242 inset: var(--pad);
5243 height: var(--side);
5244 width: var(--side);
5245 -webkit-backface-visibility: hidden; /* Safari */
5246 backface-visibility: hidden;
5247 }
5248
5249 .copy-button:hover .copy-button-inner {
5250 background-color: var(--gray-2);
5251 }
5252
5253 /* Style the back side */
5254 .copy-button .back {
5255 --pad: var(--space-1);
5256 color: var(--green-8);
5257 transform: rotateY(180deg);
5258 }
5259 `
5260 ];
5261 customElements.define("shiny-error-message", ShinyErrorMessage);
5262 function showShinyClientMessage({
5263 headline = "",
5264 message,
5265 status = "warning"
5266 }) {
5267 const consoleMessage = `[shiny] ${headline}${headline ? " - " : ""}${message}`;
5268 switch (status) {
5269 case "error":
5270 console.error(consoleMessage);
5271 break;
5272 case "warning":
5273 console.warn(consoleMessage);
5274 break;
5275 default:
5276 console.log(consoleMessage);
5277 break;
5278 }
5279 if (!isShinyInDevMode()) {
5280 return;
5281 }
5282 let sec = document.querySelector("shiny-error-console");
5283 if (!sec) {
5284 sec = document.createElement("shiny-error-console");
5285 document.body.appendChild(sec);
5286 }
5287 sec.appendConsoleMessage({ headline, message });
5288 }
5289 function showErrorInClientConsole(e4) {
5290 let errorMsg = null;
5291 let headline = "Error on client while running Shiny app";
5292 if (typeof e4 === "string") {
5293 errorMsg = e4;
5294 } else if (e4 instanceof ShinyClientError) {
5295 errorMsg = e4.message;
5296 headline = e4.headline;
5297 } else if (e4 instanceof Error) {
5298 errorMsg = e4.message;
5299 } else {
5300 errorMsg = "Unknown error";
5301 }
5302 showShinyClientMessage({ headline, message: errorMsg, status: "error" });
5303 }
5304 var ShinyClientMessageEvent = class extends CustomEvent {
5305 constructor(detail) {
5306 super("shiny:client-message", { detail, bubbles: true, cancelable: true });
5307 }
5308 };
5309 window.addEventListener("shiny:client-message", (ev) => {
5310 if (!(ev instanceof CustomEvent)) {
5311 throw new Error("[shiny] shiny:client-message expected a CustomEvent");
5312 }
5313 const { headline, message, status } = ev.detail;
5314 if (!message) {
5315 throw new Error(
5316 "[shiny] shiny:client-message expected a `message` property in `event.detail`."
5317 );
5318 }
5319 showShinyClientMessage({ headline, message, status });
5320 });
5321
5322 // srcts/src/imageutils/resetBrush.ts
5323 function resetBrush(brushId) {
5324 shinySetInputValue(brushId, null);
5325 imageOutputBinding.find(document.documentElement).trigger("shiny-internal:brushed", {
5326 brushId,
5327 outputId: null
5328 });
5329 }
5330
5331 // srcts/src/inputPolicies/inputBatchSender.ts
5332 var InputBatchSender = class {
5333 constructor(shinyapp) {
5334 this.pendingData = {};
5335 this.reentrant = false;
5336 this.sendIsEnqueued = false;
5337 this.lastChanceCallback = [];
5338 this.shinyapp = shinyapp;
5339 }
5340 setInput(nameType, value, opts) {
5341 this.pendingData[nameType] = value;
5342 if (!this.reentrant) {
5343 if (opts.priority === "event") {
5344 this._sendNow();
5345 } else if (!this.sendIsEnqueued) {
5346 this.shinyapp.taskQueue.enqueue(() => {
5347 this.sendIsEnqueued = false;
5348 this._sendNow();
5349 });
5350 }
5351 }
5352 }
5353 _sendNow() {
5354 if (this.reentrant) {
5355 console.trace("Unexpected reentrancy in InputBatchSender!");
5356 }
5357 this.reentrant = true;
5358 try {
5359 this.lastChanceCallback.forEach((callback) => callback());
5360 const currentData = this.pendingData;
5361 this.pendingData = {};
5362 this.shinyapp.sendInput(currentData);
5363 } finally {
5364 this.reentrant = false;
5365 }
5366 }
5367 };
5368
5369 // srcts/src/inputPolicies/inputDeferDecorator.ts
5370 var InputDeferDecorator = class {
5371 constructor(target) {
5372 this.pendingInput = {};
5373 this.target = target;
5374 }
5375 setInput(nameType, value, opts) {
5376 if (/^\./.test(nameType)) this.target.setInput(nameType, value, opts);
5377 else this.pendingInput[nameType] = { value, opts };
5378 }
5379 submit() {
5380 for (const nameType in this.pendingInput) {
5381 if (hasDefinedProperty(this.pendingInput, nameType)) {
5382 const { value, opts } = this.pendingInput[nameType];
5383 this.target.setInput(nameType, value, opts);
5384 }
5385 }
5386 }
5387 };
5388
5389 // srcts/src/inputPolicies/inputEventDecorator.ts
5390 var import_jquery34 = __toESM(require_jquery());
5391
5392 // srcts/src/inputPolicies/splitInputNameType.ts
5393 function splitInputNameType(nameType) {
5394 const name2 = nameType.split(":");
5395 return {
5396 name: name2[0],
5397 inputType: name2.length > 1 ? name2[1] : ""
5398 };
5399 }
5400
5401 // srcts/src/inputPolicies/inputEventDecorator.ts
5402 var InputEventDecorator = class {
5403 constructor(target) {
5404 this.target = target;
5405 }
5406 setInput(nameType, value, opts) {
5407 const evt = import_jquery34.default.Event("shiny:inputchanged");
5408 const input = splitInputNameType(nameType);
5409 evt.name = input.name;
5410 evt.inputType = input.inputType;
5411 evt.value = value;
5412 evt.binding = opts.binding || null;
5413 evt.el = opts.el || null;
5414 evt.priority = opts.priority;
5415 (0, import_jquery34.default)(opts.el || window.document).trigger(evt);
5416 if (!evt.isDefaultPrevented()) {
5417 let name = evt.name;
5418 if (evt.inputType !== "") name += ":" + evt.inputType;
5419 this.target.setInput(name, evt.value, { priority: opts.priority });
5420 }
5421 }
5422 };
5423
5424 // srcts/src/inputPolicies/inputNoResendDecorator.ts
5425 var InputNoResendDecorator = class {
5426 constructor(target, initialValues = {}) {
5427 this.lastSentValues = {};
5428 this.target = target;
5429 this.reset(initialValues);
5430 }
5431 setInput(nameType, value, opts) {
5432 const { name: inputName, inputType } = splitInputNameType(nameType);
5433 const jsonValue = JSON.stringify(value);
5434 if (opts.priority !== "event" && this.lastSentValues[inputName] && this.lastSentValues[inputName].jsonValue === jsonValue && this.lastSentValues[inputName].inputType === inputType) {
5435 return;
5436 }
5437 this.lastSentValues[inputName] = { jsonValue, inputType };
5438 this.target.setInput(nameType, value, opts);
5439 }
5440 reset(values = {}) {
5441 const cacheValues = {};
5442 for (const inputName in values) {
5443 if (hasDefinedProperty(values, inputName)) {
5444 const { name, inputType } = splitInputNameType(inputName);
5445 cacheValues[name] = {
5446 jsonValue: JSON.stringify(values[inputName]),
5447 inputType
5448 };
5449 }
5450 }
5451 this.lastSentValues = cacheValues;
5452 }
5453 forget(name) {
5454 delete this.lastSentValues[name];
5455 }
5456 };
5457
5458 // srcts/src/inputPolicies/inputRateDecorator.ts
5459 var InputRateDecorator = class {
5460 constructor(target) {
5461 this.inputRatePolicies = {};
5462 this.target = target;
5463 }
5464 // Note that the first argument of setInput() and setRatePolicy()
5465 // are passed both the input name (i.e., inputId) and type.
5466 // https://github.com/rstudio/shiny/blob/67d3a/srcjs/init_shiny.js#L111-L126
5467 // However, $ensureInit() and $doSetInput() are meant to be passed just
5468 // the input name (i.e., inputId), which is why we distinguish between
5469 // nameType and name.
5470 setInput(nameType, value, opts) {
5471 const { name: inputName } = splitInputNameType(nameType);
5472 this._ensureInit(inputName);
5473 if (opts.priority !== "deferred")
5474 this.inputRatePolicies[inputName].immediateCall(nameType, value, opts);
5475 else this.inputRatePolicies[inputName].normalCall(nameType, value, opts);
5476 }
5477 setRatePolicy(nameType, mode, millis) {
5478 const { name: inputName } = splitInputNameType(nameType);
5479 if (mode === "direct") {
5480 this.inputRatePolicies[inputName] = new Invoker(this, this._doSetInput);
5481 } else if (mode === "debounce") {
5482 this.inputRatePolicies[inputName] = new Debouncer(
5483 this,
5484 this._doSetInput,
5485 millis
5486 );
5487 } else if (mode === "throttle") {
5488 this.inputRatePolicies[inputName] = new Throttler(
5489 this,
5490 this._doSetInput,
5491 millis
5492 );
5493 }
5494 }
5495 _ensureInit(name) {
5496 if (!(name in this.inputRatePolicies)) this.setRatePolicy(name, "direct");
5497 }
5498 _doSetInput(nameType, value, opts) {
5499 this.target.setInput(nameType, value, opts);
5500 }
5501 };
5502
5503 // srcts/src/inputPolicies/inputValidateDecorator.ts
5504 function addDefaultInputOpts(opts) {
5505 const newOpts = {
5506 priority: "immediate",
5507 ...opts
5508 };
5509 switch (newOpts.priority) {
5510 case "deferred":
5511 case "immediate":
5512 case "event":
5513 break;
5514 default:
5515 throw new Error(
5516 "Unexpected input value mode: '" + newOpts.priority + "'"
5517 );
5518 }
5519 return newOpts;
5520 }
5521 var InputValidateDecorator = class {
5522 constructor(target) {
5523 this.target = target;
5524 }
5525 setInput(nameType, value, opts = {}) {
5526 if (!nameType) throw "Can't set input with empty name.";
5527 const newOpts = addDefaultInputOpts(opts);
5528 this.target.setInput(nameType, value, newOpts);
5529 }
5530 };
5531
5532 // srcts/src/utils/promise.ts
5533 function promiseWithResolvers() {
5534 let resolve;
5535 let reject;
5536 const promise = new Promise(
5537 (res, rej) => {
5538 resolve = res;
5539 reject = rej;
5540 }
5541 );
5542 return { promise, resolve, reject };
5543 }
5544 function createInitStatus() {
5545 const { promise, resolve } = promiseWithResolvers();
5546 let _resolved = false;
5547 return {
5548 promise,
5549 resolve(x2) {
5550 _resolved = true;
5551 resolve(x2);
5552 },
5553 then: promise.then.bind(promise),
5554 catch: promise.catch.bind(promise),
5555 finally: promise.finally.bind(promise),
5556 [Symbol.toStringTag]: "InitStatus",
5557 resolved() {
5558 return _resolved;
5559 }
5560 };
5561 }
5562
5563 // srcts/src/shiny/bind.ts
5564 var import_jquery35 = __toESM(require_jquery());
5565
5566 // srcts/src/bindings/outputAdapter.ts
5567 var OutputBindingAdapter = class {
5568 constructor(el, binding) {
5569 this.el = el;
5570 this.binding = binding;
5571 if (binding.resize) {
5572 this.onResize = makeResizeFilter(el, function(width, height) {
5573 binding.resize(el, width, height);
5574 });
5575 }
5576 }
5577 getId() {
5578 return this.binding.getId(this.el);
5579 }
5580 async onValueChange(data) {
5581 await this.binding.onValueChange(this.el, data);
5582 }
5583 onValueError(err) {
5584 this.binding.onValueError(this.el, err);
5585 }
5586 showProgress(show3) {
5587 this.binding.showProgress(this.el, show3);
5588 }
5589 onResize() {
5590 }
5591 };
5592
5593 // srcts/src/shiny/bind.ts
5594 function isJQuery(value) {
5595 return Boolean(value && value.jquery);
5596 }
5597 function valueChangeCallback(inputs, binding, el, priority) {
5598 let id = binding.getId(el);
5599 if (id) {
5600 const value = binding.getValue(el);
5601 const type = binding.getType(el);
5602 if (type) id = id + ":" + type;
5603 const normalizedPriority = normalizeEventPriority(priority);
5604 inputs.setInput(id, value, { priority: normalizedPriority, binding, el });
5605 }
5606 }
5607 function normalizeEventPriority(priority) {
5608 if (priority === false || priority === void 0) {
5609 return "immediate";
5610 }
5611 if (priority === true) {
5612 return "deferred";
5613 }
5614 if (typeof priority === "object" && "priority" in priority) {
5615 return priority.priority;
5616 }
5617 return priority;
5618 }
5619 var bindingsRegistry = /* @__PURE__ */ (() => {
5620 const bindings = /* @__PURE__ */ new Map();
5621 function checkValidity(scope) {
5622 if (!isJQuery(scope) && !(scope instanceof HTMLElement)) {
5623 return;
5624 }
5625 const duplicateIds = /* @__PURE__ */ new Map();
5626 const problems = /* @__PURE__ */ new Set();
5627 bindings.forEach((idTypes, id) => {
5628 const counts = { input: 0, output: 0 };
5629 idTypes.forEach((type) => counts[type] += 1);
5630 if (counts.input + counts.output < 2) {
5631 return;
5632 }
5633 duplicateIds.set(id, counts);
5634 if (counts.input > 1) {
5635 problems.add("input");
5636 }
5637 if (counts.output > 1) {
5638 problems.add("output");
5639 }
5640 if (counts.input >= 1 && counts.output >= 1) {
5641 problems.add("shared");
5642 }
5643 });
5644 if (duplicateIds.size === 0) return;
5645 const duplicateIdMsg = Array.from(duplicateIds.entries()).map(([id, counts]) => {
5646 const messages = [
5647 pluralize(counts.input, "input"),
5648 pluralize(counts.output, "output")
5649 ].filter((msg) => msg !== "").join(" and ");
5650 return `- "${id}": ${messages}`;
5651 }).join("\n");
5652 let txtVerb = "Duplicate";
5653 let txtNoun = "input/output";
5654 if (problems.has("input") && problems.has("output")) {
5655 } else if (problems.has("input")) {
5656 txtNoun = "input";
5657 } else if (problems.has("output")) {
5658 txtNoun = "output";
5659 } else if (problems.has("shared")) {
5660 txtVerb = "Shared";
5661 }
5662 const txtIdsWere = duplicateIds.size == 1 ? "ID was" : "IDs were";
5663 const headline = `${txtVerb} ${txtNoun} ${txtIdsWere} found`;
5664 const message = `The following ${txtIdsWere} used for more than one ${problems.has("shared") ? "input/output" : txtNoun}:
5665 ${duplicateIdMsg}`;
5666 const event = new ShinyClientMessageEvent({ headline, message });
5667 const scopeElement = isJQuery(scope) ? scope.get(0) : scope;
5668 (scopeElement || window).dispatchEvent(event);
5669 }
5670 function addBinding(id, bindingType) {
5671 const existingBinding = bindings.get(id);
5672 if (existingBinding) {
5673 existingBinding.push(bindingType);
5674 } else {
5675 bindings.set(id, [bindingType]);
5676 }
5677 }
5678 function removeBinding(id, bindingType) {
5679 const existingBinding = bindings.get(id);
5680 if (existingBinding) {
5681 const index = existingBinding.indexOf(bindingType);
5682 if (index > -1) {
5683 existingBinding.splice(index, 1);
5684 }
5685 }
5686 if (existingBinding?.length === 0) {
5687 bindings.delete(id);
5688 }
5689 }
5690 return {
5691 addBinding,
5692 removeBinding,
5693 checkValidity
5694 };
5695 })();
5696 function pluralize(num, word) {
5697 if (num === 0) return "";
5698 if (num === 1) return `${num} ${word}`;
5699 return `${num} ${word}s`;
5700 }
5701 function bindInputs(shinyCtx, scope = document.documentElement) {
5702 const { inputs, inputsRate, inputBindings } = shinyCtx;
5703 const bindings = inputBindings.getBindings();
5704 const inputItems = {};
5705 for (let i5 = 0; i5 < bindings.length; i5++) {
5706 const binding = bindings[i5].binding;
5707 const matches = binding.find(scope) || [];
5708 for (let j2 = 0; j2 < matches.length; j2++) {
5709 const el = matches[j2];
5710 if (el.hasAttribute("data-shiny-no-bind-input")) continue;
5711 const id = binding.getId(el);
5712 if (!id || (0, import_jquery35.default)(el).hasClass("shiny-bound-input")) continue;
5713 const type = binding.getType(el);
5714 const effectiveId = type ? id + ":" + type : id;
5715 inputItems[effectiveId] = {
5716 value: binding.getValue(el),
5717 opts: {
5718 immediate: true,
5719 binding,
5720 el
5721 }
5722 };
5723 const thisCallback = /* @__PURE__ */ function() {
5724 const thisBinding = binding;
5725 const thisEl = el;
5726 return function(priority) {
5727 valueChangeCallback(inputs, thisBinding, thisEl, priority);
5728 };
5729 }();
5730 binding.subscribe(el, thisCallback);
5731 (0, import_jquery35.default)(el).data("shiny-input-binding", binding);
5732 (0, import_jquery35.default)(el).addClass("shiny-bound-input");
5733 const ratePolicy = binding.getRatePolicy(el);
5734 if (ratePolicy !== null) {
5735 inputsRate.setRatePolicy(
5736 effectiveId,
5737 ratePolicy.policy,
5738 ratePolicy.delay
5739 );
5740 }
5741 bindingsRegistry.addBinding(id, "input");
5742 (0, import_jquery35.default)(el).trigger({
5743 type: "shiny:bound",
5744 // @ts-expect-error; Can not remove info on a established, malformed Event object
5745 binding,
5746 bindingType: "input"
5747 });
5748 }
5749 }
5750 return inputItems;
5751 }
5752 async function bindOutputs({
5753 sendOutputHiddenState,
5754 maybeAddThemeObserver,
5755 outputBindings,
5756 outputIsRecalculating
5757 }, scope = document.documentElement) {
5758 const $scope = (0, import_jquery35.default)(scope);
5759 const bindings = outputBindings.getBindings();
5760 for (let i5 = 0; i5 < bindings.length; i5++) {
5761 const binding = bindings[i5].binding;
5762 const matches = binding.find($scope) || [];
5763 for (let j2 = 0; j2 < matches.length; j2++) {
5764 const el = matches[j2];
5765 const id = binding.getId(el);
5766 if (!id) continue;
5767 if (!import_jquery35.default.contains(document.documentElement, el)) continue;
5768 const $el = (0, import_jquery35.default)(el);
5769 if ($el.hasClass("shiny-bound-output")) {
5770 continue;
5771 }
5772 maybeAddThemeObserver(el);
5773 const bindingAdapter = new OutputBindingAdapter(el, binding);
5774 await shinyAppBindOutput(id, bindingAdapter);
5775 $el.data("shiny-output-binding", bindingAdapter);
5776 $el.addClass("shiny-bound-output");
5777 if (!$el.attr("aria-live")) $el.attr("aria-live", "polite");
5778 if (outputIsRecalculating(id)) {
5779 bindingAdapter.showProgress(true);
5780 }
5781 bindingsRegistry.addBinding(id, "output");
5782 $el.trigger({
5783 type: "shiny:bound",
5784 // @ts-expect-error; Can not remove info on a established, malformed Event object
5785 binding,
5786 bindingType: "output"
5787 });
5788 }
5789 }
5790 setTimeout(sendImageSizeFns.regular, 0);
5791 setTimeout(sendOutputHiddenState, 0);
5792 }
5793 function unbindInputs(scope = document.documentElement, includeSelf = false) {
5794 const inputs = (0, import_jquery35.default)(scope).find(".shiny-bound-input").toArray();
5795 if (includeSelf && (0, import_jquery35.default)(scope).hasClass("shiny-bound-input")) {
5796 inputs.push(scope);
5797 }
5798 for (let i5 = 0; i5 < inputs.length; i5++) {
5799 const el = inputs[i5];
5800 const binding = (0, import_jquery35.default)(el).data("shiny-input-binding");
5801 if (!binding) continue;
5802 const id = binding.getId(el);
5803 (0, import_jquery35.default)(el).removeClass("shiny-bound-input");
5804 bindingsRegistry.removeBinding(id, "input");
5805 binding.unsubscribe(el);
5806 (0, import_jquery35.default)(el).trigger({
5807 type: "shiny:unbound",
5808 // @ts-expect-error; Can not remove info on a established, malformed Event object
5809 binding,
5810 bindingType: "input"
5811 });
5812 }
5813 }
5814 function unbindOutputs({ sendOutputHiddenState }, scope = document.documentElement, includeSelf = false) {
5815 const outputs = (0, import_jquery35.default)(scope).find(".shiny-bound-output").toArray();
5816 if (includeSelf && (0, import_jquery35.default)(scope).hasClass("shiny-bound-output")) {
5817 outputs.push(scope);
5818 }
5819 for (let i5 = 0; i5 < outputs.length; i5++) {
5820 const $el = (0, import_jquery35.default)(outputs[i5]);
5821 const bindingAdapter = $el.data("shiny-output-binding");
5822 if (!bindingAdapter) continue;
5823 const id = bindingAdapter.binding.getId(outputs[i5]);
5824 shinyAppUnbindOutput(id, bindingAdapter);
5825 bindingsRegistry.removeBinding(id, "output");
5826 $el.removeClass("shiny-bound-output");
5827 $el.removeData("shiny-output-binding");
5828 $el.trigger({
5829 type: "shiny:unbound",
5830 // @ts-expect-error; Can not remove info on a established, malformed Event object
5831 binding: bindingAdapter.binding,
5832 bindingType: "output"
5833 });
5834 }
5835 setTimeout(sendImageSizeFns.regular, 0);
5836 setTimeout(sendOutputHiddenState, 0);
5837 }
5838 async function _bindAll(shinyCtx, scope) {
5839 await bindOutputs(shinyCtx, scope);
5840 const currentInputs = bindInputs(shinyCtx, scope);
5841 bindingsRegistry.checkValidity(scope);
5842 return currentInputs;
5843 }
5844 function unbindAll(shinyCtx, scope, includeSelf = false) {
5845 unbindInputs(scope, includeSelf);
5846 unbindOutputs(shinyCtx, scope, includeSelf);
5847 }
5848 async function bindAll(shinyCtx, scope) {
5849 const currentInputItems = await _bindAll(shinyCtx, scope);
5850 const inputs = shinyCtx.inputs;
5851 import_jquery35.default.each(currentInputItems, function(name, item) {
5852 inputs.setInput(name, item.value, item.opts);
5853 });
5854 shinyCtx.initDeferredIframes();
5855 }
5856
5857 // srcts/src/shiny/modal.ts
5858 var import_jquery36 = __toESM(require_jquery());
5859 async function show({
5860 html = "",
5861 deps = []
5862 } = {}) {
5863 await renderDependenciesAsync(deps);
5864 (0, import_jquery36.default)(".modal-backdrop").remove();
5865 let $modal = (0, import_jquery36.default)("#shiny-modal-wrapper");
5866 if ($modal.length === 0) {
5867 $modal = (0, import_jquery36.default)('<div id="shiny-modal-wrapper"></div>');
5868 (0, import_jquery36.default)(document.body).append($modal);
5869 $modal.on("hidden.bs.modal", function(e4) {
5870 if (e4.target === (0, import_jquery36.default)("#shiny-modal")[0]) {
5871 shinyUnbindAll($modal);
5872 $modal.remove();
5873 }
5874 });
5875 }
5876 $modal.on("keydown.shinymodal", function(e4) {
5877 if ((0, import_jquery36.default)("#shiny-modal").data("keyboard") === false) return;
5878 if (e4.keyCode === 27) {
5879 e4.stopPropagation();
5880 e4.preventDefault();
5881 }
5882 });
5883 await renderContentAsync($modal, { html });
5884 }
5885 function remove() {
5886 const $modal = (0, import_jquery36.default)("#shiny-modal-wrapper");
5887 $modal.off("keydown.shinymodal");
5888 const $bsModal = $modal.find(".modal");
5889 if ($bsModal.length > 0) {
5890 $bsModal.on("shown.bs.modal", () => $bsModal.modal("hide"));
5891 $bsModal.modal("hide");
5892 } else {
5893 shinyUnbindAll($modal);
5894 $modal.remove();
5895 }
5896 }
5897
5898 // srcts/src/shiny/notifications.ts
5899 var import_jquery37 = __toESM(require_jquery());
5900 var fadeDuration = 250;
5901 async function show2({
5902 html = "",
5903 action = "",
5904 deps = [],
5905 duration = 5e3,
5906 id = null,
5907 closeButton = true,
5908 type = null
5909 } = {}) {
5910 if (!id) id = randomId();
5911 await renderDependenciesAsync(deps);
5912 createPanel();
5913 let $notificationInit = get(id);
5914 if ($notificationInit?.length === 0) $notificationInit = create(id);
5915 const $notification = $notificationInit;
5916 const newHtml = `<div class="shiny-notification-content-text">${html}</div><div class="shiny-notification-content-action">${action}</div>`;
5917 const $content = $notification.find(".shiny-notification-content");
5918 await renderContentAsync($content, { html: newHtml });
5919 const classes = $notification?.attr("class");
5920 if (classes) {
5921 const classVal = classes.split(/\s+/).filter((cls) => cls.match(/^shiny-notification-/)).join(" ");
5922 $notification.removeClass(classVal);
5923 }
5924 if (type && type !== "default")
5925 $notification.addClass("shiny-notification-" + type);
5926 const $close = $notification.find(".shiny-notification-close");
5927 if (closeButton && $close.length === 0) {
5928 $notification.append('<div class="shiny-notification-close">&times;</div>');
5929 } else if (!closeButton && $close.length !== 0) {
5930 $close.remove();
5931 }
5932 if (duration) addRemovalCallback(id, duration);
5933 else clearRemovalCallback(id);
5934 return id;
5935 }
5936 function remove2(id) {
5937 get(id)?.fadeOut(fadeDuration, function() {
5938 shinyUnbindAll(this);
5939 (0, import_jquery37.default)(this).remove();
5940 if (ids().length === 0) {
5941 getPanel().remove();
5942 }
5943 });
5944 }
5945 function get(id) {
5946 if (!id) return null;
5947 return getPanel().find("#shiny-notification-" + $escape(id));
5948 }
5949 function ids() {
5950 return getPanel().find(".shiny-notification").map(function() {
5951 return this.id.replace(/shiny-notification-/, "");
5952 }).get();
5953 }
5954 function getPanel() {
5955 return (0, import_jquery37.default)("#shiny-notification-panel");
5956 }
5957 function createPanel() {
5958 const $panel = getPanel();
5959 if ($panel.length > 0) return $panel;
5960 (0, import_jquery37.default)(document.body).append('<div id="shiny-notification-panel">');
5961 return $panel;
5962 }
5963 function create(id) {
5964 let $notification = get(id);
5965 if ($notification?.length === 0) {
5966 $notification = (0, import_jquery37.default)(
5967 `<div id="shiny-notification-${id}" class="shiny-notification"><div class="shiny-notification-close">&times;</div><div class="shiny-notification-content"></div></div>`
5968 );
5969 $notification.find(".shiny-notification-close").on("click", (e4) => {
5970 e4.preventDefault();
5971 e4.stopPropagation();
5972 remove2(id);
5973 });
5974 getPanel().append($notification);
5975 }
5976 return $notification;
5977 }
5978 function addRemovalCallback(id, delay) {
5979 clearRemovalCallback(id);
5980 const removalCallback = setTimeout(function() {
5981 remove2(id);
5982 }, delay);
5983 get(id)?.data("removalCallback", removalCallback);
5984 }
5985 function clearRemovalCallback(id) {
5986 const $notification = get(id);
5987 const oldRemovalCallback = $notification?.data("removalCallback");
5988 if (oldRemovalCallback) {
5989 clearTimeout(oldRemovalCallback);
5990 }
5991 }
5992
5993 // srcts/src/shiny/reconnectDialog.ts
5994 var import_jquery38 = __toESM(require_jquery());
5995 function updateTime(reconnectTime) {
5996 const $time = (0, import_jquery38.default)("#shiny-reconnect-time");
5997 if ($time.length === 0) return;
5998 const seconds = Math.floor((reconnectTime - (/* @__PURE__ */ new Date()).getTime()) / 1e3);
5999 if (seconds > 0) {
6000 $time.text(" in " + seconds + "s");
6001 } else {
6002 $time.text("...");
6003 }
6004 setTimeout(function() {
6005 updateTime(reconnectTime);
6006 }, 1e3);
6007 }
6008 async function showReconnectDialog(delay) {
6009 const reconnectTime = (/* @__PURE__ */ new Date()).getTime() + delay;
6010 if ((0, import_jquery38.default)("#shiny-reconnect-text").length > 0) return;
6011 const html = '<span id="shiny-reconnect-text">Attempting to reconnect</span><span id="shiny-reconnect-time"></span>';
6012 const action = '<a id="shiny-reconnect-now" href="#" onclick="Shiny.shinyapp.reconnect();">Try now</a>';
6013 await show2({
6014 id: "reconnect",
6015 html,
6016 action,
6017 duration: null,
6018 closeButton: false,
6019 type: "warning"
6020 });
6021 updateTime(reconnectTime);
6022 }
6023 function hideReconnectDialog() {
6024 remove2("reconnect");
6025 }
6026
6027 // srcts/src/shiny/shinyapp.ts
6028 var import_jquery39 = __toESM(require_jquery());
6029
6030 // srcts/src/utils/asyncQueue.ts
6031 var AsyncQueue = class {
6032 constructor() {
6033 this.$promises = [];
6034 this.$resolvers = [];
6035 }
6036 _add() {
6037 const p3 = new Promise((resolve) => {
6038 this.$resolvers.push(resolve);
6039 });
6040 this.$promises.push(p3);
6041 }
6042 enqueue(x2) {
6043 if (!this.$resolvers.length) this._add();
6044 const resolve = this.$resolvers.shift();
6045 resolve(x2);
6046 }
6047 async dequeue() {
6048 if (!this.$promises.length) this._add();
6049 const promise = this.$promises.shift();
6050 return promise;
6051 }
6052 isEmpty() {
6053 return !this.$promises.length;
6054 }
6055 isBlocked() {
6056 return !!this.$resolvers.length;
6057 }
6058 get length() {
6059 return this.$promises.length - this.$resolvers.length;
6060 }
6061 };
6062
6063 // srcts/src/shiny/outputProgress.ts
6064 var _OutputProgressReporter_instances, updateStateFromRecalculating_fn, updateStateFromFlush_fn, updateStateFromProgress_fn, updateStateFromValueOrError_fn, getState_fn, setState_fn;
6065 var OutputProgressReporter = class {
6066 constructor() {
6067 __privateAdd(this, _OutputProgressReporter_instances);
6068 this.outputStates = /* @__PURE__ */ new Map();
6069 // A map of outputs that have changed their progress status since the last call to takeChanges().
6070 // The value is true if the output is recalculating, and false otherwise.
6071 this.changedOutputs = /* @__PURE__ */ new Map();
6072 }
6073 takeChanges() {
6074 const result = this.changedOutputs;
6075 this.changedOutputs = /* @__PURE__ */ new Map();
6076 return result;
6077 }
6078 // Returns whether the output is recalculating or not.
6079 isRecalculating(name) {
6080 const state = __privateMethod(this, _OutputProgressReporter_instances, getState_fn).call(this, name);
6081 const recalculatingStates = [
6082 "initial" /* Initial */,
6083 "running" /* Running */,
6084 "idle" /* Idle */,
6085 "persistent" /* Persistent */,
6086 "invalidated" /* Invalidated */
6087 ];
6088 return recalculatingStates.includes(state);
6089 }
6090 // Update output state based on the message received from the server.
6091 // Note that any message can be passed to this method, but only the
6092 // messages that are relevant to output progress do anything to the state.
6093 updateStateFromMessage(message) {
6094 if (isRecalculatingMessage(message)) {
6095 __privateMethod(this, _OutputProgressReporter_instances, updateStateFromRecalculating_fn).call(this, message);
6096 }
6097 if (isFlushMessage(message)) {
6098 __privateMethod(this, _OutputProgressReporter_instances, updateStateFromFlush_fn).call(this, message);
6099 }
6100 if (isProgressMessage(message)) {
6101 __privateMethod(this, _OutputProgressReporter_instances, updateStateFromProgress_fn).call(this, message);
6102 }
6103 }
6104 };
6105 _OutputProgressReporter_instances = new WeakSet();
6106 updateStateFromRecalculating_fn = function(message) {
6107 const { name, status } = message.recalculating;
6108 const state = __privateMethod(this, _OutputProgressReporter_instances, getState_fn).call(this, name);
6109 if (status === "recalculating") {
6110 switch (state) {
6111 case "initial" /* Initial */:
6112 case "invalidated" /* Invalidated */:
6113 __privateMethod(this, _OutputProgressReporter_instances, setState_fn).call(this, name, "running" /* Running */);
6114 break;
6115 default:
6116 throw new Error(
6117 `Shiny server sent a message that the output '${name}' is recalculating,
6118 but the output is in an unexpected state of: '${state}'.`
6119 );
6120 }
6121 }
6122 if (status === "recalculated") {
6123 switch (state) {
6124 case "running" /* Running */:
6125 __privateMethod(this, _OutputProgressReporter_instances, setState_fn).call(this, name, "idle" /* Idle */);
6126 break;
6127 default:
6128 throw new Error(
6129 `Shiny server sent a message that the output '${name}' has been recalculated,
6130 but the output is in an unexpected state of: '${state}'.`
6131 );
6132 }
6133 }
6134 };
6135 updateStateFromFlush_fn = function(message) {
6136 for (const name in message.values) {
6137 __privateMethod(this, _OutputProgressReporter_instances, updateStateFromValueOrError_fn).call(this, name, "value" /* Value */);
6138 }
6139 for (const name in message.errors) {
6140 __privateMethod(this, _OutputProgressReporter_instances, updateStateFromValueOrError_fn).call(this, name, "error" /* Error */);
6141 }
6142 for (const [name, state] of this.outputStates) {
6143 switch (state) {
6144 case "idle" /* Idle */:
6145 __privateMethod(this, _OutputProgressReporter_instances, setState_fn).call(this, name, "cancel" /* Cancel */);
6146 break;
6147 case "value" /* Value */:
6148 case "error" /* Error */:
6149 case "cancel" /* Cancel */:
6150 case "persistent" /* Persistent */:
6151 case "invalidated" /* Invalidated */:
6152 break;
6153 default:
6154 throw new Error(
6155 `Shiny server sent a flush message, and after processing the values and errors,
6156 the output '${name}' has an unexpected ending state of: '${state}'.`
6157 );
6158 }
6159 }
6160 };
6161 updateStateFromProgress_fn = function(message) {
6162 const { id, persistent } = message.progress.message;
6163 const state = __privateMethod(this, _OutputProgressReporter_instances, getState_fn).call(this, id);
6164 if (persistent) {
6165 switch (state) {
6166 case "running" /* Running */:
6167 __privateMethod(this, _OutputProgressReporter_instances, setState_fn).call(this, id, "persistent" /* Persistent */);
6168 break;
6169 default:
6170 throw new Error(
6171 `Shiny server has sent a 'persistent progress' message for ${id},
6172 but the output is in an unexpected state of: ${state}`
6173 );
6174 }
6175 } else {
6176 switch (state) {
6177 case "value" /* Value */:
6178 case "error" /* Error */:
6179 case "cancel" /* Cancel */:
6180 case "persistent" /* Persistent */:
6181 case "idle" /* Idle */:
6182 __privateMethod(this, _OutputProgressReporter_instances, setState_fn).call(this, id, "invalidated" /* Invalidated */);
6183 break;
6184 default:
6185 throw new Error(
6186 `Shiny server has sent a progress message for ${id},
6187 but the output is in an unexpected state of: ${state}`
6188 );
6189 }
6190 }
6191 };
6192 // When receiving values/errors as part of a flush message, outputs should generally
6193 // be moving from Idle to Value/Error state.
6194 updateStateFromValueOrError_fn = function(name, type) {
6195 const state = __privateMethod(this, _OutputProgressReporter_instances, getState_fn).call(this, name);
6196 switch (state) {
6197 case "idle" /* Idle */:
6198 __privateMethod(this, _OutputProgressReporter_instances, setState_fn).call(this, name, type);
6199 break;
6200 default:
6201 throw new Error(
6202 `Shiny server has sent a ${type} for the output '${name}',
6203 but the output is in an unexpected state of: '${state}'.`
6204 );
6205 }
6206 };
6207 getState_fn = function(name) {
6208 return this.outputStates.get(name) ?? "initial" /* Initial */;
6209 };
6210 setState_fn = function(name, state) {
6211 const oldRecalc = this.isRecalculating(name);
6212 this.outputStates.set(name, state);
6213 const newRecalc = this.isRecalculating(name);
6214 if (oldRecalc !== newRecalc) {
6215 this.changedOutputs.set(name, newRecalc);
6216 }
6217 };
6218 function isRecalculatingMessage(x2) {
6219 const m2 = x2;
6220 return m2.recalculating !== void 0;
6221 }
6222 function isFlushMessage(x2) {
6223 const m2 = x2;
6224 return m2.values !== void 0 && m2.errors !== void 0;
6225 }
6226 function isProgressMessage(x2) {
6227 const m2 = x2;
6228 return m2.progress !== void 0 && m2.progress.type === "binding";
6229 }
6230
6231 // srcts/src/shiny/shinyapp.ts
6232 var messageHandlerOrder = [];
6233 var messageHandlers = {};
6234 var customMessageHandlerOrder = [];
6235 var customMessageHandlers = {};
6236 function addMessageHandler(type, handler) {
6237 if (messageHandlers[type]) {
6238 throw 'handler for message of type "' + type + '" already added.';
6239 }
6240 if (typeof handler !== "function") {
6241 throw "handler must be a function.";
6242 }
6243 if (handler.length !== 1) {
6244 throw "handler must be a function that takes one argument.";
6245 }
6246 messageHandlerOrder.push(type);
6247 messageHandlers[type] = handler;
6248 }
6249 function addCustomMessageHandler(type, handler) {
6250 if (customMessageHandlers[type]) {
6251 const typeIdx = customMessageHandlerOrder.indexOf(type);
6252 if (typeIdx !== -1) {
6253 customMessageHandlerOrder.splice(typeIdx, 1);
6254 delete customMessageHandlers[type];
6255 }
6256 }
6257 if (typeof handler !== "function") {
6258 throw "handler must be a function.";
6259 }
6260 if (handler.length !== 1) {
6261 throw "handler must be a function that takes one argument.";
6262 }
6263 customMessageHandlerOrder.push(type);
6264 customMessageHandlers[type] = handler;
6265 }
6266 var ShinyApp = class {
6267 constructor() {
6268 this.$socket = null;
6269 // An asynchronous queue of functions. This is sort of like an event loop for
6270 // Shiny, to allow scheduling async callbacks so that they can run in order
6271 // without overlapping. This is used for handling incoming messages from the
6272 // server and scheduling outgoing messages to the server, and can be used for
6273 // other things tasks as well.
6274 this.taskQueue = new AsyncQueue();
6275 this.config = null;
6276 // Cached input values
6277 this.$inputValues = {};
6278 // Input values at initialization (and reconnect)
6279 this.$initialInput = null;
6280 // Output bindings
6281 this.$bindings = {};
6282 // Output progress states
6283 this.$outputProgress = new OutputProgressReporter();
6284 // Cached values/errors
6285 this.$values = {};
6286 this.$errors = {};
6287 // Conditional bindings (show/hide element based on expression)
6288 this.$conditionals = {};
6289 this.$pendingMessages = [];
6290 this.$activeRequests = {};
6291 this.$nextRequestId = 0;
6292 this.$allowReconnect = false;
6293 this.scheduledReconnect = void 0;
6294 // How long should we wait before trying the next reconnection?
6295 // The delay will increase with subsequent attempts.
6296 // .next: Return the time to wait for next connection, and increment counter.
6297 // .reset: Reset the attempt counter.
6298 this.reconnectDelay = /* @__PURE__ */ function() {
6299 let attempts = 0;
6300 const delays = [1500, 1500, 2500, 2500, 5500, 5500, 10500];
6301 return {
6302 next: function() {
6303 let i5 = attempts;
6304 if (i5 >= delays.length) {
6305 i5 = delays.length - 1;
6306 }
6307 attempts++;
6308 return delays[i5];
6309 },
6310 reset: function() {
6311 attempts = 0;
6312 }
6313 };
6314 }();
6315 // Progress reporting ====================================================
6316 this.progressHandlers = {
6317 // Progress for a particular object
6318 binding: function(message) {
6319 const key = message.id;
6320 const binding = this.$bindings[key];
6321 if (binding) {
6322 (0, import_jquery39.default)(binding.el).trigger({
6323 type: "shiny:outputinvalidated",
6324 // @ts-expect-error; Can not remove info on a established, malformed Event object
6325 binding,
6326 name: key
6327 });
6328 }
6329 this._updateProgress();
6330 },
6331 // Open a page-level progress bar
6332 open: async function(message) {
6333 if (message.style === "notification") {
6334 await show2({
6335 html: `<div id="shiny-progress-${message.id}" class="shiny-progress-notification"><div class="progress active" style="display: none;"><div class="progress-bar"></div></div><div class="progress-text"><span class="progress-message">message</span> <span class="progress-detail"></span></div></div>`,
6336 id: message.id,
6337 duration: null
6338 });
6339 } else if (message.style === "old") {
6340 let $container = (0, import_jquery39.default)(".shiny-progress-container");
6341 if ($container.length === 0) {
6342 $container = (0, import_jquery39.default)('<div class="shiny-progress-container"></div>');
6343 (0, import_jquery39.default)(document.body).append($container);
6344 }
6345 const depth = (0, import_jquery39.default)(".shiny-progress.open").length;
6346 const $progress = (0, import_jquery39.default)(
6347 '<div class="shiny-progress open"><div class="progress active"><div class="progress-bar bar"></div></div><div class="progress-text"><span class="progress-message">message</span><span class="progress-detail"></span></div></div>'
6348 );
6349 $progress.attr("id", message.id);
6350 $container.append($progress);
6351 const $progressBar = $progress.find(".progress");
6352 if ($progressBar) {
6353 $progressBar.css(
6354 "top",
6355 depth * $progressBar.height() + "px"
6356 );
6357 const $progressText = $progress.find(".progress-text");
6358 $progressText.css(
6359 "top",
6360 3 * $progressBar.height() + depth * $progressText.outerHeight() + "px"
6361 );
6362 $progress.hide();
6363 }
6364 }
6365 },
6366 // Update page-level progress bar
6367 update: function(message) {
6368 if (message.style === "notification") {
6369 const $progress = (0, import_jquery39.default)("#shiny-progress-" + message.id);
6370 if ($progress.length === 0) return;
6371 if (typeof message.message !== "undefined") {
6372 $progress.find(".progress-message").text(message.message);
6373 }
6374 if (typeof message.detail !== "undefined") {
6375 $progress.find(".progress-detail").text(message.detail);
6376 }
6377 if (typeof message.value !== "undefined" && message.value !== null) {
6378 $progress.find(".progress").show();
6379 $progress.find(".progress-bar").width(message.value * 100 + "%");
6380 }
6381 } else if (message.style === "old") {
6382 const $progress = (0, import_jquery39.default)("#" + message.id + ".shiny-progress");
6383 if (typeof message.message !== "undefined") {
6384 $progress.find(".progress-message").text(message.message);
6385 }
6386 if (typeof message.detail !== "undefined") {
6387 $progress.find(".progress-detail").text(message.detail);
6388 }
6389 if (typeof message.value !== "undefined" && message.value !== null) {
6390 $progress.find(".progress").show();
6391 $progress.find(".bar").width(message.value * 100 + "%");
6392 }
6393 $progress.fadeIn();
6394 }
6395 },
6396 // Close page-level progress bar
6397 close: function(message) {
6398 if (message.style === "notification") {
6399 remove2(message.id);
6400 } else if (message.style === "old") {
6401 const $progress = (0, import_jquery39.default)("#" + message.id + ".shiny-progress");
6402 $progress.removeClass("open");
6403 $progress.fadeOut({
6404 complete: function() {
6405 $progress.remove();
6406 if ((0, import_jquery39.default)(".shiny-progress").length === 0)
6407 (0, import_jquery39.default)(".shiny-progress-container").remove();
6408 }
6409 });
6410 }
6411 }
6412 };
6413 this._init();
6414 }
6415 connect(initialInput) {
6416 if (this.$socket)
6417 throw "Connect was already called on this application object";
6418 this.$socket = this.createSocket();
6419 this.$initialInput = initialInput;
6420 import_jquery39.default.extend(this.$inputValues, initialInput);
6421 this.$updateConditionals();
6422 }
6423 isConnected() {
6424 return !!this.$socket;
6425 }
6426 reconnect() {
6427 clearTimeout(this.scheduledReconnect);
6428 if (this.isConnected())
6429 throw "Attempted to reconnect, but already connected.";
6430 this.$socket = this.createSocket();
6431 this.$initialInput = import_jquery39.default.extend({}, this.$inputValues);
6432 this.$updateConditionals();
6433 }
6434 createSocket() {
6435 const createSocketFunc = getShinyCreateWebsocket() || (() => {
6436 let protocol = "ws:";
6437 if (window.location.protocol === "https:") protocol = "wss:";
6438 let defaultPath = window.location.pathname;
6439 if (!/^([$#!&-;=?-[\]_a-z~]|%[0-9a-fA-F]{2})+$/.test(defaultPath)) {
6440 defaultPath = encodeURI(defaultPath);
6441 if (isQt()) {
6442 defaultPath = encodeURI(defaultPath);
6443 }
6444 }
6445 if (!/\/$/.test(defaultPath)) defaultPath += "/";
6446 defaultPath += "websocket/";
6447 const ws = new WebSocket(
6448 protocol + "//" + window.location.host + defaultPath
6449 );
6450 ws.binaryType = "arraybuffer";
6451 return ws;
6452 });
6453 const socket = createSocketFunc();
6454 let hasOpened = false;
6455 socket.onopen = () => {
6456 hasOpened = true;
6457 (0, import_jquery39.default)(document).trigger({
6458 type: "shiny:connected",
6459 // @ts-expect-error; Can not remove info on a established, malformed Event object
6460 socket
6461 });
6462 this.onConnected();
6463 socket.send(
6464 JSON.stringify({
6465 method: "init",
6466 data: this.$initialInput
6467 })
6468 );
6469 while (this.$pendingMessages.length) {
6470 const msg = this.$pendingMessages.shift();
6471 socket.send(msg);
6472 }
6473 this.startActionQueueLoop();
6474 };
6475 socket.onmessage = (e4) => {
6476 this.taskQueue.enqueue(async () => await this.dispatchMessage(e4.data));
6477 };
6478 socket.onclose = (e4) => {
6479 const restarting = e4.code === 1012;
6480 if (hasOpened) {
6481 (0, import_jquery39.default)(document).trigger({
6482 type: "shiny:disconnected",
6483 // @ts-expect-error; Can not remove info on a established, malformed Event object
6484 socket
6485 });
6486 this.$notifyDisconnected();
6487 }
6488 this.onDisconnected(restarting);
6489 this.$removeSocket();
6490 };
6491 return socket;
6492 }
6493 async startActionQueueLoop() {
6494 while (true) {
6495 try {
6496 const action = await this.taskQueue.dequeue();
6497 await action();
6498 } catch (e4) {
6499 showErrorInClientConsole(e4);
6500 console.error(e4);
6501 }
6502 }
6503 }
6504 sendInput(values) {
6505 const msg = JSON.stringify({
6506 method: "update",
6507 data: values
6508 });
6509 this.$sendMsg(msg);
6510 import_jquery39.default.extend(this.$inputValues, values);
6511 this.$updateConditionals();
6512 }
6513 $notifyDisconnected() {
6514 if (window.parent) {
6515 window.parent.postMessage("disconnected", "*");
6516 }
6517 }
6518 $removeSocket() {
6519 this.$socket = null;
6520 }
6521 $scheduleReconnect(delay) {
6522 this.scheduledReconnect = window.setTimeout(() => {
6523 this.reconnect();
6524 }, delay);
6525 }
6526 onDisconnected(reloading = false) {
6527 if ((0, import_jquery39.default)("#shiny-disconnected-overlay").length === 0) {
6528 (0, import_jquery39.default)(document.body).append('<div id="shiny-disconnected-overlay"></div>');
6529 }
6530 (0, import_jquery39.default)("#shiny-disconnected-overlay").toggleClass("reloading", reloading);
6531 if (this.$allowReconnect === true && this.$socket.allowReconnect === true || this.$allowReconnect === "force") {
6532 const delay = this.reconnectDelay.next();
6533 showReconnectDialog(delay);
6534 this.$scheduleReconnect(delay);
6535 }
6536 }
6537 onConnected() {
6538 (0, import_jquery39.default)("#shiny-disconnected-overlay").remove();
6539 hideReconnectDialog();
6540 this.reconnectDelay.reset();
6541 }
6542 // NB: Including blobs will cause IE to break!
6543 // TODO: Make blobs work with Internet Explorer
6544 //
6545 // Websocket messages are normally one-way--i.e. the client passes a
6546 // message to the server but there is no way for the server to provide
6547 // a response to that specific message. makeRequest provides a way to
6548 // do asynchronous RPC over websocket. Each request has a method name
6549 // and arguments, plus optionally one or more binary blobs can be
6550 // included as well. The request is tagged with a unique number that
6551 // the server will use to label the corresponding response.
6552 //
6553 // @param method A string that tells the server what logic to run.
6554 // @param args An array of objects that should also be passed to the
6555 // server in JSON-ified form.
6556 // @param onSuccess A function that will be called back if the server
6557 // responds with success. If the server provides a value in the
6558 // response, the function will be called with it as the only argument.
6559 // @param onError A function that will be called back if the server
6560 // responds with error, or if the request fails for any other reason.
6561 // The parameter to onError will be a string describing the error.
6562 // @param blobs Optionally, an array of Blob, ArrayBuffer, or string
6563 // objects that will be made available to the server as part of the
6564 // request. Strings will be encoded using UTF-8.
6565 makeRequest(method, args, onSuccess, onError, blobs) {
6566 let requestId = this.$nextRequestId;
6567 while (this.$activeRequests[requestId]) {
6568 requestId = (requestId + 1) % 1e9;
6569 }
6570 this.$nextRequestId = requestId + 1;
6571 this.$activeRequests[requestId] = {
6572 onSuccess,
6573 onError
6574 };
6575 let msg = JSON.stringify({
6576 method,
6577 args,
6578 tag: requestId
6579 });
6580 if (blobs) {
6581 const uint32ToBuf = function(val) {
6582 const buffer = new ArrayBuffer(4);
6583 const view = new DataView(buffer);
6584 view.setUint32(0, val, true);
6585 return buffer;
6586 };
6587 const payload = [];
6588 payload.push(uint32ToBuf(16908802));
6589 const jsonBuf = new Blob([msg]);
6590 payload.push(uint32ToBuf(jsonBuf.size));
6591 payload.push(jsonBuf);
6592 for (let i5 = 0; i5 < blobs.length; i5++) {
6593 const blob2 = blobs[i5];
6594 payload.push(
6595 uint32ToBuf(
6596 blob2.byteLength || blob2.size || 0
6597 )
6598 );
6599 payload.push(blob2);
6600 }
6601 const blob = new Blob(payload);
6602 msg = blob;
6603 }
6604 this.$sendMsg(msg);
6605 }
6606 $sendMsg(msg) {
6607 if (this.$socket && this.$socket.readyState) {
6608 this.$socket.send(msg);
6609 } else {
6610 this.$pendingMessages.push(msg);
6611 }
6612 }
6613 receiveError(name, error) {
6614 if (this.$errors[name] === error) return;
6615 this.$errors[name] = error;
6616 delete this.$values[name];
6617 const binding = this.$bindings[name];
6618 const evt = import_jquery39.default.Event("shiny:error");
6619 evt.name = name;
6620 evt.error = error;
6621 evt.binding = binding;
6622 (0, import_jquery39.default)(binding ? binding.el : document).trigger(evt);
6623 if (!evt.isDefaultPrevented() && binding && binding.onValueError) {
6624 binding.onValueError(evt.error);
6625 }
6626 }
6627 async receiveOutput(name, value) {
6628 const binding = this.$bindings[name];
6629 const evt = import_jquery39.default.Event("shiny:value");
6630 evt.name = name;
6631 evt.value = value;
6632 evt.binding = binding;
6633 if (this.$values[name] === value) {
6634 (0, import_jquery39.default)(binding ? binding.el : document).trigger(evt);
6635 return void 0;
6636 }
6637 this.$values[name] = value;
6638 delete this.$errors[name];
6639 (0, import_jquery39.default)(binding ? binding.el : document).trigger(evt);
6640 if (!evt.isDefaultPrevented() && binding) {
6641 await binding.onValueChange(evt.value);
6642 }
6643 return value;
6644 }
6645 async bindOutput(id, binding) {
6646 if (!id) throw new Error("Can't bind an element with no ID");
6647 this.$bindings[id] = binding;
6648 if (this.$values[id] !== void 0)
6649 await binding.onValueChange(this.$values[id]);
6650 else if (this.$errors[id] !== void 0)
6651 binding.onValueError(this.$errors[id]);
6652 return binding;
6653 }
6654 unbindOutput(id, binding) {
6655 if (this.$bindings[id] === binding) {
6656 delete this.$bindings[id];
6657 return true;
6658 } else {
6659 return false;
6660 }
6661 }
6662 // Narrows a scopeComponent -- an input or output object -- to one constrained
6663 // by nsPrefix. Returns a new object with keys removed and renamed as
6664 // necessary.
6665 _narrowScopeComponent(scopeComponent, nsPrefix) {
6666 return Object.keys(scopeComponent).filter((k2) => k2.indexOf(nsPrefix) === 0).map((k2) => ({ [k2.substring(nsPrefix.length)]: scopeComponent[k2] })).reduce((obj, pair) => import_jquery39.default.extend(obj, pair), {});
6667 }
6668 // Narrows a scope -- an object with input and output "subComponents" -- to
6669 // one constrained by the nsPrefix string.
6670 //
6671 // If nsPrefix is null or empty, returns scope without modification.
6672 //
6673 // Otherwise, returns a new object with keys in subComponents removed and
6674 // renamed as necessary.
6675 _narrowScope(scope, nsPrefix) {
6676 if (nsPrefix) {
6677 return {
6678 input: this._narrowScopeComponent(scope.input, nsPrefix),
6679 output: this._narrowScopeComponent(scope.output, nsPrefix)
6680 };
6681 }
6682 return scope;
6683 }
6684 $updateConditionals() {
6685 (0, import_jquery39.default)(document).trigger({
6686 type: "shiny:conditional"
6687 });
6688 const inputs = {};
6689 for (const name in this.$inputValues) {
6690 if (hasOwnProperty(this.$inputValues, name)) {
6691 const shortName = name.replace(/:.*/, "");
6692 inputs[shortName] = this.$inputValues[name];
6693 }
6694 }
6695 const scope = { input: inputs, output: this.$values };
6696 const conditionals = (0, import_jquery39.default)(document).find("[data-display-if]");
6697 for (let i5 = 0; i5 < conditionals.length; i5++) {
6698 const el = (0, import_jquery39.default)(conditionals[i5]);
6699 let condFunc = el.data("data-display-if-func");
6700 if (!condFunc) {
6701 const condExpr = el.attr("data-display-if");
6702 condFunc = scopeExprToFunc(condExpr);
6703 el.data("data-display-if-func", condFunc);
6704 }
6705 const nsPrefix = el.attr("data-ns-prefix");
6706 const nsScope = this._narrowScope(scope, nsPrefix);
6707 const show3 = Boolean(condFunc(nsScope));
6708 const showing = el.css("display") !== "none";
6709 if (show3 !== showing) {
6710 if (show3) {
6711 el.trigger("show");
6712 el.show();
6713 el.trigger("shown");
6714 } else {
6715 el.trigger("hide");
6716 el.hide();
6717 el.trigger("hidden");
6718 }
6719 }
6720 }
6721 }
6722 // Message handler management functions =================================
6723 // // Added in shiny init method
6724 // Shiny.addCustomMessageHandler = addCustomMessageHandler;
6725 async dispatchMessage(data) {
6726 let msgObj = {};
6727 if (typeof data === "string") {
6728 msgObj = JSON.parse(data);
6729 } else {
6730 const len = new DataView(data, 0, 1).getUint8(0);
6731 const typedv = new DataView(data, 1, len);
6732 const typebuf = [];
6733 for (let i5 = 0; i5 < len; i5++) {
6734 typebuf.push(String.fromCharCode(typedv.getUint8(i5)));
6735 }
6736 const type = typebuf.join("");
6737 data = data.slice(len + 1);
6738 msgObj.custom = {};
6739 msgObj.custom[type] = data;
6740 }
6741 const evt = import_jquery39.default.Event("shiny:message");
6742 evt.message = msgObj;
6743 (0, import_jquery39.default)(document).trigger(evt);
6744 if (evt.isDefaultPrevented()) return;
6745 this.$outputProgress.updateStateFromMessage(evt.message);
6746 await this._sendMessagesToHandlers(
6747 evt.message,
6748 messageHandlers,
6749 messageHandlerOrder
6750 );
6751 this.$updateConditionals();
6752 }
6753 // Message handlers =====================================================
6754 // A function for sending messages to the appropriate handlers.
6755 // - msgObj: the object containing messages, with format {msgObj.foo, msObj.bar
6756 async _sendMessagesToHandlers(msgObj, handlers, handlerOrder) {
6757 for (let i5 = 0; i5 < handlerOrder.length; i5++) {
6758 const msgType = handlerOrder[i5];
6759 if (hasOwnProperty(msgObj, msgType)) {
6760 await handlers[msgType].call(this, msgObj[msgType]);
6761 }
6762 }
6763 }
6764 // Call showProgress() on any output bindings that have changed their
6765 // recalculating status since the last call to takeChanges().
6766 // Note that we only need to call this function when a "flush" (i.e. "values")
6767 // message or a "progress" message is received since these are the only
6768 // two types of messages that can change the recalculating status. For more,
6769 // see the state machine diagram in outputProgress.ts.
6770 _updateProgress() {
6771 const changed = this.$outputProgress.takeChanges();
6772 for (const [name, recalculating] of changed.entries()) {
6773 if (hasOwnProperty(this.$bindings, name)) {
6774 this.$bindings[name].showProgress(recalculating);
6775 }
6776 }
6777 }
6778 _init() {
6779 addMessageHandler("values", async (message) => {
6780 this._updateProgress();
6781 for (const key in message) {
6782 if (hasOwnProperty(message, key)) {
6783 await this.receiveOutput(key, message[key]);
6784 }
6785 }
6786 });
6787 addMessageHandler(
6788 "errors",
6789 (message) => {
6790 for (const key in message) {
6791 if (hasOwnProperty(message, key)) {
6792 this.receiveError(key, message[key]);
6793 }
6794 }
6795 }
6796 );
6797 addMessageHandler(
6798 "inputMessages",
6799 async (message) => {
6800 for (let i5 = 0; i5 < message.length; i5++) {
6801 const $obj = (0, import_jquery39.default)(".shiny-bound-input#" + $escape(message[i5].id));
6802 const inputBinding = $obj.data("shiny-input-binding");
6803 if ($obj.length > 0) {
6804 if (!$obj.attr("aria-live")) $obj.attr("aria-live", "polite");
6805 const el = $obj[0];
6806 const evt = import_jquery39.default.Event("shiny:updateinput");
6807 evt.message = message[i5].message;
6808 evt.binding = inputBinding;
6809 (0, import_jquery39.default)(el).trigger(evt);
6810 if (!evt.isDefaultPrevented()) {
6811 try {
6812 await inputBinding.receiveMessage(el, evt.message);
6813 } catch (error) {
6814 console.error(
6815 "[shiny] Error in inputBinding.receiveMessage()",
6816 { error, binding: inputBinding, message: evt.message }
6817 );
6818 }
6819 }
6820 }
6821 }
6822 }
6823 );
6824 addMessageHandler("javascript", (message) => {
6825 indirectEval(message);
6826 });
6827 addMessageHandler("console", (message) => {
6828 for (let i5 = 0; i5 < message.length; i5++) {
6829 if (console.log) console.log(message[i5]);
6830 }
6831 });
6832 addMessageHandler(
6833 "progress",
6834 async (message) => {
6835 if (message.type && message.message) {
6836 const handler = await this.progressHandlers[message.type];
6837 if (handler) handler.call(this, message.message);
6838 }
6839 }
6840 );
6841 addMessageHandler(
6842 "notification",
6843 async (message) => {
6844 if (message.type === "show") await show2(message.message);
6845 else if (message.type === "remove") remove2(message.message);
6846 else throw "Unkown notification type: " + message.type;
6847 }
6848 );
6849 addMessageHandler(
6850 "modal",
6851 async (message) => {
6852 if (message.type === "show") await show(message.message);
6853 else if (message.type === "remove") remove();
6854 else throw "Unkown modal type: " + message.type;
6855 }
6856 );
6857 addMessageHandler(
6858 "response",
6859 (message) => {
6860 const requestId = message.tag;
6861 const request = this.$activeRequests[requestId];
6862 if (request) {
6863 delete this.$activeRequests[requestId];
6864 if ("value" in message)
6865 request.onSuccess(message.value);
6866 else request.onError(message.error);
6867 }
6868 }
6869 );
6870 addMessageHandler("allowReconnect", (message) => {
6871 switch (message) {
6872 case true:
6873 case false:
6874 case "force":
6875 this.$allowReconnect = message;
6876 break;
6877 default:
6878 throw "Invalid value for allowReconnect: " + message;
6879 }
6880 });
6881 addMessageHandler("custom", async (message) => {
6882 const shinyOnCustomMessage = getShinyOnCustomMessage();
6883 if (shinyOnCustomMessage) await shinyOnCustomMessage(message);
6884 await this._sendMessagesToHandlers(
6885 message,
6886 customMessageHandlers,
6887 customMessageHandlerOrder
6888 );
6889 });
6890 addMessageHandler(
6891 "config",
6892 (message) => {
6893 this.config = {
6894 workerId: message.workerId,
6895 sessionId: message.sessionId
6896 };
6897 if (message.user) setShinyUser(message.user);
6898 (0, import_jquery39.default)(document).trigger("shiny:sessioninitialized");
6899 }
6900 );
6901 addMessageHandler("busy", (message) => {
6902 if (message === "busy") {
6903 (0, import_jquery39.default)(document.documentElement).addClass("shiny-busy");
6904 (0, import_jquery39.default)(document).trigger("shiny:busy");
6905 } else if (message === "idle") {
6906 (0, import_jquery39.default)(document.documentElement).removeClass("shiny-busy");
6907 (0, import_jquery39.default)(document).trigger("shiny:idle");
6908 }
6909 });
6910 addMessageHandler(
6911 "recalculating",
6912 (message) => {
6913 if (hasOwnProperty(message, "name") && hasOwnProperty(message, "status")) {
6914 const binding = this.$bindings[message.name];
6915 if (binding) {
6916 (0, import_jquery39.default)(binding.el).trigger("shiny:" + message.status);
6917 } else {
6918 (0, import_jquery39.default)().trigger("shiny:" + message.status);
6919 }
6920 }
6921 }
6922 );
6923 addMessageHandler("reload", (message) => {
6924 window.location.reload();
6925 return;
6926 message;
6927 });
6928 addMessageHandler(
6929 "shiny-insert-ui",
6930 async (message) => {
6931 const targets = (0, import_jquery39.default)(message.selector);
6932 if (targets.length === 0) {
6933 console.warn(
6934 'The selector you chose ("' + message.selector + '") could not be found in the DOM.'
6935 );
6936 await renderHtmlAsync(
6937 message.content.html,
6938 (0, import_jquery39.default)([]),
6939 message.content.deps
6940 );
6941 } else {
6942 for (const target of targets) {
6943 await renderContentAsync(target, message.content, message.where);
6944 if (message.multiple === false) break;
6945 }
6946 }
6947 }
6948 );
6949 addMessageHandler(
6950 "shiny-remove-ui",
6951 (message) => {
6952 const els = (0, import_jquery39.default)(message.selector);
6953 els.each(function(i5, el) {
6954 shinyUnbindAll(el, true);
6955 (0, import_jquery39.default)(el).remove();
6956 return message.multiple === false ? false : void 0;
6957 });
6958 }
6959 );
6960 addMessageHandler("frozen", (message) => {
6961 for (let i5 = 0; i5 < message.ids.length; i5++) {
6962 shinyForgetLastInputValue(message.ids[i5]);
6963 }
6964 });
6965 function getTabset(id) {
6966 const $tabset = (0, import_jquery39.default)("#" + $escape(id));
6967 if ($tabset.length === 0)
6968 throw "There is no tabsetPanel (or navbarPage or navlistPanel) with id equal to '" + id + "'";
6969 return $tabset;
6970 }
6971 function getTabContent($tabset) {
6972 const tabsetId = $tabset.attr("data-tabsetid");
6973 const $tabContent = (0, import_jquery39.default)(
6974 "div.tab-content[data-tabsetid='" + $escape(tabsetId) + "']"
6975 );
6976 return $tabContent;
6977 }
6978 function getTargetTabs($tabset, $tabContent, target) {
6979 const dataValue = "[data-value='" + $escape(target) + "']";
6980 const $aTag = $tabset.find("a" + dataValue);
6981 const $liTag = $aTag.parent();
6982 if ($liTag.length === 0) {
6983 throw "There is no tabPanel (or navbarMenu) with value (or menuName) equal to '" + target + "'";
6984 }
6985 const $liTags = [];
6986 const $divTags = [];
6987 if ($aTag.attr("data-toggle") === "dropdown") {
6988 const $dropdownTabset = $aTag.find("+ ul.dropdown-menu");
6989 const dropdownId = $dropdownTabset.attr("data-tabsetid");
6990 const $dropdownLiTags = $dropdownTabset.find("a[data-toggle='tab']").parent("li");
6991 $dropdownLiTags.each(function(i5, el) {
6992 $liTags.push((0, import_jquery39.default)(el));
6993 });
6994 const selector = "div.tab-pane[id^='tab-" + $escape(dropdownId) + "']";
6995 const $dropdownDivs = $tabContent.find(selector);
6996 $dropdownDivs.each(function(i5, el) {
6997 $divTags.push((0, import_jquery39.default)(el));
6998 });
6999 } else {
7000 $divTags.push($tabContent.find("div" + dataValue));
7001 }
7002 return { $liTag, $liTags, $divTags };
7003 }
7004 addMessageHandler(
7005 "shiny-insert-tab",
7006 async (message) => {
7007 const $parentTabset = getTabset(message.inputId);
7008 let $tabset = $parentTabset;
7009 const $tabContent = getTabContent($tabset);
7010 let tabsetId = $parentTabset.attr("data-tabsetid");
7011 const $fragLi = (0, import_jquery39.default)("<div>");
7012 await renderContentAsync($fragLi, message.liTag, "afterBegin");
7013 const $liTag = (0, import_jquery39.default)($fragLi).find("> li");
7014 const $aTag = $liTag.find("> a");
7015 let $targetLiTag = null;
7016 if (message.target !== null) {
7017 const targetInfo = getTargetTabs(
7018 $tabset,
7019 $tabContent,
7020 message.target
7021 );
7022 $targetLiTag = targetInfo.$liTag;
7023 }
7024 const dropdown = getDropdown();
7025 if (dropdown !== null) {
7026 if ($aTag.attr("data-toggle") === "dropdown")
7027 throw "Cannot insert a navbarMenu inside another one";
7028 $tabset = dropdown.$tabset;
7029 tabsetId = dropdown.id;
7030 $liTag.removeClass("nav-item").find(".nav-link").removeClass("nav-link").addClass("dropdown-item");
7031 }
7032 let fixupDivId = "";
7033 if ($aTag.attr("data-toggle") === "tab") {
7034 const index = getTabIndex($tabset, tabsetId);
7035 const tabId = "tab-" + tabsetId + "-" + index;
7036 $liTag.find("> a").attr("href", "#" + tabId);
7037 fixupDivId = tabId;
7038 }
7039 if (message.position === "before") {
7040 if ($targetLiTag) {
7041 $targetLiTag.before($liTag);
7042 } else {
7043 $tabset.prepend($liTag);
7044 }
7045 } else if (message.position === "after") {
7046 if ($targetLiTag) {
7047 $targetLiTag.after($liTag);
7048 } else {
7049 $tabset.append($liTag);
7050 }
7051 }
7052 await shinyBindAll($targetLiTag?.parent() || $tabset);
7053 await renderContentAsync($tabContent[0], message.divTag, "beforeEnd");
7054 if (fixupDivId) {
7055 $tabContent.find('[id="tab-tsid-id"]').attr("id", fixupDivId);
7056 }
7057 if (message.select) {
7058 $liTag.find("a").tab("show");
7059 }
7060 function getTabIndex($tabset2, tabsetId2) {
7061 const existingTabIds = [0];
7062 $tabset2.find("> li").each(function() {
7063 const $tab = (0, import_jquery39.default)(this).find("> a[data-toggle='tab']");
7064 if ($tab.length > 0) {
7065 const href = $tab.attr("href").replace(/.*(?=#[^\s]+$)/, "");
7066 const index = href.replace("#tab-" + tabsetId2 + "-", "");
7067 existingTabIds.push(Number(index));
7068 }
7069 });
7070 return Math.max.apply(null, existingTabIds) + 1;
7071 }
7072 function getDropdown() {
7073 if (message.menuName !== null) {
7074 const $dropdownATag = (0, import_jquery39.default)(
7075 "a.dropdown-toggle[data-value='" + $escape(message.menuName) + "']"
7076 );
7077 if ($dropdownATag.length === 0) {
7078 throw "There is no navbarMenu with menuName equal to '" + message.menuName + "'";
7079 }
7080 const $dropdownTabset = $dropdownATag.find("+ ul.dropdown-menu");
7081 const dropdownId = $dropdownTabset.attr("data-tabsetid");
7082 return { $tabset: $dropdownTabset, id: dropdownId };
7083 } else if (message.target !== null && $targetLiTag !== null) {
7084 const $uncleTabset = $targetLiTag.parent("ul");
7085 if ($uncleTabset.hasClass("dropdown-menu")) {
7086 const uncleId = $uncleTabset.attr("data-tabsetid");
7087 return { $tabset: $uncleTabset, id: uncleId };
7088 }
7089 }
7090 return null;
7091 }
7092 }
7093 );
7094 function ensureTabsetHasVisibleTab($tabset) {
7095 const inputBinding = $tabset.data("shiny-input-binding");
7096 if (!inputBinding.getValue($tabset)) {
7097 const destTabValue = getFirstTab($tabset);
7098 const evt = import_jquery39.default.Event("shiny:updateinput");
7099 evt.binding = inputBinding;
7100 $tabset.trigger(evt);
7101 inputBinding.setValue($tabset[0], destTabValue);
7102 }
7103 }
7104 function getFirstTab($ul) {
7105 return $ul.find("li:visible a[data-toggle='tab']").first().attr("data-value") || null;
7106 }
7107 function tabApplyFunction(target, func, liTags = false) {
7108 import_jquery39.default.each(target, function(key, el) {
7109 if (key === "$liTag") {
7110 func(el);
7111 } else if (key === "$divTags") {
7112 import_jquery39.default.each(
7113 el,
7114 function(i5, div) {
7115 func(div);
7116 }
7117 );
7118 } else if (liTags && key === "$liTags") {
7119 import_jquery39.default.each(
7120 el,
7121 function(i5, div) {
7122 func(div);
7123 }
7124 );
7125 }
7126 });
7127 }
7128 addMessageHandler(
7129 "shiny-remove-tab",
7130 (message) => {
7131 const $tabset = getTabset(message.inputId);
7132 const $tabContent = getTabContent($tabset);
7133 const target = getTargetTabs($tabset, $tabContent, message.target);
7134 tabApplyFunction(target, removeEl);
7135 ensureTabsetHasVisibleTab($tabset);
7136 function removeEl($el) {
7137 shinyUnbindAll($el, true);
7138 $el.remove();
7139 }
7140 }
7141 );
7142 addMessageHandler(
7143 "shiny-change-tab-visibility",
7144 (message) => {
7145 const $tabset = getTabset(message.inputId);
7146 const $tabContent = getTabContent($tabset);
7147 const target = getTargetTabs($tabset, $tabContent, message.target);
7148 tabApplyFunction(target, changeVisibility, true);
7149 ensureTabsetHasVisibleTab($tabset);
7150 function changeVisibility($el) {
7151 if (message.type === "show") $el.css("display", "");
7152 else if (message.type === "hide") {
7153 $el.hide();
7154 $el.removeClass("active");
7155 }
7156 }
7157 }
7158 );
7159 addMessageHandler(
7160 "updateQueryString",
7161 (message) => {
7162 if (message.mode === "replace") {
7163 window.history.replaceState(null, null, message.queryString);
7164 return;
7165 }
7166 let what = null;
7167 if (message.queryString.charAt(0) === "#") what = "hash";
7168 else if (message.queryString.charAt(0) === "?") what = "query";
7169 else
7170 throw "The 'query' string must start with either '?' (to update the query string) or with '#' (to update the hash).";
7171 const path = window.location.pathname;
7172 const oldQS = window.location.search;
7173 const oldHash = window.location.hash;
7174 let relURL = path;
7175 if (what === "query") relURL += message.queryString;
7176 else relURL += oldQS + message.queryString;
7177 window.history.pushState(null, null, relURL);
7178 if (message.queryString.indexOf("#") !== -1) what = "hash";
7179 if (window.location.hash !== oldHash) what = "hash";
7180 if (what === "hash") (0, import_jquery39.default)(document).trigger("hashchange");
7181 }
7182 );
7183 addMessageHandler(
7184 "resetBrush",
7185 (message) => {
7186 resetBrush(message.brushId);
7187 }
7188 );
7189 }
7190 //// 2021/03: TypeScript Conversion
7191 // Added in `./shiny/init.ts` as there are no instances of progressHandlers being used right away on GitHub
7192 // Shiny.progressHandlers = this.progressHandlers;
7193 // Returns a URL which can be queried to get values from inside the server
7194 // function. This is enabled with `options(shiny.testmode=TRUE)`.
7195 getTestSnapshotBaseUrl({ fullUrl = true } = {}) {
7196 const loc = window.location;
7197 let url = "";
7198 if (fullUrl) {
7199 url = loc.origin + loc.pathname.replace(/\/[^/]*$/, "");
7200 }
7201 url += "/session/" + encodeURIComponent(this.config.sessionId) + "/dataobj/shinytest?w=" + encodeURIComponent(this.config.workerId) + "&nonce=" + randomId();
7202 return url;
7203 }
7204 };
7205
7206 // srcts/src/shiny/index.ts
7207 var ShinyClass = class {
7208 constructor() {
7209 this.version = "1.13.0";
7210 const { inputBindings, fileInputBinding: fileInputBinding2 } = initInputBindings();
7211 const { outputBindings } = initOutputBindings();
7212 setFileInputBinding(fileInputBinding2);
7213 this.$escape = $escape;
7214 this.compareVersion = compareVersion;
7215 this.inputBindings = inputBindings;
7216 this.InputBinding = InputBinding;
7217 this.outputBindings = outputBindings;
7218 this.OutputBinding = OutputBinding;
7219 this.resetBrush = resetBrush;
7220 this.notifications = {
7221 show: show2,
7222 remove: remove2
7223 };
7224 this.modal = { show, remove };
7225 this.addCustomMessageHandler = addCustomMessageHandler;
7226 this.showReconnectDialog = showReconnectDialog;
7227 this.hideReconnectDialog = hideReconnectDialog;
7228 this.renderDependenciesAsync = renderDependenciesAsync;
7229 this.renderDependencies = renderDependencies;
7230 this.renderContentAsync = renderContentAsync;
7231 this.renderContent = renderContent;
7232 this.renderHtmlAsync = renderHtmlAsync;
7233 this.renderHtml = renderHtml2;
7234 this.initializedPromise = createInitStatus();
7235 (0, import_jquery40.default)(() => {
7236 setTimeout(async () => {
7237 try {
7238 await this.initialize();
7239 } catch (e4) {
7240 showErrorInClientConsole(e4);
7241 throw e4;
7242 }
7243 }, 1);
7244 });
7245 }
7246 /**
7247 * Method to check if Shiny is running in development mode. By packaging as a
7248 * method, we can we can avoid needing to look for the `__SHINY_DEV_MODE__`
7249 * variable in the global scope.
7250 * @returns `true` if Shiny is running in development mode, `false` otherwise.
7251 */
7252 inDevMode() {
7253 return isShinyInDevMode();
7254 }
7255 async initialize() {
7256 setShinyObj(this);
7257 this.shinyapp = new ShinyApp();
7258 const shinyapp = this.shinyapp;
7259 this.progressHandlers = shinyapp.progressHandlers;
7260 const inputBatchSender = new InputBatchSender(shinyapp);
7261 const inputsNoResend = new InputNoResendDecorator(inputBatchSender);
7262 const inputsEvent = new InputEventDecorator(inputsNoResend);
7263 const inputsRate = new InputRateDecorator(inputsEvent);
7264 const inputsDefer = new InputDeferDecorator(inputsEvent);
7265 let target;
7266 if (document.querySelector(".shiny-submit-button")) {
7267 target = inputsDefer;
7268 document.querySelectorAll(".shiny-submit-button").forEach(function(x2) {
7269 x2.addEventListener("click", function(event) {
7270 event.preventDefault();
7271 inputsDefer.submit();
7272 });
7273 });
7274 } else {
7275 target = inputsRate;
7276 }
7277 const inputs = new InputValidateDecorator(target);
7278 this.setInputValue = this.onInputChange = function(name, value, opts = {}) {
7279 const newOpts = addDefaultInputOpts(opts);
7280 inputs.setInput(name, value, newOpts);
7281 };
7282 this.forgetLastInputValue = function(name) {
7283 inputsNoResend.forget(name);
7284 };
7285 const inputBindings = this.inputBindings;
7286 const outputBindings = this.outputBindings;
7287 const shinyBindCtx = () => {
7288 return {
7289 inputs,
7290 inputsRate,
7291 sendOutputHiddenState,
7292 maybeAddThemeObserver,
7293 inputBindings,
7294 outputBindings,
7295 initDeferredIframes,
7296 outputIsRecalculating: (id) => this.shinyapp?.$outputProgress.isRecalculating(id) ?? false
7297 };
7298 };
7299 this.bindAll = async function(scope) {
7300 await bindAll(shinyBindCtx(), scope);
7301 };
7302 this.unbindAll = function(scope, includeSelf = false) {
7303 unbindAll(shinyBindCtx(), scope, includeSelf);
7304 };
7305 function initializeInputs(scope = document.documentElement) {
7306 const bindings = inputBindings.getBindings();
7307 for (let i5 = 0; i5 < bindings.length; i5++) {
7308 const binding = bindings[i5].binding;
7309 const inputObjects = binding.find(scope);
7310 if (inputObjects) {
7311 for (let j2 = 0; j2 < inputObjects.length; j2++) {
7312 const $inputObjectJ = (0, import_jquery40.default)(inputObjects[j2]);
7313 if (!$inputObjectJ.data("_shiny_initialized")) {
7314 $inputObjectJ.data("_shiny_initialized", true);
7315 binding.initialize(inputObjects[j2]);
7316 }
7317 }
7318 }
7319 }
7320 }
7321 this.initializeInputs = initializeInputs;
7322 function getIdFromEl(el) {
7323 const $el = (0, import_jquery40.default)(el);
7324 const bindingAdapter = $el.data("shiny-output-binding");
7325 if (!bindingAdapter) return null;
7326 else return bindingAdapter.getId();
7327 }
7328 initializeInputs(document.documentElement);
7329 const initialValues = mapValues(
7330 await _bindAll(shinyBindCtx(), document.documentElement),
7331 (x2) => x2.value
7332 );
7333 (0, import_jquery40.default)(".shiny-image-output, .shiny-plot-output, .shiny-report-size").each(
7334 function() {
7335 const id = getIdFromEl(this), rect = getBoundingClientSizeBeforeZoom(this);
7336 if (rect.width !== 0 || rect.height !== 0) {
7337 initialValues[".clientdata_output_" + id + "_width"] = rect.width;
7338 initialValues[".clientdata_output_" + id + "_height"] = rect.height;
7339 }
7340 }
7341 );
7342 function getComputedBgColor(el) {
7343 if (!el) {
7344 return null;
7345 }
7346 const bgColor = getStyle(el, "background-color");
7347 if (!bgColor) return bgColor;
7348 const m2 = bgColor.match(
7349 /^rgba\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)$/
7350 );
7351 if (bgColor === "transparent" || m2 && parseFloat(m2[4]) === 0) {
7352 const bgImage = getStyle(el, "background-image");
7353 if (bgImage && bgImage !== "none") {
7354 return null;
7355 } else {
7356 return getComputedBgColor(el.parentElement);
7357 }
7358 }
7359 return bgColor;
7360 }
7361 function getComputedFont(el) {
7362 const fontFamily = getStyle(el, "font-family");
7363 const fontSize = getStyle(el, "font-size");
7364 return {
7365 families: fontFamily?.replace(/"/g, "").split(", "),
7366 size: fontSize
7367 };
7368 }
7369 (0, import_jquery40.default)(".shiny-image-output, .shiny-plot-output, .shiny-report-theme").each(
7370 function() {
7371 const el = this;
7372 const id = getIdFromEl(el);
7373 initialValues[".clientdata_output_" + id + "_bg"] = getComputedBgColor(el);
7374 initialValues[".clientdata_output_" + id + "_fg"] = getStyle(
7375 el,
7376 "color"
7377 );
7378 initialValues[".clientdata_output_" + id + "_accent"] = getComputedLinkColor(el);
7379 initialValues[".clientdata_output_" + id + "_font"] = getComputedFont(el);
7380 maybeAddThemeObserver(el);
7381 }
7382 );
7383 function maybeAddThemeObserver(el) {
7384 if (!window.MutationObserver) {
7385 return;
7386 }
7387 const cl = el.classList;
7388 const reportTheme = cl.contains("shiny-image-output") || cl.contains("shiny-plot-output") || cl.contains("shiny-report-theme");
7389 if (!reportTheme) {
7390 return;
7391 }
7392 const $el = (0, import_jquery40.default)(el);
7393 if ($el.data("shiny-theme-observer")) {
7394 return;
7395 }
7396 const observerCallback = new Debouncer(null, () => doSendTheme(el), 100);
7397 const observer = new MutationObserver(
7398 () => observerCallback.normalCall()
7399 );
7400 const config = { attributes: true, attributeFilter: ["style", "class"] };
7401 observer.observe(el, config);
7402 $el.data("shiny-theme-observer", observer);
7403 }
7404 function doSendTheme(el) {
7405 if (el.classList.contains("shiny-output-error")) {
7406 return;
7407 }
7408 const id = getIdFromEl(el);
7409 inputs.setInput(
7410 ".clientdata_output_" + id + "_bg",
7411 getComputedBgColor(el)
7412 );
7413 inputs.setInput(
7414 ".clientdata_output_" + id + "_fg",
7415 getStyle(el, "color")
7416 );
7417 inputs.setInput(
7418 ".clientdata_output_" + id + "_accent",
7419 getComputedLinkColor(el)
7420 );
7421 inputs.setInput(
7422 ".clientdata_output_" + id + "_font",
7423 getComputedFont(el)
7424 );
7425 }
7426 function doSendImageSize() {
7427 (0, import_jquery40.default)(".shiny-image-output, .shiny-plot-output, .shiny-report-size").each(
7428 function() {
7429 const id = getIdFromEl(this), rect = getBoundingClientSizeBeforeZoom(this);
7430 if (rect.width !== 0 || rect.height !== 0) {
7431 inputs.setInput(".clientdata_output_" + id + "_width", rect.width);
7432 inputs.setInput(
7433 ".clientdata_output_" + id + "_height",
7434 rect.height
7435 );
7436 }
7437 }
7438 );
7439 (0, import_jquery40.default)(".shiny-image-output, .shiny-plot-output, .shiny-report-theme").each(
7440 function() {
7441 doSendTheme(this);
7442 }
7443 );
7444 (0, import_jquery40.default)(".shiny-bound-output").each(function() {
7445 const $this = (0, import_jquery40.default)(this), binding = $this.data("shiny-output-binding");
7446 $this.trigger({
7447 type: "shiny:visualchange",
7448 // @ts-expect-error; Can not remove info on a established, malformed Event object
7449 visible: !isHidden(this),
7450 binding
7451 });
7452 binding.onResize();
7453 });
7454 }
7455 sendImageSizeFns.setImageSend(inputBatchSender, doSendImageSize);
7456 function isHidden(obj) {
7457 if (obj === null || obj.offsetWidth !== 0 || obj.offsetHeight !== 0) {
7458 return false;
7459 } else if (getStyle(obj, "display") === "none") {
7460 return true;
7461 } else {
7462 return isHidden(obj.parentNode);
7463 }
7464 }
7465 let lastKnownVisibleOutputs = {};
7466 (0, import_jquery40.default)(".shiny-bound-output").each(function() {
7467 const id = getIdFromEl(this);
7468 if (isHidden(this)) {
7469 initialValues[".clientdata_output_" + id + "_hidden"] = true;
7470 } else {
7471 lastKnownVisibleOutputs[id] = true;
7472 initialValues[".clientdata_output_" + id + "_hidden"] = false;
7473 }
7474 });
7475 function doSendOutputHiddenState() {
7476 const visibleOutputs = {};
7477 (0, import_jquery40.default)(".shiny-bound-output").each(function() {
7478 const id = getIdFromEl(this);
7479 delete lastKnownVisibleOutputs[id];
7480 const hidden = isHidden(this), evt = {
7481 type: "shiny:visualchange",
7482 visible: !hidden
7483 };
7484 if (hidden) {
7485 inputs.setInput(".clientdata_output_" + id + "_hidden", true);
7486 } else {
7487 visibleOutputs[id] = true;
7488 inputs.setInput(".clientdata_output_" + id + "_hidden", false);
7489 }
7490 const $this = (0, import_jquery40.default)(this);
7491 evt.binding = $this.data("shiny-output-binding");
7492 $this.trigger(evt);
7493 });
7494 for (const name in lastKnownVisibleOutputs) {
7495 if (hasDefinedProperty(lastKnownVisibleOutputs, name))
7496 inputs.setInput(".clientdata_output_" + name + "_hidden", true);
7497 }
7498 lastKnownVisibleOutputs = visibleOutputs;
7499 }
7500 const sendOutputHiddenStateDebouncer = new Debouncer(
7501 null,
7502 doSendOutputHiddenState,
7503 0
7504 );
7505 function sendOutputHiddenState() {
7506 sendOutputHiddenStateDebouncer.normalCall();
7507 }
7508 inputBatchSender.lastChanceCallback.push(function() {
7509 if (sendOutputHiddenStateDebouncer.isPending())
7510 sendOutputHiddenStateDebouncer.immediateCall();
7511 });
7512 function filterEventsByNamespace(namespace, handler, ...args) {
7513 const namespaceArr = namespace.split(".");
7514 return function(e4) {
7515 const eventNamespace = e4.namespace?.split(".") ?? [];
7516 for (let i5 = 0; i5 < namespaceArr.length; i5++) {
7517 if (eventNamespace.indexOf(namespaceArr[i5]) === -1) return;
7518 }
7519 handler.apply(this, [namespaceArr, handler, ...args]);
7520 };
7521 }
7522 (0, import_jquery40.default)(window).resize(debounce(500, sendImageSizeFns.regular));
7523 const bs3classes = [
7524 "modal",
7525 "dropdown",
7526 "tab",
7527 "tooltip",
7528 "popover",
7529 "collapse"
7530 ];
7531 import_jquery40.default.each(bs3classes, function(idx, classname) {
7532 (0, import_jquery40.default)(document.body).on(
7533 "shown.bs." + classname + ".sendImageSize",
7534 "*",
7535 filterEventsByNamespace("bs", sendImageSizeFns.regular)
7536 );
7537 (0, import_jquery40.default)(document.body).on(
7538 "shown.bs." + classname + ".sendOutputHiddenState hidden.bs." + classname + ".sendOutputHiddenState",
7539 "*",
7540 filterEventsByNamespace("bs", sendOutputHiddenState)
7541 );
7542 });
7543 (0, import_jquery40.default)(document.body).on("shown.sendImageSize", "*", sendImageSizeFns.regular);
7544 (0, import_jquery40.default)(document.body).on(
7545 "shown.sendOutputHiddenState hidden.sendOutputHiddenState",
7546 "*",
7547 sendOutputHiddenState
7548 );
7549 initialValues[".clientdata_pixelratio"] = pixelRatio();
7550 (0, import_jquery40.default)(window).resize(function() {
7551 inputs.setInput(".clientdata_pixelratio", pixelRatio());
7552 });
7553 initialValues[".clientdata_url_protocol"] = window.location.protocol;
7554 initialValues[".clientdata_url_hostname"] = window.location.hostname;
7555 initialValues[".clientdata_url_port"] = window.location.port;
7556 initialValues[".clientdata_url_pathname"] = window.location.pathname;
7557 initialValues[".clientdata_url_search"] = window.location.search;
7558 (0, import_jquery40.default)(window).on("pushstate", function(e4) {
7559 inputs.setInput(".clientdata_url_search", window.location.search);
7560 return;
7561 e4;
7562 });
7563 (0, import_jquery40.default)(window).on("popstate", function(e4) {
7564 inputs.setInput(".clientdata_url_search", window.location.search);
7565 return;
7566 e4;
7567 });
7568 initialValues[".clientdata_url_hash_initial"] = window.location.hash;
7569 initialValues[".clientdata_url_hash"] = window.location.hash;
7570 (0, import_jquery40.default)(window).on("hashchange", function(e4) {
7571 inputs.setInput(".clientdata_url_hash", window.location.hash);
7572 return;
7573 e4;
7574 });
7575 const singletonText = initialValues[".clientdata_singletons"] = (0, import_jquery40.default)(
7576 'script[type="application/shiny-singletons"]'
7577 ).text();
7578 registerNames(singletonText.split(/,/));
7579 const dependencyText = (0, import_jquery40.default)(
7580 'script[type="application/html-dependencies"]'
7581 ).text();
7582 import_jquery40.default.each(dependencyText.split(/;/), function(i5, depStr) {
7583 const match = /\s*^(.+)\[(.+)\]\s*$/.exec(depStr);
7584 if (match) {
7585 registerDependency(match[1], match[2]);
7586 }
7587 });
7588 inputsNoResend.reset(initialValues);
7589 shinyapp.connect(initialValues);
7590 (0, import_jquery40.default)(document).one("shiny:connected", () => {
7591 initDeferredIframes();
7592 });
7593 (0, import_jquery40.default)(document).one("shiny:sessioninitialized", () => {
7594 this.initializedPromise.resolve();
7595 });
7596 }
7597 };
7598 function initDeferredIframes() {
7599 if (
7600 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
7601 // @ts-ignore; Do not want to define `window.Shiny` as a type to discourage usage of `window.Shiny`;
7602 // Can not expect error when combining with window available Shiny definition
7603 !window.Shiny || // eslint-disable-next-line @typescript-eslint/ban-ts-comment
7604 // @ts-ignore; Do not want to define `window.Shiny` as a type to discourage usage of `window.Shiny`;
7605 // Can not expect error when combining with window available Shiny definition
7606 !window.Shiny.shinyapp || // eslint-disable-next-line @typescript-eslint/ban-ts-comment
7607 // @ts-ignore; Do not want to define `window.Shiny` as a type to discourage usage of `window.Shiny`;
7608 // Can not expect error when combining with window available Shiny definition
7609 !window.Shiny.shinyapp.isConnected()
7610 ) {
7611 return;
7612 }
7613 (0, import_jquery40.default)(".shiny-frame-deferred").each(function(i5, el) {
7614 const $el = (0, import_jquery40.default)(el);
7615 $el.removeClass("shiny-frame-deferred");
7616 $el.attr("src", $el.attr("data-deferred-src"));
7617 $el.attr("data-deferred-src", null);
7618 });
7619 }
7620
7621 // srcts/src/window/userAgent.ts
7622 function windowUserAgent() {
7623 return window.navigator.userAgent;
7624 }
7625
7626 // srcts/src/shiny/reactlog.ts
7627 var import_jquery41 = __toESM(require_jquery());
7628 function shinyAppConfig() {
7629 return shinyShinyApp().config;
7630 }
7631 function initReactlog() {
7632 (0, import_jquery41.default)(document).on("keydown", function(e4) {
7633 if (e4.which !== 114 || !e4.ctrlKey && !e4.metaKey || e4.shiftKey || e4.altKey)
7634 return;
7635 const url = "reactlog?w=" + window.escape(shinyAppConfig().workerId) + "&s=" + window.escape(shinyAppConfig().sessionId);
7636 window.open(url);
7637 e4.preventDefault();
7638 });
7639 (0, import_jquery41.default)(document).on("keydown", function(e4) {
7640 if (
7641 // if not one of the key combos below
7642 !// cmd/ctrl + fn + f4
7643 (e4.which === 115 && (e4.ctrlKey || e4.metaKey) && !e4.shiftKey && !e4.altKey || // cmd/ctrl + shift + fn + f3
7644 e4.which === 114 && (e4.ctrlKey || e4.metaKey) && e4.shiftKey && !e4.altKey)
7645 ) {
7646 return;
7647 }
7648 const url = "reactlog/mark?w=" + window.escape(shinyAppConfig().workerId) + "&s=" + window.escape(shinyAppConfig().sessionId);
7649 import_jquery41.default.get(url, function(result) {
7650 if (result !== "marked") return;
7651 const html = '<span id="shiny-reactlog-mark-text">Marked time point in reactlog</span>';
7652 show2({
7653 html,
7654 closeButton: true
7655 });
7656 }).fail(function() {
7657 window.open(url);
7658 });
7659 e4.preventDefault();
7660 });
7661 }
7662
7663 // srcts/src/initialize/index.ts
7664 var Shiny;
7665 function init() {
7666 if (window.Shiny) {
7667 throw new Error("Trying to create window.Shiny, but it already exists!");
7668 }
7669 Shiny = window.Shiny = new ShinyClass();
7670 setUserAgent(windowUserAgent());
7671 determineBrowserInfo();
7672 trackHistory();
7673 disableFormSubmission();
7674 initReactlog();
7675 }
7676
7677 // srcts/src/index.ts
7678 init();
7679 })();
7680 /*! Bundled license information:
7681
7682 @lit/reactive-element/css-tag.js:
7683 (**
7684 * @license
7685 * Copyright 2019 Google LLC
7686 * SPDX-License-Identifier: BSD-3-Clause
7687 *)
7688
7689 @lit/reactive-element/reactive-element.js:
7690 lit-html/lit-html.js:
7691 lit-element/lit-element.js:
7692 (**
7693 * @license
7694 * Copyright 2017 Google LLC
7695 * SPDX-License-Identifier: BSD-3-Clause
7696 *)
7697
7698 lit-html/is-server.js:
7699 (**
7700 * @license
7701 * Copyright 2022 Google LLC
7702 * SPDX-License-Identifier: BSD-3-Clause
7703 *)
7704 */
7705 //# sourceMappingURL=shiny.js.map