UNPKG

p5

Version:

[![npm version](https://badge.fury.io/js/p5.svg)](https://www.npmjs.com/package/p5)

249 lines (248 loc) • 12.4 kB
import { gn as VERSION } from "./constants-DA50zLWL.js"; import { TL } from "tl-util"; //#endregion //#region src/friendly_errors/fes.js TL.addTranslations([ "en", "en-US", "en-GB" ], { tkkbbojj0n: "Sorry, Could not set the attributes, you need to call setAttributes() before calling the other drawing methods in setup()", wji0jlntb6: "Error during parsing: ${error.message}", "6eru983h1s": "Sorry, the file type is invalid. Only OBJ and STL files are supported.", wuo7dk4fkf: "It looks like you've called ${functionName} outside of a shader's modify() function.", ecbfo4yfrl: "It looks like you've called getTexture outside of a shader's modify() function.", btvs56mkpo: "It looks like you've called noise() with ${args.length} arguments. It only supports 1D to 3D input.", pzoz7wj542: "It looks like you've called random() with ${args.length} arguments. In strands, random() supports 0, 1, or 2 numeric arguments.", lgfuy6eb2r: "It looks like you've called ${typeInfo.fnName} outside of a shader's modify() function.", "4lplbdw1xp": "file", dl8q3ezp00: "JSON file", "99dup7cw27": "text file", vzls8t7bw4: "It looks like there was a problem loading your ${errorFileType}. Try checking if the file path (${path}) is correct, hosting the file online, or running a local server.\n\n+ More info: ${infoURL}", "5cz1brq3ke": "There was some trouble loading your GIF. Make sure that your GIF is using 87a or 89a encoding.", "1kv37lrbjy": "🌸 p5.js says: ", ordinal1: "first", ordinal2: "second", ordinal3: "third", ordinal4: "fourth", ordinal5: "fifth", ordinal6: "sixth", ordinal7: "seventh", ordinal8: "eighth", ordinal9: "ninth", ordinal10: "tenth", typeString: "string", typeBoolean: "boolean", typeNumber: "number", typeFunction: "function", "54cbftewi2": "${message} (https://p5js.org/reference/${referenceSection}.${funcName})", rnwntgqpx8: "${message} (https://p5js.org/reference/${referenceSection}/${funcName})", jya7nlorb5: "The preload() function has been removed in p5.js 2.0. Please load assets in setup() using async / await keywords or callbacks instead. See https://github.com/processing/p5.js-compatibility for more information about 2.0 and compatibility, or https://dev.to/limzykenneth/asynchronous-p5js-20-458f for more information about promises and async/await.", qj9oojqr1i: "It seems that you may have accidentally written ${prop} instead of ${fxns[lowercase]}. Please correct it if it's not intentional.", "0t1z3tmmr8": "${locationObj\n ? FES.log`[${locationObj.file}, line ${locationObj.line}]`\n : ''} It seems that you may have accidentally written \"${errSym}\" instead of \"${matchedSymbols[0].name}\". Please correct it to ${matchedSymbols[0].name} if you wish to use the ${matchedSymbols[0].type} from p5.js.", ita6bv1dd3: "[${locationObj.file}, line ${locationObj.line}]", "2xeoxf2b68": "${locationObj\n ? FES.log`[${locationObj.file}, line ${locationObj.line}]`\n : ''} It seems that you may have accidentally written \"${errSym}\".\\nYou may have meant one of the following: \\n${suggestions}", mfljpzrw6p: "Did you just try to use p5.js's ${symbolName} ${symbol.type}? If so, you may want to move it into your sketch's setup() function.\\n\\nFor more details, see: ${FAQ_URL}", aorhrzsojk: "Syntax Error - Found a symbol that JavaScript doesn't recognize or didn't expect at its place.\\n\\n+ More info: ${url}", xrwjb1a7yc: "Syntax Error - Symbol present at a place that wasn't expected.\\nUsually this is due to a typo. Check the line number in the error for anything missing/extra.\\n\\n+ More info: ${url}", redeclare: "Syntax Error - \"${errSym}\" is being redeclared. JavaScript doesn't allow declaring a variable more than once. Check the line number in error for redeclaration of the variable.\\n\\n+ More info: ${url}", "6tfheg3s15": "Syntax Error - A const variable is declared but not initialized. In JavaScript, an initializer for a const is required. A value must be specified in the same statement in which the variable is declared. Check the line number in the error and assign the const variable a value.\\n\\n+ More info: ${url}", ywpv6fodj4: "Syntax Error - return lies outside of a function. Make sure you’re not missing any brackets, so that return lies inside a function.\\n\\n+ More info: ${url}", a694k1m6nn: "at the ${ordinals[position]} parameter", "00gwqo2yxt": ", but received ${actualType}", jfjwdczlfk: "Expected ${expectedTypeStr} ${positionStr}${actualTypeStr}", "1roh3zggwt": "Did you mean to put \\`await\\` before a loading function? An unexpected Promise was found. ", ltzhpuu4r8: "${message}${buildTypeMismatchMessage(actualType, expectedTypesStr, position)} in ${func + '()'}.", referenceLink: "For more information, see ${documentationLink}.", paramTooFew: { "${minArgs}_[one]": "Expected at least ${minArgs} argument, but received fewer in ${func}(). ${referenceLink}", "${minArgs}_[*]": "Expected at least ${minArgs} arguments, but received fewer in ${func}(). ${referenceLink}" }, paramTooMany: { "${minArgs}_[one]": "Expected at most ${maxArgs} argument, but received more in ${func}(). ${referenceLink}", "${minArgs}_[*]": "Expected at most ${maxArgs} arguments, but received more in ${func}(). ${referenceLink}" }, paramType: "Expected ${typeName} at the ${position} parameter in ${funcName}.", hr7vkbw7rp: "┌[${location}] \\n\\t Error at line ${frame.lineNumber} in ${frame.functionName}()\\n", zcob0p6ap3: "└[${location}] \\n\\t Called from line ${frame.lineNumber} in ${frame.functionName}()\\n", e1bltb2f3i: "The media that tried to play (with '${this.src}') wasn't allowed to by this browser, most likely due to the browser's autoplay policy.\\n\\n+ More info: https://developer.mozilla.org/docs/Web/Media/Autoplay_guide", fxcmxx850s: "${experimentalMessages[subjectArea]} For more info, see https://p5js.org/contribute/${subjectArea}/", ukmn4qp8ql: "To create a WEBGPU canvas, remember to add the WebGPU add-on to your project.", gp2s5qktp8: "We weren't able to find a renderer called ${selectedRenderer}.", rf4evsxua3: "The GIF is over the maximum allowed dimension. Try to shrink the image or set p5.MAX_GIF_PIXELS to a higher value.", "5szmoepgx4": "To create a WEBGPU canvas, add the WebGPU add-on to your project.", xswmwyt2ek: "Falling back to WebGL renderer.", fxy3ssriqw: "${e.message} Falling back to WebGL renderer." }); const defaultLanguage = navigator.language; const localStorageAvailable = storageAvailable("localStorage"); const localTranslation = localStorageAvailable ? window.localStorage.getItem(`${defaultLanguage}-${VERSION}`) : null; let translationPromise = new Promise(async (resolve) => { if (localTranslation) { TL.addTranslations(defaultLanguage, JSON.parse(localTranslation)); resolve(); } else try { let translationResponse = await fetch(`./${defaultLanguage}.json`); if (!translationResponse.ok) throw new Error("Cannot reach local file"); const translation = await translationResponse.json(); TL.addTranslations(defaultLanguage, translation); if (localStorageAvailable) window.localStorage.setItem(`${defaultLanguage}-${VERSION}`, JSON.stringify(translation)); } catch { try { let translationResponse = await fetch(`https://cdn.jsdelivr.net/npm/p5@${VERSION}/translations/${defaultLanguage}/extracted.json`); if (!translationResponse.ok) throw new Error("Cannot reach CDN file"); const translation = await translationResponse.json(); TL.addTranslations(defaultLanguage, translation); if (localStorageAvailable) window.localStorage.setItem(`${defaultLanguage}-${VERSION}`, JSON.stringify(translation)); } catch {} } finally { resolve(); } }); var FES = class FES { static languageCode = navigator.languages; static translationPromise = translationPromise; static disableFriendlyErrors = false; static #printMessage(method, strings, ...values) { if (FES.disableFriendlyErrors) return; const styleStrings = []; const translation = TL.tl(strings, ...values.map((value) => { if (value instanceof StyledMessage) { const ret = `%c${value.message.toString(FES.languageCode)}%c`; styleStrings.push(value.styleString, ""); return ret; } else if (value?.message && value?.styleStrings) { styleStrings.push(...value.styleStrings); return value.message; } else return value; })); const results = translation.toString(FES.languageCode); const executor = (options) => { const { prefix } = Object.assign({ prefix: TL.tl`🌸 p5.js says: ` }, options); let footer = ""; if (options?.reference) footer += mapToReference(results, options.reference); if (prefix instanceof TL) console[method](prefix.toString(FES.languageCode) + results + footer, ...styleStrings); else if (prefix === false) console[method](results + footer, ...styleStrings); else console[method](prefix + results + footer, ...styleStrings); }; executor.message = results; executor.styleStrings = styleStrings; executor.toString = function(lang) { return translation.toString(lang); }; return executor; } static log(strings, ...values) { return FES.#printMessage("log", strings, ...values); } static debug(strings, ...values) { return FES.#printMessage("debug", strings, ...values); } static error(strings, ...values) { return FES.#printMessage("error", strings, ...values); } static info(strings, ...values) { return FES.#printMessage("info", strings, ...values); } static warn(strings, ...values) { return FES.#printMessage("warn", strings, ...values); } static TL = TL; static premade = { ordinals: [ TL.tl`first`, TL.tl`second`, TL.tl`third`, TL.tl`fourth`, TL.tl`fifth`, TL.tl`sixth`, TL.tl`seventh`, TL.tl`eighth`, TL.tl`ninth`, TL.tl`tenth` ], types: { string: TL.tl`string`, boolean: TL.tl`boolean`, number: TL.tl`number`, function: TL.tl`function` } }; }; var StyledMessage = class { message; styleString; constructor(message, styleString) { this.message = message; this.styleString = styleString; } toString(lang) { return this.message.toString(lang); } }; function style(message, mod) { const styleString = Object.entries(mod).reduce((acc, [key, val]) => { acc += `${key}: ${val};`; return acc; }, ""); if (message instanceof StyledMessage) { message.styleString += styleString; return message; } else return new StyledMessage(message, styleString); } function red(message) { return style(message, { color: "red" }); } function white(message) { return style(message, { color: "white" }); } function bgBlack(message) { return style(message, { background: "black" }); } function bgGrey(message) { return style(message, { background: "grey" }); } function underline(message) { return style(message, { "text-decoration": "underline" }); } /** * Takes a message and a p5 function func, and adds a link pointing to * the reference documentation of func at the end of the message * * @method mapToReference * @private * @param {String} message the words to be said * @param {String} [func] the name of function * * @returns {String} */ function mapToReference(message, func) { let msgWithReference = ""; if (func == null || func.substring(0, 4) === "load") msgWithReference = message; else { const methodParts = func.split("."); const referenceSection = methodParts.length > 1 ? `${methodParts[0]}.${methodParts[1]}` : "p5"; const funcName = methodParts.length === 1 ? func : methodParts.slice(2).join("/"); if (funcName.startsWith("p5.")) msgWithReference = ` (https://p5js.org/reference/${referenceSection}.${funcName})`; else msgWithReference = ` (https://p5js.org/reference/${referenceSection}/${funcName})`; } return msgWithReference; } function storageAvailable(type) { let storage; try { storage = window[type]; const x = "__storage_test__"; storage.setItem(x, x); storage.removeItem(x); return true; } catch (e) { return e instanceof DOMException && e.name === "QuotaExceededError" && storage && storage.length !== 0; } } function fes_default(p5, fn, lifecycles) { p5.FES = FES; Object.defineProperty(p5.FES, "disableFriendlyErrors", { get: () => p5.disableFriendlyErrors }); } //#endregion export { bgGrey as a, style as c, bgBlack as i, underline as l, StyledMessage as n, fes_default as o, TL as r, red as s, FES as t, white as u };