streamlit-nightly 1.39.1.dev20241101__py2.py3-none-any.whl → 1.39.1.dev20241103__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,6 +16,7 @@ from __future__ import annotations
16
16
 
17
17
  import os
18
18
  from itertools import dropwhile
19
+ from pathlib import Path
19
20
  from typing import Literal, NoReturn
20
21
 
21
22
  import streamlit as st
@@ -146,7 +147,7 @@ def rerun( # type: ignore[misc]
146
147
 
147
148
 
148
149
  @gather_metrics("switch_page")
149
- def switch_page(page: str | StreamlitPage) -> NoReturn: # type: ignore[misc]
150
+ def switch_page(page: str | Path | StreamlitPage) -> NoReturn: # type: ignore[misc]
150
151
  """Programmatically switch the current page in a multipage app.
151
152
 
152
153
  When ``st.switch_page`` is called, the current page execution stops and
@@ -157,7 +158,7 @@ def switch_page(page: str | StreamlitPage) -> NoReturn: # type: ignore[misc]
157
158
 
158
159
  Parameters
159
160
  ----------
160
- page: str or st.Page
161
+ page: str, Path, or st.Page
161
162
  The file path (relative to the main script) or an st.Page indicating
162
163
  the page to switch to.
163
164
 
@@ -197,6 +198,10 @@ def switch_page(page: str | StreamlitPage) -> NoReturn: # type: ignore[misc]
197
198
  if isinstance(page, StreamlitPage):
198
199
  page_script_hash = page._script_hash
199
200
  else:
201
+ # Convert Path to string if necessary
202
+ if isinstance(page, Path):
203
+ page = str(page)
204
+
200
205
  main_script_directory = get_main_script_directory(ctx.main_script_path)
201
206
  requested_page = os.path.realpath(
202
207
  normalize_path_join(main_script_directory, page)
@@ -15,6 +15,7 @@
15
15
  from __future__ import annotations
16
16
 
17
17
  import random
18
+ from pathlib import Path
18
19
  from textwrap import dedent
19
20
  from typing import TYPE_CHECKING, Any, Final, Literal, Mapping, Union, cast
20
21
 
@@ -105,6 +106,10 @@ def _get_favicon_string(page_icon: PageIcon) -> str:
105
106
  if isinstance(page_icon, str) and page_icon.startswith(":material"):
106
107
  return validate_material_icon(page_icon)
107
108
 
109
+ # Convert Path to string if necessary
110
+ if isinstance(page_icon, Path):
111
+ page_icon = str(page_icon)
112
+
108
113
  # Fall back to image_to_url.
109
114
  try:
110
115
  return image_to_url(
@@ -15,6 +15,7 @@
15
15
  from __future__ import annotations
16
16
 
17
17
  import os
18
+ from pathlib import Path
18
19
  from typing import TYPE_CHECKING, cast
19
20
 
20
21
  from streamlit.proto.Html_pb2 import Html as HtmlProto
@@ -29,7 +30,7 @@ class HtmlMixin:
29
30
  @gather_metrics("html")
30
31
  def html(
31
32
  self,
32
- body: str,
33
+ body: str | Path,
33
34
  ) -> DeltaGenerator:
34
35
  """Insert HTML into your app.
35
36
 
@@ -45,7 +46,7 @@ class HtmlMixin:
45
46
 
46
47
  Parameters
47
48
  ----------
48
- body : str
49
+ body : str, Path
49
50
  The HTML code to insert, or path to an HTML code file which is
50
51
  loaded and inserted.
51
52
 
@@ -67,8 +68,9 @@ class HtmlMixin:
67
68
 
68
69
  """
69
70
  html_proto = HtmlProto()
70
- # Check if the body is a file path
71
- if os.path.isfile(body):
71
+
72
+ # Check if the body is a file path. If it's a Path object, open it directly.
73
+ if os.path.isfile(body) or isinstance(body, Path):
72
74
  with open(body, encoding="utf-8") as f:
73
75
  html_proto.body = f.read()
74
76
  else:
@@ -63,12 +63,12 @@ class ImageMixin:
63
63
 
64
64
  Parameters
65
65
  ----------
66
- image : numpy.ndarray, [numpy.ndarray], BytesIO, str, or [str]
66
+ image : numpy.ndarray, [numpy.ndarray], BytesIO, str, [str], Path, or [Path]
67
67
  Monochrome image of shape (w,h) or (w,h,1)
68
68
  OR a color image of shape (w,h,3)
69
69
  OR an RGBA image of shape (w,h,4)
70
70
  OR a URL to fetch the image from
71
- OR a path of a local image file
71
+ OR a path of a local image file (str or Path object)
72
72
  OR an SVG XML string like `<svg xmlns=...</svg>`
73
73
  OR a list of one of the above, to display multiple images.
74
74
  caption : str or list of str
@@ -18,6 +18,7 @@ import io
18
18
  import os
19
19
  import re
20
20
  from enum import IntEnum
21
+ from pathlib import Path
21
22
  from typing import TYPE_CHECKING, Final, Literal, Sequence, Union, cast
22
23
 
23
24
  from typing_extensions import TypeAlias
@@ -38,7 +39,9 @@ if TYPE_CHECKING:
38
39
  PILImage: TypeAlias = Union[
39
40
  "ImageFile.ImageFile", "Image.Image", "GifImagePlugin.GifImageFile"
40
41
  ]
41
- AtomicImage: TypeAlias = Union[PILImage, "npt.NDArray[Any]", io.BytesIO, str, bytes]
42
+ AtomicImage: TypeAlias = Union[
43
+ PILImage, "npt.NDArray[Any]", io.BytesIO, str, Path, bytes
44
+ ]
42
45
 
43
46
  Channels: TypeAlias = Literal["RGB", "BGR"]
44
47
  ImageFormat: TypeAlias = Literal["JPEG", "PNG", "GIF"]
@@ -244,6 +247,10 @@ def image_to_url(
244
247
 
245
248
  image_data: bytes
246
249
 
250
+ # Convert Path to string if necessary
251
+ if isinstance(image, Path):
252
+ image = str(image)
253
+
247
254
  # Strings
248
255
  if isinstance(image, str):
249
256
  if not os.path.isfile(image) and url_util.is_url(
@@ -43,7 +43,14 @@ if TYPE_CHECKING:
43
43
 
44
44
 
45
45
  MediaData: TypeAlias = Union[
46
- str, bytes, io.BytesIO, io.RawIOBase, io.BufferedReader, "npt.NDArray[Any]", None
46
+ str,
47
+ Path,
48
+ bytes,
49
+ io.BytesIO,
50
+ io.RawIOBase,
51
+ io.BufferedReader,
52
+ "npt.NDArray[Any]",
53
+ None,
47
54
  ]
48
55
 
49
56
  SubtitleData: TypeAlias = Union[
@@ -78,8 +85,8 @@ class MediaMixin:
78
85
 
79
86
  Parameters
80
87
  ----------
81
- data : str, bytes, BytesIO, numpy.ndarray, or file
82
- Raw audio data, filename, or a URL pointing to the file to load.
88
+ data : str, Path, bytes, BytesIO, numpy.ndarray, or file
89
+ Raw audio data, file path (str or Path object), or a URL pointing to the file to load.
83
90
  Raw data formats must include all necessary file headers to match the file
84
91
  format specified via ``format``.
85
92
  If ``data`` is a numpy array, it must either be a 1D array of the waveform
@@ -212,8 +219,8 @@ class MediaMixin:
212
219
 
213
220
  Parameters
214
221
  ----------
215
- data : str, bytes, io.BytesIO, numpy.ndarray, or file
216
- Raw video data, filename, or URL pointing to a video to load.
222
+ data : str, Path, bytes, io.BytesIO, numpy.ndarray, or file
223
+ Raw video data, file path (str or Path object), or URL pointing to a video to load.
217
224
  Includes support for YouTube URLs.
218
225
  Numpy arrays and raw data formats must include all necessary file
219
226
  headers to match specified file format.
@@ -421,6 +428,8 @@ def _marshall_av_media(
421
428
  if isinstance(data, (str, bytes)):
422
429
  # Pass strings and bytes through unchanged
423
430
  data_or_filename = data
431
+ elif isinstance(data, Path):
432
+ data_or_filename = str(data)
424
433
  elif isinstance(data, io.BytesIO):
425
434
  data.seek(0)
426
435
  data_or_filename = data.getvalue()
@@ -467,7 +476,7 @@ def marshall_video(
467
476
  ----------
468
477
  coordinates : str
469
478
  proto : the proto to fill. Must have a string field called "data".
470
- data : str, bytes, BytesIO, numpy.ndarray, or file opened with
479
+ data : str, Path, bytes, BytesIO, numpy.ndarray, or file opened with
471
480
  io.open().
472
481
  Raw video data or a string with a URL pointing to the video
473
482
  to load. Includes support for YouTube URLs.
@@ -520,6 +529,9 @@ def marshall_video(
520
529
  # "type" distinguishes between YouTube and non-YouTube links
521
530
  proto.type = VideoProto.Type.NATIVE
522
531
 
532
+ if isinstance(data, Path):
533
+ data = str(data) # Convert Path to string
534
+
523
535
  if isinstance(data, str) and url_util.is_url(
524
536
  data, allowed_schemas=("http", "https", "data")
525
537
  ):
@@ -532,7 +544,6 @@ def marshall_video(
532
544
  )
533
545
  else:
534
546
  proto.url = data
535
-
536
547
  else:
537
548
  _marshall_av_media(coordinates, proto, data, mimetype)
538
549
 
@@ -711,7 +722,7 @@ def marshall_audio(
711
722
  ----------
712
723
  coordinates : str
713
724
  proto : The proto to fill. Must have a string field called "url".
714
- data : str, bytes, BytesIO, numpy.ndarray, or file opened with
725
+ data : str, Path, bytes, BytesIO, numpy.ndarray, or file opened with
715
726
  io.open()
716
727
  Raw audio data or a string with a URL pointing to the file to load.
717
728
  If passing the raw data, this must include headers and any other bytes
@@ -740,11 +751,13 @@ def marshall_audio(
740
751
  proto.end_time = end_time
741
752
  proto.loop = loop
742
753
 
754
+ if isinstance(data, Path):
755
+ data = str(data) # Convert Path to string
756
+
743
757
  if isinstance(data, str) and url_util.is_url(
744
758
  data, allowed_schemas=("http", "https", "data")
745
759
  ):
746
760
  proto.url = data
747
-
748
761
  else:
749
762
  data = _maybe_convert_to_wav_bytes(data, sample_rate)
750
763
  _marshall_av_media(coordinates, proto, data, mimetype)
@@ -17,6 +17,7 @@ from __future__ import annotations
17
17
  import io
18
18
  import os
19
19
  from dataclasses import dataclass
20
+ from pathlib import Path
20
21
  from textwrap import dedent
21
22
  from typing import (
22
23
  TYPE_CHECKING,
@@ -547,7 +548,7 @@ class ButtonMixin:
547
548
  @gather_metrics("page_link")
548
549
  def page_link(
549
550
  self,
550
- page: str | StreamlitPage,
551
+ page: str | Path | StreamlitPage,
551
552
  *,
552
553
  label: str | None = None,
553
554
  icon: str | None = None,
@@ -567,7 +568,7 @@ class ButtonMixin:
567
568
 
568
569
  Parameters
569
570
  ----------
570
- page : str or st.Page
571
+ page : str, Path, or st.Page
571
572
  The file path (relative to the main script) or an st.Page indicating
572
573
  the page to switch to. Alternatively, this can be the URL to an
573
574
  external page (must start with "http://" or "https://").
@@ -768,7 +769,7 @@ class ButtonMixin:
768
769
 
769
770
  def _page_link(
770
771
  self,
771
- page: str | StreamlitPage,
772
+ page: str | Path | StreamlitPage,
772
773
  *, # keyword-only arguments:
773
774
  label: str | None = None,
774
775
  icon: str | None = None,
@@ -797,6 +798,10 @@ class ButtonMixin:
797
798
  if label is None:
798
799
  page_link_proto.label = page.title
799
800
  else:
801
+ # Convert Path to string if necessary
802
+ if isinstance(page, Path):
803
+ page = str(page)
804
+
800
805
  # Handle external links:
801
806
  if is_url(page):
802
807
  if label is None or label == "":
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "files": {
3
3
  "main.css": "./static/css/main.a1bc16b2.css",
4
- "main.js": "./static/js/main.754d974e.js",
4
+ "main.js": "./static/js/main.61a89bda.js",
5
5
  "static/js/6679.265ca09c.chunk.js": "./static/js/6679.265ca09c.chunk.js",
6
6
  "static/js/9464.7e9a3c0a.chunk.js": "./static/js/9464.7e9a3c0a.chunk.js",
7
7
  "static/js/9077.721329d6.chunk.js": "./static/js/9077.721329d6.chunk.js",
@@ -19,7 +19,7 @@
19
19
  "static/js/4827.bf6d34b0.chunk.js": "./static/js/4827.bf6d34b0.chunk.js",
20
20
  "static/js/8237.86c539f3.chunk.js": "./static/js/8237.86c539f3.chunk.js",
21
21
  "static/js/5828.f8572ba4.chunk.js": "./static/js/5828.f8572ba4.chunk.js",
22
- "static/js/3224.919d670d.chunk.js": "./static/js/3224.919d670d.chunk.js",
22
+ "static/js/3224.925d380f.chunk.js": "./static/js/3224.925d380f.chunk.js",
23
23
  "static/js/9060.1ec8dc2b.chunk.js": "./static/js/9060.1ec8dc2b.chunk.js",
24
24
  "static/js/5625.a2d9a416.chunk.js": "./static/js/5625.a2d9a416.chunk.js",
25
25
  "static/js/6141.d2879825.chunk.js": "./static/js/6141.d2879825.chunk.js",
@@ -157,6 +157,6 @@
157
157
  },
158
158
  "entrypoints": [
159
159
  "static/css/main.a1bc16b2.css",
160
- "static/js/main.754d974e.js"
160
+ "static/js/main.61a89bda.js"
161
161
  ]
162
162
  }
@@ -1 +1 @@
1
- <!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"/><link rel="shortcut icon" href="./favicon.png"/><link rel="preload" href="./static/media/SourceSansPro-Regular.0d69e5ff5e92ac64a0c9.woff2" as="font" type="font/woff2" crossorigin><link rel="preload" href="./static/media/SourceSansPro-SemiBold.abed79cd0df1827e18cf.woff2" as="font" type="font/woff2" crossorigin><link rel="preload" href="./static/media/SourceSansPro-Bold.118dea98980e20a81ced.woff2" as="font" type="font/woff2" crossorigin><title>Streamlit</title><script>window.prerenderReady=!1</script><script defer="defer" src="./static/js/main.754d974e.js"></script><link href="./static/css/main.a1bc16b2.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>
1
+ <!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"/><link rel="shortcut icon" href="./favicon.png"/><link rel="preload" href="./static/media/SourceSansPro-Regular.0d69e5ff5e92ac64a0c9.woff2" as="font" type="font/woff2" crossorigin><link rel="preload" href="./static/media/SourceSansPro-SemiBold.abed79cd0df1827e18cf.woff2" as="font" type="font/woff2" crossorigin><link rel="preload" href="./static/media/SourceSansPro-Bold.118dea98980e20a81ced.woff2" as="font" type="font/woff2" crossorigin><title>Streamlit</title><script>window.prerenderReady=!1</script><script defer="defer" src="./static/js/main.61a89bda.js"></script><link href="./static/css/main.a1bc16b2.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>
@@ -0,0 +1 @@
1
+ "use strict";(self.webpackChunk_streamlit_app=self.webpackChunk_streamlit_app||[]).push([[3224],{53224:(e,t,n)=>{n.r(t),n.d(t,{default:()=>ye});var r=n(58878),a=n(8151),l=n(19613),i=n(56146),o=n(18364),s=n(95241),d=n(71034),c=n.n(d),u=n(34752),g=n(70691),p=n(25571),f=n(58144),h=n(50609),m=n.n(h),y=n(29669),b=n(67253);var w=n(93480),v=n(997),x=n(70474),C=n(35526);const j=e=>{var t;let{widgetMgr:n,id:a,formId:l,key:i,defaultValue:o}=e;(0,r.useEffect)((()=>{const e=n.getElementState(a,i);(0,p.hX)(e)&&(0,p.se)(o)&&n.setElementState(a,i,o)}),[n,a,i,o]);const[s,d]=(0,r.useState)(null!==(t=n.getElementState(a,i))&&void 0!==t?t:o),c=(0,r.useCallback)((e=>{n.setElementState(a,i,e),d(e)}),[n,a,i]),g=(0,r.useMemo)((()=>({formId:l||""})),[l]),f=(0,r.useCallback)((()=>c(o)),[o,c]);return(0,u.X)({element:g,widgetMgr:n,onFormCleared:f}),[s,c]};var k=n(84152),S=n(55562);const A=(e,t)=>{const{libConfig:{enforceDownloadInNewTab:n=!1}}=r.useContext(k.n);return(0,r.useCallback)((()=>{if(!e)return;const r=(0,S.A)({enforceDownloadInNewTab:n,url:e,filename:t});r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}),[e,n,t])};var U=n(89653),I=n(37888);const R=(0,U.A)("div",{target:"e12wn80j15"})(""),P=(0,U.A)("div",{target:"e12wn80j14"})((e=>{let{theme:t}=e;return{height:t.sizes.largestElementHeight,width:"100%",background:t.colors.secondaryBg,borderRadius:t.radii.default,marginBottom:t.spacing.twoXS,display:"flex",alignItems:"center",position:"relative",paddingLeft:t.spacing.xs,paddingRight:t.spacing.sm}}),""),T=(0,U.A)("div",{target:"e12wn80j13"})({name:"82a6rk",styles:"flex:1"}),E=(0,U.A)("div",{target:"e12wn80j12"})((e=>{let{show:t}=e;return{display:t?"block":"none"}}),""),L=(0,U.A)("span",{target:"e12wn80j11"})((e=>{let{theme:t,isPlayingOrRecording:n}=e;return{margin:t.spacing.sm,fontFamily:t.fonts.monospace,color:n?t.colors.bodyText:t.colors.fadedText60,backgroundColor:t.colors.secondaryBg,fontSize:t.fontSizes.sm}}),""),M=(0,U.A)("div",{target:"e12wn80j10"})({name:"1kyw74z",styles:"width:100%;text-align:center;overflow:hidden"}),z=(0,U.A)("span",{target:"e12wn80j9"})((e=>{let{theme:t}=e;return{color:t.colors.bodyText}}),""),F=(0,U.A)("a",{target:"e12wn80j8"})((e=>{let{theme:t}=e;return{color:t.colors.linkText,textDecoration:"underline"}}),""),W=(0,U.A)("div",{target:"e12wn80j7"})((e=>{let{theme:t}=e;return{height:t.sizes.largestElementHeight,display:"flex",justifyContent:"center",alignItems:"center"}}),""),B=(0,U.A)("div",{target:"e12wn80j6"})((e=>{let{theme:t}=e;const n="0.625em";return{opacity:.2,width:"100%",height:n,backgroundSize:n,backgroundImage:`radial-gradient(${t.colors.fadedText10} 40%, transparent 40%)`,backgroundRepeat:"repeat"}}),""),X=(0,U.A)("span",{target:"e12wn80j5"})((e=>{let{theme:t}=e;return{"& > button":{color:t.colors.primary,padding:t.spacing.threeXS},"& > button:hover, & > button:focus":{color:t.colors.red}}}),""),O=(0,U.A)("span",{target:"e12wn80j4"})((e=>{let{theme:t}=e;return{"& > button":{padding:t.spacing.threeXS,color:t.colors.fadedText40},"& > button:hover, & > button:focus":{color:t.colors.primary}}}),""),V=(0,U.A)("span",{target:"e12wn80j3"})((e=>{let{theme:t}=e;return{"& > button":{padding:t.spacing.threeXS,color:t.colors.fadedText60},"& > button:hover, & > button:focus":{color:t.colors.bodyText}}}),""),D=(0,U.A)("div",{target:"e12wn80j2"})((e=>{let{theme:t}=e;return{display:"flex",justifyContent:"center",alignItems:"center",flexGrow:0,flexShrink:1,padding:t.spacing.xs,gap:t.spacing.twoXS,marginRight:t.spacing.twoXS}}),""),N=(0,U.A)("div",{target:"e12wn80j1"})((e=>{let{theme:t}=e;return{marginLeft:t.spacing.sm}}),""),_=(0,U.A)(I.x,{target:"e12wn80j0"})((e=>{let{theme:t}=e;return{fontSize:t.fontSizes.sm,width:t.sizes.spinnerSize,height:t.sizes.spinnerSize,borderWidth:t.sizes.spinnerThickness,radius:t.radii.md,justifyContents:"center",padding:t.spacing.none,margin:t.spacing.none,borderColor:t.colors.borderColor,borderTopColor:t.colors.primary,flexGrow:0,flexShrink:0}}),"");var G=n(39095),H=n(90782);const K=()=>(0,H.jsxs)(M,{children:[(0,H.jsx)(z,{children:"This app would like to use your microphone."})," ",(0,H.jsx)(F,{href:G.ML,children:"Learn how to allow access."})]}),$=()=>(0,H.jsx)(W,{children:(0,H.jsx)(B,{})}),Y="00:00",Z=e=>new Date(e).toLocaleTimeString(void 0,{minute:"2-digit",second:"2-digit"});var q=n(96626),J=n(34783),Q=n(37789),ee=n(14757),te=n(88685),ne=n(36459),re=n(84720),ae=n(64611);const le=e=>{let{onClick:t,disabled:n,ariaLabel:r,iconContent:a}=e;return(0,H.jsx)(ne.Ay,{kind:re.KX.BORDERLESS_ICON,onClick:t,disabled:n,"aria-label":r,fluidWidth:!0,"data-testid":"stAudioInputActionButton",children:(0,H.jsx)(ae.A,{content:a,size:"lg",color:"inherit"})})},ie=e=>{let{disabled:t,stopRecording:n}=e;return(0,H.jsx)(X,{children:(0,H.jsx)(le,{onClick:n,disabled:t,ariaLabel:"Stop recording",iconContent:J.X})})},oe=e=>{let{disabled:t,isPlaying:n,onClickPlayPause:r}=e;return(0,H.jsx)(V,{children:n?(0,H.jsx)(le,{onClick:r,disabled:t,ariaLabel:"Pause",iconContent:Q.v}):(0,H.jsx)(le,{onClick:r,disabled:t,ariaLabel:"Play",iconContent:ee.S})})},se=e=>{let{disabled:t,startRecording:n}=e;return(0,H.jsx)(O,{children:(0,H.jsx)(le,{onClick:n,disabled:t,ariaLabel:"Record",iconContent:q.G})})},de=e=>{let{onClick:t}=e;return(0,H.jsx)(V,{children:(0,H.jsx)(le,{disabled:!1,onClick:t,ariaLabel:"Reset",iconContent:te.C})})},ce=e=>{let{disabled:t,isRecording:n,isPlaying:r,isUploading:a,isError:l,recordingUrlExists:i,startRecording:o,stopRecording:s,onClickPlayPause:d,onClear:c}=e;return l?(0,H.jsx)(D,{children:(0,H.jsx)(de,{onClick:c})}):a?(0,H.jsx)(D,{children:(0,H.jsx)(_,{"aria-label":"Uploading"})}):(0,H.jsxs)(D,{children:[n?(0,H.jsx)(ie,{disabled:t,stopRecording:s}):(0,H.jsx)(se,{disabled:t,startRecording:o}),i&&(0,H.jsx)(oe,{disabled:t,isPlaying:r,onClickPlayPause:d})]})},ue=(0,r.memo)(ce);var ge=n(84996);function pe(e,t,n){for(let r=0;r<n.length;r++,t+=2){const a=Math.max(-1,Math.min(1,n[r]));e.setInt16(t,a<0?32768*a:32767*a,!0)}}const fe=async function(e){const t=new window.AudioContext,n=await e.arrayBuffer();let r;try{r=await t.decodeAudioData(n)}catch(u){return void(0,ge.vV)(u)}const a=r.numberOfChannels,l=r.sampleRate,i=r.length*a*2+44,o=new ArrayBuffer(i),s=new DataView(o),d={0:{type:"string",value:"RIFF"},4:{type:"uint32",value:36+2*r.length*a},8:{type:"string",value:"WAVE"},12:{type:"string",value:"fmt "},16:{type:"uint32",value:16},20:{type:"uint16",value:1},22:{type:"uint16",value:a},24:{type:"uint32",value:l},28:{type:"uint32",value:l*a*2},32:{type:"uint16",value:2*a},34:{type:"uint16",value:16},36:{type:"string",value:"data"},40:{type:"uint32",value:r.length*a*2}};Object.entries(d).forEach((e=>{let[t,{type:n,value:r}]=e;const a=parseInt(t,10);"string"===n?function(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}(s,a,r):"uint32"===n?s.setUint32(a,r,!0):"uint16"===n&&s.setUint16(a,r,!0)}));for(let g=0;g<a;g++)pe(s,44+g*r.length*2,r.getChannelData(g));const c=new Uint8Array(o);return new Blob([c],{type:"audio/wav"})},he=()=>(0,H.jsx)(M,{children:(0,H.jsx)(z,{children:"An error has occurred, please try again."})}),me=e=>{var t;let{element:n,uploadClient:d,widgetMgr:h,fragmentId:k,disabled:S}=e;const U=(0,a.u)(),I=(0,C.Z)(U),[M,z]=(0,r.useState)(null),F=r.useRef(null),[W,B]=j({widgetMgr:h,id:n.id,key:"deleteFileUrl",defaultValue:null}),[X,O]=(0,r.useState)(null),[V,D]=(0,r.useState)([]),[_,G]=(0,r.useState)(null),[q,J]=j({widgetMgr:h,id:n.id,key:"recordingUrl",defaultValue:null}),[,Q]=(0,r.useState)(0),ee=()=>{Q((e=>e+1))},[te,ne]=(0,r.useState)(Y),[re,ae]=j({widgetMgr:h,id:n.id,formId:n.formId,key:"recordingTime",defaultValue:Y}),[le,ie]=(0,r.useState)(!1),[oe,se]=(0,r.useState)(!1),[de,ce]=(0,r.useState)(!1),[ge,pe]=(0,r.useState)(!1),[me,ye]=(0,r.useState)(!1),be=n.id,we=n.formId,ve=(0,r.useCallback)((async e=>{let t;if(pe(!0),(0,p.se)(we)&&h.setFormsWithUploadsInProgress(new Set([we])),t="audio/wav"===e.type?e:await fe(e),!t)return void ye(!0);const n=URL.createObjectURL(t),r=new File([t],"audio.wav",{type:t.type});J(n),(async e=>{let{files:t,uploadClient:n,widgetMgr:r,widgetInfo:a,fragmentId:l}=e,i=[];try{i=await n.fetchFileURLs(t)}catch(c){return{successfulUploads:[],failedUploads:t.map((e=>({file:e,error:(0,b.$)(c)})))}}const o=m()(t,i),s=[],d=[];return await Promise.all(o.map((async e=>{let[t,r]=e;if(!t||!r||!r.uploadUrl||!r.fileId)return{file:t,fileUrl:r,error:new Error("No upload URL found")};try{await n.uploadFile({id:r.fileId,formId:a.formId||""},r.uploadUrl,t),s.push({fileUrl:r,file:t})}catch(c){const n=(0,b.$)(c);d.push({file:t,error:n})}}))),r.setFileUploaderStateValue(a,new y.qX({uploadedFileInfo:s.map((e=>{let{file:t,fileUrl:n}=e;return new y.HY({fileId:n.fileId,fileUrls:n,name:t.name,size:t.size})}))}),{fromUi:!0},l),{successfulUploads:s,failedUploads:d}})({files:[r],uploadClient:d,widgetMgr:h,widgetInfo:{id:be,formId:we},fragmentId:k}).then((e=>{let{successfulUploads:t,failedUploads:n}=e;if(n.length>0)return void ye(!0);const r=t[0];r&&r.fileUrl.deleteUrl&&B(r.fileUrl.deleteUrl)})).finally((()=>{(0,p.se)(we)&&h.setFormsWithUploadsInProgress(new Set),pe(!1)}))}),[J,d,h,be,we,k,B]),xe=(0,r.useCallback)((e=>{let{updateWidgetManager:t}=e;(0,p.hX)(M)||(0,p.hX)(W)||(J(null),M.empty(),d.deleteFile(W),ne(Y),ae(Y),B(null),t&&h.setFileUploaderStateValue(n,{},{fromUi:!0},k),ie(!1),(0,p.se)(q)&&URL.revokeObjectURL(q))}),[W,q,d,M,n,h,k,ae,J,B]);(0,r.useEffect)((()=>{if((0,p.hX)(we))return;const e=new u.o;return e.manageFormClearListener(h,we,(()=>{xe({updateWidgetManager:!0})})),()=>e.disconnect()}),[we,xe,h]);const Ce=(0,r.useCallback)((()=>{if(null===F.current)return;const e=l.A.create({container:F.current,waveColor:q?(0,f.au)(U.colors.fadedText40,U.colors.secondaryBg):U.colors.primary,progressColor:U.colors.bodyText,height:(0,f.BY)(U.sizes.largestElementHeight)-8,barWidth:4,barGap:4,barRadius:8,cursorWidth:0,url:null!==q&&void 0!==q?q:void 0});e.on("timeupdate",(e=>{ne(Z(1e3*e))})),e.on("pause",(()=>{ee()}));const t=e.registerPlugin(i.A.create({scrollingWaveform:!1,renderRecordedAudio:!0}));return t.on("record-end",(async e=>{ve(e)})),t.on("record-progress",(e=>{ae(Z(e))})),z(e),O(t),()=>{e&&e.destroy(),t&&t.destroy()}}),[ve]);(0,r.useEffect)((()=>Ce()),[Ce]),(0,r.useEffect)((()=>{c()(I,U)||null===M||void 0===M||M.setOptions({waveColor:q?(0,f.au)(U.colors.fadedText40,U.colors.secondaryBg):U.colors.primary,progressColor:U.colors.bodyText})}),[U,I,q,M]);const je=(0,r.useCallback)((()=>{M&&(M.playPause(),ie(!0),ee())}),[M]),ke=(0,r.useCallback)((async()=>{let e=_;de||(await navigator.mediaDevices.getUserMedia({audio:!0}).then((()=>i.A.getAvailableAudioDevices().then((t=>{if(D(t),t.length>0){const{deviceId:n}=t[0];G(n),e=n}})))).catch((e=>{se(!0)})),ce(!0)),X&&e&&M&&(M.setOptions({waveColor:U.colors.primary}),q&&xe({updateWidgetManager:!1}),X.startRecording({deviceId:e}).then((()=>{ee()})))}),[_,X,U,M,q,xe,de]),Se=(0,r.useCallback)((()=>{X&&(X.stopRecording(),null===M||void 0===M||M.setOptions({waveColor:(0,f.au)(U.colors.fadedText40,U.colors.secondaryBg)}))}),[X,M,U]),Ae=A(q,"recording.wav"),Ue=Boolean(null===X||void 0===X?void 0:X.isRecording()),Ie=Boolean(null===M||void 0===M?void 0:M.isPlaying()),Re=Ue||Ie,Pe=!Ue&&!q&&!oe,Te=oe||Pe||me,Ee=S||oe;return(0,H.jsxs)(R,{className:"stAudioInput","data-testid":"stAudioInput",children:[(0,H.jsx)(x.L,{label:n.label,disabled:Ee,labelVisibility:(0,p.yv)(null===(t=n.labelVisibility)||void 0===t?void 0:t.value),children:n.help&&(0,H.jsx)(N,{children:(0,H.jsx)(w.A,{content:n.help,placement:v.W.TOP})})}),(0,H.jsxs)(P,{children:[(0,H.jsxs)(g.A,{isFullScreen:!1,disableFullscreenMode:!0,target:P,children:[q&&(0,H.jsx)(g.K,{label:"Download as WAV",icon:o.n,onClick:()=>Ae()}),W&&(0,H.jsx)(g.K,{label:"Clear recording",icon:s.e,onClick:()=>xe({updateWidgetManager:!0})})]}),(0,H.jsx)(ue,{isRecording:Ue,isPlaying:Ie,isUploading:ge,isError:me,recordingUrlExists:Boolean(q),startRecording:ke,stopRecording:Se,onClickPlayPause:je,onClear:()=>{xe({updateWidgetManager:!1}),ye(!1)},disabled:Ee}),(0,H.jsxs)(T,{children:[me&&(0,H.jsx)(he,{}),Pe&&(0,H.jsx)($,{}),oe&&(0,H.jsx)(K,{}),(0,H.jsx)(E,{"data-testid":"stAudioInputWaveSurfer",ref:F,show:!Te})]}),(0,H.jsx)(L,{isPlayingOrRecording:Re,"data-testid":"stAudioInputWaveformTimeCode",children:le?te:re})]})]})},ye=(0,r.memo)(me)},35526:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(58878);const a=e=>{const t=(0,r.useRef)();return(0,r.useEffect)((()=>{t.current=e}),[e]),t.current}}}]);