-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
files.js
2530 lines (2433 loc) · 72.1 KB
/
files.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module IO
* @submodule Input
* @for p5
* @requires core
*/
import p5 from '../core/main';
import 'whatwg-fetch';
import 'es6-promise/auto';
import fetchJsonp from 'fetch-jsonp';
import fileSaver from 'file-saver';
import '../core/friendly_errors/validate_params';
import '../core/friendly_errors/file_errors';
import '../core/friendly_errors/fes_core';
/**
* Loads a JSON file to create an `Object`.
*
* JavaScript Object Notation
* (<a href="https://developer.mozilla.org/en-US/docs/Glossary/JSON" target="_blank">JSON</a>)
* is a standard format for sending data between applications. The format is
* based on JavaScript objects which have keys and values. JSON files store
* data in an object with strings as keys. Values can be strings, numbers,
* Booleans, arrays, `null`, or other objects.
*
* The first parameter, `path`, is always a string with the path to the file.
* Paths to local files should be relative, as in
* `loadJSON('assets/data.json')`. URLs such as
* `'https://example.com/data.json'` may be blocked due to browser security.
*
* The second parameter, `successCallback`, is optional. If a function is
* passed, as in `loadJSON('assets/data.json', handleData)`, then the
* `handleData()` function will be called once the data loads. The object
* created from the JSON data will be passed to `handleData()` as its only argument.
*
* The third parameter, `failureCallback`, is also optional. If a function is
* passed, as in `loadJSON('assets/data.json', handleData, handleFailure)`,
* then the `handleFailure()` function will be called if an error occurs while
* loading. The `Error` object will be passed to `handleFailure()` as its only
* argument.
*
* Note: Data can take time to load. Calling `loadJSON()` within
* <a href="#/p5/preload">preload()</a> ensures data loads before it's used in
* <a href="#/p5/setup">setup()</a> or <a href="#/p5/draw">draw()</a>.
*
* @method loadJSON
* @param {String} path path of the JSON file to be loaded.
* @param {function} [successCallback] function to call once the data is loaded. Will be passed the object.
* @param {function} [errorCallback] function to call if the data fails to load. Will be passed an `Error` event object.
* @return {Object} object containing the loaded data.
*
* @example
*
* <div>
* <code>
* let myData;
*
* // Load the JSON and create an object.
* function preload() {
* myData = loadJSON('assets/data.json');
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Style the circle.
* fill(myData.color);
* noStroke();
*
* // Draw the circle.
* circle(myData.x, myData.y, myData.d);
*
* describe('A pink circle on a gray background.');
* }
* </code>
* </div>
*
* <div>
* <code>
* let myData;
*
* // Load the JSON and create an object.
* function preload() {
* myData = loadJSON('assets/data.json');
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Create a p5.Color object and make it transparent.
* let c = color(myData.color);
* c.setAlpha(80);
*
* // Style the circles.
* fill(c);
* noStroke();
*
* // Iterate over the myData.bubbles array.
* for (let b of myData.bubbles) {
* // Draw a circle for each bubble.
* circle(b.x, b.y, b.d);
* }
*
* describe('Several pink bubbles floating in a blue sky.');
* }
* </code>
* </div>
*
* <div>
* <code>
* let myData;
*
* // Load the GeoJSON and create an object.
* function preload() {
* myData = loadJSON('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson');
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Get data about the most recent earthquake.
* let quake = myData.features[0].properties;
*
* // Draw a circle based on the earthquake's magnitude.
* circle(50, 50, quake.mag * 10);
*
* // Style the text.
* textAlign(LEFT, CENTER);
* textFont('Courier New');
* textSize(11);
*
* // Display the earthquake's location.
* text(quake.place, 5, 80, 100);
*
* describe(`A white circle on a gray background. The text "${quake.place}" is written beneath the circle.`);
* }
* </code>
* </div>
*
* <div>
* <code>
* let bigQuake;
*
* // Load the GeoJSON and preprocess it.
* function preload() {
* loadJSON(
* 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson',
* handleData
* );
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Draw a circle based on the earthquake's magnitude.
* circle(50, 50, bigQuake.mag * 10);
*
* // Style the text.
* textAlign(LEFT, CENTER);
* textFont('Courier New');
* textSize(11);
*
* // Display the earthquake's location.
* text(bigQuake.place, 5, 80, 100);
*
* describe(`A white circle on a gray background. The text "${bigQuake.place}" is written beneath the circle.`);
* }
*
* // Find the biggest recent earthquake.
* function handleData(data) {
* let maxMag = 0;
* // Iterate over the earthquakes array.
* for (let quake of data.features) {
* // Reassign bigQuake if a larger
* // magnitude quake is found.
* if (quake.properties.mag > maxMag) {
* bigQuake = quake.properties;
* }
* }
* }
* </code>
* </div>
*
* <div>
* <code>
* let bigQuake;
*
* // Load the GeoJSON and preprocess it.
* function preload() {
* loadJSON(
* 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson',
* handleData,
* handleError
* );
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Draw a circle based on the earthquake's magnitude.
* circle(50, 50, bigQuake.mag * 10);
*
* // Style the text.
* textAlign(LEFT, CENTER);
* textFont('Courier New');
* textSize(11);
*
* // Display the earthquake's location.
* text(bigQuake.place, 5, 80, 100);
*
* describe(`A white circle on a gray background. The text "${bigQuake.place}" is written beneath the circle.`);
* }
*
* // Find the biggest recent earthquake.
* function handleData(data) {
* let maxMag = 0;
* // Iterate over the earthquakes array.
* for (let quake of data.features) {
* // Reassign bigQuake if a larger
* // magnitude quake is found.
* if (quake.properties.mag > maxMag) {
* bigQuake = quake.properties;
* }
* }
* }
*
* // Log any errors to the console.
* function handleError(error) {
* console.log('Oops!', error);
* }
* </code>
* </div>
*/
p5.prototype.loadJSON = function(...args) {
p5._validateParameters('loadJSON', args);
const path = args[0];
let callback;
let errorCallback;
let options;
const ret = {}; // object needed for preload
let t = 'json';
// check for explicit data type argument
for (let i = 1; i < args.length; i++) {
const arg = args[i];
if (typeof arg === 'string') {
if (arg === 'jsonp' || arg === 'json') {
t = arg;
}
} else if (typeof arg === 'function') {
if (!callback) {
callback = arg;
} else {
errorCallback = arg;
}
} else if (
typeof arg === 'object' &&
(arg.hasOwnProperty('jsonpCallback') ||
arg.hasOwnProperty('jsonpCallbackFunction'))
) {
t = 'jsonp';
options = arg;
}
}
const self = this;
this.httpDo(
path,
'GET',
options,
t,
resp => {
for (const k in resp) {
ret[k] = resp[k];
}
if (typeof callback !== 'undefined') {
callback(resp);
}
self._decrementPreload();
},
err => {
// Error handling
p5._friendlyFileLoadError(5, path);
if (errorCallback) {
errorCallback(err);
} else {
throw err;
}
}
);
return ret;
};
/**
* Loads a text file to create an `Array`.
*
* The first parameter, `path`, is always a string with the path to the file.
* Paths to local files should be relative, as in
* `loadStrings('assets/data.txt')`. URLs such as
* `'https://example.com/data.txt'` may be blocked due to browser security.
*
* The second parameter, `successCallback`, is optional. If a function is
* passed, as in `loadStrings('assets/data.txt', handleData)`, then the
* `handleData()` function will be called once the data loads. The array
* created from the text data will be passed to `handleData()` as its only
* argument.
*
* The third parameter, `failureCallback`, is also optional. If a function is
* passed, as in `loadStrings('assets/data.txt', handleData, handleFailure)`,
* then the `handleFailure()` function will be called if an error occurs while
* loading. The `Error` object will be passed to `handleFailure()` as its only
* argument.
*
* Note: Data can take time to load. Calling `loadStrings()` within
* <a href="#/p5/preload">preload()</a> ensures data loads before it's used in
* <a href="#/p5/setup">setup()</a> or <a href="#/p5/draw">draw()</a>.
*
* @method loadStrings
* @param {String} path path of the text file to be loaded.
* @param {function} [successCallback] function to call once the data is
* loaded. Will be passed the array.
* @param {function} [errorCallback] function to call if the data fails to
* load. Will be passed an `Error` event
* object.
* @return {String[]} new array containing the loaded text.
*
* @example
*
* <div>
* <code>
* let myData;
*
* // Load the text and create an array.
* function preload() {
* myData = loadStrings('assets/test.txt');
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Select a random line from the text.
* let phrase = random(myData);
*
* // Style the text.
* textAlign(LEFT, CENTER);
* textFont('Courier New');
* textSize(12);
*
* // Display the text.
* text(phrase, 10, 50, 90);
*
* describe(`The text "${phrase}" written in black on a gray background.`);
* }
* </code>
* </div>
*
* <div>
* <code>
* let lastLine;
*
* // Load the text and preprocess it.
* function preload() {
* loadStrings('assets/test.txt', handleData);
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Style the text.
* textAlign(LEFT, CENTER);
* textFont('Courier New');
* textSize(12);
*
* // Display the text.
* text(lastLine, 10, 50, 90);
*
* describe('The text "I talk like an orange" written in black on a gray background.');
* }
*
* // Select the last line from the text.
* function handleData(data) {
* lastLine = data[data.length - 1];
* }
* </code>
* </div>
*
* <div>
* <code>
* let lastLine;
*
* // Load the text and preprocess it.
* function preload() {
* loadStrings('assets/test.txt', handleData, handleError);
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Style the text.
* textAlign(LEFT, CENTER);
* textFont('Courier New');
* textSize(12);
*
* // Display the text.
* text(lastLine, 10, 50, 90);
*
* describe('The text "I talk like an orange" written in black on a gray background.');
* }
*
* // Select the last line from the text.
* function handleData(data) {
* lastLine = data[data.length - 1];
* }
*
* // Log any errors to the console.
* function handleError(error) {
* console.error('Oops!', error);
* }
* </code>
* </div>
*/
p5.prototype.loadStrings = function(...args) {
p5._validateParameters('loadStrings', args);
const ret = [];
let callback, errorCallback;
for (let i = 1; i < args.length; i++) {
const arg = args[i];
if (typeof arg === 'function') {
if (typeof callback === 'undefined') {
callback = arg;
} else if (typeof errorCallback === 'undefined') {
errorCallback = arg;
}
}
}
const self = this;
p5.prototype.httpDo.call(
this,
args[0],
'GET',
'text',
data => {
// split lines handling mac/windows/linux endings
const lines = data
.replace(/\r\n/g, '\r')
.replace(/\n/g, '\r')
.split(/\r/);
// safe insert approach which will not blow up stack when inserting
// >100k lines, but still be faster than iterating line-by-line. based on
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply#Examples
const QUANTUM = 32768;
for (let i = 0, len = lines.length; i < len; i += QUANTUM) {
Array.prototype.push.apply(
ret,
lines.slice(i, Math.min(i + QUANTUM, len))
);
}
if (typeof callback !== 'undefined') {
callback(ret);
}
self._decrementPreload();
},
function(err) {
// Error handling
p5._friendlyFileLoadError(3, arguments[0]);
if (errorCallback) {
errorCallback(err);
} else {
throw err;
}
}
);
return ret;
};
/**
* Reads the contents of a file or URL and creates a <a href="#/p5.Table">p5.Table</a> object with
* its values. If a file is specified, it must be located in the sketch's
* "data" folder. The filename parameter can also be a URL to a file found
* online. By default, the file is assumed to be comma-separated (in CSV
* format). Table only looks for a header row if the 'header' option is
* included.
*
* This method is asynchronous, meaning it may not finish before the next
* line in your sketch is executed. Calling <a href="#/p5/loadTable">loadTable()</a> inside <a href="#/p5/preload">preload()</a>
* guarantees to complete the operation before <a href="#/p5/setup">setup()</a> and <a href="#/p5/draw">draw()</a> are called.
* Outside of <a href="#/p5/preload">preload()</a>, you may supply a callback function to handle the
* object:
*
* All files loaded and saved use UTF-8 encoding. This method is suitable for fetching files up to size of 64MB.
* @method loadTable
* @param {String} filename name of the file or URL to load
* @param {String} [extension] parse the table by comma-separated values "csv", semicolon-separated
* values "ssv", or tab-separated values "tsv"
* @param {String} [header] "header" to indicate table has header row
* @param {function} [callback] function to be executed after
* <a href="#/p5/loadTable">loadTable()</a> completes. On success, the
* <a href="#/p5.Table">Table</a> object is passed in as the
* first argument.
* @param {function} [errorCallback] function to be executed if
* there is an error, response is passed
* in as first argument
* @return {Object} <a href="#/p5.Table">Table</a> object containing data
*
* @example
* <div class='norender'>
* <code>
* // Given the following CSV file called "mammals.csv"
* // located in the project's "assets" folder:
* //
* // id,species,name
* // 0,Capra hircus,Goat
* // 1,Panthera pardus,Leopard
* // 2,Equus zebra,Zebra
*
* let table;
*
* function preload() {
* //my table is comma separated value "csv"
* //and has a header specifying the columns labels
* table = loadTable('assets/mammals.csv', 'csv', 'header');
* //the file can be remote
* //table = loadTable("http://p5js.org/reference/assets/mammals.csv",
* // "csv", "header");
* }
*
* function setup() {
* //count the columns
* print(table.getRowCount() + ' total rows in table');
* print(table.getColumnCount() + ' total columns in table');
*
* print(table.getColumn('name'));
* //["Goat", "Leopard", "Zebra"]
*
* //cycle through the table
* for (let r = 0; r < table.getRowCount(); r++)
* for (let c = 0; c < table.getColumnCount(); c++) {
* print(table.getString(r, c));
* }
* describe(`randomly generated text from a file,
* for example "i smell like butter"`);
* }
* </code>
* </div>
*/
p5.prototype.loadTable = function(path) {
// p5._validateParameters('loadTable', arguments);
let callback;
let errorCallback;
const options = [];
let header = false;
const ext = path.substring(path.lastIndexOf('.') + 1, path.length);
let sep;
if (ext === 'csv') {
sep = ',';
} else if (ext === 'ssv') {
sep = ';';
} else if (ext === 'tsv') {
sep = '\t';
}
for (let i = 1; i < arguments.length; i++) {
if (typeof arguments[i] === 'function') {
if (typeof callback === 'undefined') {
callback = arguments[i];
} else if (typeof errorCallback === 'undefined') {
errorCallback = arguments[i];
}
} else if (typeof arguments[i] === 'string') {
options.push(arguments[i]);
if (arguments[i] === 'header') {
header = true;
}
if (arguments[i] === 'csv') {
sep = ',';
} else if (arguments[i] === 'ssv') {
sep = ';';
} else if (arguments[i] === 'tsv') {
sep = '\t';
}
}
}
const t = new p5.Table();
const self = this;
this.httpDo(
path,
'GET',
'table',
resp => {
const state = {};
// define constants
const PRE_TOKEN = 0,
MID_TOKEN = 1,
POST_TOKEN = 2,
POST_RECORD = 4;
const QUOTE = '"',
CR = '\r',
LF = '\n';
const records = [];
let offset = 0;
let currentRecord = null;
let currentChar;
const tokenBegin = () => {
state.currentState = PRE_TOKEN;
state.token = '';
};
const tokenEnd = () => {
currentRecord.push(state.token);
tokenBegin();
};
const recordBegin = () => {
state.escaped = false;
currentRecord = [];
tokenBegin();
};
const recordEnd = () => {
state.currentState = POST_RECORD;
records.push(currentRecord);
currentRecord = null;
};
for (;;) {
currentChar = resp[offset++];
// EOF
if (currentChar == null) {
if (state.escaped) {
throw new Error('Unclosed quote in file.');
}
if (currentRecord) {
tokenEnd();
recordEnd();
break;
}
}
if (currentRecord === null) {
recordBegin();
}
// Handle opening quote
if (state.currentState === PRE_TOKEN) {
if (currentChar === QUOTE) {
state.escaped = true;
state.currentState = MID_TOKEN;
continue;
}
state.currentState = MID_TOKEN;
}
// mid-token and escaped, look for sequences and end quote
if (state.currentState === MID_TOKEN && state.escaped) {
if (currentChar === QUOTE) {
if (resp[offset] === QUOTE) {
state.token += QUOTE;
offset++;
} else {
state.escaped = false;
state.currentState = POST_TOKEN;
}
} else if (currentChar === CR) {
continue;
} else {
state.token += currentChar;
}
continue;
}
// fall-through: mid-token or post-token, not escaped
if (currentChar === CR) {
if (resp[offset] === LF) {
offset++;
}
tokenEnd();
recordEnd();
} else if (currentChar === LF) {
tokenEnd();
recordEnd();
} else if (currentChar === sep) {
tokenEnd();
} else if (state.currentState === MID_TOKEN) {
state.token += currentChar;
}
}
// set up column names
if (header) {
t.columns = records.shift();
} else {
for (let i = 0; i < records[0].length; i++) {
t.columns[i] = 'null';
}
}
let row;
for (let i = 0; i < records.length; i++) {
//Handles row of 'undefined' at end of some CSVs
if (records[i].length === 1) {
if (records[i][0] === 'undefined' || records[i][0] === '') {
continue;
}
}
row = new p5.TableRow();
row.arr = records[i];
row.obj = makeObject(records[i], t.columns);
t.addRow(row);
}
if (typeof callback === 'function') {
callback(t);
}
self._decrementPreload();
},
err => {
// Error handling
p5._friendlyFileLoadError(2, path);
if (errorCallback) {
errorCallback(err);
} else {
console.error(err);
}
}
);
return t;
};
// helper function to turn a row into a JSON object
function makeObject(row, headers) {
headers = headers || [];
if (typeof headers === 'undefined') {
for (let j = 0; j < row.length; j++) {
headers[j.toString()] = j;
}
}
return Object.fromEntries(
headers
.map((key,i) => [key, row[i]])
);
}
/**
* Loads an XML file to create a <a href="#/p5.XML">p5.XML</a> object.
*
* Extensible Markup Language
* (<a href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank">XML</a>)
* is a standard format for sending data between applications. Like HTML, the
* XML format is based on tags and attributes, as in
* `<time units="s">1234</time>`.
*
* The first parameter, `path`, is always a string with the path to the file.
* Paths to local files should be relative, as in
* `loadXML('assets/data.xml')`. URLs such as `'https://example.com/data.xml'`
* may be blocked due to browser security.
*
* The second parameter, `successCallback`, is optional. If a function is
* passed, as in `loadXML('assets/data.xml', handleData)`, then the
* `handleData()` function will be called once the data loads. The
* <a href="#/p5.XML">p5.XML</a> object created from the data will be passed
* to `handleData()` as its only argument.
*
* The third parameter, `failureCallback`, is also optional. If a function is
* passed, as in `loadXML('assets/data.xml', handleData, handleFailure)`, then
* the `handleFailure()` function will be called if an error occurs while
* loading. The `Error` object will be passed to `handleFailure()` as its only
* argument.
*
* Note: Data can take time to load. Calling `loadXML()` within
* <a href="#/p5/preload">preload()</a> ensures data loads before it's used in
* <a href="#/p5/setup">setup()</a> or <a href="#/p5/draw">draw()</a>.
*
* @method loadXML
* @param {String} path path of the XML file to be loaded.
* @param {function} [successCallback] function to call once the data is
* loaded. Will be passed the
* <a href="#/p5.XML">p5.XML</a> object.
* @param {function} [errorCallback] function to call if the data fails to
* load. Will be passed an `Error` event
* object.
* @return {p5.XML} XML data loaded into a <a href="#/p5.XML">p5.XML</a>
* object.
*
* @example
* <div>
* <code>
* let myXML;
*
* // Load the XML and create a p5.XML object.
* function preload() {
* myXML = loadXML('assets/animals.xml');
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Get an array with all mammal tags.
* let mammals = myXML.getChildren('mammal');
*
* // Style the text.
* textAlign(LEFT, CENTER);
* textFont('Courier New');
* textSize(14);
*
* // Iterate over the mammals array.
* for (let i = 0; i < mammals.length; i += 1) {
*
* // Calculate the y-coordinate.
* let y = (i + 1) * 25;
*
* // Get the mammal's common name.
* let name = mammals[i].getContent();
*
* // Display the mammal's name.
* text(name, 20, y);
* }
*
* describe(
* 'The words "Goat", "Leopard", and "Zebra" written on three separate lines. The text is black on a gray background.'
* );
* }
* </code>
* </div>
*
* <div>
* <code>
* let lastMammal;
*
* // Load the XML and create a p5.XML object.
* function preload() {
* loadXML('assets/animals.xml', handleData);
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Style the text.
* textAlign(CENTER, CENTER);
* textFont('Courier New');
* textSize(16);
*
* // Display the content of the last mammal element.
* text(lastMammal, 50, 50);
*
* describe('The word "Zebra" written in black on a gray background.');
* }
*
* // Get the content of the last mammal element.
* function handleData(data) {
* // Get an array with all mammal elements.
* let mammals = data.getChildren('mammal');
*
* // Get the content of the last mammal.
* lastMammal = mammals[mammals.length - 1].getContent();
* }
* </code>
* </div>
*
* <div>
* <code>
* let lastMammal;
*
* // Load the XML and preprocess it.
* function preload() {
* loadXML('assets/animals.xml', handleData, handleError);
* }
*
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Style the text.
* textAlign(CENTER, CENTER);
* textFont('Courier New');
* textSize(16);
*
* // Display the content of the last mammal element.
* text(lastMammal, 50, 50);
*
* describe('The word "Zebra" written in black on a gray background.');
* }
*
* // Get the content of the last mammal element.
* function handleData(data) {
* // Get an array with all mammal elements.
* let mammals = data.getChildren('mammal');
*
* // Get the content of the last mammal.
* lastMammal = mammals[mammals.length - 1].getContent();
* }
*
* // Log any errors to the console.
* function handleError(error) {
* console.error('Oops!', error);
* }
* </code>
* </div>
*/
p5.prototype.loadXML = function(...args) {
const ret = new p5.XML();
let callback, errorCallback;
for (let i = 1; i < args.length; i++) {
const arg = args[i];
if (typeof arg === 'function') {
if (typeof callback === 'undefined') {
callback = arg;
} else if (typeof errorCallback === 'undefined') {
errorCallback = arg;
}
}
}
const self = this;
this.httpDo(
args[0],
'GET',
'xml',
xml => {
for (const key in xml) {
ret[key] = xml[key];
}
if (typeof callback !== 'undefined') {
callback(ret);
}
self._decrementPreload();
},
function(err) {
// Error handling
p5._friendlyFileLoadError(1, arguments[0]);
if (errorCallback) {
errorCallback(err);
} else {
throw err;
}
}
);
return ret;
};
/**
* This method is suitable for fetching files up to size of 64MB.
* @method loadBytes
* @param {string} file name of the file or URL to load
* @param {function} [callback] function to be executed after <a href="#/p5/loadBytes">loadBytes()</a>
* completes
* @param {function} [errorCallback] function to be executed if there
* is an error
* @returns {Object} an object whose 'bytes' property will be the loaded buffer
*
* @example
* <div class='norender'><code>
* let data;
*
* function preload() {