diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..572406b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/node_modules +package-lock.json \ No newline at end of file diff --git a/README.md b/README.md index cc17a05..8db2d6d 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,23 @@ -Assignment 4 - Creative Coding: Interactive Multimedia Experiences -=== -Due: October 2nd, by 11:59 AM. +Nelson Diaz -For this assignment we will focus on client-side development using popular audio/graphics/visualization technologies. The goal of this assignment is to refine our JavaScript knowledge while exploring the multimedia capabilities of the browser. +Link to Project: http://a4-nelson-diaz.glitch.me -[WebAudio / Canvas Tutorial](https://github.com/cs-4241-2023/cs4241-2023.github.io/blob/main/using.webaudio_and_canvas.md) -[SVG + D3 tutorial](https://github.com/cs-4241-2023/cs-4241-2023.github.io/blob/main/using.svg_and_d3.md) +# Conway's Game of Life -Baseline Requirements ---- - -Your application is required to implement the following functionalities: - -- A server created using Express. This server can be as simple as needed. -- A client-side interactive experience using at least one of the following web technologies frameworks. - - [Three.js](https://threejs.org/): A library for 3D graphics / VR experiences - - [D3.js](https://d3js.org): A library that is primarily used for interactive data visualizations - - [Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API): A 2D raster drawing API included in all modern browsers - - [SVG](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API): A 2D vector drawing framework that enables shapes to be defined via XML. - - [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API): An API for audio synthesis, analysis, processing, and file playback. -- A user interface for interaction with your project, which must expose at least four parameters for user control. [tweakpane](https://cocopon.github.io/tweakpane/) is highly recommended for this, but you can also use regular HTML `` tags (the `range` type is useful to create sliders). You might also explore interaction by tracking mouse movement via the `window.onmousemove` event handler in tandem with the `event.clientX` and `event.clientY` properties. Consider using the [Pointer Events API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events) to ensure that that both mouse and touch events will both be supported in your app. -- Your application should display basic documentation for the user interface when the application first loads. - -The interactive experience should possess a reasonable level of complexity. Some examples: -### Three.js -- A generative algorithm creates simple agents that move through a virtual world. Your interface controls the behavior / appearance of these agents. -- A simple 3D game... you really want this to be a simple as possible or it will be outside the scope of this assignment. -- An 3D audio visualization of a song of your choosing. User interaction should control aspects of the visualization. -### Canvas -- Implement a generative algorithm such as [Conway's Game of Life](https://bitstorm.org/gameoflife/) (or 1D cellular automata) and provide interactive controls. Note that the Game of Life has been created by 100s of people using ``; we'll be checking to ensure that your implementation is not a copy of these. -- Design a 2D audio visualizer of a song of your choosing. User interaction should control visual aspects of the experience. -### Web Audio API -- Create a screen-based musical instrument using the Web Audio API. You can use projects such as [Interface.js](http://charlie-roberts.com/interface/) or [Nexus UI](https://nexus-js.github.io/ui/api/#Piano) to provide common musical interface elements, or use dat.GUI in combination with mouse/touch events (use the Pointer Events API). Your GUI should enable users to control aspects of sound synthesis. If you want to use higher-level instruments instead of the raw WebAudio API sounds, consider trying the instruments provided by [Tone.js]() or [Gibber](https://github.com/charlieroberts/gibber.audio.lib). -### D3.js -- Create visualizations using the datasets found at [Awesome JSON Datasets](https://github.com/jdorfman/Awesome-JSON-Datasets). Experiment with providing different visualizations of the same data set, and providing users interactive control over visualization parameters and/or data filtering. Alternatively, create a single visualization with using one of the more complicated techniques shown at [d3js.org](d3js.org) and provide meaningful points of interaction for users. - -Deliverables ---- - -Do the following to complete this assignment: - -1. Implement your project with the above requirements. -3. Test your project to make sure that when someone goes to your main page on Glitch/Heroku/etc., it displays correctly. -4. Ensure that your project has the proper naming scheme `a4-firstname-lastname` so we can find it. -5. Fork this repository and modify the README to the specifications below. *NOTE: If you don't use Glitch for hosting (where we can see the files) then you must include all project files that you author in your repo for this assignment*. -6. Create and submit a Pull Request to the original repo. Name the pull request using the following template: `a4-firstname-lastname`. - -Sample Readme (delete the above when you're ready to submit, and modify the below so with your links and descriptions) ---- - -## Your Web Application Title - -your hosting link e.g. http://a4-charlieroberts.glitch.me Include a very brief summary of your project here. Images are encouraged when needed, along with concise, high-level text. Be sure to include: - the goal of the application - challenges you faced in realizing the application - the instructions you present in the website should be clear enough to use the application, but if you feel any need to provide additional instructions please do so here. + + +## Summary +This application is an interactive implementation on Conway's Game of Life. It is implemented using the Canvas API, Pointer Events API, and Tweakpane. A user is able to interact with the game by Starting/Pausing the simulation, changing the speed of the simulation, changing the rules for cell survival on the grid, changing the rules for cell generation on the grid, creating/removing cells at will by clicking & dragging, and more. The instructions for how to use the application are displayed on the right side of the screen when first navigating to the website. Challenges for this project included implementing click/drag functionality as well has using the [tweakpane-infodump](https://github.com/doersino/tweakpane-plugin-infodump) plugin to add the 'Information' tab. + +### Infodump plugin difficulty +When searching for how to add plain text into tweakpane, I came across this plugin that would allow me to do exactly what I wanted. The only problem was that the plugin was out of date compared to the most recent version of tweakpane. To resolve this issue I needed to step through the tweakpane execution with the debugger to see where it was failing so that I could resolve the issue. Eventually, I discovered that the only thing I needed to get the plugin in load was to add a variable specifying what version it was valid for. However, after I got the plugin loaded, I also needed to put the css that should have been loaded with the plugin into it's own CSS file named "tweakpane-plugin-infodump.css". This resolved the issue of the plugin's visual components not being rendered with CSS. + +### Click & Drag difficulty +When implementing click and drag I ran into a bug caused by the user clicking withing the canvas, dragging the cursor outside the canvas, and then releasing outside the canvas. This caused the cursor to paint cells when hovering over the canvas grid even without clicking. To remedy this I use the [MouseEvent.buttons](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons) property to check and see if the user is currently pressing a button while draggin over the canvas and only painting the grid if so. \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..248519b --- /dev/null +++ b/package.json @@ -0,0 +1,15 @@ +{ + "name": "a4-nelson-diaz", + "version": "", + "description": "", + "author": "", + "scripts": { + "start": "node server.improved.js" + }, + "dependencies": { + "express": "^4.16.4" + }, + "engines": { + "node": "16.x" + } +} diff --git a/public/css/custom.css b/public/css/custom.css new file mode 100644 index 0000000..380030e --- /dev/null +++ b/public/css/custom.css @@ -0,0 +1,42 @@ +body { + min-height: 100vh; + margin: 0; + padding: 1em; + display: flex; + align-items: center; + overflow-y: auto; + box-sizing: border-box; +} + +main { + width: 100vw; + display: flex; + flex-flow: row; + align-items: flex-start; + justify-content: space-evenly; +} + +canvas { + background-color: black; + border: 1px solid black; +} + +#canvasDiv { + padding: 0 1em; +} + +#optionsDiv { + margin: 0 auto; + + padding: 0 1em; + box-sizing: border-box; +} + +#optionsDiv > * { + min-width: 333px; +} + +.tp-rotv { + /*font-size: 13px !important;*/ + font-size: smaller !important; +} \ No newline at end of file diff --git a/public/css/tweakpane-plugin-infodump.css b/public/css/tweakpane-plugin-infodump.css new file mode 100644 index 0000000..9bbcc54 --- /dev/null +++ b/public/css/tweakpane-plugin-infodump.css @@ -0,0 +1,91 @@ +/** + * All css in this file was taken from the tweakpane-plugin-infodump-0.3.0.js file. + * I don't know why it wasn't being applied automatically, but I have already spent + * long enough getting the plugin to work in the first place and this gets the job done. + * Source: https://github.com/doersino/tweakpane-plugin-infodump + */ +.tp-induv { + position: relative; + align-items: center; + display: flex; + line-height: 1.3; + padding-left: var(--cnt-h-p); + padding-right: var(--cnt-h-p) +} + +.tp-induv.tp-v-disabled { + opacity: .5 +} + +.tp-induv .tp-induv_t { + color: var(--lbl-fg); + flex: 1; + -webkit-hyphens: auto; + hyphens: auto; + padding: 2px 4px 2px; + width: 1px +} + +.tp-induv .tp-induv_t>*:first-child { + margin-top: 0 +} + +.tp-induv .tp-induv_t>*:last-child { + margin-bottom: 0 +} + +.tp-induv .tp-induv_t p, +.tp-induv .tp-induv_t h1, +.tp-induv .tp-induv_t h2, +.tp-induv .tp-induv_t h3, +.tp-induv .tp-induv_t ol, +.tp-induv .tp-induv_t ul, +.tp-induv .tp-induv_t blockquote, +.tp-induv .tp-induv_t pre { + margin: .5em 0 +} + +.tp-induv .tp-induv_t a { + color: var(--btn-bg) +} + +.tp-induv .tp-induv_t a:active { + color: var(--btn-bg-a) +} + +.tp-induv .tp-induv_t a:hover { + color: var(--btn-bg-h) +} + +.tp-induv .tp-induv_t h1 { + font-size: 1.3em; + font-weight: bold +} + +.tp-induv .tp-induv_t h2 { + font-size: 1em; + font-weight: bold +} + +.tp-induv .tp-induv_t h3 { + font-size: 1em; + font-weight: normal +} + +.tp-induv .tp-induv_t ol, +.tp-induv .tp-induv_t ul, +.tp-induv .tp-induv_t blockquote { + padding-left: 28px +} + +.tp-indubv::before { + border: var(--mo-fg) dashed 1px; + border-radius: var(--elm-br); + bottom: 0; + content: ""; + left: var(--cnt-v-p); + opacity: .3; + position: absolute; + right: var(--cnt-v-p); + top: 0 +} \ No newline at end of file diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..b21055a --- /dev/null +++ b/public/index.html @@ -0,0 +1,28 @@ + + + + CS4241 Assignment 4 + + + + + + + + + + + + + + + +
+
+ +
+
+
+ + \ No newline at end of file diff --git a/public/js/main.js b/public/js/main.js new file mode 100644 index 0000000..9593bb3 --- /dev/null +++ b/public/js/main.js @@ -0,0 +1,265 @@ +import {Pane} from 'https://cdn.jsdelivr.net/npm/tweakpane@4.0.1/dist/tweakpane.min.js' + +class GridManager { + static _cellsX = 80 + static _cellsY = 45 + + #cellGrid + constructor() { + this.#cellGrid = JSON.parse(JSON.stringify(Array(GridManager._cellsX).fill(Array(GridManager._cellsY).fill(false)))) + } + + getGridState() { + // return deep clone of grid + return JSON.parse(JSON.stringify(this.#cellGrid)) + } + + /** + * @param {Array} newGrid + */ + set cellGrid(newGrid) { + if(Array.isArray(newGrid)) { + this.#cellGrid = newGrid + } + + paintCells() + } + + setCell(x, y, state) { + this.#cellGrid[x][y] = state + paintCells() + } + + getCell(x, y) { + return this.#cellGrid[x]?.[y] + } + + clearGrid() { + this.#cellGrid.forEach(arr => arr.fill(false)) + paintCells() + } +} + + +// unit are in pixels +const _cellPadding = 1 +const _gridSize = 10 +const _cellSize = _gridSize - 2*_cellPadding + +const _canvasBackground = '#000' +const _canvasCellOff = '#646464' +const _canvasCellOn = '#fff' + +// Holds boolean values for cell states: +// true = On +// false = Off +let gridManager = new GridManager() + +// Monitored parameters in Tweakpane +const GENERAL_PARAMS = { + 'Time Step': 100 +} + +const SURVIVE_PARAMS = { + 0: false, + 1: false, + 2: true, + 3: true, + 4: false, + 5: false, + 6: false, + 7: false, + 8: false +} + +const BORN_PARAMS = { + 0: false, + 1: false, + 2: false, + 3: true, + 4: false, + 5: false, + 6: false, + 7: false, + 8: false +} + +let canvas = undefined +let ctx = undefined +let stepInterval = undefined +window.onload = function() { + canvas = document.getElementById('myCanvas') + ctx = canvas.getContext('2d') + ctx.fillStyle = _canvasBackground + ctx.fillRect(0, 0, canvas.width, canvas.height) + canvas.onpointerdown = dragStart + canvas.onpointermove = drag + + paintCells() + + const pane = new Pane({container: document.getElementById('optionsDiv')}) + pane.registerPlugin(TweakpaneInfodumpPlugin) + + + let infoFolder = pane.addFolder({ + title: 'Information', + expanded: true + }) + + infoFolder.addBlade({ + view: "infodump", + content: `This is an implementation of Conway's Game of Life. There are various ways to interact with and impact the game. + + By clicking and dragging on the canvas, you are able to enable or disable cells within the grid. You can use this to create\ + any shape you want and see how it develops as time moves along. + + Under the 'General' tab, you have access to the time controls for the game, allowing you start and stop the simulation\ + as well as change the simulation speed. + + Under the 'Rules: Survival' tab are able to select what number of enabled neighbors a cell is able to have and\ + still remain enabled itself. By default both 2 and 3 neighbors are allowed. + + Under the 'Rules: Generation' tab you are able to select what number of enabled neighbors a cell is able to have that\ + will enable it from a disabled state. By default only 3 neighbors is selected.`, + + border: false, + markdown: true, + }) + + + let generalFolder = pane.addFolder({ + title: 'General', + expanded: false + }) + + generalFolder.addButton({title: 'Fill Random'}).on('click', randomFill) + generalFolder.addButton({title: 'Clear Grid'}).on('click', clearGrid) + + generalFolder.addBlade({view: 'separator'}) + + generalFolder.addButton({title: 'Play/Pause'}).on('click', toggleTime) + generalFolder.addButton({title: 'Step'}).on('click', nextState) + const timeBinding = generalFolder.addBinding(GENERAL_PARAMS, 'Time Step', {label: 'Simulation Speed (ms)', min: 1, max: 1000, step: 1}) + timeBinding.on('change', function(ev) { + if(ev.last) { + toggleTime() + toggleTime() + } + }) + + + let surviveFolder = pane.addFolder({ + title: 'Rule: Survival', + expanded: false + }) + + for(let i = 1; i <= 8; i++) { + surviveFolder.addBinding(SURVIVE_PARAMS, `${i}`, {label: `${i} Neighbor(s)`}) + } + + + let bornFolder = pane.addFolder({ + title: 'Rule: Generation', + expanded: false + }) + + for(let i = 1; i <= 8; i++) { + bornFolder.addBinding(BORN_PARAMS, `${i}`, {label: `${i} Neighbor(s)`}) + } +} + +const paintCells = function() { + let cells = gridManager.getGridState() + + for(let x = 0; x < cells.length; x++) { + for(let y = 0; y < cells[0].length; y++) { + ctx.fillStyle = cells[x][y] ? _canvasCellOn : _canvasCellOff + ctx.fillRect( + (x * _gridSize) + _cellPadding, + (y * _gridSize) + _cellPadding, + _cellSize, + _cellSize + ) + ctx.fill() + } + } +} + +const randomFill = function() { + gridManager.cellGrid = gridManager.getGridState().map(i => i.map(() => Math.random() > 0.5)) +} + +const clearGrid = function() { + gridManager.clearGrid() +} + +const nextState = function() { + let cells = gridManager.getGridState() + let newGrid = gridManager.getGridState() + + for(let x = 0; x < cells.length; x++) { + for(let y = 0; y < cells[0].length; y++) { + let neighbors = calculateNeighbors(x, y, cells) + + if(cells[x][y]) { // current cell is alive + newGrid[x][y] = SURVIVE_PARAMS[neighbors] + } else { // current cell is dead + newGrid[x][y] = BORN_PARAMS[neighbors] + } + + // current cell remains as is + } + } + + gridManager.cellGrid = newGrid +} + +const calculateNeighbors = function(x, y, gridReference) { + let neighbors = 0 + + neighbors += gridReference[x-1]?.[y-1] ? 1 : 0 + neighbors += gridReference[x-1]?.[y] ? 1 : 0 + neighbors += gridReference[x-1]?.[y+1] ? 1 : 0 + + neighbors += gridReference[x]?.[y-1] ? 1 : 0 + neighbors += gridReference[x]?.[y+1] ? 1 : 0 + + neighbors += gridReference[x+1]?.[y-1] ? 1 : 0 + neighbors += gridReference[x+1]?.[y] ? 1 : 0 + neighbors += gridReference[x+1]?.[y+1] ? 1 : 0 + + return neighbors +} + +const toggleTime = function() { + if(stepInterval) { + clearInterval(stepInterval) + stepInterval = undefined + } else { + stepInterval = setInterval(nextState, GENERAL_PARAMS['Time Step']) + } +} + + +const coordToGrid = function(coordX, coordY) { + return [Math.floor(coordX/_gridSize), Math.floor(coordY/_gridSize)] +} + +let fillType = undefined +const dragStart = function(event) { + let [x, y] = coordToGrid(event.offsetX, event.offsetY) + + const cellValue = gridManager.getCell(x, y) + if((event.buttons & 1) && (cellValue !== undefined)) { + fillType = !cellValue + gridManager.setCell(x, y, fillType) + } +} + +const drag = function(event) { + let [x, y] = coordToGrid(event.offsetX, event.offsetY) + + if((x >= 0) && (y >= 0) && (event.buttons & 1)) { + gridManager.setCell(x, y, fillType) + } +} diff --git a/public/js/tweakpane-plugin-infodump-0.3.0.js b/public/js/tweakpane-plugin-infodump-0.3.0.js new file mode 100644 index 0000000..afe57fe --- /dev/null +++ b/public/js/tweakpane-plugin-infodump-0.3.0.js @@ -0,0 +1,790 @@ +/** + * This file implements the tweakplain-plugin-infodump plugin. + * I have made very minor editws to this file in order for it + * to work properly with the most recent version of tweakplane. + * However, I did not author a vast majority of this code. + * Source: https://github.com/doersino/tweakpane-plugin-infodump + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TweakpaneInfodumpPlugin = {})); +})(this, (function (exports) { 'use strict'; + + class BladeApi { + constructor(controller) { + this.controller = controller; + } + get element() { + return this.controller.view.element; + } + get disabled() { + return this.controller.viewProps.get('disabled'); + } + set disabled(disabled) { + this.controller.viewProps.set('disabled', disabled); + } + get hidden() { + return this.controller.viewProps.get('hidden'); + } + set hidden(hidden) { + this.controller.viewProps.set('hidden', hidden); + } + dispose() { + this.controller.viewProps.set('disposed', true); + } + } + + function forceCast(v) { + return v; + } + function deepEqualsArray(a1, a2) { + if (a1.length !== a2.length) { + return false; + } + for (let i = 0; i < a1.length; i++) { + if (a1[i] !== a2[i]) { + return false; + } + } + return true; + } + + class Emitter { + constructor() { + this.observers_ = {}; + } + on(eventName, handler) { + let observers = this.observers_[eventName]; + if (!observers) { + observers = this.observers_[eventName] = []; + } + observers.push({ + handler: handler, + }); + return this; + } + off(eventName, handler) { + const observers = this.observers_[eventName]; + if (observers) { + this.observers_[eventName] = observers.filter((observer) => { + return observer.handler !== handler; + }); + } + return this; + } + emit(eventName, event) { + const observers = this.observers_[eventName]; + if (!observers) { + return; + } + observers.forEach((observer) => { + observer.handler(event); + }); + } + } + + const PREFIX = 'tp'; + function ClassName(viewName) { + const fn = (opt_elementName, opt_modifier) => { + return [ + PREFIX, + '-', + viewName, + 'v', + opt_elementName ? `_${opt_elementName}` : '', + opt_modifier ? `-${opt_modifier}` : '', + ].join(''); + }; + return fn; + } + + function compose(h1, h2) { + return (input) => h2(h1(input)); + } + function extractValue(ev) { + return ev.rawValue; + } + function bindValue(value, applyValue) { + value.emitter.on('change', compose(extractValue, applyValue)); + applyValue(value.rawValue); + } + function bindValueMap(valueMap, key, applyValue) { + bindValue(valueMap.value(key), applyValue); + } + + function applyClass(elem, className, active) { + if (active) { + elem.classList.add(className); + } + else { + elem.classList.remove(className); + } + } + function valueToClassName(elem, className) { + return (value) => { + applyClass(elem, className, value); + }; + } + + class BoundValue { + constructor(initialValue, config) { + var _a; + this.constraint_ = config === null || config === void 0 ? void 0 : config.constraint; + this.equals_ = (_a = config === null || config === void 0 ? void 0 : config.equals) !== null && _a !== void 0 ? _a : ((v1, v2) => v1 === v2); + this.emitter = new Emitter(); + this.rawValue_ = initialValue; + } + get constraint() { + return this.constraint_; + } + get rawValue() { + return this.rawValue_; + } + set rawValue(rawValue) { + this.setRawValue(rawValue, { + forceEmit: false, + last: true, + }); + } + setRawValue(rawValue, options) { + const opts = options !== null && options !== void 0 ? options : { + forceEmit: false, + last: true, + }; + const constrainedValue = this.constraint_ + ? this.constraint_.constrain(rawValue) + : rawValue; + const prevValue = this.rawValue_; + const changed = !this.equals_(prevValue, constrainedValue); + if (!changed && !opts.forceEmit) { + return; + } + this.emitter.emit('beforechange', { + sender: this, + }); + this.rawValue_ = constrainedValue; + this.emitter.emit('change', { + options: opts, + previousRawValue: prevValue, + rawValue: constrainedValue, + sender: this, + }); + } + } + + class PrimitiveValue { + constructor(initialValue) { + this.emitter = new Emitter(); + this.value_ = initialValue; + } + get rawValue() { + return this.value_; + } + set rawValue(value) { + this.setRawValue(value, { + forceEmit: false, + last: true, + }); + } + setRawValue(value, options) { + const opts = options !== null && options !== void 0 ? options : { + forceEmit: false, + last: true, + }; + const prevValue = this.value_; + if (prevValue === value && !opts.forceEmit) { + return; + } + this.emitter.emit('beforechange', { + sender: this, + }); + this.value_ = value; + this.emitter.emit('change', { + options: opts, + previousRawValue: prevValue, + rawValue: this.value_, + sender: this, + }); + } + } + + function createValue(initialValue, config) { + const constraint = config === null || config === void 0 ? void 0 : config.constraint; + const equals = config === null || config === void 0 ? void 0 : config.equals; + if (!constraint && !equals) { + return new PrimitiveValue(initialValue); + } + return new BoundValue(initialValue, config); + } + + class ValueMap { + constructor(valueMap) { + this.emitter = new Emitter(); + this.valMap_ = valueMap; + for (const key in this.valMap_) { + const v = this.valMap_[key]; + v.emitter.on('change', () => { + this.emitter.emit('change', { + key: key, + sender: this, + }); + }); + } + } + static createCore(initialValue) { + const keys = Object.keys(initialValue); + return keys.reduce((o, key) => { + return Object.assign(o, { + [key]: createValue(initialValue[key]), + }); + }, {}); + } + static fromObject(initialValue) { + const core = this.createCore(initialValue); + return new ValueMap(core); + } + get(key) { + return this.valMap_[key].rawValue; + } + set(key, value) { + this.valMap_[key].rawValue = value; + } + value(key) { + return this.valMap_[key]; + } + } + + function parseObject(value, keyToParserMap) { + const keys = Object.keys(keyToParserMap); + const result = keys.reduce((tmp, key) => { + if (tmp === undefined) { + return undefined; + } + const parser = keyToParserMap[key]; + const result = parser(value[key]); + return result.succeeded + ? Object.assign(Object.assign({}, tmp), { [key]: result.value }) : undefined; + }, {}); + return forceCast(result); + } + function parseArray(value, parseItem) { + return value.reduce((tmp, item) => { + if (tmp === undefined) { + return undefined; + } + const result = parseItem(item); + if (!result.succeeded || result.value === undefined) { + return undefined; + } + return [...tmp, result.value]; + }, []); + } + function isObject(value) { + if (value === null) { + return false; + } + return typeof value === 'object'; + } + function createParamsParserBuilder(parse) { + return (optional) => (v) => { + if (!optional && v === undefined) { + return { + succeeded: false, + value: undefined, + }; + } + if (optional && v === undefined) { + return { + succeeded: true, + value: undefined, + }; + } + const result = parse(v); + return result !== undefined + ? { + succeeded: true, + value: result, + } + : { + succeeded: false, + value: undefined, + }; + }; + } + function createParamsParserBuilders(optional) { + return { + custom: (parse) => createParamsParserBuilder(parse)(optional), + boolean: createParamsParserBuilder((v) => typeof v === 'boolean' ? v : undefined)(optional), + number: createParamsParserBuilder((v) => typeof v === 'number' ? v : undefined)(optional), + string: createParamsParserBuilder((v) => typeof v === 'string' ? v : undefined)(optional), + function: createParamsParserBuilder((v) => + typeof v === 'function' ? v : undefined)(optional), + constant: (value) => createParamsParserBuilder((v) => (v === value ? value : undefined))(optional), + raw: createParamsParserBuilder((v) => v)(optional), + object: (keyToParserMap) => createParamsParserBuilder((v) => { + if (!isObject(v)) { + return undefined; + } + return parseObject(v, keyToParserMap); + })(optional), + array: (itemParser) => createParamsParserBuilder((v) => { + if (!Array.isArray(v)) { + return undefined; + } + return parseArray(v, itemParser); + })(optional), + }; + } + const ParamsParsers = { + optional: createParamsParserBuilders(true), + required: createParamsParserBuilders(false), + }; + function parseParams(value, keyToParserMap) { + const result = ParamsParsers.required.object(keyToParserMap)(value); + return result.succeeded ? result.value : undefined; + } + + function warnMissing(info) { + console.warn([ + `Missing '${info.key}' of ${info.target} in ${info.place}.`, + 'Please rebuild plugins with the latest core package.', + ].join(' ')); + } + + function disposeElement(elem) { + if (elem && elem.parentElement) { + elem.parentElement.removeChild(elem); + } + return null; + } + + class ReadonlyValue { + constructor(value) { + this.value_ = value; + } + static create(value) { + return [ + new ReadonlyValue(value), + (rawValue, options) => { + value.setRawValue(rawValue, options); + }, + ]; + } + get emitter() { + return this.value_.emitter; + } + get rawValue() { + return this.value_.rawValue; + } + } + + const className$2 = ClassName(''); + function valueToModifier(elem, modifier) { + return valueToClassName(elem, className$2(undefined, modifier)); + } + class ViewProps extends ValueMap { + constructor(valueMap) { + var _a; + super(valueMap); + this.onDisabledChange_ = this.onDisabledChange_.bind(this); + this.onParentChange_ = this.onParentChange_.bind(this); + this.onParentGlobalDisabledChange_ = + this.onParentGlobalDisabledChange_.bind(this); + [this.globalDisabled_, this.setGlobalDisabled_] = ReadonlyValue.create(createValue(this.getGlobalDisabled_())); + this.value('disabled').emitter.on('change', this.onDisabledChange_); + this.value('parent').emitter.on('change', this.onParentChange_); + (_a = this.get('parent')) === null || _a === void 0 ? void 0 : _a.globalDisabled.emitter.on('change', this.onParentGlobalDisabledChange_); + } + static create(opt_initialValue) { + var _a, _b, _c; + const initialValue = opt_initialValue !== null && opt_initialValue !== void 0 ? opt_initialValue : {}; + return new ViewProps(ValueMap.createCore({ + disabled: (_a = initialValue.disabled) !== null && _a !== void 0 ? _a : false, + disposed: false, + hidden: (_b = initialValue.hidden) !== null && _b !== void 0 ? _b : false, + parent: (_c = initialValue.parent) !== null && _c !== void 0 ? _c : null, + })); + } + get globalDisabled() { + return this.globalDisabled_; + } + bindClassModifiers(elem) { + bindValue(this.globalDisabled_, valueToModifier(elem, 'disabled')); + bindValueMap(this, 'hidden', valueToModifier(elem, 'hidden')); + } + bindDisabled(target) { + bindValue(this.globalDisabled_, (disabled) => { + target.disabled = disabled; + }); + } + bindTabIndex(elem) { + bindValue(this.globalDisabled_, (disabled) => { + elem.tabIndex = disabled ? -1 : 0; + }); + } + handleDispose(callback) { + this.value('disposed').emitter.on('change', (disposed) => { + if (disposed) { + callback(); + } + }); + } + getGlobalDisabled_() { + const parent = this.get('parent'); + const parentDisabled = parent ? parent.globalDisabled.rawValue : false; + return parentDisabled || this.get('disabled'); + } + updateGlobalDisabled_() { + this.setGlobalDisabled_(this.getGlobalDisabled_()); + } + onDisabledChange_() { + this.updateGlobalDisabled_(); + } + onParentGlobalDisabledChange_() { + this.updateGlobalDisabled_(); + } + onParentChange_(ev) { + var _a; + const prevParent = ev.previousRawValue; + prevParent === null || prevParent === void 0 ? void 0 : prevParent.globalDisabled.emitter.off('change', this.onParentGlobalDisabledChange_); + (_a = this.get('parent')) === null || _a === void 0 ? void 0 : _a.globalDisabled.emitter.on('change', this.onParentGlobalDisabledChange_); + this.updateGlobalDisabled_(); + } + } + + function getAllBladePositions() { + return ['veryfirst', 'first', 'last', 'verylast']; + } + + const className$1 = ClassName(''); + const POS_TO_CLASS_NAME_MAP = { + veryfirst: 'vfst', + first: 'fst', + last: 'lst', + verylast: 'vlst', + }; + class BladeController { + constructor(config) { + this.parent_ = null; + this.blade = config.blade; + this.view = config.view; + this.viewProps = config.viewProps; + const elem = this.view.element; + this.blade.value('positions').emitter.on('change', () => { + getAllBladePositions().forEach((pos) => { + elem.classList.remove(className$1(undefined, POS_TO_CLASS_NAME_MAP[pos])); + }); + this.blade.get('positions').forEach((pos) => { + elem.classList.add(className$1(undefined, POS_TO_CLASS_NAME_MAP[pos])); + }); + }); + this.viewProps.handleDispose(() => { + disposeElement(elem); + }); + } + get parent() { + return this.parent_; + } + set parent(parent) { + this.parent_ = parent; + if (!('parent' in this.viewProps.valMap_)) { + warnMissing({ + key: 'parent', + target: ViewProps.name, + place: 'BladeController.parent', + }); + return; + } + this.viewProps.set('parent', this.parent_ ? this.parent_.viewProps : null); + } + } + + function createBlade() { + return new ValueMap({ + positions: createValue([], { + equals: deepEqualsArray, + }), + }); + } + + function createNumberFormatter(digits) { + return (value) => { + return value.toFixed(Math.max(Math.min(digits, 20), 0)); + }; + } + + const innerFormatter = createNumberFormatter(0); + function formatPercentage(value) { + return innerFormatter(value) + '%'; + } + + function constrainRange(value, min, max) { + return Math.min(Math.max(value, min), max); + } + + function removeAlphaComponent(comps) { + return [comps[0], comps[1], comps[2]]; + } + + function zerofill(comp) { + const hex = constrainRange(Math.floor(comp), 0, 255).toString(16); + return hex.length === 1 ? `0${hex}` : hex; + } + function colorToHexRgbString(value, prefix = '#') { + const hexes = removeAlphaComponent(value.getComponents('rgb')) + .map(zerofill) + .join(''); + return `${prefix}${hexes}`; + } + function colorToHexRgbaString(value, prefix = '#') { + const rgbaComps = value.getComponents('rgb'); + const hexes = [rgbaComps[0], rgbaComps[1], rgbaComps[2], rgbaComps[3] * 255] + .map(zerofill) + .join(''); + return `${prefix}${hexes}`; + } + function colorToFunctionalRgbString(value, opt_type) { + const formatter = createNumberFormatter(opt_type === 'float' ? 2 : 0); + const comps = removeAlphaComponent(value.getComponents('rgb', opt_type)).map((comp) => formatter(comp)); + return `rgb(${comps.join(', ')})`; + } + function createFunctionalRgbColorFormatter(type) { + return (value) => { + return colorToFunctionalRgbString(value, type); + }; + } + function colorToFunctionalRgbaString(value, opt_type) { + const aFormatter = createNumberFormatter(2); + const rgbFormatter = createNumberFormatter(opt_type === 'float' ? 2 : 0); + const comps = value.getComponents('rgb', opt_type).map((comp, index) => { + const formatter = index === 3 ? aFormatter : rgbFormatter; + return formatter(comp); + }); + return `rgba(${comps.join(', ')})`; + } + function createFunctionalRgbaColorFormatter(type) { + return (value) => { + return colorToFunctionalRgbaString(value, type); + }; + } + function colorToFunctionalHslString(value) { + const formatters = [ + createNumberFormatter(0), + formatPercentage, + formatPercentage, + ]; + const comps = removeAlphaComponent(value.getComponents('hsl')).map((comp, index) => formatters[index](comp)); + return `hsl(${comps.join(', ')})`; + } + function colorToFunctionalHslaString(value) { + const formatters = [ + createNumberFormatter(0), + formatPercentage, + formatPercentage, + createNumberFormatter(2), + ]; + const comps = value + .getComponents('hsl') + .map((comp, index) => formatters[index](comp)); + return `hsla(${comps.join(', ')})`; + } + function colorToObjectRgbString(value, type) { + const formatter = createNumberFormatter(type === 'float' ? 2 : 0); + const names = ['r', 'g', 'b']; + const comps = removeAlphaComponent(value.getComponents('rgb', type)).map((comp, index) => `${names[index]}: ${formatter(comp)}`); + return `{${comps.join(', ')}}`; + } + function createObjectRgbColorFormatter(type) { + return (value) => colorToObjectRgbString(value, type); + } + function colorToObjectRgbaString(value, type) { + const aFormatter = createNumberFormatter(2); + const rgbFormatter = createNumberFormatter(type === 'float' ? 2 : 0); + const names = ['r', 'g', 'b', 'a']; + const comps = value.getComponents('rgb', type).map((comp, index) => { + const formatter = index === 3 ? aFormatter : rgbFormatter; + return `${names[index]}: ${formatter(comp)}`; + }); + return `{${comps.join(', ')}}`; + } + function createObjectRgbaColorFormatter(type) { + return (value) => colorToObjectRgbaString(value, type); + } + [ + { + format: { + alpha: false, + mode: 'rgb', + notation: 'hex', + type: 'int', + }, + stringifier: colorToHexRgbString, + }, + { + format: { + alpha: true, + mode: 'rgb', + notation: 'hex', + type: 'int', + }, + stringifier: colorToHexRgbaString, + }, + { + format: { + alpha: false, + mode: 'hsl', + notation: 'func', + type: 'int', + }, + stringifier: colorToFunctionalHslString, + }, + { + format: { + alpha: true, + mode: 'hsl', + notation: 'func', + type: 'int', + }, + stringifier: colorToFunctionalHslaString, + }, + ...['int', 'float'].reduce((prev, type) => { + return [ + ...prev, + { + format: { + alpha: false, + mode: 'rgb', + notation: 'func', + type: type, + }, + stringifier: createFunctionalRgbColorFormatter(type), + }, + { + format: { + alpha: true, + mode: 'rgb', + notation: 'func', + type: type, + }, + stringifier: createFunctionalRgbaColorFormatter(type), + }, + { + format: { + alpha: false, + mode: 'rgb', + notation: 'object', + type: type, + }, + stringifier: createObjectRgbColorFormatter(type), + }, + { + format: { + alpha: true, + mode: 'rgb', + notation: 'object', + type: type, + }, + stringifier: createObjectRgbaColorFormatter(type), + }, + ]; + }, []), + ]; + + var n=[[/\r\n/g,"\n"],[/\n(#+)(.*)/g,function(n,t,r){void 0===r&&(r="");var e=t.length;return ""+r.trim()+""}],[/!\[([^\[]+)\]\((?:javascript:)?([^\)]+)\)/g,'$1'],[/\[([^\[]+)\]\((?:javascript:)?([^\)]+)\)/g,'$1'],[/(\*\*|__)(.*?)\1/g,"$2"],[/\\_/g,"_"],[/(\*|_)(.*?)\1/g,"$2"],[/\~\~(.*?)\~\~/g,"$1"],[/\:\"(.*?)\"\:/g,"$1"],[/\n\s*```\n([^]*?)\n\s*```\s*\n/g,"\n
$1
"],[/`(.*?)`/g,function(n,t){return ""+function(n){n=n.replace(/\&/g,"&");for(var t="'#<>`*-~_=:\"![]()nt",r=t.length,e=0;e"}],[/\n(\*|\-|\+)(.*)/g,function(n,t,r){return void 0===r&&(r=""),"
    \n\t
  • "+r.trim()+"
  • \n
"}],[/\n[0-9]+\.(.*)/g,function(n,t){return void 0===t&&(t=""),"
    \n\t
  1. "+t.trim()+"
  2. \n
"}],[/\n(>|\>)(.*)/g,function(n,t,r){return void 0===r&&(r=""),"\n
"+r.trim()+"
"}],[/\n-{5,}/g,"\n
"],[/( *\|[^\n]+\|\r?\n)((?: *\|:?[ -]+:?)+ *\|)(\n(?: *\|[^\n]+\|\r?\n?)*)?/g,function(n,t,r,e){var i=r.split("|").filter(function(n,t,r){return t>0&&t"+t.split("|").map(function(n){return n.trim()}).filter(function(n){return n&&n.length}).map(function(n,t){return ""+n+""}).join("")+""+e.split("\n").map(function(n){return n.trim()}).filter(function(n){return n&&n.length}).map(function(n){return ""+n.split("|").filter(function(n,t,r){return t>0&&t"+n.trim()+""}).join("")+""}).join("")+"\n"}],[/\n([^\n]+)\n/g,function(n,t){var r=t.trim();return /^<\/?(ul|ol|li|h|p|bl|table|tr|td)/i.test(r)?"\n"+t+"\n":"\n

\n"+r+"\n

\n"}],[/\s?<\/ul>\s?
    /g,""],[/\s?<\/ol>\s?
      /g,""],[/<\/blockquote>\n
      /g,"
      \n"],[/https?:\/\/[^"']*/g,function(n){return n.replace(/<\/?em>/g,"_")}],[/_/g,"_"]],t=function(t,r,e){return void 0===r&&(r=!1),void 0===e&&(e=!1),t="\n"+t+"\n",n.forEach(function(n){t=t.replace(n[0],n[1]);}),r?e?t.trim().replace(/^

      ([\s\S]*)<\/p>$/,"$1").replace(/