code,label "diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md @@ -102,4 +102,6 @@ Main contributors will review your code and possibly ask for changes before your If you have any questions feel free to post them to [github.com/OpenZeppelin/zeppelin-solidity/issues](https://github.com/OpenZeppelin/zeppelin-solidity/issues). +Finally, if you're looking to collaborate and want to find easy tasks to start, [look at the issues we marked as easy](https://github.com/OpenZeppelin/zeppelin-solidity/labels/easy). + Thanks for your time and code! ",0 "diff --git a/contracts/token/TransferableToken.sol b/contracts/token/TransferableToken.sol @@ -2,20 +2,47 @@ pragma solidity ^0.4.8; import ""./ERC20.sol""; +/* + +TransferableToken defines the generic interface and the implementation +to limit token transferability for different events. + +It is intended to be used as a base class for other token contracts. + +Over-writting transferableTokens(address holder, uint64 time) is the way to provide +the specific logic for limitting token transferability for a holder over time. + +TransferableToken has been designed to allow for different limitting factors, +this can be achieved by recursively calling super.transferableTokens() until the +base class is hit. For example: + +function transferableTokens(address holder, uint64 time) constant public returns (uint256) { + return min256(unlockedTokens, super.transferableTokens(holder, time)); +} + +A working example is VestedToken.sol: +https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol + +*/ + contract TransferableToken is ERC20 { + // Checks whether it can transfer or otherwise throws. modifier canTransfer(address _sender, uint _value) { if (_value > transferableTokens(_sender, uint64(now))) throw; _; } + // Checks modifier and allows transfer if tokens are not locked. function transfer(address _to, uint _value) canTransfer(msg.sender, _value) returns (bool success) { return super.transfer(_to, _value); } + // Checks modifier and allows transfer if tokens are not locked. function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) returns (bool success) { return super.transferFrom(_from, _to, _value); } + // Default transferable tokens function returns all tokens for a holder (no limit). function transferableTokens(address holder, uint64 time) constant public returns (uint256) { return balanceOf(holder); } ",0 "diff --git a/contracts/token/MintableToken.sol b/contracts/token/MintableToken.sol @@ -18,6 +18,7 @@ import '../ownership/Ownable.sol'; contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint value); + event MintFinished(); bool public mintingFinished = false; uint public totalSupply = 0; @@ -36,6 +37,7 @@ contract MintableToken is StandardToken, Ownable { function finishMinting() onlyOwner returns (bool) { mintingFinished = true; + MintFinished(); return true; } } ",0 "diff --git a/contracts/token/StandardToken.sol b/contracts/token/StandardToken.sol @@ -29,6 +29,13 @@ contract StandardToken is BasicToken, ERC20 { } function approve(address _spender, uint _value) { + + // To change the approve amount you first have to reduce the addresses` + // allowance to zero by calling `approve(_spender,0)` if it is not + // already 0 to mitigate the race condition described here: + // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 + if ((_amount!=0) && (allowed[msg.sender][_spender] !=0)) throw; + allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } ",0 "diff --git a/test/VestedToken.js b/test/VestedToken.js @@ -96,4 +96,61 @@ contract('VestedToken', function(accounts) { assert.equal(await token.balanceOf(accounts[7]), tokenAmount); }) }) + + describe('getting a non-revokable token grant', async () => { + const cliff = 10000 + const vesting = 20000 // seconds + + beforeEach(async () => { + await token.grantVestedTokens(receiver, tokenAmount, now, now + cliff, now + vesting, false, false, { from: granter }) + }) + + it('tokens are received', async () => { + assert.equal(await token.balanceOf(receiver), tokenAmount); + }) + + it('throws when granter attempts to revoke', async () => { + try { + await token.revokeTokenGrant(receiver, 0, { from: granter }); + } catch(error) { + return assertJump(error); + } + assert.fail('should have thrown before'); + }) + }) + + describe('getting a revokable/burnable token grant', async () => { + const cliff = 100000 + const vesting = 200000 // seconds + const burnAddress = '0x000000000000000000000000000000000000dead' + + beforeEach(async () => { + await token.grantVestedTokens(receiver, tokenAmount, now, now + cliff, now + vesting, true, true, { from: granter }) + }) + + it('tokens are received', async () => { + assert.equal(await token.balanceOf(receiver), tokenAmount); + }) + + it('can be revoked by granter and tokens are burned', async () => { + await token.revokeTokenGrant(receiver, 0, { from: granter }); + assert.equal(await token.balanceOf(receiver), 0); + assert.equal(await token.balanceOf(burnAddress), tokenAmount); + }) + + it('cannot be revoked by non granter', async () => { + try { + await token.revokeTokenGrant(receiver, 0, { from: accounts[3] }); + } catch(error) { + return assertJump(error); + } + assert.fail('should have thrown before'); + }) + + it('can be revoked by granter and non vested tokens are returned', async () => { + await timer(cliff); + await token.revokeTokenGrant(receiver, 0, { from: granter }); + assert.equal(await token.balanceOf(burnAddress), tokenAmount * cliff / vesting); + }) + }) }); ",0 "diff --git a/contracts/token/VestedToken.sol b/contracts/token/VestedToken.sol @@ -6,8 +6,7 @@ import ""./LimitedTransferToken.sol""; /** * @title Vested token -* @dev This tokens can be granted to a specific address after a determined -amount of time. +* @dev Tokens that can be vested for a group of addresses. */ contract VestedToken is StandardToken, LimitedTransferToken { @@ -25,9 +24,9 @@ contract VestedToken is StandardToken, LimitedTransferToken { * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. - * @param _start uint 64 The time of the begining of the grant. - * @param _cliff uint64 The time before the grant is enforceble. - * @param _vesting uint64 The time in which the tokens will be vested. + * @param _start uint64 Represents time of the begining of the grant. + * @param _cliff uint64 Represents the cliff period. + * @param _vesting uint64 Represents the vesting period. */ function grantVestedTokens( address _to, @@ -80,16 +79,18 @@ contract VestedToken is StandardToken, LimitedTransferToken { /** * @dev Check the amount of grants that an address has. * @param _holder address The holder of the grants. - * @return A uint representing the index of the grant. + * @return A uint representing the total amount of grants. */ function tokenGrantsCount(address _holder) constant returns (uint index) { return grants[_holder].length; } /** - * @dev + * @dev Get all information about a specifc grant. * @param _holder address The address which will have its tokens revoked. * @param _grantId uint The id of the token grant. + * @return Returns all the values that represent a TokenGrant(address, value, + start, cliff and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting) { TokenGrant grant = grants[_holder][_grantId]; @@ -103,6 +104,13 @@ contract VestedToken is StandardToken, LimitedTransferToken { vested = vestedTokens(grant, uint64(now)); } + /** + * @dev Get the amount of vested tokens at a specifc time. + * @param grant TokenGrant The grant to be checked. + * @param time uint64 The time to be checked + * @return An uint representing the amount of vested tokens of a specifc grant + on specifc time. + */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, @@ -113,6 +121,15 @@ contract VestedToken is StandardToken, LimitedTransferToken { ); } + /** + * @dev Calculate amount of vested tokens at a specifc time. + * @param tokens uint256 The amount of tokens grantted. + * @param time uint64 The time to be checked + * @param start uint64 A time representing the begining of the grant + * @param _cliff uint64 Represents the cliff period. + * @param _vesting uint64 Represents the vesting period. + * @return An uint representing the amount of vested tokensof a specif grant. + */ function calculateVestedTokens( uint256 tokens, uint256 time, @@ -136,10 +153,22 @@ contract VestedToken is StandardToken, LimitedTransferToken { vestedTokens = vestedTokens.add(vestingTokens.mul(time.sub(cliff)).div(vesting.sub(cliff))); } + /** + * @dev Calculate the amount of non vested tokens at a specific time. + * @param grant TokenGrant The grant to be checked. + * @param time uint64 The time to be checked + * @return An uint representing the amount of non vested tokens of a specifc grant + on the passed time frame. + */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return grant.value.sub(vestedTokens(grant, time)); } + /** + * @dev Calculate the date when the holder can trasfer all its tokens + * @param holder address The address of the holder + * @return An uint representing the date of the last transferable tokens. + */ function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; @@ -148,6 +177,12 @@ contract VestedToken is StandardToken, LimitedTransferToken { } } + /** + * @dev Calculate the total amount of transferable tokens of a holder at a given time + * @param holder address The address of the holder + * @param time uint64 The specific time. + * @return An uint representing a holder's total amount of transferable tokens. + */ function transferableTokens(address holder, uint64 time) constant public returns (uint256 nonVested) { uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { ",0 "diff --git a/contracts/MultisigWallet.sol b/contracts/MultisigWallet.sol @@ -6,9 +6,9 @@ import ""./ownership/Shareable.sol""; import ""./DayLimit.sol""; -/* +/** * MultisigWallet - * usage: + * Usage: * bytes32 h = Wallet(w).from(oneOwner).execute(to, value, data); * Wallet(w).from(anotherOwner).confirm(h); */ @@ -20,26 +20,41 @@ contract MultisigWallet is Multisig, Shareable, DayLimit { bytes data; } + /** + * Constructor, sets the owners addresses, number of approvals required, and daily spending limit + * @param _owners A list of owners. + * @param _required The amount required for a transaction to be approved. + */ function MultisigWallet(address[] _owners, uint _required, uint _daylimit) Shareable(_owners, _required) DayLimit(_daylimit) { } - // destroys the contract sending everything to `_to`. + /** + * @dev destroys the contract sending everything to `_to`. + */ function destroy(address _to) onlymanyowners(keccak256(msg.data)) external { selfdestruct(_to); } - // gets called when no other function matches + /** + * @dev Fallback function, receives value and emits a deposit event. + */ function() payable { // just being sent some cash? if (msg.value > 0) Deposit(msg.sender, msg.value); } - // Outside-visible transact entry point. Executes transaction immediately if below daily spend limit. - // If not, goes into multisig process. We provide a hash on return to allow the sender to provide - // shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value - // and _data arguments). They still get the option of using them if they want, anyways. + /** + * @dev Outside-visible transaction entry point. Executes transaction immediately if below daily + * spending limit. If not, goes into multisig process. We provide a hash on return to allow the + * sender to provide shortcuts for the other confirmations (allowing them to avoid replicating + * the _to, _value, and _data arguments). They still get the option of using them if they want, + * anyways. + * @param _to The receiver address + * @param _value The value to send + * @param _data The data part of the transaction + */ function execute(address _to, uint _value, bytes _data) external onlyOwner returns (bytes32 _r) { // first, take the opportunity to check that we're under the daily limit. if (underLimit(_value)) { @@ -60,8 +75,11 @@ contract MultisigWallet is Multisig, Shareable, DayLimit { } } - // confirm a transaction through just the hash. we use the previous transactions map, txs, in order - // to determine the body of the transaction from the hash provided. + /** + * @dev Confirm a transaction by providing just the hash. We use the previous transactions map, + * txs, in order to determine the body of the transaction from the hash provided. + * @param _h The transaction hash to approve. + */ function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) { if (txs[_h].to != 0) { if (!txs[_h].to.call.value(txs[_h].value)(txs[_h].data)) { @@ -73,17 +91,27 @@ contract MultisigWallet is Multisig, Shareable, DayLimit { } } + /** + * @dev Updates the daily limit value. + * @param _newLimit + */ function setDailyLimit(uint _newLimit) onlymanyowners(keccak256(msg.data)) external { _setDailyLimit(_newLimit); } + /** + * @dev Resets the value spent to enable more spending + * @param _newLimit + */ function resetSpentToday() onlymanyowners(keccak256(msg.data)) external { _resetSpentToday(); } // INTERNAL METHODS - + /** + * @dev Clears the list of transactions pending approval. + */ function clearPending() internal { uint length = pendingsIndex.length; for (uint i = 0; i < length; ++i) { ",0 "diff --git a/test/DayLimit.js b/test/DayLimit.js 'use strict'; const assertJump = require('./helpers/assertJump'); +const timer = require('./helpers/timer'); -var DayLimitMock = artifacts.require('helpers/DayLimitMock.sol'); +var DayLimitMock = artifacts.require('./helpers/DayLimitMock.sol'); contract('DayLimit', function(accounts) { + const day = 60 * 60 * 24; it('should construct with the passed daily limit', async function() { let initLimit = 10; @@ -84,4 +86,27 @@ contract('DayLimit', function(accounts) { assert.equal(spentToday, 3); }); + it('should allow spending if daily limit is reached and then the next has come', async function() { + let limit = 10; + let dayLimit = await DayLimitMock.new(limit); + + await dayLimit.attemptSpend(8); + let spentToday = await dayLimit.spentToday(); + assert.equal(spentToday, 8); + + try { + await dayLimit.attemptSpend(3); + } catch(error) { + assertJump(error); + } + spentToday = await dayLimit.spentToday(); + assert.equal(spentToday, 8); + + await timer(day); + + await dayLimit.attemptSpend(3); + spentToday = await dayLimit.spentToday(); + assert.equal(spentToday, 3); + }); + }); ",0 "diff --git a/contracts/ECRecovery.sol b/contracts/ECRecovery.sol @@ -2,12 +2,20 @@ pragma solidity ^0.4.11; /** -* Eliptic curve signature operations -* Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d + * @title Eliptic curve signature operations + * + * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d */ + library ECRecovery { - // Duplicate Solidity's ecrecover, but catching the CALL return value + /** + * @dev Duplicate Solidity's ecrecover, but catching the CALL return value + * @param hash bytes32 messahe hash from which the signature will be recovered + * @param v uint8 signature version + * @param r bytes32 signature r value + * @param s bytes32 signature s value + */ function safeRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) constant returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as @@ -34,6 +42,11 @@ library ECRecovery { return (ret, addr); } + /** + * @dev Recover signer address from a message by using his signature + * @param hash bytes32 messahe hash from which the signature will be recovered + * @param sig bytes signature + */ function recover(bytes32 hash, bytes sig) constant returns (address) { bytes32 r; bytes32 s; ",0 "diff --git a/test/Ownable.js b/test/Ownable.js @@ -38,6 +38,7 @@ contract('Ownable', function(accounts) { let originalOwner = await ownable.owner(); try { await ownable.transferOwnership(null, {from: originalOwner}); + assert.fail() } catch(error) { assertJump(error); } ",0 "diff --git a/test/Ownable.js b/test/Ownable.js @@ -38,7 +38,7 @@ contract('Ownable', function(accounts) { let originalOwner = await ownable.owner(); try { await ownable.transferOwnership(null, {from: originalOwner}); - assert.fail() + assert.fail(); } catch(error) { assertJump(error); } ",0 "diff --git a/scripts/test.sh b/scripts/test.sh trap cleanup EXIT cleanup() { - # Kill the testrpc instance that we started (if we started one). - if [ -n ""$testrpc_pid"" ]; then + # Kill the testrpc instance that we started (if we started one and if it's still running). + if [ -n ""$testrpc_pid"" ] && ps -p $testrpc_pid > /dev/null; then kill -9 $testrpc_pid fi } ",0 "diff --git a/contracts/examples/SimpleToken.sol b/contracts/examples/SimpleToken.sol pragma solidity ^0.4.11; -import ""./StandardToken.sol""; +import ""../token/StandardToken.sol""; /** @@ -12,10 +12,11 @@ import ""./StandardToken.sol""; */ contract SimpleToken is StandardToken { - string public name = ""SimpleToken""; - string public symbol = ""SIM""; - uint256 public decimals = 18; - uint256 public INITIAL_SUPPLY = 10000; + string public constant name = ""SimpleToken""; + string public constant symbol = ""SIM""; + uint256 public constant decimals = 18; + + uint256 public constant INITIAL_SUPPLY = 10000; /** * @dev Contructor that gives msg.sender all of existing tokens. ",0 "diff --git a/contracts/lifecycle/Pausable.sol b/contracts/lifecycle/Pausable.sol @@ -26,7 +26,7 @@ contract Pausable is Ownable { /** * @dev modifier to allow actions only when the contract IS NOT paused */ - modifier whenPaused { + modifier whenPaused() { require(paused); _; } ",0 "diff --git a/test/MintableToken.js b/test/MintableToken.js 'use strict'; -const assertJump = require('./helpers/assertJump'); +import expectThrow from './helpers/expectThrow'; var MintableToken = artifacts.require('../contracts/Tokens/MintableToken.sol'); contract('Mintable', function(accounts) { @@ -37,4 +37,10 @@ contract('Mintable', function(accounts) { assert(totalSupply, 100); }) + it('should fail to mint after call to finishMinting', async function () { + await token.finishMinting(); + assert.equal(await token.mintingFinished(), true); + await expectThrow(token.mint(accounts[0], 100)); + }) + }); ",0 "diff --git a/contracts/token/BasicToken.sol b/contracts/token/BasicToken.sol @@ -22,6 +22,7 @@ contract BasicToken is ERC20Basic { function transfer(address _to, uint256 _value) returns (bool) { require(_to != address(0)); + // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); ",0 "diff --git a/contracts/ownership/Ownable.sol b/contracts/ownership/Ownable.sol @@ -10,7 +10,7 @@ contract Ownable { address public owner; - event OwnershipTransferred(address indexed newOwner); + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** ",0 "diff --git a/contracts/token/PausableToken.sol b/contracts/token/PausableToken.sol @@ -11,11 +11,23 @@ import '../lifecycle/Pausable.sol'; contract PausableToken is StandardToken, Pausable { - function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) { + function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } - function transferFrom(address _from, address _to, uint256 _value) whenNotPaused public returns (bool) { + function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } + + function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { + return super.approve(_spender, _value); + } + + function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { + return super.increaseApproval(_spender, _addedValue); + } + + function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { + return super.decreaseApproval(_spender, _subtractedValue); + } } ",0 "diff --git a/contracts/token/StandardToken.sol b/contracts/token/StandardToken.sol @@ -14,7 +14,7 @@ import './ERC20.sol'; */ contract StandardToken is ERC20, BasicToken { - mapping (address => mapping (address => uint256)) allowed; + mapping (address => mapping (address => uint256)) internal allowed; /** @@ -70,15 +70,13 @@ contract StandardToken is ERC20, BasicToken { * the first transaction is mined) * From MonolithDAO Token.sol */ - function increaseApproval (address _spender, uint _addedValue) - returns (bool success) { + function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } - function decreaseApproval (address _spender, uint _subtractedValue) - returns (bool success) { + function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; ",0 "diff --git a/test/StandardToken.js b/test/StandardToken.js 'use strict'; const assertJump = require('./helpers/assertJump'); +const expectThrow = require('./helpers/expectThrow'); var StandardTokenMock = artifacts.require('./helpers/StandardTokenMock.sol'); contract('StandardToken', function(accounts) { @@ -70,6 +71,17 @@ contract('StandardToken', function(accounts) { } }); + it('should throw an error when trying to transferFrom more than _from has', async function() { + let balance0 = await token.balanceOf(accounts[0]); + await token.approve(accounts[1], 99); + try { + await token.transferFrom(accounts[0], accounts[2], balance0+1, {from: accounts[1]}); + assert.fail('should have thrown before'); + } catch (error) { + assertJump(error); + } + }); + describe('validating allowance updates to spender', function() { let preApproved; @@ -88,6 +100,13 @@ contract('StandardToken', function(accounts) { }) }); + it('should increase by 50 then set to 0 when decreasing by more than 50', async function() { + await token.approve(accounts[1], 50); + await token.decreaseApproval(accounts[1], 60); + let postDecrease = await token.allowance(accounts[0], accounts[1]); + postDecrease.should.be.bignumber.equal(0); +}); + it('should throw an error when trying to transfer to 0x0', async function() { let token = await StandardTokenMock.new(accounts[0], 100); try { ",0 "diff --git a/docs/source/bounty.rst b/docs/source/bounty.rst @@ -14,7 +14,7 @@ To create a bounty for your contract, inherit from the base `Bounty` contract an Next, implement invariant logic into your smart contract. -Your main contract should inherit from the Target class and implement the checkInvariant method. This is a function that should check everything your contract assumes to be true all the time. If this function returns false, it means your contract was broken in some way and is in an inconsistent state. This is what security researchers will try to acomplish when trying to get the bounty. +Your main contract should inherit from the `Target` class and implement the ```checkInvariant()``` method. This is a function that should check everything your contract assumes to be true all the time. If this function returns false, it means your contract was broken in some way and is in an inconsistent state. This is what security researchers will try to acomplish when trying to get the bounty. At contracts/YourContract.sol:: @@ -35,7 +35,7 @@ At ```migrations/2_deploy_contracts.js```:: deployer.deploy(YourBounty); }; -Next, add a reward to the bounty contract +Next, add a reward to the bounty contract. After deploying the contract, send reward funds into the bounty contract. ",0 "diff --git a/contracts/token/TokenVesting.sol b/contracts/token/TokenVesting.sol @@ -70,6 +70,8 @@ contract TokenVesting is Ownable { function vestedAmount(ERC20Basic token) constant returns (uint256) { if (now < cliff) { return 0; + } else if (now >= end) { + return token.balanceOf(this); } else { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); ",0 "diff --git a/contracts/token/TokenVesting.sol b/contracts/token/TokenVesting.sol @@ -31,6 +31,10 @@ contract TokenVesting is Ownable { * @param _end timestamp of the moment when all balance will have been vested */ function TokenVesting(address _beneficiary, uint256 _cliff, uint256 _end) { + require(_beneficiary != 0x0); + require(_cliff > now); + require(_end > _cliff); + beneficiary = _beneficiary; cliff = _cliff; end = _end; ",0 "diff --git a/test/TokenVesting.js b/test/TokenVesting.js @@ -48,6 +48,8 @@ contract('TokenVesting', function ([_, owner, beneficiary]) { balance.should.bignumber.equal(amount.mul(releaseTime - this.start).div(this.end - this.start).floor()); }); + it('should linearly release tokens during vesting period'); + it('should have released all after end', async function () { await increaseTimeTo(this.end); await this.vesting.release(this.token.address); @@ -55,4 +57,8 @@ contract('TokenVesting', function ([_, owner, beneficiary]) { balance.should.bignumber.equal(amount); }); + it('should fail to be revoked by owner if revocable not set'); + + it('should be emptied when revoked by owner'); + }); ",0 "diff --git a/contracts/crowdsale/Crowdsale.sol b/contracts/crowdsale/Crowdsale.sol @@ -59,12 +59,16 @@ contract Crowdsale { return new MintableToken(); } - // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } + // Override this function to create logic for periodization + function getTokenAmount(uint256 weiAmount) internal constant returns(uint256) { + return weiAmount.mul(rate); + } + // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); ",0 "diff --git a/test/ECRecovery.test.js b/test/ECRecovery.test.js @@ -5,7 +5,7 @@ var hashMessage = require('./helpers/hashMessage.js'); contract('ECRecovery', function (accounts) { let ecrecovery; - const TEST_MESSAGE = 'OpenZeppelin' + const TEST_MESSAGE = 'OpenZeppelin'; before(async function () { const ecRecoveryLib = await ECRecoveryLib.new(); ",0 "diff --git a/contracts/math/SafeMath.sol b/contracts/math/SafeMath.sol @@ -6,6 +6,10 @@ pragma solidity ^0.4.18; * @dev Math operations with safety checks that throw on error */ library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; @@ -15,6 +19,9 @@ library SafeMath { return c; } + /** + * @dev Integer division of two numbers, truncating the quotient. + */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; @@ -22,11 +29,17 @@ library SafeMath { return c; } + /** + * @dev Substracts two numbers, throws if subtrahend is greater than minuend. + */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } + /** + * @dev Adds two numbers, throws on overflow. + */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); ",0 "diff --git a/test/SimpleSavingsWallet.js b/test/SimpleSavingsWallet.js 'use strict' +import assertJump from './helpers/assertJump' const SimpleSavingsWallet = artifacts.require('../contracts/examples/SimpleSavingsWallet.sol') @@ -6,11 +7,46 @@ contract('SimpleSavingsWallet', function(accounts) { let savingsWallet let owner + const paymentAmount = 4242 + beforeEach(async function() { savingsWallet = await SimpleSavingsWallet.new(4141) - owner = await inheritable.owner() + owner = await savingsWallet.owner() }) it('should receive funds', async function() { - await web3.eth.sendTransaction({from: owner, to: this.contract.address, value: amount}) + await web3.eth.sendTransaction({from: owner, to: savingsWallet.address, value: paymentAmount}) + assert.isTrue( + (new web3.BigNumber(paymentAmount)).equals(web3.eth.getBalance(savingsWallet.address)) + ) + }) + + it('owner can send funds', async function() { + // Receive payment so we have some money to spend. + await web3.eth.sendTransaction({from: accounts[9], to: savingsWallet.address, value: 1000000}) + try { + await savingsWallet.sendTo(0, paymentAmount, {from: owner}) + assert.fail('should have thrown before') + } catch(error) { + assertJump(error) + } + try { + await savingsWallet.sendTo(savingsWallet.address, paymentAmount, {from: owner}) + assert.fail('should have thrown before') + } catch(error) { + assertJump(error) + } + try { + await savingsWallet.sendTo(accounts[1], 0, {from: owner}) + assert.fail('should have thrown before') + } catch(error) { + assertJump(error) + } + + const balance = web3.eth.getBalance(accounts[1]) + await savingsWallet.sendTo(accounts[1], paymentAmount, {from: owner}) + assert.isTrue( + balance.plus(paymentAmount).equals(web3.eth.getBalance(accounts[1])) + ) + }) }) ",0 "diff --git a/README.md b/README.md @@ -23,10 +23,12 @@ truffle init To install the OpenZeppelin library, run the following in your Solidity project root directory: ```sh -npm init -npm install zeppelin-solidity +npm init -y +npm install -E zeppelin-solidity ``` +**Note that OpenZeppelin does not currently follow semantic versioning.** You may encounter breaking changes upon a minor version bump. We recommend pinning the version of OpenZeppelin you use, as done by the `-E` (`--save-exact`) option. + After that, you'll get all the library's contracts in the `node_modules/zeppelin-solidity/contracts` folder. You can use the contracts in the library like so: ```js ",0 "diff --git a/test/crowdsale/IndividuallyCappedCrowdsale.test.js b/test/crowdsale/IndividuallyCappedCrowdsale.test.js @@ -23,8 +23,8 @@ contract('IndividuallyCappedCrowdsale', function ([_, wallet, alice, bob, charli beforeEach(async function () { this.token = await SimpleToken.new(); this.crowdsale = await CappedCrowdsale.new(rate, wallet, this.token.address); - this.crowdsale.setUserCap(alice, capAlice); - this.crowdsale.setUserCap(bob, capBob); + await this.crowdsale.setUserCap(alice, capAlice); + await this.crowdsale.setUserCap(bob, capBob); await this.token.transfer(this.crowdsale.address, tokenSupply); }); ",0 "diff --git a/contracts/token/ERC20/StandardToken.sol b/contracts/token/ERC20/StandardToken.sol @@ -86,7 +86,7 @@ contract StandardToken is ERC20, BasicToken { */ function increaseApproval( address _spender, - uint _addedValue + uint256 _addedValue ) public returns (bool) @@ -109,12 +109,12 @@ contract StandardToken is ERC20, BasicToken { */ function decreaseApproval( address _spender, - uint _subtractedValue + uint256 _subtractedValue ) public returns (bool) { - uint oldValue = allowed[msg.sender][_spender]; + uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { ",0 "diff --git a/RELEASING.md b/RELEASING.md @@ -34,10 +34,10 @@ git push upstream vX.Y.Z-rc.R Draft the release notes in our [GitHub releases](https://github.com/OpenZeppelin/openzeppelin-solidity/releases). Make sure to mark it as a pre-release! Try to be consistent with our previous release notes in the title and format of the text. Release candidates don't need a detailed changelog, but make sure to include a link to GitHub's compare page. -Once the CI run for the new tag is green, publish on npm. +Once the CI run for the new tag is green, publish on npm under the `next` tag. ``` -npm publish +npm publish --tag next ``` Publish the release notes on GitHub and ask our community manager to announce the release candidate on at least Slack and Twitter. @@ -67,6 +67,12 @@ npm publish Publish the release notes on GitHub and ask our community manager to announce the release! +Delete the `next` tag in the npm package as there is no longer a release candidate. + +``` +npm dist-tag rm --otp $2FA_CODE openzeppelin-solidity next +``` + ## Merging the release branch After the final release, the release branch should be merged back into `master`. This merge must not be squashed, because it would lose the tagged release commit, so it should be merged locally and pushed. ",0 "diff --git a/test/lifecycle/Pausable.test.js b/test/lifecycle/Pausable.test.js const { assertRevert } = require('../helpers/assertRevert'); +const expectEvent = require('../helpers/expectEvent'); const PausableMock = artifacts.require('PausableMock'); const BigNumber = web3.BigNumber; @@ -53,4 +54,12 @@ contract('Pausable', function () { (await this.Pausable.drasticMeasureTaken()).should.equal(false); }); + + it('should log Pause and Unpause events appropriately', async function () { + const setPauseLogs = (await this.Pausable.pause()).logs; + expectEvent.inLogs(setPauseLogs, 'Pause'); + + const setUnPauseLogs = (await this.Pausable.unpause()).logs; + expectEvent.inLogs(setUnPauseLogs, 'Unpause'); + }); }); ",0 "diff --git a/README.md b/README.md npm install openzeppelin-solidity ``` +If you're interested in trying out a preview of OpenZeppelin 2.0, install `openzeppelin-solidity@next`, check out the [release notes](https://github.com/OpenZeppelin/openzeppelin-solidity/releases/tag/v2.0.0-rc.1), and let us know what you think! + ## Usage To write your custom contracts, import ours and extend them through inheritance. ",0 "diff --git a/contracts/drafts/TokenVesting.sol b/contracts/drafts/TokenVesting.sol @@ -161,7 +161,7 @@ contract TokenVesting is Ownable { * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { - uint256 currentBalance = token.balanceOf(this); + uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[token]); if (block.timestamp < _cliff) { ",0 "diff --git a/RELEASING.md b/RELEASING.md @@ -36,7 +36,7 @@ Draft the release notes in our [GitHub releases](https://github.com/OpenZeppelin Before publishing on npm you need to generate the build artifacts. This is not done automatically at the moment because of a bug in Truffle. Since some of the contracts should not be included in the package, this is a _hairy_ process that you need to do with care. -1. Delete the `contracts/mocks` and `contracts/examples` directories. +1. Delete the `contracts/mocks`, `contracts/examples` and `build` directories. 2. Run `truffle compile`. (Note that the Truffle process may never exit and you will have to interrupt it.) 3. Recover the directories using `git checkout`. It doesn't matter if you do this now or later. @@ -70,7 +70,7 @@ Draft the release notes in GitHub releases. Try to be consistent with our previo Before publishing on npm you need to generate the build artifacts. This is not done automatically at the moment because of a bug in Truffle. Since some of the contracts should not be included in the package, this is a _hairy_ process that you need to do with care. -1. Delete the `contracts/mocks` and `contracts/examples` directories. +1. Delete the `contracts/mocks`, `contracts/examples` and `build` directories. 2. Run `truffle compile`. (Note that the Truffle process may never exit and you will have to interrupt it.) 3. Recover the directories using `git checkout`. It doesn't matter if you do this now or later. ",0 "diff --git a/test/behavior/access/roles/PublicRole.behavior.js b/test/behavior/access/roles/PublicRole.behavior.js @@ -5,6 +5,21 @@ function capitalize (str) { return str.replace(/\b\w/g, l => l.toUpperCase()); } +// Tests that a role complies with the standard role interface, that is: +// * an onlyRole modifier +// * an isRole function +// * an addRole function, accessible to role havers +// * a renounceRole function +// * roleAdded and roleRemoved events +// Both the modifier and an additional internal remove function are tested through a mock contract that exposes them. +// This mock contract should be stored in this.contract. +// +// @param authorized an account that has the role +// @param otherAuthorized another account that also has the role +// @param anyone an account that doesn't have the role, passed inside an array for ergonomics +// @param rolename a string with the name of the role +// @param manager undefined for regular roles, or a manager account for managed roles. In these, only the manager +// account can create and remove new role bearers. function shouldBehaveLikePublicRole (authorized, otherAuthorized, [anyone], rolename, manager) { rolename = capitalize(rolename); ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md ## 2.2.0 (unreleased) +## 2.1.2 (2019-17-01) + * Removed most of the test suite from the npm package, except `PublicRole.behavior.js`, which may be useful to users testing their own `Roles`. + ## 2.1.1 (2019-04-01) * Version bump to avoid conflict in the npm registry. ",0 "diff --git a/contracts/drafts/ERC20Snapshot.sol b/contracts/drafts/ERC20Snapshot.sol @@ -7,7 +7,8 @@ import ""../token/ERC20/ERC20.sol""; /** * @title ERC20 token with snapshots. - * inspired by Jordi Baylina's MiniMeToken to record historical balances + * Inspired by Jordi Baylina's MiniMeToken to record historical balances: + * https://github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol * Snapshots store a value at the time a snapshot is taken (and a new snapshot id created), and the corresponding * snapshot id. Each account has individual snapshots taken on demand, as does the token's total supply. * @author Validity Labs AG ",0 "diff --git a/contracts/drafts/ERC20Snapshot.sol b/contracts/drafts/ERC20Snapshot.sol @@ -7,7 +7,7 @@ import ""../token/ERC20/ERC20.sol""; /** * @title ERC20 token with snapshots. - * Inspired by Jordi Baylina's MiniMeToken to record historical balances: + * @dev Inspired by Jordi Baylina's MiniMeToken to record historical balances: * https://github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol * Snapshots store a value at the time a snapshot is taken (and a new snapshot id created), and the corresponding * snapshot id. Each account has individual snapshots taken on demand, as does the token's total supply. ",0 "diff --git a/contracts/drafts/ERC20Snapshot.sol b/contracts/drafts/ERC20Snapshot.sol @@ -11,6 +11,11 @@ import ""../token/ERC20/ERC20.sol""; * https://github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol * When a snapshot is made, the balances and totalSupply at the time of the snapshot are recorded for later * access. + * + * To make a snapshot, call the `snapshot` function, which will emit the `Snapshot` event and return a snapshot id. + * To get the total supply from a snapshot, call the function `totalSupplyAt` with the snapshot id. + * To get the balance of an account from a snapshot, call the `balanceOfAt` function with the snapshot id and the + * account address. * @author Validity Labs AG */ contract ERC20Snapshot is ERC20 { ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md ## 2.2.0 (unreleased) ### New features: - * `ERC20`: added internal `_approve(address owner, address spender, uint256 value)`, allowing derived contracts to set the allowance of arbitrary accounts. - * `ERC20Metadata`: added internal `_setTokenURI(string memory tokenURI)`. - * `ERC20Snapshot`: create snapshots on demand of the token balances and total supply, to later retrieve and e.g. calculate dividends at a past time. + * `ERC20`: added internal `_approve(address owner, address spender, uint256 value)`, allowing derived contracts to set the allowance of arbitrary accounts. ([#1609](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1609)) + * `ERC20Metadata`: added internal `_setTokenURI(string memory tokenURI)`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618)) + * `ERC20Snapshot`: create snapshots on demand of the token balances and total supply, to later retrieve and e.g. calculate dividends at a past time. ([#1617](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1617)) ### Improvements: - * Upgraded the minimum compiler version to v0.5.2: this removes many Solidity warnings that were false positives. - * `Counter`'s API has been improved, and is now used by `ERC721` (though it is still in `drafts`). - * `ERC721`'s transfers are now more gas efficient due to removal of unnecessary `SafeMath` calls. - * Fixed variable shadowing issues. + * Upgraded the minimum compiler version to v0.5.2: this removes many Solidity warnings that were false positives. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606)) + * `Counter`'s API has been improved, and is now used by `ERC721` (though it is still in `drafts`). ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610)) + * `ERC721`'s transfers are now more gas efficient due to removal of unnecessary `SafeMath` calls. ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610)) + * Fixed variable shadowing issues. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606)) ### Bugfixes: ### Breaking changes: - * `TokenMetadata` (in drafts) has been renamed to `ERC20Metadata`. + * `TokenMetadata` (in drafts) has been renamed to `ERC20Metadata`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618)) ## 2.1.2 (2019-17-01) * Removed most of the test suite from the npm package, except `PublicRole.behavior.js`, which may be useful to users testing their own `Roles`. ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md * Fixed variable shadowing issues. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606)) ### Bugfixes: + * (minor) `SafeERC20`: `safeApprove` wasn't properly checking for a zero allowance when attempting to set a non-zero allowance. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647)) ### Breaking changes: * `TokenMetadata` (in drafts) has been renamed to `ERC20Metadata`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618)) ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md ## 2.2.0 (unreleased) +## 2.1.3 (2019-26-02) + * Backported `SafeERC20.safeApprove` bugfix. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647)) + ## 2.1.2 (2019-17-01) * Removed most of the test suite from the npm package, except `PublicRole.behavior.js`, which may be useful to users testing their own `Roles`. ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md # Changelog -## 2.2.0 (unreleased) +## 2.2.0 (2019-03-14) ### New features: * `ERC20Snapshot`: create snapshots on demand of the token balances and total supply, to later retrieve and e.g. calculate dividends at a past time. ([#1617](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1617)) ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md * Upgraded the minimum compiler version to v0.5.2: this removes many Solidity warnings that were false positives. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606)) * `ECDSA`: `recover` no longer accepts malleable signatures (those using upper-range values for `s`, or 0/1 for `v`). ([#1622](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1622)) * `ERC721`'s transfers are now more gas efficient due to removal of unnecessary `SafeMath` calls. ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610)) - * `Counter`'s API has been improved, and is now used by `ERC721` (though it is still in `drafts`). ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610)) * Fixed variable shadowing issues. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606)) ### Bugfixes: * (minor) `SafeERC20`: `safeApprove` wasn't properly checking for a zero allowance when attempting to set a non-zero allowance. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647)) -### Breaking changes: - * `TokenMetadata` (in drafts) has been renamed to `ERC20Metadata`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618)) +### Breaking changes in drafts: + * `TokenMetadata` has been renamed to `ERC20Metadata`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618)) + * The library `Counter` has been renamed to `Counters` and its API has been improved. See an example in `ERC721`, lines [17](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/3cb4a00fce1da76196ac0ac3a0ae9702b99642b5/contracts/token/ERC721/ERC721.sol#L17) and [204](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/3cb4a00fce1da76196ac0ac3a0ae9702b99642b5/contracts/token/ERC721/ERC721.sol#L204). ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610)) ## 2.1.3 (2019-02-26) * Backported `SafeERC20.safeApprove` bugfix. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647)) ",0 "diff --git a/.circleci/config.yml b/.circleci/config.yml @@ -8,6 +8,14 @@ aliases: docker: - image: circleci/node:8 + - &npm_install_if_necessary + run: + name: Install npm dependencies + command: | + if [ ! -d node_modules ]; then + npm ci + fi + - &cache_key_node_modules key: v1-node_modules-{{ checksum ""package-lock.json"" }} @@ -18,12 +26,7 @@ jobs: - checkout - restore_cache: <<: *cache_key_node_modules - - run: - name: Install npm dependencies - command: | - if [ ! -d node_modules ]; then - npm ci - fi + - *npm_install_if_necessary - save_cache: paths: - node_modules @@ -35,6 +38,7 @@ jobs: - checkout - restore_cache: <<: *cache_key_node_modules + - *npm_install_if_necessary - run: name: Linter command: npm run lint @@ -44,6 +48,7 @@ jobs: - checkout - restore_cache: <<: *cache_key_node_modules + - *npm_install_if_necessary - run: name: Unit tests command: npm run test @@ -54,6 +59,7 @@ jobs: - checkout - restore_cache: <<: *cache_key_node_modules + - *npm_install_if_necessary - run: name: Unit tests with coverage report command: npm run test ",0 "diff --git a/scripts/release/release.sh b/scripts/release/release.sh @@ -81,7 +81,10 @@ environment_check() { environment_check -if [[ ""$*"" == ""start minor"" ]]; then +if [[ ""$*"" == ""push"" ]]; then + push_and_publish next + +elif [[ ""$*"" == ""start minor"" ]]; then log ""Creating new minor pre-release"" assert_current_branch master ",0 "diff --git a/contracts/token/ERC721/ERC721.sol b/contracts/token/ERC721/ERC721.sol @@ -317,7 +317,7 @@ contract ERC721 is Context, ERC165, IERC721 { * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * - * This function is deprecated. + * This is an internal detail of the `ERC721` contract and its use is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md # Changelog -## 3.1.1 (Unreleased) +## 3.2.0 (unreleased) + +### New features + * Proxies: added the proxy contracts from OpenZeppelin SDK. ([#2335](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2335)) ### Improvements * `Address.isContract`: switched from `extcodehash` to `extcodesize` for less gas usage. ([#2311](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2311)) +### Breaking changes + * `ERC20Snapshot`: switched to using `_beforeTokenTransfer` hook instead of overriding ERC20 operations. ([#2312](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2312)) + +This small change in the way we implemented `ERC20Snapshot` may affect users who are combining this contract with +other ERC20 flavors, since it no longer overrides `_transfer`, `_mint`, and `_burn`. This can result in having to remove Solidity `override(...)` specifiers in derived contracts for these functions, and to instead have to add it for `_beforeTokenTransfer`. See [Using Hooks](https://docs.openzeppelin.com/contracts/3.x/extending-contracts#using-hooks) in the documentation. + ## 3.1.0 (2020-06-23) ### New features ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md # Changelog +## 3.2.1-solc-0.7 (unreleased) + +* `ERC777`: Remove a warning about function state visibility in Solidity 0.7. ([#2327](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2327)) + ## 3.2.0 (2020-09-10) ### New features ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md ## 3.3.0 (unreleased) * `Address`: added `functionStaticCall` and `functionDelegateCall`, similar to the existing `functionCall`. ([#2333](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2333)) + * `TimelockController`: added a contract to augment access control schemes with a delay. ([#2364](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2364)) ## 3.2.0 (2020-09-10) ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md # Changelog +## Unreleased + + * Add beacon proxy. ([#2411](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2411)) + ## Unreleased * Now supports both Solidity 0.6 and 0.7. Compiling with solc 0.7 will result in warnings. Install the `solc-0.7` tag to compile without warnings. ",0 "diff --git a/contracts/math/SafeMath.sol b/contracts/math/SafeMath.sol pragma solidity ^0.8.0; +// CAUTION +// This version of SafeMath should only be used with Solidity 0.8 or later, +// because it relies on the compiler's built in overflow checks. + /** * @dev Wrappers over Solidity's arithmetic operations. */ ",0 "diff --git a/contracts/utils/structs/EnumerableSet.sol b/contracts/utils/structs/EnumerableSet.sol @@ -89,7 +89,7 @@ library EnumerableSet { // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value - set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based + set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex // Delete the slot where the moved value was stored set._values.pop(); ",0 "diff --git a/docs/modules/ROOT/pages/upgradeable.adoc b/docs/modules/ROOT/pages/upgradeable.adoc @@ -6,6 +6,8 @@ This variant is available as a separate package called `@openzeppelin/contracts- It follows all of the rules for xref:upgrades-plugins::writing-upgradeable.adoc[Writing Upgradeable Contracts]: constructors are replaced by initializer functions, state variables are initialized in initializer functions, and we additionally check for storage incompatibilities across minor versions. +TIP: OpenZeppelin provides a full suite of tools for deploying and securing upgradeable smart contracts. xref:openzeppelin::upgrades.adoc[Check out the full list of resources]. + == Overview === Installation ",0 "diff --git a/contracts/utils/cryptography/ECDSA.sol b/contracts/utils/cryptography/ECDSA.sol @@ -28,15 +28,13 @@ library ECDSA { * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { - // Divide the signature in r, s and v variables - bytes32 r; - bytes32 s; - uint8 v; - // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { + bytes32 r; + bytes32 s; + uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { @@ -44,25 +42,45 @@ library ECDSA { s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } + return recover(hash, v, r, s); } else if (signature.length == 64) { + bytes32 r; + bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { - let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) - s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) - v := add(shr(255, vs), 27) + vs := mload(add(signature, 0x40)) } + return recover(hash, r, vs); } else { revert(""ECDSA: invalid signature length""); } + } + /** + * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately. + * + * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] + * + * _Available since v4.2._ + */ + function recover( + bytes32 hash, + bytes32 r, + bytes32 vs + ) internal pure returns (address) { + bytes32 s; + uint8 v; + assembly { + s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) + v := add(shr(255, vs), 27) + } return recover(hash, v, r, s); } /** - * @dev Overload of {ECDSA-recover} that receives the `v`, - * `r` and `s` signature fields separately. + * @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately. */ function recover( bytes32 hash, ",0 "diff --git a/contracts/governance/compatibility/GovernorCompatibilityBravo.sol b/contracts/governance/compatibility/GovernorCompatibilityBravo.sol @@ -15,6 +15,8 @@ import ""./IGovernorCompatibilityBravo.sol""; * This compatibility layer includes a voting system and requires a {IGovernorTimelock} compatible module to be added * through inheritance. It does not include token bindings, not does it include any variable upgrade patterns. * + * NOTE: When using this module, you may need to enable the Solidity optimizer to avoid hitting the contract size limit. + * * _Available since v4.3._ */ abstract contract GovernorCompatibilityBravo is ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md @@ -95,6 +95,10 @@ Make sure you're using git or another version control system to be able to recov Some further changes have been done between the different beta iterations. Transitions made during this period are configured in the `migrate-imports` script. Consequently, you can upgrade from any previous 4.0-beta.x version using the same script as described in the *How to upgrade from 3.x* section. +## 3.4.1 (2021-03-03) + + * `ERC721`: made `_approve` an internal function (was private). + ## 3.4.0 (2021-02-02) * `BeaconProxy`: added new kind of proxy that allows simultaneous atomic upgrades. ([#2411](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2411)) ",0 "diff --git a/contracts/proxy/utils/Initializable.sol b/contracts/proxy/utils/Initializable.sol @@ -13,6 +13,22 @@ pragma solidity ^0.8.0; * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. + * + * [CAUTION] + * ==== + * Avoid leaving a contract uninitialized. + * + * An uninitialized contract can be used in certain kinds of exploits since it may allow an attacker to take control of + * the contract. This includes the implementation contract behind a proxy. You can either invoke the initializer + * manually, independently of initialization of the proxy, or you can include a constructor to automatically mark it as + * initialized when it is deployed: + * + * [.hljs-theme-light.nopadding] + * ``` + * /// @custom:oz-upgrades-unsafe-allow constructor + * constructor() initializer {} + * ``` + * ==== */ abstract contract Initializable { /** ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md * `PaymentSplitter`: now supports ERC20 assets in addition to Ether. ([#2858](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/#2858)) * `ECDSA`: add a variant of `toEthSignedMessageHash` for arbitrary length message hashing. ([#2865](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/#2865)) * `MerkleProof`: add a `processProof` function that returns the rebuilt root hash given a leaf and a proof. ([#2841](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2841)) - * `VestingWallet`: new contract that handles the vesting of Ether and ERC20 tokens following a customizable vesting schedule. ([#2748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/#2748)) + * `VestingWallet`: new contract that handles the vesting of Ether and ERC20 tokens following a customizable vesting schedule. ([#2748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2748)) + * `Governor`: enable receiving Ether when a Timelock contract is not used. ([#2748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2748)) + * `GovernorTimelockCompound`: fix ability to use Ether stored in the Timelock contract. ([#2748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2748)) ## 4.3.2 (2021-09-14) ",0 "diff --git a/SECURITY.md b/SECURITY.md @@ -11,6 +11,8 @@ The recommendation is to use the latest version available. | 2.5 | :white_check_mark: | | < 2.0 | :x: | +Note that the Solidity language itself only guarantees security updates for the latest release. + ## Reporting a Vulnerability Please report any security issues you find to security@openzeppelin.org. ",0 "diff --git a/docs/modules/ROOT/pages/governance.adoc b/docs/modules/ROOT/pages/governance.adoc @@ -134,6 +134,7 @@ For 3) we will use GovernorCountingSimple, a module that offers 3 options to vot Besides these modules, Governor itself has some parameters we must set. votingDelay: How long after a proposal is created should voting power be fixed. A large voting delay gives users time to unstake tokens if necessary. + votingPeriod: How long does a proposal remain open to votes. These parameters are specified in number of blocks. Assuming block time of around 13.14 seconds, we will set votingDelay = 1 day = 6570 blocks, and votingPeriod = 1 week = 45992 blocks. ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md * `GovernorTimelockControl`: improve the `state()` function to have it reflect cases where a proposal has been canceled directly on the timelock. ([#2977](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2977)) * `Math`: add a `abs(int256)` method that returns the unsigned absolute value of a signed value. ([#2984](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2984)) +* Preset contracts are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com). ([#2986](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2986)) ## Unreleased ",0 "diff --git a/docs/modules/ROOT/pages/erc721.adoc b/docs/modules/ROOT/pages/erc721.adoc @@ -16,10 +16,11 @@ Here's what a contract for tokenized items might look like: // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; +import ""@openzeppelin/contracts/token/ERC721/ERC721.sol""; import ""@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol""; import ""@openzeppelin/contracts/utils/Counters.sol""; -contract GameItem is ERC721URIStorage { +contract GameItem is ERC721, ERC721URIStorage { using Counters for Counters.Counter; Counters.Counter private _tokenIds; ",0 "diff --git a/contracts/governance/extensions/GovernorTimelockControl.sol b/contracts/governance/extensions/GovernorTimelockControl.sol @@ -10,7 +10,7 @@ import ""../TimelockController.sol""; /** * @dev Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a * delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The - * {Governor} needs the proposer (an ideally the executor) roles for the {Governor} to work properly. + * {Governor} needs the proposer (and ideally the executor) roles for the {Governor} to work properly. * * Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus, * the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be ",0 "diff --git a/contracts/governance/extensions/GovernorTimelockControl.sol b/contracts/governance/extensions/GovernorTimelockControl.sol @@ -16,6 +16,10 @@ import ""../TimelockController.sol""; * the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be * inaccessible. * + * WARNING: Setting up the TimelockController to have additional proposers besides the governor introduces the risk that + * approved governance proposals could be blocked by the other proposers, effectively executing a Denial of Service attack, + * and therefore blocking access to governance-controlled assets. + * * _Available since v4.3._ */ abstract contract GovernorTimelockControl is IGovernorTimelock, Governor { ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md * `Votes`: Added a base contract for vote tracking with delegation. ([#2944](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2944)) * `ERC721Votes`: Added an extension of ERC721 enabled with vote tracking and delegation. ([#2944](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2944)) * `ERC2771Context`: use immutable storage to store the forwarder address, no longer an issue since Solidity >=0.8.8 allows reading immutable variables in the constructor. ([#2917](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2917)) - * `Base64`: add a library to parse bytes into base64 strings using `encode(bytes memory)` function, and provide examples to show how to use to build URL-safe `tokenURIs` ([#2884](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/#2884)) - * `ERC20`: reduce allowance before triggering transfer. + * `Base64`: add a library to parse bytes into base64 strings using `encode(bytes memory)` function, and provide examples to show how to use to build URL-safe `tokenURIs`. ([#2884](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/#2884)) + * `ERC20`: reduce allowance before triggering transfer. ([#3056](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/#3056)) ## 4.4.1 (2021-12-14) ",0 "diff --git a/contracts/token/ERC20/utils/TokenTimelock.sol b/contracts/token/ERC20/utils/TokenTimelock.sol @@ -24,6 +24,11 @@ contract TokenTimelock { // timestamp when token release is enabled uint256 private immutable _releaseTime; + /** + * @dev Deploys a timelock instance that is able to hold the token specified, and will only release it to + * `beneficiary_` when {release} is invoked after `releaseTime_`. The release time is specified as a Unix timestamp + * (in seconds). + */ constructor( IERC20 token_, address beneficiary_, @@ -36,28 +41,29 @@ contract TokenTimelock { } /** - * @return the token being held. + * @dev Returns the token being held. */ function token() public view virtual returns (IERC20) { return _token; } /** - * @return the beneficiary of the tokens. + * @dev Returns the beneficiary that will receive the tokens. */ function beneficiary() public view virtual returns (address) { return _beneficiary; } /** - * @return the time when the tokens are released. + * @dev Returns the time when the tokens are released in seconds since Unix epoch (i.e. Unix timestamp). */ function releaseTime() public view virtual returns (uint256) { return _releaseTime; } /** - * @notice Transfers tokens held by timelock to beneficiary. + * @dev Transfers tokens held by the timelock to the beneficiary. Will only succeed if invoked after the release + * time. */ function release() public virtual { require(block.timestamp >= releaseTime(), ""TokenTimelock: current time is before release time""); ",0 "diff --git a/contracts/utils/cryptography/SignatureChecker.sol b/contracts/utils/cryptography/SignatureChecker.sol @@ -8,16 +8,20 @@ import ""../Address.sol""; import ""../../interfaces/IERC1271.sol""; /** - * @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and - * ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with - * smart contract wallets such as Argent and Gnosis. - * - * Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change - * through time. It could return true at block N and false at block N+1 (or the opposite). + * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA + * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like + * Argent and Gnosis Safe. * * _Available since v4.1._ */ library SignatureChecker { + /** + * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the + * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. + * + * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus + * change through time. It could return true at block N and false at block N+1 (or the opposite). + */ function isValidSignatureNow( address signer, bytes32 hash, ",0 "diff --git a/contracts/token/ERC1155/extensions/ERC1155Supply.sol b/contracts/token/ERC1155/extensions/ERC1155Supply.sol @@ -51,7 +51,13 @@ abstract contract ERC1155Supply is ERC1155 { if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { - _totalSupply[ids[i]] -= amounts[i]; + uint256 id = ids[i]; + uint256 amount = amounts[i]; + uint256 supply = _totalSupply[id]; + require(supply >= amount, ""ERC1155: burn amount exceeds totalSupply""); + unchecked { + _totalSupply[id] = supply - amount; + } } } } ",0 "diff --git a/contracts/utils/structs/DoubleEndedQueue.sol b/contracts/utils/structs/DoubleEndedQueue.sol @@ -102,6 +102,8 @@ library DoubleEndedQueue { /** * @dev Returns the item at the beginning of the queue. + * + * Reverts with `Empty` if the queue is empty. */ function front(Bytes32Deque storage deque) internal view returns (bytes32 value) { if (empty(deque)) revert Empty(); @@ -111,6 +113,8 @@ library DoubleEndedQueue { /** * @dev Returns the item at the end of the queue. + * + * Reverts with `Empty` if the queue is empty. */ function back(Bytes32Deque storage deque) internal view returns (bytes32 value) { if (empty(deque)) revert Empty(); ",0 "diff --git a/README.md b/README.md @@ -22,6 +22,8 @@ $ npm install @openzeppelin/contracts OpenZeppelin Contracts features a [stable API](https://docs.openzeppelin.com/contracts/releases-stability#api-stability), which means your contracts won't break unexpectedly when upgrading to a newer minor version. +An alternative to npm is to use the GitHub repository `openzeppelin/openzeppelin-contracts` to retrieve the contracts. When doing this, make sure to specify the tag for a release such as `v4.5.0`, instead of using the `master` branch. + ### Usage Once installed, you can use the contracts in the library by importing them: ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md * `DoubleEndedQueue`: a new data structure that supports efficient push and pop to both front and back, useful for FIFO and LIFO queues. ([#3153](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3153)) * `Governor`: improved security of `onlyGovernance` modifier when using an external executor contract (e.g. a timelock) that can operate without necessarily going through the governance protocol. ([#3147](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3147)) * `ERC20FlashMint`: support infinite allowance when paying back a flash loan. ([#3226](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3226)) - * `Governor`: Add a way to parameterize votes. This can be used to implement voting systems such as fractionalized voting, ERC721 based voting, or any number of other systems. The `params` argument added to `_countVote` method, and included in the newly added `_getVotes` method, can be used by counting and voting modules respectively for such purposes. + * `Governor`: Add a way to parameterize votes. This can be used to implement voting systems such as fractionalized voting, ERC721 based voting, or any number of other systems. The `params` argument added to `_countVote` method, and included in the newly added `_getVotes` method, can be used by counting and voting modules respectively for such purposes. ([#3043](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3043)) * `TimelockController`: Add a separate canceller role for the ability to cancel. ([#3165](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3165)) * `draft-ERC20Permit`: replace `immutable` with `constant` for `_PERMIT_TYPEHASH` since the `keccak256` of string literals is treated specially and the hash is evaluated at compile time. ([#3196](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3196)) * `ERC20Wrapper`: the `decimals()` function now tries to fetch the value from the underlying token instance. If that calls revert, then the default value is used. ([#3259](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3259)) ",0 "diff --git a/contracts/mocks/crosschain/receivers.sol b/contracts/mocks/crosschain/receivers.sol @@ -19,6 +19,7 @@ abstract contract Receiver is Ownable, CrossChainEnabled { * AMB */ contract CrossChainEnabledAMBMock is Receiver, CrossChainEnabledAMB { + /// @custom:oz-upgrades-unsafe-allow constructor constructor(address bridge) CrossChainEnabledAMB(bridge) {} } @@ -26,6 +27,7 @@ contract CrossChainEnabledAMBMock is Receiver, CrossChainEnabledAMB { * Arbitrum */ contract CrossChainEnabledArbitrumL1Mock is Receiver, CrossChainEnabledArbitrumL1 { + /// @custom:oz-upgrades-unsafe-allow constructor constructor(address bridge) CrossChainEnabledArbitrumL1(bridge) {} } @@ -35,6 +37,7 @@ contract CrossChainEnabledArbitrumL2Mock is Receiver, CrossChainEnabledArbitrumL * Optimism */ contract CrossChainEnabledOptimismMock is Receiver, CrossChainEnabledOptimism { + /// @custom:oz-upgrades-unsafe-allow constructor constructor(address bridge) CrossChainEnabledOptimism(bridge) {} } @@ -42,5 +45,6 @@ contract CrossChainEnabledOptimismMock is Receiver, CrossChainEnabledOptimism { * Polygon */ contract CrossChainEnabledPolygonChildMock is Receiver, CrossChainEnabledPolygonChild { + /// @custom:oz-upgrades-unsafe-allow constructor constructor(address bridge) CrossChainEnabledPolygonChild(bridge) {} } ",0 "diff --git a/CHANGELOG.md b/CHANGELOG.md * `Initializable`: add an Initialized event that tracks initialized version numbers. ([#3294](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3294)) * `ERC2981`: make `royaltyInfo` public to allow super call in overrides. ([#3305](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3305)) +### Upgradeability notice + +* `TimelockController`: **(Action needed)** The upgrade from <4.6 to >=4.6 introduces a new `CANCELLER_ROLE` that requires set up to be assignable. After the upgrade, only addresses with this role will have the ability to cancel. Proposers will no longer be able to cancel. Assigning cancellers can be done by an admin (including the timelock itself) once the role admin is set up. To do this, we recommend upgrading to the `TimelockControllerWith46MigrationUpgradeable` contract and then calling the `migrateTo46` function. + ### Breaking changes * `Governor`: Adds internal virtual `_getVotes` method that must be implemented; this is a breaking change for existing concrete extensions to `Governor`. To fix this on an existing voting module extension, rename `getVotes` to `_getVotes` and add a `bytes memory` argument. ([#3043](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3043)) ",0 "diff --git a/contracts/access/AccessControl.sol b/contracts/access/AccessControl.sol @@ -138,6 +138,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 { * Requirements: * * - the caller must have ``role``'s admin role. + * + * May emit a {RoleGranted} event. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); @@ -151,6 +153,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 { * Requirements: * * - the caller must have ``role``'s admin role. + * + * May emit a {RoleRevoked} event. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); @@ -169,6 +173,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 { * Requirements: * * - the caller must be `account`. + * + * May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), ""AccessControl: can only renounce roles for self""); @@ -183,6 +189,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 { * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * + * May emit a {RoleGranted} event. + * * [WARNING] * ==== * This function should only be called from the constructor when setting @@ -213,6 +221,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 { * @dev Grants `role` to `account`. * * Internal function without access restriction. + * + * May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { @@ -225,6 +235,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 { * @dev Revokes `role` from `account`. * * Internal function without access restriction. + * + * May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { ",0 "diff --git a/contracts/token/ERC20/extensions/ERC4626.sol b/contracts/token/ERC20/extensions/ERC4626.sol @@ -16,6 +16,10 @@ import ""../../../utils/math/Math.sol""; * the ERC20 standard. Any additional extensions included along it would affect the ""shares"" token represented by this * contract and not the ""assets"" token which is an independent contract. * + * CAUTION: Deposits and withdrawals may incur unexpected slippage. Users should verify that the amount received of + * shares or assets is as expected. EOAs should operate through a wrapper that performs these checks such as + * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router]. + * * _Available since v4.7._ */ abstract contract ERC4626 is ERC20, IERC4626 { ",0 "diff --git a/README.md b/README.md [![Docs](https://img.shields.io/badge/docs-%F0%9F%93%84-blue)](https://docs.openzeppelin.com/contracts) [![NPM Package](https://img.shields.io/npm/v/@openzeppelin/contracts.svg)](https://www.npmjs.org/package/@openzeppelin/contracts) [![Coverage Status](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts/graph/badge.svg)](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts) +[![gitpoap badge](https://public-api.gitpoap.io/v1/repo/OpenZeppelin/openzeppelin-contracts/badge)](https://www.gitpoap.io/gh/OpenZeppelin/openzeppelin-contracts) **A library for secure smart contract development.** Build on a solid foundation of community-vetted code. ",0 "diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml @@ -13,6 +13,19 @@ concurrency: cancel-in-progress: true jobs: + changelog: + if: github.event_name == 'pull_request' && github.repository != 'OpenZeppelin/openzeppelin-contracts-upgradeable' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Check diff + run: | + git fetch origin ${{ github.base_ref }} --depth=1 + if git diff --exit-code origin/${{ github.base_ref }} -- CHANGELOG.md ; then + echo 'Missing changelog entry' + exit 1 + fi + lint: if: github.repository != 'OpenZeppelin/openzeppelin-contracts-upgradeable' runs-on: ubuntu-latest ",0 "diff --git a/docs/modules/ROOT/pages/extending-contracts.adoc b/docs/modules/ROOT/pages/extending-contracts.adoc @@ -129,3 +129,8 @@ contract MyToken is ERC20 { ``` That's it! Enjoy simpler code using hooks! +== Security + +The maintainers of OpenZeppelin Contracts are mainly concerned with the correctness and security of the code as published in the library, and the combinations of base contracts with the official extensions from the library. + +Custom overrides, and those of hooks in particular, may break some important assumptions and introduce vulnerabilities in otherwise secure code. While we try to ensure the contracts remain secure in the face of a wide range of potential customizations, this is done in a best-effort manner. Similarly, while we try to document all important assumptions, this should not be relied upon. Custom overrides should be carefully reviewed and checked against the source code of the contract they are customizing so as to fully understand their impact and guarantee their security. ",0 "diff --git a/contracts/utils/Arrays.sol b/contracts/utils/Arrays.sol @@ -56,6 +56,9 @@ library Arrays { */ function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) { bytes32 slot; + // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` + // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. + /// @solidity memory-safe-assembly assembly { mstore(0, arr.slot) @@ -71,6 +74,9 @@ library Arrays { */ function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) { bytes32 slot; + // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` + // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. + /// @solidity memory-safe-assembly assembly { mstore(0, arr.slot) @@ -86,6 +92,9 @@ library Arrays { */ function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) { bytes32 slot; + // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` + // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. + /// @solidity memory-safe-assembly assembly { mstore(0, arr.slot) ",0 "diff --git a/test/token/ERC1155/extensions/ERC1155URIStorage.test.js b/test/token/ERC1155/extensions/ERC1155URIStorage.test.js @@ -17,7 +17,7 @@ contract(['ERC1155URIStorage'], function (accounts) { describe('with base uri set', function () { beforeEach(async function () { this.token = await ERC1155URIStorageMock.new(erc1155Uri); - this.token.setBaseURI(baseUri); + await this.token.setBaseURI(baseUri); await this.token.mint(holder, tokenId, amount, '0x'); }); ",0 "diff --git a/test/token/ERC20/extensions/ERC4626.t.sol b/test/token/ERC20/extensions/ERC4626.t.sol @@ -3,6 +3,7 @@ pragma solidity ^0.8.0; import ""erc4626-tests/ERC4626.test.sol""; +import {SafeCast} from ""../../../../contracts/utils/math/SafeCast.sol""; import {ERC20Mock} from ""../../../../contracts/mocks/ERC20Mock.sol""; import {ERC4626Mock, IERC20Metadata} from ""../../../../contracts/mocks/ERC4626Mock.sol""; @@ -14,4 +15,22 @@ contract ERC4626StdTest is ERC4626Test { _vaultMayBeEmpty = false; _unlimitedAmount = true; } + + // solhint-disable-next-line func-name-mixedcase + function test_RT_mint_withdraw(ERC4626Test.Init memory init, uint256 shares) public override { + // There is an edge case where we currently behave different than the property tests, + // when all assets are lost to negative yield. + + // Sum all initially deposited assets. + int256 initAssets = 0; + for (uint256 i = 0; i < init.share.length; i++) { + vm.assume(init.share[i] <= uint256(type(int256).max - initAssets)); + initAssets += SafeCast.toInt256(init.share[i]); + } + + // Reject tests where the yield loses all assets from the vault. + vm.assume(init.yield > -initAssets); + + super.test_RT_mint_withdraw(init, shares); + } } ",0 "diff --git a/contracts/utils/Address.sol b/contracts/utils/Address.sol @@ -22,6 +22,10 @@ library Address { * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed + * + * Furthermore, `isContract` will also return true if the target contract within + * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, + * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] ",0 "diff --git a/renovate.json b/renovate.json { - ""extends"": [ - ""github>OpenZeppelin/configs"" - ], - ""packageRules"": [ - { - ""extends"": [""packages:eslint""], - ""enabled"": false - } - ] + ""extends"": [""github>OpenZeppelin/configs""], + ""labels"": [""ignore-changelog""] } ",0 "diff --git a/docs/modules/ROOT/pages/extending-contracts.adoc b/docs/modules/ROOT/pages/extending-contracts.adoc @@ -126,4 +126,6 @@ That's it! Enjoy simpler code using hooks! The maintainers of OpenZeppelin Contracts are mainly concerned with the correctness and security of the code as published in the library, and the combinations of base contracts with the official extensions from the library. -Custom overrides, and those of hooks in particular, may break some important assumptions and introduce vulnerabilities in otherwise secure code. While we try to ensure the contracts remain secure in the face of a wide range of potential customizations, this is done in a best-effort manner. Similarly, while we try to document all important assumptions, this should not be relied upon. Custom overrides should be carefully reviewed and checked against the source code of the contract they are customizing so as to fully understand their impact and guarantee their security. +Custom overrides, and those of hooks in particular, may break some important assumptions and introduce vulnerabilities in otherwise secure code. While we try to ensure the contracts remain secure in the face of a wide range of potential customizations, this is done in a best-effort manner. While we try to document all important assumptions, this should not be relied upon. Custom overrides should be carefully reviewed and checked against the source code of the contract they are customizing so as to fully understand their impact and guarantee their security. + +The way functions interact internally should not be assumed to stay stable across releases of the library. For example, a function that is used in one context in a particular release may not be used in the same context in the next release. Contracts that override functions should revalidate their assumptions when updating the version of OpenZeppelin Contracts they are built on. ",0 "diff --git a/GUIDELINES.md b/GUIDELINES.md @@ -62,6 +62,20 @@ Some other examples of automation are: - Looking for common security vulnerabilities or errors in our code (eg. reentrancy analysis). - Keeping dependencies up to date and monitoring for vulnerable dependencies. +## Pull requests + +Pull requests are squash-merged to keep the `master` branch history clean. The title of the pull request becomes the commit message, so it should be written in a consistent format: + +1) Begin with a capital letter. +2) Do not end with a period. +3) Write in the imperative: ""Add feature X"" and not ""Adds feature X"" or ""Added feature X"". + +This repository does not follow conventional commits, so do not prefix the title with ""fix:"" or ""feat:"". + +Work in progress pull requests should be submitted as Drafts and should not be prefixed with ""WIP:"". + +Branch names don't matter, and commit messages within a pull request mostly don't matter either, although they can help the review process. + # Solidity Conventions In addition to the official Solidity Style Guide we have a number of other conventions that must be followed. ",0 "diff --git a/src/fetch/fetch.js b/src/fetch/fetch.js @@ -115,3 +115,18 @@ export function syncCatalog(catalogId) { if (!catalogId) return Promise.reject(new Error('catalogId is required')) return superRequest(`https://inspire.data.gouv.fr/api/geogw/services/${catalogId}/sync`, 'POST') } + +export function dissociateProducer(producerId, organizationId) { + if (!producerId && organizationId) return Promise.reject(new Error('producerId and organizationId is required')) + const url = `https://inspire.data.gouv.fr/dgv/api/organizations/${organizationId}/producers/${producerId}` + + return superRequest(url, 'DELETE') +} + +export function associateProducer(producerId, organizationId) { + if (!producerId && organizationId) return Promise.reject(new Error('producerId and organizationId is required')) + const url = `https://inspire.data.gouv.fr/dgv/api/organizations/${organizationId}/producers` + const params = { '_id': producerId, 'associatedTo': organizationId } + + return superRequest(url, 'POST', params) +} ",0 "diff --git a/src/modules/Datasets/components/DatasetTable/DatasetTable.css b/src/modules/Datasets/components/DatasetTable/DatasetTable.css +@import ""../../../../theme/colors""; + .table table { margin: 10px; } .table th, .table td { text-align: center; - padding: 5px; + padding: 7px; } /* PAGINATION */ .table a { padding: 10px; - background-color: #fff; - margin: 8px; } .table a.reactable-current-page { - background-color: #d0ebf5; + color: #fff; + background-color: var(--blue); +} + +.table a:hover { + color: #fff; + background-color: var(--blue); } ",0 "diff --git a/src/modules/Datasets/components/Datasets/Datasets.js b/src/modules/Datasets/components/Datasets/Datasets.js @@ -77,6 +77,8 @@ class Datasets extends Component { const page = (offset / limit) + 1 const changes = { page, offset } + window.scrollTo(0, 0); + this.setState(changes, () => { this.search(changes) }) ",0 "diff --git a/src/modules/Publication/components/Layout/Layout.js b/src/modules/Publication/components/Layout/Layout.js @@ -9,6 +9,7 @@ import styles from './Layout.css' function Layout({ user, organization, pageTitle, title, children }) { if (!user) return null + const organizationLogo = !organization.logo ? organization.logo : 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Pas_d\'image_disponible.svg/200px-Pas_d\'image_disponible.svg.png' return ( @@ -16,7 +17,7 @@ function Layout({ user, organization, pageTitle, title, children }) { {organization ? - + : null } ",0 "diff --git a/src/modules/Datasets/components/DatasetSection/__test__/DatasetSection.test.js b/src/modules/Datasets/components/DatasetSection/__test__/DatasetSection.test.js @@ -35,6 +35,10 @@ describe('', () => { it('should display lineage', () => { expect(wrapper.contains(datasetMock.metadata.lineage)).to.be.true }) + + it('should display purpose', () => { + expect(wrapper.contains(datasetMock.metadata.purpose)).to.be.true + }) }) describe('When metadata are undefined', () => { ",0 "diff --git a/src/modules/Events/pages/Events/Events.js b/src/modules/Events/pages/Events/Events.js @@ -8,9 +8,9 @@ import PastEvent from '../../../../components/Event/PastEvent' import { events, eventsList, pastEventsList } from './Events.css' const pastEvents = [ - {name: 'Atelier #1', date: '06/10/2016', link: 'https://github.com/sgmap/inspire/files/838072/1489399578890.pdf'}, - {name: 'Atelier #3', date: '09/02/2017', link: 'https://github.com/sgmap/inspire/files/838076/Synthese.atelier.3.pdf'}, - {name: 'Atelier #4', date: '09/03/2017', link: ''}, + {name: 'Atelier #1', date: '06/10/2016', link: '/assets/ateliers/synthese_atelier_1.pdf'}, + {name: 'Atelier #3', date: '09/02/2017', link: '/assets/ateliers/synthese_atelier_3.pdf'}, + {name: 'Atelier #4', date: '09/03/2017', link: '/assets/ateliers/synthese_atelier_4.pdf'}, ] const Events = () => { ",0 "diff --git a/src/routes/Search/components/SearchPage/SearchPage.js b/src/routes/Search/components/SearchPage/SearchPage.js import React from 'react' +import PropTypes from 'prop-types' import DocumentTitle from 'react-document-title' import { unionWith, isEqual } from 'lodash' @@ -11,7 +12,28 @@ import SearchResults from '../SearchResults' import styles from './SearchPage.scss' -class SearchPage extends React.Component { +class SearchPage extends React.PureComponent { + static propTypes = { + query: PropTypes.shape({ + textInput: PropTypes.string, + page: PropTypes.number.isRequired, + filters: PropTypes.array.isRequired + }).isRequired, + + search: PropTypes.shape({ + pending: PropTypes.bool.isRequired, + error: PropTypes.oneOfType([ + PropTypes.object, + PropTypes.bool + ]).isRequired, + query: PropTypes.object.isRequired, + results: PropTypes.array.isRequired, + facets: PropTypes.object.isRequired + }).isRequired, + + update: PropTypes.func.isRequired + } + addFilter = filter => { const { update, query } = this.props ",0 "diff --git a/src/routes/Dataset/components/DatasetView/DatasetView.js b/src/routes/Dataset/components/DatasetView/DatasetView.js @@ -102,6 +102,14 @@ class DatasetView extends React.PureComponent { + + {dataset.metadata.credit && ( + +
+ {dataset.metadata.credit} +
+
+ )} ",0 "diff --git a/build/webpack.config.js b/build/webpack.config.js @@ -224,7 +224,13 @@ if (!__TEST__) { bundles.unshift('vendor') config.entry.vendor = project.vendors } + config.plugins.push(new webpack.optimize.CommonsChunkPlugin({ names: bundles })) + config.plugins.push(new webpack.optimize.CommonsChunkPlugin({ + name: 'app', + async: 'common', + minChunks: 2 + })) } // Production Optimizations ",0 "diff --git a/.circleci/config.yml b/.circleci/config.yml @@ -80,6 +80,7 @@ jobs: path: reports/tests/ - store_artifacts: + name: Store coverage artifacts path: coverage/ - run: @@ -109,6 +110,7 @@ jobs: - reports/ - store_artifacts: + name: Store build report artifacts path: reports/ - persist_to_workspace: ",0 "diff --git a/package.json b/package.json ""compile"": ""node build/scripts/compile"", ""build"": ""npm run clean && cross-env NODE_ENV=production npm run compile"", ""test"": ""cross-env NODE_ENV=test mocha -r build/tests/bootstrap.js -r ignore-styles src/**/*.test.js"", - ""test:ci"": ""cross-env NODE_ENV=test MOCHA_FILE=reports/tests/results.xml nyc mocha -r build/tests/bootstrap.js -r ignore-styles --reporter mocha-circleci-reporter src/**/*.test.js"", + ""test:ci"": ""cross-env NODE_ENV=test MOCHA_FILE=reports/tests/geodatagouv/results.xml nyc mocha -r build/tests/bootstrap.js -r ignore-styles --reporter mocha-circleci-reporter src/**/*.test.js"", ""codecov"": ""codecov -f coverage/coverage-final.json"", ""deploy"": ""gh-pages -d dist"", ""lint"": ""npm run lint:scripts && npm run lint:styles"", ",0 "diff --git a/src/routes/Dataset/components/DatasetDownloadList/DatasetDownloadList.js b/src/routes/Dataset/components/DatasetDownloadList/DatasetDownloadList.js @@ -19,6 +19,8 @@ class DatasetDownloadList extends React.PureComponent { t: PropTypes.func.isRequired } + state = {} + setPreview = ({ distribution, link }) => { const { fetchGeoJson } = this.props ",0 "diff --git a/.circleci/config.yml b/.circleci/config.yml @@ -140,6 +140,14 @@ jobs: name: Setup SSH to GitHub command: mkdir ~/.ssh && ssh-keyscan github.com > ~/.ssh/known_hosts + - run: + name: Set SSH user email + command: git config --global user.email ""infra@beta.gouv.fr"" + + - run: + name: Set SSH user name + command: git config --global user.name ""Deployment Bot"" + - deploy: name: Deploy to gh-pages branch on GitHub command: yarn deploy ",0 "diff --git a/.gitignore b/.gitignore @@ -8,6 +8,7 @@ pids logs *.log npm-debug.log* +CHANGELOG.md # Mac *.DS_Store ",0 "diff --git a/pages/_error.js b/pages/_error.js @@ -30,7 +30,7 @@ class ErrorPage extends React.Component { - +
{statusCode ?

{statusCode}

: null}

{message}

@@ -43,7 +43,7 @@ class ErrorPage extends React.Component { flex: 1; align-items: center; justify-content: center; - margin: 5em 0 3em; + margin: 7em 0 2em; } h1 { ",0 "diff --git a/components/catalog-preview.js b/components/catalog-preview.js import React from 'react' import PropTypes from 'prop-types' +import moment from 'moment' import { translate } from 'react-i18next' import { get } from 'lodash' @@ -8,7 +9,11 @@ import HarvestStatus from './harvest-status' import Counter from './counter' import Percent from './percent' -// import ObsoleteWarning from './ObsoleteWarning' +const isObsolete = (catalog) => { + const revisionDate = get(catalog, 'metrics.mostRecentRevisionDate') + + return revisionDate && moment().subtract(6, 'months').isAfter(revisionDate) +} export const CatalogPreview = ({ catalog, t }) => { let metrics = catalog.metrics @@ -18,11 +23,20 @@ export const CatalogPreview = ({ catalog, t }) => { return ( -
+
+ {isObsolete(catalog) && ( + {t('components.ObsoleteWarning.obsoleteCatalog')} + )} + + {catalog.name} +
- {/* */}
{!metrics ?
{t('components.CatalogPreview.noData')}
: ( @@ -52,7 +66,7 @@ export const CatalogPreview = ({ catalog, t }) => { a { display: block; - padding: 1.4em 2em; + padding: 16px 22px; text-align: left; position: relative; width: 360px; @@ -67,6 +81,13 @@ export const CatalogPreview = ({ catalog, t }) => { } } + img { + height: 23px; + display: inline-block; + vertical-align: bottom; + margin-right: 5px; + } + .title { font-size: 1.4em; line-height: 1.2em; ",0 "diff --git a/pages/_error.js b/pages/_error.js @@ -9,7 +9,7 @@ import Content from '../components/content' class ErrorPage extends React.Component { static propTypes = { - statusCode: PropTypes.number.isRequired, + code: PropTypes.number, i18n: PropTypes.shape({ exists: PropTypes.func.isRequired }).isRequired, @@ -17,22 +17,23 @@ class ErrorPage extends React.Component { } static getInitialProps ({ res, err }) { - const statusCode = res ? res.statusCode : (err ? err.statusCode : null) - return { statusCode } + const code = res ? res.statusCode : (err ? err.statusCode : null) + + return { code } } render() { - const { statusCode, i18n, t } = this.props + const { code, i18n, t } = this.props - const message = i18n.exists(`errors.${statusCode}`) ? t(`errors.${statusCode}`) : t('errors.unknown') + const message = i18n.exists(`errors.${code}`) ? t(`errors.${code}`) : t('errors.unknown') return ( - +
- {statusCode ?

{statusCode}

: null} +

{t('errors.title', { code })}

{message}

",0 "diff --git a/components/facet.js b/components/facet.js @@ -9,10 +9,10 @@ const Facet = ({ facet, count, detailed, remove, onClick, t, i18n }) => { return (
onClick(facet))}> - {detailed && {title}} - {value} + {detailed &&
{title}
} +
{value}
- {count && × {count}} + {count &&
× {count}
}
",0 "diff --git a/pages/search.js b/pages/search.js @@ -65,7 +65,7 @@ class SearchPage extends React.Component {
-
+
@@ -84,6 +84,10 @@ class SearchPage extends React.Component { display: flex; } + .search { + flex: 1; + } + .facets { margin-left: 2em; flex-basis: 300px; ",0 "diff --git a/components/search/facets.js b/components/search/facets.js @@ -84,7 +84,7 @@ class Facets extends React.Component { right: 0; background: #fff; box-shadow: -2px 0 2px rgba(0, 0, 0, 0.2); - padding: 1em 1em 1em 1.5em; + padding: 2em 1em 2em 1.5em; } } ",0 "diff --git a/components/catalog/statistics.js b/components/catalog/statistics.js @@ -26,24 +26,6 @@ const Statistics = ({ metrics, t }) => { />
-
-

- {t('details.statistics.recordTypeChart')} -

-
- -
-
- -
-

- {t('details.statistics.metadataTypeChart')} -

-
- -
-
-

{t('details.statistics.openDataPercent')} @@ -66,6 +48,24 @@ const Statistics = ({ metrics, t }) => { />

+
+

+ {t('details.statistics.recordTypeChart')} +

+
+ +
+
+ +
+

+ {t('details.statistics.metadataTypeChart')} +

+
+ +
+
+

{t('details.statistics.dataTypeChart')} @@ -82,10 +82,6 @@ const Statistics = ({ metrics, t }) => { display: flex; flex-wrap: wrap; margin: 1em -0.6em 0 -0.6em; - - @media (max-width: 551px) { - flex-direction: column; - } } .block { @@ -94,13 +90,21 @@ const Statistics = ({ metrics, t }) => { justify-content: center; flex-direction: column; height: 200px; - border: 1px solid $lightgrey; padding: 2em; + border: 1px solid $lightgrey; border-radius: 2px; margin: 0 0.6em 1em 0.6em; - flex: 1 1 31%; text-align: center; max-width: calc(100% - 1.2em); + width: calc(33.33% - 1.2em); + + @media (max-width: 960px) { + width: calc(50% - 1.2em); + } + + @media (max-width: 768px) { + width: calc(100% - 1.2em); + } div { display: flex; ",0 "diff --git a/components/catalog/harvests/table.js b/components/catalog/harvests/table.js @@ -75,7 +75,12 @@ Table.propTypes = { })).isRequired, catalog: PropTypes.shape({ - _id: PropTypes.string.isRequired + _id: PropTypes.string.isRequired, + service: PropTypes.shape({ + sync: PropTypes.shape({ + pending: PropTypes.bool.isRequired + }).isRequired + }).isRequired }).isRequired, t: PropTypes.func.isRequired ",0 "diff --git a/pages/_error.js b/pages/_error.js @@ -6,6 +6,7 @@ import withI18n from '../components/hoc/with-i18n' import Page from '../components/page' import Meta from '../components/meta' import Content from '../components/content' +import Box from '../components/box' class ErrorPage extends React.Component { static propTypes = { @@ -33,8 +34,12 @@ class ErrorPage extends React.Component {
+ +

{t('errors.title', { code })}

{message}

+
+
@@ -51,6 +56,15 @@ class ErrorPage extends React.Component { } } + section { + padding: 10px; + + @media (min-width: 552px) { + display: flex; + align-items: center; + } + } + h1 { font-size: 24px; fontWeight: 500; ",0 "diff --git a/components/page/footer/index.js b/components/page/footer/index.js @@ -11,7 +11,7 @@ const Footer = ({ t }) => (
- + Etalab
",0 "diff --git a/components/dataset/downloads/dataset-download.js b/components/dataset/downloads/dataset-download.js @@ -5,6 +5,7 @@ import strRightBack from 'underscore.string/strRightBack' import DownloadIcon from 'react-icons/lib/fa/download' import PreviewIcon from 'react-icons/lib/fa/eye' +import FailIcon from 'react-icons/lib/fa/close' import formats from '../../../lib/formats' @@ -27,54 +28,89 @@ export const DatasetDownload = ({ distribution, t }) => { const name = layerName || distribution.typeName return ( -
-
{name}
+
{distribution.available ? ( -
+
+
+
+ +
+
+ {name} {formats.map(format => ( -
+
))} - +
+
- ) : t('downloads.unavailable')} + ) : ( +
+
+ +
+
+ {name} + {t('downloads.unavailable')} +
+
+ )}
) ",0 "diff --git a/locales/en/common.json b/locales/en/common.json ""enums"": { ""dataTypes"": { - ""dataset"": ""dataset"" + ""dataset"": ""dataset"", + ""nonGeographicDataset"": ""non-geographic dataset"" }, ""frequencies"": { ",0 "diff --git a/components/content.js b/components/content.js @@ -2,7 +2,7 @@ import React from 'react' import PropTypes from 'prop-types' const Content = ({ children, clouds }) => ( -
+
{children}
",0 "diff --git a/components/dataset/downloads/preview.js b/components/dataset/downloads/preview.js @@ -3,9 +3,13 @@ import PropTypes from 'prop-types' import dynamic from 'next/dynamic' import { translate } from 'react-i18next' +import MapIcon from 'react-icons/lib/fa/map' +import TableIcon from 'react-icons/lib/fa/table' + import { _get } from '../../../lib/fetch' import Modal from '../../modal' +import Button from '../../button' const CenteredMap = dynamic(import('../../centered-map'), { ssr: false, @@ -22,7 +26,8 @@ class Preview extends React.Component { state = { loading: true, - data: null + data: null, + view: 'map' } async componentDidMount() { @@ -36,15 +41,38 @@ class Preview extends React.Component { })) } + changeView = view => () => { + this.setState(() => ({ + view + })) + } + render() { const { onClose, t } = this.props - const { loading, data } = this.state + const { loading, data, view } = this.state return ( {loading ? t('common:loading') : (
+
+ + +
+ {view === 'map' ? (
+ ) : ( + 'table' + )}
)} @@ -74,6 +105,13 @@ class Preview extends React.Component { height: 100%; width: 100%; } + + .actions { + :global(button) { + margin-right: 7px; + margin-bottom: 10px; + } + } `}
) ",0 "diff --git a/pages/dataset.js b/pages/dataset.js @@ -35,7 +35,9 @@ class DatasetPage extends React.Component { metadata: PropTypes.shape({ id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, - thumbnails: PropTypes.array, + thumbnails: PropTypes.arrayOf(PropTypes.shape({ + originalUrlHash: PropTypes.string.isRequired + })), spatialExtent: PropTypes.object, equivalentScaleDenominator: PropTypes.number, spatialResolution: PropTypes.object, @@ -109,7 +111,13 @@ class DatasetPage extends React.Component { return ( - + `${GEODATA_API_URL}/records/${recordId}/thumbnails/${thumbnail.originalUrlHash}` + )} + /> ",0 "diff --git a/components/dataset/downloads/preview.js b/components/dataset/downloads/preview.js @@ -38,12 +38,19 @@ class Preview extends React.Component { async componentDidMount() { const { link } = this.props + try { const data = await _get(`${link}?format=GeoJSON&projection=WGS84`) - this.setState(() => ({ + this.setState({ loading: false, data - })) + }) + } catch (error) { + this.setState({ + loading: false, + error + }) + } } changeView = view => () => { @@ -54,7 +61,7 @@ class Preview extends React.Component { render() { const { onClose, t } = this.props - const { loading, data, view } = this.state + const { loading, data, view, error } = this.state return ( @@ -76,6 +83,8 @@ class Preview extends React.Component {
+ + {error ? {t('preview.errors.download')} : (
{view === 'map' ? (
@@ -90,16 +99,23 @@ class Preview extends React.Component { )}
+ )}
)}
@@ -58,7 +94,13 @@ Header.propTypes = { first_name: PropTypes.string.isRequired, last_name: PropTypes.string.isRequired, email: PropTypes.string.isRequired - }).isRequired + }).isRequired, + + organization:PropTypes.shape({ + id: PropTypes.string.isRequired, + name: PropTypes.string.isRequired, + logo_thumbnail: PropTypes.string + }) } export default Header ",0 "diff --git a/pages/publication/organization.js b/pages/publication/organization.js @@ -71,11 +71,11 @@ class PublicationPage extends React.Component {
) ",0 "diff --git a/pages/publication/producers.js b/pages/publication/producers.js @@ -16,7 +16,6 @@ import RequireAuth from '../../components/require-auth' import Header from '../../components/publication/header' import Breadcrumbs from '../../components/publication/breadcrumbs' - import Producers from '../../components/publication/producers' import { PUBLICATION_BASE_URL } from '@env' ",0 "diff --git a/pages/_document.js b/pages/_document.js @@ -15,7 +15,7 @@ export default class MyDocument extends Document {
- ``` -It's also possible to manually initialize each component you want to use individually: +It's also possible to manually initialize each individual component: ```js $('#my-button').button(); ",1 "diff --git a/src/components/wizard/wizard.js b/src/components/wizard/wizard.js @@ -251,7 +251,7 @@ Wizard.prototype = { * Fires before a step is activated/pressed. You can cancel selection by returning a 'beforeactivate' * handler as 'false' * @event beforeactivate - * @memberof Datagrid + * @memberof Wizard * @property {object} event - The jquery event object * @property {HTMLElement} tick - The tick (link) that was activated. */ @@ -272,7 +272,7 @@ Wizard.prototype = { * Fires while a step is activated/pressed. * handler as 'false' * @event activated - * @memberof Datagrid + * @memberof Wizard * @property {object} event - The jquery event object * @property {HTMLElement} tick - The tick (link) that was activated. */ @@ -281,8 +281,8 @@ Wizard.prototype = { /** * Fires after a step is activated/pressed. And the new Dom is loaded. * handler as 'false' - * @event activated - * @memberof Datagrid + * @event afteractivated + * @memberof Wizard * @property {object} event - The jquery event object * @property {HTMLElement} tick - The tick (link) that was activated. */ ",1 "diff --git a/src/components/dropdown/dropdown.js b/src/components/dropdown/dropdown.js @@ -978,7 +978,6 @@ Dropdown.prototype = { return; } - results.removeClass('hidden'); list.not(results).add(headers).addClass('hidden'); list.filter(results).each(function (i) { @@ -1012,10 +1011,12 @@ Dropdown.prototype = { term = ''; this.position(); + if (this.list.find('svg').length > 2) { + this.list.find('svg').last().changeIcon('icon-empty-circle'); + } + if (noIcons && this.list.find('input').css('padding-left')) { this.list.find('input').addClass('no-icon-padding'); - } else { - this.list.find('svg').last().changeIcon('icon-empty-circle'); } }, @@ -1070,6 +1071,10 @@ Dropdown.prototype = { lis.removeClass('hidden'); this.position(); + if (this.list.find('svg').length === 2) { + this.list.find('svg').last().remove(); + } + if (this.list.find('input').css('padding-left')) { this.list.find('input').addClass('no-icon-padding'); } ",1 "diff --git a/test/components/bar/bar-stacked.e2e-spec.js b/test/components/bar/bar-stacked.e2e-spec.js @@ -55,14 +55,14 @@ describe('Stacked Bar Chart example-colors', () => { await utils.checkForErrors(); }); - it('Should first bar is green', async () => { + it('Should detect that first bar is green', async () => { const fGroupEl = await element.all(by.css('.series-group')).get(0); const barEl = await fGroupEl.element(by.css('.bar.series-0')); expect(await barEl.getCssValue('fill')).toBe('rgb(142, 209, 198)'); }); - it('Should second bar is violet', async () => { + it('Should detect that second bar is violet', async () => { const sGroupEl = await element.all(by.css('.series-group')).get(1); const barEl = await sGroupEl.element(by.css('.bar.series-0')); ",1 "diff --git a/src/components/dropdown/dropdown.js b/src/components/dropdown/dropdown.js @@ -1057,7 +1057,15 @@ Dropdown.prototype = { const li = $(this); const text = a.text(); - const icon = (li.children('a').find('svg').length !== 0) ? li.children('a').find('svg')[0].outerHTML : ''; + let icon = ''; + + if (li.children('a').find('svg').length !== 0) { + if (li.children('a').find('svg')[0].outerHTML) { + icon = li.children('a').find('svg')[0].outerHTML; + } else { + icon = new XMLSerializer().serializeToString(li.children('a').find('svg')[0]); + } + } if (icon) { hasIcons = true; ",1 "diff --git a/src/components/colorpicker/colorpicker.js b/src/components/colorpicker/colorpicker.js @@ -115,7 +115,8 @@ const COLORPICKER_DEFAULTS = { { label: 'Azure', number: '05', value: '4EA0D1' }, { label: 'Azure', number: '04', value: '69B5DD' }, { label: 'Azure', number: '03', value: '8DC9E6' }, - { label: 'Azure', number: '02', value: 'ADD8EB' } + { label: 'Azure', number: '02', value: 'ADD8EB' }, + { label: 'Azure', number: '01', value: 'C8E9F4' } ], placeIn: null, // null|'editor' showLabel: false, @@ -540,10 +541,6 @@ ColorPicker.prototype = { const a = $(``).appendTo(li); a.data('label', s.clearableText).data('value', '').tooltip(); menu.append(li); - } else if (!this.settings.customColors) { - const li = $('
  • '); - $('
    ').appendTo(li).tooltip(); - menu.append(li); } $('body').append(menu); ",1 "diff --git a/src/components/bar/bar.js b/src/components/bar/bar.js @@ -647,6 +647,11 @@ Bar.prototype = { * @private */ setTextValues() { + if (this.settings.isGrouped) { + // These are TODO, as you need a different structure since its using the group name + return; + } + const elems = document.querySelectorAll('.bar-chart .axis.y .tick text'); const dataset = this.settings.dataset; for (let i = 0; i < dataset.length; i++) { ",1 "diff --git a/src/components/searchfield/_searchfield.scss b/src/components/searchfield/_searchfield.scss @@ -86,6 +86,7 @@ $cubic-bezier-ease: cubic-bezier(0.17, 0.04, 0.03, 0.94); border-left: 0; border-right: 0; border-top: 0; + height: 33px; padding-left: 32px; width: 100%; ",1 "diff --git a/test/components/listview/listview.e2e-spec.js b/test/components/listview/listview.e2e-spec.js @@ -52,14 +52,14 @@ describe('Listview example-singleselect tests', () => { it('Should deselect one item on click', async () => { const listviewItemEl = await element(by.css('li[aria-posinset=""1""]')); - listviewItemEl.click(); + await listviewItemEl.click(); await browser.driver .wait(protractor.ExpectedConditions.presenceOf(element(by.css('li[aria-selected=""true""].is-selected'))), config.waitsFor); expect(await element(by.css('li[aria-selected=""true""]')).isPresent()).toBeTruthy(); expect(await element(by.className('selection-count')).getText()).toContain('1 Selected'); - listviewItemEl.click(); + await listviewItemEl.click(); await browser.driver .wait(protractor.ExpectedConditions.presenceOf(element(by.css('li[aria-selected=""false""]'))), config.waitsFor); ",1 "diff --git a/src/components/tabs/tabs.js b/src/components/tabs/tabs.js @@ -3235,7 +3235,17 @@ Tabs.prototype = { e.preventDefault(); e.stopPropagation(); + + if (li.is('.dismissible') && li.is('.has-popupmenu') && li.is('.submenu')) { + const listMenu = li.find('.wrapper').children().children(); + const hrefs = []; + $.each(listMenu, (i, item) => { + hrefs.push(item.children[0].href); + }); + self.closeDismissibleTabs(hrefs); + } else { self.closeDismissibleTab(li.children('a').attr('href')); + } self.popupmenu.close(); } ",1 "diff --git a/test/components/datepicker/datepicker.e2e-spec.js b/test/components/datepicker/datepicker.e2e-spec.js @@ -640,6 +640,7 @@ describe('Datepicker Timeformat Tests', () => { const todayEl = await element(by.css('button.is-today')); const testDate = new Date(); await todayEl.click(); + const value = await element(by.id('dp3')).getAttribute('value'); let hours = testDate.getHours(); const minutes = testDate.getMinutes(); @@ -651,10 +652,12 @@ describe('Datepicker Timeformat Tests', () => { } expect([ + `${(testDate.getMonth() + 1)}/${testDate.getDate()}/${testDate.getFullYear()} ${hours}:${(minutes - 2).toString().padStart(2, '0')} ${amPm}`, + `${(testDate.getMonth() + 1)}/${testDate.getDate()}/${testDate.getFullYear()} ${hours}:${(minutes - 1).toString().padStart(2, '0')} ${amPm}`, `${(testDate.getMonth() + 1)}/${testDate.getDate()}/${testDate.getFullYear()} ${hours}:${(minutes).toString().padStart(2, '0')} ${amPm}`, `${(testDate.getMonth() + 1)}/${testDate.getDate()}/${testDate.getFullYear()} ${hours}:${(minutes + 1).toString().padStart(2, '0')} ${amPm}`, `${(testDate.getMonth() + 1)}/${testDate.getDate()}/${testDate.getFullYear()} ${hours}:${(minutes + 2).toString().padStart(2, '0')} ${amPm}` // for slow test on ci - ]).toContain(await element(by.id('dp3')).getAttribute('value')); + ]).toContain(value); }); }); ",1 "diff --git a/test/components/tabs/tabs-api.func-spec.js b/test/components/tabs/tabs-api.func-spec.js @@ -289,11 +289,15 @@ describe('Tabs API', () => { expect(tab.length).toBeFalsy(); }); - it('Should select tab, and focus', () => { + it('Should select tab, and focus', (done) => { tabsObj.select('#tabs-normal-contracts'); expect(document.querySelector('.tab.is-selected').innerText).toEqual('Contracts'); + + setTimeout(() => { expect(parseInt(document.querySelector('.animated-bar').style.left, 10)).toBeCloseTo(0, 1); + done(); + }, 500); }); it('Should return false whether tabs are overflowed at 300px', () => { ",1 "diff --git a/test/components/datagrid/datagrid.e2e-spec.js b/test/components/datagrid/datagrid.e2e-spec.js @@ -1506,7 +1506,7 @@ describe('Datagrid timezone tests', () => { if (utils.isChrome() && utils.isCI()) { it('Should not visual regress', async () => { const containerEl = await element(by.className('container')); - await browser.driver.sleep(1500); + await browser.driver.sleep(400); expect(await browser.protractorImageComparison.checkElement(containerEl, 'datagrid-timezone')).toEqual(0); }); ",1 "diff --git a/test/components/datagrid/datagrid.e2e-spec.js b/test/components/datagrid/datagrid.e2e-spec.js @@ -1490,11 +1490,11 @@ describe('Datagrid select event tests', () => { }); }); -describe('Datagrid timezone tests', () => { +fdescribe('Datagrid timezone tests', () => { beforeEach(async () => { await utils.setPage('/components/datagrid/test-timezone-formats?layout=nofrills&locale=nl-NL'); - const datagridEl = await element(by.css('.datagrid tr:nth-child(10)')); + const datagridEl = await element(by.css('.datagrid tr:nth-child(5)')); await browser.driver .wait(protractor.ExpectedConditions.presenceOf(datagridEl), config.waitsFor); }); @@ -1506,7 +1506,6 @@ describe('Datagrid timezone tests', () => { if (utils.isChrome() && utils.isCI()) { it('Should not visual regress', async () => { const containerEl = await element(by.className('container')); - await browser.driver.sleep(400); expect(await browser.protractorImageComparison.checkElement(containerEl, 'datagrid-timezone')).toEqual(0); }); ",1 "diff --git a/src/components/form-compact/_form-compact.scss b/src/components/form-compact/_form-compact.scss font-weight: 700; } +// Specific paddings for non-Blink-based browsers (IE, FF) +.ie, +.is-firefox { + .form-compact { + .column, + .columns { + &.form-section-header { + padding: 16px 10px 15px; + } + + label { + padding: 6px 9px 0; + } + + input { + padding: 0 8px 6px; + } + } + } +} + // Ensures a common min-height on headers @media (max-width: $breakpoint-phone-to-tablet + 1) { .form-compact { ",1 "diff --git a/test/components/datagrid/datagrid.e2e-spec.js b/test/components/datagrid/datagrid.e2e-spec.js @@ -612,7 +612,7 @@ describe('Datagrid paging tests', () => { await element(by.css('.pager-count input')).clear(); await element(by.css('.pager-count input')).sendKeys('101'); await element(by.css('.pager-count input')).sendKeys(protractor.Key.ENTER); - await browser.driver.sleep(300); + await browser.driver.sleep(500); expect(await element(by.css('tbody tr:nth-child(1) td:nth-child(2) span')).getText()).toEqual('0'); expect(await element(by.css('tbody tr:nth-child(10) td:nth-child(2) span')).getText()).toEqual('9'); ",1 "diff --git a/test/components/datagrid/datagrid.e2e-spec.js b/test/components/datagrid/datagrid.e2e-spec.js @@ -1081,7 +1081,7 @@ describe('Datagrid disableRowDeactivation setting tests', () => { beforeEach(async () => { await utils.setPage('/components/datagrid/test-mixed-selection-disable-row-dectivation'); - const datagridEl = await element(by.id('datagrid-header')); + const datagridEl = await element(by.css('#datagrid-header .datagrid-body tbody tr:nth-child(1)')); await browser.driver .wait(protractor.ExpectedConditions.presenceOf(datagridEl), config.waitsFor); }); ",1 "diff --git a/test/components/datagrid/datagrid.e2e-spec.js b/test/components/datagrid/datagrid.e2e-spec.js @@ -394,7 +394,7 @@ describe('Datagrid index tests', () => { beforeEach(async () => { await utils.setPage('/components/datagrid/example-index?layout=nofrills'); - const datagridEl = await element(by.id('datagrid')); + const datagridEl = await element(by.css('#datagrid tbody tr:nth-child(1)')); await browser.driver .wait(protractor.ExpectedConditions.presenceOf(datagridEl), config.waitsFor); await element(by.css('body')).sendKeys(protractor.Key.TAB); ",1 "diff --git a/test/components/datepicker/datepicker.e2e-spec.js b/test/components/datepicker/datepicker.e2e-spec.js @@ -577,7 +577,7 @@ describe('Datepicker Timeformat Tests', () => { const dateVariances = [-2, -1, 0, 1, 2] .map(amt => testDate.setSeconds(testDate.getSeconds() + amt)); - expect(dateVariances).toEqual(new Date(value).getTime()); + expect(dateVariances).toContain(new Date(value).getTime()); }); }); ",1 "diff --git a/app/views/components/mask/test-number-mask-gauntlet.html b/app/views/components/mask/test-number-mask-gauntlet.html } }; - var localeString = Locale.currentLocale.name, + var thisLocale = Locale.currentLocale, + localeString = thisLocale.name, isLocalized = localeString !== 'en-US'; // default for the test suite // localize the label if (isLocalized) { - var number = Locale.parseNumber(numberSpan.text().toString()), + var spanText = numberSpan.text(); + var hasThousands = spanText.indexOf(thisLocale.data.numbers.group) !== -1; + var number = Locale.parseNumber(spanText.toString()), localizedLabelOpts = { group: thisOpts.patternOptions.symbols.thousands, decimal: thisOpts.patternOptions.symbols.decimal, minusSign: thisOpts.patternOptions.symbols.negative, minimumFractionDigits: 0 }; + if (!hasThousands) { + localizedLabelOpts.groupSizes = [0, 0]; + } if (thisOpts.patternOptions.decimalLimit) { localizedLabelOpts.maximumFractionDigits = thisOpts.patternOptions.decimalLimit; } ",1 "diff --git a/package.json b/package.json ""build"": ""node ./scripts/build"", ""build:custom"": ""node ./scripts/build"", ""build:icons"": ""node ./scripts/build-icons.js"", - ""clean"": ""npx grunt clean"", + ""clean"": ""rimraf temp && rimraf dist"", + ""clean:app"": ""rimraf app/dist"", ""stop"": ""./scripts/stop.sh"", ""watch"": ""npx grunt watch"", ""stylelint:demo"": ""npx stylelint 'app/src/**/*.scss'"", ""eslint:error-only"": ""npm run build:icons && npx eslint -c .eslintrc.js --quiet src test"", ""lint:ci"": ""npm run eslint:error-only && npm run mdlint && npm run stylelint"", ""minify"": ""node ./scripts/minify.js"", - ""minify:js"": ""node ./scripts/minify-js.js"", - ""minify:css"": ""node ./scripts/minify-css.js"", ""functional:local"": ""npx karma start test/karma.conf.js"", ""functional:ci"": ""npx karma start test/karma.conf.js --single-run"", ""e2e:ci"": ""npm run webdriver:update && npx protractor test/protractor.ci.conf.js"", ""pygmentize-bundled"": ""^2.3.0"", ""r2"": ""^2.0.1"", ""release-it"": ""^10.3.1"", + ""rimraf"": ""^2.6.3"", ""rollup"": ""^1.6.0"", ""rollup-plugin-analyzer"": ""^3.0.0"", ""rollup-plugin-babel"": ""^3.0.2"", ",1 "diff --git a/src/components/header/header.js b/src/components/header/header.js @@ -368,32 +368,34 @@ Header.prototype = { const self = this; this.element - .on('updated.header', (e, settings) => { + .on(`updated.${COMPONENT_NAME}`, (e, settings) => { self.updated(settings); }) - .on('reset.header', () => { + .on(`reset.${COMPONENT_NAME}`, () => { self.reset(); }) - .on('drilldown.header', (e, viewTitle) => { + .on(`drilldown.${COMPONENT_NAME}`, (e, viewTitle) => { self.drilldown(viewTitle); }) - .on('drillup.header', (e, viewTitle) => { + .on(`drillup.${COMPONENT_NAME}`, (e, viewTitle) => { self.drillup(viewTitle); }); // Events for the title button. e.preventDefault(); stops Application Menu // functionality while drilled - this.titleButton.bindFirst('click.header', (e) => { + if (this.titleButton && this.titleButton.length) { + this.titleButton.bindFirst(`click.${COMPONENT_NAME}`, (e) => { if (self.levelsDeep.length > 1) { e.stopImmediatePropagation(); self.drillup(); e.returnValue = false; } }); + } // Popupmenu Events - if (this.settings.usePopupmenu) { - this.titlePopup.on('selected.header', function (e, anchor) { + if (this.titlePopup && this.titlePopup.length) { + this.titlePopup.on(`selected.${COMPONENT_NAME}`, function (e, anchor) { $(this).children('h1').text(anchor.text()); }); } @@ -716,8 +718,21 @@ Header.prototype = { * @returns {this} component instance */ unbind() { - this.titleButton.off('click.header'); - this.element.off('drilldown.header drillup.header'); + if (this.titleButton && this.titleButton.length) { + this.titleButton.off(`click.${COMPONENT_NAME}`); + } + + if (this.titlePopup && this.titlePopup.length) { + this.titlePopup.off(`updated.${COMPONENT_NAME}`); + } + + this.element.off([ + `updated.${COMPONENT_NAME}`, + `reset.${COMPONENT_NAME}`, + `drilldown.${COMPONENT_NAME}`, + `drillup.${COMPONENT_NAME}`, + ].join(' ')); + return this; }, ",1 "diff --git a/test/components/locale/locale.func-spec.js b/test/components/locale/locale.func-spec.js @@ -1053,7 +1053,7 @@ describe('Locale API', () => { }); it('Should handle group size', () => { - Locale.set('en-US'); // 3, 0 + Locale.set('en-US'); // 3, 3 expect(Locale.formatNumber(-2.53, { style: 'percent', minimumFractionDigits: 2 })).toEqual('-253.00 %'); expect(Locale.formatNumber(1.1234)).toEqual('1.123'); @@ -1103,7 +1103,7 @@ describe('Locale API', () => { }); it('Should parse group size', () => { - Locale.set('en-US'); // 3, 0 + Locale.set('en-US'); // 3, 3 expect(Locale.parseNumber('-253.00 %')).toEqual(-253); expect(Locale.parseNumber('1.123')).toEqual(1.123); @@ -1153,7 +1153,7 @@ describe('Locale API', () => { }); it('Should be able to not show the group size', () => { - Locale.set('en-US'); // 3, 0 + Locale.set('en-US'); // 3, 3 expect(Locale.formatNumber(1234567.1234, { group: '' })).toEqual('1234567.123'); expect(Locale.formatNumber(12345678.1234, { group: '' })).toEqual('12345678.123'); @@ -1170,7 +1170,7 @@ describe('Locale API', () => { }); it('Should be able to set the group size', () => { - Locale.set('en-US'); // 3, 0 + Locale.set('en-US'); // 3, 3 expect(Locale.formatNumber(1234567.1234, { groupSizes: [3, 0] })).toEqual('1234,567.123'); expect(Locale.formatNumber(12345678.1234, { groupSizes: [3, 0] })).toEqual('12345,678.123'); @@ -1187,7 +1187,7 @@ describe('Locale API', () => { }); it('Should be able to set zero group size', () => { - Locale.set('en-US'); // 3, 0 + Locale.set('en-US'); // 3, 3 expect(Locale.formatNumber(1234567.1234, { groupSizes: [0, 0] })).toEqual('1234567.123'); expect(Locale.formatNumber(12345678.1234, { groupSizes: [0, 0] })).toEqual('12345678.123'); ",1 "diff --git a/src/components/expandablearea/readme.md b/src/components/expandablearea/readme.md @@ -56,7 +56,6 @@ Its possible to assign a custom button that can toggle a specific area using the
    ``` - ## Testability - Please refer to the [Application Testability Checklist](https://design.infor.com/resources/application-testability-checklist) for further details. ",1 "diff --git a/src/components/personalize/personalize.js b/src/components/personalize/personalize.js @@ -311,8 +311,8 @@ Personalize.prototype = { */ setTheme(incomingTheme) { if (theme.currentTheme.id === incomingTheme) { - if (!$('html').hasClass(`${theme}-theme`)) { - $('html').addClass(`${theme}-theme`); + if (!$('html').hasClass(`${incomingTheme}-theme`)) { + $('html').addClass(`${incomingTheme}-theme`); } return; } ",1 "diff --git a/scripts/build/create-svg-html.js b/scripts/build/create-svg-html.js @@ -142,8 +142,7 @@ function createHtmlFiles() { */ function createSvgHtml(verbose) { IS_VERBOSE = verbose; - cleanFiles(); - return createHtmlFiles(); + cleanFiles().then(createHtmlFiles); } module.exports = createSvgHtml; ",1 "diff --git a/src/components/datagrid/_datagrid.scss b/src/components/datagrid/_datagrid.scss @@ -193,13 +193,13 @@ $datagrid-short-row-height: 23px; &.has-group-headers.has-filterable-columns { .datagrid-body { - height: calc(100% - 100px); + height: calc(100% - 105px); } } &.has-filterable-columns { .datagrid-body { - height: calc(100% - 65px); + height: calc(100% - 66px); } .datagrid-filter-wrapper { ",1 "diff --git a/app/views/components/slider/example-index.html b/app/views/components/slider/example-index.html
    - +

    ",1 "diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md - `[Datagrid]` Added an example of expandOnActivate on a customer editor. ([#353](https://github.com/infor-design/enterprise-ng/issues/353)) - `[Datagrid]` Added ability to pass a function to the tooltip option for custom formatting. ([#354](https://github.com/infor-design/enterprise-ng/issues/354)) - `[Dropdown]` Changed the way dropdowns work with screen readers to be a collapsible listbox.([#404](https://github.com/infor-design/enterprise/issues/404)) -- `[Dropdown]` Changed the way dropdowns work with screen readers to be a collapsible listbox.([#404](https://github.com/infor-design/enterprise/issues/404)) +- `[Dropdown]` Fixed an issue where multiselect dropdown unchecking ""Select All"" was not getting clear after close list with Safari browser.([#1882](https://github.com/infor-design/enterprise/issues/1882)) - `[Dropdown]` Added an example of a color dropdown showing palette colors as icons.([#2013](https://github.com/infor-design/enterprise/issues/2013)) - `[Listbuilder]` Fixed an issue where the text was not sanitizing. ([#1692](https://github.com/infor-design/enterprise/issues/1692)) - `[Lookup]` Fixed an issue where the tooltip was using audible text in the code block component. ([#354](https://github.com/infor-design/enterprise-ng/issues/354)) ",1 "diff --git a/src/components/applicationmenu/applicationmenu.js b/src/components/applicationmenu/applicationmenu.js @@ -29,7 +29,7 @@ const APPLICATIONMENU_DEFAULTS = { dismissOnClickMobile: false, filterable: false, openOnLarge: false, - triggers: [], + triggers: ['.application-menu-trigger'], onExpandSwitcher: null, onCollapseSwitcher: null, }; ",1 "diff --git a/README.md b/README.md [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![npm version](https://badge.fury.io/js/ids-enterprise.svg)](https://badge.fury.io/js/ids-enterprise) [![Build Status](https://travis-ci.com/infor-design/enterprise.svg?branch=master)](https://travis-ci.com/infor-design/enterprise) -[![BrowserStack Status](https://www.browserstack.com/automate/badge.svg?badge_key=M2l2RFNkS2hHUU1CU0kvcFdsSGdIWFlMNEF0RVZzRzNvSHVTemJIektiOD0tLTUvWm1JUWNXbjhML01oR2hJNllLb2c9PQ==--dff99debefe381a9d6031c2ce209d663d727ecf9)](https://www.browserstack.com/automate/public-build/M2l2RFNkS2hHUU1CU0kvcFdsSGdIWFlMNEF0RVZzRzNvSHVTemJIektiOD0tLTUvWm1JUWNXbjhML01oR2hJNllLb2c9PQ==--dff99debefe381a9d6031c2ce209d663d727ecf9) +[![BrowserStack Status](https://www.browserstack.com/automate/badge.svg?badge_key=ZTBSMS9NZFgxN2VCZnpaNmdsa1NhY2J1NHlsNnFuMG5UcGViQUhMYnl1QT0tLVlTTks3UUVQbXd0emlxL1BKK2RjeGc9PQ==--eb3493141181901c21b84c0bf6c9c7d44635df2ausmvtmcconechy:enterprusmusmvtuusuuuuusuusmvusmvtuusmvuusuuuuuuu)](https://www.browserstack.com/automate/public-build/ZTBSMS9NZFgxN2VCZnpaNmdsa1NhY2J1NHlsNnFuMG5UcGViQUhMYnl1QT0tLVlTTks3UUVQbXd0emlxL1BKK2RjeGc9PQ==--eb3493141181901c21b84c0bf6c9c7d44635df2ausmvtmcconechy:enterprusmusmvtuusuuuuusuusmvusmvtuusmvuusuuuuuuu) Infor Design System's Enterprise component library is a framework-independent UI library consisting of CSS and JS that provides Infor product development teams, partners, and customers the tools to create user experiences that are approachable, focused, relevant, perceptive. ",1 "diff --git a/README.md b/README.md [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![npm version](https://badge.fury.io/js/ids-enterprise.svg)](https://badge.fury.io/js/ids-enterprise) [![Build Status](https://travis-ci.com/infor-design/enterprise.svg?branch=master)](https://travis-ci.com/infor-design/enterprise) -[![BrowserStack Status](https://www.browserstack.com/automate/badge.svg?badge_key=YjZiNnMrdklFaml2V3ZaY1g0NnFVNVhsZ2RjTjJleStKb2pzdmN1c2lraz0tLWEzdVBmUDhFYml5VzV2cGdKVnZiQnc9PQ==--2f996e1132d31738f133e4d1414e9591e2187a10](https://www.browserstack.com/automate/public-build/YjZiNnMrdklFaml2V3ZaY1g0NnFVNVhsZ2RjTjJleStKb2pzdmN1c2lraz0tLWEzdVBmUDhFYml5VzV2cGdKVnZiQnc9PQ==--2f996e1132d31738f133e4d1414e9591e2187a10) +[![BrowserStack Status](https://www.browserstack.com/automate/badge.svg?badge_key=YjZiNnMrdklFaml2V3ZaY1g0NnFVNVhsZ2RjTjJleStKb2pzdmN1c2lraz0tLWEzdVBmUDhFYml5VzV2cGdKVnZiQnc9PQ==--2f996e1132d31738f133e4d1414e9591e2187a10)](https://www.browserstack.com/automate/public-build/YjZiNnMrdklFaml2V3ZaY1g0NnFVNVhsZ2RjTjJleStKb2pzdmN1c2lraz0tLWEzdVBmUDhFYml5VzV2cGdKVnZiQnc9PQ==--2f996e1132d31738f133e4d1414e9591e2187a10) Infor Design System's Enterprise component library is a framework-independent UI library consisting of CSS and JS that provides Infor product development teams, partners, and customers the tools to create user experiences that are approachable, focused, relevant, perceptive. ",1 "diff --git a/test/components/listbuilder/listbuilder-api.func-spec.js b/test/components/listbuilder/listbuilder-api.func-spec.js import { ListBuilder } from '../../../src/components/listbuilder/listbuilder'; +import { cleanup } from '../../helpers/func-utils'; const listbuilderHTML = require('../../../app/views/components/listbuilder/example-index.html'); const svg = require('../../../src/components/icons/svg.html'); @@ -6,7 +7,6 @@ const svg = require('../../../src/components/icons/svg.html'); require('../../../src/components/locale/cultures/en-US.js'); let listbuilderEl; -let svgEl; let listbuilderObj; // Define dataset @@ -27,19 +27,16 @@ ds.push({ id: 12, value: 'opt-12', text: 'Libya' }); describe('ListBuilder API', () => { beforeEach(() => { listbuilderEl = null; - svgEl = null; listbuilderObj = null; document.body.insertAdjacentHTML('afterbegin', svg); document.body.insertAdjacentHTML('afterbegin', listbuilderHTML); listbuilderEl = document.body.querySelector('#example-listbuilder'); - svgEl = document.body.querySelector('.svg-icons'); listbuilderObj = new ListBuilder(listbuilderEl, { dataset: [...ds] }); }); afterEach(() => { listbuilderObj.destroy(); - listbuilderEl.parentNode.removeChild(listbuilderEl); - svgEl.parentNode.removeChild(svgEl); + cleanup(['#example-listbuilder-container', '.svg-icons', '#listbuilder-script', '#listbuilder-tmpl']); }); it('Should be defined as an object', () => { ",1 "diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md -# What's New with Enterprise +turquoiseturquoise# What's New with Enterprise ## v4.19.0 - `[Listview]` Improved accessibility when configured as selectable (all types), as well as re-enabled accessibility e2e tests. ([#403](https://github.com/infor-design/enterprise/issues/403)) - `[Datagrid]` Fixed charts in columns not resizing correctly to short row height. ([#1930](https://github.com/infor-design/enterprise/issues/1930)) - `[Datagrid]` Fixed an issue for xss where console.log was not sanitizing and make grid to not render. ([#1941](https://github.com/infor-design/enterprise/issues/1941)) +- `[Personalization]` Changed the default turquoise personalization to a darker one. ([#2063](https://github.com/infor-design/enterprise/issues/2063)) +- `[Personalization]` Added a default option to the personalization color pickers. ([#2063](https://github.com/infor-design/enterprise/issues/2063)) - `[Tree]` Fixed an issue where children property null was breaking tree to not render. ([#1908](https://github.com/infor-design/enterprise/issues/1908)) ### v4.19.0 Chores & Maintenance ",1 "diff --git a/test/components/toolbar-flex/toolbar-flex-api.func-spec.js b/test/components/toolbar-flex/toolbar-flex-api.func-spec.js @@ -109,7 +109,7 @@ describe('Flex Toolbar', () => { expect(overflow[0]).toEqual(jasmine.any(ToolbarFlexItem)); expect(overflow[0].overflowed).toBeTruthy(); done(); - }, 300); + }, 350); }); it('Can programmatically navigate toolbar items', () => { @@ -332,7 +332,9 @@ describe('Flex Toolbar', () => { const textButton = toolbarAPI.items[0]; expect(textButton.overflowed).toBeFalsy(); + }, 300); + setTimeout(() => { const secondIconButton = toolbarAPI.items[2]; expect(secondIconButton.overflowed).toBeTruthy(); ",1 "diff --git a/src/components/datagrid/_datagrid.scss b/src/components/datagrid/_datagrid.scss @@ -1051,6 +1051,10 @@ $datagrid-short-row-height: 23px; min-width: 20px; } + &.btn-primary { + top: -1px; + } + .icon { margin-top: -3px; } ",1 "diff --git a/src/components/personalize/personalize.js b/src/components/personalize/personalize.js @@ -261,14 +261,14 @@ Personalize.prototype = { // Adapt them for backwards compatibility const legacyThemeNames = ['light', 'dark', 'high-contrast']; - if (legacyThemeNames.includes(incomingTheme)) { + if (legacyThemeNames.indexOf(incomingTheme) > -1) { incomingTheme += '-theme'; } $html .removeClass((idx, val) => { const classes = val.split(' '); - const toRemove = classes.filter(c => c.includes('theme')); + const toRemove = classes.filter(c => c.indexOf('theme') > -1); return toRemove.join(); }) .addClass(incomingTheme); @@ -375,7 +375,7 @@ Personalize.prototype = { } // Copy the old settings to compare - const prevSettings = Object.assign({}, this.settings); + const prevSettings = utils.extend({ }, this.settings); // Merge in the new settings this.settings = utils.mergeSettings(this.element[0], settings, this.settings); ",1 "diff --git a/src/components/searchfield/_searchfield.scss b/src/components/searchfield/_searchfield.scss @@ -355,6 +355,11 @@ $cubic-bezier-ease: cubic-bezier(0.17, 0.04, 0.03, 0.94); // RTL Styles html[dir='rtl'] { .searchfield-wrapper { + .searchfield { + padding-left: 10px; + padding-right: 34px; + } + > .icon { &:not(.close) { left: auto; ",1 "diff --git a/app/views/components/hierarchy/test-multiple-charts.html b/app/views/components/hierarchy/test-multiple-charts.html console.log(event, eventInfo); if (eventInfo.data.childrenUrl) { - $.getJSON(`{{basepath}}api/${eventInfo.data.childrenUrl}`, function(newData) { + $.getJSON('{{basepath}}api/' + eventInfo.data.childrenUrl, function(newData) { reload(eventInfo, hierarchyControl, newData); }); }
    -
    +
    - \n""); print("" \n""); print("" \n""); - print("" \n""); + print("" ""); [% END %] - ",2 "diff --git a/MaterialSkin/HTML/material/html/css/style.css b/MaterialSkin/HTML/material/html/css/style.css @@ -349,23 +349,22 @@ div.v-subheader { .image-grid-select-btn, .image-grid-select-btn:hover { position:absolute; top:2px !important; - left:6px !important; + left:4px !important; } .image-grid-item .emblem { position:absolute; top:2px !important; - right:8px !important; - width:28px !important; - height:28px !important; + right:4px !important; + width:32px !important; + height:32px !important; border-radius:50% !important; - padding:2px; - box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); + padding:3px; } .image-grid-item .emblem img { - width:24px !important; - height:24px !important; + width:26px !important; + height:26px !important; } .lms-list-sub .emblem, .lms-list-jump .emblem { ",2 "diff --git a/MaterialSkin/HTML/material/html/js/toolbar.js b/MaterialSkin/HTML/material/html/js/toolbar.js @@ -650,7 +650,7 @@ Vue.component('lms-toolbar', { return this.$store.state.visibleMenus.size>0 }, updatesAvailable() { - return true || this.$store.state.updatesAvailable.size>0 + return this.$store.state.updatesAvailable.size>0 }, keyboardControl() { return this.$store.state.keyboardControl && !IS_MOBILE ",2 "diff --git a/MaterialSkin/HTML/material/html/js/browse-resp.js b/MaterialSkin/HTML/material/html/js/browse-resp.js @@ -12,6 +12,16 @@ function itemText(i) { return i.title ? i.title : i.name ? i.name : i.caption ? i.caption : i.credits ? i.credits : undefined; } +function removeDiactrics(key) { + if (undefined!=key && key.length==1) { + var code = key.charCodeAt(0); + if (code>127) { // Non-ASCII... + return key.normalize(""NFD"").replace(/[\u0300-\u036f]/g, """"); + } + } + return key; +} + function parseBrowseResp(data, parent, options, cacheKey) { // NOTE: If add key to resp, then update addToCache in utils.js var resp = {items: [], baseActions:[], canUseGrid: false, jumplist:[] }; @@ -19,7 +29,6 @@ function parseBrowseResp(data, parent, options, cacheKey) { try { if (data && data.result) { logJsonMessage(""RESP"", data); - var textKeys = new Set(); if (data.result.item_loop) { // SlimBrowse response var playAction = false; var addAction = false; @@ -359,10 +368,9 @@ function parseBrowseResp(data, parent, options, cacheKey) { i.section = parent ? parent.section : undefined; - var key = i.textkey; - if (undefined!=key && (resp.jumplist.length==0 || (resp.jumplist[resp.jumplist.length-1].key!=key && !textKeys.has(key)))) { + var key = removeDiactrics(i.textkey); + if (undefined!=key && (resp.jumplist.length==0 || resp.jumplist[resp.jumplist.length-1].key!=key)) { resp.jumplist.push({key: key, index: resp.items.length}); - textKeys.add(key); } if (isFavorites) { i.draggable = true; @@ -458,10 +466,9 @@ function parseBrowseResp(data, parent, options, cacheKey) { resp.canUseGrid = lmsOptions.infoPlugin && lmsOptions.artistImages; for (var idx=0, loop=data.result.artists_loop, loopLen=loop.length; idx0) { title+="" ("" + i.year + "")""; } - var key = jumpListYear ? (""""+i.year) : i.textkey; - if (undefined!=key && (resp.jumplist.length==0 || (resp.jumplist[resp.jumplist.length-1].key!=key && !textKeys.has(key)))) { + var key = jumpListYear ? (""""+i.year) : removeDiactrics(i.textkey); + if (undefined!=key && (resp.jumplist.length==0 || resp.jumplist[resp.jumplist.length-1].key!=key)) { resp.jumplist.push({key: key, index: resp.items.length}); - textKeys.add(key); } var album = { @@ -627,10 +633,9 @@ function parseBrowseResp(data, parent, options, cacheKey) { } else if (data.result.genres_loop) { for (var idx=0, loop=data.result.genres_loop, loopLen=loop.length; idx 0,'pmgr-title':0==players.length}"" class=""ellipsis"">{{player.server}} - + ",2 "diff --git a/MaterialSkin/HTML/material/html/js/server.js b/MaterialSkin/HTML/material/html/js/server.js @@ -398,7 +398,6 @@ var lmsServer = Vue.component('lms-server', { for (var idx=0, len=data.players_loop.length; idx {{playerStatus.current.title ? playerStatus.current.title : """"}}
    {{playerStatus.current.artistAndComposer ? playerStatus.current.artistAndComposer : """"}}
    - {{playerStatus.current.album ? playerStatus.current.album : playerStatus.current.remote_title && playerStatus.current.remote_title!=playerStatus.current.title ? playerStatus.current.remote_title : """"}}

    + {{playerStatus.current.album ? playerStatus.current.album : playerStatus.current.remote_title && playerStatus.current.remote_title!=playerStatus.current.title ? playerStatus.current.remote_title : """"}}
    ",2 "diff --git a/MaterialSkin/HTML/material/html/js/nowplaying-page.js b/MaterialSkin/HTML/material/html/js/nowplaying-page.js @@ -315,8 +315,7 @@ var lmsNowPlaying = Vue.component(""lms-now-playing"", { disablePrev:true, disableNext:true, dstm:false, - infoZoom:10, - threeLines:false + infoZoom:10 }; }, mounted() { @@ -393,8 +392,6 @@ var lmsNowPlaying = Vue.component(""lms-now-playing"", { var playStateChanged = false; var trackChanged = false; - this.threeLines = playerStatus.current.remote_title && (""""+playerStatus.current.id)[0]=='-'; - // Have other items changed if (playerStatus.isplaying!=this.playerStatus.isplaying) { this.playerStatus.isplaying = playerStatus.isplaying; ",2 "diff --git a/MaterialSkin/HTML/material/html/js/browse-page.js b/MaterialSkin/HTML/material/html/js/browse-page.js @@ -2363,6 +2363,8 @@ var lmsBrowse = Vue.component(""lms-browse"", { this.top[i].params.push(""menu:1""); } else if (this.top[i].id==TOP_RADIO_ID) { this.top[i].icon=undefined; this.top[i].svg=""radio-tower""; + } else if (this.top[i].id==TOP_MYMUSIC_ID) { + this.top[i].menu=undefined; } } for (var i=0, len=this.top.length; i1) { + } else if (undefined!=view.$store.state.ratingsPlugin && view.items.length>1) { view.currentActions.items.push({albumRating:true, title:i18n(""Set rating for all tracks""), icon:""stars"", weight:99}); } view.currentActions.items.sort(function(a, b) { return a.weight!=b.weight ? a.weight { logJsonMessage(""RESP"", data); if (data && view.isCurrent(data, ARTIST_TAB)) { - if (data.result && data.result.biograph)) { + if (data.result && data.result.biograph) { if (data.result.artist) { view.info.tabs[ARTIST_TAB].found = true; if (view.info.tabs[ARTIST_TAB].first) { ",2 "diff --git a/MaterialSkin/HTML/material/html/js/track-sources.js b/MaterialSkin/HTML/material/html/js/track-sources.js @@ -13,7 +13,6 @@ function initTrackSources() { function getTrackSource(track) { if (undefined!=track.url) { - console.log(track.url); if (track.url.startsWith(""file:"") && !track.url.startsWith(""tmp:"")) { return i18n(""Local""); } ",2 "diff --git a/MaterialSkin/HTML/material/html/js/customactions.js b/MaterialSkin/HTML/material/html/js/customactions.js @@ -56,6 +56,8 @@ function performCustomAction(obj, action, player, item) { } } +const ACTION_KEYS = ['ID', 'NAME', 'ARTISTID', 'ARTISTNAME', 'ALBUMID', 'ALBUMNAME', 'TRACKID', 'TRACKNAME', 'TRACKNUM', 'DISC', 'GENREID', 'GENRENAME', 'YEAR', 'COMPOSER']; + function doReplacements(string, player, item) { let val = ''+string; if (undefined!=player) { @@ -100,6 +102,9 @@ function doReplacements(string, player, item) { if (undefined!=item.album_id) { val=val.replace(""$ALBUMNAME"", item.album); } + if (undefined!=item.composer) { + val=val.replace(""$COMPOSER"", item.composer); + } if (undefined!=item.title) { if (undefined!=item.id) { let id = ''+item.id; @@ -116,9 +121,9 @@ function doReplacements(string, player, item) { val=val.replace(""$TRACKNAME"", item.title); } } - if (undefined!=item.composer) { - val=val.replace(""$COMPOSER"", item.composer); } + for (var i=0, len=ACTION_KEYS.length; i
    ",7 "diff --git a/src/components/personalize/personalize.styles.js b/src/components/personalize/personalize.styles.js @@ -395,14 +395,32 @@ html[class*=""theme-uplift-""] .application-menu.is-personalizable .accordion.pane color: ${colors.subtext} !important; } -html[class*=""theme-uplift-""] .application-menu.is-personalizable .accordion.panel.inverse > .accordion-header.is-expanded.is-selected { +html[class*=""theme-uplift""] .application-menu.is-personalizable .accordion.panel.inverse > .accordion-header.is-focused:not(.hide-focus):not(.is-expanded) { + border-color: ${colors.contrast} !important; +} + +html[class*=""theme-uplift""] .application-menu.is-personalizable .accordion.panel.inverse > .accordion-header.is-focused.is-expanded { + border-color: transparent !important; +} + +html[class*=""theme-uplift-""] .application-menu.is-personalizable .accordion.panel.inverse > .accordion-header.is-expanded.is-selected::before { background-color: ${colors.darker} !important; + border-color: ${colors.darker} !important; +} + +html[class*=""theme-uplift-""] .application-menu.is-personalizable .accordion.panel.inverse > .accordion-header.is-expanded.is-focused::before { + border-color: ${colors.contrast} !important; } html[class*=""theme-uplift-""] .application-menu.is-personalizable .accordion.panel.inverse > .accordion-header.is-expanded + .accordion-pane { background-color: ${colors.dark} !important; } +html[class*=""theme-uplift-""] .application-menu.is-personalizable .accordion.panel.inverse > .accordion-header.is-expanded:hover::before { + border-color: ${colors.darkest} !important; + background-color: ${colors.darkest} !important; +} + .is-personalizable .personalize-header, .is-personalizable.tab-container { background-color: ${colors.base} !important; ",7 "diff --git a/app/views/components/tag/test-taglist-gauntlet.html b/app/views/components/tag/test-taglist-gauntlet.html }); $('body').on('initialized', function () { + if ($('#newtag-is-link').prop('checked')) { + $('#href-settings-container').removeClass('hidden'); + } // Submit $('#create-tag').on('submit.test', function (e) { ",7 "diff --git a/test/components/searchfield/searchfield.e2e-spec.js b/test/components/searchfield/searchfield.e2e-spec.js @@ -186,11 +186,16 @@ if (utils.isChrome() && utils.isCI()) { await utils.setPage('/components/searchfield/test-place-on-bottom.html?layout=nofrills'); await browser.driver .wait(protractor.ExpectedConditions - .presenceOf(element(by.id('#searchfield-template'))), config.waitsFor); + .presenceOf(element(by.id('searchfield-template'))), config.waitsFor); }); it('should correctly place the results list above the field if it can\'t fit beneath (visual regression)', async () => { - const searchfieldInputEl = await element(by.id('#searchfield-template')); + // shrink the page to check ajax menu button in the overflow + const windowSize = await browser.driver.manage().window().getSize(); + browser.driver.manage().window().setSize(640, 480); + await browser.driver.sleep(config.sleep); + + const searchfieldInputEl = await element(by.id('searchfield-template')); await browser.driver .wait(protractor.ExpectedConditions.presenceOf(searchfieldInputEl), config.waitsFor); await browser.driver.sleep(config.sleep); @@ -199,7 +204,9 @@ if (utils.isChrome() && utils.isCI()) { await browser.driver.sleep(config.sleep); expect(await browser.protractorImageComparison - .checkElement(await element(by.id('maincontent')), 'searchfield-open')).toEqual(0); + .checkElement(await element(by.css('.container')), 'searchfield-open')).toEqual(0); + + await browser.driver.manage().window().setSize(windowSize.width, windowSize.height); }); }); } ",7 "diff --git a/test/components/message/message.e2e-spec.js b/test/components/message/message.e2e-spec.js @@ -26,14 +26,18 @@ describe('Message tests', () => { const modalButtonPrimaryEl = await element(by.css('.btn-modal-primary')); await modalButtonPrimaryEl.sendKeys(protractor.Key.TAB); + const modalButtonPrimaryClasses = await modalButtonPrimaryEl.getAttribute('class'); - expect(['hide-focus', 'btn-modal-primary', 'btn-modal-primary hide-focus']).toContain(await modalButtonPrimaryEl.getAttribute('class')); + expect(modalButtonPrimaryClasses).toContain('btn-modal-primary'); + expect(modalButtonPrimaryClasses).toContain('hide-focus'); const modalButtonEl = await element(by.css('.btn-modal')); await modalButtonEl.sendKeys(protractor.Key.TAB); + const modalButtonClasses = await modalButtonEl.getAttribute('class'); - expect(['hide-focus', 'btn-modal', 'btn-modal hide-focus']).toContain(await modalButtonEl.getAttribute('class')); + expect(modalButtonClasses).toContain('btn-modal'); + expect(modalButtonClasses).toContain('hide-focus'); }); }); ",7 "diff --git a/test/components/datagrid/datagrid.e2e-spec.js b/test/components/datagrid/datagrid.e2e-spec.js @@ -2487,7 +2487,7 @@ describe('Datagrid disable last page', () => { }); it('Should be have last and next page disabled', async () => { - expect(await element.all(by.css('.pager-toolbar .is-disabled')).count()).toEqual(2); + expect(await element.all(by.css('.pager-toolbar button.is-disabled')).count()).toEqual(2); }); }); @@ -2509,12 +2509,12 @@ describe('Datagrid paging force disabled', () => { await element(by.id('force-disabled')).click(); await browser.driver.sleep(config.sleep); - expect(await element.all(by.css('.pager-toolbar .is-disabled')).count()).toEqual(4); + expect(await element.all(by.css('.pager-toolbar button.is-disabled')).count()).toEqual(4); await element(by.id('force-enabled')).click(); await browser.driver.sleep(config.sleep); - expect(await element.all(by.css('.pager-toolbar .is-disabled')).count()).toEqual(0); + expect(await element.all(by.css('.pager-toolbar button.is-disabled')).count()).toEqual(0); }); }); ",7 "diff --git a/test/components/swaplist/swaplist-beforeswap.func-spec.js b/test/components/swaplist/swaplist-beforeswap.func-spec.js import { SwapList } from '../../../src/components/swaplist/swaplist'; +import { cleanup } from '../../helpers/func-utils'; const swaplistHTML = require('../../../app/views/components/swaplist/test-beforeswap-with-search.html'); const svg = require('../../../src/components/icons/svg.html'); @@ -20,29 +21,28 @@ dataset.push({ id: 13, value: 'opt-13', text: 'Option MM' }); dataset.push({ id: 14, value: 'opt-14', text: 'Option NN' }); let swaplistEl; -let svgEl; let swaplistObj; describe('SwapList API', () => { beforeEach(() => { swaplistEl = null; - svgEl = null; swaplistObj = null; document.body.insertAdjacentHTML('afterbegin', svg); document.body.insertAdjacentHTML('afterbegin', swaplistHTML); - svgEl = document.body.querySelector('.svg-icons'); swaplistEl = document.body.querySelector('#example-swaplist-1'); swaplistObj = new SwapList(swaplistEl, { available: dataset, searchable: true }); }); afterEach(() => { swaplistObj.destroy(); - swaplistEl.parentNode.removeChild(swaplistEl); - svgEl.parentNode.removeChild(svgEl); - - const rowEl = document.body.querySelector('.row'); - rowEl.parentNode.removeChild(rowEl); + cleanup([ + '#swaplist-tmpl', + '#swaplist-code', + '.svg-icons', + '.row', + '.page-container' + ]); }); it('Should be defined as an object', () => { ",7 "diff --git a/app/views/components/modal/test-long-title-large-content.html b/app/views/components/modal/test-long-title-large-content.html $(this).focus(); setModal(modals[this.id]); - if ($('.modal-title').height() > 35) { + var sohoTheme = (Soho.theme.currentTheme.name.lastIndexOf('Soho') !== -1 || Soho.theme.currentTheme.name === 'Soho Light') && $('.modal-title')[0].innerHTML.length > 68; + + var upliftTheme = (Soho.theme.currentTheme.name.lastIndexOf('Uplift') !== -1 || Soho.theme.currentTheme.name === 'Soho Uplift') && $('.modal-title')[0].innerHTML.length > 47; + setTimeout(function () { + if (sohoTheme || upliftTheme) { $('.modal-title').tooltip(TOOLTIP_OPTIONS); - }, 500); } + }, 100); + }); }) ",7 "diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md - `[Application Menu]` Fixed misalignment/size of bullet icons in the accordion on Android devices. ([#1429](http://localhost:4000/components/applicationmenu/test-six-levels.html)) - `[Application Menu]` Add keyboard support for closing Role Switcher panel ([#3477](https://github.com/infor-design/enterprise/issues/3477)) - `[Autocomplete]` Added a check to prevent the autocomplete from incorrectly stealing form focus, by checking for inner focus before opening a list on typeahead. ([#3639](https://github.com/infor-design/enterprise/issues/3070)) -- `[Autocomplete]` Fixed an issue where an change event was not firing while navigating list. ([#804](https://github.com/infor-design/enterprise/issues/804)) +- `[Autocomplete]` Fixed an issue where an change event was not firing when selecting from the menu. ([#804](https://github.com/infor-design/enterprise/issues/804)) - `[Bubble Chart]` Fixed an issue where an extra axis line was shown when using the domain formatter. ([#501](https://github.com/infor-design/enterprise/issues/501)) - `[Bullet Chart]` Added support to format ranges and difference values. ([#3447](https://github.com/infor-design/enterprise/issues/3447)) - `[Button]` Fixed the button disabled method to no longer use class `is-disabled`. ([#3447](https://github.com/infor-design/enterprise-ng/issues/799)) ",7 "diff --git a/app/views/utils/example-color-saturation.html b/app/views/utils/example-color-saturation.html
    + +
    ",7 "diff --git a/src/components/locale/locale.js b/src/components/locale/locale.js @@ -992,17 +992,22 @@ const Locale = { // eslint-disable-line dateFormat = dateFormat.replace(',', ''); dateString = dateString.replace(',', ''); - if (dateFormat === 'Mdyyyy' || dateFormat === 'dMyyyy') { - dateString = `${dateString.substr(0, dateString.length - 4)}/${dateString.substr(dateString.length - 4, dateString.length)}`; - dateString = `${dateString.substr(0, dateString.indexOf('/') / 2)}/${dateString.substr(dateString.indexOf('/') / 2)}`; - } - - if (dateFormat === 'Mdyyyy') { - dateFormat = 'M/d/yyyy'; - } - - if (dateFormat === 'dMyyyy') { - dateFormat = 'd/M/yyyy'; + // Adjust short dates where no separators or special characters are present. + const hasMdyyyy = dateFormat.indexOf('Mdyyyy'); + const hasdMyyyy = dateFormat.indexOf('dMyyyy'); + let startIndex = -1; + let endIndex = -1; + if (hasMdyyyy > -1 || hasdMyyyy > -1) { + startIndex = hasMdyyyy > -1 ? hasMdyyyy : hasdMyyyy > -1 ? hasdMyyyy : 0; + endIndex = startIndex + dateString.indexOf('/') > -1 ? dateString.indexOf('/') : dateString.length; + dateString = `${dateString.substr(startIndex, endIndex - 4)}/${dateString.substr(endIndex - 4, dateString.length)}`; + dateString = `${dateString.substr(startIndex, dateString.indexOf('/') / 2)}/${dateString.substr(dateString.indexOf('/') / 2, dateString.length)}`; + } + if (hasMdyyyy > -1) { + dateFormat = dateFormat.replace('Mdyyyy', 'M/d/yyyy'); + } + if (hasdMyyyy > -1) { + dateFormat = dateFormat.replace('dMyyyy', 'd/M/yyyy'); } if (dateFormat.indexOf(' ') !== -1) { ",7 "diff --git a/src/components/mask/mask-api.js b/src/components/mask/mask-api.js @@ -280,6 +280,7 @@ MaskAPI.prototype = { while (rawValueArr.length > 0) { // Let's retrieve the first user character in the queue of characters we have left const rawValueChar = rawValueArr.shift(); + const nextChar = rawValue.slice(l, l + 1); // If the character we got from the user input is a placeholder character (which happens // regularly because user input could be something like (540) 90_-____, which includes @@ -297,19 +298,19 @@ MaskAPI.prototype = { } else if ( maskObj.literalRegex && maskObj.literalRegex.test(rawValueChar.char) && - rawValue.slice(l, l + 1) === rawValueChar.char + nextChar === rawValueChar.char ) { // Analyze the number of this particular literal in the value, // and only add it if we haven't passed the maximum const thisLiteralRegex = new RegExp(`(${rawValueChar.char})`, 'g'); const numberLiteralsPlaceholder = settings.placeholder.match(thisLiteralRegex).length; const numberLiteralsRawValue = rawValue.match(thisLiteralRegex).length; - if (numberLiteralsRawValue < numberLiteralsPlaceholder) { + if (numberLiteralsRawValue <= numberLiteralsPlaceholder) { resultStr += rawValueChar.char; } - const rawValueAfterLiteral = rawValue.slice(l + 1, rawValue.length - 1); - let literalIndex = rawValueAfterLiteral.indexOf(rawValueChar.char); + // Fast forward the loop to the after the next instance of this literal. + let literalIndex = settings.placeholder.slice(l).indexOf(rawValueChar.char); while (literalIndex > 0) { l++; literalIndex--; ",7 "diff --git a/src/components/tabs-module/_tabs-module-uplift.scss b/src/components/tabs-module/_tabs-module-uplift.scss &.application-menu-trigger { a { - padding: 5px 6px 7px; + padding: 5px 12px 7px; width: 100%; } } .icon.app-header { top: -6px; + + span:not(.audible) { + width: 18px; + } } } ",7 "diff --git a/src/components/colorpicker/_colorpicker.scss b/src/components/colorpicker/_colorpicker.scss // Color Picker //================================================== // +$trigger-size: 30px; + @import '../icons/icons'; @import '../input/input'; @import '../popupmenu/popupmenu'; } } +.colorpicker-input-xs, +.colorpicker-input-sm, +.colorpicker-input-md, +.colorpicker-input-mm, +.colorpicker-input-lg { + flex-shrink: 0; + margin-right: $trigger-size; +} + .colorpicker-input-xs { width: 18px !important; + } .colorpicker-input-sm { background-color: $input-color-initial-background; border: 1px solid $input-color-initial-border; border-radius: 2px; - display: inline-block; + display: inline-flex; height: $input-size-regular-height; + max-width: 100%; overflow: hidden; + position: relative; width: 150px; + .trigger { + position: absolute; + right: 0; + } + &.is-focused { border-color: $input-color-focus-border; box-shadow: $focus-box-shadow; display: inline-block; height: $input-size-regular-height - 0.4; left: 1px; + min-width: $input-size-regular-height - 0.4; position: relative; top: 1px; vertical-align: top; .trigger { height: $input-size-compact-height - 0.4; margin-left: -($input-size-compact-height - 0.4); + right: 0; width: $input-size-compact-height - 0.4; .icon:not(.icon-error) { ",7 "diff --git a/src/components/datagrid/datagrid.js b/src/components/datagrid/datagrid.js @@ -6398,7 +6398,7 @@ Datagrid.prototype = { const isEditable = self.makeCellEditable(self.activeCell.rowIndex, self.activeCell.cell, e); - if (col.click && typeof col.click === 'function' && target.is('button, input[checkbox], a, a.search-mode i') || target.parent().is('button')) { //eslint-disable-line + if (col.click && typeof col.click === 'function' && target.is('button, input[checkbox], a, a.search-mode i') || target.parent().is('button:not(.trigger)')) { const rowElem = $(this).closest('tr'); let rowIdx = self.actualRowIndex(rowElem); dataRowIdx = self.dataRowIndex(rowElem); ",7 "diff --git a/src/components/button/button.js b/src/components/button/button.js @@ -166,7 +166,7 @@ Button.prototype = { // Derive X/Y coordinates from input events if (e) { - if (!env.features.touch) { + if (e.originalEvent instanceof MouseEvent) { // Standard Mouse Click xPos = e.pageX - btnOffset.left; yPos = e.pageY - btnOffset.top; @@ -182,8 +182,8 @@ Button.prototype = { } // If values have not been defined, simply set them to the center of the element. - xPos = (xPos < 0) ? this.element.outerWidth() / 2 : xPos; - yPos = (yPos < 0) ? this.element.outerHeight() / 2 : yPos; + if (!xPos) { xPos = this.element.outerWidth() / 2; } + if (!yPos) { yPos = this.element.outerHeight() / 2; } // Create/place the ripple effect const ripple = $(` ",7 "diff --git a/app/views/components/locale/test-format-number-15-decimal.html b/app/views/components/locale/test-format-number-15-decimal.html // transform var options = { - decimal: '.', - group: '', maximumFractionDigits: 15, minimumFractionDigits: 15, - round: true, - style: 'decimal' + round: true } var nbr = Soho.Locale.formatNumber(value, options); $('#parsed-number-field').val(nbr); ",7 "diff --git a/test/components/bar/bar.puppeteer-spec.js b/test/components/bar/bar.puppeteer-spec.js @@ -34,6 +34,7 @@ describe('Bar Chart Puppeteer Tests', () => { it('should not show pointer as a cursor', async () => { const checkCursor = async el => page.$eval(el, e => e.style.cursor); + await page.waitForSelector('#bar-a-bar', { visible: true }); await page.hover('#bar-a-bar'); await page.waitForTimeout(100); expect(await checkCursor('#bar-a-bar')).toContain('inherit'); ",7 "diff --git a/test/components/input/input.e2e-spec.js b/test/components/input/input.e2e-spec.js @@ -82,6 +82,7 @@ describe('Input Test Reset', () => { expect(await element.all(by.css('.icon-dirty')).count()).toEqual(4); await element(by.id('btn-save')).click(); + await browser.driver.sleep(config.sleepShort); expect(await element.all(by.css('.icon-dirty')).count()).toEqual(0); }); @@ -95,10 +96,6 @@ describe('Input tooltip tests', () => { .presenceOf(element(by.id('first-name'))), config.waitsFor); }); - it('Should not have errors', async () => { - await utils.checkForErrors(); - }); - // This test is more important as a windows test it('Should be able to select text', async () => { const inputEl = await element(by.id('first-name')); ",7 "diff --git a/web/examples/composite-brush-multi-dim.html b/web/examples/composite-brush-multi-dim.html

    Usually sub charts of a composite chart share the dimension of the parent. However sometimes, especially when scatter plots are composed, the sub charts may - used different dimensions. This example uses two scatter plots both using array dimensions. - Typically scatter plots use two dimensional brushing (see scatter brushing), - however, composite charts only support one dimensional (along x axis) brushing.

    -

    Try brushing on the chart and see data getting filtered on the right.

    -

    For the curious, you will notice that unlike other charts brushing removes points outside range of the brush + use different dimensions. This example uses two scatter plots both using array dimensions. + Typically scatter plots use two dimensional brushing (see scatter brushing); + however, composite charts only support one dimensional brushing along the x axis.

    +

    Try brushing on the chart and see data getting filtered in the table on the right.

    +

    Notice that unlike in other charts, brushing removes points outside range of the brush instead of just fading them. - The three dimensions used by different charts are actually related. - When brush applies filters on all these three dimensions, all data outside the brush range actually gets removed - by crossfilter. There is no easy way to currently avoid that.

    + This is because the composite chart uses three different dimensions for the child charts, + so each observes the filter applied to the others.

    -
    +
    @@ -93,7 +92,10 @@ chart.width(768) dataTable .dimension(dimX) .group(function (d) { return d.x; }) - .columns(['x', 'y', 'z']); + .columns(['x', 'y', 'z']) + .on('renderlet', function (table) { + table.selectAll('.dc-table-group').classed('info', true); + }); dc.renderAll(); ",7 "diff --git a/src/base/base-mixin.js b/src/base/base-mixin.js @@ -24,8 +24,10 @@ const _defaultFilterHandler = (dimension, filters) => { dimension.filterFunction(d => { for (let i = 0; i < filters.length; i++) { const filter = filters[i]; - if (filter.isFiltered && filter.isFiltered(d)) { + if (filter.isFiltered) { + if(filter.isFiltered(d)) { return true; + } } else if (filter <= d && filter >= d) { return true; } ",7 "diff --git a/src/plugins/process-global-plugin.js b/src/plugins/process-global-plugin.js @@ -30,7 +30,7 @@ export default function processGlobalPlugin({ NODE_ENV = 'development' } = {}) { // if that wasn't the only way `process.env` was referenced... if (code.match(/[^a-zA-Z0-9]process\.env/)) { // hack: avoid injecting imports into commonjs modules - if (!code.match(/require\(/)) { + if (/^import[\s{]|^export\s\w/gm.test(code)) { code = `import process from '\0builtins:process.js';${code}`; } else { code = `var process=${processObj};${code}`; ",7 "diff --git a/src/plugins/npm-plugin/registry.js b/src/plugins/npm-plugin/registry.js @@ -201,7 +201,12 @@ export async function loadPackageFiles({ module, version }) { return await getTarFiles(info.dist.tarball, module, version); } -/** @type {Map} */ +/** + * Cache file contents of package files for quick access. + * Example: + * `my-module@1.0.0 :: /index.js` -> `console.log(""hello world"")` + * @type {Map} + */ const DISK_CACHE = new Map(); /** ",7 "diff --git a/src/plugins/wmr/client.js b/src/plugins/wmr/client.js @@ -147,11 +147,8 @@ function updateStyleSheet(url) { const sheets = document.styleSheets; for (let i = 0; i < sheets.length; i++) { if (strip(sheets[i].href) === url) { - const ownerNode = sheets[i].ownerNode; - if (ownerNode) { // @ts-ignore - ownerNode.href = strip(url) + '?t=' + Date.now(); - } + sheets[i].ownerNode.href = strip(url) + '?t=' + Date.now(); return true; } } ",7 "diff --git a/packages/wmr/src/lib/normalize-options.js b/packages/wmr/src/lib/normalize-options.js @@ -111,13 +111,9 @@ export async function normalizeOptions(options, mode) { // The execution order is: ""pre"" -> ""normal"" -> ""post"" if (options.plugins) { options.plugins = options.plugins.flat().sort((a, b) => { - if (a.enforce === b.enforce) return 0; - else if ((a.enforce === 'pre' && b.enforce !== 'pre') || b.enforce === 'post') { - return -1; - } else if (b.enforce === 'pre' || a.enforce === 'post') { - return 1; - } - return 0; + const aScore = a.enforce === 'post' ? 1 : a.enforce === 'pre' ? -1 : 0; + const bScore = b.enforce === 'post' ? 1 : b.enforce === 'pre' ? -1 : 0; + return aScore - bScore; }); } ",7 "diff --git a/packages/wmr/src/lib/normalize-options.js b/packages/wmr/src/lib/normalize-options.js @@ -166,11 +166,14 @@ export async function normalizeOptions(options, mode) { /** * Deeply merge two config objects - * @param {Partial} a - * @param {Partial} b - * @returns {Partial} + * @template {Record} T + * @template {Record} U + * @param {T} a + * @param {U} b + * @returns {T & U} */ function mergeConfig(a, b) { + /** @type {any} */ const merged = { ...a }; for (const key in b) { ",7 "diff --git a/docs/public/styles/index.css b/docs/public/styles/index.css @@ -337,8 +337,7 @@ h5:hover .anchor { * Layouts */ .sidebar-layout { - position: absolute; - grid-template-columns: minmax(min-content, 33.33%) minmax(40rem, 2fr); + width: 100%; } .sidebar { @@ -360,7 +359,7 @@ h5:hover .anchor { @media (min-width: 900px) { .sidebar-layout { display: grid; - grid-template-columns: minmax(min-content, 33.33%) minmax(40rem, 2fr); + grid-template-columns: minmax(min-content, 33.33%) minmax(40rem, 110ch); } .sidebar { ",7 "diff --git a/docs/public/lib/use-localstorage.js b/docs/public/lib/use-localstorage.js import { useState } from 'preact/hooks'; -const SUPPORTS_LOCAL_STORAGE = window !== undefined && 'localStorage' in window; +const SUPPORTS_LOCAL_STORAGE = typeof localStorage !== 'undefined'; /** * @type {(name: string, value: T) => [T, (v: T) => void]} ",7 "diff --git a/docs/public/styles/index.css b/docs/public/styles/index.css --color-bg-code: #1f2427; --color-info: #d7f1ff; --color-focus: #ff459c; + --color-btn-secondary-hover: rgba(0, 0, 0, 0.1); --focus-width: 0.25rem; --header-height: 3.5rem; --color-bg-code-inline: #66676f; --color-bg-code: #1f2427; --color-info: #184c68; + --color-btn-secondary-hover: rgba(255, 255, 255, 0.1); --header-accent-height: 0.1875rem; } @@ -59,6 +61,7 @@ html[theme='light'] { --color-bg-code-inline: #dddddf; --color-bg-code: #1f2427; --color-info: #d7f1ff; + --color-btn-secondary-hover: rgba(0, 0, 0, 0.1); --header-height: 3.5rem; --header-accent-height: 0.125rem; @@ -320,17 +323,25 @@ h5:hover .anchor { letter-spacing: 0.5px; white-space: nowrap; line-height: 1; + transition: background .3s, transform .1s; +} +.btn:active { + transform: translate3d(0, .2rem, 0); } .btn-primary { - border: 0.1875rem solid var(--color-brand); background: var(--color-brand); color: #fff; } +.btn-primary:hover { + background: rgba(51, 174, 241, .8) +} .btn-secondary { - border: 0.125rem solid var(--color-text); background: none; color: var(--color-text); } +.btn-secondary:hover { + background: var(--color-btn-secondary-hover); +} .btn-img-left { display: block; float: left; ",7 "diff --git a/packages/wmr/src/lib/prerender.js b/packages/wmr/src/lib/prerender.js @@ -102,6 +102,10 @@ async function workerCode({ cwd, out, publicPath, customRoutes }) { const doPrerender = m.prerender; // const App = m.default || m[Object.keys(m)[0]]; + if (typeof doPrerender !== 'function') { + throw Error(`No prerender() function was exported by the first +``` +::: + ### Drag to upload You can drag your file to a certain area to upload it. ",7 "diff --git a/packages/theme-default/src/color-picker.css b/packages/theme-default/src/color-picker.css height: 180px; @descendent white, black { - cursor: pointer; position: absolute; top: 0; left: 0; } @descendent cursor { - cursor: pointer; position: absolute; > div { ",7 "diff --git a/docs/4.0/components/card.md b/docs/4.0/components/card.md @@ -33,14 +33,14 @@ Below is an example of a basic card with mixed content and a fixed width. Cards Cards support a wide variety of content, including images, text, list groups, links, and more. Below are examples of what's supported. -### Blocks +### Body The building block of a card is the `.card-body`. Use it whenever you need a padded section within a card. {% example html %}
    - This is some text within a card block. + This is some text within a card body.
    {% endexample %} ",7 "diff --git a/scss/_functions.scss b/scss/_functions.scss @function theme-color-level($color-name: ""primary"", $level: 0) { $color: theme-color($color-name); $color-base: if($level > 0, #000, #fff); + $level: abs($level); - @if $level < 0 { - // Lighter values need a quick double negative for the Sass math to work - @return mix($color-base, $color, $level * -1 * $theme-color-interval); - } @else { @return mix($color-base, $color, $level * $theme-color-interval); } -} ",7 "diff --git a/docs/4.0/utilities/display.md b/docs/4.0/utilities/display.md @@ -35,13 +35,13 @@ The media queries effect screen widths with the given breakpoint *or larger*. Fo ## Examples {% example html %} -
    d-inline
    -
    d-inline
    +
    d-inline
    +
    d-inline
    {% endexample %} {% example html %} -d-block -d-block +d-block +d-block {% endexample %} ## Hiding Elements ",7 "diff --git a/build/lint-vars.js b/build/lint-vars.js @@ -44,7 +44,7 @@ function findUnusedVars(dir) { // Array of all Sass variables const variables = sassFilesString.match(/(^\$[a-zA-Z0-9_-]+[^:])/gm) - console.log(`There's a total of ${variables.length} variables.`) + console.log(`Found ${variables.length} total variables.`) // Loop through each variable variables.forEach((variable) => { @@ -52,7 +52,7 @@ function findUnusedVars(dir) { const count = (sassFilesString.match(re) || []).length if (count === 1) { - console.log(`Variable ""${variable}"" is only used once!`) + console.log(`Variable ""${variable}"" is not being used.`) unusedVarsFound = true globalSuccess = false } ",7 "diff --git a/site/docs/4.1/content/tables.md b/site/docs/4.1/content/tables.md @@ -764,8 +764,10 @@ Across every breakpoint, use `.table-responsive` for horizontally scrolling tabl Use `.table-responsive{-sm|-md|-lg|-xl}` as needed to create responsive tables up to a particular breakpoint. From that breakpoint and up, the table will behave normally and not scroll horizontally. -
    +**These tables may appear broken until their responsive styles apply at specific viewport widths.** + {% for bp in site.data.breakpoints %}{% unless bp.breakpoint == ""xs"" %} +
    @@ -818,15 +820,12 @@ Use `.table-responsive{-sm|-md|-lg|-xl}` as needed to create responsive tables u
    -{% endunless %}{% endfor %}
    - {% highlight html %} -{% for bp in site.data.breakpoints %}{% unless bp.breakpoint == ""xs"" %}
    ...
    -{% endunless %}{% endfor %} {% endhighlight %} +{% endunless %}{% endfor %} ",7 "diff --git a/.circleci/config.yml b/.circleci/config.yml @@ -7,7 +7,7 @@ defaults: &defaults default_filters: &default_filters tags: - only: '^v.*' + only: '/v[0-9]+(\.[0-9]+)*/' jobs: install: @@ -139,3 +139,5 @@ workflows: - build filters: <<: *default_filters + branches: + ignore: '/.*/' ",8 "diff --git a/pages/search.js b/pages/search.js @@ -77,7 +77,9 @@ class SearchPage extends React.Component { .filter(([name]) => name !== 'keyword') .map(([name, values]) => ({ name, - values: values.filter(v => !query.facets.some(a => a.name === name && a.value === v.value)) + values: values.filter(v => ( + v.count !== count && !query.facets.some(a => a.name === name && a.value === v.value) + )) })) .filter(group => group.values.length > 1) } ",8 "diff --git a/MaterialSkin/HTML/material/html/js/main.js b/MaterialSkin/HTML/material/html/js/main.js @@ -49,6 +49,9 @@ var app = new Vue({ }, methods: { swipe(ev, direction) { + if (this.$store.state.visibleMenus.size>0) { + return; + } if (this.openDialogs.size>1 || (this.openDialogs.size==1 && (this.$store.state.page=='now-playing' || (!this.openDialogs.has('np-viewer') && !this.openDialogs.has('info-dialog'))))) { ",8 "diff --git a/MaterialSkin/HTML/material/html/js/browse-page.js b/MaterialSkin/HTML/material/html/js/browse-page.js @@ -46,7 +46,7 @@ var lmsBrowse = Vue.component(""lms-browse"", { cancel - home + home arrow_back 1}""> {{headerTitle}} @@ -1266,6 +1266,11 @@ var lmsBrowse = Vue.component(""lms-browse"", { this.fetchingItems = false; }); }, + homeBtnPressed() { + if (this.$store.state.visibleMenus.size<1) { + this.goHome(); + } + }, goHome() { if (this.fetchingItems) { //if (lmsListSource) { @@ -1314,8 +1319,10 @@ var lmsBrowse = Vue.component(""lms-browse"", { } }, backBtnPressed() { + if (this.$store.state.visibleMenus.size<1) { this.lastBackBtnPress = new Date(); this.goBack(); + } }, goBack(refresh) { if (this.fetchingItems) { ",8 "diff --git a/MaterialSkin/HTML/material/html/js/nowplaying-page.js b/MaterialSkin/HTML/material/html/js/nowplaying-page.js @@ -1108,6 +1108,9 @@ var lmsNowPlaying = Vue.component(""lms-now-playing"", { } }, touchStart(event) { + if (event.srcElement.classList.contains(""np-title"") || event.srcElement.classList.contains(""np-text"") || event.srcElement.classList.contains(""np-text-landscape"")) { + return; + } if (this.$store.state.swipeVolume && !this.menu.show && event.touches && event.touches.length>0 && this.playerStatus.dvc) { this.touch={x:event.touches[0].clientX, y:event.touches[0].clientY, moving:false}; this.lastSentVolume=-1; ",8 "diff --git a/MaterialSkin/HTML/material/html/js/browse-functions.js b/MaterialSkin/HTML/material/html/js/browse-functions.js @@ -674,7 +674,9 @@ function browseItemAction(view, act, item, index, event) { if (item.presetParams && item.presetParams.favorites_url) { favUrl = item.presetParams.favorites_url; favIcon = item.presetParams.icon; + if (SECTION_PODCASTS!=item.section) { favType = item.presetParams.favorites_type; + } if (item.presetParams.favorites_title) { favTitle = item.presetParams.favorites_title; } ",8 "diff --git a/MaterialSkin/HTML/material/html/js/server.js b/MaterialSkin/HTML/material/html/js/server.js @@ -496,13 +496,21 @@ var lmsServer = Vue.component('lms-server', { player.model = this.$store.state.player.model; this.isPlaying = player.isplaying; } else { + let found = false; for (var i=0, len=this.$store.state.players.length; i
    ) } ",9 "diff --git a/modules/gui/frontend/src/widget/userAgent.js b/modules/gui/frontend/src/widget/userAgent.js @@ -12,5 +12,5 @@ export const isMobile = () => { return true const dimensions = select('dimensions') - return dimensions.width < 500 || dimensions.height < 500 + return dimensions.width < 500 || (dimensions.height < 500 && dimensions.height > 0) } ",9 "diff --git a/modules/google-earth-engine/docker/src/sepalinternal/radar/__init__.py b/modules/google-earth-engine/docker/src/sepalinternal/radar/__init__.py @@ -11,7 +11,7 @@ class RadarMosaic(ImageSpec): self.spec = spec self.model = spec['recipe']['model'] self.aoi = Aoi.create(spec['recipe']['model']['aoi']) - self.bands = spec['bands'] + self.bands = spec.get('bands', []) self.time_scan = not self.model['dates'].get('targetDate') self.harmonics_dependents = [ dependent ",9 "diff --git a/modules/google-earth-engine/docker/sepal-ee/sepal/ee/rx/drive.py b/modules/google-earth-engine/docker/sepal-ee/sepal/ee/rx/drive.py @@ -3,14 +3,15 @@ from threading import local from apiclient import discovery from apiclient.http import MediaIoBaseDownload -from rx import Callable, concat, from_callable, of, throw -from rx.operators import do_action, flat_map, filter, first, map, reduce, take_while +from rx import Callable, concat, empty, from_callable, of, throw +from rx.operators import do_action, expand, flat_map, filter, first, map, reduce, scan, take_while from sepal.ee.rx import get_credentials from sepal.rx import forever, using_file from sepal.rx.workqueue import WorkQueue CHUNK_SIZE = 10 * 1024 * 1024 +PAGE_SIZE = 100 class Drive(local): @@ -44,15 +45,28 @@ class Drive(local): ) def list_folder(self, folder, name_filter=None): - def action(): + def next_page(acc): + def load_page(): if name_filter: q = ""'{0}' in parents and name = '{1}'"".format(folder['id'], name_filter) else: q = ""'{0}' in parents"".format(folder['id']) - files = self.service.files().list( + page = self.service.files().list( q=q, - fields=""files(id, name, size, mimeType, modifiedTime)"" - ).execute().get('files', []) + fields=""nextPageToken, files(id, name, size, mimeType, modifiedTime)"", + pageSize=PAGE_SIZE, + pageToken=acc.get('nextPageToken')).execute() + return page + + return _execute(load_page, retries=0).pipe( + map(lambda page: { + 'files': acc['files'] + page.get('files', []), + 'nextPageToken': page.get('nextPageToken') + }) + ) + + def extract_files(result): + files = result.get('files', []) for file in files: file['path'] = '{}{}{}'.format( folder['path'], @@ -61,9 +75,10 @@ class Drive(local): ) return files - # TODO: Deal with pagination - - return _execute(action) + return next_page({'files': [], 'nextPageToken': None}).pipe( + expand(lambda acc: next_page(acc) if acc.get('nextPageToken') else empty()), + map(extract_files) + ) def list_folder_recursively(self, folder): def recurse(file): @@ -78,7 +93,7 @@ class Drive(local): return self.list_folder(folder).pipe( flat_map(lambda files: of(*files)), flat_map(recurse), - reduce(lambda acc, files: acc + files, []) + reduce(lambda acc, files: acc + files, []), ) def download(self, file, destination): @@ -125,12 +140,38 @@ class Drive(local): ) return next_destination + def seed_stats(files): + return { + 'progress': 0, + 'total_files': len(files), + 'total_bytes': sum([int(f.get('size', 0)) for f in files]), + 'downloaded_files': 0, + 'downloaded_bytes': 0 + } + + def update_stats(stats, download): + downloaded_files = stats['downloaded_files'] + (0 if download['progress'] < 1 else 1) + downloaded_bytes = stats['downloaded_bytes'] + download['downloaded_bytes'] + progress = downloaded_bytes / stats['total_bytes'] + return { + 'progress': progress, + 'total_files': stats['total_files'], + 'total_bytes': stats['total_bytes'], + 'downloaded_files': downloaded_files, + 'downloaded_bytes': downloaded_bytes + } + if _is_folder(file): return self.list_folder_recursively(file).pipe( - flat_map(lambda files: of(*files)), + flat_map( + lambda files: of(True).pipe( + flat_map(lambda _: of(*files).pipe( filter(lambda f: not _is_folder(f)), - # TODO: Come up with a new destination based on f['path'] and file['path'] difference flat_map(lambda f: self.download(f, get_destination(f))) + )), + scan(update_stats, seed_stats(files)) + ) + ) ) else: return self.download(file, destination) ",9 "diff --git a/modules/google-earth-engine/docker/sepal-ee/sepal/drive/rx/download.py b/modules/google-earth-engine/docker/sepal-ee/sepal/drive/rx/download.py @@ -154,7 +154,7 @@ def download( flat_map( lambda files: combine_latest( *[download_file(f, get_file_destination(f)) for f in files] - ) + ) if files else empty() ), flat_map(aggregate_progress) ) ",9 "diff --git a/modules/sepal-server/src/main/groovy/org/openforis/sepal/component/task/endpoint/TaskEndpoint.groovy b/modules/sepal-server/src/main/groovy/org/openforis/sepal/component/task/endpoint/TaskEndpoint.groovy @@ -98,7 +98,7 @@ class TaskEndpoint { submit(new UpdateTaskProgress( taskId: taskId, state: Task.State.ACTIVE, - statusDescription: description, + statusDescription: toJson(description), username: currentUser.username )) } ",9 "diff --git a/lib/js/shared/src/ee/aoi.js b/lib/js/shared/src/ee/aoi.js @@ -24,12 +24,15 @@ const polygon = ({path}) => const eeTable = ({id, keyColumn, key}) => { const table = ee.FeatureCollection(id) + if (keyColumn) { const filters = [ee.Filter.eq(keyColumn, key)] if (_.isFinite(key)) filters.push(ee.Filter.eq(keyColumn, _.toNumber(key))) - return table .filter(ee.Filter.or(...filters)) + } else { + return table + } } module.exports = {toGeometry, toFeatureCollection} ",9 "diff --git a/modules/gui/frontend/src/app/home/map/tileProvider/monitoringTileProvider.js b/modules/gui/frontend/src/app/home/map/tileProvider/monitoringTileProvider.js +import {BehaviorSubject} from 'rxjs' import {DelegatingTileProvider} from './delegatingTileProvider' -import {Subject} from 'rxjs' -import {finalize, scan} from 'rxjs/operators' +import {debounceTime, finalize} from 'rxjs/operators' export class MonitoringTileProvider extends DelegatingTileProvider { constructor(nextTileProvider, progress$) { - super() - this.nextTileProvider = nextTileProvider - this.requestById = {} - this.pending$ = new Subject() + super(nextTileProvider) + this.pending$ = new BehaviorSubject(0) this.pending$.pipe( - scan((pending, current) => pending += current) + debounceTime(200) ).subscribe( pending => progress$ && progress$.next({loading: pending}) ) - } - - addRequest(requestId) { - this.requestById[requestId] = Date.now() - this.pending$.next(1) - } - - removeRequest(requestId) { - delete this.requestById[requestId] - this.pending$.next(-1) + this.requests = {} } loadTile$(tileRequest) { - const requestId = tileRequest.id - this.addRequest(requestId) - return this.nextTileProvider.loadTile$(tileRequest).pipe( - finalize(() => this.removeRequest(requestId)) + this.pending$.next(this.pending$.value + 1) + return super.loadTile$(tileRequest).pipe( + finalize(() => { + this.requests[tileRequest.id] = true + this.pending$.next(this.pending$.value - 1) + }) ) } - releaseTile(tileElement) { - return this.nextTileProvider.releaseTile(tileElement) + releaseTile(requestId) { + if (!this.requests[requestId]) { + super.releaseTile(requestId) + this.pending$.next(this.pending$.value - 1) + } + delete this.requests[requestId] } } ",9 "diff --git a/modules/gui/frontend/src/app/home/body/process/recipe/opticalMosaic/opticalMosaicRecipe.js b/modules/gui/frontend/src/app/home/body/process/recipe/opticalMosaic/opticalMosaicRecipe.js @@ -107,7 +107,7 @@ export const RecipeActions = id => { } export const getAllVisualizations = recipe => [ - ...Object.values((recipe.layers.userDefinedVisualizations['this-recipe'] || {})), + ...Object.values((selectFrom(recipe, ['layers.userDefinedVisualizations', 'this-recipe']) || {})), ...visualizations[reflectance(recipe)], ...visualizations.indexes, ...(median(recipe) ? visualizations.metadata : []) ",9 "diff --git a/modules/gui/frontend/src/app/home/body/process/recipe/classification/panels/trainingData/sampleClassificationSection.js b/modules/gui/frontend/src/app/home/body/process/recipe/classification/panels/trainingData/sampleClassificationSection.js @@ -152,7 +152,8 @@ class SampleClassificationSection extends Component { } }, error => { - const {response: {defaultMessage, messageKey, messageArgs} = {}} = error + const response = error.response || {} + const {defaultMessage, messageKey, messageArgs} = response this.props.inputs.assetToSample.setInvalid( messageKey ? msg(messageKey, messageArgs, defaultMessage) ",9 "diff --git a/modules/gateway/docker/src/proxy.js b/modules/gateway/docker/src/proxy.js @@ -20,14 +20,15 @@ const logLevel = sepalLogLevel === 'trace' : sepalLogLevel const proxy = app => - ({path, target, authenticate, cache, noCache, rewrite}) => { - const proxyMiddleware = createProxyMiddleware({ + ({path, target, prefix, authenticate, cache, noCache, rewrite}) => { + const proxyMiddleware = createProxyMiddleware(path, { target, logProvider, logLevel, proxyTimeout: 0, timeout: 0, pathRewrite: {[`^${path}`]: ''}, + ignorePath: !prefix, changeOrigin: true, ws: true, onOpen: () => { @@ -42,10 +43,10 @@ const proxy = app => onProxyReq: (proxyReq, req) => { const user = req.session.user const username = user ? user.username : 'not-authenticated' - req.socket.on('close', () => { - log.trace(`[${username}] [${req.originalUrl}] Response closed`) - proxyReq.destroy() - }) + // req.socket.on('close', () => { + // log.trace(`[${username}] [${req.originalUrl}] Response closed`) + // proxyReq.destroy() + // }) if (authenticate && user) { log.trace(`[${username}] [${req.originalUrl}] Setting sepal-user header`) proxyReq.setHeader('sepal-user', JSON.stringify(user)) @@ -81,5 +82,3 @@ const proxy = app => } module.exports = {proxyEndpoints} - -// TODO: Non-prefix endpoints ",9 "diff --git a/modules/gui/frontend/src/sources.js b/modules/gui/frontend/src/sources.js @@ -37,7 +37,7 @@ export const getAvailableBands = ({ include = ['class', 'regression', 'class_probability', 'probabilities'] } = {} }) => { - const dataSetIds = dataSets || [dataSetId] + const dataSetIds = dataSets || dataSetId ? [dataSetId] : [] const dataSetBands = Object.keys( dataSetIds.find(dataSetId => isOpticalDataSet(dataSetId)) ? getAvailableOpticalBands( @@ -63,7 +63,7 @@ export const groupedBandOptions = ({ include = ['class', 'regression', 'class_probability', 'probabilities'] } = {} }) => { - const dataSetIds = dataSets || [dataSetId] + const dataSetIds = dataSets || dataSetId ? [dataSetId] : [] const dataSetOptions = dataSetIds.find(dataSetId => isOpticalDataSet(dataSetId)) ? getGroupedOpticalBandOptions( toOpticalRecipe({dataSetIds, corrections}), ",9 "diff --git a/modules/sepal-server/src/main/groovy/org/openforis/sepal/component/hostingservice/aws/AwsInstanceProvider.groovy b/modules/sepal-server/src/main/groovy/org/openforis/sepal/component/hostingservice/aws/AwsInstanceProvider.groovy @@ -62,8 +62,13 @@ final class AwsInstanceProvider implements InstanceProvider { LOG.debug(""Getting instance $instance.id to see if the public ID is assigned yet, "" + ""instanceType: $instanceType, reservation: $reservation"") + try { instance = getInstance(instance.id) LOG.debug(""Got instance $instance"") + } catch (AmazonEC2Exception ignore) { + // Instance might not be available straight away + LOG.warn(""Failed to get instance $instance.id. Will still keep on waiting for it to become available."") + } Thread.sleep(1000) } if (!instance.host) @@ -256,17 +261,17 @@ final class AwsInstanceProvider implements InstanceProvider { private void tagInstance(String instanceId, Collection... tagCollections) { try { - retry(10) { + retry(10, ({ def tags = tagCollections.toList().flatten() as Tag[] LOG.info(""Tagging instance $instanceId with $tags"") def request = new CreateTagsRequest() .withResources(instanceId) .withTags(tags) client.createTags(request) - } + } as Closure)) } catch (Exception e) { - terminate() - throw new FailedToTagInstance(""Failed to tag instance $instanceId with $tags"", e) + terminate(instanceId) + throw new FailedToTagInstance(""Failed to tag instance $instanceId with $tagCollections"", e) } } @@ -285,7 +290,7 @@ final class AwsInstanceProvider implements InstanceProvider { } } - private int backoff(int retries) { + private void backoff(int retries) { def millis = (long) Math.pow(2, retries ?: 0) * 1000 Thread.sleep(millis) } ",9 "diff --git a/modules/gui/frontend/src/app/home/body/process/recipe/classChange/panels/inputImage/imageForm.js b/modules/gui/frontend/src/app/home/body/process/recipe/classChange/panels/inputImage/imageForm.js @@ -26,7 +26,9 @@ class ImageForm extends Component { {React.createElement(inputComponent, { input, onLoading: () => { + band.set(null) bands.set({}) + legendEntries.set(null) }, onLoaded: ({id, bands, metadata, visualizations, recipe}) => this.onLoaded(id, bands, metadata, visualizations, recipe) })} @@ -81,7 +83,11 @@ class ImageForm extends Component { const bandNames = Object.keys(loadedBands) const selectedBand = band.value if (!selectedBand || !bandNames.includes(selectedBand)) { - const defaultBand = bandNames.find(bandName => loadedBands[bandName].values.length) + const defaultBand = bandNames + .find(bandName => { + const values = loadedBands[bandName].values + return values && values.length + }) || bandNames[0] band.set(defaultBand) } ",9 "diff --git a/modules/gui/frontend/src/app/home/body/process/recipe/recipeImageLayerSource.js b/modules/gui/frontend/src/app/home/body/process/recipe/recipeImageLayerSource.js @@ -54,7 +54,7 @@ class _RecipeImageLayerSource extends React.Component { const {currentUserDefinedVisualizations, recipeId, source, recipeActionBuilder} = this.props const description = toDescription(recipe) if (recipeId !== source.sourceConfig.recipeId) { - const userDefinedVisualizations = selectFrom(recipe, 'layers.userDefinedVisualizations.this-recipe') + const userDefinedVisualizations = selectFrom(recipe, 'layers.userDefinedVisualizations.this-recipe') || [] const currentVisualizationIds = currentUserDefinedVisualizations.map(({id}) => id) userDefinedVisualizations .reduce( ",9 "diff --git a/modules/gee/src/jobs/ee/ccdc/loadSegments.js b/modules/gee/src/jobs/ee/ccdc/loadSegments.js @@ -27,7 +27,10 @@ const worker$ = ({recipe, latLng, bands}) => { ) const assetSegments$ = () => - of(new ee.Image(recipe.id)) + imageFactory({ + type: 'ASSET', + id: recipe.id + }).getImage$() const recipeRef$ = () => imageFactory(recipe, {selection: bands}).getRecipe$() ",9 "diff --git a/modules/gui/src/app/home/map/imageLayerSource/planetImageLayer.js b/modules/gui/src/app/home/map/imageLayerSource/planetImageLayer.js @@ -166,9 +166,13 @@ class _PlanetImageLayer extends React.Component { ) return filtered.length ? this.selectUrlTemplate(filtered[0].urlTemplate) - : this.selectUrlTemplate(mosaics[0].urlTemplate) + : mosaics.length + ? this.selectUrlTemplate(mosaics[0].urlTemplate) + : null } else { - return this.selectUrlTemplate(mosaics[0].urlTemplate) + return mosaics.length + ? this.selectUrlTemplate(mosaics[0].urlTemplate) + : null } } ",9 "diff --git a/packages/vega-scenegraph/src/render/svg/SVGRenderer.js b/packages/vega-scenegraph/src/render/svg/SVGRenderer.js @@ -192,23 +192,31 @@ prototype._dirtyCheck = function(items) { if (!items) return true; var id = ++this._dirtyID, - item, mark, mdef, i, n; + item, mark, mdef, i, n, o; for (i=0, n=items.length; i new Promise((resolve, reject) => { +const launchAndroidSimulator = (c, platform, target, isIndependentThread = false) => { logTask(`launchAndroidSimulator:${platform}:${target}`); if (target === '?' || target === undefined || target === '') { - _listAndroidTargets(c, true, false) + return _listAndroidTargets(c, true, false) .then((devicesArr) => { let devicesString = '\n'; @@ -56,39 +56,25 @@ const launchAndroidSimulator = (c, platform, target, isIndependentThread = false if (isIndependentThread) { // const child = require('child_process').spawn(c.cli[CLI_ANDROID_EMULATOR], [ // '-avd', `""${selectedDevice.name}""`]); - execCLI(c, CLI_ANDROID_EMULATOR, `-avd ""${selectedDevice.name}""`); - resolve(); - } else { - execCLI(c, CLI_ANDROID_EMULATOR, `-avd ""${selectedDevice.name}""`) - .then(() => resolve()) - .catch(e => reject(e)); + return execCLI(c, CLI_ANDROID_EMULATOR, `-avd ""${selectedDevice.name}""`).catch(logError); } - } else { - logError(`Wrong choice ${v}! Ingoring`); + return execCLI(c, CLI_ANDROID_EMULATOR, `-avd ""${selectedDevice.name}""`); } + logError(`Wrong choice ${v}! Ingoring`); + }); }); - }) - .catch(e => reject(e)); - - return; } if (target) { if (isIndependentThread) { // const child = require('child_process').spawn(c.cli[CLI_ANDROID_EMULATOR], [ // '-avd', `""${target}""`]); - execCLI(c, CLI_ANDROID_EMULATOR, `-avd ""${target}""`); - resolve(); - } else { - execCLI(c, CLI_ANDROID_EMULATOR, `-avd ""${target}""`) - .then(() => resolve()) - .catch(e => reject(e)); + return execCLI(c, CLI_ANDROID_EMULATOR, `-avd ""${target}""`).catch(logError); } - - return; + return execCLI(c, CLI_ANDROID_EMULATOR, `-avd ""${target}""`); } - reject('No simulator -t target name specified!'); -}); + return Promise.reject('No simulator -t target name specified!'); +}; const listAndroidTargets = c => new Promise((resolve, reject) => { logTask('listAndroidTargets'); @@ -212,14 +198,16 @@ const _askForNewEmulator = (c, platform) => new Promise((resolve, reject) => { ); }); -const _createEmulator = (c, apiVersion, emuPlatform, emuName) => new Promise((resolve, reject) => { +const _createEmulator = (c, apiVersion, emuPlatform, emuName) => { logTask('_createEmulator'); - return execCLI(c, CLI_ANDROID_SDKMANAGER, `""system-images;android-${apiVersion};${emuPlatform};x86""`).then(() => execCLI( + return execCLI(c, CLI_ANDROID_SDKMANAGER, `""system-images;android-${apiVersion};${emuPlatform};x86""`) + .then(() => execCLI( c, CLI_ANDROID_AVDMANAGER, `create avd -n ${emuName} -k ""system-images;android-${apiVersion};${emuPlatform};x86"" `, - )); -}); + )) + .catch(e => logError(e, true)); +}; const copyAndroidAssets = (c, platform) => new Promise((resolve) => { logTask('copyAndroidAssets'); ",9 "diff --git a/server/persistence/login.go b/server/persistence/login.go package persistence import ( + ""context"" ""encoding/base64"" ""fmt"" + ""sync"" ""github.com/lestrrat-go/jwx/jwk"" ""github.com/offen/offen/server/keys"" @@ -274,11 +276,26 @@ func (p *persistenceLayer) findAccountUser(emailAddress string, includeRelations } func selectAccountUser(available []AccountUser, email string) (*AccountUser, error) { - // TODO: run this concurrently without leaking goroutines - for _, accountUser := range available { + ctx, cancel := context.WithCancel(context.Background()) + match := make(chan AccountUser) + wg := sync.WaitGroup{} + for _, a := range available { + wg.Add(1) + go func(accountUser AccountUser) { if err := keys.CompareString(email, accountUser.HashedEmail); err == nil { - return &accountUser, nil - } - } + match <- accountUser + } + wg.Done() + }(a) + } + go func() { + wg.Wait() + cancel() + }() + select { + case result := <-match: + return &result, nil + case <-ctx.Done(): return nil, fmt.Errorf(""persistence: no account user found for %s"", email) } +} ",9 "diff --git a/src/commands/watch.js b/src/commands/watch.js @@ -43,6 +43,8 @@ export default asyncCommand({ async handler(argv) { argv.production = false; + if (process.env.HTTPS) argv.https = true; + if (argv.https) { let ssl = await getSslCert(); if (!ssl) { ",9 "diff --git a/html/src/app.js b/html/src/app.js @@ -1863,9 +1863,12 @@ speechSynthesis.getVoices(); } */ API.getInstanceShortName = function (params) { - return this.call(`instances/${params.worldId}:${params.instanceId}/shortName`, { + return this.call( + `instances/${params.worldId}:${params.instanceId}/shortName`, + { method: 'GET' - }).then((json) => { + } + ).then((json) => { var args = { json, params @@ -6952,7 +6955,9 @@ speechSynthesis.getVoices(); $app.data.showUserDialogHistory = new Set(); $app.methods.quickSearchUserHistory = function () { - var userHistory = Array.from(this.showUserDialogHistory.values()).reverse().slice(0, 5); + var userHistory = Array.from(this.showUserDialogHistory.values()) + .reverse() + .slice(0, 5); var results = []; userHistory.forEach((userId) => { var ref = API.cachedUsers.get(userId); @@ -10183,16 +10188,23 @@ speechSynthesis.getVoices(); var input = instance.inputValue; var testUrl = input.substring(0, 15); if (testUrl === 'https://vrch.at') { - AppApi.FollowUrl(input).then((url) => { + AppApi.FollowUrl(input).then((output) => { + var url = output; // /home/launch?worldId=wrld_f20326da-f1ac-45fc-a062-609723b097b1&instanceId=33570~region(jp)&shortName=cough-stockinglinz-ddd26 // https://vrch.at/wrld_f20326da-f1ac-45fc-a062-609723b097b1 - if (url.substring(0, 18) === 'https://vrchat.com') { + if ( + url.substring(0, 18) === + 'https://vrchat.com' + ) { url = url.substring(18); } if (url.substring(0, 13) === '/home/launch?') { - var urlParams = new URLSearchParams(url.substring(13)); + var urlParams = new URLSearchParams( + url.substring(13) + ); var worldId = urlParams.get('worldId'); - var instanceId = urlParams.get('instanceId'); + var instanceId = + urlParams.get('instanceId'); if (instanceId) { var location = `${worldId}:${instanceId}`; this.showWorldDialog(location); @@ -12721,7 +12733,10 @@ speechSynthesis.getVoices(); } D.url = getLaunchURL(L.worldId, L.instanceId); D.visible = true; - API.getInstanceShortName({worldId: L.worldId, instanceId: L.instanceId}); + API.getInstanceShortName({ + worldId: L.worldId, + instanceId: L.instanceId + }); }; $app.methods.locationToLaunchArg = function (location) { ",9 "diff --git a/src/browser/errorParser.js b/src/browser/errorParser.js @@ -61,7 +61,9 @@ function Stack(exception) { } var name = exception.constructor && exception.constructor.name; - name = name || exception.name; + if (!name || !name.length || name.length < 3) { + name = exception.name; + } return { stack: getStack(), ",9 "diff --git a/src/server/rollbar.js b/src/server/rollbar.js @@ -263,8 +263,15 @@ Rollbar.errorHandler = function() { }; Rollbar.prototype.lambdaHandler = function(handler, timeoutHandler) { + if (handler.length <= 2) { + return this.asyncLambdaHandler(handler, timeoutHandler); + } + return this.syncLambdaHandler(handler, timeoutHandler); +}; + +Rollbar.prototype.asyncLambdaHandler = function(handler, timeoutHandler) { var self = this; - var _timeoutHandler = function(event, context, cb) { + var _timeoutHandler = function(event, context) { var message = 'Function timed out'; var custom = { originalEvent: event, @@ -273,25 +280,43 @@ Rollbar.prototype.lambdaHandler = function(handler, timeoutHandler) { self.error(message, custom); }; var shouldReportTimeouts = self.options.captureLambdaTimeouts; - return function(event, context, callback) { + return function(event, context) { + return new Promise(function(resolve, reject) { self.lambdaContext = context; if (shouldReportTimeouts) { - var timeoutCb = (timeoutHandler || _timeoutHandler).bind(null, event, context, callback); + var timeoutCb = (timeoutHandler || _timeoutHandler).bind(null, event, context); self.lambdaTimeoutHandle = setTimeout(timeoutCb, context.getRemainingTimeInMillis() - 1000); } - try { - if (handler.length <= 2) { - // handler is async handler(event, context) - .then(function(resp) { return callback(null, resp); }) + .then(function(resp) { resolve(resp); }) .catch(function(err) { self.error(err); self.wait(function() { clearTimeout(self.lambdaTimeoutHandle); - callback(err); + reject(err); }); }); - } else { + }); + }; +}; +Rollbar.prototype.syncLambdaHandler = function(handler, timeoutHandler) { + var self = this; + var _timeoutHandler = function(event, context, cb) { + var message = 'Function timed out'; + var custom = { + originalEvent: event, + originalRequestId: context.awsRequestId, + }; + self.error(message, custom); + }; + var shouldReportTimeouts = self.options.captureLambdaTimeouts; + return function(event, context, callback) { + self.lambdaContext = context; + if (shouldReportTimeouts) { + var timeoutCb = (timeoutHandler || _timeoutHandler).bind(null, event, context, callback); + self.lambdaTimeoutHandle = setTimeout(timeoutCb, context.getRemainingTimeInMillis() - 1000); + } + try { handler(event, context, function(err, resp) { if (err) { self.error(err); @@ -301,7 +326,6 @@ Rollbar.prototype.lambdaHandler = function(handler, timeoutHandler) { callback(err, resp); }); }); - } } catch (err) { self.error(err); self.wait(function() { ",9 "diff --git a/bin/cordova b/bin/cordova @@ -26,7 +26,8 @@ const cli = require('../src/cli'); cli(process.argv).catch(err => { if (!(err instanceof Error)) { - throw new CordovaError('Promise rejected with non-error: ' + util.inspect(err)); + const errorOutput = typeof err === 'string' ? err : util.inspect(err); + throw new CordovaError('Promise rejected with non-error: ' + errorOutput); } process.exitCode = err.code || 1; ",9 "diff --git a/scss/_functions.scss b/scss/_functions.scss @@ -181,6 +181,14 @@ $_luminance-list: .0008 .001 .0011 .0013 .0015 .0017 .002 .0022 .0025 .0027 .003 @return $value1 + $value2; } + @if type-of($value1) != number { + $value1: unquote(""("") + $value1 + unquote("")""); + } + + @if type-of($value2) != number { + $value2: unquote(""("") + $value2 + unquote("")""); + } + @return if($return-calc == true, calc(#{$value1} + #{$value2}), $value1 + unquote("" + "") + $value2); } @@ -201,5 +209,13 @@ $_luminance-list: .0008 .001 .0011 .0013 .0015 .0017 .002 .0022 .0025 .0027 .003 @return $value1 - $value2; } + @if type-of($value1) != number { + $value1: unquote(""("") + $value1 + unquote("")""); + } + + @if type-of($value2) != number { + $value2: unquote(""("") + $value2 + unquote("")""); + } + @return if($return-calc == true, calc(#{$value1} - #{$value2}), $value1 + unquote("" - "") + $value2); } ",9 "diff --git a/modules/helpers/modifiers.js b/modules/helpers/modifiers.js @@ -71,7 +71,7 @@ export default class ModifierHelpers { }); } } - } else if (item.type === ""forcepower"" || item.type === ""specialization"") { + } else if (item.type === ""forcepower"" || item.type === ""specialization"" || item.type === ""signatureability"") { // apply basic force power/specialization modifiers if (attrsToApply.length > 0) { attrsToApply.forEach((attr) => { @@ -89,7 +89,7 @@ export default class ModifierHelpers { }); } let upgrades; - if (item.type === ""forcepower"") { + if (item.type === ""forcepower"" || item.type === ""signatureability"") { // apply force power upgrades upgrades = Object.keys(item.data.upgrades) .filter((k) => item.data.upgrades[k].islearned) ",9 "diff --git a/modules/ffg-destiny-tracker.js b/modules/ffg-destiny-tracker.js @@ -101,7 +101,7 @@ export default class DestinyTracker extends FormApplication { const pointType = event.currentTarget.dataset.group; var typeName = null; const add = event.shiftKey; - const remove = event.ctrlKey; + const remove = event.ctrlKey || event.metaKey; var flipType = null; var actionType = null; if (pointType == ""dPoolLight"") { ",9 "diff --git a/src/text-editor-component.js b/src/text-editor-component.js @@ -29,6 +29,9 @@ class TextEditorComponent { this.horizontalPixelPositionsByScreenLineId = new Map() // Values are maps from column to horiontal pixel positions this.lineNodesByScreenLineId = new Map() this.textNodesByScreenLineId = new Map() + this.lastKeydown = null + this.lastKeydownBeforeKeypress = null + this.openedAccentedCharacterMenu = false this.cursorsToRender = [] if (this.props.model) this.observeModel() @@ -350,7 +353,13 @@ class TextEditorComponent { ref: 'hiddenInput', key: 'hiddenInput', className: 'hidden-input', - on: {blur: this.didBlur}, + on: { + blur: this.didBlur, + textInput: this.didTextInput, + keydown: this.didKeydown, + keyup: this.didKeyup, + keypress: this.didKeypress + }, tabIndex: -1, style: { position: 'absolute', @@ -491,6 +500,72 @@ class TextEditorComponent { } } + didTextInput (event) { + event.stopPropagation() + + // WARNING: If we call preventDefault on the input of a space character, + // then the browser interprets the spacebar keypress as a page-down command, + // causing spaces to scroll elements containing editors. This is impossible + // to test. + if (event.data !== ' ') event.preventDefault() + + // if (!this.isInputEnabled()) return + + // Workaround of the accented character suggestion feature in macOS. This + // will only occur when the user is not composing in IME mode. When the user + // selects a modified character from the macOS menu, `textInput` will occur + // twice, once for the initial character, and once for the modified + // character. However, only a single keypress will have fired. If this is + // the case, select backward to replace the original character. + if (this.openedAccentedCharacterMenu) { + this.getModel().selectLeft() + this.openedAccentedCharacterMenu = false + } + + this.getModel().insertText(event.data, {groupUndo: true}) + } + + // We need to get clever to detect when the accented character menu is + // opened on macOS. Usually, every keydown event that could cause input is + // followed by a corresponding keypress. However, pressing and holding + // long enough to open the accented character menu causes additional keydown + // events to fire that aren't followed by their own keypress and textInput + // events. + // + // Therefore, we assume the accented character menu has been deployed if, + // before observing any keyup event, we observe events in the following + // sequence: + // + // keydown(keyCode: X), keypress, keydown(keyCode: X) + // + // The keyCode X must be the same in the keydown events that bracket the + // keypress, meaning we're *holding* the _same_ key we intially pressed. + // Got that? + didKeydown (event) { + if (this.lastKeydownBeforeKeypress != null) { + if (this.lastKeydownBeforeKeypress.keyCode === event.keyCode) { + this.openedAccentedCharacterMenu = true + } + this.lastKeydownBeforeKeypress = null + } else { + this.lastKeydown = event + } + } + + didKeypress () { + this.lastKeydownBeforeKeypress = this.lastKeydown + this.lastKeydown = null + + // This cancels the accented character behavior if we type a key normally + // with the menu open. + this.openedAccentedCharacterMenu = false + } + + didKeyup () { + this.lastKeydownBeforeKeypress = null + this.lastKeydown = null + } + performInitialMeasurements () { this.measurements = {} this.staleMeasurements = {} @@ -628,7 +703,9 @@ class TextEditorComponent { observeModel () { const {model} = this.props - this.disposables.add(model.selectionsMarkerLayer.onDidUpdate(this.scheduleUpdate.bind(this))) + const scheduleUpdate = this.scheduleUpdate.bind(this) + this.disposables.add(model.selectionsMarkerLayer.onDidUpdate(scheduleUpdate)) + this.disposables.add(model.displayLayer.onDidChangeSync(scheduleUpdate)) } isVisible () { ",9 "diff --git a/src/text-editor-component.js b/src/text-editor-component.js @@ -36,7 +36,7 @@ class TextEditorComponent { this.previousScrollHeight = 0 this.lastKeydown = null this.lastKeydownBeforeKeypress = null - this.openedAccentedCharacterMenu = false + this.accentedCharacterMenuIsOpen = false this.decorationsToRender = { lineNumbers: new Map(), lines: new Map(), @@ -368,7 +368,10 @@ class TextEditorComponent { textInput: this.didTextInput, keydown: this.didKeydown, keyup: this.didKeyup, - keypress: this.didKeypress + keypress: this.didKeypress, + compositionstart: this.didCompositionStart, + compositionupdate: this.didCompositionUpdate, + compositionend: this.didCompositionEnd }, tabIndex: -1, style: { @@ -643,17 +646,12 @@ class TextEditorComponent { // to test. if (event.data !== ' ') event.preventDefault() + // TODO: Deal with disabled input // if (!this.isInputEnabled()) return - // Workaround of the accented character suggestion feature in macOS. This - // will only occur when the user is not composing in IME mode. When the user - // selects a modified character from the macOS menu, `textInput` will occur - // twice, once for the initial character, and once for the modified - // character. However, only a single keypress will have fired. If this is - // the case, select backward to replace the original character. - if (this.openedAccentedCharacterMenu) { - this.getModel().selectLeft() - this.openedAccentedCharacterMenu = false + if (this.compositionCheckpoint) { + this.getModel().revertToCheckpoint(this.compositionCheckpoint) + this.compositionCheckpoint = null } this.getModel().insertText(event.data, {groupUndo: true}) @@ -678,7 +676,8 @@ class TextEditorComponent { didKeydown (event) { if (this.lastKeydownBeforeKeypress != null) { if (this.lastKeydownBeforeKeypress.keyCode === event.keyCode) { - this.openedAccentedCharacterMenu = true + this.accentedCharacterMenuIsOpen = true + this.getModel().selectLeft() } this.lastKeydownBeforeKeypress = null } else { @@ -686,20 +685,44 @@ class TextEditorComponent { } } - didKeypress () { + didKeypress (event) { this.lastKeydownBeforeKeypress = this.lastKeydown this.lastKeydown = null // This cancels the accented character behavior if we type a key normally // with the menu open. - this.openedAccentedCharacterMenu = false + this.accentedCharacterMenuIsOpen = false } - didKeyup () { + didKeyup (event) { this.lastKeydownBeforeKeypress = null this.lastKeydown = null } + // The IME composition events work like this: + // + // User types 's', chromium pops up the completion helper + // 1. compositionstart fired + // 2. compositionupdate fired; event.data == 's' + // User hits arrow keys to move around in completion helper + // 3. compositionupdate fired; event.data == 's' for each arry key press + // User escape to cancel + // 4. compositionend fired + // OR User chooses a completion + // 4. compositionend fired + // 5. textInput fired; event.data == the completion string + didCompositionStart (event) { + this.compositionCheckpoint = this.getModel().createCheckpoint() + } + + didCompositionUpdate (event) { + this.getModel().insertText(event.data, {select: true}) + } + + didCompositionEnd (event) { + event.target.value = '' + } + didRequestAutoscroll (autoscroll) { this.pendingAutoscroll = autoscroll this.scheduleUpdate() ",9 "diff --git a/script/lib/generate-startup-snapshot.js b/script/lib/generate-startup-snapshot.js @@ -43,6 +43,9 @@ module.exports = function (packagedAppPath) { relativePath == path.join('..', 'node_modules', 'glob', 'glob.js') || relativePath == path.join('..', 'node_modules', 'graceful-fs', 'graceful-fs.js') || relativePath == path.join('..', 'node_modules', 'htmlparser2', 'lib', 'index.js') || + relativePath == path.join('..', 'node_modules', 'markdown-preview', 'node_modules', 'htmlparser2', 'lib', 'index.js') || + relativePath == path.join('..', 'node_modules', 'roaster', 'node_modules', 'htmlparser2', 'lib', 'index.js') || + relativePath == path.join('..', 'node_modules', 'task-lists', 'node_modules', 'htmlparser2', 'lib', 'index.js') || relativePath == path.join('..', 'node_modules', 'iconv-lite', 'encodings', 'index.js') || relativePath == path.join('..', 'node_modules', 'less', 'index.js') || relativePath == path.join('..', 'node_modules', 'less', 'lib', 'less', 'fs.js') || ",9 "diff --git a/src/grammar-registry.js b/src/grammar-registry.js @@ -236,7 +236,7 @@ class GrammarRegistry extends FirstMate.GrammarRegistry { grammarForLanguageName (languageName) { const lowercaseLanguageName = languageName.toLowerCase() - return this.getGrammars().find(grammar => grammar.name.toLowerCase() === lowercaseLanguageName) + return this.getGrammars().find(({name}) => name && name.toLowerCase() === lowercaseLanguageName) } grammarAddedOrUpdated (grammar) { ",9 "diff --git a/src/ipc-helpers.js b/src/ipc-helpers.js @@ -3,6 +3,8 @@ let ipcRenderer = null let ipcMain = null let BrowserWindow = null +let nextResponseChannelId = 0 + exports.on = function (emitter, eventName, callback) { emitter.on(eventName, callback) return new Disposable(() => emitter.removeListener(eventName, callback)) @@ -14,7 +16,7 @@ exports.call = function (channel, ...args) { ipcRenderer.setMaxListeners(20) } - const responseChannel = getResponseChannel(channel) + const responseChannel = `ipc-helpers-response-${nextResponseChannelId++}` return new Promise(resolve => { ipcRenderer.on(responseChannel, (event, result) => { @@ -22,7 +24,7 @@ exports.call = function (channel, ...args) { resolve(result) }) - ipcRenderer.send(channel, ...args) + ipcRenderer.send(channel, responseChannel, ...args) }) } @@ -33,15 +35,9 @@ exports.respondTo = function (channel, callback) { BrowserWindow = electron.BrowserWindow } - const responseChannel = getResponseChannel(channel) - - return exports.on(ipcMain, channel, async (event, ...args) => { + return exports.on(ipcMain, channel, async (event, responseChannel, ...args) => { const browserWindow = BrowserWindow.fromWebContents(event.sender) const result = await callback(browserWindow, ...args) event.sender.send(responseChannel, result) }) } - -function getResponseChannel (channel) { - return 'ipc-helpers-' + channel + '-response' -} ",9 "diff --git a/src/menu-helpers.js b/src/menu-helpers.js @@ -26,7 +26,7 @@ function merge (menu, item, itemSpecificity = Infinity) { for (let submenuItem of item.submenu) { merge(matchingItem.submenu, submenuItem, itemSpecificity) } - } else if (itemSpecificity >= ItemSpecificities.get(matchingItem)) { + } else if (itemSpecificity && itemSpecificity >= ItemSpecificities.get(matchingItem)) { menu[matchingItemIndex] = item } } ",9 "diff --git a/src/workspace.js b/src/workspace.js @@ -507,10 +507,13 @@ module.exports = class Workspace extends Model { // It's important to call handleGrammarUsed after emitting the did-add event: // if we activate a package between adding the editor to the registry and emitting // the package may receive the editor twice from `observeTextEditors`. + // (Note that the item can be destroyed by an `observeTextEditors` handler.) + if (!item.isDestroyed()) { subscriptions.add( item.observeGrammar(this.handleGrammarUsed.bind(this)) ) } + } }) } ",9 "diff --git a/script/lib/generate-startup-snapshot.js b/script/lib/generate-startup-snapshot.js @@ -37,6 +37,7 @@ module.exports = function (packagedAppPath) { requiredModuleRelativePath.endsWith(path.join('node_modules', 'minimatch', 'minimatch.js')) || requiredModuleRelativePath.endsWith(path.join('node_modules', 'request', 'index.js')) || requiredModuleRelativePath.endsWith(path.join('node_modules', 'request', 'request.js')) || + requiredModuleRelativePath.endsWith(path.join('node_modules', 'temp', 'lib', 'temp.js')) || requiredModuleRelativePath === path.join('..', 'exports', 'atom.js') || requiredModuleRelativePath === path.join('..', 'src', 'electron-shims.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'atom-keymap', 'lib', 'command-event.js') || @@ -60,7 +61,6 @@ module.exports = function (packagedAppPath) { requiredModuleRelativePath === path.join('..', 'node_modules', 'spelling-manager', 'node_modules', 'natural', 'lib', 'natural', 'index.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'tar', 'tar.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'ls-archive', 'node_modules', 'tar', 'tar.js') || - requiredModuleRelativePath === path.join('..', 'node_modules', 'temp', 'lib', 'temp.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'tmp', 'lib', 'tmp.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'tree-sitter', 'index.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'yauzl', 'index.js') || ",9 "diff --git a/src/panel-container-element.js b/src/panel-container-element.js @@ -54,7 +54,7 @@ class PanelContainerElement extends HTMLElement { if (visible) { this.hideAllPanelsExcept(panel) } })) - if (panel.autoFocus !== false) { + if (panel.autoFocus) { const focusOptions = { // focus-trap will attempt to give focus to the first tabbable element // on activation. If there aren't any tabbable elements, ",9 "diff --git a/v3/src/input/components/PointWithinGameObject.js b/v3/src/input/components/PointWithinGameObject.js @@ -8,6 +8,10 @@ var PointWithinGameObject = function (gameObject, x, y) return false; } + // Normalize the origin + x += gameObject.displayOriginX; + y += gameObject.displayOriginY; + return gameObject.hitAreaCallback(gameObject.hitArea, x, y); }; ",9 "diff --git a/v3/src/loader/filetypes/AudioFile.js b/v3/src/loader/filetypes/AudioFile.js @@ -14,7 +14,7 @@ var AudioFile = new Class({ function AudioFile (key, url, path, xhrSettings, soundManager) { - this.sound = soundManager; + this.soundManager = soundManager; var fileConfig = { type: 'audio', @@ -33,12 +33,28 @@ var AudioFile = new Class({ { this.state = CONST.FILE_PROCESSING; - // TODO handle decoding - this.data = this.xhrLoader.response; + var _this = this; - this.onComplete(); + // interesting read https://github.com/WebAudio/web-audio-api/issues/1305 + this.soundManager.context.decodeAudioData(this.xhrLoader.response, + function (audioBuffer) + { + this.data = audioBuffer; + + _this.onComplete(); - callback(this); + callback(_this); + }, + function (e) + { + // TODO properly log decoding error + console.error('Error with decoding audio data for \'' + this.key + '\':', e.message); + + _this.state = CONST.FILE_ERRORED; + + callback(_this); + } + ); } }); ",9 "diff --git a/v3/src/sound/BaseSound.js b/v3/src/sound/BaseSound.js @@ -114,6 +114,10 @@ var BaseSound = new Class({ }, play: function (marker, config) { if (marker === void 0) { marker = ''; } + if (typeof marker === 'object') { + config = marker; + marker = ''; + } if (typeof marker !== 'string') { console.error('Sound marker name has to be a string!'); return null; ",9 "diff --git a/v3/src/sound/webaudio/WebAudioSound.js b/v3/src/sound/webaudio/WebAudioSound.js @@ -65,18 +65,25 @@ var WebAudioSound = new Class({ this.source.buffer = this.audioBuffer; this.source.connect(this.muteNode); this.applyConfig(); - this.source.start(); + this.source.start(0, 0, this.currentConfig.duration); this.startTime = this.manager.context.currentTime; this.pausedTime = 0; return this; }, pause: function () { BaseSound.prototype.pause.call(this); + this.source.stop(); + this.source = null; this.pausedTime = this.manager.context.currentTime - this.startTime; return this; }, resume: function () { BaseSound.prototype.resume.call(this); + this.source = this.manager.context.createBufferSource(); + this.source.buffer = this.audioBuffer; + this.source.connect(this.muteNode); + this.applyConfig(); + this.source.start(0, this.pausedTime, this.currentConfig.duration - this.pausedTime); this.startTime = this.manager.context.currentTime - this.pausedTime; this.pausedTime = 0; return this; ",9 "diff --git a/v3/src/gameobjects/text/static/Text.js b/v3/src/gameobjects/text/static/Text.js @@ -4,6 +4,7 @@ var Class = require('../../../utils/Class'); var Components = require('../../components'); var GameObject = require('../../GameObject'); var GetTextSize = require('../GetTextSize'); +var GetValue = require('../../../utils/object/GetValue'); var RemoveFromDOM = require('../../../dom/RemoveFromDOM'); var TextRender = require('./TextRender'); var TextStyle = require('../TextStyle'); @@ -68,10 +69,10 @@ var Text = new Class({ /** * Specify a padding value which is added to the line width and height when calculating the Text size. - * Allows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. + * Allows you to add extra spacing if the browser is unable to accurately determine the true font dimensions. * @property {Phaser.Point} padding */ - this.padding = { x: 0, y: 0 }; + this.padding = { left: 0, right: 0, top: 0, bottom: 0 }; this.width = 1; this.height = 1; @@ -81,6 +82,11 @@ var Text = new Class({ this.initRTL(); + if (style && style.padding) + { + this.setPadding(style.padding); + } + this.setText(text); var _this = this; @@ -145,6 +151,21 @@ var Text = new Class({ return this.style.setFont(font); }, + setFontFamily: function (family) + { + return this.style.setFontFamily(family); + }, + + setFontSize: function (size) + { + return this.style.setFontSize(size); + }, + + setFontStyle: function (style) + { + return this.style.setFontStyle(style); + }, + setFixedSize: function (width, height) { return this.style.setFixedSize(width, height); @@ -155,9 +176,9 @@ var Text = new Class({ return this.style.setBackgroundColor(color); }, - setFill: function (color) + setColor: function (color) { - return this.style.setFill(color); + return this.style.setColor(color); }, setStroke: function (color, thickness) @@ -200,6 +221,59 @@ var Text = new Class({ return this.style.setAlign(align); }, + // 'left' can be an object + // if only 'left' and 'top' are given they are treated as 'x' and 'y' + setPadding: function (left, top, right, bottom) + { + if (typeof left === 'object') + { + var config = left; + + // If they specify x and/or y this applies to all + var x = GetValue(config, 'x', null); + + if (x !== null) + { + left = x; + right = x; + } + else + { + left = GetValue(config, 'left', 0); + right = GetValue(config, 'right', left); + } + + var y = GetValue(config, 'y', null); + + if (y !== null) + { + top = y; + bottom = y; + } + else + { + top = GetValue(config, 'top', 0); + bottom = GetValue(config, 'bottom', top); + } + } + else + { + if (left === undefined) { left = 0; } + if (top === undefined) { top = left; } + if (right === undefined) { right = left; } + if (bottom === undefined) { bottom = top; } + } + + this.padding.left = left; + this.padding.top = top; + this.padding.right = right; + this.padding.bottom = bottom; + + console.log(this.padding); + + return this.updateText(); + }, + setMaxLines: function (max) { return this.style.setMaxLines(max); @@ -238,8 +312,8 @@ var Text = new Class({ var padding = this.padding; - var w = (textSize.width + (padding.x * 2)) * this.resolution; - var h = (textSize.height + (padding.y * 2)) * this.resolution; + var w = (textSize.width + padding.left + padding.right) * this.resolution; + var h = (textSize.height + padding.top + padding.bottom) * this.resolution; if (canvas.width !== w || canvas.height !== h) { @@ -262,7 +336,7 @@ var Text = new Class({ context.textBaseline = 'alphabetic'; // Apply padding - context.translate(padding.x, padding.y); + context.translate(padding.left, padding.top); var linePositionX; var linePositionY; @@ -282,9 +356,7 @@ var Text = new Class({ { linePositionX = w - linePositionX; } - else - { - if (style.align === 'right') + else if (style.align === 'right') { linePositionX += textSize.width - textSize.lineWidths[i]; } @@ -292,7 +364,6 @@ var Text = new Class({ { linePositionX += (textSize.width - textSize.lineWidths[i]) / 2; } - } if (this.autoRound) { @@ -307,7 +378,7 @@ var Text = new Class({ context.strokeText(lines[i], linePositionX, linePositionY); } - if (style.fill) + if (style.color) { this.style.syncShadow(context, style.shadowFill); @@ -337,8 +408,10 @@ var Text = new Class({ style: this.style.toJSON(), resolution: this.resolution, padding: { - x: this.padding.x, - y: this.padding.y + left: this.padding.left, + right: this.padding.right, + top: this.padding.top, + bottom: this.padding.bottom } }; ",9 "diff --git a/src/sound/html5/HTML5AudioSound.js b/src/sound/html5/HTML5AudioSound.js @@ -126,7 +126,16 @@ var HTML5AudioSound = new Class({ BaseSound.prototype.stop.call(this); }, update: function (time, delta) { - + if (this.isPlaying) { + // handling delayed playback + if (this.startTime > 0) { + if (this.startTime < time) { + this.audio.currentTime += (time - this.startTime) / 1000; + this.startTime = 0; + this.audio.play(); + } + } + } }, destroy: function () { BaseSound.prototype.destroy.call(this); ",9 "diff --git a/test/PullPayment.js b/test/PullPayment.js @@ -2,10 +2,10 @@ var PullPaymentMock = artifacts.require(""./helpers/PullPaymentMock.sol""); contract('PullPayment', function(accounts) { let ppce; - let tAMOUNT = 17*1e18; + let amount = 17*1e18; beforeEach(async function() { - ppce = await PullPaymentMock.new({value: tAMOUNT}); + ppce = await PullPaymentMock.new({value: amount}); }); it(""can't call asyncSend externally"", async function() { @@ -50,13 +50,13 @@ contract('PullPayment', function(accounts) { let payee = accounts[1]; let initialBalance = web3.eth.getBalance(payee); - let call1 = await ppce.callSend(payee, tAMOUNT); + let call1 = await ppce.callSend(payee, amount); let payment1 = await ppce.payments(payee); - assert.equal(payment1, tAMOUNT); + assert.equal(payment1, amount); let totalPayments = await ppce.totalPayments(); - assert.equal(totalPayments, tAMOUNT); + assert.equal(totalPayments, amount); let withdraw = await ppce.withdrawPayments({from: payee}); let payment2 = await ppce.payments(payee); @@ -66,7 +66,7 @@ contract('PullPayment', function(accounts) { assert.equal(totalPayments, 0); let balance = web3.eth.getBalance(payee); - assert(Math.abs(balance-initialBalance-tAMOUNT) < 1e16); + assert(Math.abs(balance-initialBalance-amount) < 1e16); }); }); ",10 "diff --git a/contracts/governance/TimelockController.sol b/contracts/governance/TimelockController.sol @@ -131,7 +131,7 @@ contract TimelockController is AccessControl, IERC721Receiver, IERC1155Receiver * @dev Returns whether an id correspond to a registered operation. This * includes both Pending, Ready and Done operations. */ - function isOperation(bytes32 id) public view virtual returns (bool pending) { + function isOperation(bytes32 id) public view virtual returns (bool registered) { return getTimestamp(id) > 0; } ",10 "diff --git a/contracts/token/ERC721/IERC721.sol b/contracts/token/ERC721/IERC721.sol @@ -112,7 +112,7 @@ interface IERC721 is IERC165 { * * Emits an {ApprovalForAll} event. */ - function setApprovalForAll(address operator, bool _approved) external; + function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns the account approved for `tokenId` token. ",10 "diff --git a/contracts/token/common/ERC2981.sol b/contracts/token/common/ERC2981.sol @@ -40,14 +40,14 @@ abstract contract ERC2981 is IERC2981, ERC165 { /** * @inheritdoc IERC2981 */ - function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) { - RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; + function royaltyInfo(uint256 tokenId, uint256 salePrice) public view virtual override returns (address, uint256) { + RoyaltyInfo memory royalty = _tokenRoyaltyInfo[tokenId]; if (royalty.receiver == address(0)) { royalty = _defaultRoyaltyInfo; } - uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); + uint256 royaltyAmount = (salePrice * royalty.royaltyFraction) / _feeDenominator(); return (royalty.receiver, royaltyAmount); } ",10 "diff --git a/build/webpack.config.js b/build/webpack.config.js @@ -313,8 +313,8 @@ config.module.rules.push({ test: new RegExp(`\\.${extension}$`), loader: 'url-loader', options: { - name: 'fonts/[name].[ext]', - limit: 10000, + name: __DEV__ ? 'fonts/[name].[ext]' : 'fonts/[name].[hash].[ext]', + limit: 8192, mimetype } }) ",10 "diff --git a/MaterialSkin/HTML/material/html/js/server.js b/MaterialSkin/HTML/material/html/js/server.js @@ -142,7 +142,7 @@ var lmsServer = Vue.component('lms-server', { if (this.cometd) { this.cometd.disconnect(); } - this.cancelTimers(); + this.cancelServerStatusTimer(); this.subscribedPlayers = new Set(); this.cometd = new org.cometd.CometD(); this.cometd.init({url: '/cometd', logLevel:'off'}); @@ -160,8 +160,8 @@ var lmsServer = Vue.component('lms-server', { {data:{response:'/'+this.cometd.getClientId()+'/slim/favorites', request:['favorites', ['changed']]}}); this.updateFavorites(); // If we don't get a statu supdate within 5 seconds, assume something wrong and reconnect - this.statusTimer = setTimeout(function () { - this.statusTimer = undefined; + this.serverStatusTimer = setTimeout(function () { + this.serverStatusTimer = undefined; this.connectToCometD(); }.bind(this), 5000); } @@ -184,7 +184,7 @@ var lmsServer = Vue.component('lms-server', { }, handleServerStatus(data) { logCometdMessage(""SERVER"", data); - this.cancelTimers(); + this.cancelServerStatusTimer(); var players = []; if (lmsLastScan!=data.lastscan) { lmsLastScan = data.lastscan; @@ -337,10 +337,10 @@ var lmsServer = Vue.component('lms-server', { } }); }, - cancelTimers() { - if (undefined!==this.statusTimer) { - clearTimeout(this.statusTimer); - this.statusTimer = undefined; + cancelServerStatusTimer() { + if (undefined!==this.serverStatusTimer) { + clearTimeout(this.serverStatusTimer); + this.serverStatusTimer = undefined; } } }, @@ -416,7 +416,7 @@ var lmsServer = Vue.component('lms-server', { }.bind(this)); }, beforeDestroy() { - this.cancelTimers(); + this.cancelServerStatusTimer(); }, watch: { '$store.state.player': function (newVal) { ",10 "diff --git a/MaterialSkin/HTML/material/html/js/browse-page.js b/MaterialSkin/HTML/material/html/js/browse-page.js @@ -311,7 +311,7 @@ var lmsBrowse = Vue.component(""lms-browse"", { } }, created() { - this.serverMyMusic=[]; + this.myMusic=[]; this.history=[]; this.fetchingItems = false; this.current = null; @@ -383,7 +383,7 @@ var lmsBrowse = Vue.component(""lms-browse"", { this.refreshList(); } else if ((this.current && this.current.id == TOP_MYMUSIC_ID) || (this.history.length>1 && this.history[1].current && this.history[1].current.id==TOP_MYMUSIC_ID)) { - this.serverMyMusicMenu(); + this.myMusicMenu(); } }.bind(this)); @@ -849,8 +849,8 @@ var lmsBrowse = Vue.component(""lms-browse"", { if (TOP_MYMUSIC_ID==item.id) { this.addHistory(); - this.items = this.serverMyMusic; - this.serverMyMusicMenu(); + this.items = this.myMusic; + this.myMusicMenu(); this.headerTitle = item.title; this.headerSubTitle = i18n(""Browse music library""); this.current = item; @@ -1867,11 +1867,11 @@ var lmsBrowse = Vue.component(""lms-browse"", { } }); }, - serverMyMusicMenu() { + myMusicMenu() { this.fetchingItems=true; lmsCommand("""", [""material-skin"", ""browsemodes""]).then(({data}) => { if (data && data.result) { - this.serverMyMusic = []; + this.myMusic = []; // Get basic, configurable, browse modes... if (data && data.result && data.result.modes_loop) { for (var idx=0, loop=data.result.modes_loop, loopLen=loop.length; idx=0) { item['mapgenre']=true; } - this.serverMyMusic.push(item); + this.myMusic.push(item); } } } - this.serverMyMusic.sort(function(a, b) { return a.weight!=b.weight ? a.weight1 && this.history[1].current && this.history[1].current.id==TOP_MYMUSIC_ID) { - this.history[1].items = this.serverMyMusic; + this.history[1].items = this.myMusic; } } this.fetchingItems=false; @@ -2050,8 +2050,8 @@ var lmsBrowse = Vue.component(""lms-browse"", { if (this.history.length<1) { this.items = this.top; } - for (var i=0, len=this.serverMyMusic.length; i\n* ${bannerList}\n* Date: <%= grunt.template.today(""dd/mm/yyyy h:MM:ss TT"") %>\n* Revision: <%= meta.revision %>\n* <%= meta.copyright %>\n*/ \n`; + bannerText = `/**\n* IDS Enterprise Components v<%= pkg.version %>\n* ${bannerList}\n* Date: <%= grunt.template.today(""dd/mm/yyyy h:MM:ss TT"") %>\n* Revision: <%= meta.revision %>\n* <%= meta.copyright %>\n*/ \n`; } else { selectedControls = controls; } ",10 "diff --git a/src/components/dropdown/dropdown.js b/src/components/dropdown/dropdown.js @@ -311,7 +311,7 @@ Dropdown.prototype = { this.setDisplayedValues(); this.setInitial(); this.setWidth(); - this.initTooltip(); + this.setTooltip(); this.element.triggerHandler('rendered'); @@ -492,7 +492,7 @@ Dropdown.prototype = { /** * Triggers tooltip in multiselect */ - initTooltip() { + setTooltip() { const opts = this.element.find('option:selected'); const optText = this.getOptionText(opts); @@ -2369,7 +2369,7 @@ Dropdown.prototype = { this.element.trigger('change').triggerHandler('selected', [option, isAdded]); if (this.pseudoElem.find('span').width() >= this.pseudoElem.width()) { - this.initTooltip(); + this.setTooltip(); } else if (this.tooltipApi) { this.tooltipApi.destroy(); ",10 "diff --git a/app/views/components/listview/test-remove-clear.html b/app/views/components/listview/test-remove-clear.html
    -
    +
    My Tasks
    ",10 "diff --git a/test/components/listview/listview.e2e-spec.js b/test/components/listview/listview.e2e-spec.js @@ -575,7 +575,7 @@ describe('Listview with indeterminate paging inside of List/Detail Pattern', () describe('Listview flex card empty tests', () => { beforeEach(async () => { - await utils.setPage('/components/listview/test-empty-message-no-card?layout=nofrills'); + await utils.setPage('/components/listview/test-empty-message-flex-container?layout=nofrills'); const emptyMessage = await element(by.css('.empty-message')); await browser.driver .wait(protractor.ExpectedConditions.presenceOf(emptyMessage), config.waitsFor); ",10 "diff --git a/test/components/form/form.e2e-spec.js b/test/components/form/form.e2e-spec.js @@ -55,7 +55,7 @@ describe('Form Tests', () => { await utils.checkForErrors(); - expect(await browser.protractorImageComparison.checkElement(containerEl, 'form-compact-fields')).toEqual(0); + expect(await browser.protractorImageComparison.checkElement(containerEl, 'form-compact-mode')).toEqual(0); }); it('Should not visual regress on compact/short fields in RTL', async () => { @@ -65,7 +65,7 @@ describe('Form Tests', () => { await utils.checkForErrors(); - expect(await browser.protractorImageComparison.checkElement(containerEl, 'form-compact-fields')).toEqual(0); + expect(await browser.protractorImageComparison.checkElement(containerEl, 'form-compact-mode-rtl')).toEqual(0); }); } }); ",10 "diff --git a/test/components/button/button-api.func-spec.js b/test/components/button/button-api.func-spec.js @@ -36,7 +36,7 @@ describe('Button API', () => { expect(buttonAPI).toEqual(jasmine.any(Object)); }); - it('Should destroy button', (done) => { + it('can be destroyed', (done) => { const spyEvent = spyOnEvent(buttonEl, 'click.button'); buttonAPI.destroy(); buttonEl.click(); @@ -48,7 +48,7 @@ describe('Button API', () => { expect($(buttonEl).data('button')).toBeFalsy(); }); - it('Should set settings', () => { + it('has default settings', () => { const settings = { replaceText: false, toggleOffIcon: null, @@ -59,7 +59,7 @@ describe('Button API', () => { expect(buttonAPI.settings).toEqual(settings); }); - it('Should update settings via parameter', () => { + it('can update settings via the `updated()` method', () => { const settings = { replaceText: true, toggleOffIcon: null, @@ -71,7 +71,7 @@ describe('Button API', () => { expect(buttonAPI.settings.replaceText).toEqual(settings.replaceText); }); - it('Should update menu icon setting via parameter', () => { + it('should properly update the `hideMenuArrow` setting via the `updated()` method', () => { const settings = { replaceText: false, toggleOffIcon: null, @@ -83,7 +83,7 @@ describe('Button API', () => { expect(buttonAPI.settings.hideMenuArrow).toEqual(settings.hideMenuArrow); }); - it('Should remove menu icon if hideMenuArrow set to true', () => { + it('should remove menu icon if hideMenuArrow set to true', () => { const elem = buttonAPI.element[0]; buttonAPI.updated({ hideMenuArrow: true }); ",10 "diff --git a/test/components/datagrid/datagrid.e2e-spec.js b/test/components/datagrid/datagrid.e2e-spec.js @@ -2028,7 +2028,7 @@ describe('Datagrid Frozen Column Card (auto) tests', () => { describe('Datagrid Frozen Column Card (fixed) tests', () => { beforeEach(async () => { - await utils.setPage('/components/datagrid/test-frozen-columns-fixed-row-height?layout=nofrills'); + await utils.setPage('/components/datagrid/test-card-frozen-columns-fixed-row-height?layout=nofrills'); const datagridEl = await element(by.css('#datagrid tbody tr:nth-child(1)')); await browser.driver ",10 "diff --git a/client/src/js/djng-forms.js b/client/src/js/djng-forms.js // module: djng.forms // Correct Angular's form.FormController behavior after rendering bound forms. // Additional validators for form elements. -var djng_forms_module = angular.module('djng.forms', []); +var djngModule = angular.module('djng.forms', []); + // create a simple hash code for the given string function hashCode(s) { @@ -42,7 +43,7 @@ function addNgModelDirective() { // Bound fields with invalid input data, shall be marked as ng-invalid-bound, so that // the input field visibly contains invalid data, even if pristine -djng_forms_module.directive('djngError', function() { +djngModule.directive('djngError', function() { return { restrict: 'A', require: '?^form', @@ -68,7 +69,7 @@ djng_forms_module.directive('djngError', function() { // This directive overrides some of the internal behavior on forms if used together with AngularJS. // Otherwise, the content of bound forms is not displayed, because AngularJS does not know about // the concept of bound forms and thus hides values preset by Django while rendering HTML. -djng_forms_module.directive('ngModel', ['$log', function($log) { +djngModule.directive('ngModel', ['$log', function($log) { function restoreInputField(field) { // restore the field's content from the rendered content of bound fields switch (field.type) { @@ -134,9 +135,8 @@ djng_forms_module.directive('ngModel', ['$log', function($log) { var curModelValue = scope.$eval(attrs.ngModel); // if model already has a value defined, don't set the default - if (!field || !formCtrl || angular.isDefined(curModelValue)) { + if (!field || !formCtrl || angular.isDefined(curModelValue)) return; - } switch (field.tagName) { case 'INPUT': @@ -163,7 +163,7 @@ djng_forms_module.directive('ngModel', ['$log', function($log) { // This directive is added automatically by django-angular for widgets of type RadioSelect and // CheckboxSelectMultiple. This is necessary to adjust the behavior of a collection of input fields, // which forms a group for one `django.forms.Field`. -djng_forms_module.directive('validateMultipleFields', function() { +djngModule.directive('validateMultipleFields', function() { return { restrict: 'A', require: '^?form', @@ -218,7 +218,7 @@ djng_forms_module.directive('validateMultipleFields', function() { // // Now, such an input field is only considered valid, if the date is a valid date and if it matches // against the given regular expression. -djng_forms_module.directive('validateDate', function() { +djngModule.directive('validateDate', function() { var validDatePattern = null; function validateDate(date) { @@ -260,7 +260,7 @@ djng_forms_module.directive('validateDate', function() { // This directive can be added to an input field to validate emails using a similar regex to django -djng_forms_module.directive('validateEmail', function() { +djngModule.directive('validateEmail', function() { return { require: '?ngModel', restrict: 'A', @@ -286,7 +286,7 @@ djng_forms_module.directive('validateEmail', function() { // djangoForm.setErrors($scope.form, data.errors); // }); // djangoForm.setErrors returns false, if no errors have been transferred. -djng_forms_module.factory('djangoForm', function() { +djngModule.factory('djangoForm', function() { var NON_FIELD_ERRORS = '__all__'; function isNotEmpty(obj) { @@ -380,7 +380,7 @@ djng_forms_module.factory('djangoForm', function() { // Directive behaves similar to `ng-bind` but leaves the elements // content as is, if the value to bind is undefined. This allows to set a default value in case the // scope variables are not ready yet. -djng_forms_module.directive('djngBindIf', function() { +djngModule.directive('djngBindIf', function() { return { restrict: 'A', compile: function(templateElement) { ",10 "diff --git a/client/src/js/djng-forms.js b/client/src/js/djng-forms.js @@ -164,33 +164,34 @@ djngModule.directive('validateMultipleFields', function() { return { restrict: 'A', require: '^?form', - link: function(scope, element, attrs, formCtrl) { + link: function(scope, element, attrs, controller) { var subFields, checkboxElems = []; + if (!controller) + return; + function validate(event) { var valid = false; angular.forEach(checkboxElems, function(checkbox) { valid = valid || checkbox.checked; }); - formCtrl.$setValidity('required', valid); + controller.$setValidity('required', valid); if (event) { - formCtrl.$dirty = true; - formCtrl.$pristine = false; + controller.$dirty = true; + controller.$pristine = false; // element.on('change', validate) is jQuery and runs outside of Angular's digest cycle. // Therefore Angular does not get the end-of-digest signal and $apply() must be invoked manually. scope.$apply(); } } - if (!formCtrl) - return; try { subFields = angular.fromJson(attrs.validateMultipleFields); } catch (SyntaxError) { if (!angular.isString(attrs.validateMultipleFields)) return; subFields = [attrs.validateMultipleFields]; - formCtrl = formCtrl[subFields]; + controller = controller[subFields]; } angular.forEach(element.find('input'), function(elem) { if (subFields.indexOf(elem.name) >= 0) { ",10 "diff --git a/runtime/ms-rest-azure/lib/cloudError.js b/runtime/ms-rest-azure/lib/cloudError.js * * @member {array} [details] An array of CloudError objects specifying the details * - * @member {Object} [innerError] The inner error parsed from the body of the http error response + * @member {Object} [innererror] The inner error parsed from the body of the http error response */ class CloudError extends Error { constructor(parameters) { @@ -46,8 +46,8 @@ class CloudError extends Error { this.details = tempDetails; } - if (parameters.innerError) { - this.innerError = JSON.parse(JSON.stringify(parameters.innerError)); + if (parameters.innererror) { + this.innererror = JSON.parse(JSON.stringify(parameters.innererror)); } } } @@ -102,9 +102,9 @@ class CloudError extends Error { } } }, - innerError: { + innererror: { required: false, - serializedName: 'innerError', + serializedName: 'innererror', type: { name: 'Object' } @@ -145,8 +145,8 @@ class CloudError extends Error { payload.error.details = deserializedArray; } - if (this.innerError) { - payload.error.innerError = JSON.parse(JSON.stringify(this.innerError)); + if (this.innererror) { + payload.error.innererror = JSON.parse(JSON.stringify(this.innererror)); } return payload; } @@ -185,8 +185,8 @@ class CloudError extends Error { this.details = deserializedArray; } - if (instance.error.innerError) { - this.innerError = JSON.parse(JSON.stringify(instance.error.innerError)); + if (instance.error.innererror) { + this.innererror = JSON.parse(JSON.stringify(instance.error.innererror)); } } } ",10 "diff --git a/src/lib/default-project/project.json b/src/lib/default-project/project.json -{""targets"":[{""id"":""`jEk@4|i[#Fk?(8x)AV."",""name"":""Stage"",""isStage"":true,""x"":0,""y"":0,""size"":100,""direction"":90,""draggable"":false,""currentCostume"":0,""costume"":{""name"":""backdrop1"",""bitmapResolution"":1,""rotationCenterX"":240,""rotationCenterY"":180,""skinId"":2,""dataFormat"":""png"",""assetId"":""739b5e2a2435f6e1ec2993791b423146""},""costumeCount"":1,""visible"":true,""rotationStyle"":""all around"",""blocks"":{},""variables"":{""`jEk@4|i[#Fk?(8x)AV.-my variable"":{""id"":""`jEk@4|i[#Fk?(8x)AV.-my variable"",""name"":""my variable"",""type"":"""",""isCloud"":false,""value"":0}},""lists"":{},""costumes"":[{""name"":""backdrop1"",""bitmapResolution"":1,""rotationCenterX"":240,""rotationCenterY"":180,""skinId"":2,""dataFormat"":""png"",""assetId"":""739b5e2a2435f6e1ec2993791b423146""}],""sounds"":[{""name"":""pop"",""format"":"""",""rate"":11025,""sampleCount"":258,""soundID"":1,""md5"":""83a9787d4cb6f3b7632b4ddfebf74367.wav"",""data"":null,""dataFormat"":""wav"",""assetId"":""83a9787d4cb6f3b7632b4ddfebf74367"",""soundId"":""p=i?*Zt*I]@]x_*V`mut""}]},{""id"":""9xJ@2eKXvx:/*Q^3Rib#"",""name"":""Sprite1"",""isStage"":false,""x"":0,""y"":0,""size"":100,""direction"":90,""draggable"":false,""currentCostume"":0,""costume"":{""name"":""costume1"",""bitmapResolution"":1,""rotationCenterX"":47,""rotationCenterY"":55,""skinId"":0,""dataFormat"":""svg"",""assetId"":""09dc888b0b7df19f70d81588ae73420e""},""costumeCount"":2,""visible"":true,""rotationStyle"":""all around"",""blocks"":{},""variables"":{},""lists"":{},""costumes"":[{""name"":""costume1"",""bitmapResolution"":1,""rotationCenterX"":47,""rotationCenterY"":55,""skinId"":0,""dataFormat"":""svg"",""assetId"":""09dc888b0b7df19f70d81588ae73420e""},{""name"":""costume2"",""bitmapResolution"":1,""rotationCenterX"":47,""rotationCenterY"":55,""skinId"":1,""dataFormat"":""svg"",""assetId"":""3696356a03a8d938318876a593572843""}],""sounds"":[{""name"":""Meow"",""format"":"""",""rate"":22050,""sampleCount"":18688,""soundID"":0,""md5"":""83c36d806dc92327b9e7049a565c6bff.wav"",""data"":null,""dataFormat"":""wav"",""assetId"":""83c36d806dc92327b9e7049a565c6bff"",""soundId"":""]z6@jLeJ2W%gr/eA1HB+""}]}],""meta"":{""semver"":""3.0.0"",""vm"":""0.1.0"",""agent"":""Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36""}} \ No newline at end of file +{""targets"":[{""id"":""`jEk@4|i[#Fk?(8x)AV."",""name"":""Stage"",""isStage"":true,""x"":0,""y"":0,""size"":100,""direction"":90,""draggable"":false,""currentCostume"":0,""costume"":{""name"":""backdrop1"",""bitmapResolution"":1,""rotationCenterX"":240,""rotationCenterY"":180,""skinId"":2,""dataFormat"":""png"",""assetId"":""739b5e2a2435f6e1ec2993791b423146""},""costumeCount"":1,""visible"":true,""rotationStyle"":""all around"",""blocks"":{},""variables"":{""`jEk@4|i[#Fk?(8x)AV.-my variable"":{""id"":""`jEk@4|i[#Fk?(8x)AV.-my variable"",""name"":""my variable"",""type"":"""",""isCloud"":false,""value"":0}},""lists"":{},""costumes"":[{""name"":""backdrop1"",""bitmapResolution"":1,""rotationCenterX"":240,""rotationCenterY"":180,""skinId"":2,""dataFormat"":""png"",""assetId"":""739b5e2a2435f6e1ec2993791b423146""}],""sounds"":[{""name"":""pop"",""format"":"""",""rate"":11025,""sampleCount"":258,""soundID"":1,""md5ext"":""83a9787d4cb6f3b7632b4ddfebf74367.wav"",""data"":null,""dataFormat"":""wav"",""assetId"":""83a9787d4cb6f3b7632b4ddfebf74367"",""soundId"":""p=i?*Zt*I]@]x_*V`mut""}]},{""id"":""9xJ@2eKXvx:/*Q^3Rib#"",""name"":""Sprite1"",""isStage"":false,""x"":0,""y"":0,""size"":100,""direction"":90,""draggable"":false,""currentCostume"":0,""costume"":{""name"":""costume1"",""bitmapResolution"":1,""rotationCenterX"":47,""rotationCenterY"":55,""skinId"":0,""dataFormat"":""svg"",""assetId"":""09dc888b0b7df19f70d81588ae73420e""},""costumeCount"":2,""visible"":true,""rotationStyle"":""all around"",""blocks"":{},""variables"":{},""lists"":{},""costumes"":[{""name"":""costume1"",""bitmapResolution"":1,""rotationCenterX"":47,""rotationCenterY"":55,""skinId"":0,""dataFormat"":""svg"",""assetId"":""09dc888b0b7df19f70d81588ae73420e""},{""name"":""costume2"",""bitmapResolution"":1,""rotationCenterX"":47,""rotationCenterY"":55,""skinId"":1,""dataFormat"":""svg"",""assetId"":""3696356a03a8d938318876a593572843""}],""sounds"":[{""name"":""Meow"",""format"":"""",""rate"":22050,""sampleCount"":18688,""soundID"":0,""md5ext"":""83c36d806dc92327b9e7049a565c6bff.wav"",""data"":null,""dataFormat"":""wav"",""assetId"":""83c36d806dc92327b9e7049a565c6bff"",""soundId"":""]z6@jLeJ2W%gr/eA1HB+""}]}],""meta"":{""semver"":""3.0.0"",""vm"":""0.1.0"",""agent"":""Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36""}} ",10 "diff --git a/src/containers/costume-tab.jsx b/src/containers/costume-tab.jsx @@ -63,7 +63,7 @@ const messages = defineMessages({ id: 'gui.costumeTab.addFileCostume' }, addCameraCostumeMsg: { - defaultMessage: 'Coming Soon', + defaultMessage: 'Camera', description: 'Button to use the camera to create a costume costume in the editor tab', id: 'gui.costumeTab.addCameraCostume' } ",10 "diff --git a/src/lib/file-uploader.js b/src/lib/file-uploader.js @@ -51,7 +51,7 @@ const handleFileUpload = function(fileInput, onload) { */ /** - * Cache an asset (costume, sound) in storage and return an object representation + * Create an asset (costume, sound) with storage and return an object representation * of the asset to track in the VM. * @param {ScratchStorage} storage The storage to cache the asset in * @param {string} fileName The name of the asset @@ -62,7 +62,7 @@ const handleFileUpload = function(fileInput, onload) { * @return {VMAsset} An object representing this asset and relevant information * which can be used to look up the data in storage */ -const cacheAsset = function(storage, fileName, assetType, dataFormat, data) { +const createVMAsset = function(storage, fileName, assetType, dataFormat, data) { const asset = storage.createAsset( assetType, dataFormat, @@ -117,7 +117,7 @@ const costumeUpload = function(fileData, fileType, costumeName, storage, handleC const bitmapAdapter = new BitmapAdapter(); const addCostumeFromBuffer = function(dataBuffer) { - const vmCostume = cacheAsset( + const vmCostume = createVMAsset( storage, costumeName, assetType, @@ -173,7 +173,7 @@ const soundUpload = function(fileData, fileType, soundName, storage, handleSound return; } - const vmSound = cacheAsset( + const vmSound = createVMAsset( storage, soundName, storage.AssetType.Sound, ",10 "diff --git a/lib/run/index.js b/lib/run/index.js @@ -54,7 +54,7 @@ var fs = require('fs'), * @private * @type {Object} */ - knownReporters = { + knownReporterErrorMessages = { teamcity: ' run `npm install teamcity`' }; @@ -349,8 +349,8 @@ module.exports = function (options, callback) { // @todo: route this via print module to respect silent flags console.warn(`newman warning: ""${reporterName}"" reporter could not be loaded.`); // print install instruction in case a known reporter is missing - if (knownReporters[reporterName]) { - console.warn(knownReporters[reporterName]); + if (knownReporterErrorMessages[reporterName]) { + console.warn(knownReporterErrorMessages[reporterName]); } else { console.warn(' please install reporter using npm'); ",10 "diff --git a/lib/run/secure-fs.js b/lib/run/secure-fs.js @@ -60,7 +60,7 @@ const fs = require('fs'), * @param {*} [insecureFileRead=false] - If true, allow reading files outside working directory * @param {*} [fileWhitelist=[]] - List of allowed files outside of working directory */ -function SecureFs (workingDir, insecureFileRead = false, fileWhitelist = []) { +function SecureFS (workingDir, insecureFileRead = false, fileWhitelist = []) { this._fs = fs; this._path = path; this.constants = this._fs.constants; @@ -80,7 +80,7 @@ function SecureFs (workingDir, insecureFileRead = false, fileWhitelist = []) { * * @returns {String} The resolved path */ -SecureFs.prototype._resolve = function (relOrAbsPath, whiteList) { +SecureFS.prototype._resolve = function (relOrAbsPath, whiteList) { // Special handling for windows absolute paths to work cross platform this.isWindows && isWindowsRoot(relOrAbsPath) && (relOrAbsPath = relOrAbsPath.substring(1)); @@ -106,7 +106,7 @@ SecureFs.prototype._resolve = function (relOrAbsPath, whiteList) { * @param {Array} [whiteList] - A optional list of additional absolute path to whitelist * @param {Function} callback - */ -SecureFs.prototype.resolvePath = function (relOrAbsPath, whiteList, callback) { +SecureFS.prototype.resolvePath = function (relOrAbsPath, whiteList, callback) { if (!callback && typeof whiteList === FUNCTION) { callback = whiteList; whiteList = []; @@ -129,7 +129,7 @@ SecureFs.prototype.resolvePath = function (relOrAbsPath, whiteList, callback) { * * @returns {String} The resolved path */ -SecureFs.prototype.resolvePathSync = function (relOrAbsPath, whiteList) { +SecureFS.prototype.resolvePathSync = function (relOrAbsPath, whiteList) { // Resolve the path from the working directory const resolvedPath = this._resolve(relOrAbsPath, _.concat(this.fileWhitelist, whiteList)); @@ -147,11 +147,11 @@ Object.getOwnPropertyNames(fs).map((prop) => { return; } - SecureFs.prototype[prop] = fs[prop]; + SecureFS.prototype[prop] = fs[prop]; }); // Override the required functions -SecureFs.prototype.stat = function (path, callback) { +SecureFS.prototype.stat = function (path, callback) { this.resolvePath(path, (err, resolvedPath) => { if (err) { return callback(err); @@ -161,7 +161,7 @@ SecureFs.prototype.stat = function (path, callback) { }); }; -SecureFs.prototype.createReadStream = function (path, options) { +SecureFS.prototype.createReadStream = function (path, options) { try { return this._fs.createReadStream(this.resolvePathSync(path), options); } @@ -184,4 +184,4 @@ SecureFs.prototype.createReadStream = function (path, options) { } }; -module.exports = SecureFs; +module.exports = SecureFS; ",10 "diff --git a/lib/syntax/node/AttributeSelector.js b/lib/syntax/node/AttributeSelector.js @@ -77,19 +77,19 @@ function getOperator() { } // '[' S* attrib_name ']' -// '[' S* attrib_name S* attrib_match S* [ IDENT | STRING ] S* attrib_flags? S* ']' +// '[' S* attrib_name S* attrib_matcher S* [ IDENT | STRING ] S* attrib_flags? S* ']' module.exports = { name: 'AttributeSelector', structure: { name: 'Identifier', - operator: [String, null], + matcher: [String, null], value: ['String', 'Identifier', null], flags: [String, null] }, parse: function() { var start = this.scanner.tokenStart; var name; - var operator = null; + var matcher = null; var value = null; var flags = null; @@ -102,7 +102,7 @@ module.exports = { if (this.scanner.tokenType !== RIGHTSQUAREBRACKET) { // avoid case `[name i]` if (this.scanner.tokenType !== IDENTIFIER) { - operator = getOperator.call(this); + matcher = getOperator.call(this); this.scanner.skipSC(); @@ -128,7 +128,7 @@ module.exports = { type: 'AttributeSelector', loc: this.getLocation(start, this.scanner.tokenStart), name: name, - operator: operator, + matcher: matcher, value: value, flags: flags }; @@ -139,8 +139,8 @@ module.exports = { processChunk('['); this.generate(processChunk, node.name); - if (node.operator !== null) { - processChunk(node.operator); + if (node.matcher !== null) { + processChunk(node.matcher); if (node.value !== null) { this.generate(processChunk, node.value); ",10 "diff --git a/lib/testbridge/bridge/src/main.ml b/lib/testbridge/bridge/src/main.ml @@ -19,17 +19,17 @@ let rec zip4_exn xs ys zs ws = | _ -> failwith ""lists not same length"" ;; -let get_old_pods (nodes: Kubernetes.Node.t List.t) (pods: Kubernetes.Pod.t List.t) = - let old_pods = +let get_misassigned_pods (nodes: Kubernetes.Node.t List.t) (pods: Kubernetes.Pod.t List.t) = + let misassigned_pods = List.filter_map pods ~f:(fun pod -> if List.exists nodes ~f:(fun node -> node.hostname = pod.node_selector) then None else Some (pod.container_name ^ "" -> "" ^ pod.node_selector) ) in - match old_pods with + match misassigned_pods with | [] -> None - | _ -> Some (""Old Pods:\n"" ^ String.concat ~sep:""\n"" old_pods) + | _ -> Some (""Old Pods:\n"" ^ String.concat ~sep:""\n"" misassigned_pods) let get_pods image_host @@ -76,8 +76,8 @@ let get_pods printf ""%s\n"" (String.concat ~sep:"", "" (List.map pods ~f:(fun pod -> Sexp.to_string_hum ([%sexp_of: Kubernetes.Pod.t] pod))));*) let () = - match get_old_pods nodes pods with - | Some err -> printf ""%s\n"" err; failwith ""Pods are old run cleanup.sh""; + match get_misassigned_pods nodes pods with + | Some err -> printf ""%s\n"" err; failwith ""Pods are old/misassigned... run cleanup.sh""; | None -> printf ""F R E S H pods, good to go.\n"" in ",10 "diff --git a/src/lib/coda_graphql/coda_graphql.ml b/src/lib/coda_graphql/coda_graphql.ml @@ -431,15 +431,15 @@ module Types = struct ~doc:""Status for whenever the blockchain is reorganized"" ~values:[enum_value ""CHANGED"" ~value:`Changed] - let protocol_amounts = - obj ""ProtocolAmounts"" ~fields:(fun _ -> + let genesis_constants = + obj ""GenesisConstants"" ~fields:(fun _ -> [ field ""accountCreationFee"" ~typ:(non_null uint64) ~doc:""The fee charged to create a new account"" ~args:Arg.[] ~resolve:(fun {ctx= coda; _} () -> (Coda_lib.config coda).precomputed_values.constraint_constants .account_creation_fee |> Currency.Fee.to_uint64 ) - ; field ""coinbaseReward"" ~typ:(non_null uint64) + ; field ""coinbase"" ~typ:(non_null uint64) ~doc: ""The amount received as a coinbase reward for producing a block"" ~args:Arg.[] @@ -2610,11 +2610,13 @@ module Queries = struct | None -> [] ) - let protocol_amounts = - field ""protocolAmounts"" - ~doc:""The currency amounts for different events in the protocol"" + let genesis_constants = + field ""genesisConstants"" + ~doc: + ""The constants used to determine the configuration of the genesis \ + block and all of its transitive dependencies"" ~args:Arg.[] - ~typ:(non_null Types.protocol_amounts) + ~typ:(non_null Types.genesis_constants) ~resolve:(fun _ () -> ()) let commands = @@ -2639,7 +2641,7 @@ module Queries = struct ; trust_status_all ; snark_pool ; pending_snark_work - ; protocol_amounts ] + ; genesis_constants ] end let schema = ",10 "diff --git a/src/app/test_executive/test_executive.ml b/src/app/test_executive/test_executive.ml @@ -116,9 +116,9 @@ let main inputs = | Some deferred -> [%log error] ""additional call to cleanup testnet while already cleaning up \ - ($reason, $hard_error)"" + ($reason, $error)"" ~metadata: - [(""reason"", `String reason); (""hard_error"", `String test_error_str)] ; + [(""reason"", `String reason); (""error"", `String test_error_str)] ; deferred | None -> [%log info] ""cleaning up testnet ($reason, $error)"" ",10 "diff --git a/src/lib/marlin_plonk_bindings/types/marlin_plonk_bindings_types.ml b/src/lib/marlin_plonk_bindings/types/marlin_plonk_bindings_types.ml @@ -12,17 +12,17 @@ end module Plonk_verification_evals = struct type 'poly_comm t = - { sigma_comm0: 'poly_comm - ; sigma_comm1: 'poly_comm - ; sigma_comm2: 'poly_comm + { sigma_comm_0: 'poly_comm + ; sigma_comm_1: 'poly_comm + ; sigma_comm_2: 'poly_comm ; ql_comm: 'poly_comm ; qr_comm: 'poly_comm ; qo_comm: 'poly_comm ; qm_comm: 'poly_comm ; qc_comm: 'poly_comm - ; rcm_comm0: 'poly_comm - ; rcm_comm1: 'poly_comm - ; rcm_comm2: 'poly_comm + ; rcm_comm_0: 'poly_comm + ; rcm_comm_1: 'poly_comm + ; rcm_comm_2: 'poly_comm ; psm_comm: 'poly_comm ; add_comm: 'poly_comm ; mul1_comm: 'poly_comm ",10 "diff --git a/src/app/test_executive/test_executive.ml b/src/app/test_executive/test_executive.ml @@ -126,7 +126,7 @@ let main inputs = let net_manager_ref : Engine.Network_manager.t option ref = ref None in let log_engine_ref : Engine.Log_engine.t option ref = ref None in let cleanup_deferred_ref = ref None in - let dispatch_cleanup_PARTIAL = + let f_dispatch_cleanup = dispatch_cleanup ~logger ~cleanup_func:Engine.Network_manager.cleanup ~destroy_func:Engine.Log_engine.destroy ~net_manager_ref ~log_engine_ref ~cleanup_deferred_ref @@ -139,7 +139,7 @@ let main inputs = @@ Printf.sprintf ""received signal %s"" (Signal.to_string signal) in don't_wait_for - (dispatch_cleanup_PARTIAL ""signal received"" + (f_dispatch_cleanup ""signal received"" (Malleable_error.of_error_hard error)) ) ; let%bind monitor_test_result = Monitor.try_with ~extract_exn:true (fun () -> @@ -158,7 +158,7 @@ let main inputs = Engine.Log_engine.create ~logger ~network ~on_fatal_error:(fun message -> don't_wait_for - (dispatch_cleanup_PARTIAL + (f_dispatch_cleanup (sprintf !""log engine fatal error: %s"" (Yojson.Safe.to_string (Logger.Message.to_yojson message))) @@ -174,7 +174,7 @@ let main inputs = | Error exn -> Malleable_error.of_error_hard (Error.of_exn exn) in - let%bind () = dispatch_cleanup_PARTIAL ""test completed"" test_result in + let%bind () = f_dispatch_cleanup ""test completed"" test_result in exit 0 let start inputs = ",10 "diff --git a/src/lib/gossip_net/libp2p.ml b/src/lib/gossip_net/libp2p.ml @@ -62,7 +62,8 @@ module Make (Rpc_intf : Mina_base.Rpc_intf.Rpc_interface_intf) : (Message.msg Envelope.Incoming.t * Coda_net2.Validation_callback.t) Strict_pipe.Reader.t ; subscription: - Message.msg Coda_net2.Pubsub.Subscription.t Deferred.t ref } + Message.msg Coda_net2.Pubsub.Subscription.t Deferred.t ref + ; restart_helper: unit -> unit } let create_rpc_implementations (Rpc_handler {rpc; f= handler; cost; budget}) = @@ -416,6 +417,10 @@ module Make (Rpc_intf : Mina_base.Rpc_intf.Rpc_interface_intf) : in let net2_ref = ref (Deferred.never ()) in let subscription_ref = ref (Deferred.never ()) in + let restarts_r, restarts_w = + Strict_pipe.create ~name:""libp2p-restarts"" + (Strict_pipe.Buffered (`Capacity 0, `Overflow Strict_pipe.Drop_head)) + in let%bind () = let rec on_libp2p_create res = net2_ref := @@ -464,6 +469,12 @@ module Make (Rpc_intf : Mina_base.Rpc_intf.Rpc_interface_intf) : high_connectivity_ivar ~on_unexpected_termination in on_libp2p_create res ; + don't_wait_for + (Strict_pipe.Reader.iter restarts_r ~f:(fun () -> + let%bind n = !net2_ref in + let%bind () = Coda_net2.shutdown n in + let%bind () = on_unexpected_termination () in + !net2_ref >>| ignore )) ; let%map _ = res in () in @@ -513,7 +524,8 @@ module Make (Rpc_intf : Mina_base.Rpc_intf.Rpc_interface_intf) : ; high_connectivity_ivar ; subscription= subscription_ref ; message_reader - ; ban_reader } + ; ban_reader + ; restart_helper= (fun () -> Strict_pipe.Writer.write restarts_w ()) } let peers t = !(t.net2) >>= Coda_net2.peers @@ -681,10 +693,10 @@ module Make (Rpc_intf : Mina_base.Rpc_intf.Rpc_interface_intf) : (peer_id : Peer.Id.t) (rpc : (q, r) rpc) (qs : q list) = let%bind net2 = !(t.net2) in match%bind - Mina_net2.open_stream net2 ~protocol:rpc_transport_proto peer_id + Coda_net2.open_stream net2 ~protocol:rpc_transport_proto peer_id with | Ok stream -> - let peer = Mina_net2.Stream.remote_peer stream in + let peer = Coda_net2.Stream.remote_peer stream in let transport = prepare_stream_transport stream in let (module Impl) = implementation_of_rpc rpc in try_call_rpc_with_dispatch ?heartbeat_timeout ?timeout @@ -731,6 +743,8 @@ module Make (Rpc_intf : Mina_base.Rpc_intf.Rpc_interface_intf) : let set_connection_gating t config = let%bind net2 = !(t.net2) in Coda_net2.set_connection_gating_config net2 config + + let restart_helper t = t.restart_helper () end include T ",10 "diff --git a/automation/terraform/modules/kubernetes/testnet/helm.tf b/automation/terraform/modules/kubernetes/testnet/helm.tf @@ -29,13 +29,13 @@ locals { ""/dns4/seed-node.${var.testnet_name}/tcp/${var.seed_port}/p2p/${split("","", var.seed_discovery_keypairs[0])[2]}"" ] - all_seed_peers = [ for name in keys(data.local_file.libp2p_peers) : ""/dns4/${name}.${var.testnet_name}/tcp/10501/p2p/${trimspace(data.local_file.libp2p_peers[name].content)}""] + static_peers = [ for name in keys(data.local_file.libp2p_peers) : ""/dns4/${name}.${var.testnet_name}/tcp/10501/p2p/${trimspace(data.local_file.libp2p_peers[name].content)}""] coda_vars = { runtimeConfig = var.generate_and_upload_artifacts ? data.local_file.genesis_ledger.content : var.runtime_config image = var.coda_image privkeyPass = var.block_producer_key_pass - seedPeers = concat(var.additional_seed_peers, local.seed_peers) + seedPeers = concat(var.additional_seed_peers, local.seed_peers, local.static_peers) logLevel = var.log_level logSnarkWorkGossip = var.log_snark_work_gossip uploadBlocksToGCloud = var.upload_blocks_to_gcloud @@ -109,7 +109,6 @@ locals { libp2pSecret = config.libp2p_secret enablePeerExchange = config.enable_peer_exchange isolated = config.isolated - seedPeers = local.all_seed_peers } ] } @@ -172,8 +171,8 @@ locals { } -output all_seed_peers { - value = local.all_seed_peers +output static_peers { + value = local.static_peers } # Cluster-Local Seed Node ",10 "diff --git a/src/app/libp2p_helper/src/codanet.go b/src/app/libp2p_helper/src/codanet.go @@ -153,30 +153,30 @@ func (cm *CodaConnectionManager) GetInfo() p2pconnmgr.CMInfo { type CodaGatingState struct { logger logging.EventLogger KnownPrivateAddrFilters *ma.Filters - DeniedAddrFilters *ma.Filters - AllowedAddrFilters *ma.Filters - DeniedPeers *peer.Set - AllowedPeers *peer.Set + BannedAddrFilters *ma.Filters + TrustedAddrFilters *ma.Filters + BannedPeers *peer.Set + TrustedPeers *peer.Set } // NewCodaGatingState returns a new CodaGatingState -func NewCodaGatingState(deniedAddrFilters *ma.Filters, allowedAddrFilters *ma.Filters, deniedPeers *peer.Set, allowedPeers *peer.Set) *CodaGatingState { +func NewCodaGatingState(bannedAddrFilters *ma.Filters, trustedAddrFilters *ma.Filters, bannedPeers *peer.Set, trustedPeers *peer.Set) *CodaGatingState { logger := logging.Logger(""codanet.CodaGatingState"") - if deniedAddrFilters == nil { - deniedAddrFilters = ma.NewFilters() + if bannedAddrFilters == nil { + bannedAddrFilters = ma.NewFilters() } - if allowedAddrFilters == nil { - allowedAddrFilters = ma.NewFilters() + if trustedAddrFilters == nil { + trustedAddrFilters = ma.NewFilters() } - if deniedPeers == nil { - deniedPeers = peer.NewSet() + if bannedPeers == nil { + bannedPeers = peer.NewSet() } - if allowedPeers == nil { - allowedPeers = peer.NewSet() + if trustedPeers == nil { + trustedPeers = peer.NewSet() } // we initialize the known private addr filters to reject all ip addresses initially @@ -185,17 +185,17 @@ func NewCodaGatingState(deniedAddrFilters *ma.Filters, allowedAddrFilters *ma.Fi return &CodaGatingState{ logger: logger, - DeniedAddrFilters: deniedAddrFilters, - AllowedAddrFilters: allowedAddrFilters, + BannedAddrFilters: bannedAddrFilters, + TrustedAddrFilters: trustedAddrFilters, KnownPrivateAddrFilters: knownPrivateAddrFilters, - DeniedPeers: deniedPeers, - AllowedPeers: allowedPeers, + BannedPeers: bannedPeers, + TrustedPeers: trustedPeers, } } func (gs *CodaGatingState) MarkPrivateAddrAsKnown(addr ma.Multiaddr) { if isPrivateAddr(addr) && gs.KnownPrivateAddrFilters.AddrBlocked(addr) { - gs.logger.Infof(""marking private addr %v as known"", addr) + gs.logger.Debugf(""marking private addr %v as known"", addr) ip, err := manet.ToIP(addr) if err != nil { @@ -211,36 +211,36 @@ func (gs *CodaGatingState) MarkPrivateAddrAsKnown(addr ma.Multiaddr) { } } -func (gs *CodaGatingState) isPeerWhitelisted(p peer.ID) bool { - return gs.AllowedPeers.Contains(p) +func (gs *CodaGatingState) isPeerTrusted(p peer.ID) bool { + return gs.TrustedPeers.Contains(p) } -func (gs *CodaGatingState) isPeerBlacklisted(p peer.ID) bool { - return gs.DeniedPeers.Contains(p) +func (gs *CodaGatingState) isPeerBanned(p peer.ID) bool { + return gs.BannedPeers.Contains(p) } // checks if a peer id is allowed to dial/accept func (gs *CodaGatingState) isAllowedPeer(p peer.ID) bool { - return gs.isPeerWhitelisted(p) || !gs.isPeerBlacklisted(p) + return gs.isPeerTrusted(p) || !gs.isPeerBanned(p) } -func (gs *CodaGatingState) isAddrWhitelisted(addr ma.Multiaddr) bool { - return !gs.AllowedAddrFilters.AddrBlocked(addr) +func (gs *CodaGatingState) isAddrTrusted(addr ma.Multiaddr) bool { + return !gs.TrustedAddrFilters.AddrBlocked(addr) } -func (gs *CodaGatingState) isAddrBlacklisted(addr ma.Multiaddr) bool { - return gs.DeniedAddrFilters.AddrBlocked(addr) +func (gs *CodaGatingState) isAddrBanned(addr ma.Multiaddr) bool { + return gs.BannedAddrFilters.AddrBlocked(addr) } // checks if an address is allowed to dial/accept func (gs *CodaGatingState) isAllowedAddr(addr ma.Multiaddr) bool { publicOrKnownPrivate := !isPrivateAddr(addr) || !gs.KnownPrivateAddrFilters.AddrBlocked(addr) - return gs.isAddrWhitelisted(addr) || (!gs.isAddrBlacklisted(addr) && publicOrKnownPrivate) + return gs.isAddrTrusted(addr) || (!gs.isAddrBanned(addr) && publicOrKnownPrivate) } -// checks if a peer is allowed to dial/accept; if the peer is in the whitelist, the address checks are overriden +// checks if a peer is allowed to dial/accept; if the peer is in the trustlist, the address checks are overriden func (gs *CodaGatingState) isAllowedPeerWithAddr(p peer.ID, addr ma.Multiaddr) bool { - return gs.isPeerWhitelisted(p) || (gs.isAllowedPeer(p) && gs.isAllowedAddr(addr)) + return gs.isPeerTrusted(p) || (gs.isAllowedPeer(p) && gs.isAllowedAddr(addr)) } func (gs *CodaGatingState) logGate() { @@ -283,7 +283,7 @@ func (gs *CodaGatingState) InterceptAddrDial(id peer.ID, addr ma.Multiaddr) (all // Bluetooth), straight after it has accepted a connection from its socket. func (gs *CodaGatingState) InterceptAccept(addrs network.ConnMultiaddrs) (allow bool) { remoteAddr := addrs.RemoteMultiaddr() - allow = gs.isAddrWhitelisted(remoteAddr) || !gs.isAddrBlacklisted(remoteAddr) + allow = gs.isAddrTrusted(remoteAddr) || !gs.isAddrBanned(remoteAddr) if !allow { gs.logger.Infof(""refusing to accept inbound connection from addr: %v"", remoteAddr) ",10 "diff --git a/src/lib/child_processes/child_processes.ml b/src/lib/child_processes/child_processes.ml @@ -379,9 +379,10 @@ let kill : t -> Unix.Exit_or_signal.t Deferred.Or_error.t = | Some _ -> Deferred.Or_error.error_string ""already terminated"" -let register_process ?termination_expected (t : Termination.t) (process : t) - kind = - Termination.register_process ?termination_expected t process.process kind +let register_process ?termination_expected (termination : Termination.t) + (process : t) kind = + Termination.register_process ?termination_expected termination + process.process kind let%test_module _ = ( module struct ",10 "diff --git a/scripts/rebuild-deb.sh b/scripts/rebuild-deb.sh @@ -19,10 +19,10 @@ PVKEYHASH=$(./default/src/app/cli/src/mina.exe internal snark-hashes | sort | md # TODO: be smarter about this when we introduce a devnet package #if [[ ""$GITBRANCH"" == ""master"" ]] ; then -DUNE_PROFILE=""testnet_postake_medium_curves"" +DUNE_PROFILE=""mainnet"" #fi -PROJECT=""mina-$(echo ""$DUNE_PROFILE"" | tr _ -)"" +PROJECT=""mina-dev"" BUILD_NUM=${BUILDKITE_BUILD_NUM} BUILD_URL=${BUILDKITE_BUILD_URL} ",10 "diff --git a/src/lib/cli_lib/flag.ml b/src/lib/cli_lib/flag.ml @@ -273,7 +273,7 @@ module Uri = struct (Resolve_with_default default) let rest_graphql_opt = - create ~name:""rest-server"" ~aliases:[""rest-server""] + create ~name:""--rest-server"" ~aliases:[""rest-server""] ~arg_type:(arg_type ~path:""graphql"") doc_builder Optional end ",10 "diff --git a/src/lib/mina_lib/mina_lib.ml b/src/lib/mina_lib/mina_lib.ml @@ -908,9 +908,9 @@ let add_full_transactions t user_command = |> Deferred.don't_wait_for ; Ivar.read result_ivar -let add_snapp_transactions t (snapp_parties : Parties.t list) = +let add_snapp_transactions t (snapp_txns : Parties.t list) = let result_ivar = Ivar.create () in - let cmd_inputs = Snapp_command_inputs snapp_parties in + let cmd_inputs = Snapp_command_inputs snapp_txns in Strict_pipe.Writer.write t.pipes.user_command_input_writer (cmd_inputs, Ivar.fill result_ivar, get_current_nonce t, get_account t) |> Deferred.don't_wait_for ; @@ -1585,13 +1585,14 @@ let create ?wallets (config : Config.t) = ~metadata:[ (""error"", Error_json.error_to_yojson e) ] ; result_cb (Error e) ; Deferred.unit ) - | Snapp_command_inputs parties -> + | Snapp_command_inputs snapp_txns -> (* TODO: here, submit a Parties.t, which includes a nonce allow the nonce to be omitted, and infer it, as done for user command inputs *) Strict_pipe.Writer.write local_txns_writer - ( List.map parties ~f:(fun cmd -> User_command.Parties cmd) + ( List.map snapp_txns ~f:(fun cmd -> + User_command.Parties cmd) , result_cb )) |> Deferred.don't_wait_for ; let ((most_recent_valid_block_reader, _) as most_recent_valid_block) = ",10 "diff --git a/src/lib/crypto/kimchi_backend/common/plonk_dlog_proof.ml b/src/lib/crypto/kimchi_backend/common/plonk_dlog_proof.ml @@ -210,8 +210,8 @@ module Make (Inputs : Inputs_intf) = struct Array.iter arr ~f:(fun fe -> Fq.Vector.emplace_back vec fe) ; vec - (** Note that this function will panic if some of the points are points at infinity *) - let opening_proof_of_backend (t : Opening_proof_backend.t) = + (** This function will panic if any of the points are the point at infinity *) + let opening_proof_of_backend_exn (t : Opening_proof_backend.t) = let g (x : G.Affine.Backend.t) : G.Affine.t = G.Affine.of_backend x |> Pickles_types.Or_infinity.finite_exn in @@ -229,7 +229,7 @@ module Make (Inputs : Inputs_intf) = struct } let of_backend (t : Backend.t) : t = - let proof = opening_proof_of_backend t.proof in + let proof = opening_proof_of_backend_exn t.proof in let evals = (fst t.evals, snd t.evals) |> Tuple_lib.Double.map ~f:(fun e -> ",10 "diff --git a/src/lib/transaction_snark/transaction_snark.ml b/src/lib/transaction_snark/transaction_snark.ml @@ -4718,13 +4718,13 @@ let%test_module ""transaction_snark"" = { pk = acct1.account.public_key ; update = Party.Update.noop ; token_id = Token_id.default - ; delta = + ; balance_change = Amount.Signed.(of_unsigned receiver_amount |> negate) ; increment_nonce = true ; events = [] ; sequence_events = [] ; call_data = Field.zero - ; depth = 0 + ; call_depth = 0 } ; predicate = Accept } ",10 "diff --git a/src/app/archive/archive_lib/processor.ml b/src/app/archive/archive_lib/processor.ml @@ -2114,7 +2114,7 @@ module Block = struct ; next_available_token : int64 ; ledger_hash : string ; height : int64 - ; global_slot_since_hard_fork : int64 + ; global_slot : int64 ; global_slot_since_genesis : int64 ; timestamp : int64 } @@ -2240,7 +2240,7 @@ module Block = struct consensus_state |> Consensus.Data.Consensus_state.blockchain_length |> Unsigned.UInt32.to_int64 - ; global_slot_since_hard_fork = + ; global_slot = Consensus.Data.Consensus_state.curr_global_slot consensus_state |> Unsigned.UInt32.to_int64 ; global_slot_since_genesis = @@ -2557,7 +2557,7 @@ module Block = struct |> Unsigned.UInt64.to_int64 ; ledger_hash = block.ledger_hash |> Ledger_hash.to_base58_check ; height = block.height |> Unsigned.UInt32.to_int64 - ; global_slot_since_hard_fork = + ; global_slot = block.global_slot_since_hard_fork |> Unsigned.UInt32.to_int64 ; global_slot_since_genesis = block.global_slot_since_genesis |> Unsigned.UInt32.to_int64 ",10 "diff --git a/src/lib/staged_ledger_diff/staged_ledger_diff.ml b/src/lib/staged_ledger_diff/staged_ledger_diff.ml @@ -78,7 +78,7 @@ module Pre_diff_two = struct module Stable = struct [@@@no_toplevel_latest_type] - module V1 = struct + module V2 = struct type ('a, 'b) t = { completed_works : 'a list ; commands : 'b list @@ -107,7 +107,7 @@ module Pre_diff_one = struct module Stable = struct [@@@no_toplevel_latest_type] - module V1 = struct + module V2 = struct type ('a, 'b) t = { completed_works : 'a list ; commands : 'b list @@ -140,7 +140,7 @@ module Pre_diff_with_at_most_two_coinbase = struct type t = ( Transaction_snark_work.Stable.V2.t , User_command.Stable.V2.t With_status.Stable.V2.t ) - Pre_diff_two.Stable.V1.t + Pre_diff_two.Stable.V2.t [@@deriving compare, sexp, yojson] let to_latest = Fn.id @@ -159,7 +159,7 @@ module Pre_diff_with_at_most_one_coinbase = struct type t = ( Transaction_snark_work.Stable.V2.t , User_command.Stable.V2.t With_status.Stable.V2.t ) - Pre_diff_one.Stable.V1.t + Pre_diff_one.Stable.V2.t [@@deriving compare, sexp, yojson] let to_latest = Fn.id ",10 "diff --git a/src/app/archive/zkapp_tables.sql b/src/app/archive/zkapp_tables.sql @@ -112,7 +112,7 @@ CREATE TABLE zkapp_nonce_bounds , nonce_upper_bound bigint NOT NULL ); -CREATE TYPE zkapp_account_precondition_type AS ENUM ('full', 'nonce', 'accept'); +CREATE TYPE zkapp_precondition_type AS ENUM ('full', 'nonce', 'accept'); /* NULL convention */ CREATE TABLE zkapp_precondition_accounts @@ -132,7 +132,7 @@ CREATE TABLE zkapp_precondition_accounts */ CREATE TABLE zkapp_account_precondition ( id serial PRIMARY KEY -, kind zkapp_account_precondition_type NOT NULL +, kind zkapp_precondition_type NOT NULL , precondition_account_id int REFERENCES zkapp_precondition_accounts(id) , nonce bigint ); @@ -235,7 +235,7 @@ CREATE TABLE zkapp_party_body ); CREATE TABLE zkapp_party -( id serial NOT NULL PRIMARY KEY +( id serial PRIMARY KEY , body_id int NOT NULL REFERENCES zkapp_party_body(id) , account_precondition_id int NOT NULL REFERENCES zkapp_account_precondition(id) , authorization_kind zkapp_authorization_kind_type NOT NULL ",10 "diff --git a/src/lib/crypto/kimchi_bindings/wasm/src/plonk_verifier_index.rs b/src/lib/crypto/kimchi_bindings/wasm/src/plonk_verifier_index.rs @@ -224,7 +224,7 @@ macro_rules! impl_verification_key { pub domain: WasmDomain, pub max_poly_size: i32, pub max_quot_size: i32, - pub public: i32, + pub public_: i32, #[wasm_bindgen(skip)] pub srs: $WasmSrs, #[wasm_bindgen(skip)] @@ -241,7 +241,7 @@ macro_rules! impl_verification_key { domain: &WasmDomain, max_poly_size: i32, max_quot_size: i32, - public: i32, + public_: i32, srs: &$WasmSrs, evals: &WasmPlonkVerificationEvals, shifts: &WasmShifts, @@ -250,7 +250,7 @@ macro_rules! impl_verification_key { domain: domain.clone(), max_poly_size, max_quot_size, - public, + public_, srs: srs.clone(), evals: evals.clone(), shifts: shifts.clone(), @@ -289,7 +289,7 @@ macro_rules! impl_verification_key { }, max_poly_size: vi.max_poly_size as i32, max_quot_size: vi.max_quot_size as i32, - public: vi.public as i32, + public_: vi.public as i32, srs: srs.into(), evals: WasmPlonkVerificationEvals { sigma_comm: IntoIterator::into_iter(vi.sigma_comm).map(From::from).collect(), @@ -363,7 +363,7 @@ macro_rules! impl_verification_key { pub fn of_wasm( max_poly_size: i32, max_quot_size: i32, - public: i32, + public_: i32, log_size_of_group: i32, srs: &$WasmSrs, evals: &WasmPlonkVerificationEvals, @@ -410,7 +410,7 @@ macro_rules! impl_verification_key { endo: endo_q, max_poly_size: max_poly_size as usize, max_quot_size: max_quot_size as usize, - public: public as usize, + public: public_ as usize, zkpm: { let res = once_cell::sync::OnceCell::new(); res.set(zk_polynomial(domain)).unwrap(); @@ -443,7 +443,7 @@ macro_rules! impl_verification_key { of_wasm( index.max_poly_size, index.max_quot_size, - index.public, + index.public_, index.domain.log_size_of_group, &index.srs, &index.evals, @@ -582,7 +582,7 @@ macro_rules! impl_verification_key { }, max_poly_size: 0, max_quot_size: 0, - public: 0, + public_: 0, srs: $WasmSrs(Arc::new(SRS::create(0))), evals: WasmPlonkVerificationEvals { sigma_comm: vec_comm(PERMUTS), ",10 "diff --git a/packages/jss-preset-default/src/index.js b/packages/jss-preset-default/src/index.js -import functionPlugin from 'jss-plugin-syntax-rule-value-function' -import observablePlugin from 'jss-plugin-syntax-rule-value-observable' +import functions from 'jss-plugin-syntax-rule-value-function' +import observable from 'jss-plugin-syntax-rule-value-observable' import template from 'jss-plugin-syntax-template' import global from 'jss-plugin-syntax-global' import extend from 'jss-plugin-syntax-extend' @@ -13,8 +13,8 @@ import propsSort from 'jss-plugin-props-sort' export default (options = {}) => ({ plugins: [ - functionPlugin(options.function), - observablePlugin(options.observable), + functions(options.function), + observable(options.observable), template(options.template), global(options.global), extend(options.extend), ",10 "diff --git a/src/utils/Card.js b/src/utils/Card.js @@ -95,7 +95,7 @@ export const cardRarity = (card) => card.rarity ?? card.details.rarity; export const cardAddedTime = (card) => card.addedTmsp; -export const cardImg = (card) => card.imgUrl ?? card.details.image_normal ?? card.details.image_small; +export const cardImageUrl = (card) => card.imgUrl ?? card.details.image_normal ?? card.details.image_small; export const cardNotes = (card) => card.notes; @@ -178,7 +178,7 @@ export default { cardType, cardRarity, cardAddedTime, - cardImg, + cardImageUrl, cardNotes, cardColorCategory, cardCost, ",10 "diff --git a/index.html b/index.html this.state.login.trim(), this.state.password.trim(), vcard(this.state.fn, this.state.imageDataUrl), - {""type"": ""email"", ""val"": this.state.email}); + {""meth"": ""email"", ""val"": this.state.email}); } }, render: function() { ",10 "diff --git a/index.html b/index.html Tinode - - + + ",10 "diff --git a/src/widgets/contact-list.jsx b/src/widgets/contact-list.jsx @@ -48,14 +48,14 @@ class ContactList extends React.Component { // If filter function is provided, filter out the items // which don't satisfy the condition. if (this.props.filterFunc && this.props.filter) { - let content = [key]; + const filterOn = [key]; if (c.private && c.private.comment) { - content.push(('' + c.private.comment).toLowerCase()); + filterOn.push(('' + c.private.comment).toLowerCase()); } if (c.public && c.public.fn) { - content.push(('' + c.public.fn).toLowerCase()); + filterOn.push(('' + c.public.fn).toLowerCase()); } - if (!this.props.filterFunc(this.props.filter, content)) { + if (!this.props.filterFunc(this.props.filter, filterOn)) { return; } } ",10 "diff --git a/src/widgets/audio-player.jsx b/src/widgets/audio-player.jsx @@ -39,7 +39,7 @@ export default class AudioPlayer extends React.PureComponent { this.initAudio = this.initAudio.bind(this); this.initCanvas = this.initCanvas.bind(this); - this.calcPreviewBars = this.calcPreviewBars.bind(this); + this.resampleBars = this.resampleBars.bind(this); this.visualize = this.visualize.bind(this); this.handlePlay = this.handlePlay.bind(this); @@ -106,7 +106,7 @@ export default class AudioPlayer extends React.PureComponent { this.canvasContext = this.canvasRef.current.getContext('2d'); this.canvasContext.lineCap = 'round'; - this.viewBuffer = this.calcPreviewBars(this.state.preview); + this.viewBuffer = this.resampleBars(this.state.preview); this.visualize(); } @@ -172,7 +172,7 @@ export default class AudioPlayer extends React.PureComponent { } // Quick and dirty downsampling of the original preview bars into a smaller (or equal) number of bars we can display here. - calcPreviewBars(original) { + resampleBars(original) { const barCount = Math.min(original.length, ((this.canvasRef.current.width - SPACING) / (LINE_WIDTH + SPACING)) | 0); const factor = original.length / barCount; let amps = []; ",10 "diff --git a/package.json b/package.json ""test:ci"": ""NODE_ENV=test BABEL_ENV=test jest --ci --coverage"", ""test:update-snaps"": ""NODE_ENV=test BABEL_ENV=test jest -u"", ""test"": ""NODE_ENV=test BABEL_ENV=test jest"", - ""component"": ""node scripts/create_component.js"" + ""create-common-component"": ""node scripts/create_component.js"" }, ""lint-staged"": { ""*.js"": [ ",10 "diff --git a/components/Press/PressLinks/ArticleGroup/ArticleGroup.js b/components/Press/PressLinks/ArticleGroup/ArticleGroup.js @@ -4,7 +4,7 @@ import OutboundLink from 'components/_common_/OutboundLink/OutboundLink'; import Button from 'components/_common_/Button/Button'; import styles from './ArticleGroup.css'; -class ArticleItem extends Component { +class ArticleGroup extends Component { static propTypes = { links: PropTypes.arrayOf( PropTypes.shape({ @@ -57,4 +57,4 @@ class ArticleItem extends Component { } } -export default ArticleItem; +export default ArticleGroup; ",10 "diff --git a/components/HeroBanner/__stories__/HeroBanner.stories.js b/components/HeroBanner/__stories__/HeroBanner.stories.js @@ -12,7 +12,7 @@ storiesOf('Common/HeroBanner', module) 'default', withInfo()(() => ( ",10 "diff --git a/components/SocialMedia/SocialMedia.js b/components/SocialMedia/SocialMedia.js import React from 'react'; import FacebookLogo from 'static/images/icons/facebook_logo.svg'; import TwitterLogo from 'static/images/icons/twitter_logo.svg'; -import GithubLogoCircle from 'static/images/icons/github_logo_circle.svg'; +import GitHubLogo from 'static/images/icons/github_logo_circle.svg'; import InstagramLogo from 'static/images/icons/instagram_logo.svg'; import SocialMediaContainer from './SocialMediaContainer/SocialMediaContainer'; import SocialMediaItem from './SocialMediaItem/SocialMediaItem'; @@ -28,7 +28,7 @@ function SocialMedia() { } + svg={} /> ); ",10 "diff --git a/common/constants/partners.js b/common/constants/partners.js @@ -74,9 +74,9 @@ const partners = [ type: PARTNER_TYPES.KIND, }, { - name: 'Zeit', - logoSource: `${s3}partnerLogos/zeit.png`, - url: 'https://zeit.co/home', + name: 'Vercel', + logoSource: `${s3}partnerLogos/vercel.png`, + url: 'https://vercel.com/home', type: PARTNER_TYPES.KIND, }, ]; ",10 "diff --git a/package.json b/package.json ""name"": ""materialize-css"", ""description"": ""Builds Materialize distribution packages"", ""author"": ""Alvin Wang, Alan Chang"", - ""url"": ""http://materializecss.com/"", + ""homepage"": ""http://materializecss.com/"", ""version"": ""0.98.2"", ""main"": ""dist/js/materialize.js"", ""style"": ""dist/css/materialize.css"", ",10 "diff --git a/jade/page-contents/helpers_content.html b/jade/page-contents/helpers_content.html
    - +
    -

    Hiding Content

    -

    We provide easy to use classes to hide content on specific screen sizes.

    +

    Hiding/Showing Content

    +

    We provide easy to use classes to hide/show content on specific screen sizes.

    ",10 "diff --git a/jade/_navbar.jade b/jade/_navbar.jade @@ -77,7 +77,7 @@ header a(href='pagination.html') Pagination li(class=(page == ""Preloader"" ? ""active"" : """")) a(href='preloader.html') Preloader - li.bold(class=(page == ""Dialogs"" || page == ""Modals"" || page == ""Dropdown"" || page == ""FeatureDiscovery"" || page == ""Tabs"" || page == ""ScrollFire"" || page == ""Scrollspy"" || page == ""SideNav"" || page == ""Pushpin"" || page == ""Waves"" || page == ""Media"" || page == ""Transitions"" || page == ""Parallax"" || page == ""Collapsible"" ? ""active"" : """" || page == ""Carousel"" ? ""active"" : """")) + li.bold(class=(page == ""Dialogs"" || page == ""Modals"" || page == ""Dropdown"" || page == ""FeatureDiscovery"" || page == ""Tabs"" || page == ""ScrollFire"" || page == ""Scrollspy"" || page == ""Sidenav"" || page == ""Pushpin"" || page == ""Waves"" || page == ""Media"" || page == ""Transitions"" || page == ""Parallax"" || page == ""Collapsible"" ? ""active"" : """" || page == ""Carousel"" ? ""active"" : """")) a.collapsible-header(class=""waves-effect waves-teal"") | JavaScript .collapsible-body ",10 "diff --git a/modules/sepal-server/src/main/groovy/org/openforis/sepal/component/datasearch/adapter/CsvBackedUsgsGateway.groovy b/modules/sepal-server/src/main/groovy/org/openforis/sepal/component/datasearch/adapter/CsvBackedUsgsGateway.groovy @@ -110,7 +110,7 @@ class CsvBackedUsgsGateway implements DataSetMetadataGateway { } private Double cloudCover(Sensor sensor, data) { - def result = data.cloudCoverFull.toDouble() as Double + def result = data.cloudCover.toDouble() as Double // LANDSAT_7 with SLC off always miss about 22% of its data. Consider that cloud cover. if (result && sensor == LANDSAT_7 && data.SCAN_GAP_INTERPOLATION) result = Math.min(100, result + 22) @@ -121,7 +121,7 @@ class CsvBackedUsgsGateway implements DataSetMetadataGateway { def prefix = (data.sceneID as String).substring(0, 3) return data.COLLECTION_CATEGORY in ['T1', 'T2'] && data.dayOrNight == 'DAY' && - data.cloudCoverFull.toDouble() >= 0d && + data.cloudCover.toDouble() >= 0d && prefix in ['LT4', 'LT5', 'LE7', 'LC8'] } ",10 "diff --git a/modules/gui-react/frontend/src/backend.js b/modules/gui-react/frontend/src/backend.js @@ -256,9 +256,9 @@ const transformAoi = (aoi) => { case 'fusionTable': return { type: 'fusionTable', - tableName: aoi.id, + id: aoi.id, keyColumn: aoi.keyColumn, - keyValue: aoi.key + key: aoi.key } case 'polygon': return { ",10 "diff --git a/modules/gui-react/frontend/src/locale/en/translations.json b/modules/gui-react/frontend/src/locale/en/translations.json }, ""typology"": { ""title"": ""Typology"", - ""button"": ""TOP"", + ""button"": ""TYP"", ""tooltip"": ""Select typology"" }, ""trainingData"": { ",10 "diff --git a/modules/gui/frontend/src/locale/en/translations.json b/modules/gui/frontend/src/locale/en/translations.json ""type"": { ""label"": ""Scene selection"", ""all.label"": ""Use all scenes"", - ""select.label"": ""Select individual scenes"" + ""select.label"": ""Select scenes"" }, ""targetDateWeight"": { ""label"": ""Priority"", ",10 "diff --git a/modules/gui/frontend/src/locale/en/translations.json b/modules/gui/frontend/src/locale/en/translations.json ""tooltip"":""Remove image from classification"" }, ""sections"": { - ""title"": ""Add image to classify"" + ""title"": ""Image to classify"" }, ""recipe"": { - ""title"": ""Add saved Sepal recipe"" + ""title"": ""Saved Sepal recipe"" }, ""asset"": { - ""title"": ""Add Earth Engine asset"" + ""title"": ""Earth Engine asset"" }, ""form"": { ""section"": { ",10 "diff --git a/hosting-services/aws/sepal/monit/config.template b/hosting-services/aws/sepal/monit/config.template @@ -8,4 +8,4 @@ set mailserver {{ smtp_host }} port {{ smtp_port }} set mail-format { from: {{ smtp_from }} } -set alert {{ sepal_operator_email }} +set alert {{ sepal_monitoring_email }} ",10 "diff --git a/plugin.js b/plugin.js @@ -14,23 +14,23 @@ export default function({ app }, inject) { } let _fireStore, _fireFunc, _fireStorage, _fireAuth - if (!options.use || options.use.includes('firestore')) { + if (!options.useOnly || options.useOnly.includes('firestore')) { firebase.firestore().settings({ timestampsInSnapshots: true }) _fireStore = firebase.firestore() inject('fireStore', _fireStore) } - if (!options.use || options.use.includes('functions')) { + if (!options.useOnly || options.useOnly.includes('functions')) { _fireFunc = firebase.functions() inject('fireFunc', _fireFunc) } - if (!options.use || options.use.includes('storage')) { + if (!options.useOnly || options.useOnly.includes('storage')) { _fireStorage = firebase.storage() inject('fireStorage', _fireStorage) } - if (!options.use || options.use.includes('auth')) { + if (!options.useOnly || options.useOnly.includes('auth')) { const _fireAuth = firebase.auth() inject('fireAuth', _fireAuth) } ",10 "diff --git a/README.md b/README.md @@ -44,7 +44,7 @@ modules: [ #### useOnly -By default, all supported services are loaded. If you only wish to load certain services (recommended!), add this `useOnly` option. +By default, all supported Firebase products are loaded. If you only wish to load certain products (recommended!), add this `useOnly` option. - type: `Array` - default: `null` @@ -75,11 +75,11 @@ Same es `config`, but applies when `NODE_ENV === 'development'`. ## Usage -You can access the various Firebase services with **\$foo** in almost any context using `app.$foo` or `this.$foo`, including store actions. Make sure to replace the _foo_ with a shortcut from the table below. +You can access the various Firebase products with **\$foo** in almost any context using `app.$foo` or `this.$foo`, including store actions. Make sure to replace the _foo_ with a shortcut from the table below. -Services supported by nuxt-fire so far: +Firebase products supported by nuxt-fire so far: -| Firebase Service | Shortcut | +| Firebase Product | Shortcut | | ----------------- | --------------- | | Authentication | \$fireAuth | | RealTime Database | \$fireDb | ",10 "diff --git a/README.md b/README.md @@ -82,12 +82,12 @@ You can access the various Firebase products with **\$foo** in almost any contex Firebase products supported by nuxt-fire so far: | Firebase Product | Shortcut | -| ----------------- | --------------- | +| ----------------- | ------------- | | Authentication | \$fireAuth | | RealTime Database | \$fireDb | | Firestore | \$fireStore | | Storage | \$fireStorage | -| Functions | \$fireFunctions | +| Functions | \$fireFunc | See [Firebase's official docs](https://firebase.google.com/docs/) for more usage information. ",10 "diff --git a/plugin.js b/plugin.js @@ -50,8 +50,8 @@ export default (ctx, inject) => { } if(process.browser && options.useOnly.includes('performance')){ - const perf = firebase.performance() - inject('perf', perf) + const firePerf = firebase.performance() + inject('firePerf', firePerf) } } ",10 "diff --git a/packages/docs/options/README.md b/packages/docs/options/README.md @@ -113,7 +113,7 @@ All services mentioned below can have the following options: #### static -By default, each service gets imported dynamically, which splits them into separate chunks. If `static = true` however, we import them statically, so the services are bundled into `vendor.js`. +By default, each service gets imported dynamically, which splits them into separate chunks. If `static = true` however, we import them statically, so the services are bundled into `vendors.app.js`. ```js // static: false (default) ",10 "diff --git a/docs/examples/u-district-cuisine.md b/docs/examples/u-district-cuisine.md @@ -5,6 +5,6 @@ permalink: /examples/u-district-cuisine/index.html spec: u-district-cuisine --- -A [joy plot](http://blog.revolutionanalytics.com/2017/07/joyplots.html) showing the prevalence of various food and beverage categories in Seattle's University District. One never has to go far for coffee! Similar to a [violin plot](../violin-plot), this plot uses a continuous approximation of discrete data computed using [kernel density estimation (KDE)](https://en.wikipedia.org/wiki/Kernel_density_estimation). This graphic originally appeared in [Alaska Airlines Beyond Magazine (Sep 2017, p. 120)](http://www.paradigmcg.com/digitaleditions/abm-0917/html5/). +A [ridgeline plot](http://blog.revolutionanalytics.com/2017/07/joyplots.html) showing the prevalence of various food and beverage categories in Seattle's University District. One never has to go far for coffee! Similar to a [violin plot](../violin-plot), this plot uses a continuous approximation of discrete data computed using [kernel density estimation (KDE)](https://en.wikipedia.org/wiki/Kernel_density_estimation). This graphic originally appeared in [Alaska Airlines Beyond Magazine (Sep 2017, p. 120)](http://www.paradigmcg.com/digitaleditions/abm-0917/html5/). {% include example spec=page.spec %} ",10 "diff --git a/packages/vega-scenegraph/src/ImageLoader.js b/packages/vega-scenegraph/src/ImageLoader.js import Image from './util/canvas/image'; import {load} from 'vega-loader'; -export default function ImageLoader(loadConfig) { +export default function ImageLoader(loadOptions) { this._pending = 0; - this._config = loadConfig || ImageLoader.Config; + this._options = loadOptions || ImageLoader.Options; } // Overridable global default load configuration -ImageLoader.Config = {}; +ImageLoader.Options = {}; var prototype = ImageLoader.prototype; @@ -16,7 +16,7 @@ prototype.pending = function() { }; prototype.imageURL = function(uri) { - return load.sanitize(uri, this._config); + return load.sanitize(uri, this._options); }; prototype.loadImage = function(uri) { ",10 "diff --git a/packages/vega-encode/src/Scale.js b/packages/vega-encode/src/Scale.js @@ -17,8 +17,8 @@ var SKIP = { 'zero': 1, 'range': 1, + 'rangeStep': 1, 'round': 1, - 'bandSize': 1, 'reverse': 1 }; @@ -89,11 +89,15 @@ function configureRange(scale, _, count) { var type = scale.type, range = _.range; - if (_.bandSize != null) { + if (_.rangeStep != null) { if (type !== 'band' && type !== 'point') { - error('Only band and point scales support bandSize.'); + error('Only band and point scales support rangeStep.'); } - range = [0, _.bandSize * count]; + // calculate full range based on requested step size and padding + // Mirrors https://github.com/d3/d3-scale/blob/master/src/band.js#L23 + var inner = (_.paddingInner != null ? _.paddingInner : _.padding) || 0, + outer = (_.paddingOuter != null ? _.paddingOuter : _.padding) || 0; + range = [0, _.rangeStep * (count - (count > 1 ? inner : 0) + outer * 2)]; } if (range) { ",10 "diff --git a/packages/vega-runtime/test/expression-test.js b/packages/vega-runtime/test/expression-test.js @@ -15,7 +15,7 @@ tape('Parser parses expressions', function(test) { {id:0, type:'Operator', value: 50}, {id:1, type:'Operator', update: '2 * _.foo', params: {foo:{$ref:0}}}, {id:2, type:'Collect', value: {$ingest: values}}, - {id:3, type:'Apply', params: { + {id:3, type:'Formula', params: { expr: { $expr: 'datum.x * datum.y', $fields: ['x', 'y'] ",10 "diff --git a/packages/vega-typings/types/spec/scale.d.ts b/packages/vega-typings/types/spec/scale.d.ts @@ -114,23 +114,23 @@ export interface SequentialScale extends BaseScale { range: RangeScheme; clamp?: boolean | SignalRef; zero?: boolean | SignalRef; - nice?: boolean | Nice | SignalRef; + nice?: boolean | TimeInterval | SignalRef; } -export type Nice = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; +export type TimeInterval = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; export interface TimeScale extends BaseScale { type: 'time' | 'utc'; range?: RangeScheme; clamp?: boolean | SignalRef; - nice?: boolean | Nice | SignalRef; + nice?: boolean | TimeInterval | SignalRef; } export interface IdentityScale extends BaseScale { type: 'identity'; - nice?: Nice; + nice?: TimeInterval; } export interface DiscretizingScale extends BaseScale { type: DiscreteScaleType; range?: RangeScheme; - nice?: boolean | Nice | SignalRef; + nice?: boolean | TimeInterval | SignalRef; zero?: boolean | SignalRef; } export interface LinearScale extends BaseScale { ",10 "diff --git a/plugins/candela/web_client/views/CandelaWidget.js b/plugins/candela/web_client/views/CandelaWidget.js @@ -6,7 +6,6 @@ import CandelaWidgetTemplate from '../templates/candelaWidget.pug'; import '../stylesheets/candelaWidget.styl'; import candela from 'candela'; -import d3 from 'd3'; import datalib from 'datalib'; var CandelaWidget = View.extend({ @@ -46,8 +45,30 @@ var CandelaWidget = View.extend({ components: this._components })); this.parametersView.setElement($('.g-item-candela-parameters')); - d3.csv('/api/v1/item/' + this.item.get('_id') + '/download', (error, data) => { + datalib.csv('/api/v1/item/' + this.item.get('_id') + '/download', (error, data) => { datalib.read(data, {parse: 'auto'}); + + // Vega has issues with empty-string fields and fields with dots, so rename those. + let rename = []; + for (let key in data.__types__) { + if (data.__types__.hasOwnProperty(key)) { + if (key === '') { + rename.push(['', 'id']); + } else if (key.indexOf('.') >= 0) { + rename.push([key, key.replace(/\./g, '_')]); + } + } + } + + rename.forEach(d => { + data.__types__[d[1]] = data.__types__[d[0]]; + delete data.__types__[d[0]]; + data.forEach(row => { + row[d[1]] = row[d[0]]; + delete row[d[0]]; + }); + }); + let columns = []; for (let key in data.__types__) { if (data.__types__.hasOwnProperty(key)) { ",10 "diff --git a/plugins/candela/girder_candela/web_client/package.json b/plugins/candela/girder_candela/web_client/package.json ""peerDependencies"": { ""@girder/item_tasks"": ""*"" }, - ""girder-plugin"": { + ""girderPlugin"": { ""name"": ""candela"", ""main"": ""./main.js"", ""dependencies"": [""item_tasks""], ",10 "diff --git a/html/app.js b/html/app.js @@ -123,21 +123,21 @@ if (window.CefSharp) { Vue.filter('commaNumber', commaNumber); var formatDate = (s, format) => { - var ctx = new Date(s); - if (isNaN(ctx)) { + var dt = new Date(s); + if (isNaN(dt)) { return escapeTag(s); } - var hours = ctx.getHours(); + var hours = dt.getHours(); var map = { - 'YYYY': String(10000 + ctx.getFullYear()).substr(-4), - 'MM': String(101 + ctx.getMonth()).substr(-2), - 'DD': String(100 + ctx.getDate()).substr(-2), + 'YYYY': String(10000 + dt.getFullYear()).substr(-4), + 'MM': String(101 + dt.getMonth()).substr(-2), + 'DD': String(100 + dt.getDate()).substr(-2), 'HH24': String(100 + hours).substr(-2), 'HH': String(100 + (hours > 12 ? hours - 12 : hours)).substr(-2), - 'MI': String(100 + ctx.getMinutes()).substr(-2), - 'SS': String(100 + ctx.getSeconds()).substr(-2), + 'MI': String(100 + dt.getMinutes()).substr(-2), + 'SS': String(100 + dt.getSeconds()).substr(-2), 'AMPM': hours >= 12 ? 'PM' : 'AM' ",10 "diff --git a/html/app.js b/html/app.js @@ -206,11 +206,11 @@ if (window.CefSharp) { var API = {}; - API.$eventHandlers = new Map(); + API.eventHandlers = new Map(); API.$emit = function (name, ...args) { // console.log(name, ...args); - var handlers = this.$eventHandlers.get(name); + var handlers = this.eventHandlers.get(name); if (handlers === undefined) { return; } @@ -225,16 +225,16 @@ if (window.CefSharp) { }; API.$on = function (name, fx) { - var handlers = this.$eventHandlers.get(name); + var handlers = this.eventHandlers.get(name); if (handlers === undefined) { handlers = []; - this.$eventHandlers.set(name, handlers); + this.eventHandlers.set(name, handlers); } handlers.push(fx); }; API.$off = function (name, fx) { - var handlers = this.$eventHandlers.get(name); + var handlers = this.eventHandlers.get(name); if (handlers === undefined) { return; } @@ -244,14 +244,14 @@ if (window.CefSharp) { if (length > 1) { handlers.splice(i, 1); } else { - this.$eventHandlers.delete(name); + this.eventHandlers.delete(name); } break; } } }; - API.$pendingGetRequests = new Map(); + API.pendingGetRequests = new Map(); API.call = function (endpoint, options) { var input = `https://api.vrchat.cloud/api/1/${endpoint}`; @@ -276,7 +276,7 @@ if (window.CefSharp) { } delete init.body; // merge requests - var request = this.$pendingGetRequests.get(input); + var request = this.pendingGetRequests.get(input); if (request) { return request; } @@ -324,15 +324,15 @@ if (window.CefSharp) { if (isGetRequest) { req.finally(() => { - this.$pendingGetRequests.delete(input); + this.pendingGetRequests.delete(input); }); - this.$pendingGetRequests.set(input, req); + this.pendingGetRequests.set(input, req); } return req; }; - API.$status = { + API.statusCodes = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', @@ -410,7 +410,7 @@ if (window.CefSharp) { API.$throw = function (code, error, extra) { var text = []; if (code) { - var status = this.$status[code]; + var status = this.statusCodes[code]; if (status) { text.push(`${code} ${status}`); } else { ",10 "diff --git a/html/app.js b/html/app.js @@ -798,12 +798,12 @@ CefSharp.BindObjectAsync( }; var applyUserTrustLevel = function (ref) { - ref.$isVIP = ref.developerType && + ref.$isModerator = ref.developerType && ref.developerType !== 'none'; ref.$isTroll = false; var { tags } = ref; if (tags.includes('admin_moderator')) { - ref.$isVIP = true; + ref.$isModerator = true; } if (tags.includes('system_troll') || tags.includes('system_probable_troll')) { @@ -831,7 +831,7 @@ CefSharp.BindObjectAsync( ref.$trustLevel = 'Visitor'; ref.$trustClass = 'x-tag-untrusted'; } - if (ref.$isVIP) { + if (ref.$isModerator) { ref.$trustLevel = 'VRChat Team'; ref.$trustClass = 'x-tag-vip'; } else if (ref.$isTroll) { @@ -876,7 +876,7 @@ CefSharp.BindObjectAsync( offlineFriends: [], // VRCX $homeLocation: {}, - $isVIP: false, + $isModerator: false, $isTroll: false, $trustLevel: 'Visitor', $trustClass: 'x-tag-untrusted', @@ -956,7 +956,7 @@ CefSharp.BindObjectAsync( // VRCX $location: {}, $location_at: Date.now(), - $isVIP: false, + $isModerator: false, $isTroll: false, $trustLevel: 'Visitor', $trustClass: 'x-tag-untrusted', ",10 "diff --git a/html/src/app.js b/html/src/app.js @@ -10912,9 +10912,9 @@ speechSynthesis.getVoices(); $app.data.VRChatConfigFile = {}; $app.data.VRChatConfigList = { - cache_size: { name: 'Max Cache Size in Gigabytes (minimum 20)', default: '20' }, - cache_expiry_delay: { name: 'Expire Cache in Days (minimum 30)', default: '30' }, - cache_directory: { name: 'Custom Cache Directory Location', default: '%AppData%\\..\\LocalLow\\VRChat\\vrchat' }, + cache_size: { name: 'Max Cache Size [GB] (minimum 20)', default: '20' }, + cache_expiry_delay: { name: 'Cache Expiry [Days] (minimum 30)', default: '30' }, + cache_directory: { name: 'Custom Cache Folder Location', default: '%AppData%\\..\\LocalLow\\VRChat\\vrchat' }, dynamic_bone_max_affected_transform_count: { name: 'Dynamic Bones Limit Max Transforms (0 disables all components)', default: '32' }, dynamic_bone_max_collider_check_count: { name: 'Dynamic Bones Limit Max Collider Collisions (0 disables all components)', default: '8' } }; ",10 "diff --git a/src/browser/telemetry.js b/src/browser/telemetry.js @@ -87,8 +87,8 @@ Instrumenter.prototype.instrumentNetwork = function() { method: method, url: url, status_code: null, - open_time_ms: _.now(), - done_time_ms: null + start_time_ms: null, + end_time_ms: null }; } return orig.apply(this, arguments); @@ -102,9 +102,14 @@ Instrumenter.prototype.instrumentNetwork = function() { var xhr = this; function onreadystatechangeHandler() { - if (xhr.__rollbar_xhr && xhr.readyState === 4) { + // FIXME: This may create two identical events because of JS references + if (xhr.__rollbar_xhr && (xhr.readState === 1 || xhr.readyState === 4)) { try { - xhr.__rollbar_xhr.done_time_ms = _.now(); + if (xhr.readState === 1) { + xhr.__rollbar_xhr.start_time_ms = _.now(); + } else { + xhr.__rollbar_xhr.end_time_ms = _.now(); + } xhr.__rollbar_xhr.status_code = xhr.status; } catch (e) { /* ignore possible exception from xhr.status */ @@ -156,12 +161,12 @@ Instrumenter.prototype.instrumentNetwork = function() { method: method, url: url, status_code: null, - open_time_ms: _.now(), - done_time_ms: null + start_time_ms: _.now(), + end_time_ms: null }; self.telemeter.captureNetwork(metadata, 'fetch'); return orig.apply(this, args).then(function (resp) { - metadata.done_time_ms = _.now(); + metadata.end_time_ms = _.now(); metadata.status_code = resp.status; return resp; }); ",10 "diff --git a/src/browser/transforms.js b/src/browser/transforms.js @@ -309,12 +309,12 @@ function errorClass(stackInfo, guess, options) { } } -function addScrubber(scrub) { +function addScrubber(scrubFn) { return function (item, options, callback) { - if (scrub) { + if (scrubFn) { var scrubFields = options.scrubFields || []; var scrubPaths = options.scrubPaths || []; - item.data = scrub(item.data, scrubFields, scrubPaths); + item.data = scrubFn(item.data, scrubFields, scrubPaths); } callback(null, item); } ",10 "diff --git a/package.json b/package.json ""scripts"": { ""db"": ""nodemon ./db"", ""build"": ""webpack --config webpack_config/webpack.prod.js"", - ""build:demo"": ""BUILD_GH_PAGES=true webpack --config webpack_config/webpack.prod.js"", - ""jest"": ""jest"", - ""test"": ""jest --config=jest_config/jest.config.json --coverage"", + ""build:demo"": ""BUILD_DEMO=true webpack --config webpack_config/webpack.prod.js"", + ""test"": ""jest --config=jest_config/jest.config.json --coverage --forceExit"", ""dev"": ""node webpack_config/server.js"", ""ssr"": ""nodemon --exec REACT_WEBPACK_ENV='dev' babel-node ./common/server"" }, ",10 "diff --git a/docs/components/forms.md b/docs/components/forms.md @@ -189,7 +189,7 @@ Here are examples of `.form-control` applied to each textual HTML5 `` `ty | `time` | | | `color` | | -## Form layouts +## Layout Since Bootstrap applies `display: block` and `width: 100%` to almost all our form controls, forms will by default stack vertically. Additional classes can be used to vary this layout on a per-form basis. ",10 "diff --git a/build/saucelabs-unit-test.js b/build/saucelabs-unit-test.js @@ -17,13 +17,12 @@ const jsUnitSaucelabs = new JSUnitSaucelabs({ const testURL = 'http://localhost:3000/js/tests/index.html?hidepassed' const browsersFile = require(path.resolve(__dirname, './sauce_browsers.json')) let jobsDone = 0 -let jobsSuccess = 0 +let jobsSucceeded = 0 const waitingCallback = (error, body, id) => { if (error) { console.error(error) process.exit(1) - return } if (typeof body !== 'undefined') { @@ -55,14 +54,14 @@ const waitingCallback = (error, body, id) => { } if (passed) { - jobsSuccess++ + jobsSucceeded++ } jobsDone++ // Exit if (jobsDone === browsersFile.length - 1) { jsUnitSaucelabs.stop() - process.exit(jobsDone === jobsSuccess ? 0 : 1) + process.exit(jobsDone === jobsSucceeded ? 0 : 1) } } } @@ -70,9 +69,10 @@ const waitingCallback = (error, body, id) => { jsUnitSaucelabs.on('tunnelCreated', () => { browsersFile.forEach((tmpBrowser) => { - const broPlatform = typeof tmpBrowser.platform === 'undefined' ? tmpBrowser.platformName : tmpBrowser.platform - const arrayBro = [broPlatform, tmpBrowser.browserName, tmpBrowser.version] - jsUnitSaucelabs.start([arrayBro], testURL, 'qunit', (error, success) => { + const browsersPlatform = typeof tmpBrowser.platform === 'undefined' ? tmpBrowser.platformName : tmpBrowser.platform + const browsersArray = [browsersPlatform, tmpBrowser.browserName, tmpBrowser.version] + + jsUnitSaucelabs.start([browsersArray], testURL, 'qunit', (error, success) => { if (typeof success !== 'undefined') { const taskIds = success['js tests'] @@ -91,4 +91,5 @@ jsUnitSaucelabs.on('tunnelCreated', () => { }) }) }) + jsUnitSaucelabs.initTunnel() ",10 "diff --git a/scss/_variables.scss b/scss/_variables.scss @@ -530,9 +530,9 @@ $navbar-padding-x: $spacer !default; $navbar-brand-font-size: $font-size-lg !default; // Compute the navbar-brand padding-y so the navbar-brand will have the same height as navbar-text and nav-link -$nav-link-height: $navbar-brand-font-size * $line-height-base !default; -$navbar-brand-height: ($font-size-base * $line-height-base + $nav-link-padding-y * 2) !default; -$navbar-brand-padding-y: ($navbar-brand-height - $nav-link-height) / 2 !default; +$nav-link-height: ($font-size-base * $line-height-base + $nav-link-padding-y * 2) !default; +$navbar-brand-height: $navbar-brand-font-size * $line-height-base !default; +$navbar-brand-padding-y: ($nav-link-height - $navbar-brand-height) / 2 !default; $navbar-toggler-padding-y: .25rem !default; $navbar-toggler-padding-x: .75rem !default; ",10 "diff --git a/package.json b/package.json ""docs-lint-vnu-jar"": ""node build/vnu-jar.js"", ""docs-serve"": ""bundle exec jekyll serve"", ""docs-workbox-precache"": ""node build/workbox.js"", - ""maintenance-dependencies"": ""ncu -a -x jquery && npm update && bundle update && shx echo \""Manually update site/docs/4.1/assets/js/vendor/*, js/tests/vendor/* and .travis.yml\"""", + ""update-deps"": ""ncu -a -x jquery -x bundlesize && npm update && bundle update && shx echo Manually update \""site/docs/4.1/assets/js/vendor/\"""", ""release-sri"": ""node build/generate-sri.js"", ""release-version"": ""node build/change-version.js"", ""release-zip"": ""cross-env-shell \""shx cp -r dist/ bootstrap-$npm_package_version-dist && zip -r9 bootstrap-$npm_package_version-dist.zip bootstrap-$npm_package_version-dist && shx rm -rf bootstrap-$npm_package_version-dist\"""", ",10 "diff --git a/scss/_dropdown.scss b/scss/_dropdown.scss --#{$variable-prefix}dropdown-inner-border: #{$dropdown-inner-border-radius}; --#{$variable-prefix}dropdown-divider-bg: #{$dropdown-divider-bg}; --#{$variable-prefix}dropdown-divider-margin-y: #{$dropdown-divider-margin-y}; - --#{$variable-prefix}dropdown-shadow: #{$dropdown-box-shadow}; + --#{$variable-prefix}dropdown-box-shadow: #{$dropdown-box-shadow}; --#{$variable-prefix}dropdown-link-color: #{$dropdown-link-color}; --#{$variable-prefix}dropdown-link-hover-color: #{$dropdown-link-hover-color}; --#{$variable-prefix}dropdown-link-hover-bg: #{$dropdown-link-hover-bg}; background-clip: padding-box; border: var(--#{$variable-prefix}dropdown-border-width) solid var(--#{$variable-prefix}dropdown-border-color); @include border-radius(var(--#{$variable-prefix}dropdown-border-radius)); - @include box-shadow(var(--#{$variable-prefix}dropdown-shadow)); + @include box-shadow(var(--#{$variable-prefix}dropdown-box-shadow)); &[data-bs-popper] { top: 100%; --#{$variable-prefix}dropdown-color: #{$dropdown-dark-color}; --#{$variable-prefix}dropdown-bg: #{$dropdown-dark-bg}; --#{$variable-prefix}dropdown-border-color: #{$dropdown-dark-border-color}; - --#{$variable-prefix}dropdown-shadow: #{$dropdown-dark-box-shadow}; + --#{$variable-prefix}dropdown-box-shadow: #{$dropdown-dark-box-shadow}; --#{$variable-prefix}dropdown-link-color: #{$dropdown-dark-link-color}; --#{$variable-prefix}dropdown-link-hover-color: #{$dropdown-dark-link-hover-color}; --#{$variable-prefix}dropdown-divider-bg: #{$dropdown-dark-divider-bg}; ",10 "diff --git a/src/components/CenteredMap.js b/src/components/CenteredMap.js @@ -40,7 +40,7 @@ class CenteredMap extends React.PureComponent { minZoom={zoom} dragging={!frozen} scrollWheelZoom={false} - doubleClickZoom={false} + doubleClickZoom={!frozen} zoomControl={!frozen} > ( - ) +} Button.propTypes = { children: PropTypes.node, type: PropTypes.string, - name: PropTypes.string, - onClick: PropTypes.func, - disabled: PropTypes.bool, + href: PropTypes.string, size: PropTypes.oneOf([ 'large' ]) @@ -50,7 +67,7 @@ Button.propTypes = { Button.defaultProps = { type: 'button', - disabled: false + href: null } export default Button ",11 "diff --git a/components/box.js b/components/box.js import React from 'react' import PropTypes from 'prop-types' -const Box = ({ children, title, color }) => ( +const Box = ({ children, title, subtitle, color }) => (
    - {title &&

    {title}

    } + {(title || subtitle) && ( +
    + {title &&

    {title}

    } + {subtitle &&
    {subtitle}
    } +
    + )}
    {children}
    @@ -19,16 +24,23 @@ const Box = ({ children, title, color }) => ( overflow: hidden; } + .header { + padding: 0.6em 0.75em 0.55em; + } + h3 { font-size: 1.1em; margin: 0; - padding: 0.6em 0.75em 0.55em; max-width: 100%; overflow: hidden; text-overflow: ellipsis; font-weight: normal; } + .subtitle { + font-size: 0.9em; + } + .inner { padding: 1.5em 1.7em; @@ -41,11 +53,19 @@ const Box = ({ children, title, color }) => ( .grey { background-color: $lightgrey; + + .subtitle { + color: $grey; + } } .blue { background-color: $blue; color: $white; + + .subtitle { + color: lighten($blue, 35%); + } } `}
    @@ -54,6 +74,7 @@ const Box = ({ children, title, color }) => ( Box.propTypes = { children: PropTypes.node, title: PropTypes.string, + subtitle: PropTypes.string, color: PropTypes.oneOf([ 'grey', 'blue' ",11 "diff --git a/MaterialSkin/HTML/material/html/js/queue-page.js b/MaterialSkin/HTML/material/html/js/queue-page.js @@ -83,10 +83,10 @@ var lmsQueue = Vue.component(""LmsQueue"", { {{ snackbar.msg }} - + 0"">{{trackCount | displayCount}} {{duration | displayTime(true)}} - queue_music + queue_music save clear_all @@ -108,7 +108,7 @@ var lmsQueue = Vue.component(""LmsQueue"", { {{item.subtitle}} 0"" class=""pq-time"">{{item.duration | displayTime}} - 1"" @click.stop=""itemMenu(item, index, $event)""> + 0"" @click.stop=""itemMenu(item, index, $event)""> more_vert ",11 "diff --git a/MaterialSkin/HTML/material/html/js/toolbar.js b/MaterialSkin/HTML/material/html/js/toolbar.js @@ -58,10 +58,10 @@ Vue.component('lms-toolbar', { info - + pause_circle_outline - + play_circle_outline volume_down ",11 "diff --git a/MaterialSkin/HTML/material/html/js/store.js b/MaterialSkin/HTML/material/html/js/store.js @@ -145,7 +145,7 @@ const store = new Vuex.Store({ var config = getLocalStorageVal('player'); if (config) { state.players.forEach(p => { - if (p.id === config) { + if (p.id === config || p.name == config) { state.player = p; } }); ",11 "diff --git a/MaterialSkin/HTML/material/html/css/mobile.css b/MaterialSkin/HTML/material/html/css/mobile.css .np-image { display: block; object-fit: contain; - height:calc((var(--vh, 1vh)*100) - (var(--main-toolbar-height) + var(--bottom-nav-height) - 24px)); + height:calc((var(--vh, 1vh)*100) - (var(--main-toolbar-height) + var(--bottom-nav-height) - 32px)); width:calc(100vw - 16px); margin-left: auto; margin-right: auto; ",11 "diff --git a/MaterialSkin/HTML/material/html/js/browse-page.js b/MaterialSkin/HTML/material/html/js/browse-page.js @@ -959,20 +959,35 @@ var lmsBrowse = Vue.component(""lms-browse"", { } }, itemAction(act, item, index, suppressNotification) { - if (!this.playerId()) { - bus.$emit('showError', undefined, i18n(""No Player"")); - return; + if (act==SEARCH_LIB_ACTION) { + this.dialog = { show:true, title:i18n(""Search library""), ok: i18n(""Search""), cancel:undefined, + command:[""search""], params:[""tags:jlyAdt"", ""extended:1"", ""term:""+TERM_PLACEHOLDER], item:{title:i18n(""Search""), id:TOP_SEARCH_ID}}; + } else if (act===MORE_ACTION) { + this.fetchItems(this.buildCommand(item, B_ACTIONS[act].cmd), item); + } else if (act===MORE_LIB_ACTION) { + if (item.id) { + if (item.id.startsWith(""artist_id:"")) { + this.fetchItems({command: [""artistinfo"", ""items""], params: [""menu:1"", item.id, ""html:1""]}, item); + } else if (item.id.startsWith(""album_id:"")) { + this.fetchItems({command: [""albuminfo"", ""items""], params: [""menu:1"", item.id, ""html:1""]}, item); + } else if (item.id.startsWith(""track_id:"")) { + this.fetchItems({command: [""trackinfo"", ""items""], params: [""menu:1"", item.id, ""html:1""]}, item); + } else if (item.id.startsWith(""genre_id:"")) { + this.fetchItems({command: [""genreinfo"", ""items""], params: [""menu:1"", item.id, ""html:1""]}, item); } - - if (act===RENAME_PL_ACTION) { + } + } else if (act===PIN_ACTION) { + this.pin(item, true); + } else if (act===UNPIN_ACTION) { + this.pin(item, false); + } else if (!this.playerId()) { // *************** NO PLAYER *************** + bus.$emit('showError', undefined, i18n(""No Player"")); + } else if (act===RENAME_PL_ACTION) { this.dialog = { show:true, title:i18n(""Rename playlist""), hint:item.value, value:item.title, ok: i18n(""Rename""), cancel:undefined, command:[""playlists"", ""rename"", item.id, ""newname:""+TERM_PLACEHOLDER]}; } else if (act==RENAME_FAV_ACTION) { this.dialog = { show:true, title:i18n(""Rename favorite""), hint:item.value, value:item.title, ok: i18n(""Rename""), cancel:undefined, command:[""favorites"", ""rename"", item.id, ""title:""+TERM_PLACEHOLDER]}; - } else if (act==SEARCH_LIB_ACTION) { - this.dialog = { show:true, title:i18n(""Search library""), ok: i18n(""Search""), cancel:undefined, - command:[""search""], params:[""tags:jlyAdt"", ""extended:1"", ""term:""+TERM_PLACEHOLDER], item:{title:i18n(""Search""), id:TOP_SEARCH_ID}}; } else if (act==ADD_FAV_ACTION) { bus.$emit('dlg.open', 'favorite', 'add'); } else if (act==EDIT_FAV_ACTION) { @@ -1074,24 +1089,6 @@ var lmsBrowse = Vue.component(""lms-browse"", { }).catch(err => { logAndShowError(err, undefined, [""albums""], params, 0, 1); }); - } else if (act===MORE_ACTION) { - this.fetchItems(this.buildCommand(item, B_ACTIONS[act].cmd), item); - } else if (act===MORE_LIB_ACTION) { - if (item.id) { - if (item.id.startsWith(""artist_id:"")) { - this.fetchItems({command: [""artistinfo"", ""items""], params: [""menu:1"", item.id, ""html:1""]}, item); - } else if (item.id.startsWith(""album_id:"")) { - this.fetchItems({command: [""albuminfo"", ""items""], params: [""menu:1"", item.id, ""html:1""]}, item); - } else if (item.id.startsWith(""track_id:"")) { - this.fetchItems({command: [""trackinfo"", ""items""], params: [""menu:1"", item.id, ""html:1""]}, item); - } else if (item.id.startsWith(""genre_id:"")) { - this.fetchItems({command: [""genreinfo"", ""items""], params: [""menu:1"", item.id, ""html:1""]}, item); - } - } - } else if (act===PIN_ACTION) { - this.pin(item, true); - } else if (act===UNPIN_ACTION) { - this.pin(item, false); } else if (SELECT_ACTION===act) { var idx=this.selection.indexOf(index); if (idx<0) { ",11 "diff --git a/MaterialSkin/HTML/material/html/css/classic-skin-mods.css b/MaterialSkin/HTML/material/html/css/classic-skin-mods.css @@ -124,7 +124,8 @@ select option[value=INTERFACE_SETTINGS] { .homeMenuSection div, .settingSection .groupHead, .settingSection .prefHead { background-color: transparent; - height: 15px; + min-height: 15px; + height: auto !important; padding: 8px 6px 4px 0px; font-weight: bold; } ",11 "diff --git a/MaterialSkin/HTML/material/html/js/server.js b/MaterialSkin/HTML/material/html/js/server.js @@ -761,7 +761,7 @@ var lmsServer = Vue.component('lms-server', { bindKey('left'); bindKey('right'); bus.$on('keyboard', function(key) { - if (!this.$store.state.keyboardControl || this.$store.state.visibleMenus.size>0 || this.$store.state.openDialogs.length>0 || !this.$store.state.player) { + if (!this.$store.state.keyboardControl || !this.$store.state.player || this.$store.state.visibleMenus.size>0 || (this.$store.state.openDialogs.length>0 && this.$store.state.openDialogs[0]!='info-dialog')) { return; } var command = undefined; ",11 "diff --git a/MaterialSkin/HTML/material/html/js/utils.js b/MaterialSkin/HTML/material/html/js/utils.js @@ -19,7 +19,7 @@ function logJsonMessage(type, msg) { function logCometdMessage(type, msg) { if (debug && (debug.has(""cometd"") || debug.has(""true""))) { - console.log(""["" + new Date().toLocaleTimeString()+""] COMETED ""+type+"": ""+JSON.stringify(msg)); + console.log(""["" + new Date().toLocaleTimeString()+""] COMETED ""+type+(msg ? ("": ""+JSON.stringify(msg)) : """")); } } ",11 "diff --git a/MaterialSkin/HTML/material/html/js/toolbar.js b/MaterialSkin/HTML/material/html/js/toolbar.js @@ -39,7 +39,7 @@ Vue.component('lms-toolbar', { {{index|playerShortcut}} - 1""> + open_in_new ",11 "diff --git a/MaterialSkin/HTML/material/html/js/randommix-dialog.js b/MaterialSkin/HTML/material/html/js/randommix-dialog.js @@ -20,7 +20,7 @@ Vue.component('lms-randommix', { -
    +
    check_box ",12 "diff --git a/MaterialSkin/HTML/material/html/js/browse-resp.js b/MaterialSkin/HTML/material/html/js/browse-resp.js @@ -13,6 +13,13 @@ function parseBrowseResp(data, parent, options, idStart, cacheKey) { try { if (data && data.result) { resp.total = data.result.count; + if (resp.total>LMS_BATCH_SIZE) { + resp.total = 1; + resp.subtitle=i18n(""%1 Items"", data.result.count); + resp.items.push({title:i18n(""ERROR: Too many items. A maximum of %1 items can be handled. Please use A..Z groups""), type: 'text', id:'error'}); + return resp; + } + resp.useScroller = (parent && parent.range ? parent.range.count : resp.total) >= LMS_MIN_LIST_SCROLLER_ITEMS; logJsonMessage(""RESP"", data); if (parent.id && TOP_SEARCH_ID===parent.id) { ",12 "diff --git a/MaterialSkin/HTML/material/html/js/utils.js b/MaterialSkin/HTML/material/html/js/utils.js @@ -268,8 +268,11 @@ function fixId(id, prefix) { function setBgndCover(elem, coverUrl, isDark) { if (elem) { elem.style.backgroundColor = isDark ? ""#424242"" : ""#fff""; - elem.style.backgroundImage = ""url('""+(undefined==coverUrl || coverUrl.endsWith(DEFAULT_COVER) || coverUrl.endsWith(""/music/undefined/cover"") - ? undefined : coverUrl)+""')""; + if (undefined==coverUrl || coverUrl.endsWith(DEFAULT_COVER) || coverUrl.endsWith(""/music/undefined/cover"")) { + elem.style.backgroundImage = ""url()""; + } else { + elem.style.backgroundImage = ""url('""+coverUrl+""')""; + } if (isDark) { //if (coverUrl) { elem.style.boxShadow = ""inset 0 0 120vw 120vh rgba(72,72,72,0.9)""; ",12 "diff --git a/MaterialSkin/HTML/material/html/js/browse-resp.js b/MaterialSkin/HTML/material/html/js/browse-resp.js @@ -10,6 +10,9 @@ const MORE_COMMANDS = new Set([""item_add"", ""item_insert"", ""itemplay"", ""item_fav"" function parseBrowseResp(data, parent, options, idStart, cacheKey) { // NOTE: If add key to resp, then update addToCache in utils.js var resp = {items: [], baseActions:[], useGrid: false, total: 0, useScroller: false, jumplist:[] }; + if (undefined==idStart) { + idStart = 0; + } try { if (data && data.result) { @@ -431,9 +434,6 @@ function parseBrowseResp(data, parent, options, idStart, cacheKey) { } if (!i.id) { - if (undefined==idStart) { - idStart = 0; - } if (parent.id.startsWith(TOP_ID_PREFIX)) { i.id=""item_id:""+idStart; } else { @@ -721,7 +721,7 @@ function parseBrowseResp(data, parent, options, idStart, cacheKey) { var isFolder = i.type===""folder""; var key = i.textkey; if (undefined!=key && (resp.jumplist.length==0 || resp.jumplist[resp.jumplist.length-1].key!=key)) { - resp.jumplist.push({key: key, index: resp.items.length+idStart, title}); + resp.jumplist.push({key: key, index: resp.items.length+idStart}); } resp.items.push({ id: (isFolder ? ""folder_id:"" : ""track_id:"") + i.id, ",12 "diff --git a/MaterialSkin/HTML/material/html/css/style.css b/MaterialSkin/HTML/material/html/css/style.css .v-list__tile__title, .v-select__selection, .v-select__selection--comma { font-size:var(--std-font-size); + font-weight:var(--std-weight); } .v-list__tile__sub-title, .v-btn__content, .v-select__slot .v-label { font-size:var(--small-font-size); + font-weight:var(--std-weight); } .v-text-field, .v-select__slot .v-label, .v-input .v-label { @@ -44,6 +46,7 @@ html { overflow-y:hidden; margin:0px; font-size:var(--std-font-size); + font-weight:var(--std-weight); } body { @@ -371,6 +374,7 @@ a { .maintoolbar-title { font-size:var(--std-font-size) !important; + font-weight:var(--bold-weight); } .noplayer-title { ",12 "diff --git a/MaterialSkin/HTML/material/html/js/toolbar.js b/MaterialSkin/HTML/material/html/js/toolbar.js @@ -131,7 +131,7 @@ Vue.component('lms-toolbar', { {{playerStatus.isplaying ? 'pause_circle_outline' : 'play_circle_outline'}} - + info_outline ",12 "diff --git a/MaterialSkin/HTML/material/html/js/toolbar.js b/MaterialSkin/HTML/material/html/js/toolbar.js @@ -270,7 +270,7 @@ Vue.component('lms-toolbar', { if (this.desktop) { bus.$on('playerChanged', function() { // Ensure we update volume when player changes. - this.playerVolume.id = undefined; + this.playerVolume = undefined; }.bind(this)); } ",12 "diff --git a/MaterialSkin/HTML/material/html/js/main.js b/MaterialSkin/HTML/material/html/js/main.js @@ -316,6 +316,7 @@ var app = new Vue({ var that = this; this.splitter = Split([that.$refs.left, that.$refs.right], { sizes: [this.splitterPercent, 100-this.splitterPercent], + minSize: Math.floor(LMS_MIN_DESKTOP_WIDTH/2), gutterSize: 3, gutterAlign: 'center', snapOffset: 5, ",12 "diff --git a/MaterialSkin/HTML/material/html/js/queue-page.js b/MaterialSkin/HTML/material/html/js/queue-page.js @@ -399,6 +399,9 @@ var lmsQueue = Vue.component(""lms-queue"", { this.playlistName=playerStatus.playlist.name; if (playerStatus.playlist.timestamp!=this.timestamp || (playerStatus.playlist.timestamp>0 && this.items.length<1) || (playerStatus.playlist.timestamp<=0 && this.items.length>0) || this.listSize!=playerStatus.playlist.count) { + if (playerStatus.playlist.current!=this.currentIndex) { + this.autoScrollRequired = true; + } this.currentIndex = playerStatus.playlist.current; this.timestamp = playerStatus.playlist.timestamp; this.updateItems(); ",12 "diff --git a/MaterialSkin/HTML/material/html/css/style.css b/MaterialSkin/HTML/material/html/css/style.css @@ -162,6 +162,14 @@ html, .mini-player { max-width:10px; } +::-webkit-scrollbar-thumb:vertical { + min-height:64px; +} + +::-webkit-scrollbar-thumb:horizontal { + min-width:64px; +} + html { overflow-y:hidden; margin:0px; ",12 "diff --git a/MaterialSkin/HTML/material/html/js/constants.js b/MaterialSkin/HTML/material/html/js/constants.js const LMS_BATCH_SIZE = 25000; const LMS_QUEUE_BATCH_SIZE = 500; -const LMS_MAX_NON_SCROLLER_ITEMS = 200; +const LMS_MAX_NON_SCROLLER_ITEMS = 75; const LMS_MAX_PLAYERS = 100; const LMS_IMAGE_SZ = 300 const LMS_IMAGE_SIZE = ""_""+LMS_IMAGE_SZ+""x""+LMS_IMAGE_SZ+""_f""; ",12 "diff --git a/MaterialSkin/HTML/material/html/js/constants.js b/MaterialSkin/HTML/material/html/js/constants.js const LMS_BATCH_SIZE = 25000; const LMS_QUEUE_BATCH_SIZE = 500; -const LMS_MAX_NON_SCROLLER_ITEMS = 75; +const LMS_MAX_NON_SCROLLER_ITEMS = 100; const LMS_MAX_PLAYERS = 100; const LMS_IMAGE_SZ = 300 const LMS_IMAGE_SIZE = ""_""+LMS_IMAGE_SZ+""x""+LMS_IMAGE_SZ+""_f""; ",12 "diff --git a/MaterialSkin/HTML/material/html/js/manage-players.js b/MaterialSkin/HTML/material/html/js/manage-players.js @@ -96,7 +96,7 @@ Vue.component('lms-manage-players', { - {{player.icon.icon}} + {{player.icon.icon}} {{player.name}}checkhotel {{player.track}} @@ -571,6 +571,7 @@ Vue.component('lms-manage-players', { dragStart(which, ev) { ev.dataTransfer.dropEffect = 'move'; ev.dataTransfer.setData('Text', ""player:""+which); + ev.dataTransfer.setDragImage(document.getElementById(""pmgr-player-""+which), 0, 0); this.dragIndex = which; this.stopScrolling = false; this.draggingSyncedPlayer = this.players[which].issyncmaster || undefined!=this.players[which].syncmaster; ",12 "diff --git a/MaterialSkin/HTML/material/html/js/search-field.js b/MaterialSkin/HTML/material/html/js/search-field.js @@ -55,7 +55,7 @@ Vue.component('lms-search-field', { stopDebounce() { if (undefined!=this.debounceTimer) { clearTimeout(this.debounceTimer); - this.debounceTimer; + this.debounceTimer = undefined; } }, advanced() { ",12 "diff --git a/MaterialSkin/HTML/material/html/js/browse-resp.js b/MaterialSkin/HTML/material/html/js/browse-resp.js @@ -145,6 +145,7 @@ function parseBrowseResp(data, parent, options, cacheKey, parentCommand, parentG i.text = undefined; i.image = resolveImage(i.icon ? i.icon : i[""icon-id""], undefined, LMS_IMAGE_SIZE); + i.icon = undefined; if (!i.image && i.commonParams && i.commonParams.album_id) { i.image = resolveImage(""music/0/cover"" + LMS_IMAGE_SIZE); ",12 "diff --git a/MaterialSkin/Plugin.pm b/MaterialSkin/Plugin.pm @@ -72,6 +72,8 @@ sub initPlugin { if (my $bandgenres = $prefs->get('bandgenres')) { $prefs->set('bandgenres', $DEFAULT_BAND_GENRES) if $bandgenres eq ''; + } else { + $prefs->set('bandgenres', $DEFAULT_BAND_GENRES); } $prefs->init({ ",12 "diff --git a/MaterialSkin/HTML/material/html/js/iframe-dialog.js b/MaterialSkin/HTML/material/html/js/iframe-dialog.js @@ -165,7 +165,7 @@ function hideClassicSkinElems(page, textCol) { selector.addEventListener(""change"", selectChanged); selectChanged(); } - } else if ('other'==page || 'extra'==page) { + } else if ('other'==page || 'lms'==page) { if (content) { if (content.addEventListener) { content.addEventListener('click', otherClickHandler); @@ -252,8 +252,8 @@ Vue.component('lms-iframe-dialog', { ? ""player"" : page.indexOf(""server/basic.html"")>0 ? ""server"" - : page.startsWith(""plugins/"") && (page.indexOf(""?player="")>0 || page.indexOf(""&player="")>0) - ? ""extra"" + : (page == '/material/html/docs/index.html') || (page.startsWith(""plugins/"") && (page.indexOf(""?player="")>0 || page.indexOf(""&player="")>0)) + ? ""lms"" // tech info, or 'extra' entry : ""other""; this.show = true; this.showMenu = false; ",12 "diff --git a/MaterialSkin/HTML/material/html/js/browse-page.js b/MaterialSkin/HTML/material/html/js/browse-page.js @@ -1555,7 +1555,7 @@ var lmsBrowse = Vue.component(""lms-browse"", { var len = this.history.length; this.click(item); if (this.history.length>len) { - this.prevPage = NP_INFO; + this.prevPage = page; } } else { this.fetchItems(this.replaceCommandTerms({command:cmd, params:params}), {cancache:false, id:params[0], title:title, stdItem:params[0].startsWith(""artist_id:"") ? STD_ITEM_ARTIST : STD_ITEM_ALBUM}, page); ",12 "diff --git a/MaterialSkin/HTML/material/standardheader.html b/MaterialSkin/HTML/material/standardheader.html [% IF pagetitle %][% pagetitle | html -%][% ELSE %][% ""SQUEEZEBOX_SERVER"" | string %][% END -%] - - + + ",12 "diff --git a/MaterialSkin/HTML/material/index.html b/MaterialSkin/HTML/material/index.html + ",12 "diff --git a/MaterialSkin/HTML/material/index.html b/MaterialSkin/HTML/material/index.html - Logitech Media Server [% PERL %] my $version=Plugins::MaterialSkin::Plugin->pluginVersion(); + my $windowTitle=Plugins::MaterialSkin::Plugin->windowTitle(); my $ua=$stash->get('userAgent'); print(""\n""); print("" \n""); print("" \n""); - print("" ""); + print("" \n""); + print("" ${windowTitle}\n""); + print("" \n""); + print("" ""); [% END %] - -
    [% PERL %] my $version=Plugins::MaterialSkin::Plugin->pluginVersion(); my $windowTitle=Plugins::MaterialSkin::Plugin->windowTitle(); - print(""\n""); + print(""\n""); print("" \n""); print("" \n""); print("" \n""); ",12 "diff --git a/MaterialSkin/HTML/material/html/js/browse-page.js b/MaterialSkin/HTML/material/html/js/browse-page.js @@ -181,7 +181,7 @@ var lmsBrowse = Vue.component(""lms-browse"", { - + ",12 "diff --git a/MaterialSkin/HTML/material/html/js/browse-resp.js b/MaterialSkin/HTML/material/html/js/browse-resp.js @@ -184,7 +184,7 @@ function parseBrowseResp(data, parent, options, cacheKey, parentCommand, parentG if (!i.type && !i.style && i.actions && i.actions.go && i.actions.go.params) { for (var key in i.actions.go.params) { if (i.actions.go.params[key]==TERM_PLACEHOLDER) { - i.type = ""entry""; + i.type = key==""search"" ? key : ""entry""; } } } ",12 "diff --git a/app/templates/components/payments/funds-recipient/details-form.hbs b/app/templates/components/payments/funds-recipient/details-form.hbs
    SSN Last 4
    - {{input type=""text"" name=""legal-entity-ssn-last-4"" value=stripeConnectAccount.legalEntitySsnLast4}} + {{input type=""text"" name=""legal-entity-ssn-last-4"" maxlength=""4"" value=stripeConnectAccount.legalEntitySsnLast4}}
    ",12 "diff --git a/app/routes/project-version/namespaces/namespace.js b/app/routes/project-version/namespaces/namespace.js import ClassRoute from '../classes/class'; export default ClassRoute.extend({ - templateName: 'project-version/class', + templateName: 'project-version/classes/class', model(params, transition) { return this.getModel('namespace', params, transition); ",12 "diff --git a/bin/ember-fastboot b/bin/ember-fastboot const FastBootAppServer = require('fastboot-app-server'); const ExpressHTTPServer = require('fastboot-app-server/src/express-http-server'); const parseArgs = require('minimist'); +const express = require('express'); const { URL } = require('url'); // Provide a title to the process in `ps` @@ -26,7 +27,6 @@ if (!distPath) { } const serverOptions = { - // assetsCacheControl: 'max-age=365000000, immutable', distPath, gzip: false, // Let Fastly take care of compression, reducing load on the fastboot }; @@ -35,6 +35,12 @@ const httpServer = new ExpressHTTPServer(serverOptions); const app = httpServer.app; +app.use(express.static(distPath, { + setHeaders(res, path, stat) { + res.setHeader('Cache-Control', 'public, max-age=365000000, immutable'); + } +})); + /** We rewrite the 307 location header into a relativeURL so that our special setup is handled */ app.use(function(req, res, next) { const originalSendFn = res.send; ",12 "diff --git a/.travis.yml b/.travis.yml @@ -12,7 +12,7 @@ cache: yarn: true before_install: - - curl -o- -L https://yarnpkg.com/install.sh | bash + - curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.0.1 - export PATH=$HOME/.yarn/bin:$PATH - yarn global add bower ",12 "diff --git a/test/protractor.ci.bs.conf.js b/test/protractor.ci.bs.conf.js @@ -40,6 +40,7 @@ exports.config = { 'browserstack.video': true, 'browserstack.local': false, 'browserstack.networkLogs': false, + 'browserstack.timezone': 'America/New_York', build: browserstackBuildID, name: `${theme} theme ci:bs e2e tests`, project: 'ids-enterprise-e2e-ci' ",12 "diff --git a/.travis.yml b/.travis.yml @@ -19,6 +19,7 @@ install: - npm install -g grunt-cli - npm install before_script: + - export TZ=America/New_York - if [ $TEST_SUITE != lint ]; then npm run build; fi script: - if [ $TEST_SUITE = e2e ]; then (npm run quickstart &) && sleep 5; fi ",12 "diff --git a/src/components/tabs/tabs.js b/src/components/tabs/tabs.js @@ -2500,12 +2500,12 @@ Tabs.prototype = { */ this.element.trigger('close', [targetLi]); - // If any tabs are left in the list, set the previous tab as the currently selected one. + // If any tabs are left in the list, set the first available tab as the currently selected one. let count = targetLiIndex - 1; while (count > -1) { count = -1; if (prevLi.is(notATab)) { - prevLi = prevLi.prev(); + prevLi = this.tablist.children('li').not(notATab)[0]; count -= 1; } } @@ -2538,6 +2538,7 @@ Tabs.prototype = { } } + console.log(prevLi); this.focusBar(prevLi); a.focus(); ",12 "diff --git a/package.json b/package.json { ""name"": ""ids-enterprise"", ""slug"": ""ids-enterprise"", - ""version"": ""4.22.0-rc.0"", + ""version"": ""4.23.0-dev"", ""description"": ""Infor Design System (IDS) Enterprise Components for the web"", ""repository"": { ""type"": ""git"", ",12 "diff --git a/src/components/homepage/homepage.js b/src/components/homepage/homepage.js @@ -25,6 +25,7 @@ const HOMEPAGE_DEFAULTS = { animate: true, columns: 3, editable: true, + editing = false, // Private easing: 'blockslide', // Private gutterSize: 20, // Private widgetWidth: 360, // Private @@ -34,7 +35,6 @@ const HOMEPAGE_DEFAULTS = { function Homepage(element, settings) { this.settings = utils.mergeSettings(element, settings, HOMEPAGE_DEFAULTS); - this.editing = true; // Private this.element = $(element); debug.logTimeStart(COMPONENT_NAME); this.init(); ",12 "diff --git a/src/components/checkboxes/_checkboxes.scss b/src/components/checkboxes/_checkboxes.scss input.checkbox, span.checkbox > input { - left: -99999px; + left: 0; opacity: 0; - position: fixed; + position: absolute; top: 0; width: 16px;// use fixed, to prevent page jump on click ",12 "diff --git a/src/components/mask/masks.js b/src/components/mask/masks.js @@ -129,6 +129,8 @@ function addThousandsSeparator(n, thousands, options, localeStringOpts) { zeros -= 1; formatted = `0${formatted}`; } + } else { + formatted = n; } return formatted; @@ -170,6 +172,12 @@ masks.numberMask = function sohoNumberMask(rawValue, options) { if (!options.locale || !options.locale.length) { options.locale = Locale.currentLocale.name; } + + const dSeparator = Locale.getSeparator(options.locale, 'decimal'); + if (dSeparator === ',') { + options.symbols.decimal = ','; + } + // Deprecated in v4.25.1 if (options.allowLeadingZeroes) { warnAboutDeprecation('allowLeadingZeros', 'allowLeadingZeroes', 'Number Mask'); @@ -185,6 +193,9 @@ masks.numberMask = function sohoNumberMask(rawValue, options) { const suffixLength = SUFFIX && SUFFIX.length || 0; const thousandsSeparatorSymbolLength = THOUSANDS && THOUSANDS.length || 0; + console.log(THOUSANDS); + console.log(DECIMAL); + function numberMask(thisRawValue) { if (typeof thisRawValue !== 'string') { thisRawValue = masks.EMPTY_STRING; @@ -249,6 +260,7 @@ masks.numberMask = function sohoNumberMask(rawValue, options) { style: 'decimal', useGrouping: true }; + integer = (options.allowThousandsSeparator) ? addThousandsSeparator(integer, THOUSANDS, options, localeOptions) : integer; ",12 "diff --git a/src/utils/environment.js b/src/utils/environment.js @@ -273,6 +273,7 @@ const Environment = { if (Environment.browser.isIPad()) { const osVersionStr = nUAgent.substr(nUAgent.indexOf('Version'), nUAgent.substr(nUAgent.indexOf('Version')).indexOf(' ')); osVersion = osVersionStr.replace('Version/', ''); + os = 'IOS'; } this.devicespecs = { ",12 "diff --git a/package.json b/package.json ""e2e:puppeteer"": ""npx --no-install jest --config=test/jest.config.js --runInBand --detectOpenHandles --forceExit"", ""e2e:update-imagesnapshots"": ""npx --no-install jest --config=test/jest.config.js --updateSnapshot --runInBand --detectOpenHandles --forceExit"", ""webdriver:clean"": ""npx webdriver-manager clean"", - ""webdriver:update"": ""npx webdriver-manager update --standalone false --quiet --gecko=false"", + ""webdriver:update"": ""npx webdriver-manager update --versions.chrome=98.0.4758.102 --standalone false --quiet --gecko=false"", ""zip-dist"": ""npx grunt zip-dist"", ""documentation"": ""node ./scripts/deploy-documentation.js"", ""release:dev"": ""node scripts/publish-nightly-manual"", ""node-version-check"": ""npx check-node-version --node 14"", ""node-updates-check"": ""npx ncu"" }, - ""chrome-version"": ""99"", + ""chrome-version"": ""98"", ""dependencies"": { ""d3"": ""^5.16.0"", ""ids-identity"": ""4.11.3"", ",12 "diff --git a/examples/manage.py b/examples/manage.py @@ -6,6 +6,7 @@ sys.path[0:0] = [os.path.abspath('..'), os.path.abspath('../../django-websocket- if __name__ == ""__main__"": os.environ.setdefault(""DJANGO_SETTINGS_MODULE"", ""server.settings"") + os.environ.setdefault('DJANGO_STATIC_ROOT', '/web/production/managed/djangular/static') from django.core.management import execute_from_command_line ",12 "diff --git a/djng/forms/fields.py b/djng/forms/fields.py @@ -277,6 +277,11 @@ class MultipleFieldMixin(DefaultFieldMixin): class ChoiceField(MultipleFieldMixin, fields.ChoiceField): + def __init__(self, *args, **kwargs): + super(ChoiceField, self).__init__(*args, **kwargs) + if isinstance(self.widget, widgets.Select) and self.initial is None and len(self.choices): + self.initial = self.choices[0][0] + def has_subwidgets(self): return isinstance(self.widget, widgets.RadioSelect) ",12 "diff --git a/examples/server/forms/combined_validation.py b/examples/server/forms/combined_validation.py @@ -33,7 +33,9 @@ class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3Form): sex = fields.ChoiceField( choices=(('m', 'Male'), ('f', 'Female')), widget=widgets.RadioSelect, - error_messages={'invalid_choice': 'Please select your sex'}) + required=True, + error_messages={'invalid_choice': 'Please select your sex'}, + ) email = fields.EmailField( label='E-Mail', @@ -81,8 +83,10 @@ class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3Form): notifyme = fields.MultipleChoiceField( label='Notify by', choices=NOTIFY_BY, - widget=widgets.CheckboxSelectMultiple, required=True, - help_text='Must choose at least one type of notification') + widget=widgets.CheckboxSelectMultiple, + required=True, + help_text='Must choose at least one type of notification', + ) annotation = fields.CharField( label='Annotation', @@ -98,6 +102,7 @@ class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3Form): label='Password', widget=widgets.PasswordInput, validators=[validate_password], + min_length=6, help_text='The password is ""secret""') confirmation_key = fields.CharField( @@ -126,4 +131,5 @@ default_subscribe_data = { 'notifyme': ['email', 'sms'], 'annotation': ""Lorem ipsum dolor sit amet, consectetur adipiscing elit."", 'agree': True, + 'password': '', } ",12 "diff --git a/src/epics/fetch-dataset-epic.js b/src/epics/fetch-dataset-epic.js @@ -17,8 +17,7 @@ const fetchDatasetEpic = (action$, store) => { return Observable .ajax({ url: url, crossDomain: true, responseType: 'json' }) .map((result) => result.response ) - // .of(fakeData.slice(0, size)).delay(1000) // Fake AJAX call for now - .map((data) => setDataset({ dataset: data }) ) + .map((data) => setDataset({ dataset: data.dataset, configuration: data.configuration }) ) .concat(Observable.of(setHierarchyConfig([]))) // Ignore result if another request has started. ",12 "diff --git a/src/containers/blocks.jsx b/src/containers/blocks.jsx @@ -210,6 +210,8 @@ class Blocks extends React.Component { const dynamicBlocksXML = this.props.vm.runtime.getBlocksXML(); const toolboxXML = makeToolboxXML(dynamicBlocksXML); this.props.onExtensionAdded(toolboxXML); + const categoryName = blocksInfo[0].json.category; + this.workspace.toolbox_.setSelectedCategoryByName(categoryName); } setBlocks (blocks) { this.blocks = blocks; ",12 "diff --git a/src/components/sprite-info/sprite-info.jsx b/src/components/sprite-info/sprite-info.jsx @@ -56,6 +56,7 @@ class SpriteInfo extends React.Component {
    @@ -78,6 +79,7 @@ class SpriteInfo extends React.Component {
    ",12 "diff --git a/.travis.yml b/.travis.yml @@ -36,3 +36,13 @@ deploy: skip_cleanup: true email: $NPM_EMAIL api_key: $NPM_TOKEN +- provider: s3 + on: + branch: master + access_key_id: $AWS_ACCESS_KEY_ID + secret_access_key: $AWS_SECRET_ACCESS_KEY + bucket: $AWS_BUCKET_NAME + acl: public_read + detect_encoding: true + skip_cleanup: true + local_dir: build ",12 "diff --git a/.travis.yml b/.travis.yml @@ -6,7 +6,9 @@ addons: node_js: - 8 env: + global: - NODE_ENV=production + - SMOKE_URL=https://llk.github.io/scratch-gui/$TRAVIS_PULL_REQUEST_BRANCH cache: directories: - node_modules @@ -19,7 +21,7 @@ before_deploy: - git config --global user.name $(git log --pretty=format:""%an"" -n1) script: - npm test -- if [ ""$TRAVIS_PULL_REQUEST"" != ""false"" ] && [ ""$TRAVIS_BRANCH"" == ""master"" ]; then npm run test:smoke; fi +- if [ ""$TRAVIS_EVENT_TYPE"" == ""pull_request"" ] && [ ""$TRAVIS_BRANCH"" == ""master"" ]; then npm run test:smoke; fi deploy: - provider: script on: ",12 "diff --git a/sheets/wsl.md b/sheets/wsl.md @@ -23,6 +23,15 @@ Change between WSL versions wsl --set-version Debian 2 ``` +## Set the default version of WSL + +When installing new Linux distros you can default them all to be WSL2 +or or one: + +```bash +wsl --set-default-version 2 +``` + ## List installed WSL Distros ```bash ",12 "diff --git a/package.json b/package.json ""build"": ""npm run gen:syntax && browserify --standalone csstree lib/index.js | uglifyjs --compress --mangle -o dist/csstree.js"", ""codestyle-and-test"": ""npm run codestyle && npm test"", ""codestyle"": ""jscs data lib scripts test && eslint data lib scripts test"", - ""test"": ""mocha --reporter dot"", - ""coverage"": ""istanbul cover _mocha -- -R dot"", + ""test"": ""mocha --reporter progress"", + ""coverage"": ""istanbul cover _mocha -- -R min"", ""prepublish"": ""npm run build"", ""travis"": ""npm run codestyle-and-test && npm run coveralls"", - ""coveralls"": ""istanbul cover _mocha --report lcovonly -- -R dot && cat ./coverage/lcov.info | coveralls"", + ""coveralls"": ""istanbul cover _mocha --report lcovonly -- -R min && cat ./coverage/lcov.info | coveralls"", ""hydrogen"": ""node --trace-hydrogen --trace-phase=Z --trace-deopt --code-comments --hydrogen-track-positions --redirect-code-traces --redirect-code-traces-to=code.asm --trace_hydrogen_file=code.cfg --print-opt-code bin/parse --stat -o /dev/null"" }, ""dependencies"": { ",12 "diff --git a/package.json b/package.json ""test"": ""mocha --reporter progress"", ""gen:syntax"": ""node scripts/gen-syntax-data"", ""coverage"": ""istanbul cover _mocha -- -R min"", - ""prepublish"": ""npm run build"", + ""prepublishOnly"": ""npm run build"", ""travis"": ""npm run lint-and-test && npm run coveralls"", ""coveralls"": ""istanbul cover _mocha --report lcovonly -- -R min && cat ./coverage/lcov.info | coveralls"", ""hydrogen"": ""node --trace-hydrogen --trace-phase=Z --trace-deopt --code-comments --hydrogen-track-positions --redirect-code-traces --redirect-code-traces-to=code.asm --trace_hydrogen_file=code.cfg --print-opt-code bin/parse --stat -o /dev/null"" ",12 "diff --git a/package.json b/package.json ""format"": ""prettier --write \""src/**/*.js\"""", ""lint"": ""eslint ."", ""test"": ""echo \""Error: no test specified\"" && exit 1"", - ""storybook"": ""start-storybook -p 6006 -s static"", - ""build-storybook"": ""build-storybook -s static"", + ""storybook"": ""NODE_ENV=production start-storybook -p 6006 -s static"", + ""build-storybook"": ""NODE_ENV=production build-storybook -s static"", ""chromatic"": ""CHROMATIC_APP_CODE=dd2oqshntir chromatic test"" }, ""devDependencies"": { ",12 "diff --git a/buildkite/src/Jobs/Lint/ValidationService.dhall b/buildkite/src/Jobs/Lint/ValidationService.dhall @@ -58,7 +58,7 @@ in Pipeline.build Pipeline.Config::{ commands = commands, label = ""Validation service lint steps; employs various forms static analysis on the elixir codebase"", key = ""lint"", - target = Size.Large, + target = Size.Small, docker = None Docker.Type } ] ",12 "diff --git a/buildkite/src/Jobs/LintOpt.dhall b/buildkite/src/Jobs/LintOpt.dhall @@ -26,7 +26,9 @@ Pipeline.build , steps = [ Command.build Command.Config:: - { commands = OpamInit.andThenRunInDocker [""CI=true"", ""BASE_BRANCH_NAME=$BUILDKITE_PULL_REQUEST_BASE_BRANCH"" ] ""./scripts/compare_ci_diff_types.sh"" + { commands = [ Cmd.run ""git config http.sslVerify false"" ] # OpamInit.andThenRunInDocker + ([""CI=true"", ""BASE_BRANCH_NAME=$BUILDKITE_PULL_REQUEST_BASE_BRANCH"" ]) + (""./scripts/compare_ci_diff_types.sh"") , label = ""Compare CI diff types"" , key = ""lint-diff-types"" , target = Size.Medium @@ -34,7 +36,9 @@ Pipeline.build }, Command.build Command.Config:: - { commands = OpamInit.andThenRunInDocker [""CI=true"", ""BASE_BRANCH_NAME=$BUILDKITE_PULL_REQUEST_BASE_BRANCH"" ] ""./scripts/compare_ci_diff_binables.sh"" + { commands = [ Cmd.run ""git config http.sslVerify false"" ] # OpamInit.andThenRunInDocker + ([""CI=true"", ""BASE_BRANCH_NAME=$BUILDKITE_PULL_REQUEST_BASE_BRANCH"" ]) + (""./scripts/compare_ci_diff_binables.sh"") , label = ""Compare CI diff binables"" , key = ""lint-diff-binables"" , target = Size.Medium ",12 "diff --git a/scripts/archive/build-release-archives.sh b/scripts/archive/build-release-archives.sh @@ -98,7 +98,7 @@ if [ -n ""${BUILDKITE+x}"" ]; then set -x # Export variables for use with downstream steps echo ""export CODA_SERVICE=coda-archive"" >> ./ARCHIVE_DOCKER_DEPLOY - echo ""export CODA_VERSION=${VERSION}"" >> ./ARCHIVE_DOCKER_DEPLOY + echo ""export CODA_VERSION=${DOCKER_TAG}"" >> ./ARCHIVE_DOCKER_DEPLOY echo ""export CODA_DEB_VERSION=${VERSION}"" >> ./ARCHIVE_DOCKER_DEPLOY echo ""export CODA_DEB_REPO=${CODENAME}"" >> ./ARCHIVE_DOCKER_DEPLOY echo ""export CODA_GIT_HASH=${GITHASH}"" >> ./ARCHIVE_DOCKER_DEPLOY ",12 "diff --git a/src/app/archive/archive_lib/processor.ml b/src/app/archive/archive_lib/processor.ml @@ -810,6 +810,15 @@ module Block = struct ~protocol_state:t.protocol_state ~staged_ledger_diff:t.staged_ledger_diff ~hash:(Protocol_state.hash t.protocol_state) + let set_parent_id_if_null (module Conn : CONNECTION) ~parent_hash + ~(parent_id : int) = + Conn.exec + (Caqti_request.exec + Caqti_type.(tup2 int string) + ""UPDATE blocks SET parent_id = ? WHERE parent_hash = ? AND parent_id \ + IS NULL"") + (parent_id, State_hash.to_base58_check parent_hash) + let delete_if_older_than ?height ?num_blocks ?timestamp (module Conn : CONNECTION) = let open Deferred.Result.Let_syntax in @@ -897,11 +906,19 @@ let run (module Conn : CONNECTION) reader ~constraint_constants ~logger match%bind let open Deferred.Result.Let_syntax in let%bind () = Conn.start () in - let%bind _ = + let%bind block_id = Block.add_if_doesn't_exist ~constraint_constants (module Conn) block in + (* if an existing block has a parent hash that's for the block just added, + set its parent id + *) + let%bind () = + Block.set_parent_id_if_null + (module Conn) + ~parent_hash:block.hash ~parent_id:block_id + in match delete_older_than with | Some num_blocks -> Block.delete_if_older_than ~num_blocks (module Conn) ",12 "diff --git a/automation/terraform/modules/kubernetes/testnet/helm.tf b/automation/terraform/modules/kubernetes/testnet/helm.tf @@ -22,7 +22,7 @@ data ""local_file"" ""libp2p_peers"" { } locals { - use_local_charts = true + use_local_charts = false mina_helm_repo = ""https://coda-charts.storage.googleapis.com"" seed_peers = [ ",12 "diff --git a/buildkite/src/Command/DeployTestnet.dhall b/buildkite/src/Command/DeployTestnet.dhall @@ -34,8 +34,8 @@ let testnetArtifactPath = ""/tmp/artifacts"" in ), Cmd.run ( -- upload/cache testnet genesis_ledger - ""BUILDKITE_ARTIFACT_UPLOAD_DESTINATION=gs://buildkite_k8s/coda/shared/\\\${BUILDKITE_JOB_ID}"" ++ - "" pushd ${testnetArtifactPath} && buildkite-agent artifact upload \""genesis_ledger.json\"" && popd"" + ""pushd ${testnetArtifactPath} && BUILDKITE_ARTIFACT_UPLOAD_DESTINATION=gs://buildkite_k8s/coda/shared/\\\${BUILDKITE_JOB_ID}"" ++ + "" buildkite-agent artifact upload \""genesis_ledger.json\"" && popd"" ), Cmd.run ( -- always execute post-deploy operation ",12 "diff --git a/automation/terraform/modules/o1-testnet/testnet.tf b/automation/terraform/modules/o1-testnet/testnet.tf @@ -54,7 +54,24 @@ module ""kubernetes_testnet"" { seed_zone = var.seed_zone seed_region = var.seed_region - archive_configs = var.archive_configs + archive_configs = length(var.archive_configs) != 0 ? var.archive_configs : concat( + # by default, deploy a single local daemon and associated PostgresDB enabled archive server + [ + { + name = ""archive-1"" + enableLocalDaemon = true + enablePostgresDB = true + } + ], + # in addition to stand-alone archive servers upto the input archive node count + [ + for i in range(2, var.archive_node_count + 1) : { + name = ""archive-${i}"" + enableLocalDaemon = false + enablePostgresDB = false + } + ] + ) mina_archive_schema = var.mina_archive_schema snark_worker_replicas = var.snark_worker_replicas ",12 "diff --git a/automation/terraform/testnets/mainnet/main.tf b/automation/terraform/testnets/mainnet/main.tf @@ -55,8 +55,8 @@ variable ""seed_count"" { locals { testnet_name = ""mainnet"" - coda_image = ""TODO"" # TODO - coda_archive_image = ""TODO"" # TODO + coda_image = ""gcr.io/o1labs-192920/coda-daemon-baked:1.1.1-06691e3-mainnet-ffbe7e0"" + coda_archive_image = ""gcr.io/o1labs-192920/coda-archive:1.1.1-06691e3"" seed_region = ""us-east4"" seed_zone = ""us-east4-b"" ",12 "diff --git a/src/app/archive/archive_lib/metrics.ml b/src/app/archive/archive_lib/metrics.ml @@ -15,7 +15,7 @@ let default_missing_blocks_width = 2000 module Max_block_height = struct let query = Caqti_request.find Caqti_type.unit Caqti_type.int - ""SELECT MAX(height) FROM blocks"" + ""SELECT GREATEST(0, MAX(height)) FROM blocks"" let update (module Conn : Caqti_async.CONNECTION) metric_server = time ~label:""max_block_height"" (fun () -> ",12 "diff --git a/src/app/archive/archive_lib/processor.ml b/src/app/archive/archive_lib/processor.ml @@ -1628,6 +1628,18 @@ module Block = struct (Caqti_request.find Caqti_type.unit Caqti_type.(tup2 int int64) ""SELECT id,height FROM blocks WHERE chain_status='canonical' ORDER BY height DESC LIMIT 1"") + let get_nearest_canonical_block_above (module Conn : CONNECTION) height = + Conn.find + (Caqti_request.find Caqti_type.int64 Caqti_type.(tup2 int int64) + ""SELECT id,height FROM blocks WHERE chain_status='canonical' AND height > ? ORDER BY height ASC LIMIT 1"") + height + + let get_nearest_canonical_block_below (module Conn : CONNECTION) height = + Conn.find + (Caqti_request.find Caqti_type.int64 Caqti_type.(tup2 int int64) + ""SELECT id,height FROM blocks WHERE chain_status='canonical' AND height < ? ORDER BY height DESC LIMIT 1"") + height + let mark_as_canonical (module Conn : CONNECTION) ~state_hash = Conn.exec (Caqti_request.exec Caqti_type.string @@ -1651,18 +1663,27 @@ module Block = struct let%bind highest_canonical_block_id,greatest_canonical_height = get_highest_canonical_block (module Conn) () in if Int64.(>) block.height (Int64.(+) greatest_canonical_height k_int64) then - (* subchain between new block and highest canonical block *) + (* a new block, allows marking some pending blocks as canonical *) let%bind subchain_blocks = get_subchain (module Conn) ~start_block_id:highest_canonical_block_id ~end_block_id:block_id in let block_height_less_k_int64 = Int64.(-) block.height k_int64 in (* mark canonical, orphaned blocks in subchain at least k behind the new block *) let canonical_blocks = List.filter subchain_blocks ~f:(fun subchain_block -> Int64.(<=) subchain_block.height block_height_less_k_int64) in - let%map () = deferred_result_list_fold canonical_blocks ~init:() ~f:(fun () block -> + deferred_result_list_fold canonical_blocks ~init:() ~f:(fun () block -> + let%bind () = mark_as_canonical (module Conn) ~state_hash:block.state_hash in + mark_as_orphaned (module Conn) ~state_hash:block.state_hash ~height:block.height) + else if Int64.(<) block.height greatest_canonical_height then + (* a missing block added in the middle of canonical chain *) + let%bind canonical_block_above_id,_above_height = get_nearest_canonical_block_above (module Conn) block.height in + let%bind canonical_block_below_id,_below_height = get_nearest_canonical_block_below (module Conn) block.height in + (* we can always find this chain: the genesis block should be marked as canonical, and we've found a + canonical block above this one *) + let%bind canonical_blocks = get_subchain (module Conn) ~start_block_id:canonical_block_below_id ~end_block_id:canonical_block_above_id in + deferred_result_list_fold canonical_blocks ~init:() ~f:(fun () block -> let%bind () = mark_as_canonical (module Conn) ~state_hash:block.state_hash in mark_as_orphaned (module Conn) ~state_hash:block.state_hash ~height:block.height) - in - () else + (* a block at or above highest canonical block, not high enough to mark any blocks as canonical *) Deferred.Result.return () let delete_if_older_than ?height ?num_blocks ?timestamp ",12 "diff --git a/src/lib/transaction_snark/test/zkapps_examples/initialize_state/initialize_state.ml b/src/lib/transaction_snark/test/zkapps_examples/initialize_state/initialize_state.ml @@ -60,6 +60,20 @@ let%test_module ""Initialize state test"" = *) Zkapp_account.digest_vk vk } + ; permissions = + Set + { edit_state = Proof + ; send = Proof + ; receive = Proof + ; set_delegate = Proof + ; set_permissions = Proof + ; set_verification_key = Proof + ; set_zkapp_uri = Proof + ; edit_sequence_state = Proof + ; set_token_symbol = Proof + ; increment_nonce = Proof + ; set_voting_for = Proof + } } ; use_full_commitment = true ; account_precondition = Accept ",12 "diff --git a/src/lib/mina_wire_types/mina_base/mina_base_signed_command.mli b/src/lib/mina_wire_types/mina_base/mina_base_signed_command.mli @@ -27,7 +27,7 @@ module With_valid_signature : sig module M : sig module Stable : sig module V2 : sig - type t = Stable.V2.t + type t = private Stable.V2.t end end end ",12 "diff --git a/src/lib/transaction_snark/test/zkapps_examples/big_circuit/big_circuit.ml b/src/lib/transaction_snark/test/zkapps_examples/big_circuit/big_circuit.ml @@ -46,6 +46,7 @@ let deploy_account_update_body : Account_update.Body.t = { Account_update.Preconditions.network = Zkapp_precondition.Protocol_state.accept ; account = Accept + ; valid_while = Ignore } ; call_type = Call ; use_full_commitment = true ",12 "diff --git a/serverjs/util.js b/serverjs/util.js @@ -68,7 +68,8 @@ function addCardToCube(cube, card_details, idOverride) { colors: card_details.color_identity, cmc: card_details.cmc, cardID: idOverride === undefined ? card_details._id : idOverride, - type: card_details.type + type: card_details.type, + addedTmsp: new Date() }); } ",12 "diff --git a/__tests__/serverjs/cubefn.test.js b/__tests__/serverjs/cubefn.test.js +var sinon = require(""sinon""); const cubefn = require(""../../serverjs/cubefn""); const carddb = require(""../../serverjs/cards""); const cubefixture = require(""../../fixtures/examplecube""); @@ -163,9 +164,14 @@ const exampleBasics = { } }; -beforeEach(() => {}); +beforeEach(() => { + sinon.stub(Cube, ""findOne""); +}); -afterEach(() => {}); +afterEach(() => { + Cube.findOne.restore(); + carddb.unloadCardDb(); +}); test(""get_cube_id returns urlAlias when defined"", () => { const testCube = { @@ -337,4 +343,17 @@ test(""setCubeType correctly sets the type and card_count of its input cube"", () test(""sanitize"", () => {}); test(""addAutocard"", () => {}); -test(""generatePack"", () => {}); \ No newline at end of file + +test(""generatePack"", () => { + expect.assertions(1); + const seed = new Date(); + var exampleCube = JSON.parse(JSON.stringify(cubefixture.exampleCube)); + var expected = {}; + Cube.findOne.yields(null, exampleCube); + var callback = sinon.stub(); + var promise = carddb.initializeCardDb(fixturesPath, true); + return promise.then(function() { + cubefn.generatePack('', carddb, seed, callback); + sinon.assert.calledWith(callback, expected) + }); +}); \ No newline at end of file ",12 "diff --git a/src/pages/BrowsePackagesPage.js b/src/pages/BrowsePackagesPage.js @@ -45,7 +45,7 @@ const BrowsePackagesPage = ({ user, loginCallback }) => { const [alerts, setAlerts] = useState([]); const [page, setPage] = useQueryParam('p', 0); const [filter, setFilter] = useQueryParam('f', ''); - const [filterTemp, setFilterTemp] = useState(filter); + const [filterTemp, setFilterTemp] = useState(''); const [sort, setSort] = useQueryParam('s', 'votes'); const [sortDirection, setSortDirection] = useQueryParam('d', '-1'); const [selectedTab, setSelectedTab] = useQueryParam('tab', '0'); @@ -82,7 +82,7 @@ const BrowsePackagesPage = ({ user, loginCallback }) => { } return []; }; - fetchData(); + fetchData().then(() => setFilterTemp(filter)); }, [filter, page, sort, sortDirection, selectedTab, refresh, setRefresh]); return ( ",12 "diff --git a/src/pages/CubePlaytestPage.js b/src/pages/CubePlaytestPage.js @@ -585,7 +585,20 @@ CubePlaytestPage.propTypes = { defaultDraftFormat: PropTypes.number, _id: PropTypes.string.isRequired, owner: PropTypes.string.isRequired, - draft_formats: PropTypes.arrayOf(PropTypes.object), + draft_formats: PropTypes.shape({ + title: PropTypes.string, + multiples: PropTypes.bool, + markdown: PropTypes.string.isRequired, + packs: PropTypes.arrayOf( + PropTypes.shape({ + slots: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired, + steps: PropTypes.shape({ + action: PropTypes.oneOf(['pass', 'pick', 'trash', 'pickrandom', 'trashrandom']), + amount: PropTypes.number, + }), + }).isRequired, + ).isRequired, + }).isRequired, }).isRequired, decks: PropTypes.arrayOf(DeckPropType).isRequired, user: UserPropType, ",12 "diff --git a/src/extensions/export/bootstrap-table-export.js b/src/extensions/export/bootstrap-table-export.js @@ -86,6 +86,41 @@ $.BootstrapTable = class extends $.BootstrapTable { let $menu = $(this.constants.html.toolbarDropdown.join('')) + let exportTypes = o.exportTypes + + if (typeof exportTypes === 'string') { + const types = exportTypes.slice(1, -1).replace(/ /g, '').split(',') + exportTypes = types.map(t => t.slice(1, -1)) + } + + if (exportTypes.length === 1) { + this.$export = $(` +
    + +
    + `).appendTo($btnGroup) + + this.updateExportButton() + + $btnGroup.click(e => { + e.preventDefault() + + const type = exportTypes[0] + const exportOptions = { + type, + escape: false + } + + this.exportTable(exportOptions) + }) + } + else { this.$export = $(`
    - - ",13 "diff --git a/src/components/datagrid/datagrid.js b/src/components/datagrid/datagrid.js @@ -7374,10 +7374,6 @@ Datagrid.prototype = { // Sync the Ui and call the events this.dontSyncUi = false; - // It should not clear the selectedRows in lookup - const isLookup = $('.lookup'); - this._selectedRows = !isLookup.length ? [] : this._selectedRows; - // Update the display counts when unselecting all rows this.displayCounts(); ",13 "diff --git a/test/components/applicationmenu/applicationmenu.puppeteer-spec.js b/test/components/applicationmenu/applicationmenu.puppeteer-spec.js @@ -102,7 +102,7 @@ describe('Application Menu Puppeteer Test', () => { .then(boundingBox => expect(boundingBox.width).toEqual(menuSize.width)); }); - it('should resize at the near end of the page', async () => { + it.skip('should resize at the near end of the page', async () => { const windowSize = await page.viewport(); const location = [{ y: 0, x: windowSize.width - (windowSize.width * 0.1) }]; @@ -128,7 +128,7 @@ describe('Application Menu Puppeteer Test', () => { .then(boundingBox => expect(boundingBox.width).toEqual(menuSize.width)); }); - it('should save last resize', async () => { + it.skip('should save last resize', async () => { const windowSize = await page.viewport(); const location = [{ y: 0, x: windowSize.width - (windowSize.width * 0.1) }]; ",13 "diff --git a/package.json b/package.json ""e2e:puppeteer"": ""npx --no-install jest --config=test/jest.config.js --runInBand --detectOpenHandles --forceExit"", ""e2e:update-imagesnapshots"": ""npx --no-install jest --config=test/jest.config.js --updateSnapshot --runInBand --detectOpenHandles --forceExit"", ""webdriver:clean"": ""npx webdriver-manager clean"", - ""webdriver:update"": ""npx webdriver-manager update --versions.chrome=99.0.4844.35 --standalone false --quiet --gecko=false"", + ""webdriver:update"": ""npx webdriver-manager update --standalone false --quiet --gecko=false"", ""zip-dist"": ""npx grunt zip-dist"", ""documentation"": ""node ./scripts/deploy-documentation.js"", ""release:dev"": ""node scripts/publish-nightly-manual"", ",13 "diff --git a/src/components/datagrid/_datagrid.scss b/src/components/datagrid/_datagrid.scss @@ -2822,10 +2822,12 @@ $datagrid-small-row-height: 25px; } } - //Cell Editting + //Cell Editing &.is-editing { background-color: $datagrid-cell-editing-bg-color; position: relative; + outline: 1px solid $ids-color-brand-primary-base; + outline-offset: -1px; &.has-singlecolumn { display: block; @@ -2833,7 +2835,6 @@ $datagrid-small-row-height: 25px; } .datagrid-cell-wrapper { - border: 1px solid $ids-color-brand-primary-base; left: 0; position: absolute; text-overflow: clip; ",13 "diff --git a/test/components/datagrid/datagrid-validation.func-spec.js b/test/components/datagrid/datagrid-validation.func-spec.js @@ -15,23 +15,23 @@ let datagridObj; // Define Columns for the Grid. const columns = []; -columns.push({ id: 'selectionCheckbox', sortable: false, resizable: false, formatter: Soho.Formatters.SelectionCheckbox, align: 'center' }); -columns.push({ id: 'productId', name: 'Id', field: 'productId', reorderable: true, formatter: Soho.Formatters.Text, width: 100, filterType: 'Text' }); +columns.push({ id: 'selectionCheckbox', sortable: false, resizable: false, formatter: Formatters.SelectionCheckbox, align: 'center' }); +columns.push({ id: 'productId', name: 'Id', field: 'productId', reorderable: true, formatter: Formatters.Text, width: 100, filterType: 'Text' }); columns.push({ - id: 'productName', name: 'Product Name', field: 'productName', reorderable: true, formatter: Soho.Formatters.Hyperlink, width: 300, filterType: 'Text', editor: Editors.Input + id: 'productName', name: 'Product Name', field: 'productName', reorderable: true, formatter: Formatters.Hyperlink, width: 300, filterType: 'Text', editor: Editors.Input }); columns.push({ id: 'activity', name: 'Activity', field: 'activity', reorderable: true, filterType: 'Text', required: true, validate: 'required', editor: Editors.Input }); columns.push({ id: 'hidden', hidden: true, name: 'Hidden', field: 'hidden', filterType: 'Text' }); columns.push({ - id: 'price', align: 'right', name: 'Actual Price', field: 'price', reorderable: true, formatter: Soho.Formatters.Decimal, validate: 'required', numberFormat: { minimumFractionDigits: 0, maximumFractionDigits: 0, style: 'currency', currencySign: '$' }, editor: Editors.Input + id: 'price', align: 'right', name: 'Actual Price', field: 'price', reorderable: true, formatter: Formatters.Decimal, validate: 'required', numberFormat: { minimumFractionDigits: 0, maximumFractionDigits: 0, style: 'currency', currencySign: '$' }, editor: Editors.Input }); -columns.push({ id: 'percent', align: 'right', name: 'Actual %', field: 'percent', reorderable: true, formatter: Soho.Formatters.Decimal, numberFormat: { minimumFractionDigits: 0, maximumFractionDigits: 0, style: 'percent' } }); +columns.push({ id: 'percent', align: 'right', name: 'Actual %', field: 'percent', reorderable: true, formatter: Formatters.Decimal, numberFormat: { minimumFractionDigits: 0, maximumFractionDigits: 0, style: 'percent' } }); columns.push({ - id: 'orderDate', name: 'Order Date', field: 'orderDate', reorderable: true, formatter: Soho.Formatters.Date, dateFormat: 'M/d/yyyy', validate: 'required date', editor: Editors.Date + id: 'orderDate', name: 'Order Date', field: 'orderDate', reorderable: true, formatter: Formatters.Date, dateFormat: 'M/d/yyyy', validate: 'required date', editor: Editors.Date }); -columns.push({ id: 'phone', name: 'Phone', field: 'phone', reorderable: true, filterType: 'Text', formatter: Soho.Formatters.Text }); +columns.push({ id: 'phone', name: 'Phone', field: 'phone', reorderable: true, filterType: 'Text', formatter: Formatters.Text }); describe('Datagrid Validation API', () => { const Locale = window.Soho.Locale; ",13 "diff --git a/test/components/cards/cards.puppeteer-spec.js b/test/components/cards/cards.puppeteer-spec.js @@ -248,22 +248,22 @@ describe('Cards', () => { expect(await page.$eval('.card:nth-child(2)', el => el.getAttribute('class'))).toBe('card auto-height is-selectable is-selected'); }); - // it.skip('should not visual regress', async () => { - // await page.waitForSelector('.card', { visible: true }) - // .then(element => expect(element).toBeTruthy()); + it.skip('should not visual regress', async () => { + await page.waitForSelector('.card', { visible: true }) + .then(element => expect(element).toBeTruthy()); - // const button1 = await page.$('.card:nth-child(1)'); - // await button1.click(); + const button1 = await page.$('.card:nth-child(1)'); + await button1.click(); - // const button2 = await page.$('.card:nth-child(2)'); - // await button2.click(); + const button2 = await page.$('.card:nth-child(2)'); + await button2.click(); - // const window = await page.$('#cardlist'); - // const image = await window.screenshot(); - // const config = getConfig('cards-multi-select'); + const window = await page.$('#cardlist'); + const image = await window.screenshot(); + const config = getConfig('cards-multi-select'); - // expect(image).toMatchImageSnapshot(config); - // }); + expect(image).toMatchImageSnapshot(config); + }); }); describe('Actionable', () => { ",13 "diff --git a/web/stock.js b/web/stock.js @@ -411,7 +411,7 @@ d3.csv('ndx.csv').then(function (data) { // [Line Chart](https://github.com/dc-js/dc.js/blob/master/web/docs/api-latest.md#line-chart) moveChart /* dc.lineChart('#monthly-move-chart', 'chartGroup') */ .renderArea(true) - .width(300) + .width(990) .height(200) .transitionDuration(1000) .margins({top: 30, right: 50, bottom: 25, left: 40}) ",13 "diff --git a/package.json b/package.json ""adal-node"": ""^0.1.17"", ""azure-storage-legacy"": ""0.9.14"", ""glob"": ""^7.1.1"", - ""grunt"": ""^1.0.1"", - ""grunt-contrib-connect"": ""^1.0.2"", - ""grunt-contrib-symlink"": ""^1.0.0"", - ""grunt-devserver"": ""^0.6.0"", - ""grunt-jsdoc"": ""^2.1.0"", + ""grunt"": ""~0.4"", + ""grunt-contrib-connect"": ""^0.10.1"", + ""grunt-contrib-symlink"": ""^0.3.0"", + ""grunt-devserver"": ""~0.6"", + ""grunt-jsdoc"": ""~0.6"", ""grunt-gh-pages"": ""1.1.0"", ""jshint"": ""2.9.4"", ""minami"": ""git://github.com/devigned/minami#master"", ",13 "diff --git a/package.json b/package.json ""bin"": ""wmr.cjs"", ""type"": ""module"", ""scripts"": { - ""demo"": ""cd demo && node --experimental-modules ../src/cli.js build 2>&1 | grep -v ExperimentalWarning"", + ""demo"": ""cd demo && node --experimental-modules ../src/cli.js 2>&1 | grep -v ExperimentalWarning"", + ""demo:prod"": ""cd demo && node --experimental-modules ../src/cli.js build 2>&1 | grep -v ExperimentalWarning"", ""dev"": ""PROFILE=true nodemon -w src --exec \""npm run -s demo\"""", ""build"": ""rollup -c"", ""test"": ""eslint && jest --runInBand"" ",13 "diff --git a/packages/create-wmr/tpl/tsconfig.json b/packages/create-wmr/tpl/tsconfig.json ""allowSyntheticDefaultImports"": true, ""downlevelIteration"": true }, - ""include"": [""node_modules/wmr/types.d.ts""], + ""include"": [""node_modules/wmr/types.d.ts"", ""**/*""], ""typeAcquisition"": { ""enable"": true } ",13 "diff --git a/examples/demo/package.json b/examples/demo/package.json ""private"": true, ""type"": ""module"", ""scripts"": { - ""start"": ""cross-env DEBUG=false node ../../packages/wmr/src/cli.js"", + ""start"": ""cross-env DEBUG=true node ../../packages/wmr/src/cli.js"", ""build"": ""yarn start build --prerender"", ""serve"": ""yarn start serve"", ""start:prod"": ""cross-env DEBUG=true wmr"", ",13 "diff --git a/src/features/visualization/d3-viz/setup-annotations.js b/src/features/visualization/d3-viz/setup-annotations.js @@ -39,7 +39,7 @@ const setupAnnotations = ({packedData, annotationRoot}) =>{ .append('text') .classed('svg-icon', true) .classed('nag', true) - .style('font-size', (d) => (3 * d.height * fontScale) + ""%"") + .style('font-size', (d) => (4 * d.height * fontScale) + ""%"") .text('\uf06a');//font-awesome annotations ",13 "diff --git a/test/common.js b/test/common.js @@ -4,7 +4,7 @@ var thunky = require('thunky') exports.getConfig = thunky(function (cb) { // Includes TURN -- needed for tests to pass on Sauce Labs // https://github.com/feross/simple-peer/issues/41 - get.concat('https://instant.io/__rtcConfig__', function (err, res, data) { + get.concat('https://instant.io/_rtcConfig', function (err, res, data) { if (err) return cb(err) data = data.toString() try { ",13 "diff --git a/src/containers/stage.jsx b/src/containers/stage.jsx @@ -179,7 +179,7 @@ class Stage extends React.Component { this.updateRect(); const {x, y} = getEventXY(e); const mousePosition = [x - this.rect.left, y - this.rect.top]; - if (e.which === 1) { + if (true) { this.setState({ mouseDown: true, mouseDownPosition: mousePosition, ",13 "diff --git a/src/components/library-item/library-item.jsx b/src/components/library-item/library-item.jsx @@ -46,7 +46,7 @@ class LibraryItem extends React.PureComponent { ) : ( -
    {this.props.name} -
    + ); } } ",13 "diff --git a/src/lib/blocks.js b/src/lib/blocks.js @@ -126,16 +126,9 @@ export default function (vm) { }; ScratchBlocks.Blocks.sensing_of_object_menu.init = function () { - const start = [ + const json = jsonForMenuBlock('OBJECT', spriteMenu, sensingColors, [ ['Stage', '_stage_'] - ]; - if (vm.editingTarget) { - start.splice(0, 0, - [vm.editingTarget.sprite.name, vm.editingTarget.sprite.name] - ); - } - - const json = jsonForMenuBlock('OBJECT', spriteMenu, sensingColors, start); + ]); this.jsonInit(json); }; ",13 "diff --git a/src/components/layout/FeaturesLayout.js b/src/components/layout/FeaturesLayout.js import React from 'react'; import PropTypes from 'prop-types'; -import styled from 'styled-components'; +import styled, { css } from 'styled-components'; import { styles } from '@storybook/design-system'; @@ -26,7 +26,7 @@ const Layout = styled.div` ${(props) => props.columns === 2 && - ` + css` ${pageMargins}; @media (min-width: ${breakpoint * 1}px) { margin: 0 ${pageMargin * 3}%; @@ -41,7 +41,7 @@ const Layout = styled.div` ${(props) => props.columns === 3 && - ` + css` ${pageMargins}; @media (min-width: ${breakpoint * 1}px) { > * { ",13 "diff --git a/buildkite/src/Pipeline/TriggerCommand.dhall b/buildkite/src/Pipeline/TriggerCommand.dhall @@ -3,5 +3,5 @@ in ( \(dhallPipelineRelativeToBuildKiteDir : Text) -> - Cmd.quietly ""dhall-to-yaml --quoted <<< '(./buildkite/${dhallPipelineRelativeToBuildKiteDir}).pipeline' | BUILDKITE_AGENT_META_DATA_SIZE=small buildkite-agent pipeline upload"" + Cmd.quietly ""dhall-to-yaml --quoted <<< '(./buildkite/${dhallPipelineRelativeToBuildKiteDir}).pipeline' | buildkite-agent pipeline upload"" ) : Text -> Cmd.Type ",13 "diff --git a/buildkite/src/Jobs/Lint/Fast.dhall b/buildkite/src/Jobs/Lint/Fast.dhall @@ -44,7 +44,7 @@ Pipeline.build (""./scripts/compare_ci_diff_types.sh"") , label = ""Optional fast lint steps; versions compatability changes"" , key = ""lint-optional-types"" - , target = Size.Large + , target = Size.Medium , soft_fail = Some (Command.SoftFail.Boolean True) , docker = None Docker.Type }, @@ -55,7 +55,7 @@ Pipeline.build (""./scripts/compare_ci_diff_binables.sh"") , label = ""Optional fast lint steps; binable compatability changes"" , key = ""lint-optional-binable"" - , target = Size.Large + , target = Size.Medium , soft_fail = Some (Command.SoftFail.Boolean True) , docker = None Docker.Type } ",13 "diff --git a/src/lib/integration_test_cloud_engine/coda_automation.ml b/src/lib/integration_test_cloud_engine/coda_automation.ml @@ -76,7 +76,7 @@ module Network_config = struct in let testnet_name = ""integration-test-"" ^ test_name in (* HARD CODED NETWORK VALUES *) - let coda_automation_location = ""/home/steck/tmp/coda-automation"" in + let coda_automation_location = ""../automation"" in let project_id = ""o1labs-192920"" in let cluster_id = ""gke_o1labs-192920_us-east1_coda-infra-east"" in let cluster_name = ""coda-infra-east"" in ",13 "diff --git a/src/lib/genesis_ledger_helper/genesis_ledger_helper.ml b/src/lib/genesis_ledger_helper/genesis_ledger_helper.ml @@ -482,7 +482,7 @@ module Ledger = struct | Ok () -> file_exists filename Cache_dir.s3_install_path | Error e -> - [%log info] ""Could not download $ledger from $uri"" + [%log info] ""Could not download $ledger from $uri: $error"" ~metadata: [ (""ledger"", `String ledger_name_prefix) ; (""uri"", `String s3_path) @@ -886,7 +886,8 @@ module Genesis_proof = struct | Ok () -> file_exists filename Cache_dir.s3_install_path | Error e -> - [%log info] ""Could not download genesis proof file from $uri"" + [%log info] + ""Could not download genesis proof file from $uri: $error"" ~metadata: [ (""uri"", `String s3_path) ; (""error"", Error_json.error_to_yojson e) ] ; ",13 "diff --git a/scripts/run_local_network.sh b/scripts/run_local_network.sh @@ -210,8 +210,6 @@ for i in $(seq 1 $nodes); do metrics_port=$(echo $node_start_port + 3 + $i*5 | bc) libp2p_metrics_port=$(echo $node_start_port + 4 + $i*5 | bc) - echo ""rest port"" $rest_port - CODA_PRIVKEY_PASS=""naughty blue worm"" $CODA daemon -peer ""/ip4/127.0.0.1/tcp/3002/p2p/12D3KooWAFFq2yEQFFzhU5dt64AWqawRuomG9hL8rSmm5vxhAsgr"" -client-port $client_port -rest-port $rest_port -external-port $ext_port -metrics-port $metrics_port -libp2p-metrics-port $libp2p_metrics_port -config-directory $folder -config-file $daemon -generate-genesis-proof true -log-json -log-level Trace &> $logfile & node_pids[${i}]=$! node_logfiles[${i}]=$logfile ",13 "diff --git a/scripts/run_local_network.sh b/scripts/run_local_network.sh @@ -146,7 +146,7 @@ mkdir -p $nodesfolder mkdir $nodesfolder/seed -$CODA daemon -seed -client-port 3000 -rest-port 3001 -external-port 3002 -metrics-port 3003 -libp2p-metrics-port 3004 -config-directory $nodesfolder/seed -config-file $daemon -generate-genesis-proof true -discovery-keypair CAESQNf7ldToowe604aFXdZ76GqW/XVlDmnXmBT+otorvIekBmBaDWu/6ZwYkZzqfr+3IrEh6FLbHQ3VSmubV9I9Kpc=,CAESIAZgWg1rv+mcGJGc6n6/tyKxIehS2x0N1Uprm1fSPSqX,12D3KooWAFFq2yEQFFzhU5dt64AWqawRuomG9hL8rSmm5vxhAsgr -log-json -log-level Trace -archive-address 3086 &> $nodesfolder/seed/log.txt & +$CODA daemon -seed -client-port 3000 -rest-port 3001 -external-port 3002 -metrics-port 3003 -libp2p-metrics-port 3004 -config-directory $nodesfolder/seed -config-file $daemon -generate-genesis-proof true -discovery-keypair CAESQNf7ldToowe604aFXdZ76GqW/XVlDmnXmBT+otorvIekBmBaDWu/6ZwYkZzqfr+3IrEh6FLbHQ3VSmubV9I9Kpc=,CAESIAZgWg1rv+mcGJGc6n6/tyKxIehS2x0N1Uprm1fSPSqX,12D3KooWAFFq2yEQFFzhU5dt64AWqawRuomG9hL8rSmm5vxhAsgr -log-json -log-level Trace &> $nodesfolder/seed/log.txt & seed_pid=$! echo 'waiting for seed to go up...' ",13 "diff --git a/src/app/rosetta/rosetta.conf b/src/app/rosetta/rosetta.conf ""network"": ""mainnet"" }, ""online_url"": ""http://localhost:3087"", - ""data_directory"": ""rosetta-cli"", + ""data_directory"": ""/data/rosetta-cli"", ""http_timeout"": 500, ""max_sync_concurrency"": 64, ""retry_elapsed_time"": 0, ""inactive_discrepency_search_disabled"": false, ""balance_tracking_disabled"": false, ""coin_tracking_disabled"": false, - ""results_output_file"": ""rosetta-cli/results"", + ""results_output_file"": ""/data/rosetta-cli/results"", ""end_conditions"": { ""tip"": true } ",13 "diff --git a/src/lib/mina_base/zkapp_precondition.ml b/src/lib/mina_base/zkapp_precondition.ml @@ -186,8 +186,11 @@ module Numeric = struct open Fields_derivers_zkapps.Derivers let block_time_inner obj = + let ( ^^ ) = Fn.compose in iso_string ~name:""BlockTime"" ~js_type:UInt64 - ~of_string:Block_time.of_string_exn ~to_string:Block_time.to_string obj + ~of_string:(Block_time.of_uint64 ^^ Unsigned_extended.UInt64.of_string) + ~to_string:(Unsigned_extended.UInt64.to_string ^^ Block_time.to_uint64) + obj let nonce obj = deriver ""Nonce"" uint32 obj @@ -227,14 +230,6 @@ module Numeric = struct |> finish ""T"" ~t_toplevel_annots end - let%test_unit ""to string"" = - [%test_eq: string] Block_time.(to_string max_value) ""-1"" - - let%test_unit ""of string"" = - [%test_eq: Block_time.t] - Block_time.(of_string_exn ""-1"") - Block_time.max_value - let%test_unit ""roundtrip json"" = let open Fields_derivers_zkapps.Derivers in let full = o () in ",13 "diff --git a/src/lib/integration_test_lib/wait_condition.ml b/src/lib/integration_test_lib/wait_condition.ml @@ -280,7 +280,7 @@ struct in let soft_timeout_in_slots = 4 in { id = Persisted_frontier_loaded - ; description = ""persisted transition frontier loaded"" + ; description = ""persisted transition frontier to load"" ; predicate = Event_predicate (Event_type.Persisted_frontier_loaded, (), check) ; soft_timeout = Slots soft_timeout_in_slots ",13 "diff --git a/buildkite/scripts/replayer-test.sh b/buildkite/scripts/replayer-test.sh @@ -38,4 +38,4 @@ cd /workdir echo ""Running replayer"" mina-replayer --archive-uri postgres://postgres:$PGPASSWORD@localhost:5432/archive \ - --input-file $TEST_DIR/input.json --output-file /dev/null + --input-file $TEST_DIR/input.json --output-file /dev/null --continue-on-error ",13 "diff --git a/src/app/test_executive/zkapps.ml b/src/app/test_executive/zkapps.ml @@ -529,7 +529,7 @@ module Make (Inputs : Intf.Test.Inputs_intf) = struct , zkapp_command_token_transfer2 ) in let with_timeout = - let soft_slots = 6 in + let soft_slots = 4 in let soft_timeout = Network_time_span.Slots soft_slots in let hard_timeout = Network_time_span.Slots (soft_slots * 2) in Wait_condition.with_timeouts ~soft_timeout ~hard_timeout ",13 "diff --git a/src/lib/crypto/kimchi_bindings/js/bindings.js b/src/lib/crypto/kimchi_bindings/js/bindings.js @@ -2124,12 +2124,6 @@ var caml_pasta_fq_plonk_proof_verify = function (index, proof) { return plonk_wasm.caml_pasta_fq_plonk_proof_verify(index, proof); }; -// Provides: prover_to_json -// Requires: plonk_wasm -var prover_to_json = function (prover_index) { - return plonk_wasm.prover_to_json(prover_index); -}; - // Provides: caml_pasta_fq_plonk_proof_batch_verify // Requires: plonk_wasm, caml_array_to_rust_vector, caml_pallas_poly_comm_to_rust, caml_pasta_fq_plonk_verifier_index_to_rust, caml_pasta_fq_proof_to_rust var caml_pasta_fq_plonk_proof_batch_verify = function(indexes, proofs) { @@ -2315,3 +2309,9 @@ function caml_pasta_fp_plonk_proof_example_with_lookup() { // This is only used in the pickles unit tests throw new Error(""Unimplemented caml_pasta_fp_plonk_proof_example_with_lookup""); } + +// Provides: prover_to_json +// Requires: plonk_wasm +var prover_to_json = function (prover_index) { + return plonk_wasm.prover_to_json(prover_index); +}; ",13 "diff --git a/src/lib/crypto/kimchi_bindings/stubs/kimchi_types.ml b/src/lib/crypto/kimchi_bindings/stubs/kimchi_types.ml @@ -16,8 +16,10 @@ type nonrec 'caml_f random_oracles = ; v_chal : 'caml_f scalar_challenge ; u_chal : 'caml_f scalar_challenge } +[@@boxed] type nonrec 'evals point_evaluations = { zeta : 'evals; zeta_omega : 'evals } +[@@boxed] type nonrec 'caml_f lookup_evaluations = { sorted : 'caml_f array point_evaluations array @@ -25,6 +27,7 @@ type nonrec 'caml_f lookup_evaluations = ; table : 'caml_f array point_evaluations ; runtime : 'caml_f array point_evaluations option } +[@@boxed] type nonrec 'caml_f proof_evaluations = { w : @@ -71,21 +74,26 @@ type nonrec 'caml_f proof_evaluations = ; generic_selector : 'caml_f array point_evaluations ; poseidon_selector : 'caml_f array point_evaluations } +[@@boxed] type nonrec 'caml_g poly_comm = { unshifted : 'caml_g array; shifted : 'caml_g option } +[@@boxed] type nonrec ('caml_g, 'caml_f) recursion_challenge = { chals : 'caml_f array; comm : 'caml_g poly_comm } +[@@boxed] type nonrec ('g, 'f) opening_proof = { lr : ('g * 'g) array; delta : 'g; z1 : 'f; z2 : 'f; sg : 'g } +[@@boxed] type nonrec 'caml_g lookup_commitments = { sorted : 'caml_g poly_comm array ; aggreg : 'caml_g poly_comm ; runtime : 'caml_g poly_comm option } +[@@boxed] type nonrec 'caml_g prover_commitments = { w_comm : @@ -108,6 +116,7 @@ type nonrec 'caml_g prover_commitments = ; t_comm : 'caml_g poly_comm ; lookup : 'caml_g lookup_commitments option } +[@@boxed] type nonrec ('caml_g, 'caml_f) prover_proof = { commitments : 'caml_g prover_commitments @@ -117,8 +126,9 @@ type nonrec ('caml_g, 'caml_f) prover_proof = ; public : 'caml_f array ; prev_challenges : ('caml_g, 'caml_f) recursion_challenge array } +[@@boxed] -type nonrec wire = { row : int; col : int } +type nonrec wire = { row : int; col : int } [@@boxed] type nonrec gate_type = | Zero @@ -155,6 +165,7 @@ type nonrec 'f circuit_gate = ; wires : wire * wire * wire * wire * wire * wire * wire ; coeffs : 'f array } +[@@boxed] type nonrec curr_or_next = Curr | Next @@ -164,6 +175,7 @@ type nonrec 'f oracles = ; opening_prechallenges : 'f array ; digest_before_evaluations : 'f } +[@@boxed] module VerifierIndex = struct module Lookup = struct @@ -182,6 +194,7 @@ module VerifierIndex = struct ; max_joint_size : int ; uses_runtime_tables : bool } + [@@boxed] type nonrec 't lookup_selectors = { lookup_gate : 't option } [@@boxed] @@ -193,9 +206,11 @@ module VerifierIndex = struct ; lookup_info : lookup_info ; runtime_tables_selector : 'poly_comm option } + [@@boxed] end type nonrec 'fr domain = { log_size_of_group : int; group_gen : 'fr } + [@@boxed] type nonrec 'poly_comm verification_evals = { sigma_comm : 'poly_comm array @@ -208,6 +223,7 @@ module VerifierIndex = struct ; endomul_scalar_comm : 'poly_comm ; chacha_comm : 'poly_comm array option } + [@@boxed] type nonrec ('fr, 'srs, 'poly_comm) verifier_index = { domain : 'fr domain @@ -220,4 +236,5 @@ module VerifierIndex = struct ; shifts : 'fr array ; lookup_index : 'poly_comm Lookup.t option } + [@@boxed] end ",13 "diff --git a/changelog.md b/changelog.md @@ -2,6 +2,10 @@ Since you are interested in what happens next, in case, you work for a for-profi ## Next (version and date will be generated, add changes below) +### Bug fixes + +- Reverting [1563](https://github.com/cssinjs/jss/pull/1563) because of regression [1565](https://github.com/cssinjs/jss/issues/1565) + ## 10.8.1 (2021-10-16) ### Bug fixes ",13 "diff --git a/public/js/editcube.js b/public/js/editcube.js @@ -635,7 +635,7 @@ function getLabels(sort) { } else if (sort == 'Supertype') { - return ['Basic','Elite','Host','Legendary','Ongoing','Tribal','World','Snow']; + return ['Snow','Legendary','Tribal','Basic','Elite','Host','Ongoing','World']; } else if (sort == 'Tags') { ",13 "diff --git a/contracts/token/StandardToken.sol b/contracts/token/StandardToken.sol @@ -26,7 +26,7 @@ contract StandardToken is ERC20, BasicToken { function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); - var _allowance = allowed[_from][msg.sender]; + uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); ",14 "diff --git a/src/components/Home/Home.css b/src/components/Home/Home.css } } -.events { - display: flex; - justify-content: center; - flex-wrap: wrap; +.events a { + color: #fff; } -.events iframe { - margin: 1em; +.events a:hover { + color: #fff; + text-decoration: underline; } .catalogs { ",14 "diff --git a/src/routes/Dataset/components/DatasetView/DatasetView.js b/src/routes/Dataset/components/DatasetView/DatasetView.js @@ -22,6 +22,8 @@ import DatasetContactList from '../DatasetContactList' import styles from './DatasetView.scss' +const { INSPIRE_API_URL } = process.env + class DatasetView extends React.PureComponent { static propTypes = { dataset: PropTypes.shape({ @@ -79,9 +81,13 @@ class DatasetView extends React.PureComponent { - { hasThumbnails && } + {hasThumbnails && ( + + )} - { hasThumbnails && } + {hasThumbnails && ( + + )} {i18n.exists(`Dataset:components.DatasetView.consequences.${status}`) && ( ",14 "diff --git a/src/routes/Dataset/components/DatasetHeader/DatasetHeader.js b/src/routes/Dataset/components/DatasetHeader/DatasetHeader.js @@ -12,12 +12,17 @@ import styles from './DatasetHeader.scss' const DatasetHeader = ({ dataset, t }) => { const { title, description, type, purpose, lineage, inspireTheme } = dataset.metadata - const revisionDate = doneSince(dataset.revisionDate) const license = getLicense(dataset.metadata.license) const dataType = t(`Common:enums.dataTypes.${type}`, { defaultValue: type }) + const { creationDate, revisionDate } = dataset.metadata + const updatedAt = revisionDate || creationDate + const updatedAtLabel = updatedAt + ? doneSince(updatedAt) + : t('Common:enums.unknownData.unknown', { context: 'female' }) + return (
    @@ -34,7 +39,7 @@ const DatasetHeader = ({ dataset, t }) => { ) : license}
    - {t('components.DatasetHeader.lastUpdate')} : {revisionDate} + {t('components.DatasetHeader.lastUpdate')} : {updatedAtLabel}
    ",14 "diff --git a/src/components/Markdown/Markdown.js b/src/components/Markdown/Markdown.js @@ -7,7 +7,7 @@ import styles from './Markdown.scss' const Markdown = ({ markdown, renderer }) => { const md = marked(markdown, { renderer }) return ( -

    ",14 "diff --git a/src/components/Dropdown/Dropdown.scss b/src/components/Dropdown/Dropdown.scss position: absolute; background-color: #fff; text-align: left; - margin-left: -100%; + margin-left: -90px; box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2); z-index: 1; ",14 "diff --git a/MaterialSkin/HTML/material/html/js/toolbar.js b/MaterialSkin/HTML/material/html/js/toolbar.js @@ -41,11 +41,10 @@ function startMediaSession() { } function stopMediaSession() { - if (!mediaInterval) { + if (!mediaStarted) { return; } - clearInterval(mediaInterval); - mediaInterval = undefined; + mediaStarted = false; if (mediaAudio.src) { mediaAudio.src = undefined; } ",14 "diff --git a/MaterialSkin/HTML/material/html/js/ui-settings.js b/MaterialSkin/HTML/material/html/js/ui-settings.js @@ -459,7 +459,9 @@ Vue.component('lms-ui-settings', { } } if (data && data.result && data.result.themes) { - this.themes.push.apply(this.themes, data.result.themes); + for (var i=0, list=data.result.themes, len=list.length; i { }); ",14 "diff --git a/MaterialSkin/HTML/material/html/js/customactions.js b/MaterialSkin/HTML/material/html/js/customactions.js @@ -122,6 +122,7 @@ function doReplacements(string, player, item) { } } } + val=val.replace(""$HOST"", window.location.hostname); for (var i=0, len=ACTION_KEYS.length; i +

    +
    +
    +

    This example tests state maintenance for personalization of colors and theme. Personalizations should maintain upon reinitialization of elements after having chosen a theme or color from the ""..."" button in the header.

    +

    Personalization button will set all colors to defaults as declared in HTML script tag, regardless of theme.



    +
    +
    +
    - +

    - +
    -
    +
    ",14 "diff --git a/src/components/lookup/lookup.js b/src/components/lookup/lookup.js @@ -1086,7 +1086,7 @@ Lookup.prototype = { */ enable() { this.element.prop('disabled', false).prop('readonly', false).removeClass('is-not-editable'); - this.element.parent().removeClass('is-disabled'); + this.element.closest('.field').removeClass('is-disabled'); this.icon.prop('disabled', false); }, ",14 "diff --git a/spec/heatmap-spec.js b/spec/heatmap-spec.js @@ -228,7 +228,7 @@ describe('dc.heatmap', () => { p.cols.add(d.colData); p.rows.add(d.rowData); return p; - }, {cols: d3.set(), rows: d3.set()}); + }, {cols: new Set(), rows: new Set()}); }; beforeEach(() => { @@ -245,21 +245,21 @@ describe('dc.heatmap', () => { it('should have the correct number of columns', () => { chart.selectAll('.box-group').each(d => { - expect(originalDomain.cols.has(d.key[0])).toBeTruthy(); + expect(originalDomain.cols.has(`${d.key[0]}`)).toBeTruthy(); }); chart.selectAll('.cols.axis text').each(d => { - expect(originalDomain.cols.has(d)).toBeTruthy(); + expect(originalDomain.cols.has(`${d}`)).toBeTruthy(); }); }); it('should have the correct number of rows', () => { chart.selectAll('.box-group').each(d => { - expect(originalDomain.rows.has(d.key[1])).toBeTruthy(); + expect(originalDomain.rows.has(`${d.key[1]}`)).toBeTruthy(); }); chart.selectAll('.rows.axis text').each(d => { - expect(originalDomain.rows.has(d)).toBeTruthy(); + expect(originalDomain.rows.has(`${d}`)).toBeTruthy(); }); }); }); ",14 "diff --git a/gulpfile.js b/gulpfile.js @@ -22,32 +22,8 @@ const use = args['use']; const regexForExcludedServices = /\/(intune|documentdbManagement|insightsManagement|insights|search)\//i; function findReadmeNodejsMdFilePaths(azureRestAPISpecsRoot) { - const nodejsReadmeFilePaths = []; - - // Find all of the readme.nodejs.md files within the azure-rest-api-specs/specification folder. const specificationFolderPath = path.resolve(azureRestAPISpecsRoot, 'specification'); - - const folderPathsToSearch = [specificationFolderPath]; - while (folderPathsToSearch.length > 0) { - const folderPathToSearch = folderPathsToSearch.pop(); - - const folderEntryPaths = fs.readdirSync(folderPathToSearch); - for (let i = 0; i < folderEntryPaths.length; ++i) { - const folderEntryPath = path.resolve(folderPathToSearch, folderEntryPaths[i]); - const folderEntryStats = fs.lstatSync(folderEntryPath); - if (folderEntryStats.isDirectory()) { - folderPathsToSearch.push(folderEntryPath); - } - else if (folderEntryStats.isFile()) { - const fileName = path.basename(folderEntryPath); - if (fileName === 'readme.nodejs.md') { - nodejsReadmeFilePaths.push(folderEntryPath); - } - } - } - } - - return nodejsReadmeFilePaths; + return glob.sync('**/readme.nodejs.md', { absolute: true, cwd: specificationFolderPath }); } function getPackageNameFromReadmeNodejsMdFileContents(readmeNodejsMdFileContents) { @@ -243,6 +219,8 @@ gulp.task('publish-packages', (cb) => { for (let i = 0; i < nodejsReadmeFilePaths.length; ++i) { const nodejsReadmeFilePath = nodejsReadmeFilePaths[i]; + // console.log(`INFO: Processing ${nodejsReadmeFilePath}`); + const nodejsReadmeFileContents = fs.readFileSync(nodejsReadmeFilePath, 'utf8'); const relativeOutputFolderPath = nodejsReadmeFileContents.match(/output\-folder: \$\(node\-sdks\-folder\)\/(lib\/services\/\S+)/)[1]; const packageFolderPath = path.resolve(azureSDKForNodeRepoRoot, relativeOutputFolderPath); ",14 "diff --git a/runtime/ms-rest/lib/serialization.js b/runtime/ms-rest/lib/serialization.js @@ -75,7 +75,8 @@ exports.serialize = function (mapper, object, objectName) { // false || X | undefined // undefined || X | undefined/null - const { required, nullable } = mapper; + const required = mapper.required; + const nullable = mapper.nullable; if (required && nullable && object === undefined) { throw new Error(`${objectName} cannot be undefined.`); ",14 "diff --git a/packages/wmr/src/wmr-middleware.js b/packages/wmr/src/wmr-middleware.js @@ -10,8 +10,6 @@ import { debug, formatPath } from './lib/output-utils.js'; import { getPlugins } from './lib/plugins.js'; import { watch } from './lib/fs-watcher.js'; import { matchAlias, resolveAlias } from './lib/aliasing.js'; -import { modularizeCss } from './plugins/wmr/styles/css-modules.js'; -import { processSass } from './plugins/wmr/styles/sass.js'; const NOOP = () => {}; @@ -237,17 +235,15 @@ export default function wmrMiddleware(options) { } else if (queryParams.has('asset')) { cacheKey += '?asset'; transform = TRANSFORMS.asset; - } else if (prefix || hasIdPrefix || isModule || /\.([mc]js|[tj]sx?)$/.test(file)) { + } else if (prefix || hasIdPrefix || isModule || /\.([mc]js|[tj]sx?)$/.test(file) || /\.(css|s[ac]ss)$/.test(file)) { transform = TRANSFORMS.js; - } else if (/\.(css|s[ac]ss)$/.test(file)) { - transform = TRANSFORMS.css; } else { transform = TRANSFORMS.generic; } try { const start = Date.now(); - const result = await transform({ + let result = await transform({ req, res, id, @@ -266,6 +262,20 @@ export default function wmrMiddleware(options) { // return a value to use it as the response: if (result != null) { + // Grab the asset id out of the compiled js + // TODO: Wire this up into Style-Plugin by passing the + // import type through resolution somehow + if (!isModule && /\.(css|s[ac]ss)$/.test(file) && typeof result === 'string') { + const match = result.match(/style\([""']\/([^""']+?)[""'].*?\);/m); + + if (match) { + if (WRITE_CACHE.has(match[1])) { + result = /** @type {string} */ WRITE_CACHE.get(match[1]); + res.setHeader('Content-Type', 'text/css;charset=utf-8'); + } + } + } + log(`<-- ${kl.cyan(formatPath(id))} as ${kl.dim('' + res.getHeader('Content-Type'))}`); const time = Date.now() - start; res.writeHead(200, { @@ -554,41 +564,6 @@ export const TRANSFORMS = { } }, - // Handles CSS Modules (the actual CSS) - async css({ id, path, file, root, out, res, alias, cacheKey }) { - if (!/\.(css|s[ac]ss)$/.test(path)) throw null; - - const isModular = /\.module\.(css|s[ac]ss)$/.test(path); - - const isSass = /\.(s[ac]ss)$/.test(path); - - res.setHeader('Content-Type', 'text/css;charset=utf-8'); - - if (WRITE_CACHE.has(id)) return WRITE_CACHE.get(id); - - const idAbsolute = resolveFile(file, root, alias); - let code = await fs.readFile(idAbsolute, 'utf-8'); - - if (isModular) { - code = await modularizeCss(code, id.replace(/^\.\//, ''), undefined, idAbsolute); - } else if (isSass) { - code = processSass(code); - } - - // const plugin = wmrStylesPlugin({ cwd, hot: false, fullPath: true }); - // let code; - // const context = { - // emitFile(asset) { - // code = asset.source; - // } - // }; - // await plugin.load.call(context, file); - - writeCacheFile(out, cacheKey, code); - - return code; - }, - // Falls through to sirv async generic(ctx) { // Serve ~/200.html fallback for requests with no extension ",14 "diff --git a/index.js b/index.js @@ -199,7 +199,7 @@ Peer.prototype.signal = function (data) { self._pendingCandidates = [] if (self._pc.remoteDescription.type === 'offer') self._createAnswer() - }, function (err) { self._onError(err) }) + }, function (err) { self._destroy(err) }) } if (!data.sdp && !data.candidate) { self._destroy(new Error('signal() called with invalid signal data')) @@ -212,7 +212,7 @@ Peer.prototype._addIceCandidate = function (candidate) { self._pc.addIceCandidate( new self._wrtc.RTCIceCandidate(candidate), noop, - function (err) { self._onError(err) } + function (err) { self._destroy(err) } ) } catch (err) { self._destroy(new Error('error adding candidate: ' + err.message)) @@ -245,7 +245,7 @@ Peer.prototype._destroy = function (err, onclose) { if (self.destroyed) return if (onclose) self.once('close', onclose) - self._debug('destroy (error: %s)', err && err.message) + self._debug('destroy (error: %s)', err && (err.message || err)) self.readable = self.writable = false @@ -307,7 +307,7 @@ Peer.prototype._setupData = function (event) { // In some situations `pc.createDataChannel()` returns `undefined` (in wrtc), // which is invalid behavior. Handle it gracefully. // See: https://github.com/feross/simple-peer/issues/163 - return self._onError(new Error('Data channel event is missing `channel` property')) + return self._destroy(new Error('Data channel event is missing `channel` property')) } self._channel = event.channel @@ -343,7 +343,7 @@ Peer.prototype._write = function (chunk, encoding, cb) { try { self.send(chunk) } catch (err) { - return self._onError(err) + return self._destroy(err) } if (self._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) { self._debug('start backpressure: bufferedAmount %d', self._channel.bufferedAmount) @@ -386,7 +386,7 @@ Peer.prototype._createOffer = function () { self._pc.createOffer(function (offer) { if (self.destroyed) return offer.sdp = self.sdpTransform(offer.sdp) - self._pc.setLocalDescription(offer, noop, function (err) { self._onError(err) }) + self._pc.setLocalDescription(offer, noop, function (err) { self._destroy(err) }) var sendOffer = function () { var signal = self._pc.localDescription || offer self._debug('signal') @@ -397,7 +397,7 @@ Peer.prototype._createOffer = function () { } if (self.trickle || self._iceComplete) sendOffer() else self.once('_iceComplete', sendOffer) // wait for candidates - }, function (err) { self._onError(err) }, self.offerConstraints) + }, function (err) { self._destroy(err) }, self.offerConstraints) } Peer.prototype._createAnswer = function () { @@ -407,7 +407,7 @@ Peer.prototype._createAnswer = function () { self._pc.createAnswer(function (answer) { if (self.destroyed) return answer.sdp = self.sdpTransform(answer.sdp) - self._pc.setLocalDescription(answer, noop, function (err) { self._onError(err) }) + self._pc.setLocalDescription(answer, noop, function (err) { self._destroy(err) }) if (self.trickle || self._iceComplete) sendAnswer() else self.once('_iceComplete', sendAnswer) @@ -419,7 +419,7 @@ Peer.prototype._createAnswer = function () { sdp: signal.sdp }) } - }, function (err) { self._onError(err) }, self.answerConstraints) + }, function (err) { self._destroy(err) }, self.answerConstraints) } Peer.prototype._onIceConnectionStateChange = function () { @@ -594,7 +594,7 @@ Peer.prototype._maybeReady = function () { try { self.send(self._chunk) } catch (err) { - return self._onError(err) + return self._destroy(err) } self._chunk = null self._debug('sent chunk from ""write before connect""') @@ -696,13 +696,6 @@ Peer.prototype._onTrack = function (event) { self.emit('stream', event.streams[0]) } -Peer.prototype._onError = function (err) { - var self = this - if (self.destroyed) return - self._debug('error %s', err.message || err) - self._destroy(err) -} - Peer.prototype._debug = function () { var self = this var args = [].slice.call(arguments) ",14 "diff --git a/index.js b/index.js @@ -553,15 +553,9 @@ Peer.prototype._maybeReady = function () { self._connecting = true - var withinIntervalCallback = false // We can't rely on order here, for details see https://github.com/js-platform/node-webrtc/issues/339 - var interval = setInterval(function () { - if (self.destroyed) { - clearInterval(interval) - return - } - if (withinIntervalCallback) return - withinIntervalCallback = true + function findCandidatePair () { + if (self.destroyed) return self.getStats(function (err, items) { if (self.destroyed) return @@ -647,10 +641,8 @@ Peer.prototype._maybeReady = function () { ) } - withinIntervalCallback = false - if (self.connected) { - clearInterval(interval) - } else { + if (!self.connected) { + setTimeout(findCandidatePair, 100) return } @@ -682,7 +674,8 @@ Peer.prototype._maybeReady = function () { self._earlyMessage = null } }) - }, 100) + } + findCandidatePair() } Peer.prototype._onInterval = function () { ",14 "diff --git a/test/multistream.js b/test/multistream.js @@ -12,6 +12,11 @@ test('get config', function (t) { }) test('multistream', function (t) { + if (common.isBrowser('ios')) { + t.pass('Skip on iOS emulator which does not support this reliably') // iOS emulator issue #486 + t.end() + return + } t.plan(20) var peer1 = new Peer({ @@ -54,6 +59,49 @@ test('multistream', function (t) { }) }) +test('multistream (track event)', function (t) { + t.plan(20) + + var peer1 = new Peer({ + config: config, + initiator: true, + wrtc: common.wrtc, + streams: (new Array(5)).fill(null).map(function () { return common.getMediaStream() }) + }) + var peer2 = new Peer({ + config: config, + wrtc: common.wrtc, + streams: (new Array(5)).fill(null).map(function () { return common.getMediaStream() }) + }) + + peer1.on('signal', function (data) { if (!peer2.destroyed) peer2.signal(data) }) + peer2.on('signal', function (data) { if (!peer1.destroyed) peer1.signal(data) }) + + var receivedIds = {} + + peer1.on('track', function (track) { + t.pass('peer1 got track') + if (receivedIds[track.id]) { + t.fail('received one unique track per event') + } else { + receivedIds[track.id] = true + } + }) + peer2.on('track', function (track) { + t.pass('peer2 got track') + if (receivedIds[track.id]) { + t.fail('received one unique track per event') + } else { + receivedIds[track.id] = true + } + }) + + t.on('end', () => { + peer1.destroy() + peer2.destroy() + }) +}) + test('multistream on non-initiator only', function (t) { t.plan(30) @@ -135,6 +183,11 @@ test('delayed stream on non-initiator', function (t) { }) test('incremental multistream', function (t) { + if (common.isBrowser('ios')) { + t.pass('Skip on iOS emulator which does not support this reliably') // iOS emulator issue #486 + t.end() + return + } t.plan(12) var peer1 = new Peer({ @@ -197,7 +250,75 @@ test('incremental multistream', function (t) { }) }) +test('incremental multistream (track event)', function (t) { + t.plan(22) + + var peer1 = new Peer({ + config: config, + initiator: true, + wrtc: common.wrtc, + streams: [] + }) + var peer2 = new Peer({ + config: config, + wrtc: common.wrtc, + streams: [] + }) + + peer1.on('signal', function (data) { if (!peer2.destroyed) peer2.signal(data) }) + peer2.on('signal', function (data) { if (!peer1.destroyed) peer1.signal(data) }) + + peer1.on('connect', function () { + t.pass('peer1 connected') + peer1.addStream(common.getMediaStream()) + }) + peer2.on('connect', function () { + t.pass('peer2 connected') + peer2.addStream(common.getMediaStream()) + }) + + var receivedIds = {} + + var count1 = 0 + peer1.on('track', function (track) { + t.pass('peer1 got track') + if (receivedIds[track.id]) { + t.fail('received one unique track per event') + } else { + receivedIds[track.id] = true + } + count1++ + if (count1 % 2 === 0 && count1 < 10) { + peer1.addStream(common.getMediaStream()) + } + }) + + var count2 = 0 + peer2.on('track', function (track) { + t.pass('peer2 got track') + if (receivedIds[track.id]) { + t.fail('received one unique track per event') + } else { + receivedIds[track.id] = true + } + count2++ + if (count2 % 2 === 0 && count2 < 10) { + peer2.addStream(common.getMediaStream()) + } + }) + + t.on('end', () => { + peer1.destroy() + peer2.destroy() + }) +}) + test('incremental multistream on non-initiator only', function (t) { + if (common.isBrowser('ios')) { + t.pass('Skip on iOS emulator which does not support this reliably') // iOS emulator issue #486 + t.end() + return + } t.plan(7) var peer1 = new Peer({ @@ -245,6 +366,54 @@ test('incremental multistream on non-initiator only', function (t) { }) }) +test('incremental multistream on non-initiator only (track event)', function (t) { + t.plan(12) + + var peer1 = new Peer({ + config: config, + initiator: true, + wrtc: common.wrtc, + streams: [] + }) + var peer2 = new Peer({ + config: config, + wrtc: common.wrtc, + streams: [] + }) + + peer1.on('signal', function (data) { if (!peer2.destroyed) peer2.signal(data) }) + peer2.on('signal', function (data) { if (!peer1.destroyed) peer1.signal(data) }) + + peer1.on('connect', function () { + t.pass('peer1 connected') + }) + peer2.on('connect', function () { + t.pass('peer2 connected') + peer2.addStream(common.getMediaStream()) + }) + + var receivedIds = {} + + var count = 0 + peer1.on('track', function (track) { + t.pass('peer1 got track') + if (receivedIds[track.id]) { + t.fail('received one unique track per event') + } else { + receivedIds[track.id] = true + } + count++ + if (count % 2 === 0 && count < 10) { + peer2.addStream(common.getMediaStream()) + } + }) + + t.on('end', () => { + peer1.destroy() + peer2.destroy() + }) +}) + test('addStream after removeStream', function (t) { if (common.isBrowser('safari') || common.isBrowser('ios')) { t.pass('Skip on Safari and iOS which do not support this reliably') // TODO: Enable in Safari 12.2 ",14 "diff --git a/src/lib/default-project/project.json b/src/lib/default-project/project.json ""currentCostume"": 0, ""costumes"": [ { - ""assetId"": ""739b5e2a2435f6e1ec2993791b423146"", + ""assetId"": ""cd21514d0531fdffb22204e0ec5ed84a"", ""name"": ""backdrop1"", - ""bitmapResolution"": 1, - ""md5ext"": ""739b5e2a2435f6e1ec2993791b423146.png"", - ""dataFormat"": ""png"", + ""md5ext"": ""cd21514d0531fdffb22204e0ec5ed84a.svg"", + ""dataFormat"": ""svg"", ""rotationCenterX"": 240, ""rotationCenterY"": 180 } ",14 "diff --git a/sheets/javascript.md b/sheets/javascript.md @@ -224,3 +224,39 @@ axios({ console.log(result.data); }); ``` + +## Remove vowels from string + +Use a regular expression: + +```js +'replace vowels from string'.replace(/[aeiou]/gi, ''); +``` + +Output: + +```bash +""rplc vwls frm strng"" +``` + +With JavaScript functions: + +```js +'replace vowels from string' + .split('a') + .join('') + .split('e') + .join('') + .split('i') + .join('') + .split('o') + .join('') + .split('u') + .join(''); +``` + +Output: + +```bash +""rplc vwls frm strng"" +``` ",14 "diff --git a/lib/run/index.js b/lib/run/index.js @@ -112,7 +112,7 @@ module.exports = function (options, callback) { }, certificates: options.sslClientCert && new sdk.CertificateList({}, [{ name: 'client-cert', - matches: [''], // todo - expose this as a constant from the SDK. + matches: [sdk.UrlMatchPattern.MATCH_ALL_URLS], key: { src: options.sslClientKey }, cert: { src: options.sslClientCert }, passphrase: options.sslClientPassphrase ",14 "diff --git a/lib/cli/index.js b/lib/cli/index.js @@ -6,6 +6,22 @@ var _ = require('lodash'), colors = require('colors'), version = require('../../package.json').version, + /** + * A CLI parser helper to process stringified numbers into integers, perform safety checks, and return the result. + * + * @param {String} arg - The stringified number argument pulled from the CLI arguments list. + * @returns {Number} - The supplied argument, casted to an integer. + */ + Integer = (arg) => { + var num = Number(arg); + + if (!_.isSafeInteger(num)) { + throw new Error('The value must be an integer.'); + } + + return num.valueOf(); + }, + /** * Separates reporter specific arguments from the rest. * @@ -55,6 +71,7 @@ var _ = require('lodash'), * @returns {{key, value}} - The object representation of the current CLI variable. */ function collect (val, memo) { + console.log(""Val : "", val); var arg = val, eqIndex = arg.indexOf('='), hasEq = eqIndex !== -1; @@ -73,27 +90,27 @@ var _ = require('lodash'), .option('-g, --globals ', 'Specify a URL or Path to a file containing Postman Globals.') .option('--folder ', 'Run a single folder from a collection.') .option('-r, --reporters [reporters]', 'Specify the reporters to use for this run.', 'cli') - .option('-n, --iteration-count ', 'Define the number of iterations to run.', parseInt) + .option('-n, --iteration-count ', 'Define the number of iterations to run.', Integer) .option('-d, --iteration-data ', 'Specify a data file to use for iterations (either json or csv).') .option('--export-environment ', 'Exports the environment to a file after completing the run.') .option('--export-globals ', 'Specify an output file to dump Globals before exiting.') - .option('--export-collection', 'Specify an output file to save the executed collection') - .option('--delay-request [n]', 'Specify the extent of delay between requests (milliseconds)', parseInt, 0) + .option('--export-collection ', 'Specify an output file to save the executed collection') + .option('--delay-request [n]', 'Specify the extent of delay between requests (milliseconds)', Integer) .option('--bail', - 'Specify whether or not to gracefully stop a collection run on encountering the first error', false) + 'Specify whether or not to gracefully stop a collection run on encountering the first error.') .option('-x , --suppress-exit-code', - 'Specify whether or not to override the default exit code for the current run', false) - .option('--silent', 'Prevents newman from showing output to CLI', false) + 'Specify whether or not to override the default exit code for the current run.') + .option('--silent', 'Prevents newman from showing output to CLI.') .option('--disable-unicode', 'Forces unicode compliant symbols to be replaced by their plain text equivalents') - .option('--global-var [value]', + .option('--global-var ', 'Allows the specification of global variables via the command line, in a key=value format', collect, []) // commander had some issue with flags starting with --no, thus camelCased // resolved https://github.com/tj/commander.js/pull/709 .option('--no-color', 'Disable colored output.') .option('--color', 'Force colored output (for use in CI environments).') - .option('--timeout-request ', 'Specify a timeout for requests (in milliseconds).', parseInt) - .option('--timeout-script ', 'Specify a timeout for script (in milliseconds).', parseInt) + .option('--timeout-request ', 'Specify a timeout for requests (in milliseconds).', Integer) + .option('--timeout-script ', 'Specify a timeout for script (in milliseconds).', Integer) .option('--ignore-redirects', 'If present, Newman will not follow HTTP Redirects.') .option('-k, --insecure', 'Disables SSL validations.') .option('--ssl-client-cert ', @@ -166,7 +183,7 @@ var _ = require('lodash'), var command = options._name, optionsObj = { [command]: {} }; - optionsObj[command].version = options.version || false; + optionsObj[command].version = options._version || false; optionsObj[command].noColor = !options.color || false; optionsObj[command].color = options.color || false; optionsObj[command].timeoutRequest = options.timeoutRequest || null; ",14 "diff --git a/package.json b/package.json ""eslint-plugin-mocha"": ""4.11.0"", ""eslint-plugin-security"": ""1.4.0"", ""expect.js"": ""0.3.1"", - ""istanbul"": ""0.4.5"", ""js-yaml"": ""3.10.0"", ""jsdoc"": ""3.5.5"", ""jsdoc-to-markdown"": ""3.0.1"", ""mocha"": ""4.0.1"", ""nsp"": ""2.8.1"", + ""nyc"": ""11.3.0"", ""packity"": ""0.3.2"", ""parse-gitignore"": ""0.4.0"", ""postman-jsdoc-theme"": ""0.0.3"", ",14 "diff --git a/package.json b/package.json ""dependencies"": { ""async"": ""2.6.1"", ""cli-progress"": ""1.8.0"", - ""cli-table2"": ""0.2.0"", + ""cli-table3"": ""0.4.0"", ""colors"": ""1.3.0"", ""commander"": ""2.15.1"", ""csv-parse"": ""1.3.3"", ",14 "diff --git a/lib/reporters/cli/index.js b/lib/reporters/cli/index.js var _ = require('lodash'), colors = require('colors/safe'), - Table = require('cli-table2'), + Table = require('cli-table3'), format = require('util').format, util = require('../../util'), ",14 "diff --git a/lib/syntax/index.js b/lib/syntax/index.js @@ -21,7 +21,13 @@ function createParseContext(name) { } function isValidNumber(value) { - return Number.isInteger(value) && value >= 0; + // Number.isInteger(value) && value >= 0 + return ( + typeof value === 'number' && + isFinite(value) && + Math.floor(value) === value && + value >= 0 + ); } function isValidLocation(loc) { ",14 "diff --git a/src/components/screens/IndexScreen/Hero.js b/src/components/screens/IndexScreen/Hero.js @@ -374,7 +374,7 @@ export default function Hero({ title=""Chromatic intro video"" width=""560"" height=""315"" - src=""https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1&rel=0&showinfo=0"" + src=""https://www.youtube.com/embed/wj9tcB5CGxI?autoplay=1&rel=0&showinfo=0"" frameBorder=""0"" allow=""autoplay; encrypted-media"" allowFullScreen ",14 "diff --git a/README.md b/README.md - +
    -Coda is the first cryptocurrency with a lightweight, constant-sized blockchain. This is the main source code repository for the Coda project. It contains code for the OCaml protocol implementation, [website](https://codaprotocol.org), and wallet. +Coda is the first cryptocurrency with a lightweight, constant-sized blockchain. This is the main source code repository for the Coda project. It contains code for the OCaml protocol implementation, [website](https://codaprotocol.com), and wallet. ## Notes ",14 "diff --git a/scripts/pin-external-packages.sh b/scripts/pin-external-packages.sh PACKAGES=""ocaml-sodium rpc_parallel ocaml-extlib digestif ocaml-extlib async_kernel coda_base58 graphql_ppx"" -git package sync && git package update --init --recursive +git submodule sync && git submodule update --init --recursive for pkg in $PACKAGES; do echo ""Pinning package"" $pkg ",14 "diff --git a/buildkite/src/Jobs/LintOpt.dhall b/buildkite/src/Jobs/LintOpt.dhall @@ -24,7 +24,7 @@ Pipeline.build , steps = [ Command.build Command.Config:: - { commands = OpamInit.andThenRunInDocker ([] : List Text) ""CI=true BASE_BRANCH_NAME=$(pipeline.git.base_revision) ./scripts/compare_ci_diff_types.sh"" + { commands = OpamInit.andThenRunInDocker ([] : List Text) ""CI=true BASE_BRANCH_NAME=$BUILDKITE_PULL_REQUEST_BASE_BRANCH ./scripts/compare_ci_diff_types.sh"" , label = ""Compare CI diff types"" , key = ""lint-diff-types"" , target = Size.Medium @@ -32,7 +32,7 @@ Pipeline.build }, Command.build Command.Config:: - { commands = OpamInit.andThenRunInDocker ([] : List Text) ""CI=true BASE_BRANCH_NAME=$(pipeline.git.base_revision) ./scripts/compare_ci_diff_binables.sh"" + { commands = OpamInit.andThenRunInDocker ([] : List Text) ""CI=true BASE_BRANCH_NAME=$BUILDKITE_PULL_REQUEST_BASE_BRANCH ./scripts/compare_ci_diff_binables.sh"" , label = ""Compare CI diff binables"" , key = ""lint-diff-binables"" , target = Size.Medium ",14 "diff --git a/src/lib/zexe_backend/zexe_backend_common/plonk_dlog_keypair.ml b/src/lib/zexe_backend/zexe_backend_common/plonk_dlog_keypair.ml @@ -102,9 +102,9 @@ module Make (Inputs : Inputs_intf) = struct let urs = ref None in let degree = 1 lsl Pickles_types.Nat.to_int Rounds.n in (* TODO *) - let public_inputs = Unsigned.Size_t.of_int 0 in + let public_inputs = failwith ""TODO"" in (* TODO *) - let size = Unsigned.Size_t.of_int 0 in + let size = failwith ""TODO"" in let set_urs_info specs = Set_once.set_exn urs_info Lexing.dummy_pos specs in ",14 "diff --git a/src/lib/staged_ledger/staged_ledger.ml b/src/lib/staged_ledger/staged_ledger.ml @@ -1910,7 +1910,7 @@ let%test_module ""test"" = | (cmd : User_command.Valid.t) :: cmds -> let%bind _ = Ledger.apply_transaction ~constraint_constants test_ledger - ~txn_state_view:(failwith ""TODO"") + ~txn_state_view:(dummy_state_view ()) (Command (cmd :> User_command.t)) in apply_cmds cmds ",14 "diff --git a/rfcs/0039-snark-keys-management.md b/rfcs/0039-snark-keys-management.md @@ -52,7 +52,12 @@ JSON format before the actual contents, specifying zexe repos used when generating the keys * the length of the binary data following the header, so that we can validate that the file was successfully downloaded in full, where applicable -* the date when the file's contents were created +* the date associated with the current commit + - we don't chose the file generation time, in order to make the header + reproducible + - it is helpful to have some notion of date, so that we can build a simple + `ls`-style tool that we can use to identify out-of-date keys in the local + cache etc. * the type of the file's contents * the constraint system hash (for keys) or domain size (for URS) * any other input information @@ -82,7 +87,7 @@ For example, a header for the transaction snark key file might look like: , ""marlin"": ""COMMIT_SHA_HERE"" , ""zexe"": ""COMMIT_SHA_HERE"" } , ""length"": 1000000000 -, ""date"": ""1970-01-01 00:00:00"" +, ""commit_date"": ""1970-01-01 00:00:00"" , ""constraint_system_hash"": ""MD5_HERE"" , ""identifying_hash"": ""HASH_HERE"" } ``` ",14 "diff --git a/automation/terraform/modules/kubernetes/testnet/helm.tf b/automation/terraform/modules/kubernetes/testnet/helm.tf @@ -119,13 +119,13 @@ locals { # in addition to stand-alone servers up to input count [ for index in range(2, var.archive_node_count + 1): - defaults( + merge( + local.default_archive_node, { name = ""archive-${index}"", enableLocalDaemon = false, enablePostgresDB = false - }, - local.default_archive_node + } ) ] ) ",14 "diff --git a/src/lib/genesis_ledger_helper/lib/genesis_ledger_helper_lib.ml b/src/lib/genesis_ledger_helper/lib/genesis_ledger_helper_lib.ml @@ -129,29 +129,9 @@ module Accounts = struct t (List.length state) else Ok (Snapp_state.V.of_list_exn state) in - let%bind verification_key = - (* Use a URI-safe alphabet to make life easier for maintaining json - We prefer this to base58-check here because users should not - be manually entering verification keys. - *) - Option.value_map ~default:(Ok None) verification_key - ~f:(fun verification_key -> - let%map vk = - Base64.decode ~alphabet:Base64.uri_safe_alphabet - verification_key - |> Result.map_error ~f:(function `Msg s -> - Error.createf - !""Could not parse verification key account \ - %{sexp:Runtime_config.Accounts.Single.t}: %s"" - t s) - |> Result.map - ~f: - (Binable.of_string - ( module Pickles.Side_loaded.Verification_key - .Stable - .Latest )) - in - Some (With_hash.of_data ~hash_data:Snapp_account.digest_vk vk)) + let verification_key = + Option.map verification_key + ~f:(With_hash.of_data ~hash_data:Snapp_account.digest_vk) in let%map rollup_state = if @@ -288,12 +268,7 @@ module Accounts = struct -> let state = Snapp_state.V.to_list app_state in let verification_key = - Option.map verification_key ~f:(fun vk -> - With_hash.data vk - |> Binable.to_string - ( module Pickles.Side_loaded.Verification_key.Stable - .Latest ) - |> Base64.encode_exn ~alphabet:Base64.uri_safe_alphabet) + Option.map verification_key ~f:With_hash.data in let rollup_state = Pickles_types.Vector.to_list rollup_state in let last_rollup_slot = ",14 "diff --git a/src/lib/crypto/kimchi_bindings/stubs/README.md b/src/lib/crypto/kimchi_bindings/stubs/README.md @@ -28,7 +28,12 @@ There are two ways of dealing with types: The first option is the easiest one, unless there are some foreign types in there. (Because of Rust's [*orphan rule*](https://github.com/Ixrec/rust-orphan-rules)) you can't implement the ToValue and FromValue traits on foreign types.) -This means that you'll have to use the second option anytime you're dealing with foreign types, by wrapping them into a local type and using `custom!`. +You should use a custom type where OCaml doesn't need to access the internal +fields of the type (or if it is itself a primitive, such as a field element or +bigint); otherwise, you must create the desired OCaml structure/enum as a rust +structure and perform a conversion between this new type and the original +foreign rust type. In general, the choice of which to use should be governed by +what's required in OCaml, **not** by limitations in the rust language. ### The ToValue and FromValue traits ",14 "diff --git a/src/lib/crypto/kimchi_bindings/stubs/README.md b/src/lib/crypto/kimchi_bindings/stubs/README.md @@ -37,7 +37,7 @@ what's required in OCaml, **not** by limitations in the rust language. ### The ToValue and FromValue traits -In both methods, the [traits ToValue and FromValue](https://github.com/zshipko/ocaml-rs/blob/master/src/value.rs#L55:L73) are used: +In both methods, the [traits ToValue and FromValue](https://github.com/zshipko/ocaml-rs/blob/f300f2f382a694a6cc51dc14a9b3f849191580f0/src/value.rs#L55:L73) are used: ```rust= pub unsafe trait IntoValue { @@ -48,7 +48,7 @@ pub unsafe trait FromValue<'a> { } ``` -these traits are implemented for all primitive Rust types ([here](https://github.com/zshipko/ocaml-rs/blob/master/src/conv.rs)), and can be derived automatically via [derive macros](https://docs.rs/ocaml/0.22.0/ocaml/#derives). Don't forget that you can use [cargo expand](https://github.com/dtolnay/cargo-expand) to expand macros, which is really useful to understand what the ocaml-rs macros are doing. +these traits are implemented for all primitive Rust types ([here](https://github.com/zshipko/ocaml-rs/blob/f300f2f382a694a6cc51dc14a9b3f849191580f0/src/conv.rs)), and can be derived automatically via [derive macros](https://docs.rs/ocaml/0.22.0/ocaml/#derives). Don't forget that you can use [cargo expand](https://github.com/dtolnay/cargo-expand) to expand macros, which is really useful to understand what the ocaml-rs macros are doing. ``` $ cargo expand -- some_filename_without_rs > expanded.rs @@ -56,7 +56,7 @@ $ cargo expand -- some_filename_without_rs > expanded.rs ### Custom types -The macro [custom!](https://github.com/zshipko/ocaml-rs/blob/master/src/custom.rs) allows you to quickly create custom types. +The macro [custom!](https://github.com/zshipko/ocaml-rs/blob/f300f2f382a694a6cc51dc14a9b3f849191580f0/src/custom.rs) allows you to quickly create custom types. Values of custom types are opaque to OCaml, used to store the data of some rust value on the OCaml heap. When this data may contain pointers to the rust heap, @@ -89,7 +89,7 @@ pub unsafe fn alloc_custom() -> Value { } ``` -and the data of your type (probably a pointer to some Rust memory) is copied into the OCaml's heap ([source](https://github.com/zshipko/ocaml-rs/blob/master/src/types.rs#L80)): +and the data of your type (probably a pointer to some Rust memory) is copied into the OCaml's heap ([source](https://github.com/zshipko/ocaml-rs/blob/f300f2f382a694a6cc51dc14a9b3f849191580f0/src/types.rs#L80)): ```rust= pub fn set(&mut self, x: T) { ",14 "diff --git a/src/lib/crypto/kimchi_backend/common/plonk_constraint_system.ml b/src/lib/crypto/kimchi_backend/common/plonk_constraint_system.ml @@ -198,7 +198,10 @@ module Plonk_constraint = struct ; b8 = f b8 } - (* TODO: this seems to be a ""double check"" type of function? It just checks that the basic gate is equal to 0? what is eval_one? what is v and f? *) + (** [eval (module F) get_variable gate] checks that [gate]'s polynomial is + satisfied by the assignments given by [get_variable]. + Currently only implemented for the [Basic] gate. + *) let eval (type v f) (module F : Snarky_backendless.Field_intf.S with type t = f) (eval_one : v -> f) (t : (v, f) t) = ",14 "diff --git a/src/lib/crypto/kimchi_backend/common/plonk_constraint_system.ml b/src/lib/crypto/kimchi_backend/common/plonk_constraint_system.ml @@ -200,7 +200,7 @@ module Plonk_constraint = struct (** [eval (module F) get_variable gate] checks that [gate]'s polynomial is satisfied by the assignments given by [get_variable]. - Currently only implemented for the [Basic] gate. + Warning: currently only implemented for the [Basic] gate. *) let eval (type v f) (module F : Snarky_backendless.Field_intf.S with type t = f) @@ -228,7 +228,6 @@ module Plonk_constraint = struct false ) else true | _ -> - (* TODO: this fails open for other gates than basic? *) true end ",14 "diff --git a/src/lib/snarky_js_bindings/lib/snarky_js_bindings_lib.ml b/src/lib/snarky_js_bindings/lib/snarky_js_bindings_lib.ml @@ -1622,39 +1622,79 @@ let dummy_constraints = (Kimchi_backend_common.Scalar_challenge.create x) : Field.t * Field.t ) -type ('a_var, 'a_value, 'a_weird) pickles_rule = - { identifier : string - ; prevs : 'a_weird list - ; main : 'a_var list -> 'a_var -> Boolean.var list - ; main_value : 'a_value list -> 'a_value -> bool list - } +type ('a_var, 'a_value) packed_pickles_rule = + | Packed_inductive : + ( 'prev_vars + , 'prev_values + , 'widths + , 'heights + , 'a_var + , 'a_value ) + Pickles.Inductive_rule.t + -> ('a_var, 'a_value) packed_pickles_rule + +type ('a_var, 'a_value) packed_pickles_rules = + | Packed_inductive_list : + ( 'prev_varss + , 'prev_valuess + , 'widthss + , 'heightss + , 'a_var + , 'a_value ) + Pickles_types.Hlist.H4_2.T(Pickles.Inductive_rule).t + -> ('a_var, 'a_value) packed_pickles_rules + +let rec combine_packed_rules : + type a_var a_value. + (a_var, a_value) packed_pickles_rule list + -> (a_var, a_value) packed_pickles_rules = function + | [] -> + Packed_inductive_list [] + | Packed_inductive hd :: tl -> + let (Packed_inductive_list tl) = combine_packed_rules tl in + Packed_inductive_list (hd :: tl) + +let rec split_packed_rules : + type a_var a_value. + (a_var, a_value) packed_pickles_rules + -> (a_var, a_value) packed_pickles_rule list = function + | Packed_inductive_list [] -> + [] + | Packed_inductive_list (hd :: tl) -> + Packed_inductive hd :: split_packed_rules (Packed_inductive_list tl) type pickles_rule_js = Js.js_string Js.t * (zkapp_statement_js -> unit) let create_pickles_rule ((identifier, main) : pickles_rule_js) = + Packed_inductive { identifier = Js.to_string identifier ; prevs = [] ; main = - (fun _ statement -> + (fun statement -> dummy_constraints () ; main (Zkapp_statement.to_js statement) ; [] ) - ; main_value = (fun _ _ -> []) } let dummy_rule self = + Packed_inductive { identifier = ""dummy"" ; prevs = [ self; self ] - ; main_value = (fun _ _ -> [ true; true ]) ; main = - (fun _ _ -> + (fun _ -> dummy_constraints () ; (* unsatisfiable *) let x = Impl.exists Field.typ ~compute:(fun () -> Field.Constant.zero) in Field.(Assert.equal x (x + one)) ; - Boolean.[ true_; true_ ] ) + let public_input = + Impl.exists zkapp_statement_typ ~compute:(fun () -> + assert false ) + in + [ { public_input; proof_must_verify = Boolean.true_ } + ; { public_input; proof_must_verify = Boolean.true_ } + ] ) } let other_verification_key_constr : @@ -1697,13 +1737,55 @@ let nat_module (i : int) : (module Pickles_types.Nat.Intf) = let pickles_compile (choices : pickles_rule_js Js.js_array Js.t) = let choices = choices |> Js.to_array |> Array.to_list in let branches = List.length choices + 1 in + let module Types = struct + type prev_varss + + type prev_valuess + + type widthss + + type heightss + end in let choices ~self = + let (Packed_inductive_list l) = List.map choices ~f:create_pickles_rule @ [ dummy_rule self ] + |> combine_packed_rules + in + let convert_unsafe : + type prev_varss prev_valuess widthss heightss. + ( prev_varss + , prev_valuess + , widthss + , heightss + , Zkapp_statement.t + , Zkapp_statement.Constant.t ) + Pickles_types.Hlist.H4_2.T(Pickles.Inductive_rule).t + -> ( Types.prev_varss + , Types.prev_valuess + , Types.widthss + , Types.heightss + , Zkapp_statement.t + , Zkapp_statement.Constant.t ) + Pickles_types.Hlist.H4_2.T(Pickles.Inductive_rule).t = + fun l -> + (* Be very careful with this value. *) + let (T, T, T, T) + : (prev_varss, Types.prev_varss) Core_kernel.Type_equal.t + * (prev_valuess, Types.prev_valuess) Core_kernel.Type_equal.t + * (widthss, Types.widthss) Core_kernel.Type_equal.t + * (heightss, Types.heightss) Core_kernel.Type_equal.t = + ( Obj.magic Core_kernel.Type_equal.T + , Obj.magic Core_kernel.Type_equal.T + , Obj.magic Core_kernel.Type_equal.T + , Obj.magic Core_kernel.Type_equal.T ) + in + l + in + convert_unsafe l in let (module Branches) = nat_module branches in - (* TODO get rid of Obj.magic for choices *) let tag, _cache, p, provers = - Pickles.compile_promise ~choices:(Obj.magic choices) + Pickles.compile_promise ~choices (module Zkapp_statement) (module Zkapp_statement.Constant) ~typ:zkapp_statement_typ @@ -1728,8 +1810,7 @@ let pickles_compile (choices : pickles_rule_js Js.js_array Js.t) = let module Proof = (val p) in let to_js_prover prover = let prove (statement_js : zkapp_statement_js) = - (* TODO: get rid of Obj.magic, this should be an empty ""H3.T"" *) - let prevs = Obj.magic [] in + let prevs: (_, _, _) Statement_with_proof.t = Obj.magic [] in let statement = Zkapp_statement.(statement_js |> of_js |> to_constant) in prover ?handler:None prevs statement |> Promise_js_helpers.to_js in ",14 "diff --git a/src/app/client_sdk/js_util.ml b/src/app/client_sdk/js_util.ml @@ -6,7 +6,8 @@ open Mina_base module Global_slot = Mina_numbers.Global_slot module Memo = Signed_command_memo -let raise_js_error s = Js.raise_js_error (new%js Js.error_constr (Js.string s)) +let raise_js_error s = + Js_error.(raise_ @@ of_error (new%js Js.error_constr (Js.string s))) type string_js = Js.js_string Js.t ",14 "diff --git a/src/lib/pickles/pickles.ml b/src/lib/pickles/pickles.ml @@ -520,12 +520,13 @@ struct let step_data = let i = ref 0 in Timer.clock __LOC__ ; - let module M = - H4.Map (IR) (Branch_data) - (struct - let f : - type a b c d. (a, b, c, d) IR.t -> (a, b, c, d) Branch_data.t = - fun rule -> + let rec f : + type a b c d. + (a, b, c, d) H4.T(IR).t -> (a, b, c, d) H4.T(Branch_data).t = function + | [] -> + [] + | rule :: rules -> + let first = Timer.clock __LOC__ ; let res = Common.time ""make step data"" (fun () -> @@ -536,9 +537,10 @@ struct ~wrap_domains ~proofs_verifieds ) in Timer.clock __LOC__ ; incr i ; res - end) in - M.f choices + first :: f rules + in + f choices in Timer.clock __LOC__ ; let step_domains = ",14 "diff --git a/src/lib/pickles/pseudo/pseudo.ml b/src/lib/pickles/pseudo/pseudo.ml @@ -64,7 +64,7 @@ module Make (Impl : Snarky_backendless.Snark_intf.Run) = struct let all_shifts = Vector.map log2s ~f:(fun d -> shifts ~log2_size:d) in match all_shifts with | [] -> - Array.init num_shifts ~f:(fun _ -> Field.zero) + failwith ""Pseudo.Domain.shifts: no domains were given"" | shifts :: other_shiftss -> (* Runtime check that the shifts across all domains are consistent. The optimisation below will not work if this is not true; if the ",14 "diff --git a/serverjs/cubefn.js b/serverjs/cubefn.js @@ -106,7 +106,7 @@ function setCubeType(cube, carddb) { let peasant = false; let type = FORMATS.length - 1; for (const card of cube.cards) { - if (pauper && !['legal', 'banned'].includes(carddb.cardFromId(card.cardID).legalities.Pauper)) { + if (pauper && !cardIsLegal(carddb.cardFromId(card.cardID), 'Pauper')) { pauper = false; peasant = true; } ",14 "diff --git a/README.md b/README.md @@ -49,10 +49,10 @@ To get started, check out: Use [Releases page](https://github.com/wenzhixin/bootstrap-table/releases) or [the source](https://github.com/wenzhixin/bootstrap-table/archive/master.zip). -### Bower +### Yarn ``` -bower install bootstrap-table +yarn add bootstrap-table ``` ### Npm ",14 "diff --git a/docusaurus/docs/setting-up-your-editor.md b/docusaurus/docs/setting-up-your-editor.md @@ -55,7 +55,7 @@ Then add the block below to your `launch.json` file and put it inside the `.vsco ""type"": ""chrome"", ""request"": ""launch"", ""url"": ""http://localhost:3000"", - ""webRoot"": ""${workspaceRoot}/src"", + ""webRoot"": ""${workspaceFolder}/src"", ""sourceMapPathOverrides"": { ""webpack:///src/*"": ""${webRoot}/*"" } ",14 "diff --git a/packages/react-scripts/lib/react-app.d.ts b/packages/react-scripts/lib/react-app.d.ts @@ -42,7 +42,7 @@ declare module '*.webp' { declare module '*.svg' { import * as React from 'react'; - export const ReactComponent: React.SFC>; + export const ReactComponent: React.FunctionComponent>; const src: string; export default src; ",14 "diff --git a/updater.bat b/updater.bat @@ -39,7 +39,7 @@ IF DEFINED _updateb ( IF NOT ""!_myname:~0,9!""==""[updated]"" ( ECHO Checking updater version... ECHO. - DEL /F ""[updated]!_myname!.bat"" 2>nul + IF EXIST ""[updated]!_myname!.bat"" ( DEL /F ""[updated]!_myname!.bat"" ) REM Uncomment the next line and comment the powershell call for testing. REM COPY /B /V /Y ""!_myname!.bat"" ""[updated]!_myname!.bat"" ( @@ -51,7 +51,7 @@ IF DEFINED _updateb ( ) ELSE ( ECHO Failed. Make sure PowerShell is allowed internet access. ECHO. - PING -n 301 127.0.0.1>nul + TIMEOUT 300 EXIT /B ) ) ELSE ( @@ -63,7 +63,7 @@ IF DEFINED _updateb ( ) ELSE ( ECHO. ECHO The [updated] label is reserved. Do not run an [updated] script directly, or rename it to something else before you run it. - PING -n 301 127.0.0.1>nul + TIMEOUT 300 EXIT /B ) ) ",14 "diff --git a/updater.bat b/updater.bat @@ -16,7 +16,7 @@ IF /I ""%~1""==""-logp"" (SET _log=1 & SET _logp=1) IF /I ""%~1""==""-multioverrides"" (SET _multi=1) IF /I ""%~1""==""-merge"" (SET _merge=1) IF /I ""%~1""==""-updatebatch"" (SET _updateb=1) -IF /I ""%~1""==""-multibackups"" (SET _multibackups=1) +IF /I ""%~1""==""-singlebackup"" (SET _singlebackup=1) SHIFT GOTO parse :endparse @@ -158,10 +158,10 @@ IF EXIST user.js.new ( ) IF ""!_changed!""==""true"" ( CALL :message ""Backing up..."" - IF DEFINED _multibackups ( - MOVE /Y user.js ""user-backup-!date:/=-!_!time::=.!.js"" >nul - ) ELSE ( + IF DEFINED _singlebackup ( MOVE /Y user.js user.js.bak >nul + ) ELSE ( + MOVE /Y user.js ""user-backup-!date:/=-!_!time::=.!.js"" >nul ) REN user.js.new user.js CALL :message ""Update complete."" @@ -196,18 +196,14 @@ REM ############ Merge function ############ :merge SETLOCAL DisableDelayedExpansion ( - FOR /F tokens^=2^,^*^ delims^=^'^"" %%G IN ('FINDSTR /B /R /C:""user_pref.*\).*;"" ""%~1""') DO ( - IF NOT ""%%G""=="""" ( - IF NOT ""%%H""=="""" (SET ""%%G=%%H"") - ) - ) + FOR /F tokens^=2^,^*^ delims^=^'^"" %%G IN ('FINDSTR /B /R /C:""user_pref.*\)[ ]*;"" ""%~1""') DO (IF NOT ""%%H""=="""" (SET ""%%G=%%H"")) FOR /F ""tokens=1,* delims=:"" %%I IN ('FINDSTR /N ""^"" ""%~1""') DO ( SET ""_temp=%%J"" SETLOCAL EnableDelayedExpansion - IF ""!_temp:)=!""==""!_temp!"" ( + IF NOT ""!_temp:~0,9!""==""user_pref"" ( ENDLOCAL & ECHO:%%J ) ELSE ( - IF NOT ""!_temp:~0,9!""==""user_pref"" ( + IF ""!_temp:;=!""==""!_temp!"" ( ENDLOCAL & ECHO:%%J ) ELSE ( ENDLOCAL ",14 "diff --git a/pages/code_schools.js b/pages/code_schools.js @@ -57,7 +57,7 @@ export default class CodeSchools extends React.Component { isFullTime={school.full_time} locations={school.locations} logoSource={`${s3}codeSchoolLogos/${school.name - .replace(/ /g, '_') + .replace(/[ \u00A0]/g, '_') .toLowerCase()}.jpg`} name={school.name} website={school.url} ",14 "diff --git a/pages/history.js b/pages/history.js import Head from 'components/head'; import { s3 } from 'common/constants/urls'; -import Section from 'components/_common_/Section/Section'; +import Content from 'components/Content/Content'; import HeroBanner from 'components/HeroBanner/HeroBanner'; import Timeline from 'components/Timeline/Timeline'; import styles from './styles/history.css'; @@ -24,9 +24,7 @@ export default function() { -
    - -
    + ]} /> ); } ",14 "diff --git a/pages/styles/leadership_circle.css b/pages/styles/leadership_circle.css -.center { - align-self: center; +.linkButtonContainer { + text-align: center; + margin-top: 2rem; } ",14 "diff --git a/jade/page-contents/media_content.html b/jade/page-contents/media_content.html

    Captions

    It is very easy to add a short caption to your photo. Just add the caption as a data-caption attribute.

    - +
    
    - <img class=""materialboxed"" data-caption=""A picture of some deer and tons of trees"" width=""250"" src=""http://th01.deviantart.net/fs70/PRE/i/2013/126/1/e/nature_portrait_by_pw_fotografie-d63tx0n.jpg"">
    + <img class=""materialboxed"" data-caption=""A picture of a way with a group of trees in a park"" width=""250"" src=""http://lorempixel.com/800/400/nature/4"">
    
    ",14 "diff --git a/modules/backup/docker/script/init_container.sh b/modules/backup/docker/script/init_container.sh @@ -10,7 +10,7 @@ printf '%s\n' \ printf '%s\n' \ ""$S3_BACKUP_BUCKET"" \ - >> ~/bucket + > ~/bucket printf '%s\n' \ ""$BACKUP_CRON_EXP root flock -xn ~/backup.lck -c /script/backup.sh"" \ ",14 "diff --git a/modules/gui/frontend/src/app/home/body/browse/browse.js b/modules/gui/frontend/src/app/home/body/browse/browse.js @@ -87,7 +87,7 @@ const removeFile$ = (path) => { const directory = Path.dirname(path) const fileName = Path.basename(path) return actionBuilder('FILE_REMOVED', {directory, fileName}) - .delValueByKey(['files', 'loaded', directory, 'files'], 'name', fileName) + .delValueByTemplate(['files', 'loaded', directory, 'files'], {name: fileName}) .build() }) } @@ -97,7 +97,7 @@ const removeDirectory$ = (path) => { const directory = Path.dirname(path) const fileName = Path.basename(path) return actionBuilder('DIRECTORY_REMOVED', path) - .delValueByKey(['files', 'loaded', directory, 'files'], 'name', fileName) + .delValueByTemplate(['files', 'loaded', directory, 'files'], {name: fileName}) .del(['files', 'loaded', path]) .build() }) ",14 "diff --git a/modules/gui/frontend/src/app/home/body/body.js b/modules/gui/frontend/src/app/home/body/body.js @@ -2,7 +2,7 @@ import {CenteredProgress} from 'widget/progress' import {Select} from 'widget/selectable' import {connect} from 'store' import {initGoogleMapsApi$} from '../map/map' -import {isPathInLocation, location} from 'route' +import {isPathInLocation, location, history} from 'route' import {loadApps$, requestedApps, runApp$} from 'apps' import {msg} from 'translate' import Account from './account/account' @@ -33,6 +33,11 @@ class Body extends React.Component { .dispatch() } + componentDidUpdate() { + if (this.props.location.pathname === '/') + history().replace('/process').dispatch() + } + UNSAFE_componentWillReceiveProps({action, location, requestedApps}) { if (action('LOAD_APPS').dispatched && isPathInLocation('/app/sandbox')) { const path = location.pathname.replace(/^\/app/, '') ",14 "diff --git a/modules/gui/frontend/src/locale/en/translations.json b/modules/gui/frontend/src/locale/en/translations.json ""corrections"": { ""label"": ""Corrections"", ""surfaceReflectance"": { - ""label"": ""Surface reflectance"", + ""label"": ""SR"", ""tooltip"": ""Use scenes atmospherically corrected surface reflectance."" }, ""brdf"": { ",14 "diff --git a/modules/gui/frontend/src/app/home/body/users/users.js b/modules/gui/frontend/src/app/home/body/users/users.js @@ -403,8 +403,8 @@ class User extends React.Component {
    {format.dollars(monthlyInstanceSpending)}
    {format.dollars(monthlyStorageBudget, 0)}
    {format.dollars(monthlyStorageSpending)}
    -
    {format.GB(storageQuota, 0)}
    -
    {format.GB(storageUsed)}
    +
    {format.fileSize(storageQuota, 0)}
    +
    {format.fileSize(storageUsed)}
    ) } ",14 "diff --git a/modules/gui/frontend/src/widget/tabs.module.css b/modules/gui/frontend/src/widget/tabs.module.css .container { + position: relative; padding: 0; pointer-events: none; } pointer-events: all; } +/* .tabBar:before { + content: ''; + position: absolute; + height: 3rem; + width: 5rem; + right: 5.3rem; + z-index: 3; + background: red; + mask-image: linear-gradient(to right, rgba(0, 0, 0, 1), transparent); +} */ + .tabs { + position: relative; padding: 0 0 0 1rem; display: flex; - flex-wrap: wrap; width: 100%; + overflow-x: auto; + margin-right: .5rem; } .newTab { .tab { position: relative; display: flex; + flex-grow: 1; background-color: #2B2B29; border-bottom: 3px solid var(--tab-default-border-color); border-top-right-radius: 0.5rem; ",14 "diff --git a/modules/gui/frontend/src/widget/slider.js b/modules/gui/frontend/src/widget/slider.js @@ -69,14 +69,14 @@ class SliderContainer extends React.Component { } renderDynamics() { - const {input, width, range, float, ticks, snap, minValue, maxValue} = this.props + const {input, width, range, decimals, ticks, snap, minValue, maxValue} = this.props return ( ({...prevState, position})) const value = this.toValue(this.snapPosition(position)) - this.props.input.set( - this.props.float - ? value - : Math.round(value) - ) + const factor = Math.pow(10, this.props.decimals) + const roundedValue = Math.round(value * factor) / factor + this.props.input.set(roundedValue) } } } @@ -391,7 +389,7 @@ SliderDynamics.propTypes = { maxValue: PropTypes.number.isRequired, minValue: PropTypes.number.isRequired, normalize: PropTypes.func.isRequired, - float: PropTypes.bool, + decimals: PropTypes.number, snap: PropTypes.bool, ticks: PropTypes.array, width: PropTypes.number @@ -462,14 +460,14 @@ export default class Slider extends React.Component { } renderContainer() { - const {input, logScale, float = false, snap, range = 'left', info, disabled} = this.props + const {input, logScale, decimals = 0, snap, range = 'left', info, disabled} = this.props const {ticks, minValue, maxValue, width} = this.state return ( const units = (value, precisionDigits = 3) => number({value, precisionDigits}) const unitsPerHour = (value, precisionDigits = 3) => number({value, precisionDigits, suffix: '/h'}) const dollars = (value, {precisionDigits = 3, prefix = '$'} = {}) => number({value, precisionDigits, prefix, minScale: ''}) -const dollarsPerHour = (value, {precisionDigits = 3, prefix = '$'} = {}) => number({value, precisionDigits, minScale: '', prefix, unit: '/h'}) -const dollarsPerMonth = (value, {precisionDigits = 3, prefix = '$'} = {}) => number({value, precisionDigits, minScale: '', prefix, unit: '/mon'}) +const dollarsPerHour = (value, {precisionDigits = 3, prefix = '$'} = {}) => number({value, precisionDigits, minScale: '', prefix, suffix: '/h'}) +const dollarsPerMonth = (value, {precisionDigits = 3, prefix = '$'} = {}) => number({value, precisionDigits, minScale: '', prefix, suffix: '/mon'}) const hours = (value, decimals = 2) => - {action('LOAD_SCENE_AREAS').dispatched + {stream('LOAD_SCENE_AREAS') === 'COMPLETED' ? sceneAreasShown && this.state.show ? this.renderSceneAreas() : null : } @@ -79,14 +79,14 @@ class SceneAreas extends React.Component { loadSceneAreas(aoi, source) { this.loadSceneArea$.next() this.recipeActions.setSceneAreas(null).dispatch() - this.props.asyncActionBuilder('LOAD_SCENE_AREAS', + this.props.stream('LOAD_SCENE_AREAS', api.gee.sceneAreas$({aoi, source}).pipe( - map(sceneAreas => - this.recipeActions.setSceneAreas(sceneAreas) + map(sceneAreas => { + this.recipeActions.setSceneAreas(sceneAreas).dispatch() + } ), takeUntil(this.loadSceneArea$) )) - .dispatch() } } ",14 "diff --git a/modules/gui/frontend/src/app/home/body/process/radarMosaic/bandSelection.js b/modules/gui/frontend/src/app/home/body/process/radarMosaic/bandSelection.js @@ -32,6 +32,7 @@ class BandSelection extends React.Component { 'VH', 'VV/VH' ], + searchableText: 'VV VH VV_VH VV/VH', timeScan: false, pointInTime: true }, { @@ -41,6 +42,7 @@ class BandSelection extends React.Component { VHmed, VVsd ], + searchableText: 'VV_median VH_median VV_stdDev median stdDev sd', timeScan: true, pointInTime: false }, { @@ -50,6 +52,7 @@ class BandSelection extends React.Component { VHmed, VVmed/VHmed ], + searchableText: 'VV_median VH_median VV_median_VH_median median', timeScan: true, pointInTime: false }, { @@ -59,6 +62,7 @@ class BandSelection extends React.Component { VVmin, VVsd ], + searchableText: 'VV_max VV_min VV_stdDev max min stdDev sd', timeScan: true, pointInTime: false }, { @@ -68,6 +72,7 @@ class BandSelection extends React.Component { VHmin, VVsd ], + searchableText: 'VV_min VH_min VV_stdDev min stdDev sd', timeScan: true, pointInTime: false }] @@ -106,7 +111,8 @@ class BandSelection extends React.Component { recipeActions={this.recipeActions} selection={selection} options={options} - onChange={() => this.setSelectorShown(false)}/> + onChange={() => this.setSelectorShown(false)} + onCancel={() => this.setSelectorShown(false)}/> : this.setSelectorShown(true)}/> @@ -141,14 +147,12 @@ class BandSelection extends React.Component { return bandOptions } - setSelectorShown(shown) { - this.setState(prevState => - ({...prevState, showSelector: shown}) - ) + setSelectorShown(showSelector) { + this.setState({showSelector}) } } -const BandSelector = ({recipeActions, selection, options, onChange}) => +const BandSelector = ({recipeActions, selection, options, onChange, onCancel}) =>
    keepOpen inputClassName={styles.comboInput} optionsClassName={styles.comboOptions} - onBlur={onChange} onChange={option => { - recipeActions.setBands(option ? option.value : null).dispatch() + recipeActions.setBands(option.value).dispatch() onChange() - }}/> + }} + onCancel={onCancel}/> const SelectedBands = ({selectedOption, onClick}) => { ",14 "diff --git a/modules/gui/frontend/src/widget/datePicker.js b/modules/gui/frontend/src/widget/datePicker.js @@ -147,7 +147,11 @@ class _DatePickerPanel extends React.Component { const startYear = startDate.year() const endYear = endDate.year() const selectedYear = date.year() - const options = _.range(startYear, endYear + 1).map(year => ({label: year, value: year})) + const options = _.concat( + _.range(startYear - 5, startYear).map(year => ({label: year})), + _.range(startYear, endYear + 1).map(year => ({label: year, value: year})), + _.range(endYear + 1, endYear + 6).map(year => ({label: year})) + ) const selectedOption = _.find(options, ({value}) => value === selectedYear) return (
    @@ -155,7 +159,6 @@ class _DatePickerPanel extends React.Component { options={options} selectedOption={selectedOption} onSelect={option => this.updateDate('year', option.value)} - overScroll={true} />
    ) ",14 "diff --git a/modules/gui/frontend/src/app/home/body/process/classification/inputImagery/recipeSection.js b/modules/gui/frontend/src/app/home/body/process/classification/inputImagery/recipeSection.js @@ -3,7 +3,6 @@ import {connect, select} from 'store' import {isMobile} from 'widget/userAgent' import {msg} from 'translate' import Combo from 'widget/combo' -import Label from 'widget/label' import PropTypes from 'prop-types' import React from 'react' @@ -22,9 +21,9 @@ class RecipeSection extends React.Component { })) return ( -