or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

dialog-management.mddom-access.mdindex.mdinput-validation.mdstate-management.mdtimer-control.md

state-management.mddocs/

0

# State Management

1

2

Methods for checking popup state, controlling visibility, managing loading states, and updating popup content dynamically.

3

4

## Capabilities

5

6

### Visibility State

7

8

Methods to check if a popup is currently visible and control popup visibility.

9

10

```typescript { .api }

11

/**

12

* Determines if a popup is currently shown

13

* @returns True if a popup is visible, false otherwise

14

*/

15

function isVisible(): boolean;

16

17

/**

18

* Closes the currently open SweetAlert2 popup programmatically

19

* @param result - Optional result object to resolve the popup promise with

20

*/

21

function close(result?: Partial<SweetAlertResult>): void;

22

```

23

24

**Usage Examples:**

25

26

```typescript

27

// Check if popup is visible before opening another

28

if (!Swal.isVisible()) {

29

Swal.fire('No popup is currently open');

30

} else {

31

console.log('A popup is already visible');

32

}

33

34

// Close with custom result

35

Swal.close({

36

isConfirmed: false,

37

isDismissed: true,

38

dismiss: Swal.DismissReason.backdrop

39

});

40

41

// Auto-close after condition

42

setTimeout(() => {

43

if (Swal.isVisible()) {

44

Swal.close();

45

}

46

}, 5000);

47

```

48

49

### Loading State

50

51

Methods to manage loading states and spinner display.

52

53

```typescript { .api }

54

/**

55

* Determines if popup is in the loading state

56

* @returns True if loading spinner is shown, false otherwise

57

*/

58

function isLoading(): boolean;

59

60

/**

61

* Shows loader (spinner), useful with AJAX requests

62

* @param buttonToReplace - Optional button element to replace with loader

63

*/

64

function showLoading(buttonToReplace?: HTMLButtonElement | null): void;

65

66

/**

67

* Hides loader and shows back the button which was hidden by showLoading()

68

*/

69

function hideLoading(): void;

70

```

71

72

**Usage Examples:**

73

74

```typescript

75

// Show loading on confirm button

76

Swal.fire({

77

title: 'Processing...',

78

text: 'Please wait',

79

allowOutsideClick: false,

80

didOpen: () => {

81

Swal.showLoading();

82

}

83

});

84

85

// Custom loading with specific button

86

const result = await Swal.fire({

87

title: 'Upload File',

88

text: 'Select a file to upload',

89

showCancelButton: true,

90

confirmButtonText: 'Upload',

91

preConfirm: async () => {

92

Swal.showLoading(Swal.getConfirmButton());

93

94

try {

95

// Simulate upload

96

await new Promise(resolve => setTimeout(resolve, 2000));

97

return 'Upload successful';

98

} catch (error) {

99

Swal.showValidationMessage('Upload failed');

100

return false;

101

} finally {

102

Swal.hideLoading();

103

}

104

}

105

});

106

107

// Check loading state

108

if (Swal.isLoading()) {

109

console.log('Currently loading...');

110

}

111

```

112

113

### Dynamic Updates

114

115

Methods to update popup content and options while the popup is displayed.

116

117

```typescript { .api }

118

/**

119

* Updates popup options dynamically

120

* @param options - Object containing updatable options

121

*/

122

function update(options: Pick<SweetAlertOptions, SweetAlertUpdatableParameters>): void;

123

```

124

125

**Usage Examples:**

126

127

```typescript

128

// Progress indicator with updates

129

Swal.fire({

130

title: 'Processing...',

131

html: 'Progress: 0%',

132

allowOutsideClick: false,

133

didOpen: () => {

134

let progress = 0;

135

const interval = setInterval(() => {

136

progress += 10;

137

138

Swal.update({

139

html: `Progress: ${progress}%`,

140

title: progress < 100 ? 'Processing...' : 'Complete!'

141

});

142

143

if (progress >= 100) {

144

clearInterval(interval);

145

Swal.update({

146

icon: 'success',

147

confirmButtonText: 'Done'

148

});

149

}

150

}, 500);

151

}

152

});

153

154

// Dynamic content based on user interaction

155

Swal.fire({

156

title: 'Choose an option',

157

input: 'select',

158

inputOptions: {

159

'option1': 'Option 1',

160

'option2': 'Option 2',

161

'option3': 'Option 3'

162

},

163

inputPlaceholder: 'Select an option',

164

showCancelButton: true,

165

didOpen: () => {

166

const input = Swal.getInput();

167

if (input) {

168

input.addEventListener('change', (e) => {

169

const value = e.target.value;

170

let newText = '';

171

172

switch(value) {

173

case 'option1':

174

newText = 'You selected Option 1 - This is great for beginners';

175

break;

176

case 'option2':

177

newText = 'You selected Option 2 - Perfect for intermediate users';

178

break;

179

case 'option3':

180

newText = 'You selected Option 3 - Advanced users love this';

181

break;

182

}

183

184

Swal.update({

185

text: newText

186

});

187

});

188

}

189

}

190

});

191

```

192

193

### Button State Control

194

195

Methods to enable and disable buttons dynamically.

196

197

```typescript { .api }

198

/**

199

* Enables "Confirm" and "Cancel" buttons

200

*/

201

function enableButtons(): void;

202

203

/**

204

* Disables "Confirm" and "Cancel" buttons

205

*/

206

function disableButtons(): void;

207

```

208

209

**Usage Examples:**

210

211

```typescript

212

// Conditional button enabling

213

Swal.fire({

214

title: 'Terms and Conditions',

215

html: `

216

<div style="max-height: 200px; overflow-y: auto; text-align: left;">

217

<p>Please read these terms and conditions carefully...</p>

218

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>

219

</div>

220

<label style="margin-top: 15px;">

221

<input type="checkbox" id="agree-checkbox"> I agree to the terms and conditions

222

</label>

223

`,

224

showCancelButton: true,

225

confirmButtonText: 'Accept',

226

didOpen: () => {

227

Swal.disableButtons();

228

229

const checkbox = document.getElementById('agree-checkbox');

230

if (checkbox) {

231

checkbox.addEventListener('change', (e) => {

232

if (e.target.checked) {

233

Swal.enableButtons();

234

} else {

235

Swal.disableButtons();

236

}

237

});

238

}

239

}

240

});

241

242

// Async validation with button control

243

Swal.fire({

244

title: 'Enter username',

245

input: 'text',

246

inputPlaceholder: 'Username',

247

showCancelButton: true,

248

didOpen: () => {

249

const input = Swal.getInput();

250

if (input) {

251

input.addEventListener('input', async (e) => {

252

const value = e.target.value;

253

254

if (value.length < 3) {

255

Swal.disableButtons();

256

return;

257

}

258

259

// Simulate username availability check

260

Swal.disableButtons();

261

try {

262

await new Promise(resolve => setTimeout(resolve, 500));

263

// Assume username is available

264

Swal.enableButtons();

265

} catch (error) {

266

Swal.disableButtons();

267

}

268

});

269

}

270

}

271

});

272

```

273

274

## Updatable Parameters

275

276

The following parameters can be updated using the `update()` method:

277

278

```typescript { .api }

279

type SweetAlertUpdatableParameters =

280

| 'allowEscapeKey'

281

| 'allowOutsideClick'

282

| 'background'

283

| 'buttonsStyling'

284

| 'cancelButtonAriaLabel'

285

| 'cancelButtonColor'

286

| 'cancelButtonText'

287

| 'closeButtonAriaLabel'

288

| 'closeButtonHtml'

289

| 'confirmButtonAriaLabel'

290

| 'confirmButtonColor'

291

| 'confirmButtonText'

292

| 'currentProgressStep'

293

| 'customClass'

294

| 'denyButtonAriaLabel'

295

| 'denyButtonColor'

296

| 'denyButtonText'

297

| 'didClose'

298

| 'didDestroy'

299

| 'footer'

300

| 'hideClass'

301

| 'html'

302

| 'icon'

303

| 'iconColor'

304

| 'imageAlt'

305

| 'imageHeight'

306

| 'imageUrl'

307

| 'imageWidth'

308

| 'preConfirm'

309

| 'preDeny'

310

| 'progressSteps'

311

| 'reverseButtons'

312

| 'showCancelButton'

313

| 'showCloseButton'

314

| 'showConfirmButton'

315

| 'showDenyButton'

316

| 'text'

317

| 'title'

318

| 'titleText'

319

| 'theme'

320

| 'willClose';

321

```

322

323

## Advanced State Management Examples

324

325

```typescript

326

// Multi-step wizard with state management

327

let currentStep = 1;

328

const totalSteps = 3;

329

330

const showStep = (step: number) => {

331

const stepData = {

332

1: {

333

title: 'Step 1: Personal Information',

334

html: '<input id="name" class="swal2-input" placeholder="Your name">',

335

confirmButtonText: 'Next'

336

},

337

2: {

338

title: 'Step 2: Contact Details',

339

html: '<input id="email" class="swal2-input" placeholder="Your email">',

340

confirmButtonText: 'Next',

341

showCancelButton: true

342

},

343

3: {

344

title: 'Step 3: Confirmation',

345

html: 'Please review your information before submitting.',

346

confirmButtonText: 'Submit',

347

showCancelButton: true

348

}

349

};

350

351

Swal.update({

352

...stepData[step],

353

progressSteps: ['1', '2', '3'],

354

currentProgressStep: step - 1

355

});

356

};

357

358

// Real-time validation with state updates

359

Swal.fire({

360

title: 'Form Validation Example',

361

html: `

362

<input id="username" class="swal2-input" placeholder="Username (min 3 chars)">

363

<input id="password" class="swal2-input" type="password" placeholder="Password (min 6 chars)">

364

<input id="confirm" class="swal2-input" type="password" placeholder="Confirm password">

365

`,

366

showCancelButton: true,

367

confirmButtonText: 'Register',

368

didOpen: () => {

369

Swal.disableButtons();

370

371

const validateForm = () => {

372

const username = document.getElementById('username').value;

373

const password = document.getElementById('password').value;

374

const confirm = document.getElementById('confirm').value;

375

376

const isValid = username.length >= 3 &&

377

password.length >= 6 &&

378

password === confirm;

379

380

if (isValid) {

381

Swal.enableButtons();

382

Swal.update({

383

text: '✓ Form is valid',

384

icon: undefined

385

});

386

} else {

387

Swal.disableButtons();

388

let message = 'Please fix the following:';

389

if (username.length < 3) message += '\n• Username too short';

390

if (password.length < 6) message += '\n• Password too short';

391

if (password !== confirm) message += '\n• Passwords do not match';

392

393

Swal.update({

394

text: message,

395

icon: 'warning'

396

});

397

}

398

};

399

400

['username', 'password', 'confirm'].forEach(id => {

401

document.getElementById(id).addEventListener('input', validateForm);

402

});

403

}

404

});

405

```