diff --git a/.all-contributorsrc b/.all-contributorsrc index 4cbe7f138a..7dda768fcd 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -5657,6 +5657,179 @@ "a11y", "doc" ] + }, + { + "login": "sproutleaf", + "name": "Miaoye Que", + "avatar_url": "https://avatars.githubusercontent.com/u/116130954?v=4", + "profile": "https://github.com/sproutleaf", + "contributions": [ + "translation", + "maintenance" + ] + }, + { + "login": "sphantom-code", + "name": "sphantom-code", + "avatar_url": "https://avatars.githubusercontent.com/u/74479963?v=4", + "profile": "https://github.com/sphantom-code", + "contributions": [ + "doc" + ] + }, + { + "login": "wooknick", + "name": "Minwook Park", + "avatar_url": "https://avatars.githubusercontent.com/u/23724801?v=4", + "profile": "http://parkminwook.com", + "contributions": [ + "translation" + ] + }, + { + "login": "Harrycheng233", + "name": "Harrycheng233", + "avatar_url": "https://avatars.githubusercontent.com/u/129256087?v=4", + "profile": "https://github.com/Harrycheng233", + "contributions": [ + "translation" + ] + }, + { + "login": "DianaMGalindo", + "name": "Diana Galindo", + "avatar_url": "https://avatars.githubusercontent.com/u/95235340?v=4", + "profile": "https://github.com/DianaMGalindo", + "contributions": [ + "translation" + ] + }, + { + "login": "douMax", + "name": "Lingxiao Wang", + "avatar_url": "https://avatars.githubusercontent.com/u/28494194?v=4", + "profile": "https://github.com/douMax", + "contributions": [ + "translation" + ] + }, + { + "login": "ml008008", + "name": "ml.008", + "avatar_url": "https://avatars.githubusercontent.com/u/141788009?v=4", + "profile": "https://github.com/ml008008", + "contributions": [ + "translation" + ] + }, + { + "login": "EmilioOcelotl", + "name": "EmilioOcelotl", + "avatar_url": "https://avatars.githubusercontent.com/u/8987515?v=4", + "profile": "http://ocelotl.cc", + "contributions": [ + "translation" + ] + }, + { + "login": "MarianneTeixido", + "name": "Teixido", + "avatar_url": "https://avatars.githubusercontent.com/u/32370294?v=4", + "profile": "https://marianneteixido.github.io/", + "contributions": [ + "translation" + ] + }, + { + "login": "ienground", + "name": "IENGROUND", + "avatar_url": "https://avatars.githubusercontent.com/u/32572338?v=4", + "profile": "https://www.ien.zone", + "contributions": [ + "translation" + ] + }, + { + "login": "Orwiss", + "name": "Orwiss", + "avatar_url": "https://avatars.githubusercontent.com/u/7181108?v=4", + "profile": "https://www.behance.net/orwiss", + "contributions": [ + "translation" + ] + }, + { + "login": "ranaaditya", + "name": "Aditya Rana", + "avatar_url": "https://avatars.githubusercontent.com/u/42575044?v=4", + "profile": "http://ranaa.tech", + "contributions": [ + "translation" + ] + }, + { + "login": "EshaanAgg", + "name": "Eshaan Aggarwal", + "avatar_url": "https://avatars.githubusercontent.com/u/96648934?v=4", + "profile": "https://eshaanagg.netlify.app/", + "contributions": [ + "translation" + ] + }, + { + "login": "yunyoungJang", + "name": "everything became blue", + "avatar_url": "https://avatars.githubusercontent.com/u/39682540?v=4", + "profile": "https://github.com/yunyoungJang", + "contributions": [ + "translation" + ] + }, + { + "login": "YewonCALLI", + "name": "YewonCALLI", + "avatar_url": "https://avatars.githubusercontent.com/u/96384200?v=4", + "profile": "https://github.com/YewonCALLI", + "contributions": [ + "translation" + ] + }, + { + "login": "designerSejinOH", + "name": "SejinOH", + "avatar_url": "https://avatars.githubusercontent.com/u/39869184?v=4", + "profile": "http://sejinoh.live", + "contributions": [ + "translation", + "review" + ] + }, + { + "login": "Surbhi-Pittie", + "name": "Surbhi Pittie", + "avatar_url": "https://avatars.githubusercontent.com/u/101015196?v=4", + "profile": "https://github.com/Surbhi-Pittie", + "contributions": [ + "translation" + ] + }, + { + "login": "Tmicrd", + "name": "nancy", + "avatar_url": "https://avatars.githubusercontent.com/u/53132820?v=4", + "profile": "https://github.com/Tmicrd", + "contributions": [ + "translation" + ] + }, + { + "login": "jaiakash", + "name": "Akash Jaiswal", + "avatar_url": "https://avatars.githubusercontent.com/u/33419526?v=4", + "profile": "https://github.com/jaiakash", + "contributions": [ + "translation" + ] } ], "repoType": "github", diff --git a/.github/workflows/update-p5jswebsite.yml b/.github/workflows/update-p5jswebsite.yml deleted file mode 100644 index cfb26efecc..0000000000 --- a/.github/workflows/update-p5jswebsite.yml +++ /dev/null @@ -1,18 +0,0 @@ -name: Trigger documentation update in p5.js-website - -on: - release: - types: [published] - -jobs: - trigger: - runs-on: ubuntu-latest - name: Dispatch event to p5.js-website - steps: - - name: Dispatch event to p5.js-website - uses: peter-evans/repository-dispatch@v1 - with: - token: ${{ secrets.P5JS_TOKEN }} - repository: processing/p5.js-website - event-type: p5.js-release - client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}"}' \ No newline at end of file diff --git a/README.md b/README.md index 1ac923deb0..b8d7d272c6 100644 --- a/README.md +++ b/README.md @@ -959,6 +959,31 @@ We recognize all types of contributions. This project follows the [all-contribut Nat Decker
Nat Decker

️️️️♿️ 📖 + Miaoye Que
Miaoye Que

🌍 🚧 + sphantom-code
sphantom-code

📖 + Minwook Park
Minwook Park

🌍 + Harrycheng233
Harrycheng233

🌍 + Diana Galindo
Diana Galindo

🌍 + + + Lingxiao Wang
Lingxiao Wang

🌍 + ml.008
ml.008

🌍 + EmilioOcelotl
EmilioOcelotl

🌍 + Teixido
Teixido

🌍 + IENGROUND
IENGROUND

🌍 + Orwiss
Orwiss

🌍 + + + Aditya Rana
Aditya Rana

🌍 + Eshaan Aggarwal
Eshaan Aggarwal

🌍 + everything became blue
everything became blue

🌍 + YewonCALLI
YewonCALLI

🌍 + SejinOH
SejinOH

🌍 👀 + Surbhi Pittie
Surbhi Pittie

🌍 + + + nancy
nancy

🌍 + Akash Jaiswal
Akash Jaiswal

🌍 diff --git a/contributor_docs/access.md b/contributor_docs/access.md index 02c23ca5d4..788ead722b 100644 --- a/contributor_docs/access.md +++ b/contributor_docs/access.md @@ -1,3 +1,5 @@ + + # Our Focus on Access At the [2019 Contributors Conference](https://p5js.org/community/contributors-conference-2019.html), p5.js made the commitment to only add new features that increase access (inclusion and accessibility). We will not accept feature requests that don't support these efforts. We commit to the work of acknowledging, dismantling, and preventing barriers. This means considering intersecting[^1] experiences of diversity that can impact access and participation. These include alignments of gender, race, ethnicity, sexuality, language, location, et cetera. We center the needs of marginalized groups over the continued comfort of those privileged within the p5.js community. We are collectively exploring the meaning of access. We are learning how to practice and teach access. We choose to think of access through expansive, intersectional, and coalitionary frameworks. This commitment is part of the core values of p5.js outlined in our [Community Statement](https://p5js.org/community/). diff --git a/contributor_docs/custom_p5_build.md b/contributor_docs/archive/custom_p5_build.md similarity index 95% rename from contributor_docs/custom_p5_build.md rename to contributor_docs/archive/custom_p5_build.md index 3e4ee78fb1..04eab00f67 100644 --- a/contributor_docs/custom_p5_build.md +++ b/contributor_docs/archive/custom_p5_build.md @@ -1,3 +1,5 @@ + + # Creating a custom build of p5.js with select components ## Overview diff --git a/contributor_docs/archive/discussions.md b/contributor_docs/archive/discussions.md deleted file mode 100644 index 41327fb689..0000000000 --- a/contributor_docs/archive/discussions.md +++ /dev/null @@ -1,3 +0,0 @@ -Joining in on the discussion about how p5 is developed is a great way to contribute. This can be done in a number of ways but one great place to start is by checking out the existing Github [issues that have been labeled 'discussion'](https://github.com/processing/p5.js/labels/discussion) and adding your voice. - -The documents in this subsection are developed based on these discussion. This is where we compile ideas about current and future design for the library. diff --git a/contributor_docs/internationalization.md b/contributor_docs/archive/internationalization.md similarity index 98% rename from contributor_docs/internationalization.md rename to contributor_docs/archive/internationalization.md index 0d560445d3..4d75cb124e 100644 --- a/contributor_docs/internationalization.md +++ b/contributor_docs/archive/internationalization.md @@ -1,3 +1,5 @@ + + # 🌐 Internationalization [Internationalization](https://developer.mozilla.org/docs/Glossary/Internationalization_and_localization) (sometimes abbreviated "i18n") refers to supporting multiple languages in a software project. This often means maintaining translations of text strings used in the project and letting users choose which translation they receive (or detecting it from their browser settings). diff --git a/contributor_docs/issue_labels.md b/contributor_docs/archive/issue_labels.md similarity index 97% rename from contributor_docs/issue_labels.md rename to contributor_docs/archive/issue_labels.md index 33768978ba..d70bb5fc33 100644 --- a/contributor_docs/issue_labels.md +++ b/contributor_docs/archive/issue_labels.md @@ -1,3 +1,5 @@ + + # p5.js issue labels p5.js uses a set of labels to help sort and organize issues. diff --git a/contributor_docs/supported_browsers.md b/contributor_docs/archive/supported_browsers.md similarity index 97% rename from contributor_docs/supported_browsers.md rename to contributor_docs/archive/supported_browsers.md index b9e7dde67e..28fba0e4f1 100644 --- a/contributor_docs/supported_browsers.md +++ b/contributor_docs/archive/supported_browsers.md @@ -1,3 +1,5 @@ + + # Supported browsers ## Our stated goal diff --git a/contributor_docs/contributing_documentation.md b/contributor_docs/contributing_documentation.md index 8a2caddf64..75c4685b86 100644 --- a/contributor_docs/contributing_documentation.md +++ b/contributor_docs/contributing_documentation.md @@ -1,3 +1,5 @@ + + # Contributing Documentation Documentation is essential for new learners and experienced programmers alike. It helps make our community inclusive by extending a friendly hand to those who are less familiar with p5.js. It also helps us find the bugs and issues with the code itself, because we test and try things out as we document. diff --git a/contributor_docs/contributing_to_the_p5.js_reference.md b/contributor_docs/contributing_to_the_p5.js_reference.md index 115ceb1e65..283c97f6f2 100644 --- a/contributor_docs/contributing_to_the_p5.js_reference.md +++ b/contributor_docs/contributing_to_the_p5.js_reference.md @@ -1,3 +1,5 @@ + + # Contributing to the p5.js Reference In p5.js, we author the code reference you see on the [reference](https://p5js.org/reference/) page on the p5.js website by including them alongside the library’s source code as specialized comments. These reference comments include the description, the function’s signature (its parameters and return value), and usage examples. In other words, the content on each p5.js function/variable’s reference page is built from the reference comments in the source code. @@ -11,62 +13,62 @@ When you look at the source code of p5.js, you will see many lines in the librar ``` /** - * Calculates the sine of an angle. `sin()` is useful for many geometric tasks - * in creative coding. The values returned oscillate between -1 and 1 as the - * input angle increases. `sin()` takes into account the current - * angleMode. - * - * @method sin - * @param  {Number} angle the angle. - * @return {Number} sine of the angle. - * - * @example - *
- * - * function draw() { - *   background(200); - * - *   let t = frameCount; - *   let x = 50; - *   let y = 30 * sin(t * 0.05) + 50; - *   line(x, 50, x, y); - *   circle(x, y, 20); - * - *   describe('A white ball on a string oscillates up and down.'); - * } - * - *
- * - *
- * - * function draw() { - *   let x = frameCount; - *   let y = 30 * sin(x * 0.1) + 50; - *   point(x, y); - * - *   describe('A series of black dots form a wave pattern.'); - * } - * - *
- * - *
- * - * function draw() { - *   let t = frameCount; - *   let x = 30 * cos(t * 0.1) + 50; - *   let y = 10 * sin(t * 0.2) + 50; - *   point(x, y); - * - *   describe('A series of black dots form an infinity symbol.'); - * } - * - *
- */ + * Calculates the sine of an angle. `sin()` is useful for many geometric tasks + * in creative coding. The values returned oscillate between -1 and 1 as the + * input angle increases. `sin()` takes into account the current + * angleMode. + * + * @method sin + * @param {Number} angle the angle. + * @return {Number} sine of the angle. + * + * @example + *
+ * + * function draw() { + * background(200); + * + * let t = frameCount; + * let x = 50; + * let y = 30 * sin(t * 0.05) + 50; + * line(x, 50, x, y); + * circle(x, y, 20); + * + * describe('A white ball on a string oscillates up and down.'); + * } + * + *
+ * + *
+ * + * function draw() { + * let x = frameCount; + * let y = 30 * sin(x * 0.1) + 50; + * point(x, y); + * + * describe('A series of black dots form a wave pattern.'); + * } + * + *
+ * + *
+ * + * function draw() { + * let t = frameCount; + * let x = 30 * cos(t * 0.1) + 50; + * let y = 10 * sin(t * 0.2) + 50; + * point(x, y); + * + * describe('A series of black dots form an infinity symbol.'); + * } + * + *
+ */ ``` They are usually followed by the actual JavaScript code that defines the function. Reference comments always start with `/**` and end with `*/`, with each line in between the two starting with `*`. -Anything in a block in this manner will be interpreted as reference documentation. You may be familiar with this style of code comments through [JSDoc](https://jsdoc.app/). While p5.js does not use JSDoc, it uses a very similar tool called [YUIDoc](https://yui.github.io/yuidoc/), which has a very similar reference syntax. In this style of reference comments, each comment block is further divided into individual elements, which we will have a look at next.  +Anything in a block in this manner will be interpreted as reference documentation. You may be familiar with this style of code comments through [JSDoc](https://jsdoc.app/). While p5.js does not use JSDoc, it uses a very similar tool called [YUIDoc](https://yui.github.io/yuidoc/), which has a very similar reference syntax. In this style of reference comments, each comment block is further divided into individual elements, which we will have a look at next. ## Reference comments block @@ -75,18 +77,18 @@ Let’s break down the reference comments block above for the `sin()` function a ``` /** - * Calculates the sine of an angle. `sin()` is useful for many geometric tasks - * in creative coding. The values returned oscillate between -1 and 1 as the - * input angle increases. `sin()` takes into account the current - * angleMode. + * Calculates the sine of an angle. `sin()` is useful for many geometric tasks + * in creative coding. The values returned oscillate between -1 and 1 as the + * input angle increases. `sin()` takes into account the current + * angleMode. ``` At the very top of the comment is the text description of the function. This description can contain both markdown syntax and HTML. The description should be concise and describe what the function does and, if necessary, some details about its quirks or behaviors. ``` * @method sin - * @param  {Number} angle  the angle. - * @return {Number} sine of the angle. + * @param {Number} angle the angle. + * @return {Number} sine of the angle. ``` A function will typically have the three sections above, each starting with an `@` symbol followed by one of the following keywords: @@ -145,18 +147,18 @@ If a function has multiple possible parameter options, you can specify each indi ``` /** - * @method background - * @param {String} colorstring color string, possible formats include: integer - *                         rgb() or rgba(), percentage rgb() or rgba(), - *                         3-digit hex, 6-digit hex - * @param {Number} [a] alpha value - */ + * @method background + * @param {String} colorstring color string, possible formats include: integer + * rgb() or rgba(), percentage rgb() or rgba(), + * 3-digit hex, 6-digit hex + * @param {Number} [a] alpha value + */ /** - * @method background - * @param {Number} gray specifies a value between white and black - * @param {Number} [a] - */ + * @method background + * @param {Number} gray specifies a value between white and black + * @param {Number} [a] + */ ``` @@ -171,27 +173,27 @@ So far, we have looked at how to write references for functions and constants. V ``` /** - * The system variable mouseX always contains the current horizontal - * position of the mouse, relative to (0, 0) of the canvas. The value at - * the top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL. - * If touch is used instead of mouse input, mouseX will hold the x value - * of the most recent touch point. - * - * @property {Number} mouseX - * @readOnly - * - * @example - *
- * - * // Move the mouse across the canvas - * function draw() { - *   background(244, 248, 252); - *   line(mouseX, 0, mouseX, 100); - *   describe('horizontal black line moves left and right with mouse x-position'); - * } - * - *
- */ + * The system variable mouseX always contains the current horizontal + * position of the mouse, relative to (0, 0) of the canvas. The value at + * the top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL. + * If touch is used instead of mouse input, mouseX will hold the x value + * of the most recent touch point. + * + * @property {Number} mouseX + * @readOnly + * + * @example + *
+ * + * // Move the mouse across the canvas + * function draw() { + * background(244, 248, 252); + * line(mouseX, 0, mouseX, 100); + * describe('horizontal black line moves left and right with mouse x-position'); + * } + * + *
+ */ ``` The start of the block contains the description of the variable (`mouseX` in this case). To define the name of the variable, we use `@property` instead of `@method`. `@property` follows the same syntax as `@param` for defining the type and its name. The `@readonly` tag is present on most p5.js variables and is used internally to indicate this value should not be overwritten directly by a library user. @@ -207,23 +209,23 @@ The relevant `@example` tag to create the above is as follows: ``` * @example - *
- * - * const c = color(255, 204, 0); - * fill(c); - * rect(15, 20, 35, 60); - * // Sets 'redValue' to 255. - * const redValue = red(c); - * fill(redValue, 0, 0); - * rect(50, 20, 35, 60); - * describe( - *   'Two rectangles with black edges. The rectangle on the left is yellow and the one on the right is red.' - * ); - * - *
-``` - -After the `@example` tag, you should start an HTML `
` tag followed by a `` tag. In between the opening and closing ``  tag, you will insert the relevant example code. The basic principle of writing good example code for the reference is to keep things simple and minimal. The example should be meaningful and explain how the feature works without being too complicated. The example’s canvas should be 100x100 pixels and if the `setup()` function is not included, such as in the example above, the code will be automatically wrapped in a `setup()` function with a default 100x100 pixels gray background canvas created. We won’t go through the details about best practices and code style for the example code here; please see the reference style guide instead. + *
+ * + * const c = color(255, 204, 0); + * fill(c); + * rect(15, 20, 35, 60); + * // Sets 'redValue' to 255. + * const redValue = red(c); + * fill(redValue, 0, 0); + * rect(50, 20, 35, 60); + * describe( + * 'Two rectangles with black edges. The rectangle on the left is yellow and the one on the right is red.' + * ); + * + *
+``` + +After the `@example` tag, you should start an HTML `
` tag followed by a `` tag. In between the opening and closing `` tag, you will insert the relevant example code. The basic principle of writing good example code for the reference is to keep things simple and minimal. The example should be meaningful and explain how the feature works without being too complicated. The example’s canvas should be 100x100 pixels and if the `setup()` function is not included, such as in the example above, the code will be automatically wrapped in a `setup()` function with a default 100x100 pixels gray background canvas created. We won’t go through the details about best practices and code style for the example code here; please see the reference style guide instead. You can have multiple examples for one feature.To do so, add an additional `
` and `` HTML block right after the first closed, separated by a blank line. @@ -235,7 +237,7 @@ You can have multiple examples for one feature.To do so, add an additional `
*
-*  +* *
* * arc(50, 50, 80, 80, 0, PI, OPEN); @@ -262,8 +264,8 @@ If you do not want the example to be run as part of the automated tests (for exa * @example *
* function setup() { -*   let c = createCanvas(100, 100); -*   saveCanvas(c, 'myCanvas', 'jpg'); +* let c = createCanvas(100, 100); +* saveCanvas(c, 'myCanvas', 'jpg'); * } *
``` @@ -273,7 +275,7 @@ If your example uses external asset files, put them in the [/docs/yuidoc-p5-them ### Add a canvas description using `describe()` -Finally, for every example you add, you are required to use the p5.js function `describe()` in the example to create a screen-reader accessible description for the canvas. Include only one parameter: a string with a brief description of what is happening on the canvas.  +Finally, for every example you add, you are required to use the p5.js function `describe()` in the example to create a screen-reader accessible description for the canvas. Include only one parameter: a string with a brief description of what is happening on the canvas. ``` * @example @@ -281,26 +283,26 @@ Finally, for every example you add, you are required to use the p5.js function ` * * let xoff = 0.0; * function draw() { -*   background(204); -*   xoff = xoff + 0.01; -*   let n = noise(xoff) * width; -*   line(n, 0, n, height); -*   describe('A vertical line moves randomly from left to right.'); +* background(204); +* xoff = xoff + 0.01; +* let n = noise(xoff) * width; +* line(n, 0, n, height); +* describe('A vertical line moves randomly from left to right.'); * } * *
-*  +* *
* * let noiseScale = 0.02; * function draw() { -*   background(0); -*   for (let x = 0; x < width; x += 1) { -*     let noiseVal = noise((mouseX + x) * noiseScale, mouseY * noiseScale); -*     stroke(noiseVal*255); -*     line(x, mouseY + noiseVal * 80, x, height); -*   } -*   describe('A horizontal wave pattern moves in the opposite direction of the mouse.'); +* background(0); +* for (let x = 0; x < width; x += 1) { +* let noiseVal = noise((mouseX + x) * noiseScale, mouseY * noiseScale); +* stroke(noiseVal*255); +* line(x, mouseY + noiseVal * 80, x, height); +* } +* describe('A horizontal wave pattern moves in the opposite direction of the mouse.'); * } * *
@@ -315,15 +317,15 @@ With all the above you should have most of the tools needed to write and edit p5 You can use the `@private` if a property or variable is a private function or variable. If a feature is marked as `@private` it will not be included as part of the rendered reference on the website. The reason to use the `@private` tag to mark a reference comments block as private is when you document internal features for the library itself. For example, see the reference comments for `_start` below: -    + ``` /** - * _start calls preload() setup() and draw() - *  - * @method _start - * @private - */ + * _start calls preload() setup() and draw() + * + * @method _start + * @private + */ p5.prototype._start = function () { ``` @@ -338,12 +340,12 @@ The `@requires` tag defines the required imported modules that the current modul ``` /** - * @module Color - * @submodule Creating & Reading - * @for p5 - * @requires core - * @requires constants - */ + * @module Color + * @submodule Creating & Reading + * @for p5 + * @requires core + * @requires constants + */ ``` The convention p5.js follows is that each subfolder in the `src/` folder will be one `@module` while each file inside the subfolder will be its own `@submodule` under the overall subfolder’s `@module`. Unless you are adding new subfolders/files to the p5.js source code, you shouldn’t need to edit this reference comments block. @@ -355,31 +357,31 @@ Class constructors are defined with the `@class` tag and the `@constructor` tag. ``` /** - * A class to describe a color. Each `p5.Color` object stores the color mode - * and level maxes that were active during its construction. These values are - * used to interpret the arguments passed to the object's constructor. They - * also determine output formatting such as when - * saturation() is called. - * - * Color is stored internally as an array of ideal RGBA values in floating - * point form, normalized from 0 to 1. These values are used to calculate the - * closest screen colors, which are RGBA levels from 0 to 255. Screen colors - * are sent to the renderer. - * - * When different color representations are calculated, the results are cached - * for performance. These values are normalized, floating-point numbers. - * - * color() is the recommended way to create an instance - * of this class. - * - * @class p5.Color - * @constructor - * @param {p5} [pInst]                  pointer to p5 instance. - * - * @param {Number[]|String} vals        an array containing the color values - *                                      for red, green, blue and alpha channel - *                                      or CSS color. - */ + * A class to describe a color. Each `p5.Color` object stores the color mode + * and level maxes that were active during its construction. These values are + * used to interpret the arguments passed to the object's constructor. They + * also determine output formatting such as when + * saturation() is called. + * + * Color is stored internally as an array of ideal RGBA values in floating + * point form, normalized from 0 to 1. These values are used to calculate the + * closest screen colors, which are RGBA levels from 0 to 255. Screen colors + * are sent to the renderer. + * + * When different color representations are calculated, the results are cached + * for performance. These values are normalized, floating-point numbers. + * + * color() is the recommended way to create an instance + * of this class. + * + * @class p5.Color + * @constructor + * @param {p5} [pInst] pointer to p5 instance. + * + * @param {Number[]|String} vals an array containing the color values + * for red, green, blue and alpha channel + * or CSS color. + */ ``` @@ -387,7 +389,7 @@ Class constructors are defined with the `@class` tag and the `@constructor` tag. The p5.js repository is set up so that you can generate and preview the reference without needing to build and run the p5.js website as well. -- The main command to generate the reference from the reference comments in the source code is to run the following command.  +- The main command to generate the reference from the reference comments in the source code is to run the following command. ``` npm run docs diff --git a/contributor_docs/contributor_guidelines.md b/contributor_docs/contributor_guidelines.md index 80a3d4c9fb..cc7b08341f 100644 --- a/contributor_docs/contributor_guidelines.md +++ b/contributor_docs/contributor_guidelines.md @@ -1,3 +1,5 @@ + + # Contributor Guidelines Welcome to the contributor guidelines! This document is for new contributors looking to contribute code to p5.js, contributors looking to refresh their memories on some technical steps, or just about anything else to do with code contributions to p5.js. @@ -455,11 +457,11 @@ git push -u origin [branch_name] Once the push is complete, you may see a link in the terminal that lets you open a pull request, if not you can navigate to your fork in your web browser, switch to the branch you are working on with the dropdown button on top of the file list, click on "Contribute" then "Open pull request." -![](https://lh7-us.googleusercontent.com/xoqM9gLSFXyw7b3gzG8JlHqoO0zxHALbjSz93E3D0HNh4Jw2wDWdzHKUEchnB6hdjQC7hVn-o5prrXkLw2WiEOoVKJF6kpmyA65sirN0z-Vy3PBY3rCXC5Ifn5stQhcdUQxQS0rsVoW0_hlkfTcY8PQ) +![Screenshot of the git command line response after pushing a new branch. It includes a GitHub link to open a new pull request.](images/new-branch.png) You may also see a button to open a pull request when you visit the p5.js Github repo. Clicking it will also work to open a new pull request. -![Cropped screenshot of the main page of the p5.js GitHub repository web page. A section near the top of the page is a yellow call to action box containing a green button with the text "Compare & pull request".](images/recent-pushes) +![Cropped screenshot of the main page of the p5.js GitHub repository web page. A section near the top of the page is a yellow call to action box containing a green button with the text "Compare & pull request".](images/recent-pushes.png) ### Pull request information diff --git a/contributor_docs/creating_libraries.md b/contributor_docs/creating_libraries.md index 0974213ae2..3bd66a4055 100644 --- a/contributor_docs/creating_libraries.md +++ b/contributor_docs/creating_libraries.md @@ -1,3 +1,5 @@ + + # Creating an Addon Library A p5.js addon library is JavaScript code that extends or adds to the p5.js core functionality. While p5.js itself already provides a wide range of functionality, it doesn’t aim to cover everything you can do with JavaScript and the Web API. Addon libraries let you extend p5.js without needing to incorporate the features into p5.js. This guide will take you through the steps of creating an addon library that loads a simple CSV file by implementing a `loadCSV()` function. @@ -32,7 +34,7 @@ The main way to extend p5.js is by adding methods to the p5.prototype object. Fo ```js p5.prototype.loadCSV = function(){ -  console.log('I will load a CSV file soon!'); + console.log('I will load a CSV file soon!'); }; ``` @@ -42,7 +44,7 @@ You can also extend p5.js classes such as` p5.Element` or` p5.Graphics` by addin ```js p5.Element.prototype.shout = function () { -  this.elt.innerHTML += '!'; + this.elt.innerHTML += '!'; }; ``` @@ -53,23 +55,23 @@ You now have a p5.loadcsv.js file with one method attached to the `p5.prototype` ```js function setup() { -  createCanvas(400, 400); -  loadCSV(); + createCanvas(400, 400); + loadCSV(); } ``` ```html -   -     + + + + + -     -     + + -     -   -   -   + ``` @@ -83,20 +85,20 @@ To load a CSV file with your `loadCSV()` function, the function needs to accept ```js p5.prototype.loadCSV = function (filename) { -  console.log(`I will load the CSV file ${filename} soon!`); + console.log(`I will load the CSV file ${filename} soon!`); }; ``` -  + In our test sketch, we can use it like so: ```js function setup() { -  createCanvas(400, 400); + createCanvas(400, 400); -  // Prints "I will load the CSV file data.csv soon!" to the console. -  loadCSV('data.csv'); + // Prints "I will load the CSV file data.csv soon!" to the console. + loadCSV('data.csv'); } ``` @@ -111,17 +113,17 @@ You can access p5.js functions and variables such as `circle()` and `PI` in your ```js p5.prototype.loadCSV = (filename) => { -  // this === window is true because -  // "this" refers to the window object. -  // This is almost never what you want. -  console.log(this === window); + // this === window is true because + // "this" refers to the window object. + // This is almost never what you want. + console.log(this === window); }; p5.prototype.loadCSV = function (filename) { -  // Prints 'I will load the CSV file data.csv at 10:30' -  // to the console. -  console.log(`I will load the CSV file ${filename} at ${this.hour()}:${this.minute()}!`); + // Prints 'I will load the CSV file data.csv at 10:30' + // to the console. + console.log(`I will load the CSV file ${filename} at ${this.hour()}:${this.minute()}!`); }; ``` @@ -136,19 +138,19 @@ First make the following changes to your `loadCSV()` method: ```js p5.prototype.loadCSV = function(filename){ -  console.log(`I will load the CSV file ${filename} at ${this.hour()}:${this.minute}!`); + console.log(`I will load the CSV file ${filename} at ${this.hour()}:${this.minute}!`); -  let result = []; + let result = []; -  fetch(filename) -    .then((res) => res.text()) -    .then((data) => { -      data.split('\n').forEach((line) => { -        result.push(line.split(',')); -      }); -    }); + fetch(filename) + .then((res) => res.text()) + .then((data) => { + data.split('\n').forEach((line) => { + result.push(line.split(',')); + }); + }); -  return result; + return result; }; ``` @@ -158,9 +160,9 @@ Now, when you run the sketch, pass a file path to a simple CSV file to your `loa ```js function setup(){ -  createCanvas(400, 400); -  let myCSV = loadCSV('data.csv'); -  print(myCSV); + createCanvas(400, 400); + let myCSV = loadCSV('data.csv'); + print(myCSV); } ``` @@ -172,12 +174,12 @@ Simply moving where you call `loadCSV()` to `preload()` in this case is not enou let myCSV; function preload(){ -  myCSV = loadCSV('data.csv'); + myCSV = loadCSV('data.csv'); } function setup(){ -  createCanvas(400, 400); -  print(myCSV); // Still prints []  + createCanvas(400, 400); + print(myCSV); // Still prints [] } ``` @@ -185,21 +187,21 @@ p5 will need to be told that the addon’s `loadCSV()` function is something it ```js p5.prototype.loadCSV = function (filename){ -  console.log(`I will load the CSV file ${filename} at ${this.hour()}:${this.minute}!`); + console.log(`I will load the CSV file ${filename} at ${this.hour()}:${this.minute}!`); -  let result = []; + let result = []; -  fetch(filename) -    .then((res) => res.text()) -    .then((data) => { -      data.split('\n').forEach((line) => { -        result.push(line.split(',')); -      }); + fetch(filename) + .then((res) => res.text()) + .then((data) => { + data.split('\n').forEach((line) => { + result.push(line.split(',')); + }); -      this._decrementPreload(); -    }); + this._decrementPreload(); + }); -  return result; + return result; }; p5.prototype.registerPreloadMethod('loadCSV', p5.prototype); @@ -245,13 +247,13 @@ To create an action hook, you can use the snippet below. ```js p5.prototype.doRemoveStuff = function (){ -  // Addon library related cleanup + // Addon library related cleanup }; p5.prototype.registerMethod("remove", p5.prototype.doRemoveStuff); p5.prototype.setDefaultBackground = function(){ -  // Set background to be p5 pink by default  -  this.background("#ed225d"); + // Set background to be p5 pink by default + this.background("#ed225d"); }; p5.prototype.registerMethod("pre", p5.prototype.setDefaultBackground); ``` diff --git a/contributor_docs/design_principles.md b/contributor_docs/design_principles.md index a32d23d1c2..0c1b787522 100644 --- a/contributor_docs/design_principles.md +++ b/contributor_docs/design_principles.md @@ -1,3 +1,5 @@ + + # Design principles for p5.js - **Beginner Friendly** The p5.js API aims to be friendly to beginner coders, offering a low barrier to creating interactive and visual web content with cutting-edge HTML5/canvas/DOM APIs. diff --git a/contributor_docs/documentation_style_guide.md b/contributor_docs/documentation_style_guide.md index 76d52c12d1..7dbf721621 100644 --- a/contributor_docs/documentation_style_guide.md +++ b/contributor_docs/documentation_style_guide.md @@ -1,3 +1,5 @@ + + # Documentation Style Guide Hello! Welcome to the guidelines for writing p5.js documentation. This document is a remix of the following resources: @@ -35,6 +37,7 @@ Our community is large and diverse. Many people learn to code using p5.js, and a - [Arrays](#arrays) - [Functions](#functions) - [Arrow Functions](#arrow-functions) +- [Chaining](#chaining) - [Classes](#classes) - [Assets](#assets) @@ -1041,6 +1044,30 @@ function processImage(img) { // Good. [1, 2, 3].map((number) => number * number); ``` +**[⬆ back to top](#table-of-contents)** + +## Chaining + +* Use individual function calls instead of function chaining. + +> Why? To accommodate users who may not be familiar with the concept of function chaining. + +```javascript +// Bad. +fill(0) + .strokeWeight(6) + .textSize(20); + +// Bad. +fill(0).strokeWeight(6).textSize(20); + +// Good. +fill(0); +strokeWeight(6); +textSize(20); +``` + +**[⬆ back to top](#table-of-contents)** ## Classes diff --git a/contributor_docs/es/contributing_to_the_p5.js_reference.md b/contributor_docs/es/contributing_to_the_p5.js_reference.md new file mode 100644 index 0000000000..e1dc00139c --- /dev/null +++ b/contributor_docs/es/contributing_to_the_p5.js_reference.md @@ -0,0 +1,398 @@ +# Contribuir a la referencia de p5.js + +En p5.js, creamos las referencias de código que ves en la página de [referencia](https://p5js.org/reference/) del sitio web de p5.js incluyéndolas junto al código fuente de la biblioteca como comentarios especializados. Estos comentarios de referencia incluyen la descripción, la firma de la función (sus parámetros y valor de retorno) y ejemplos de uso. En otras palabras, el contenido en la página de referencia de cada función/variable de p5.js se construye a partir de los comentarios de referencia en el código fuente. + +Este documento te mostrará cómo escribir y formatear los comentarios de referencia para que eventualmente puedan ser renderizados correctamente en el sitio web. Debes seguir esta guía siempre que estés editando o escribiendo una referencia para cualquier función o variable de p5.js. + +## Una introducción rápida al funcionamiento de los comentarios de referencia + +Cuando mires el código fuente de p5.js, verás que muchas líneas en la biblioteca son comentarios de referencia; se ven así: + +``` +/** + * Calculates the sine of an angle. `sin()` is useful for many geometric tasks + * in creative coding. The values returned oscillate between -1 and 1 as the + * input angle increases. `sin()` takes into account the current + * angleMode. + * + * @method sin + * @param {Number} angle the angle. + * @return {Number} sine of the angle. + * + * @example + *
+ * + * function draw() { + * background(200); + * + * let t = frameCount; + * let x = 50; + * let y = 30 * sin(t * 0.05) + 50; + * line(x, 50, x, y); + * circle(x, y, 20); + * + * describe('A white ball on a string oscillates up and down.'); + * } + * + *
+ * + *
+ * + * function draw() { + * let x = frameCount; + * let y = 30 * sin(x * 0.1) + 50; + * point(x, y); + * + * describe('A series of black dots form a wave pattern.'); + * } + * + *
+ * + *
+ * + * function draw() { + * let t = frameCount; + * let x = 30 * cos(t * 0.1) + 50; + * let y = 10 * sin(t * 0.2) + 50; + * point(x, y); + * + * describe('A series of black dots form an infinity symbol.'); + * } + * + *
+ */ +``` + +Por lo general, estos comentarios están seguidos del código JavaScript real que define a la función. Los comentarios de referencia siempre comienzan con `/**` y terminan con `*/`, con cada línea entre los dos con `*` al inicio. + +Cualquier cosa en un bloque de estos se interpretará como documentación de referencia. Es posible que estés familiarizado con este estilo de comentarios de código a través de [JSDoc](https://jsdoc.app/). Aunque p5.js no usa JSDoc, utiliza una herramienta llamada [YUIDoc](https://yui.github.io/yuidoc/) que tiene una sintaxis para referencias muy similar. En este estilo de comentarios de referencia cada bloque de comentarios se subdivide en elementos individuales, como veremos a continuación. + +## Bloque de comentarios de referencia + +Desglosemos el bloque de comentarios de referencia anterior para la función `sin()` y veamos qué hace cada sección. Puedes comparar lo que vez en estos comentarios con el contenido de la página de referencia para [`sin()`](https://p5js.org/reference/#/p5/sin). + +``` +/** + * Calculates the sine of an angle. `sin()` is useful for many geometric tasks + * in creative coding. The values returned oscillate between -1 and 1 as the + * input angle increases. `sin()` takes into account the current + * angleMode. +``` + +En la parte superior del comentario está la descripción textual de la función. Esta descripción puede contener tanto sintaxis de markdown como HTML. La descripción debe ser concisa y describir qué hace la función y, si es necesario, algunos detalles sobre sus peculiaridades o comportamientos. + +``` + * @method sin + * @param {Number} angle the angle. + * @return {Number} sine of the angle. +``` + +Una función normalmente tendrá las tres secciones anteriores, cada una comenzando con el símbolo `@` seguido de una de las siguientes palabras clave: + +- `@method` se usa para definir el nombre de la función, en este caso `sin` (nota que el nombre de la función no incluye los paréntesis `()`). +- `@param` se usa para definir los parámetros o argumentos que acepta la función. + - Después de la palabra clave `@param`, almacenado entre llaves `{}`, está el tipo del parámetro. + - Después del tipo, la siguiente palabra (angle) es el nombre del parámetro. + - Después del nombre, el resto de la línea es la descripción del parámetro. +- `@return` se usa para definir el valor de retorno de la función. + - Después de la palabra clave `@return`, almacenado entre llaves `{}`, está el tipo de valor del retorno. + - Después del tipo, el resto de la línea es la descripción del valor de retorno. + +Para los parámetros este es el formato genérico: + +``` +@param {type} name Description here. +``` + +Si el parámetro es opcional, agrega corchetes alrededor del nombre: + +``` +@param {type} [name] Description here. +``` + +### Información adicional: Constantes + +Si el parámetro toma uno o más valores definidos en [`constants.js`](https://github.com/processing/p5.js/blob/main/src/core/constants.js), entonces el tipo debe especificarse como `{Constant}` y los valores válidos deben enumerarse en el comentario que sigue a la palabra clave `either`, por ejemplo: + +``` +@param {Constant} horizAlign horizontal alignment, either LEFT, CENTER, or RIGHT +``` + +Para los tipos de retorno, debes seguir este formato: + +``` +@return {type} Description of the data returned. +``` + +Si la función no tiene un valor de retorno, puedes omitir la etiqueta `@return`. + +### Información adicional: Encadenamiento + +Si el método devuelve el objeto de la superclase, puedes omitir la etiqueta `@return` y agregar esta línea en su lugar: + +``` +@chainable +``` + +## Firmas adicionales + +Si una función tiene múltiples opciones de parámetros posibles, puedes especificar cada una individualmente. Por ejemplo, la función [`background()`](http://p5js.org/reference/#p5/background) toma una serie de opciones de parámetros diferentes (ver la sección "Sintaxis" en la página de referencia). Elige una versión para incluirla como la primera firma usando la plantilla anterior. Al final del primer bloque de comentarios de referencia puedes agregar firmas adicionales, cada una en su propio bloque, como en el siguiente ejemplo. + +``` +/** + * @method background + * @param {String} colorstring color string, possible formats include: integer + * rgb() or rgba(), percentage rgb() or rgba(), + * 3-digit hex, 6-digit hex + * @param {Number} [a] alpha value + */ + +/** + * @method background + * @param {Number} gray specifies a value between white and black + * @param {Number} [a] + */ +``` + +### Información adicional: Múltiples firmas + +No es necesario crear una firma separada si la única diferencia entre dos firmas es la adición de un parámetro opcional. Limita el uso de esta función en la medida de lo posible porque puede crear ruido innecesario en la referencia. + +## Referencia para variables de p5.js + +Hasta ahora hemos visto cómo escribir referencias para funciones y constantes. Las variables siguen la misma estructura, pero usan etiquetas diferentes. + +``` +/** + * The system variable mouseX always contains the current horizontal + * position of the mouse, relative to (0, 0) of the canvas. The value at + * the top-left corner is (0, 0) for 2-D and (-width/2, -height/2) for WebGL. + * If touch is used instead of mouse input, mouseX will hold the x value + * of the most recent touch point. + * + * @property {Number} mouseX + * @readOnly + * + * @example + *
+ * + * // Move the mouse across the canvas + * function draw() { + * background(244, 248, 252); + * line(mouseX, 0, mouseX, 100); + * describe('horizontal black line moves left and right with mouse x-position'); + * } + * + *
+ */ +``` + +El inicio del bloque contiene la descripción de la variable (`mouseX` en este caso). Para definir el nombre de la variable usamos `@property` en lugar de `@method`. `@property` sigue la misma sintaxis que `@param` para definir el tipo y su nombre. La etiqueta `@readonly` está presente en la mayoría de las variables de p5.js y se utiliza internamente para indicar que dicho valor no debe ser sobrescrito directamente por un usuario de la biblioteca. + +## Agregar ejemplos + +Una etiqueta que está presente tanto en los comentarios de referencia de `sin()` como de `mouseX` y que aún no hemos discutido es la etiqueta `@example`. Con esta etiqueta defines el código de (los) ejemplo(s) que se ejecuta cuando visitas la página de referencia. + +![Screenshot of the p5.js reference page of the "red()" function, showing only the example code section.](images/reference-screenshot.png) + +El código con la etiqueta `@example` que crea el ejemplo anterior es el siguiente: + +``` + * @example + *
+ * + * const c = color(255, 204, 0); + * fill(c); + * rect(15, 20, 35, 60); + * // Sets 'redValue' to 255. + * const redValue = red(c); + * fill(redValue, 0, 0); + * rect(50, 20, 35, 60); + * describe( + * 'Two rectangles with black edges. The rectangle on the left is yellow and the one on the right is red.' + * ); + * + *
+``` + +Después de la etiqueta `@example`, debes comenzar con una etiqueta HTML `
` seguida de una etiqueta ``. Entre la etiqueta `` de apertura y cierre, insertarás el ejemplo de código en cuestión. El principio básico para escribir un buen ejemplo de código para la referencia es mantener las cosas simples y mínimas. El ejemplo debe ser significativo y explicar cómo funciona la función, valga la redundancia, sin ser demasiado complicado. El lienzo para el ejemplo debe ser de 100x100 pixeles y si la función `setup()` no está incluida, como en el ejemplo anterior, el código será envuelto automáticamente en una función `setup()` con un lienzo predeterminado de fondo gris y 100x100 píxeles. No entraremos aquí en detalles sobre buenas prácticas y estilo para los ejemplos de código; consulta la guía de estilo de referencia en su lugar. + +Puedes tener múltiples ejemplos para una función. Para hacerlo agrega un `
` y un bloque HTML `` adicionales justo después del primer bloque cerrado, separados por una línea en blanco. + +``` +* @example +*
+* +* arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN); +* describe('An ellipse created using an arc with its top right open.'); +* +*
+* +*
+* +* arc(50, 50, 80, 80, 0, PI, OPEN); +* describe('The bottom half of an ellipse created using arc.'); +* +*
+``` + +Si no deseas que la página de referencia ejecute tu código de ejemplo (es decir, solo quieres que se muestre el código), incluye la clase "`norender`" en el `
`: + +``` +* @example +*
+* +* arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN); +* describe('ellipse created using arc with its top right open'); +* +*
+``` + +Si no quieres que el ejemplo se ejecute como parte de las pruebas automatizadas (por ejemplo, si el ejemplo requiere interacción del usuario), incluye la clase "`notest`" en el `
`: + +``` +* @example +*
+* function setup() { +* let c = createCanvas(100, 100); +* saveCanvas(c, 'myCanvas', 'jpg'); +* } +*
+``` + +Si tu ejemplo utiliza archivos externos como recursos, colócalos en la carpeta [/docs/yuidoc-p5-theme/assets](https://github.com/processing/p5.js/tree/main/docs/yuidoc-p5-theme/assets) (o reutiliza uno que ya esté allí) y luego enlázalos con "assets/nombrearchivo.ext" en el código. Consulta la referencia de [tint()](http://p5js.org/reference/#/p5/tint) como ejemplo. + +### Agregar descripción a un lienzo usando `describe()` + +Por último, para cada ejemplo que añadas, se requiere que utilices la función de p5.js `describe()` en el ejemplo para crear una descripción accesible del lienzo para lectores de pantalla. Incluye sólo un parámetro: una cadena con una breve descripción de lo que está sucediendo en el lienzo. + +``` +* @example +*
+* +* let xoff = 0.0; +* function draw() { +* background(204); +* xoff = xoff + 0.01; +* let n = noise(xoff) * width; +* line(n, 0, n, height); +* describe('A vertical line moves randomly from left to right.'); +* } +* +*
+* +*
+* +* let noiseScale = 0.02; +* function draw() { +* background(0); +* for (let x = 0; x < width; x += 1) { +* let noiseVal = noise((mouseX + x) * noiseScale, mouseY * noiseScale); +* stroke(noiseVal*255); +* line(x, mouseY + noiseVal * 80, x, height); +* } +* describe('A horizontal wave pattern moves in the opposite direction of the mouse.'); +* } +* +*
+``` + +Para obtener más información sobre `describe()`, visita la [documentación de accesibilidad web para contribuyentes](https://p5js.org/contributor-docs/#/web_accessibility?id=user-generated-accessible-canvas-descriptions). + +Con todo lo anterior, deberías tener la mayoría de las herramientas necesarias para escribir y editar comentarios de referencia de p5.js. Sin embargo, hay algunos usos más especializados de comentarios de referencia estilo JSDoc que puedes encontrar en p5.js. Estos son útiles en situaciones específicas y no son algo que necesites con frecuencia. + +### Etiqueta `@private` + +Puedes usar la etiqueta `@private` si una propiedad o variable es una función o variable privada. Si una característica está marcada como `@private`, no se renderizará como parte de la referencia en el sitio web. La razón para usar la etiqueta `@private` para marcar un bloque de comentarios de referencia como privado es documentar características internas de la propia biblioteca. Por ejemplo, consulta los comentarios de referencia para `_start` a continuación: + + +``` +/** + * _start calls preload() setup() and draw() + * + * @method _start + * @private + */ +p5.prototype._start = function () { +``` + +### `@module` y otras etiquetas relacionadas + +En la parte superior de cada archivo de código fuente habrá una etiqueta `@module`. Los módulos corresponden a un grupo de características en p5.js que, al renderizar la página de referencia en el sitio web, se dividen en las secciones correspondientes. Dentro de cada módulo hay submódulos adicionales definidos con la etiqueta `@submodule`. + +La etiqueta `@for` define la relación entre este módulo y la clase general `p5`, indicando efectivamente que este módulo es una parte de la clase `p5`. + +La etiqueta `@requires` define los módulos de los que depende el módulo actual y es necesario importar. + +``` +/** + * @module Color + * @submodule Creating & Reading + * @for p5 + * @requires core + * @requires constants + */ +``` + +La convención que sigue p5.js es que cada subcarpeta en la carpeta `src/` será un `@module`, mientras que cada archivo dentro de la subcarpeta será su propio `@submodule` bajo el `@module` general de la subcarpeta. A menos que estés añadiendo nuevas subcarpetas/archivos al código fuente de p5.js, no deberías necesitar editar este bloque de comentarios de referencia. + +### Etiqueta `@class` + +Los constructores de clases se definen con la etiqueta `@class`y la etiqueta `@constructor`. El formato para este bloque es similar a cómo se define una función con el bloque `@method`; el nombre de la clase debe definirse con la etiqueta `@class` y la etiqueta `@constructor` indicará que la clase tiene una función constructora. Mira el ejemplo de la clase `p5.Color` a continuación: + +``` +/** + * A class to describe a color. Each `p5.Color` object stores the color mode + * and level maxes that were active during its construction. These values are + * used to interpret the arguments passed to the object's constructor. They + * also determine output formatting such as when + * saturation() is called. + * + * Color is stored internally as an array of ideal RGBA values in floating + * point form, normalized from 0 to 1. These values are used to calculate the + * closest screen colors, which are RGBA levels from 0 to 255. Screen colors + * are sent to the renderer. + * + * When different color representations are calculated, the results are cached + * for performance. These values are normalized, floating-point numbers. + * + * color() is the recommended way to create an instance + * of this class. + * + * @class p5.Color + * @constructor + * @param {p5} [pInst] pointer to p5 instance. + * + * @param {Number[]|String} vals an array containing the color values + * for red, green, blue and alpha channel + * or CSS color. + */ +``` + +## Generando y previsualizando la referencia + +El repositorio de p5.js está configurado para que puedas generar y previsualizar la referencia sin necesidad de compilar y ejecutar también el sitio web de p5.js. + +- El comando principal para generar la referencia a partir de los comentarios de referencia en el código fuente es el siguiente. + +``` +npm run docs +``` + +Esto generará los archivos de vista previa necesarios y el archivo principal `docs/reference/data.json`, que es el mismo archivo (después de la minificación) que se utilizará para renderizar la página de referencia en el sitio web. + +- Para trabajar continuamente en la referencia, puedes ejecutar el siguiente comando. + +``` +npm run docs:dev +``` + +Esto lanzará una vista previa en vivo de la referencia cuyo renderizado se actualizará cada vez que realices cambios (necesitarás actualizar la página después de realizar cambios para verlos aparecer). Esto es útil, especialmente para previsualizar el código de ejemplos que se ejecutan en el navegador. + +- Los archivos de plantilla principales se almacenan en la carpeta `docs/` y, en la mayoría de los casos, no deberías realizar cambios directamente en los archivos de esta carpeta, excepto para añadir nuevos archivos de recursos en la carpeta `docs/yuidoc-p5-theme/assets`. + +## Siguientes pasos + +Para más detalles sobre el sistema de referencias puedes consultar la documentación de [JSDoc](https://jsdoc.app/) y [YUIDoc](https://yui.github.io/yuidoc/). + +Para ver ejemplos de problemas relacionados con las referencias, echa un vistazo a [#6519](https://github.com/processing/p5.js/issues/6519) y [#6045](https://github.com/processing/p5.js/issues/6045). El documento de [pautas para contribuyentes](https://github.com/processing/p5.js/blob/main/contributor_docs/es/contributor_guidelines.md) también es un buen lugar para comenzar. diff --git a/contributor_docs/es/contributor_guidelines.md b/contributor_docs/es/contributor_guidelines.md new file mode 100644 index 0000000000..24e30738bc --- /dev/null +++ b/contributor_docs/es/contributor_guidelines.md @@ -0,0 +1,543 @@ +# Instrucciones para colaboradores + +¡Bienvenidos! Este documento está diseñado para ayudar a nuevos contribuidores que deseen aportar código a la biblioteca de p5.js, así como a aquellos que busquen refrescar sus conocimientos sobre procedimientos técnicos. También es útil para cualquier persona interesada en realizar cualquier tipo de contribución al código de p5.js. + +Si estás buscando contribuir más allá de los repositorios de p5.js (escribiendo tutoriales, planeando clases, organizando eventos), por favor consulta la documentación correspondiente para este tipo de colaboraciones. Aquellos que sean Supervisores o Responsables de mantenimiento, encontrarán más útil referirse a las [Instrucciones para Supervisores](https://github.com/processing/p5.js/blob/main/contributor_docs/es/steward_guidelines.md) cuando se trata de revisar 'Issues' (problemas) y 'Pull Requests'. + +Este es un documento relativamente largo e integral, pero trataremos de indicar todos los pasos tan claro como sea posible. Utiliza la tabla de contenidos para encontrar las secciones que son relevantes para ti, y siéntete libre de omitir secciones que no son relevantes para las contribuciones que planeas hacer. + +**Si eres un nuevo contribuidor te sugerimos comenzar con la primera sección: “Todo acerca de los 'Issues' (o problemas)”. Si simplemente quieres una configuración paso-a-paso del proceso de desarrollo, puedes dirigirte a la sección de “Inicio Rápido para Desarrolladores”.** + + +# Tabla de Contenidos + +- [Todo acerca de los 'Issues' o problemas](#todo-acerca-de-los-issues-o-problemas) + - [¿Qué son los 'Issues' en GitHub?](#qué-son-los-issues-en-github) + - [Plantillas para reportar 'Issues'](#plantillas-para-reportar-issues) + - [Reportar un error](#reportar-un-error) + - [Sugerir una mejora a una funcionalidad existente](#sugerir-una-mejora-a-una-funcionalidad-existente) + - [Sugerir una funcionalidad nueva](#sugerir-una-funcionalidad-nueva) + - [Abrir una discusión ](#abrir-una-discusión) +- [Trabajando en la base de código de p5.js](#trabajando-en-la-base-de-código-de-p5js) + - [Inicio Rápido para Desarrolladores](#inicio-rápido-para-desarrolladores) + - [Utilizando la funcionalidad de edición de Github](#utilizando-la-funcionalidad-de-edición-de-github) + - [Haciendo un fork de p5.js y trabajando desde tu fork](#haciendo-un-fork-de-p5js-y-trabajando-desde-tu-fork) + - [Utilizando Github Desktop](#utilizando-github-desktop) + - [Utilizando la interfaz de línea de comandos de Git](#utilizando-la-interfaz-de-línea-de-comandos-de-git) + - [Desglose de la base de código ](#desglose-de-la-base-de-código) + - [Configuración de compilación](#configuración-de-compilación) + - [Flujo de trabajo de Git](#flujo-de-trabajo-de-git) + - [Código fuente](#código-fuente) + - [Pruebas unitarias](#pruebas-unitarias) + - [Documentación en línea](#documentación-en-línea) + - [Internacionalización](https://github.com/processing/p5.js/blob/main/contributor_docs/contributor_guidelines.md#internationalization) + - [Accesibilidad](#accesibilidad) + - [Estándares de código](#estándares-de-código) + - [Principios de Diseño de Software](#principios-de-diseño-de-software) +- [Pull Requests](#pull-requests) + - [Creación de un Pull Request](#creación-de-un-pull-request) + - [Información sobre el Pull Request](#información-sobre-el-pull-request) + - [Titulo](#titulo) + - [Resuelve](#resuelve) + - [Cambios](#cambios) + - [Captura de pantalla de los cambios](#captura-de-pantalla-de-los-cambios) + - [Lista de verificación del Pull Request](#lista-de-verificación-del-pull-request) + - [Rebase y resolución de conflictos](#rebase-y-resolución-de-conflictos) + - [Discutir y Corregir](#discutir-y-corregir) + +--- +# Todo acerca de los “Issues” o problemas + +La mayoría de la actividad en los repositorios de GitHub de p5.js (también conocidos como "repo" de forma abreviada) ocurre en los 'Issues', o problemas, lo cual es un excelente lugar para comenzar tu viaje de contribución. + + +## ¿Qué son los "Issues" en GitHub? + +![A cropped screenshot of the p5.js library GitHub repository, only showing contents of the top right corner. A red box is drawn on top of the screenshot surrounding the Issues tab.](../images/issues-tab.png) + +'Issues' es el nombre común que se le da a una publicación en GitHub que apunta a describir, como lo dice su nombre, un problema. Los Issues pueden ser reportes de error, solicitudes para añadir un nueva funcionalidad, una discusión, o cualquier publicación que se relacione con el desarrollo de la biblioteca de p5.js. Cualquiera con una cuenta de GitHub puede añadir comentarios debajo de cada Issue, ¡incluyendo bots! Este es el lugar donde los contribuidores discuten temas relacionados con el desarrollo del proyecto dentro del repositorio. + +Mientras un Issue puede ser creado por diferentes razones, usualmente utilizamos la creación de un Issue para discutir el desarrollo del código fuente de p5.js. Temas como la corrección de errores de tu propio código, invitación de colaboradores a tu proyecto, u otros temas no relacionados, deben ser discutidos ya sea en el [foro](https://discourse.processing.com) o en otras plataformas de comunicación como [Discord](https://discord.gg/SHQ8dH25r9). + +¡Hemos creado plantillas fáciles de usar que puede ayudarte a determinar si un tema es adecuado para ser publicado como un Issue en GitHub, o si sería más apropiado publicarlo en otro lugar! + + +## Plantillas para reportar "Issues" +Las plantillas para reportar Issues en p5.js hacen que sea más sencillo para los Supervisores y los responsables de mantenimiento entender y revisar el contenido sugerido por el colaborador. Además, las plantillas le facilitan al colaborador el proceso de completar un Issue y, así mismo, le permiten recibir una respuesta más rápida. + +![Screenshot of an example of what an issue looks like on GitHub. The title of the issue in the screenshot is "Warning being logged in Safari when using a filter shader in 2D mode #6597"](../images/github-issue.png) + +Para registrar un Issue por primera vez dentro del repositorio de p5.js, haz click en la pestaña que dice "Issues", ubicada en la parte superior. Una vez dentro de la página de "Issues" haz clic en el botón "New Issue" (problema nuevo), que se encuentra al costado derecho. Se te presentarán diferentes opciones de plantilla que te van a dirigir al lugar adecuado para registrar tu Issue. Te recomendamos elegir la plantilla más relevante para tu caso para asegurarte de que tu Issue reciba rápidamente la atención correcta. + +![Cropped screenshot of the GitHub repository's issue page with the green "New issue" button highlighted with a red box surrounding it.](../images/new-issue.png) + +### ["Reportar un Error"](https://github.com/processing/p5.js/issues/new?assignees=\&labels=Bug\&projects=\&template=found-a-bug.yml) + +Cuando encuentres un comportamiento incorrecto en p5.js, o algo que no se esté comportando como se ha descrito en la documentación, [usa esta plantilla]( https://github.com/processing/p5.js/issues/new?assignees=&labels=Bug&projects=&template=found-a-bug.yml). Por favor, ten en cuenta que si estás tratado de corregir el código de tu sketch (boceto), y crees que el problema tal vez se encuentra en tu código, primero consulta en el [foro de discusiones]( https://discourse.processing.org/) antes de reportar un error. + +Esta plantilla provee campos que debes llenar con la siguiente información relevante: + +1. **¿Cuál es la subárea más adecuada de p5.js?:** esto añadirá automáticamente las [etiquetas]( https://github.com/processing/p5.js/blob/main/contributor_docs/issue_labels.md) relevantes a tu Issue, lo que nos ayudará a identificar y responder adecuadamente. +2. **Versión de p5.js:** Puedes verificar la versión de p5.js dentro de la etiqueta `