conflict_resolution
stringlengths
27
16k
<<<<<<< /* DateInput */ if (kendo.ui.DateInput) { kendo.ui.DateInput.prototype.options.messages = $.extend(true, kendo.ui.DateInput.prototype.options.messages, { "year": "Jahr", "month": "Monat", "day": "Tag", "weekday": "Wochentag", "hour": "Stunden", "minute": "Minuten", "second": "Sekunden", "dayperiod": "AM/PM" }); } ======= /* FlatColorPicker messages */ if (kendo.ui.FlatColorPicker) { kendo.ui.FlatColorPicker.prototype.options.messages = $.extend(true, kendo.ui.FlatColorPicker.prototype.options.messages, { "apply": "Anwenden", "cancel": "Abbrechen", "noColor": "keine Farbe", "clearColor": "Farbe löschen" }); } /* ColorPicker messages */ if (kendo.ui.ColorPicker) { kendo.ui.ColorPicker.prototype.options.messages = $.extend(true, kendo.ui.ColorPicker.prototype.options.messages, { "apply": "Anwenden", "cancel": "Abbrechen", "noColor": "keine Farbe", "clearColor": "Farbe löschen" }); } >>>>>>> /* DateInput */ if (kendo.ui.DateInput) { kendo.ui.DateInput.prototype.options.messages = $.extend(true, kendo.ui.DateInput.prototype.options.messages, { "year": "Jahr", "month": "Monat", "day": "Tag", "weekday": "Wochentag", "hour": "Stunden", "minute": "Minuten", "second": "Sekunden", "dayperiod": "AM/PM" }); } /* FlatColorPicker messages */ if (kendo.ui.FlatColorPicker) { kendo.ui.FlatColorPicker.prototype.options.messages = $.extend(true, kendo.ui.FlatColorPicker.prototype.options.messages, { "apply": "Anwenden", "cancel": "Abbrechen", "noColor": "keine Farbe", "clearColor": "Farbe löschen" }); } /* ColorPicker messages */ if (kendo.ui.ColorPicker) { kendo.ui.ColorPicker.prototype.options.messages = $.extend(true, kendo.ui.ColorPicker.prototype.options.messages, { "apply": "Anwenden", "cancel": "Abbrechen", "noColor": "keine Farbe", "clearColor": "Farbe löschen" }); }
<<<<<<< var _ = require('lodash'); var Node = require('./'); var OrderByValueNode = require('./orderByValue'); var ParameterNode = require('./parameter'); var TextNode = require('./text'); ======= var ParameterNode = require(__dirname + '/parameter'); >>>>>>> var OrderByValueNode = require('./orderByValue'); var ParameterNode = require('./parameter'); var TextNode = require('./text'); <<<<<<< var ValueExpressionMixin = module.exports = function() { var BinaryNode = require('./binary'); var CastNode = require('./cast'); var PostfixUnaryNode = require('./postfixUnary'); var TernaryNode = require('./ternary'); ======= var ValueExpressionMixin = function() { var PostfixUnaryNode = require(__dirname + '/postfixUnary'); var BinaryNode = require(__dirname + '/binary'); var TernaryNode = require(__dirname + '/ternary'); var CastNode = require(__dirname + '/cast'); >>>>>>> var ValueExpressionMixin = function() { var BinaryNode = require('./binary'); var CastNode = require('./cast'); var PostfixUnaryNode = require('./postfixUnary'); var TernaryNode = require('./ternary'); <<<<<<< }; var orderMethod = function(direction) { return function() { return new OrderByValueNode({ value : this.toNode(), direction : direction ? new TextNode(direction) : undefined }); }; }; ======= }; >>>>>>> }; var orderMethod = function(direction) { return function() { return new OrderByValueNode({ value : this.toNode(), direction : direction ? new TextNode(direction) : undefined }); }; };
<<<<<<< ======= let {Map} = require("immutable"); let Axios = require("axios"); >>>>>>> <<<<<<< ======= Actions.add.completed.preEmit = function(res) { // We also can redirect to `/{res.data.id}/edit` Router.transitionTo("robot-index"); // or use link = router.makePath("robot-index", params, query), concat anchor, this.transitionTo(link) }; Actions.remove.completed.preEmit = function(res) { // We also can redirect to `/{res.data.id}/edit` Router.transitionTo("robot-index"); // or use link = router.makePath("robot-index", params, query), concat anchor, this.transitionTo(link) }; >>>>>>> Actions.add.completed.preEmit = function(res) { // We also can redirect to `/{res.data.id}/edit` Router.transitionTo("robot-index"); // or use link = router.makePath("robot-index", params, query), concat anchor, this.transitionTo(link) }; Actions.remove.completed.preEmit = function(res) { // We also can redirect to `/{res.data.id}/edit` Router.transitionTo("robot-index"); // or use link = router.makePath("robot-index", params, query), concat anchor, this.transitionTo(link) };
<<<<<<< ======= <div className="pull-right"> <div className="btn-group"> <Link to="robot-index" withQuery={{page: {limit: 3}}} className="btn btn-sm btn-secondary"> Perpage 3 </Link> <Link to="robot-index" withQuery={{page: {limit: 5}}} className="btn btn-sm btn-secondary"> Perpage 5 </Link> <Link to="robot-index" withQuery={{page: {limit: 10}}} className="btn btn-sm btn-secondary"> Perpage 10 </Link> </div> </div> <div className="pull-right"> <div className="btn-group"> <Link to="robot-index" withQuery={{sort: "+name"}} className="btn btn-sm btn-secondary"> SortBy +name </Link> <Link to="robot-index" withQuery={{sort: "-name"}} className="btn btn-sm btn-secondary"> SortBy -name </Link> </div> </div> <div className="pull-right"> <div className="btn-group"> <Link to="robot-index" withQuery={{filter: "undefined", reset: true}} className="btn btn-sm btn-secondary"> Reset filters </Link> <Link to="robot-index" withQuery={{filter: {manufacturer: "Russia"}}} className="btn btn-sm btn-secondary"> FilterBy manufacturer=Russia </Link> </div> </div> >>>>>>>
<<<<<<< <Link to="robot-edit" params={{id: model.get("id")}} className="btn btn-blue" title="Edit"> ======= <Link to="robot-edit" params={{id: model.id}} className="btn btn-orange" title="Edit"> >>>>>>> <Link to="robot-edit" params={{id: model.get("id")}} className="btn btn-orange" title="Edit">
<<<<<<< pg : 'SELECT "post"."content" FROM "post" ORDER BY "post"."content", ("post"."userId" DESC)', sqlite: 'SELECT "post"."content" FROM "post" ORDER BY "post"."content", "post"."userId" DESC', ======= pg : 'SELECT "post"."content" FROM "post" ORDER BY "post"."content", "post"."userId" DESC', >>>>>>> pg : 'SELECT "post"."content" FROM "post" ORDER BY "post"."content", "post"."userId" DESC', sqlite: 'SELECT "post"."content" FROM "post" ORDER BY "post"."content", "post"."userId" DESC', <<<<<<< pg : 'SELECT "post"."content" FROM "post" ORDER BY "post"."content", ("post"."userId" DESC)', sqlite: 'SELECT "post"."content" FROM "post" ORDER BY "post"."content", "post"."userId" DESC', ======= pg : 'SELECT "post"."content" FROM "post" ORDER BY "post"."content", "post"."userId" DESC', >>>>>>> pg : 'SELECT "post"."content" FROM "post" ORDER BY "post"."content", "post"."userId" DESC', sqlite: 'SELECT "post"."content" FROM "post" ORDER BY "post"."content", "post"."userId" DESC',
<<<<<<< var https_opts = {}; var js_bundles = {}; var bug, client_js_path, writer, server, ======= var post_opts = https_opts = {}; var bug, client_js_path, post_opts, server, >>>>>>> var https_opts = {}; var js_bundles = {}; var bug, client_js_path, post_opts, server, <<<<<<< bug = fs.readFileSync(options["png-bug"]); client_js_path = options["client-js-path"]; https_opts.key = fs.readFileSync(options["https-key"]), https_opts.cert = fs.readFileSync(options["https-cert"]); ======= exports.initialize = function(options) { bug = fs.readFileSync(options["png-bug"]); client_js_path = options["client-js-path"]; https_opts.key = fs.readFileSync(options["https-key"]), https_opts.cert = fs.readFileSync(options["https-cert"]); >>>>>>> bug = fs.readFileSync(options["png-bug"]); client_js_path = options["client-js-path"]; https_opts.key = fs.readFileSync(options["https-key"]), https_opts.cert = fs.readFileSync(options["https-cert"]); <<<<<<< ======= var version = /^v(\d+)\.(\d+)\.(\d+)$/.exec(process.version); var agent; if (version[1] > 0 || version[2] > 4) { agent = new http.Agent({host: options["devent-host"], port: options["devent-port"]}); } else { agent = http.getAgent(options["devent-host"], options["devent-port"]); } agent.maxSockets = 512; post_opts = { host: options["devent-host"], port: options["devent-port"], path: "/" + options["devent-topic"], method: "POST", agent: agent, headers: { "content-type": "application/json" } }; >>>>>>> <<<<<<< if (req.method !== "GET") { ======= if (req.method !== "GET") { >>>>>>> if (req.method !== "GET") { <<<<<<< writer.emit('data', json); return; ======= var req = http.request(post_opts, function (res) { res.on("end", function () { if (res.statusCode !== 200) { util.log("bad response: " + res.statusCode); } }); }); req.on("error", function (e) { util.log("error posting to devent-forwarder" + e.toString()); }); req.end(json); >>>>>>> writer.emit('data', json);
<<<<<<< const [, mm, dd, yyyy] = /^(\d{2})-(\d{2})-(\d{4})$/.exec('12-25-1995'); const n = new Date(`${mm}, ${dd} ${yyyy}`); ======= >>>>>>> const [, mm, dd, yyyy] = /^(\d{2})-(\d{2})-(\d{4})$/.exec('12-25-1995'); const n = new Date(`${mm}, ${dd} ${yyyy}`); expect(m.valueOf()).toBe(n.getTime()); <<<<<<< const day = dayjs('12-25-1995'); expect(m.valueOf()).toBe(n.getTime()); ======= >>>>>>> <<<<<<< const m = moment(time).format('dddd, MMMM Do YYYY, h:mm:ss A'); const d = date.format(new Date(time), 'eeee, MMMM do YYYY, h:mm:ss aa', { awareOfUnicodeTokens: true, }); ======= const m = moment(time).format('dddd, MMMM D YYYY, h:mm:ss A'); const d = date.format(new Date(time), 'eeee, MMMM d YYYY, h:mm:ss aa', { awareOfUnicodeTokens: true, }); >>>>>>> const m = moment(time).format('dddd, MMMM Do YYYY, h:mm:ss A'); const d = date.format(new Date(time), 'eeee, MMMM do YYYY, h:mm:ss aa', { awareOfUnicodeTokens: true, });
<<<<<<< if ( navigator && navigator.requestMIDIAccess ) { navigator.requestMIDIAccess().then(onSuccessCallback, onErrorCallback); } ======= try { navigator.requestMIDIAccess().then(onSuccessCallback, onErrorCallback); } catch(err) { var text = "There was an error on this page.\n\n"; text += "Error description: " + err.message + "\n\n"; text += "Click OK to continue.\n\n"; console.log(text); } >>>>>>> if ( navigator && navigator.requestMIDIAccess ) { try { navigator.requestMIDIAccess().then(onSuccessCallback, onErrorCallback); } catch(err) { var text = "There was an error on this page.\n\n"; text += "Error description: " + err.message + "\n\n"; text += "Click OK to continue.\n\n"; console.log(text); } }
<<<<<<< /** Change the playback speed of a Wad during playback. inputSpeed is a value of 0 < speed, and is the rate of playback of the audio. E.g. if input speed = 2.0, the playback will be twice as fast **/ Wad.prototype.setSpeed = function(inputSpeed){ //Check/Save the input var speed; if(inputSpeed && inputSpeed > 0) speed = inputSpeed; else speed = 0; //Check if we have a soundsource (Though we always should) if(this.soundSource) { //Set the value this.soundSource.playbackRate.value = speed; } else { //Inform that there is no delay on the current wad console.log("Sorry, but the wad does not contain a soundSource!"); } return this; }; ======= /** Change the Reverb of a Wad at any time, including during playback. inputWet is a value of 0 < wetness/gain < 1 **/ Wad.prototype.setReverb = function(inputWet){ //Check/Save the input var wet; if(inputWet && inputWet > 0 && inputWet < 1) wet = inputWet; else wet = 0; //Check if we have delay if(this.reverb) { //Set the value this.reverb.wet = wet; //Set the node's value, if it exists if(this.reverb.node) { this.reverb.node.wet.gain.value = wet; } } else { //Inform that there is no reverb on the current wad console.log("Sorry, but the wad does not contain Reverb!"); } return this; }; >>>>>>> /** Change the playback speed of a Wad during playback. inputSpeed is a value of 0 < speed, and is the rate of playback of the audio. E.g. if input speed = 2.0, the playback will be twice as fast **/ Wad.prototype.setSpeed = function(inputSpeed){ //Check/Save the input var speed; if(inputSpeed && inputSpeed > 0) speed = inputSpeed; else speed = 0; //Check if we have a soundsource (Though we always should) if(this.soundSource) { //Set the value this.soundSource.playbackRate.value = speed; } else { //Inform that there is no delay on the current wad console.log("Sorry, but the wad does not contain a soundSource!"); } return this; }; /** Change the Reverb of a Wad at any time, including during playback. inputWet is a value of 0 < wetness/gain < 1 **/ Wad.prototype.setReverb = function(inputWet){ //Check/Save the input var wet; if(inputWet && inputWet > 0 && inputWet < 1) wet = inputWet; else wet = 0; //Check if we have delay if(this.reverb) { //Set the value this.reverb.wet = wet; //Set the node's value, if it exists if(this.reverb.node) { this.reverb.node.wet.gain.value = wet; } } else { //Inform that there is no reverb on the current wad console.log("Sorry, but the wad does not contain Reverb!"); } return this; };
<<<<<<< import { Toggles } from 'utils/constants'; import lang from 'languages'; import useSidebar from 'hooks/useSidebar'; import useToggle from 'hooks/useToggle'; ======= >>>>>>> import { Toggles } from 'utils/constants'; import useToggle from 'hooks/useToggle';
<<<<<<< const CDPList = memo(function({ currentPath, currentQuery, address }) { const { showType } = useModal(); ======= const CDPList = memo(function({ currentPath, currentQuery }) { const { showByType } = useModal(); >>>>>>> const CDPList = memo(function({ currentPath, currentQuery, address }) { const { showByType } = useModal(); <<<<<<< {/* {!address ? null : ( */} { <DashedFakeButton onClick={() => showType('cdpcreate')} justifyContent="center" borderRadius="4px" py="s" > <Plus /> </DashedFakeButton> } ======= <DashedFakeButton onClick={() => showByType('cdpcreate')} justifyContent="center" borderRadius="4px" py="s" > <Plus /> </DashedFakeButton> >>>>>>> {/* {!address ? null : ( */} { <DashedFakeButton onClick={() => showByType('cdpcreate')} justifyContent="center" borderRadius="4px" py="s" > <Plus /> </DashedFakeButton> }
<<<<<<< import { ETH, MDAI } from '@makerdao/dai-plugin-mcd'; ======= import { fromWei } from 'utils/units'; >>>>>>> import { ETH, MDAI } from '@makerdao/dai-plugin-mcd'; import { fromWei } from 'utils/units'; <<<<<<< export function getEventHistory(cdp) { //return cdp.getEventHistory(); return mockHistoryDataFromSDK; //TODO switch to real data } export const mockHistoryDataFromSDK = [ { transactionHash: '0xbe023a205453b833e65bf29063de8b8b3bd44d2e68c9c079f681ec46a765a63f', changeInCollateral: ETH(99.5), collateralAction: 'free', time: new Date(Date.now()), senderAddress: '0x1ad35418e7b7c5746ea42295a1100480a810256a', resultingCollateral: ETH(900.5), resultingDebt: MDAI(10090), ilk: 'ETH-A' }, { transactionHash: '0xbe023a205453b833e65bf29063de8b8b3bd44d2e68c9c079f681ec46a765a63f', changeInCollateral: ETH(0), changeInDebt: MDAI(1000), daiAction: 'wipe', time: new Date(Date.now() - 10000000000), senderAddress: '0x1ad35418e7b7c5746ea42295a1100480a810256a', resultingCollateral: ETH(1000), resultingDebt: MDAI(10045), ilk: 'ETH-A' }, { transactionHash: '0xbe023a205453b833e65bf29063de8b8b3bd44d2e68c9c079f681ec46a765a63f', changeInCollateral: ETH(10000), collateralAction: 'lock', changeInDebt: MDAI(120000), daiAction: 'draw', time: new Date(Date.now() - 20000000000), senderAddress: '0x1ad35418e7b7c5746ea42295a1100480a810256a', resultingCollateral: ETH(1000), resultingDebt: MDAI(1100), ilk: 'ETH-A' } ]; ======= function convert(valueType, value) { switch (valueType) { case INK: case ART: return fromWei(value); default: return value; } } >>>>>>> export function getEventHistory(cdp) { //return cdp.getEventHistory(); return mockHistoryDataFromSDK; //TODO switch to real data } export const mockHistoryDataFromSDK = [ { transactionHash: '0xbe023a205453b833e65bf29063de8b8b3bd44d2e68c9c079f681ec46a765a63f', changeInCollateral: ETH(99.5), collateralAction: 'free', time: new Date(Date.now()), senderAddress: '0x1ad35418e7b7c5746ea42295a1100480a810256a', resultingCollateral: ETH(900.5), resultingDebt: MDAI(10090), ilk: 'ETH-A' }, { transactionHash: '0xbe023a205453b833e65bf29063de8b8b3bd44d2e68c9c079f681ec46a765a63f', changeInCollateral: ETH(0), changeInDebt: MDAI(1000), daiAction: 'wipe', time: new Date(Date.now() - 10000000000), senderAddress: '0x1ad35418e7b7c5746ea42295a1100480a810256a', resultingCollateral: ETH(1000), resultingDebt: MDAI(10045), ilk: 'ETH-A' }, { transactionHash: '0xbe023a205453b833e65bf29063de8b8b3bd44d2e68c9c079f681ec46a765a63f', changeInCollateral: ETH(10000), collateralAction: 'lock', changeInDebt: MDAI(120000), daiAction: 'draw', time: new Date(Date.now() - 20000000000), senderAddress: '0x1ad35418e7b7c5746ea42295a1100480a810256a', resultingCollateral: ETH(1000), resultingDebt: MDAI(1100), ilk: 'ETH-A' } ]; function convert(valueType, value) { switch (valueType) { case INK: case ART: return fromWei(value); default: return value; } }
<<<<<<< import React, { useCallback, useContext, useEffect, useState } from 'react'; ======= import React, { useContext, useRef } from 'react'; >>>>>>> import React, { useContext, useRef } from 'react'; <<<<<<< import { isOnlyEmojis, renderText, getReadByTooltipText, smartRender, } from '../../utils'; import { TranslationContext, ChannelContext } from '../../context'; ======= import { getReadByTooltipText, smartRender } from '../../utils'; import { TranslationContext, ChannelContext } from '../../context'; >>>>>>> import { getReadByTooltipText, smartRender } from '../../utils'; import { TranslationContext, ChannelContext } from '../../context'; <<<<<<< import { useUserRole } from './hooks/useUserRole'; import { useReactionHandler } from './hooks/useReactionHandler'; import { useOpenThreadHandler } from './hooks/useOpenThreadHandler'; import { useMentionsHandler } from './hooks/useMentionsHandler'; import { useMuteHandler } from './hooks/useMuteHandler'; import { useFlagHandler } from './hooks/useFlagHandler'; import { isUserMuted, areMessagePropsEqual } from './utils'; import { useEditHandler } from './hooks/useEditHandler'; import { useDeleteHandler } from './hooks/useDeleteHandler'; import { useActionHandler } from './hooks/useActionHandler'; import { useRetryHandler } from './hooks/useRetryHandler'; import { useUserHandler } from './hooks/useUserHandler'; /** @type {(message: import('stream-chat').MessageResponse | undefined) => boolean} */ const messageHasReactions = (message) => { if (!message) { return false; } return Boolean(message.latest_reactions && message.latest_reactions.length); }; /** @type {(message: import('stream-chat').MessageResponse | undefined) => boolean} */ const messageHasAttachments = (message) => { return Boolean(message && message.attachments && message.attachments.length); }; ======= import { useActionHandler, useOpenThreadHandler, useReactionClick, useReactionHandler, useRetryHandler, useUserHandler, useUserRole, } from './hooks'; import { areMessagePropsEqual, messageHasReactions, messageHasAttachments, } from './utils'; >>>>>>> import { useActionHandler, useOpenThreadHandler, useReactionClick, useReactionHandler, useRetryHandler, useUserHandler, useUserRole, } from './hooks'; import { areMessagePropsEqual, messageHasReactions, messageHasAttachments, } from './utils'; <<<<<<< // eslint-disable-next-line sonarjs/cognitive-complexity const MessageSimple = (props) => { const { clearEditingState, editing, message, messageListRect, threadList, updateMessage: propUpdateMessage, handleAction: propHandleAction, handleOpenThread: propHandleOpenThread, handleReaction: propHandleReaction, handleRetry: propHandleRetry, onUserClick: onUserClickCustomHandler, onUserHover: onUserHoverCustomHandler, tDateTimeParser: propTDateTimeParser, } = props; const { updateMessage: channelUpdateMessage } = useContext(ChannelContext); const updateMessage = propUpdateMessage || channelUpdateMessage; const { tDateTimeParser } = useContext(TranslationContext); const [showDetailedReactions, setShowDetailedReactions] = useState(false); const [actionsBoxOpen, setActionsBoxOpen] = useState(false); const { isMyMessage } = useUserRole(props.message); const handleOpenThread = useOpenThreadHandler(message); const handleReaction = useReactionHandler(message); const handleAction = useActionHandler(message); const handleRetry = useRetryHandler(); const { onUserClick, onUserHover } = useUserHandler( { onUserClickHandler: onUserClickCustomHandler, onUserHoverHandler: onUserHoverCustomHandler, }, message, ); const { Attachment = DefaultAttachment, MessageDeleted = DefaultMessageDeleted, } = props; /** @type { React.RefObject<ReactionSelector> | null } */ const reactionSelectorRef = React.createRef(); /** @type {EventListener} */ const closeDetailedReactions = useCallback( (event) => { if ( event.target && // @ts-ignore reactionSelectorRef?.current?.reactionSelector?.current?.contains( event.target, ) ) { return; } setShowDetailedReactions(() => false); }, [setShowDetailedReactions, reactionSelectorRef], ); /** @type {() => void} Typescript syntax */ const onReactionListClick = () => setShowDetailedReactions(true); useEffect(() => { if (showDetailedReactions) { document.addEventListener('click', closeDetailedReactions); document.addEventListener('touchend', closeDetailedReactions); } else { document.removeEventListener('click', closeDetailedReactions); document.removeEventListener('touchend', closeDetailedReactions); } return () => { document.removeEventListener('click', closeDetailedReactions); document.removeEventListener('touchend', closeDetailedReactions); }; }, [showDetailedReactions, closeDetailedReactions]); /** @type {() => void} Typescript syntax */ const hideOptions = () => setActionsBoxOpen(false); useEffect(() => { if (message?.deleted_at) { document.removeEventListener('click', closeDetailedReactions); document.removeEventListener('touchend', closeDetailedReactions); document.removeEventListener('click', hideOptions); } }, [message, closeDetailedReactions]); const dateTimeParser = propTDateTimeParser || tDateTimeParser; const when = dateTimeParser && message && dateTimeParser(message.created_at).calendar && dateTimeParser(message.created_at).calendar(); const hasReactions = messageHasReactions(message); const hasAttachment = messageHasAttachments(message); const messageClasses = isMyMessage ? 'str-chat__message str-chat__message--me str-chat__message-simple str-chat__message-simple--me' : 'str-chat__message str-chat__message-simple'; const images = hasAttachment && message?.attachments?.filter( /** @type {(item: import('stream-chat').Attachment) => boolean} Typescript syntax */ (item) => item.type === 'image', ); if (message?.type === 'message.read' || message?.type === 'message.date') { return null; ======= // eslint-disable-next-line sonarjs/cognitive-complexity const MessageSimple = (props) => { const { clearEditingState, editing, message, messageListRect, threadList, updateMessage: propUpdateMessage, handleAction: propHandleAction, handleOpenThread: propHandleOpenThread, handleReaction: propHandleReaction, handleRetry: propHandleRetry, onUserClick: onUserClickCustomHandler, onUserHover: onUserHoverCustomHandler, tDateTimeParser: propTDateTimeParser, } = props; /** *@type {import('types').ChannelContextValue} */ const { updateMessage: channelUpdateMessage } = useContext(ChannelContext); const updateMessage = propUpdateMessage || channelUpdateMessage; const { tDateTimeParser } = useContext(TranslationContext); const { isMyMessage } = useUserRole(message); const handleOpenThread = useOpenThreadHandler(message); const handleReaction = useReactionHandler(message); const handleAction = useActionHandler(message); const handleRetry = useRetryHandler(); const { onUserClick, onUserHover } = useUserHandler( { onUserClickHandler: onUserClickCustomHandler, onUserHoverHandler: onUserHoverCustomHandler, }, message, ); const reactionSelectorRef = React.createRef(); const messageWrapperRef = useRef(null); const { onReactionListClick, showDetailedReactions } = useReactionClick( reactionSelectorRef, message, ); const { Attachment = DefaultAttachment, MessageDeleted = DefaultMessageDeleted, } = props; const dateTimeParser = propTDateTimeParser || tDateTimeParser; const when = dateTimeParser && message && dateTimeParser(message.created_at).calendar && dateTimeParser(message.created_at).calendar(); const hasReactions = messageHasReactions(message); const hasAttachment = messageHasAttachments(message); const messageClasses = isMyMessage ? 'str-chat__message str-chat__message--me str-chat__message-simple str-chat__message-simple--me' : 'str-chat__message str-chat__message-simple'; const images = hasAttachment && message?.attachments?.filter( /** @type {(item: import('stream-chat').Attachment) => boolean} Typescript syntax */ (item) => item.type === 'image', ); if (message?.type === 'message.read' || message?.type === 'message.date') { return null; >>>>>>> // eslint-disable-next-line sonarjs/cognitive-complexity const MessageSimple = (props) => { const { clearEditingState, editing, message, messageListRect, threadList, updateMessage: propUpdateMessage, handleAction: propHandleAction, handleOpenThread: propHandleOpenThread, handleReaction: propHandleReaction, handleRetry: propHandleRetry, onUserClick: onUserClickCustomHandler, onUserHover: onUserHoverCustomHandler, tDateTimeParser: propTDateTimeParser, } = props; const { updateMessage: channelUpdateMessage } = useContext(ChannelContext); const updateMessage = propUpdateMessage || channelUpdateMessage; const { tDateTimeParser } = useContext(TranslationContext); const { isMyMessage } = useUserRole(message); const handleOpenThread = useOpenThreadHandler(message); const handleReaction = useReactionHandler(message); const handleAction = useActionHandler(message); const handleRetry = useRetryHandler(); const { onUserClick, onUserHover } = useUserHandler( { onUserClickHandler: onUserClickCustomHandler, onUserHoverHandler: onUserHoverCustomHandler, }, message, ); const reactionSelectorRef = React.createRef(); const messageWrapperRef = useRef(null); const { onReactionListClick, showDetailedReactions } = useReactionClick( reactionSelectorRef, message, ); const { Attachment = DefaultAttachment, MessageDeleted = DefaultMessageDeleted, } = props; const dateTimeParser = propTDateTimeParser || tDateTimeParser; const when = dateTimeParser && message && dateTimeParser(message.created_at).calendar && dateTimeParser(message.created_at).calendar(); const hasReactions = messageHasReactions(message); const hasAttachment = messageHasAttachments(message); const messageClasses = isMyMessage ? 'str-chat__message str-chat__message--me str-chat__message-simple str-chat__message-simple--me' : 'str-chat__message str-chat__message-simple'; const images = hasAttachment && message?.attachments?.filter( /** @type {(item: import('stream-chat').Attachment) => boolean} Typescript syntax */ (item) => item.type === 'image', ); if (message?.type === 'message.read' || message?.type === 'message.date') { return null;
<<<<<<< } export function getUnique(arr, comp) { return arr .map(e => e[comp]) .map((e, i, final) => final.indexOf(e) === i && i) .filter(e => arr[e]) .map(e => arr[e]); } export function firstLetterLowercase(str) { return str.charAt(0).toLowerCase() + str.slice(1); } export function cleanSymbol(s) { if (s === 'MDAI') return 'DAI'; return s; } export const actionToText = { lock: lang.actions_past_tense.deposit, free: lang.actions_past_tense.withdraw, wipe: lang.actions_past_tense.pay_back, draw: lang.actions_past_tense.generate }; export function activityString(action, amount, lowercase) { const and = lowercase ? ' and ' : ''; const formattedAction = lowercase ? firstLetterLowercase(actionToText[action]) : actionToText[action]; return ( and + formattedAction + ' ' + prettifyNumber(amount.toNumber()) + ' ' + cleanSymbol(amount.symbol) ); } export function fullActivityString(e) { let str = ''; if (e.collateralAction) str += activityString(e.collateralAction, e.changeInCollateral); if (e.daiAction) str += activityString(e.daiAction, e.changeInDebt, e.collateralAction); return str; } export function formatDate(d) { return d.toLocaleDateString(lang.getInterfaceLanguage(), { year: 'numeric', month: 'short', day: 'numeric' }); ======= >>>>>>> } export function firstLetterLowercase(str) { return str.charAt(0).toLowerCase() + str.slice(1); } export function cleanSymbol(s) { if (s === 'MDAI') return 'DAI'; return s; } export const actionToText = { lock: lang.actions_past_tense.deposit, free: lang.actions_past_tense.withdraw, wipe: lang.actions_past_tense.pay_back, draw: lang.actions_past_tense.generate }; export function activityString(action, amount, lowercase) { const and = lowercase ? ' and ' : ''; const formattedAction = lowercase ? firstLetterLowercase(actionToText[action]) : actionToText[action]; return ( and + formattedAction + ' ' + prettifyNumber(amount.toNumber()) + ' ' + cleanSymbol(amount.symbol) ); } export function fullActivityString(e) { let str = ''; if (e.collateralAction) str += activityString(e.collateralAction, e.changeInCollateral); if (e.daiAction) str += activityString(e.daiAction, e.changeInDebt, e.collateralAction); return str; } export function formatDate(d) { return d.toLocaleDateString(lang.getInterfaceLanguage(), { year: 'numeric', month: 'short', day: 'numeric' });
<<<<<<< import LedgerType from 'components/LedgerType'; import LedgerAddresses from './LedgerAddresses'; import { Grid } from '@makerdao/ui-components-core'; ======= import { Grid, Flex, Box } from '@makerdao/ui-components-core'; >>>>>>> import LedgerType from 'components/LedgerType'; import LedgerAddresses from './LedgerAddresses'; import { Grid, Flex, Box } from '@makerdao/ui-components-core';
<<<<<<< > <MakerSmall /> </NavbarItem> {shownIlks.map((cdp, idx) => { const linkPath = `/cdp/${cdp.slug}`; ======= /> {cdps.map((cdp, idx) => { const linkPath = `/cdp/${cdp.id}/`; >>>>>>> > <MakerSmall /> </NavbarItem> {cdps.map((cdp, idx) => { const linkPath = `/cdp/${cdp.id}/`;
<<<<<<< it('should not remove undefined', function() { var objA = { user: undefined }; var objB = { user: undefined }; expect(jsonpatch.compare(objA, objB)).toReallyEqual([]); }) ======= it("should replace 0 with empty string", function () { var objA = { user: 0 }; var objB = { user: '' }; expect(jsonpatch.compare(objA, objB)).toReallyEqual([{ op: "replace", path: "/user", value: '' }]); }); >>>>>>> it('should not remove undefined', function() { var objA = { user: undefined }; var objB = { user: undefined }; expect(jsonpatch.compare(objA, objB)).toReallyEqual([]); }) it("should replace 0 with empty string", function () { var objA = { user: 0 }; var objB = { user: '' }; expect(jsonpatch.compare(objA, objB)).toReallyEqual([{ op: "replace", path: "/user", value: '' }]); });
<<<<<<< if (obj === mirror) { return; } ======= if (typeof obj.toJSON === "function") { obj = obj.toJSON(); } >>>>>>> if (obj === mirror) { return; if (typeof obj.toJSON === "function") { obj = obj.toJSON(); }
<<<<<<< Version 2.3.2 (sep 2, 2014): - Add ttp:// -> http:// alia. ======= Version 2.3.2 (sep 2, 2014): - Use TLD list! >>>>>>> Version 2.3.2 (sep 2, 2014): - Add ttp:// -> http:// alia. - Use TLD list! <<<<<<< var urlRE = /\b(?:([-a-z*]+:\/\/)[\w\.]+|(?:([\w:\.]+)@)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|[\w\.]+\.(?:com|net|org|edu|gov|biz|info|asia|cn|de|eu|jp|hk|tw|uk|us)))([^\s'"<>(),\u0080-\uffff]*)/gi; ======= >>>>>>>
<<<<<<< this._parser = new Parser(this, this._stream, {protocols: supportedProtos}); this._parser.handshakeResponse(head); ======= this._parser = new Parser(this); var handshake = this._parser.handshakeResponse(head); try { this._stream.write(handshake, 'binary') } catch (e) {} >>>>>>> this._parser = new Parser(this, {protocols: supportedProtos}); var handshake = this._parser.handshakeResponse(head); try { this._stream.write(handshake, 'binary') } catch (e) {}
<<<<<<< // Traverse in ascending order to make sure that inner circleMarkers are on top of further legs. Normal markers are re-ordered by newPosition. // The reverse order trick no longer improves performance on modern browsers. for (i = 0; i < childMarkers.length; i++) { ======= group._ignoreMove = true; for (i = childMarkers.length - 1; i >= 0; i--) { >>>>>>> group._ignoreMove = true; // Traverse in ascending order to make sure that inner circleMarkers are on top of further legs. Normal markers are re-ordered by newPosition. // The reverse order trick no longer improves performance on modern browsers. for (i = 0; i < childMarkers.length; i++) { <<<<<<< // Reveal markers and spider legs. ======= var initialLegOpacity = this.SVG_ANIMATION ? 0 : 0.3; >>>>>>> // Reveal markers and spider legs. <<<<<<< // Animate leg (animation is actually delegated to CSS transition). if (svg) { leg = m._spiderLeg; legPath = leg._path; legPath.style.strokeDashoffset = 0; //legPath.style.strokeOpacity = finalLegOpacity; leg.setStyle({opacity: finalLegOpacity}); } ======= //Add Legs. var legOptions = this._group.options.spiderLegPolylineOptions; if (legOptions.opacity === undefined) { legOptions.opacity = initialLegOpacity; } leg = new L.Polyline([me._latlng, newPos], legOptions); map.addLayer(leg); m._spiderLeg = leg; //Following animations don't work for canvas or browsers that don't support animated svg if (this.SVG_ANIMATION) { //How this works: //http://stackoverflow.com/questions/5924238/how-do-you-animate-an-svg-path-in-ios //http://dev.opera.com/articles/view/advanced-svg-animation-techniques/ //Animate length var length = leg._path.getTotalLength(); leg._path.setAttribute("stroke-dasharray", length + "," + length); var anim = document.createElementNS(xmlns, "animate"); anim.setAttribute("attributeName", "stroke-dashoffset"); anim.setAttribute("begin", "indefinite"); anim.setAttribute("from", length); anim.setAttribute("to", 0); anim.setAttribute("dur", 0.25); leg._path.appendChild(anim); anim.beginElement(); //Animate opacity anim = document.createElementNS(xmlns, "animate"); anim.setAttribute("attributeName", "stroke-opacity"); anim.setAttribute("attributeName", "stroke-opacity"); anim.setAttribute("begin", "indefinite"); anim.setAttribute("from", 0); anim.setAttribute("to", 0.3); anim.setAttribute("dur", 0.25); leg._path.appendChild(anim); anim.beginElement(); } } me.setOpacity(0.3); //Set the opacity of the spiderLegs back to their correct value // The animations above override this until they complete. // If the initial opacity of the spiderlegs isn't 0 then they appear before the animation starts. this._group._forceLayout(); for (i = childMarkers.length - 1; i >= 0; i--) { m = childMarkers[i]._spiderLeg; m.options.opacity = 0.5; m._path.setAttribute('stroke-opacity', 0.5); >>>>>>> // Animate leg (animation is actually delegated to CSS transition). if (svg) { leg = m._spiderLeg; legPath = leg._path; legPath.style.strokeDashoffset = 0; //legPath.style.strokeOpacity = finalLegOpacity; leg.setStyle({opacity: finalLegOpacity}); } <<<<<<< svg = L.Path.SVG, m, i, leg, legPath, legLength; ======= m, i, a; >>>>>>> svg = L.Path.SVG, m, i, leg, legPath, legLength; <<<<<<< // Animate the spider leg back in (animation is actually delegated to CSS transition). if (svg) { leg = m._spiderLeg; legPath = leg._path; legLength = legPath.getTotalLength() + 0.1; legPath.style.strokeDashoffset = legLength; leg.setStyle({opacity: 0}); ======= //Animate the spider legs back in if (this.SVG_ANIMATION) { a = m._spiderLeg._path.childNodes[0]; a.setAttribute('to', a.getAttribute('from')); a.setAttribute('from', 0); a.beginElement(); a = m._spiderLeg._path.childNodes[1]; a.setAttribute('from', 0.5); a.setAttribute('to', 0); a.setAttribute('stroke-opacity', 0); a.beginElement(); m._spiderLeg._path.setAttribute('stroke-opacity', 0); >>>>>>> // Animate the spider leg back in (animation is actually delegated to CSS transition). if (svg) { leg = m._spiderLeg; legPath = leg._path; legLength = legPath.getTotalLength() + 0.1; legPath.style.strokeDashoffset = legLength; leg.setStyle({opacity: 0}); <<<<<<< ======= if (!L.Browser.touch) { this._map.getRenderer(this); //Needs to happen in the pageload, not after, or animations don't work in webkit // http://stackoverflow.com/questions/8455200/svg-animate-with-dynamically-added-elements //Disable on touch browsers as the animation messes up on a touch zoom and isn't very noticable } >>>>>>> if (!L.Browser.touch) { this._map.getRenderer(this); //Needs to happen in the pageload, not after, or animations don't work in webkit // http://stackoverflow.com/questions/8455200/svg-animate-with-dynamically-added-elements //Disable on touch browsers as the animation messes up on a touch zoom and isn't very noticable }
<<<<<<< // Refresh bounds and weighted positions. this._topClusterLevel._recalculateBounds(); ======= layer.off('move', this._childMarkerMoved, this); >>>>>>> // Refresh bounds and weighted positions. this._topClusterLevel._recalculateBounds(); layer.off('move', this._childMarkerMoved, this); <<<<<<< /** * Removes a marker from all _gridUnclustered zoom levels, starting at the supplied zoom. * @param marker to be removed from _gridUnclustered. * @param z integer bottom start zoom level (included) * @private */ _removeFromGridUnclustered: function (marker, z) { var map = this._map, gridUnclustered = this._gridUnclustered; for (; z >= 0; z--) { if (!gridUnclustered[z].removeObject(marker, map.project(marker.getLatLng(), z))) { break; } } }, ======= _childMarkerMoved: function (e) { if (!this._ignoreMove) { e.target._latlng = e.oldLatLng; this.removeLayer(e.target); e.target._latlng = e.latlng; this.addLayer(e.target); } return; }, >>>>>>> /** * Removes a marker from all _gridUnclustered zoom levels, starting at the supplied zoom. * @param marker to be removed from _gridUnclustered. * @param z integer bottom start zoom level (included) * @private */ _removeFromGridUnclustered: function (marker, z) { var map = this._map, gridUnclustered = this._gridUnclustered; for (; z >= 0; z--) { if (!gridUnclustered[z].removeObject(marker, map.project(marker.getLatLng(), z))) { break; } } }, _childMarkerMoved: function (e) { if (!this._ignoreMove) { e.target._latlng = e.oldLatLng; this.removeLayer(e.target); e.target._latlng = e.latlng; this.addLayer(e.target); } }, <<<<<<< _withAnimation: { //Animated versions here _animationStart: function () { this._map._mapPane.className += ' leaflet-cluster-anim'; this._inZoomAnimation++; }, _animationZoomIn: function (previousZoomLevel, newZoomLevel) { var bounds = this._getExpandedVisibleBounds(), fg = this._featureGroup, i; //Add all children of current clusters to map and remove those clusters from map this._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) { var startPos = c._latlng, markers = c._markers, m; ======= _animationZoomIn: function (previousZoomLevel, newZoomLevel) { var bounds = this._getExpandedVisibleBounds(), fg = this._featureGroup, i; this._ignoreMove = true; //Add all children of current clusters to map and remove those clusters from map this._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) { var startPos = c._latlng, markers = c._markers, m; if (!bounds.contains(startPos)) { startPos = null; } >>>>>>> _withAnimation: { //Animated versions here _animationStart: function () { this._map._mapPane.className += ' leaflet-cluster-anim'; this._inZoomAnimation++; }, _animationZoomIn: function (previousZoomLevel, newZoomLevel) { var bounds = this._getExpandedVisibleBounds(), fg = this._featureGroup, i; this._ignoreMove = true; //Add all children of current clusters to map and remove those clusters from map this._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) { var startPos = c._latlng, markers = c._markers, m;
<<<<<<< if (year && item.date.replace(year[0],"").indexOf(year[0]) !== -1) item.date = item.date.replace(year[0],""); ======= if (year && item.date.replace(year,"").indexOf(year) !== -1) { item.date = item.date.replace(year,""); } >>>>>>> if (year && item.date.replace(year[0],"").indexOf(year[0]) !== -1) { item.date = item.date.replace(year[0],""); }
<<<<<<< triangle: function(p1, p2, p3){ return new util.Shape(function(ctx){ ctx.beginPath(); ctx.moveTo(p1.x, p1.y); ctx.lineTo(p2.x, p2.y); ctx.lineTo(p3.x, p3.y); ctx.lineTo(p1.x, p1.y); }); } ======= polygon: function(args){ var points = [].slice.call(arguments); util.setLastPoint(points[0]); return new util.Shape(function(ctx){ if (!util.isDrawingPath()){ ctx.beginPath(); } var points = this.pointsArray; for(var i=0; i < points.length; i++) { if (i === 0 && !util.isDrawingPath()) { ctx.moveTo(points[i].x, points[i].y); } else { ctx.lineTo(points[i].x, points[i].y); } if(i === points.length-1) { ctx.lineTo(points[0].x, points[0].y); } } }, points); }, lineTo: function(startPoint, toPoint){ util.setLastPoint(toPoint); return new util.Path(getContext().lineTo, new Array(toPoint.x, toPoint.y), startPoint); }, arc: function(radius, centerPoint, startAngle, endAngle, direction){ startAngle = util.deg2rad(startAngle); endAngle = util.deg2rad(endAngle); util.setLastPoint(new util.Vector(centerPoint.x + Math.cos(endAngle) * radius, centerPoint.y + Math.sin(endAngle) * radius)); return new util.Shape(function(ctx){ if (!util.isDrawingPath()){ ctx.beginPath(); } ctx.arc(centerPoint.x, centerPoint.y, radius, startAngle, endAngle, false); }); }, bezierCurve: function(startPoint, toPoint, controlPoint1, controlPoint2){ util.setLastPoint(toPoint); var path = new util.Path( getContext().bezierCurveTo, new Array(controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y, toPoint.x, toPoint.y), startPoint ); return path; }, quadraticCurve: function(startPoint, toPoint, controlPoint){ util.setLastPoint(toPoint); var path = new util.Path( getContext().quadraticCurveTo, new Array( controlPoint.x, controlPoint.y, toPoint.x, toPoint.y), startPoint ); return path; }, withClip: function withClipCtx(shape){ getContext().save(); shape.draw(getContext()); getContext().clip(); this.gatherSteps().forEach(runBlock); getContext().restore(); }, path: function(){ var args = [].slice.call(arguments); return new util.Shape(args); }, lastPoint: function(){ return util.lastPoint(); } >>>>>>> triangle: function(p1, p2, p3){ return new util.Shape(function(ctx){ ctx.beginPath(); ctx.moveTo(p1.x, p1.y); ctx.lineTo(p2.x, p2.y); ctx.lineTo(p3.x, p3.y); ctx.lineTo(p1.x, p1.y); }); }, polygon: function(args){ var points = [].slice.call(arguments); util.setLastPoint(points[0]); return new util.Shape(function(ctx){ if (!util.isDrawingPath()){ ctx.beginPath(); } var points = this.pointsArray; for(var i=0; i < points.length; i++) { if (i === 0 && !util.isDrawingPath()) { ctx.moveTo(points[i].x, points[i].y); } else { ctx.lineTo(points[i].x, points[i].y); } if(i === points.length-1) { ctx.lineTo(points[0].x, points[0].y); } } }, points); }, lineTo: function(startPoint, toPoint){ util.setLastPoint(toPoint); return new util.Path(getContext().lineTo, new Array(toPoint.x, toPoint.y), startPoint); }, arc: function(radius, centerPoint, startAngle, endAngle, direction){ startAngle = util.deg2rad(startAngle); endAngle = util.deg2rad(endAngle); util.setLastPoint(new util.Vector(centerPoint.x + Math.cos(endAngle) * radius, centerPoint.y + Math.sin(endAngle) * radius)); return new util.Shape(function(ctx){ if (!util.isDrawingPath()){ ctx.beginPath(); } ctx.arc(centerPoint.x, centerPoint.y, radius, startAngle, endAngle, false); }); }, bezierCurve: function(startPoint, toPoint, controlPoint1, controlPoint2){ util.setLastPoint(toPoint); var path = new util.Path( getContext().bezierCurveTo, new Array(controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y, toPoint.x, toPoint.y), startPoint ); return path; }, quadraticCurve: function(startPoint, toPoint, controlPoint){ util.setLastPoint(toPoint); var path = new util.Path( getContext().quadraticCurveTo, new Array( controlPoint.x, controlPoint.y, toPoint.x, toPoint.y), startPoint ); return path; }, withClip: function withClipCtx(shape){ getContext().save(); shape.draw(getContext()); getContext().clip(); this.gatherSteps().forEach(runBlock); getContext().restore(); }, path: function(){ var args = [].slice.call(arguments); return new util.Shape(args); }, lastPoint: function(){ return util.lastPoint(); }
<<<<<<< } function checkBoundingVolume(innerBoundingVolume, outerBoundingVolume, innerTransform, outerTransform) { var message; var transformedInnerTile; var transformedOuterTile; if (defined(innerBoundingVolume.box) && defined(outerBoundingVolume.box)) { // Box in Box check transformedInnerTile = getTransformedBox(innerBoundingVolume.box, innerTransform); transformedOuterTile = getTransformedBox(outerBoundingVolume.box, outerTransform); if (!boxInsideBox(transformedInnerTile, transformedOuterTile)) { message = 'box [' + innerBoundingVolume.box + '] is not within box [' + outerBoundingVolume.box + ']'; } return message; } else if (defined(innerBoundingVolume.sphere) && defined(outerBoundingVolume.sphere)) { // Sphere in Sphere transformedInnerTile = getTransformedSphere(innerBoundingVolume.sphere, innerTransform); transformedOuterTile = getTransformedSphere(outerBoundingVolume.sphere, outerTransform); if (!sphereInsideSphere(transformedInnerTile, transformedOuterTile)) { message = 'sphere [' + innerBoundingVolume.sphere + '] is not within sphere [' + outerBoundingVolume.sphere + ']'; return message; } return message } else if (defined(innerBoundingVolume.region)&& defined(outerBoundingVolume.region)) { // Region in Region // Region does not update with transform transformedInnerTile = innerBoundingVolume.region; transformedOuterTile = outerBoundingVolume.region; if (!regionInsideRegion(transformedInnerTile, transformedOuterTile)) { message = 'region [' + innerBoundingVolume.region + '] is not within region [' + outerBoundingVolume.region + ']'; return message; } return message; } else if (defined(innerBoundingVolume.box) && defined(outerBoundingVolume.sphere)) { // Box in Sphere transformedInnerTile = getTransformedBox(innerBoundingVolume.box, innerTransform); transformedOuterTile = getTransformedSphere(outerBoundingVolume.sphere, outerTransform); if (!boxInsideSphere(transformedInnerTile, transformedOuterTile)) { message = 'box [' + innerBoundingVolume.box + '] is not within sphere [' + outerBoundingVolume.sphere + ']'; return message; } return message; } else if (defined(innerBoundingVolume.sphere) && defined(outerBoundingVolume.box)) { // Sphere in Box transformedInnerTile = getTransformedSphere(innerBoundingVolume.sphere, innerTransform); transformedOuterTile = getTransformedBox(outerBoundingVolume.box, outerTransform); if (!sphereInsideBox(transformedInnerTile, transformedOuterTile)) { message = 'sphere [' + innerBoundingVolume.sphere + '] is not within box [' + outerBoundingVolume.box + ']'; return message; } return message; } } var scratchMatrix = new Matrix3(); var scratchHalfAxes = new Matrix3(); var scratchCenter = new Cartesian3(); var scratchScale = new Cartesian3(); function getTransformedBox(box, transform) { var center = Cartesian3.fromElements(box[0], box[1], box[2], scratchCenter); var halfAxes = Matrix3.fromArray(box, 3, scratchHalfAxes); // Find the transformed center and halfAxes center = Matrix4.multiplyByPoint(transform, center, center); var rotationScale = Matrix4.getRotation(transform, scratchMatrix); halfAxes = Matrix3.multiply(rotationScale, halfAxes, halfAxes); // Return a Box array var returnBox = [center.x, center.y, center.z, halfAxes[0], halfAxes[3], halfAxes[6], halfAxes[1], halfAxes[4], halfAxes[7], halfAxes[2], halfAxes[5], halfAxes[8]]; return returnBox; } function getTransformedSphere(sphere, transform) { var center = Cartesian3.fromElements(sphere[0], sphere[1], sphere[2], scratchCenter); var radius = sphere[3]; // Find the transformed center and radius center = Matrix4.multiplyByPoint(transform, center, center); var scale = Matrix4.getScale(transform, scratchScale); var uniformScale = Cartesian3.maximumComponent(scale); radius *= uniformScale; // Return a Sphere array var returnSphere = [center.x, center.y, center.z, radius]; return returnSphere; ======= } function errorMessage(originalMessage, tile) { delete tile.children; var stringJson = JSON.stringify(tile, undefined, 4); var newMessage = originalMessage + ' \n ' + stringJson; return newMessage; >>>>>>> } function checkBoundingVolume(innerBoundingVolume, outerBoundingVolume, innerTransform, outerTransform) { var message; var transformedInnerTile; var transformedOuterTile; if (defined(innerBoundingVolume.box) && defined(outerBoundingVolume.box)) { // Box in Box check transformedInnerTile = getTransformedBox(innerBoundingVolume.box, innerTransform); transformedOuterTile = getTransformedBox(outerBoundingVolume.box, outerTransform); if (!boxInsideBox(transformedInnerTile, transformedOuterTile)) { message = 'box [' + innerBoundingVolume.box + '] is not within box [' + outerBoundingVolume.box + ']'; } return message; } else if (defined(innerBoundingVolume.sphere) && defined(outerBoundingVolume.sphere)) { // Sphere in Sphere transformedInnerTile = getTransformedSphere(innerBoundingVolume.sphere, innerTransform); transformedOuterTile = getTransformedSphere(outerBoundingVolume.sphere, outerTransform); if (!sphereInsideSphere(transformedInnerTile, transformedOuterTile)) { message = 'sphere [' + innerBoundingVolume.sphere + '] is not within sphere [' + outerBoundingVolume.sphere + ']'; return message; } return message } else if (defined(innerBoundingVolume.region)&& defined(outerBoundingVolume.region)) { // Region in Region // Region does not update with transform transformedInnerTile = innerBoundingVolume.region; transformedOuterTile = outerBoundingVolume.region; if (!regionInsideRegion(transformedInnerTile, transformedOuterTile)) { message = 'region [' + innerBoundingVolume.region + '] is not within region [' + outerBoundingVolume.region + ']'; return message; } return message; } else if (defined(innerBoundingVolume.box) && defined(outerBoundingVolume.sphere)) { // Box in Sphere transformedInnerTile = getTransformedBox(innerBoundingVolume.box, innerTransform); transformedOuterTile = getTransformedSphere(outerBoundingVolume.sphere, outerTransform); if (!boxInsideSphere(transformedInnerTile, transformedOuterTile)) { message = 'box [' + innerBoundingVolume.box + '] is not within sphere [' + outerBoundingVolume.sphere + ']'; return message; } return message; } else if (defined(innerBoundingVolume.sphere) && defined(outerBoundingVolume.box)) { // Sphere in Box transformedInnerTile = getTransformedSphere(innerBoundingVolume.sphere, innerTransform); transformedOuterTile = getTransformedBox(outerBoundingVolume.box, outerTransform); if (!sphereInsideBox(transformedInnerTile, transformedOuterTile)) { message = 'sphere [' + innerBoundingVolume.sphere + '] is not within box [' + outerBoundingVolume.box + ']'; return message; } return message; } } var scratchMatrix = new Matrix3(); var scratchHalfAxes = new Matrix3(); var scratchCenter = new Cartesian3(); var scratchScale = new Cartesian3(); function getTransformedBox(box, transform) { var center = Cartesian3.fromElements(box[0], box[1], box[2], scratchCenter); var halfAxes = Matrix3.fromArray(box, 3, scratchHalfAxes); // Find the transformed center and halfAxes center = Matrix4.multiplyByPoint(transform, center, center); var rotationScale = Matrix4.getRotation(transform, scratchMatrix); halfAxes = Matrix3.multiply(rotationScale, halfAxes, halfAxes); // Return a Box array var returnBox = [center.x, center.y, center.z, halfAxes[0], halfAxes[3], halfAxes[6], halfAxes[1], halfAxes[4], halfAxes[7], halfAxes[2], halfAxes[5], halfAxes[8]]; return returnBox; } function getTransformedSphere(sphere, transform) { var center = Cartesian3.fromElements(sphere[0], sphere[1], sphere[2], scratchCenter); var radius = sphere[3]; // Find the transformed center and radius center = Matrix4.multiplyByPoint(transform, center, center); var scale = Matrix4.getScale(transform, scratchScale); var uniformScale = Cartesian3.maximumComponent(scale); radius *= uniformScale; // Return a Sphere array var returnSphere = [center.x, center.y, center.z, radius]; return returnSphere; } function errorMessage(originalMessage, tile) { delete tile.children; var stringJson = JSON.stringify(tile, undefined, 4); var newMessage = originalMessage + ' \n ' + stringJson; return newMessage;
<<<<<<< var boxInsideBox = utility.boxInsideBox; ======= var boxInsideSphere = utility.boxInsideSphere; >>>>>>> var boxInsideBox = utility.boxInsideBox; var boxInsideSphere = utility.boxInsideSphere; <<<<<<< var contentBox = content.boundingVolume.box; ======= var contentBox = content.boundingVolume.box; >>>>>>> var contentBox = content.boundingVolume.box; <<<<<<< if (defined(contentBox) && defined(tileBox) && !boxInsideBox(contentBox, tileBox)) { return 'content box [' + contentBox + '] is not within tile box [' + tileBox + ']'; } ======= if (defined(contentBox) && defined(tileSphere) && !boxInsideSphere(contentBox, tileSphere)) { return 'content box [' + contentBox + '] is not within tile sphere [' + tileSphere + ']'; } >>>>>>> if (defined(contentBox) && defined(tileBox) && !boxInsideBox(contentBox, tileBox)) { return 'content box [' + contentBox + '] is not within tile box [' + tileBox + ']'; } if (defined(contentBox) && defined(tileSphere) && !boxInsideSphere(contentBox, tileSphere)) { return 'content box [' + contentBox + '] is not within tile sphere [' + tileSphere + ']'; }
<<<<<<< var gltfUpAxis = tileset.asset.gltfUpAxis; if (defined(gltfUpAxis)) { if (gltfUpAxis !== 'X' && gltfUpAxis !== 'Y' && gltfUpAxis !== 'Z') { return 'gltfUpAxis should either be "X", "Y", or "Z".'; } } ======= if (!defined(tileset.asset)) { return 'Tileset must declare its asset as a top-level property.'; } if (!defined(tileset.asset.version)) { return 'Tileset must declare a version in its asset property'; } if (tileset.asset.version !== '1.0') { return 'Tileset version must be 1.0. Tileset version provided: ' + tileset.asset.version; } >>>>>>> var gltfUpAxis = tileset.asset.gltfUpAxis; if (defined(gltfUpAxis)) { if (gltfUpAxis !== 'X' && gltfUpAxis !== 'Y' && gltfUpAxis !== 'Z') { return 'gltfUpAxis should either be "X", "Y", or "Z".'; } } if (!defined(tileset.asset)) { return 'Tileset must declare its asset as a top-level property.'; } if (!defined(tileset.asset.version)) { return 'Tileset must declare a version in its asset property'; } if (tileset.asset.version !== '1.0') { return 'Tileset version must be 1.0. Tileset version provided: ' + tileset.asset.version; }
<<<<<<< * @param {Array} [options.extensionsUsed] An array containing names of extensions used in the tileset. * @param {Array} [options.extensionsRequired] An array containing names of extensions required by the tileset. * @param {String} [options.gltfUpAxis] Specifies the up-axis of embedded glTF models. ======= >>>>>>> * @param {Array} [options.extensionsUsed] An array containing names of extensions used in the tileset. * @param {Array} [options.extensionsRequired] An array containing names of extensions required by the tileset.
<<<<<<< var extractI3dm = require('../lib/extractI3dm'); ======= var fileExists = require('../lib/fileExists'); >>>>>>> var extractI3dm = require('../lib/extractI3dm'); var fileExists = require('../lib/fileExists'); <<<<<<< } else if (command === 'i3dmToGlb') { // i3dmToGlb is not a pipeline tool, so handle it separately. readI3dmWriteGlb(input, output, force); ======= } else if (command === 'tileset2sqlite3') { // tileset2sqlite3 is not a pipeline tool, so handle it separately. tileset2sqlite3(input, output, force); >>>>>>> } else if (command === 'i3dmToGlb') { // i3dmToGlb is not a pipeline tool, so handle it separately. readI3dmWriteGlb(input, output, force); } else if (command === 'tileset2sqlite3') { // tileset2sqlite3 is not a pipeline tool, so handle it separately. tileset2sqlite3(input, output, force);
<<<<<<< export default '1.1.2'; ======= module.exports = '1.1.3'; >>>>>>> export default '1.1.3';
<<<<<<< import { LOCALE_DATE_OPTIONS, ROUTES } from '../constants'; import { HeartIcon, StrengthIcon } from '../components/SvgIcons'; import CreateLinkIcon from '../components/CreateLinkIcon'; ======= import { ROUTES } from '../constants'; import ExerciseEntry from '../components/ExerciseEntry'; import { CreateIcon } from '../components/SvgIcons'; >>>>>>> import { ROUTES } from '../constants'; import ExerciseEntry from '../components/ExerciseEntry'; import CreateLinkIcon from '../components/CreateLinkIcon';
<<<<<<< var value = cell.value if (value === '?') { value = 'OTHER' } return value + '<br/>' + (cell.stats['volume_difference'] * 100).toFixed(2) + '%' ======= var vd = (cell.stats['volume_difference'] * 100).toFixed(2) + '%' var cd = (cell.stats['contribution_difference'] * 100).toFixed(2) + '%' var cellContent = cell.value + '<br/>' + vd if (cell.stats['contribution_difference'] > 0) { cellContent += ' <span class="cell-down">(&#916;' + cd + ')</span>' } else { cellContent += ' <span class="cell-up">(&#916;' + cd + ')</span>' } return cellContent >>>>>>> var value = cell.value if (value === '?') { value = 'OTHER' } var vd = (cell.stats['volume_difference'] * 100).toFixed(2) + '%' var cd = (cell.stats['contribution_difference'] * 100).toFixed(2) + '%' var cellContent = value + '<br/>' + vd if (cell.stats['contribution_difference'] > 0) { cellContent += ' <span class="cell-down">(&#916;' + cd + ')</span>' } else { cellContent += ' <span class="cell-up">(&#916;' + cd + ')</span>' } return cellContent <<<<<<< return 0 } }, display: function(cell) { var value = cell.value if (value === '?') { value = 'OTHER' } return value + '<br/>' + (cell.stats['contribution_difference'] * 100).toFixed(2) + '%' }, backgroundColor: function(cell) { if (cell.stats['contribution_difference'] < 0) { return 'rgba(252, 136, 138, ' + (cell.stats['current_cdf_value']) + ')' } else { return 'rgba(138, 252, 136, ' + (cell.stats['current_cdf_value']) + ')' ======= return 'rgba(252, 136, 138, ' + cell.stats['baseline_cdf_value'].toFixed(3) + ')' >>>>>>> return 'rgba(252, 136, 138, ' + cell.stats['baseline_cdf_value'].toFixed(3) + ')'
<<<<<<< const {width} = Dimensions.get('window'); ======= >>>>>>> const {width} = Dimensions.get('window'); <<<<<<< scrollsToTop: PropTypes.bool, // Enable or disable paging on scroll pagingEnabled: PropTypes.bool, // Used when calendar scroll is horizontal, default is device width, pagination should be disabled calendarWidth: PropTypes.number, // Whether the scroll is horizontal horizontal: PropTypes.bool, ======= scrollsToTop: PropTypes.bool, // Dynamic calendar height calendarHeight: PropTypes.number, >>>>>>> scrollsToTop: PropTypes.bool, // Enable or disable paging on scroll pagingEnabled: PropTypes.bool, // Used when calendar scroll is horizontal, default is device width, pagination should be disabled calendarWidth: PropTypes.number, // Whether the scroll is horizontal horizontal: PropTypes.bool, // Dynamic calendar height calendarHeight: PropTypes.number, <<<<<<< this.calendarWidth = this.props.calendarWidth || width; ======= this.calendarHeight = props.calendarHeight || calendarHeight; >>>>>>> this.calendarWidth = this.props.calendarWidth || width; this.calendarHeight = props.calendarHeight || calendarHeight; <<<<<<< return (<CalendarListItem item={item} calendarHeight={calendarHeight} calendarWidth={this.props.horizontal && this.props.pagingEnabled ? this.calendarWidth : undefined } {...this.props} />); ======= return (<CalendarListItem item={item} calendarHeight={this.calendarHeight} {...this.props} />); >>>>>>> return (<CalendarListItem item={item} calendarHeight={this.calendarHeight} calendarWidth={this.props.horizontal && this.props.pagingEnabled ? this.calendarWidth : undefined } {...this.props} />); <<<<<<< return {length: this.props.horizontal ? this.props.calendarWidth || this.calendarWidth : calendarHeight, offset: (this.props.horizontal ? this.props.calendarWidth || this.calendarWidth : calendarHeight) * index, index}; ======= return {length: this.calendarHeight, offset: this.calendarHeight * index, index}; >>>>>>> return {length: this.props.horizontal ? this.props.calendarWidth || this.calendarWidth : this.calendarHeight, offset: (this.props.horizontal ? this.props.calendarWidth || this.calendarWidth : calendarHeight) * index, index};
<<<<<<< day: PropTypes.object, markingExists: PropTypes.bool, dotTypes: PropTypes.object ======= day: PropTypes.object >>>>>>> day: PropTypes.object, dotTypes: PropTypes.object <<<<<<< dot = this.renderDots(marked); } else if (!this.props.markingExists) { textStyle.push(this.style.alignedText); ======= dotStyle.push(this.style.visibleDot); dot = (<View style={dotStyle}/>); >>>>>>> dot = this.renderDots(marked);
<<<<<<< shape: { fill: function(shapeArg){ console.log(shapeArg); shapeArg.draw(ctx()); ctx().fill(); }, stroke: function(shapeArg){ shapeArg.draw(ctx()); ctx().stroke(); }, circle: function(pt, rad){ ctx().beginPath(); ctx().arc(pt.x, pt.y, rad, 0, Math.PI * 2, true); }, rectangle: function(pt, width, height, orientation){ ctx().beginPath(); if(orientation == "center"){ ctx().moveTo(pt.x - width/2, pt.y - height/2); ctx().lineTo(pt.x + width/2, pt.y - height/2); ctx().lineTo(pt.x + width/2, pt.y + height/2); ctx().lineTo(pt.x - width/2, pt.y + height/2); ctx().lineTo(pt.x - width/2, pt.y - height/2); } else{ ctx().lineTo(pt.x + width, pt.y); ctx().lineTo(pt.x + width, pt.y + height); ctx().lineTo(pt.x, pt.y + height); ctx().lineTo(pt.x, pt.y); } }, ellipse: function(pt, rad1, rad2, rot){ ctx().beginPath(); ctx().ellipse(pt.x, pt.y, rad1, rad2, rot, 0, Math.PI * 2); }, }, ======= >>>>>>> shape: { fill: function(shapeArg){ console.log(shapeArg); shapeArg.draw(ctx()); ctx().fill(); }, stroke: function(shapeArg){ shapeArg.draw(ctx()); ctx().stroke(); }, circle: function(pt, rad){ ctx().beginPath(); ctx().arc(pt.x, pt.y, rad, 0, Math.PI * 2, true); }, rectangle: function(pt, width, height, orientation){ ctx().beginPath(); if(orientation == "center"){ ctx().moveTo(pt.x - width/2, pt.y - height/2); ctx().lineTo(pt.x + width/2, pt.y - height/2); ctx().lineTo(pt.x + width/2, pt.y + height/2); ctx().lineTo(pt.x - width/2, pt.y + height/2); ctx().lineTo(pt.x - width/2, pt.y - height/2); } else{ ctx().lineTo(pt.x + width, pt.y); ctx().lineTo(pt.x + width, pt.y + height); ctx().lineTo(pt.x, pt.y + height); ctx().lineTo(pt.x, pt.y); } }, ellipse: function(pt, rad1, rad2, rot){ ctx().beginPath(); ctx().ellipse(pt.x, pt.y, rad1, rad2, rot, 0, Math.PI * 2); }, },
<<<<<<< // Should Keyboard persist taps keyboardShouldPersistTaps: PropTypes.oneOf(['never', 'always', 'handled']) }; ======= /** Style for the List item (the calendar) */ calendarStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.number, PropTypes.array]), /** Whether to use static header that will not scroll with the list (horizontal only) */ staticHeader: PropTypes.bool, /** A custom key extractor for the generated calendar months */ keyExtractor: PropTypes.func } >>>>>>> // Should Keyboard persist taps keyboardShouldPersistTaps: PropTypes.oneOf(['never', 'always', 'handled']) }; /** Style for the List item (the calendar) */ calendarStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.number, PropTypes.array]), /** Whether to use static header that will not scroll with the list (horizontal only) */ staticHeader: PropTypes.bool, /** A custom key extractor for the generated calendar months */ keyExtractor: PropTypes.func } <<<<<<< keyboardShouldPersistTaps: 'never' ======= keyExtractor: (item, index) => String(index) >>>>>>> keyboardShouldPersistTaps: 'never' keyExtractor: (item, index) => String(index) <<<<<<< <FlatList onLayout={this.onLayout} ref={(c) => this.listView = c} //scrollEventThrottle={1000} style={[this.style.container, this.props.style]} initialListSize={this.pastScrollRange + this.futureScrollRange + 1} data={this.state.rows} //snapToAlignment='start' //snapToInterval={this.calendarHeight} removeClippedSubviews={this.props.removeClippedSubviews} pageSize={1} horizontal={this.props.horizontal} pagingEnabled={this.props.pagingEnabled} onViewableItemsChanged={this.onViewableItemsChangedBound} renderItem={this.renderCalendarBound} showsVerticalScrollIndicator={this.props.showScrollIndicator} showsHorizontalScrollIndicator={this.props.showScrollIndicator} scrollEnabled={this.props.scrollingEnabled} keyExtractor={(item, index) => String(index)} initialScrollIndex={this.state.openDate ? this.getMonthIndex(this.state.openDate) : false} getItemLayout={this.getItemLayout} scrollsToTop={this.props.scrollsToTop} keyboardShouldPersistTaps={this.props.keyboardShouldPersistTaps} /> ======= <View> <FlatList onLayout={this.onLayout} ref={(c) => this.listView = c} //scrollEventThrottle={1000} style={[this.style.container, this.props.style]} initialListSize={this.props.pastScrollRange + this.props.futureScrollRange + 1} // ListView deprecated data={this.state.rows} //snapToAlignment='start' //snapToInterval={this.calendarHeight} removeClippedSubviews={this.props.removeClippedSubviews} pageSize={1} // ListView deprecated horizontal={this.props.horizontal} pagingEnabled={this.props.pagingEnabled} onViewableItemsChanged={this.onViewableItemsChangedBound} viewabilityConfig={this.viewabilityConfig} renderItem={this.renderCalendarBound} showsVerticalScrollIndicator={this.props.showScrollIndicator} showsHorizontalScrollIndicator={this.props.showScrollIndicator} scrollEnabled={this.props.scrollEnabled} keyExtractor={this.props.keyExtractor} initialScrollIndex={this.state.openDate ? this.getMonthIndex(this.state.openDate) : false} getItemLayout={this.getItemLayout} scrollsToTop={this.props.scrollsToTop} onEndReachedThreshold={this.props.onEndReachedThreshold} onEndReached={this.props.onEndReached} /> {this.renderStaticHeader()} </View> >>>>>>> <View> <FlatList onLayout={this.onLayout} ref={(c) => this.listView = c} //scrollEventThrottle={1000} style={[this.style.container, this.props.style]} initialListSize={this.props.pastScrollRange + this.props.futureScrollRange + 1} // ListView deprecated data={this.state.rows} //snapToAlignment='start' //snapToInterval={this.calendarHeight} removeClippedSubviews={this.props.removeClippedSubviews} pageSize={1} // ListView deprecated horizontal={this.props.horizontal} pagingEnabled={this.props.pagingEnabled} onViewableItemsChanged={this.onViewableItemsChangedBound} viewabilityConfig={this.viewabilityConfig} renderItem={this.renderCalendarBound} showsVerticalScrollIndicator={this.props.showScrollIndicator} showsHorizontalScrollIndicator={this.props.showScrollIndicator} scrollEnabled={this.props.scrollEnabled} keyExtractor={this.props.keyExtractor} initialScrollIndex={this.state.openDate ? this.getMonthIndex(this.state.openDate) : false} getItemLayout={this.getItemLayout} scrollsToTop={this.props.scrollsToTop} onEndReachedThreshold={this.props.onEndReachedThreshold} onEndReached={this.props.onEndReached} keyboardShouldPersistTaps={this.props.keyboardShouldPersistTaps} /> {this.renderStaticHeader()} </View>
<<<<<<< }else if(dom.matches(dragTarget, 'wb-context, wb-step')){ ======= deleteOriginalBlock(originalBlock, originalParent, nextElem); }else if(dragTarget.matches('wb-context, wb-step')){ >>>>>>> deleteOriginalBlock(originalBlock, originalParent, nextElem); }else if(dom.matches(dragTarget, 'wb-context, wb-step')){
<<<<<<< /** * Recursively walks AST and extracts ES5 React component names, child components, props and state * @returns {Object} Nested object containing name, children, props and state properties of components */ function getES5ReactComponents() { ======= function getES5ReactComponents(ast) { >>>>>>> /** * Recursively walks AST and extracts ES5 React component names, child components, props and state * @returns {Object} Nested object containing name, children, props and state properties of components */ function getES5ReactComponents(ast) { <<<<<<< /** * Recursively walks AST and extracts ES6 React component names, child components, props and state * @returns {Object} Nested object containing name, children, props and state properties of components */ function getES6ReactComponents() { ======= function getES6ReactComponents(ast) { >>>>>>> /** * Recursively walks AST and extracts ES6 React component names, child components, props and state * @returns {Object} Nested object containing name, children, props and state properties of components */ function getES6ReactComponents(ast) {
<<<<<<< //If we've defined a validator, run it if (def.validator) { var err = def.validator(newVal, newType); if (err) { throw new TypeError('Property \'' + attr + '\' failed validation with error: ' + err); } } // If we have a defined type and the new type doesn't match, throw error. // Unless it's not required and the value is undefined. if (def.type && def.type !== 'any' && def.type !== newType && (!def.required && !_.isUndefined(newVal))) { ======= // If we are required but undefined, throw error. // If we are null and are not allowing null, throw error // If we have a defined type and the new type doesn't match, and we are not null, throw error. if (_.isUndefined(newVal) && def.required) { throw new TypeError('Required property \'' + attr + '\' must be of type ' + def.type + '. Tried to set ' + newVal); } if (_.isNull(newVal) && def.required && !def.allowNull) { throw new TypeError('Property \'' + attr + '\' must be of type ' + def.type + ' (cannot be null). Tried to set ' + newVal); } if ((def.type && def.type !== 'any' && def.type !== newType) && !_.isNull(newVal) && !_.isUndefined(newVal)) { >>>>>>> //If we've defined a validator, run it if (def.validator) { var err = def.validator(newVal, newType); if (err) { throw new TypeError('Property \'' + attr + '\' failed validation with error: ' + err); } } // If we are required but undefined, throw error. // If we are null and are not allowing null, throw error // If we have a defined type and the new type doesn't match, and we are not null, throw error. if (_.isUndefined(newVal) && def.required) { throw new TypeError('Required property \'' + attr + '\' must be of type ' + def.type + '. Tried to set ' + newVal); } if (_.isNull(newVal) && def.required && !def.allowNull) { throw new TypeError('Property \'' + attr + '\' must be of type ' + def.type + ' (cannot be null). Tried to set ' + newVal); } if ((def.type && def.type !== 'any' && def.type !== newType) && !_.isNull(newVal) && !_.isUndefined(newVal)) {
<<<<<<< myBool: ['boolean', true, false], good: { type: 'string', validator: function (newVal) { if (newVal !== 'good') { return "Value not good"; } } } ======= myBool: ['boolean', true, false], someNumber: {type: 'number', allowNull: true} >>>>>>> someNumber: {type: 'number', allowNull: true}, good: { type: 'string', validator: function (newVal) { if (newVal !== 'good') { return "Value not good"; } } } <<<<<<< test('Attribute validation works', 2, function () { var foo = new Foo({good: 'good'}); equal(foo.good, 'good'); throws(function () { foo.good = 'bad'; }, TypeError, 'Throws exception on invalid attribute value'); }); ======= test('Should only allow nulls where specified', 2, function () { var foo = new Foo({ firstName: 'bob', lastName: 'vila', someNumber: null }); equal(foo.someNumber, null); throws(function () { foo.firstName = null; }, TypeError, 'Throws exception when setting unallowed null'); }); >>>>>>> test('Attribute validation works', 2, function () { var foo = new Foo({good: 'good'}); equal(foo.good, 'good'); throws(function () { foo.good = 'bad'; }, TypeError, 'Throws exception on invalid attribute value'); }); test('Should only allow nulls where specified', 2, function () { var foo = new Foo({ firstName: 'bob', lastName: 'vila', someNumber: null }); equal(foo.someNumber, null); throws(function () { foo.firstName = null; }, TypeError, 'Throws exception when setting unallowed null'); });
<<<<<<< it('overwrite doc with update validators (gh-3556)', function(done) { var testSchema = new Schema({ name: { type: String, required: true }, otherName: String }); var Test = db.model('gh3556', testSchema); var opts = { overwrite: true, runValidators: true }; Test.update({}, { otherName: 'test' }, opts, function(error) { assert.ok(error); assert.ok(error.errors['name']); Test.update({}, { $set: { otherName: 'test' } }, opts, function(error) { assert.ifError(error); done(); }); }); }); ======= it('does not fail if passing whole doc (gh-5088)', function(done) { var schema = new Schema({ username: String, x: String }, { timestamps: true }); var User = db.model('gh5088', schema); User.create({ username: 'test' }). then(function(user) { user.x = 'test2'; return User.findOneAndUpdate({ _id: user._id }, user, { new: true }); }). then(function(user) { assert.equal(user.x, 'test2'); done(); }). catch(done); }); it('does not fail if passing whole doc (gh-5111)', function(done) { var schema = new Schema({ fieldOne: String }, { strict: true }); var Test = db.model('gh5111', schema); Test.create({ fieldOne: 'Test' }). then(function() { var data = { fieldOne: 'Test2', fieldTwo: 'Test3' }; var opts = { upsert: true, runValidators: false, strict: false }; return Test.update({}, data, opts); }). then(function() { return Test.findOne(); }). then(function(doc) { assert.equal(doc.fieldOne, 'Test2'); assert.equal(doc.get('fieldTwo'), 'Test3'); done(); }). catch(done); }); it('$pullAll with null (gh-5164)', function(done) { var schema = new Schema({ name: String, arr: [{ name: String }] }, { strict: true }); var Test = db.model('gh5164', schema); var doc = new Test({ name: 'Test', arr: [null, {name: 'abc'}] }); doc.save(). then(function(doc) { return Test.update({ _id: doc._id }, { $pullAll: { arr: [null] } }); }). then(function() { return Test.findById(doc); }). then(function(doc) { assert.equal(doc.arr.length, 1); assert.equal(doc.arr[0].name, 'abc'); done(); }). catch(done); }); >>>>>>> it('overwrite doc with update validators (gh-3556)', function(done) { var testSchema = new Schema({ name: { type: String, required: true }, otherName: String }); var Test = db.model('gh3556', testSchema); var opts = { overwrite: true, runValidators: true }; Test.update({}, { otherName: 'test' }, opts, function(error) { assert.ok(error); assert.ok(error.errors['name']); Test.update({}, { $set: { otherName: 'test' } }, opts, function(error) { assert.ifError(error); done(); }); }); }); it('does not fail if passing whole doc (gh-5088)', function(done) { var schema = new Schema({ username: String, x: String }, { timestamps: true }); var User = db.model('gh5088', schema); User.create({ username: 'test' }). then(function(user) { user.x = 'test2'; return User.findOneAndUpdate({ _id: user._id }, user, { new: true }); }). then(function(user) { assert.equal(user.x, 'test2'); done(); }). catch(done); }); it('does not fail if passing whole doc (gh-5111)', function(done) { var schema = new Schema({ fieldOne: String }, { strict: true }); var Test = db.model('gh5111', schema); Test.create({ fieldOne: 'Test' }). then(function() { var data = { fieldOne: 'Test2', fieldTwo: 'Test3' }; var opts = { upsert: true, runValidators: false, strict: false }; return Test.update({}, data, opts); }). then(function() { return Test.findOne(); }). then(function(doc) { assert.equal(doc.fieldOne, 'Test2'); assert.equal(doc.get('fieldTwo'), 'Test3'); done(); }). catch(done); }); it('$pullAll with null (gh-5164)', function(done) { var schema = new Schema({ name: String, arr: [{ name: String }] }, { strict: true }); var Test = db.model('gh5164', schema); var doc = new Test({ name: 'Test', arr: [null, {name: 'abc'}] }); doc.save(). then(function(doc) { return Test.update({ _id: doc._id }, { $pullAll: { arr: [null] } }); }). then(function() { return Test.findById(doc); }). then(function(doc) { assert.equal(doc.arr.length, 1); assert.equal(doc.arr[0].name, 'abc'); done(); }). catch(done); });
<<<<<<< if (i === len-1) ref[piece] = type.initValue(self); ======= if (!ref) ref = doc; if (i === len-1) ref[piece] = type.getDefault(self); >>>>>>> if (i === len-1) ref[piece] = type.getDefault(self); <<<<<<< * Apply defaults middleware * * @param {Function} next * @api private */ Document.prototype.applyDefaults = function (next) { if (this.isNew){ var total = 0 , self = this; if (! Object.keys(this.initPaths).length) return next(); for (var i in this.initPaths){ if (!(i in this.modifiedPaths)){ if (this.schema.get(i) instanceof DocumentArraySchema){ total++; (function(i){ process.nextTick(function () { self.get(i).applyDefaults(function () { --total || next(); }); }); })(i); } else { var def = this.schema.get(i)._default; if (typeof def == 'function') { if (def.length > 0){ total++; process.nextTick(function () { def.call(this, function () { --total || next(); }); }); } else { this.set(i, this.schema.get(i)._default(), true, false); } } else { this.set(i, this.schema.get(i)._default, true, false); } } } } } else { next(); } }; /** ======= >>>>>>> <<<<<<< // apply defaults this.pre('save', function (next) { return self.applyDefaults.call(self, next); }); ======= >>>>>>>
<<<<<<< if (typeof path != 'string'){ var prefix = val ? val + '.' : ''; for (var i in path){ if (path[i].constructor == Object) this.set(path[i], prefix + i + '.'); else this.set(prefix + i, path[i]); } } else { // TODO: do actual checking to see if the value changed this.modifiedPaths[path] = true; var schema = this.schema.path(path) , parts = path.split('.') , obj = this.doc , self = this; if ( (!schema || val === null || val === undefined) || this.try(function(){ val = schema.applySetters(schema.cast(val, self), self); }) ){ for (var i = 0, l = parts.length; i < l; i++){ if (i + 1 == l) obj[parts[i]] = val; else obj = obj[parts[i]]; } } } ======= if (this.getValue(path) !== val) this._markModified(path); var schema = this.schema.path(path) , parts = path.split('.') , obj = this.doc , self = this; this.try(function(){ val = schema.cast(val, self); }); for (var i = 0, l = parts.length; i < l-1; i++) obj = obj[parts[i]]; obj[parts[l-1]] = val; >>>>>>> if (typeof path != 'string'){ var prefix = val ? val + '.' : ''; for (var i in path){ if (path[i].constructor == Object) this.set(path[i], prefix + i + '.'); else this.set(prefix + i, path[i]); } } else { // TODO: do actual checking to see if the value changed this.modifiedPaths[path] = true; var schema = this.schema.path(path) , parts = path.split('.') , obj = this.doc , self = this; if ( (!schema || val === null || val === undefined) || this.try(function(){ val = schema.applySetters(schema.cast(val, self), self); }) ){ for (var i = 0, l = parts.length; i < l; i++){ if (i + 1 == l) obj[parts[i]] = val; else obj = obj[parts[i]]; } } } <<<<<<< fn.call(scope); return true; ======= res = fn.call(scope); >>>>>>> fn.call(scope); res = true;
<<<<<<< it('supports getting a list of populated docs (gh-9702)', function() { const Child = db.model('Child', Schema({ name: String })); const Parent = db.model('Parent', { children: [{ type: ObjectId, ref: 'Child' }], child: { type: ObjectId, ref: 'Child' } }); return co(function*() { const c = yield Child.create({ name: 'test' }); yield Parent.create({ children: [c._id], child: c._id }); const p = yield Parent.findOne().populate('children child'); p.children; // [{ _id: '...', name: 'test' }] assert.equal(p.$getPopulatedDocs().length, 2); assert.equal(p.$getPopulatedDocs()[0], p.children[0]); assert.equal(p.$getPopulatedDocs()[0].name, 'test'); assert.equal(p.$getPopulatedDocs()[1], p.child); assert.equal(p.$getPopulatedDocs()[1].name, 'test'); }); }); ======= it('handles paths named `db` (gh-9798)', function() { const schema = new Schema({ db: String }); const Test = db.model('Test', schema); return co(function*() { const doc = yield Test.create({ db: 'foo' }); doc.db = 'bar'; yield doc.save(); yield doc.deleteOne(); const _doc = yield Test.findOne({ db: 'bar' }); assert.ok(!_doc); }); }); it('object setters will be applied for each object in array after populate (gh-9838)', function() { const updatedElID = '123456789012345678901234'; const ElementSchema = new Schema({ name: 'string', nested: [{ type: Schema.Types.ObjectId, ref: 'Nested' }] }); const NestedSchema = new Schema({}); const Element = db.model('Test', ElementSchema); const NestedElement = db.model('Nested', NestedSchema); return co(function*() { const nes = new NestedElement({}); yield nes.save(); const ele = new Element({ nested: [nes.id], name: 'test' }); yield ele.save(); const ss = yield Element.findById(ele._id).populate({ path: 'nested', model: NestedElement }); ss.nested = [updatedElID]; yield ss.save(); assert.ok(typeof ss.nested[0] !== 'string'); assert.equal(ss.nested[0].toHexString(), updatedElID); }); }); >>>>>>> it('supports getting a list of populated docs (gh-9702)', function() { const Child = db.model('Child', Schema({ name: String })); const Parent = db.model('Parent', { children: [{ type: ObjectId, ref: 'Child' }], child: { type: ObjectId, ref: 'Child' } }); return co(function*() { const c = yield Child.create({ name: 'test' }); yield Parent.create({ children: [c._id], child: c._id }); const p = yield Parent.findOne().populate('children child'); p.children; // [{ _id: '...', name: 'test' }] assert.equal(p.$getPopulatedDocs().length, 2); assert.equal(p.$getPopulatedDocs()[0], p.children[0]); assert.equal(p.$getPopulatedDocs()[0].name, 'test'); assert.equal(p.$getPopulatedDocs()[1], p.child); assert.equal(p.$getPopulatedDocs()[1].name, 'test'); }); }); it('handles paths named `db` (gh-9798)', function() { const schema = new Schema({ db: String }); const Test = db.model('Test', schema); return co(function*() { const doc = yield Test.create({ db: 'foo' }); doc.db = 'bar'; yield doc.save(); yield doc.deleteOne(); const _doc = yield Test.findOne({ db: 'bar' }); assert.ok(!_doc); }); }); it('object setters will be applied for each object in array after populate (gh-9838)', function() { const updatedElID = '123456789012345678901234'; const ElementSchema = new Schema({ name: 'string', nested: [{ type: Schema.Types.ObjectId, ref: 'Nested' }] }); const NestedSchema = new Schema({}); const Element = db.model('Test', ElementSchema); const NestedElement = db.model('Nested', NestedSchema); return co(function*() { const nes = new NestedElement({}); yield nes.save(); const ele = new Element({ nested: [nes.id], name: 'test' }); yield ele.save(); const ss = yield Element.findById(ele._id).populate({ path: 'nested', model: NestedElement }); ss.nested = [updatedElID]; yield ss.save(); assert.ok(typeof ss.nested[0] !== 'string'); assert.equal(ss.nested[0].toHexString(), updatedElID); }); });
<<<<<<< returns: { blocktype: 'expression', label: 'image##', script: 'image##', type: 'image' }, ======= locals: [ { blocktype: 'expression', labels: ['image##'], script: 'image##', type: 'image' } ], >>>>>>> locals: [ { blocktype: 'expression', label: 'image##', script: 'image##', type: 'image' } ], <<<<<<< returns: { blocktype: 'expression', label: 'animation##', script: 'animation##', type: 'image' }, ======= locals: [ { blocktype: 'expression', labels: ['animation##'], script: 'animation##', type: 'image' } ], >>>>>>> locals: [ { blocktype: 'expression', label: 'animation##', script: 'animation##', type: 'image' } ], <<<<<<< returns: { blocktype: 'expression', label: 'animation##', script: 'animation##', type: 'image' }, ======= locals: [ { blocktype: 'expression', labels: ['animation##'], script: 'animation##', type: 'image' } ], >>>>>>> locals: [ { blocktype: 'expression', label: 'animation##', script: 'animation##', type: 'image' } ], <<<<<<< returns: { blocktype: 'expression', label: 'sprite##', script: 'sprite##', type: 'sprite' }, ======= locals: [ { blocktype: 'expression', labels: ['sprite##'], script: 'sprite##', type: 'sprite' } ], >>>>>>> locals: [ { blocktype: 'expression', label: 'sprite##', script: 'sprite##', type: 'sprite' } ],
<<<<<<< var query = { _id: books[1]._id }; var update = { title: 'Professional AngularJS' }; Book.update(query, update, function(error) { assert.equal(error.message, 'woops'); done(); }); ======= assert.equal(count, 1); assert.equal(preCount, 1); assert.equal(postCount, 1); done(); >>>>>>> assert.equal(count, 1); assert.equal(preCount, 1); assert.equal(postCount, 1); var query = { _id: books[1]._id }; var update = { title: 'Professional AngularJS' }; Book.update(query, update, function(error) { assert.equal(error.message, 'woops'); done(); });
<<<<<<< s.plugins = Array.prototype.slice.call(this.plugins); ======= s._plugins = utils.clone(this._plugins); s._indexes = utils.clone(this._indexes); >>>>>>> s.plugins = Array.prototype.slice.call(this.plugins); s._indexes = utils.clone(this._indexes);
<<<<<<< function makeLean(option) { option.options || (option.options = {}); option.options.lean = true; } /*! * Handle the `WriteOpResult` from the server */ exports.handleWriteOpResult = function handleWriteOpResult(callback) { return function _handleWriteOpResult(error, res) { if (error) { return callback(error); } return callback(null, res.result); }; }; ======= function makeLean(val) { return function(option) { option.options || (option.options = {}); option.options.lean = val; }; } >>>>>>> function makeLean(val) { return function(option) { option.options || (option.options = {}); option.options.lean = val; }; } /*! * Handle the `WriteOpResult` from the server */ exports.handleWriteOpResult = function handleWriteOpResult(callback) { return function _handleWriteOpResult(error, res) { if (error) { return callback(error); } return callback(null, res.result); }; };
<<<<<<< var values, errorMessage; ======= var values, len; >>>>>>> var values; var errorMessage;
<<<<<<< function changeValueOnInputChange(evt){ ======= //toggle an inputs 'filter' selection ValueProto.toggleSelect = function(){ if (this.getAttribute('selected') === 'true'){ BLOCK_MENU.removeAttribute('filtered'); this.deselect(); }else{ BLOCK_MENU.setAttribute('filtered', 'true'); this.select(); } } //select an inout field and filter the sidebar by it ValueProto.select = function(){ var i = 0; var sidebarBlocks=[]; var selectedTypeList; var existing = workspace.querySelectorAll('wb-value[selected=true]'); if (existing.length !== 0){ var i =0; for(i=0; i< existing.length; i++){ existing[i].deselect();} } this.setAttribute('selected', 'true'); selectedType = this.getAttribute('type'); selectedTypeList = selectedType.split(','); for(i=0; i<selectedTypeList.length; i++){sidebarBlocks = sidebarBlocks.concat(Array.prototype.slice.call(BLOCK_MENU.querySelectorAll('wb-expression[type *= ' + selectedTypeList[i] + ']')));} for(i=0; i< sidebarBlocks.length; i++){ sidebarBlocks[i].setAttribute('filtered', 'true');} } //deselect an inout field and unfilter the sidebar ValueProto.deselect = function(){ var i = 0; var sidebarBlocks; this.removeAttribute('selected'); sidebarBlocks = BLOCK_MENU.querySelectorAll('wb-expression'); for(i=0; i< sidebarBlocks.length; i++){ sidebarBlocks[i].removeAttribute('filtered');} selectedType = 'null'; } //when a user clicks on an inout box in the workspace Event.on(document.body, 'editor:change', 'wb-contains input, wb-contains select', function(evt){ >>>>>>> //toggle an inputs 'filter' selection ValueProto.toggleSelect = function(){ if (this.getAttribute('selected') === 'true'){ BLOCK_MENU.removeAttribute('filtered'); this.deselect(); }else{ BLOCK_MENU.setAttribute('filtered', 'true'); this.select(); } } //select an inout field and filter the sidebar by it ValueProto.select = function(){ var i = 0; var sidebarBlocks=[]; var selectedTypeList; var existing = workspace.querySelectorAll('wb-value[selected=true]'); if (existing.length !== 0){ var i =0; for(i=0; i< existing.length; i++){ existing[i].deselect();} } this.setAttribute('selected', 'true'); selectedType = this.getAttribute('type'); selectedTypeList = selectedType.split(','); for(i=0; i<selectedTypeList.length; i++){sidebarBlocks = sidebarBlocks.concat(Array.prototype.slice.call(BLOCK_MENU.querySelectorAll('wb-expression[type *= ' + selectedTypeList[i] + ']')));} for(i=0; i< sidebarBlocks.length; i++){ sidebarBlocks[i].setAttribute('filtered', 'true');} } //deselect an inout field and unfilter the sidebar ValueProto.deselect = function(){ var i = 0; var sidebarBlocks; this.removeAttribute('selected'); sidebarBlocks = BLOCK_MENU.querySelectorAll('wb-expression'); for(i=0; i< sidebarBlocks.length; i++){ sidebarBlocks[i].removeAttribute('filtered');} selectedType = 'null'; } //when a user clicks on an inout box in the workspace function changeValueOnInputChange(evt){
<<<<<<< describe('Document#getChanges(...) (gh-9096)', function() { it('returns an empty object when there are no changes', function() { return co(function*() { const User = db.model('User', { name: String, age: Number, country: String }); const user = yield User.create({ name: 'Hafez', age: 25, country: 'Egypt' }); const changes = user.getChanges(); assert.deepEqual(changes, {}); }); }); it('returns only the changed paths', function() { return co(function*() { const User = db.model('User', { name: String, age: Number, country: String }); const user = yield User.create({ name: 'Hafez', age: 25, country: 'Egypt' }); user.country = undefined; user.age = 26; const changes = user.getChanges(); assert.deepEqual(changes, { $set: { age: 26 }, $unset: { country: 1 } }); }); }); }); ======= it('supports skipping defaults on a document (gh-8271)', function() { const testSchema = new mongoose.Schema({ testTopLevel: { type: String, default: 'foo' }, testNested: { prop: { type: String, default: 'bar' } }, testArray: [{ prop: { type: String, defualt: 'baz' } }], testSingleNested: new Schema({ prop: { type: String, default: 'qux' } }) }); const Test = db.model('Test', testSchema); const doc = new Test({ testArray: [{}], testSingleNested: {} }, null, { defaults: false }); assert.ok(!doc.testTopLevel); assert.ok(!doc.testNested.prop); assert.ok(!doc.testArray[0].prop); assert.ok(!doc.testSingleNested.prop); }); >>>>>>> describe('Document#getChanges(...) (gh-9096)', function() { it('returns an empty object when there are no changes', function() { return co(function*() { const User = db.model('User', { name: String, age: Number, country: String }); const user = yield User.create({ name: 'Hafez', age: 25, country: 'Egypt' }); const changes = user.getChanges(); assert.deepEqual(changes, {}); }); }); it('returns only the changed paths', function() { return co(function*() { const User = db.model('User', { name: String, age: Number, country: String }); const user = yield User.create({ name: 'Hafez', age: 25, country: 'Egypt' }); user.country = undefined; user.age = 26; const changes = user.getChanges(); assert.deepEqual(changes, { $set: { age: 26 }, $unset: { country: 1 } }); }); }); }); it('supports skipping defaults on a document (gh-8271)', function() { const testSchema = new mongoose.Schema({ testTopLevel: { type: String, default: 'foo' }, testNested: { prop: { type: String, default: 'bar' } }, testArray: [{ prop: { type: String, defualt: 'baz' } }], testSingleNested: new Schema({ prop: { type: String, default: 'qux' } }) }); const Test = db.model('Test', testSchema); const doc = new Test({ testArray: [{}], testSingleNested: {} }, null, { defaults: false }); assert.ok(!doc.testTopLevel); assert.ok(!doc.testNested.prop); assert.ok(!doc.testArray[0].prop); assert.ok(!doc.testSingleNested.prop); });
<<<<<<< describe('mongoose.set(`strictQuery`, value); (gh-6658)', function() { let strictQueryOriginalValue; this.beforeEach(() => strictQueryOriginalValue = mongoose.get('strictQuery')); this.afterEach(() => mongoose.set('strictQuery', strictQueryOriginalValue)); it('setting `strictQuery` on base sets strictQuery to schema (gh-6658)', function() { // Arrange mongoose.set('strictQuery', 'some value'); // Act const schema = new Schema(); // Assert assert.equal(schema.get('strictQuery'), 'some value'); }); it('`strictQuery` set on base gets overwritten by option set on schema (gh-6658)', function() { // Arrange mongoose.set('strictQuery', 'base option'); // Act const schema = new Schema({}, { strictQuery: 'schema option' }); // Assert assert.equal(schema.get('strictQuery'), 'schema option'); }); }); ======= it('treats dotted paths with no parent as a nested path (gh-9020)', function() { const customerSchema = new Schema({ 'card.brand': String, 'card.last4': String }); assert.ok(customerSchema.nested['card']); }); >>>>>>> describe('mongoose.set(`strictQuery`, value); (gh-6658)', function() { let strictQueryOriginalValue; this.beforeEach(() => strictQueryOriginalValue = mongoose.get('strictQuery')); this.afterEach(() => mongoose.set('strictQuery', strictQueryOriginalValue)); it('setting `strictQuery` on base sets strictQuery to schema (gh-6658)', function() { // Arrange mongoose.set('strictQuery', 'some value'); // Act const schema = new Schema(); // Assert assert.equal(schema.get('strictQuery'), 'some value'); }); it('`strictQuery` set on base gets overwritten by option set on schema (gh-6658)', function() { // Arrange mongoose.set('strictQuery', 'base option'); // Act const schema = new Schema({}, { strictQuery: 'schema option' }); // Assert assert.equal(schema.get('strictQuery'), 'schema option'); }); }); it('treats dotted paths with no parent as a nested path (gh-9020)', function() { const customerSchema = new Schema({ 'card.brand': String, 'card.last4': String }); assert.ok(customerSchema.nested['card']); });
<<<<<<< describe('save failure', function() { it('doesnt reset "modified" status for fields', function(done) { var db = start(); var UniqueSchema = new Schema({ changer: String, unique: { type: Number, unique: true } }); var Unique = db.model('Unique', UniqueSchema); var u1 = new Unique({ changer: 'a', unique: 5 }); var u2 = new Unique({ changer: 'a', unique: 6 }); Unique.on('index', function() { u1.save(function(err) { assert.ifError(err); assert.ok(!u1.isModified('changer')); u2.save(function(err) { assert.ifError(err); assert.ok(!u2.isModified('changer')); u2.changer = 'b'; u2.unique = 5; assert.ok(u2.isModified('changer')); u2.save(function(err) { assert.ok(err); assert.ok(u2.isModified('changer')); done(); }); }); }); }); }); }); ======= describe('gh-2442', function() { it('marks array as modified when initializing non-array from db', function(done) { var db = start(); var s1 = new Schema({ array: mongoose.Schema.Types.Mixed }, { minimize: false }); var s2 = new Schema({ array: { type: [{ _id: false, value: { type: Number, default: 0 } }], default: [{}] } }); var M1 = db.model('gh-2442-1', s1, 'gh-2442'); var M2 = db.model('gh-2442-2', s2, 'gh-2442'); M1.create({ array: {} }, function(err, doc) { assert.ifError(err); assert.ok(doc.array); M2.findOne({ _id: doc._id }, function(err, doc) { assert.ifError(err); assert.equal(doc.array[0].value, 0); doc.array[0].value = 1; doc.save(function(err) { assert.ifError(err); M2.findOne({ _id: doc._id }, function(err, doc) { assert.ifError(err); assert.ok(!doc.isModified('array')); assert.deepEqual(doc.array[0].value, 1); assert.equal('[{"value":1}]', JSON.stringify(doc.array)); done(); }); }); }); }); }); }); >>>>>>> describe('save failure', function() { it('doesnt reset "modified" status for fields', function(done) { var db = start(); var UniqueSchema = new Schema({ changer: String, unique: { type: Number, unique: true } }); var Unique = db.model('Unique', UniqueSchema); var u1 = new Unique({ changer: 'a', unique: 5 }); var u2 = new Unique({ changer: 'a', unique: 6 }); Unique.on('index', function() { u1.save(function(err) { assert.ifError(err); assert.ok(!u1.isModified('changer')); u2.save(function(err) { assert.ifError(err); assert.ok(!u2.isModified('changer')); u2.changer = 'b'; u2.unique = 5; assert.ok(u2.isModified('changer')); u2.save(function(err) { assert.ok(err); assert.ok(u2.isModified('changer')); }); }); }); }); }); }); describe('gh-2442', function() { it('marks array as modified when initializing non-array from db', function(done) { var db = start(); var s1 = new Schema({ array: mongoose.Schema.Types.Mixed }, { minimize: false }); var s2 = new Schema({ array: { type: [{ _id: false, value: { type: Number, default: 0 } }], default: [{}] } }); var M1 = db.model('gh-2442-1', s1, 'gh-2442'); var M2 = db.model('gh-2442-2', s2, 'gh-2442'); M1.create({ array: {} }, function(err, doc) { assert.ifError(err); assert.ok(doc.array); M2.findOne({ _id: doc._id }, function(err, doc) { assert.ifError(err); assert.equal(doc.array[0].value, 0); doc.array[0].value = 1; doc.save(function(err) { assert.ifError(err); M2.findOne({ _id: doc._id }, function(err, doc) { assert.ifError(err); assert.ok(!doc.isModified('array')); assert.deepEqual(doc.array[0].value, 1); assert.equal('[{"value":1}]', JSON.stringify(doc.array)); done(); }); }); }); }); }); });
<<<<<<< it('report error in pre hook (gh-5520)', function(done) { var TestSchema = new Schema({ name: String }); var ops = [ 'count', 'find', 'findOne', 'findOneAndRemove', 'findOneAndUpdate', 'replaceOne', 'update', 'updateOne', 'updateMany' ]; ops.forEach(function(op) { TestSchema.pre(op, function(next) { this.error(new Error(op + ' error')); next(); }); }); var TestModel = db.model('gh5520', TestSchema); var numOps = ops.length; ops.forEach(function(op) { TestModel.find({}).update({ name: 'test' })[op](function(error) { assert.ok(error); assert.equal(error.message, op + ' error'); --numOps || done(); }); }); }); ======= it('child schema with select: false in multiple paths (gh-5603)', function(done) { var ChildSchema = new mongoose.Schema({ field: { type: String, select: false }, _id: false }, { id: false }); var ParentSchema = new mongoose.Schema({ child: ChildSchema, child2: ChildSchema }); var Parent = db.model('gh5603', ParentSchema); var ogParent = new Parent(); ogParent.child = { field: 'test' }; ogParent.child2 = { field: 'test' }; ogParent.save(function(error) { assert.ifError(error); Parent.findById(ogParent._id).exec(function(error, doc) { assert.ifError(error); assert.ok(!doc.child.field); assert.ok(!doc.child2.field); done(); }); }); }); >>>>>>> it('report error in pre hook (gh-5520)', function(done) { var TestSchema = new Schema({ name: String }); var ops = [ 'count', 'find', 'findOne', 'findOneAndRemove', 'findOneAndUpdate', 'replaceOne', 'update', 'updateOne', 'updateMany' ]; ops.forEach(function(op) { TestSchema.pre(op, function(next) { this.error(new Error(op + ' error')); next(); }); }); var TestModel = db.model('gh5520', TestSchema); var numOps = ops.length; ops.forEach(function(op) { TestModel.find({}).update({ name: 'test' })[op](function(error) { assert.ok(error); assert.equal(error.message, op + ' error'); --numOps || done(); }); }); }); it('child schema with select: false in multiple paths (gh-5603)', function(done) { var ChildSchema = new mongoose.Schema({ field: { type: String, select: false }, _id: false }, { id: false }); var ParentSchema = new mongoose.Schema({ child: ChildSchema, child2: ChildSchema }); var Parent = db.model('gh5603', ParentSchema); var ogParent = new Parent(); ogParent.child = { field: 'test' }; ogParent.child2 = { field: 'test' }; ogParent.save(function(error) { assert.ifError(error); Parent.findById(ogParent._id).exec(function(error, doc) { assert.ifError(error); assert.ok(!doc.child.field); assert.ok(!doc.child2.field); done(); }); }); });
<<<<<<< describe('overwriteDiscriminatorKey', function() { it('allows changing discriminator key in update (gh-6087)', function() { const baseSchema = new Schema({}, { discriminatorKey: 'type' }); const baseModel = db.model('Test', baseSchema); const aSchema = Schema({ aThing: Number }, { _id: false, id: false }); const aModel = baseModel.discriminator('A', aSchema); const bSchema = new Schema({ bThing: String }, { _id: false, id: false }); const bModel = baseModel.discriminator('B', bSchema); return co(function*() { // Model is created as a type A let doc = yield baseModel.create({ type: 'A', aThing: 1 }); yield aModel.updateOne( { _id: doc._id }, { type: 'B', bThing: 'two' }, { runValidators: true, overwriteDiscriminatorKey: true } ); doc = yield baseModel.findById(doc); assert.equal(doc.type, 'B'); assert.ok(doc instanceof bModel); assert.equal(doc.bThing, 'two'); }); }); }); ======= it('update validators respect storeSubdocValidationError (gh-9172)', function() { const opts = { storeSubdocValidationError: false }; const Model = db.model('Test', Schema({ nested: Schema({ arr: [{ name: { type: String, required: true } }] }, opts) })); return co(function*() { const opts = { runValidators: true }; const err = yield Model.updateOne({}, { nested: { arr: [{}] } }, opts).catch(err => err); assert.ok(err); assert.ok(err.errors['nested.arr.0.name']); assert.ok(!err.errors['nested']); }); }); >>>>>>> describe('overwriteDiscriminatorKey', function() { it('allows changing discriminator key in update (gh-6087)', function() { const baseSchema = new Schema({}, { discriminatorKey: 'type' }); const baseModel = db.model('Test', baseSchema); const aSchema = Schema({ aThing: Number }, { _id: false, id: false }); const aModel = baseModel.discriminator('A', aSchema); const bSchema = new Schema({ bThing: String }, { _id: false, id: false }); const bModel = baseModel.discriminator('B', bSchema); return co(function*() { // Model is created as a type A let doc = yield baseModel.create({ type: 'A', aThing: 1 }); yield aModel.updateOne( { _id: doc._id }, { type: 'B', bThing: 'two' }, { runValidators: true, overwriteDiscriminatorKey: true } ); doc = yield baseModel.findById(doc); assert.equal(doc.type, 'B'); assert.ok(doc instanceof bModel); assert.equal(doc.bThing, 'two'); }); }); }); it('update validators respect storeSubdocValidationError (gh-9172)', function() { const opts = { storeSubdocValidationError: false }; const Model = db.model('Test', Schema({ nested: Schema({ arr: [{ name: { type: String, required: true } }] }, opts) })); return co(function*() { const opts = { runValidators: true }; const err = yield Model.updateOne({}, { nested: { arr: [{}] } }, opts).catch(err => err); assert.ok(err); assert.ok(err.errors['nested.arr.0.name']); assert.ok(!err.errors['nested']); }); });
<<<<<<< var matchValidator = function(v) { var ret = ((null != v && '' !== v) ? regExp.test(v) : true); return ret; }; ======= function matchValidator(v) { if (!regExp) { return false; } return null != v && '' !== v ? regExp.test(v) : true; } >>>>>>> var matchValidator = function(v) { if (!regExp) { return false; } var ret = ((null != v && '' !== v) ? regExp.test(v) : true); return ret; };
<<<<<<< describe('Document#getChanges(...) (gh-9096)', function() { it('returns an empty object when there are no changes', function() { return co(function*() { const User = db.model('User', { name: String, age: Number, country: String }); const user = yield User.create({ name: 'Hafez', age: 25, country: 'Egypt' }); const changes = user.getChanges(); assert.deepEqual(changes, {}); }); }); it('returns only the changed paths', function() { return co(function*() { const User = db.model('User', { name: String, age: Number, country: String }); const user = yield User.create({ name: 'Hafez', age: 25, country: 'Egypt' }); user.country = undefined; user.age = 26; const changes = user.getChanges(); assert.deepEqual(changes, { $set: { age: 26 }, $unset: { country: 1 } }); }); }); }); it('supports skipping defaults on a document (gh-8271)', function() { const testSchema = new mongoose.Schema({ testTopLevel: { type: String, default: 'foo' }, testNested: { prop: { type: String, default: 'bar' } }, testArray: [{ prop: { type: String, defualt: 'baz' } }], testSingleNested: new Schema({ prop: { type: String, default: 'qux' } }) }); const Test = db.model('Test', testSchema); const doc = new Test({ testArray: [{}], testSingleNested: {} }, null, { defaults: false }); assert.ok(!doc.testTopLevel); assert.ok(!doc.testNested.prop); assert.ok(!doc.testArray[0].prop); assert.ok(!doc.testSingleNested.prop); }); ======= it('uses strict equality when checking mixed paths for modifications (gh-9165)', function() { const schema = Schema({ obj: {} }); const Model = db.model('gh9165', schema); return Model.create({ obj: { key: '2' } }). then(doc => { doc.obj = { key: 2 }; assert.ok(doc.modifiedPaths().indexOf('obj') !== -1); return doc.save(); }). then(doc => Model.findById(doc)). then(doc => assert.strictEqual(doc.obj.key, 2)); }); >>>>>>> describe('Document#getChanges(...) (gh-9096)', function() { it('returns an empty object when there are no changes', function() { return co(function*() { const User = db.model('User', { name: String, age: Number, country: String }); const user = yield User.create({ name: 'Hafez', age: 25, country: 'Egypt' }); const changes = user.getChanges(); assert.deepEqual(changes, {}); }); }); it('returns only the changed paths', function() { return co(function*() { const User = db.model('User', { name: String, age: Number, country: String }); const user = yield User.create({ name: 'Hafez', age: 25, country: 'Egypt' }); user.country = undefined; user.age = 26; const changes = user.getChanges(); assert.deepEqual(changes, { $set: { age: 26 }, $unset: { country: 1 } }); }); }); }); it('supports skipping defaults on a document (gh-8271)', function() { const testSchema = new mongoose.Schema({ testTopLevel: { type: String, default: 'foo' }, testNested: { prop: { type: String, default: 'bar' } }, testArray: [{ prop: { type: String, defualt: 'baz' } }], testSingleNested: new Schema({ prop: { type: String, default: 'qux' } }) }); const Test = db.model('Test', testSchema); const doc = new Test({ testArray: [{}], testSingleNested: {} }, null, { defaults: false }); assert.ok(!doc.testTopLevel); assert.ok(!doc.testNested.prop); assert.ok(!doc.testArray[0].prop); assert.ok(!doc.testSingleNested.prop); }); it('uses strict equality when checking mixed paths for modifications (gh-9165)', function() { const schema = Schema({ obj: {} }); const Model = db.model('gh9165', schema); return Model.create({ obj: { key: '2' } }). then(doc => { doc.obj = { key: 2 }; assert.ok(doc.modifiedPaths().indexOf('obj') !== -1); return doc.save(); }). then(doc => Model.findById(doc)). then(doc => assert.strictEqual(doc.obj.key, 2)); });
<<<<<<< ======= stage: { stageWidth: function(){ return Event.stage.width; }, stageHeight: function(){ return Event.stage.height; }, centerX: function(){ return (Event.stage.width / 2); }, centerY: function(){ return (Event.stage.height / 2); }, randomX: function(){ return Math.random() * Event.stage.width; }, randomY: function(){ return Math.random() * Event.stage.height; }, }, >>>>>>>
<<<<<<< goose.connect(process.env.MONGOOSE_TEST_URI || uri); db.on('open', function() { db.close(function() { done(); }); }); }); it('with options', function(done) { const goose = new Mongoose; const db = goose.connection; goose.connect(process.env.MONGOOSE_TEST_URI || uri, {}); ======= goose.connect(process.env.MONGOOSE_TEST_URI || uri, options); >>>>>>> goose.connect(process.env.MONGOOSE_TEST_URI || uri, options); <<<<<<< mong.connect(process.env.MONGOOSE_TEST_URI || uri); const db = mong.connection; ======= mong.connect(process.env.MONGOOSE_TEST_URI || uri, options); var db = mong.connection; >>>>>>> mong.connect(process.env.MONGOOSE_TEST_URI || uri, options); const db = mong.connection; <<<<<<< const db2 = mong.createConnection(process.env.MONGOOSE_TEST_URI || uri); ======= var db2 = mong.createConnection(process.env.MONGOOSE_TEST_URI || uri, options); >>>>>>> const db2 = mong.createConnection(process.env.MONGOOSE_TEST_URI || uri, options); <<<<<<< const m = new mongoose.Mongoose; m.connect('mongodb://localhost:27017/test').then(function(m) { ======= var m = new mongoose.Mongoose; m.connect('mongodb://localhost:27017/test', options).then(function(m) { >>>>>>> const m = new mongoose.Mongoose; m.connect('mongodb://localhost:27017/test', options).then(function(m) {
<<<<<<< yield Cat.update(cond, update); const found = yield Cat.findOne(cond); ======= yield Cat.updateOne(cond, update); let found = yield Cat.findOne(cond); >>>>>>> yield Cat.updateOne(cond, update); const found = yield Cat.findOne(cond); <<<<<<< describe('without a callback', function() { it('count, update, remove works', function(done) { const Product = db.model('Product', 'update_products_' + random()); new Query(p1.collection, {}, Product).count(); Product.create({tags: 12345}, function(err) { assert.ifError(err); const time = 20; Product.find({tags: 12345}).update({$set: {tags: 123456}}); setTimeout(function() { Product.find({tags: 12345}, function(err, p) { assert.ifError(err); assert.equal(p.length, 1); Product.find({tags: 123456}).remove(); setTimeout(function() { Product.find({tags: 123456}, function(err, p) { assert.ifError(err); assert.equal(p.length, 0); done(); }); }, time); }); }, time); }); }); }); ======= >>>>>>> <<<<<<< const q = Product.where().remove({strings: 'remove-single-condition'}); ======= var q = Product.where().deleteMany({strings: 'remove-single-condition'}); >>>>>>> const q = Product.where().deleteMany({strings: 'remove-single-condition'}); <<<<<<< it('single option, false', function(done) { const Test = db.model('Test_single_false', new Schema({ name: String })); ======= it.skip('single option, false', function(done) { var Test = db.model('Test_single_false', new Schema({ name: String })); >>>>>>> it.skip('single option, false', function(done) { const Test = db.model('Test_single_false', new Schema({ name: String })); <<<<<<< it('single option, true', function(done) { const Test = db.model('Test_single_true', new Schema({ name: String })); ======= it.skip('single option, true', function(done) { var Test = db.model('Test_single_true', new Schema({ name: String })); >>>>>>> it.skip('single option, true', function(done) { const Test = db.model('Test_single_true', new Schema({ name: String })); <<<<<<< it('ignores sort when passed to count', function(done) { const Product = db.model('Product', 'Product_setOptions_test'); ======= it.skip('ignores sort when passed to count', function(done) { var Product = db.model('Product', 'Product_setOptions_test'); >>>>>>> it.skip('ignores sort when passed to count', function(done) { const Product = db.model('Product', 'Product_setOptions_test'); <<<<<<< it('ignores count when passed to sort', function(done) { const Product = db.model('Product', 'Product_setOptions_test'); ======= it.skip('ignores count when passed to sort', function(done) { var Product = db.model('Product', 'Product_setOptions_test'); >>>>>>> it.skip('ignores count when passed to sort', function(done) { const Product = db.model('Product', 'Product_setOptions_test'); <<<<<<< const q = Test.update({}, { ======= var q = Test.updateOne({}, { >>>>>>> const q = Test.updateOne({}, { <<<<<<< it('allows sort with count (gh-3914)', function(done) { const Post = db.model('gh3914_0', { ======= it.skip('allows sort with count (gh-3914)', function(done) { var Post = db.model('gh3914_0', { >>>>>>> it.skip('allows sort with count (gh-3914)', function(done) { const Post = db.model('gh3914_0', { <<<<<<< it('allows sort with select (gh-3914)', function(done) { const Post = db.model('gh3914_1', { ======= it.skip('allows sort with select (gh-3914)', function(done) { var Post = db.model('gh3914_1', { >>>>>>> it.skip('allows sort with select (gh-3914)', function(done) { const Post = db.model('gh3914_1', { <<<<<<< const answersUpdate = {details: 'blah', stats: {votes: 1, count: '3'}}; const q = Post.update( ======= var answersUpdate = {details: 'blah', stats: {votes: 1, count: '3'}}; var q = Post.updateOne( >>>>>>> const answersUpdate = {details: 'blah', stats: {votes: 1, count: '3'}}; const q = Post.updateOne( <<<<<<< const opts = { setDefaultsOnInsert: true, upsert: true }; MyModel.update({}, {}, opts, function(error) { ======= var opts = { setDefaultsOnInsert: true, upsert: true }; MyModel.updateOne({}, {}, opts, function(error) { >>>>>>> const opts = { setDefaultsOnInsert: true, upsert: true }; MyModel.updateOne({}, {}, opts, function(error) { <<<<<<< it('change deleteOne to updateOne for soft deletes using $isDeleted (gh-4428)', function(done) { const schema = new mongoose.Schema({ ======= it('change remove to updateOne for soft deletes using $isDeleted (gh-4428)', function(done) { var schema = new mongoose.Schema({ >>>>>>> it('change deleteOne to updateOne for soft deletes using $isDeleted (gh-4428)', function(done) { const schema = new mongoose.Schema({ <<<<<<< const _this = this; this.update({ isDeleted: true }, function(error) { ======= var _this = this; this.constructor.updateOne({ isDeleted: true }, function(error) { >>>>>>> const _this = this; this.constructor.updateOne({ isDeleted: true }, function(error) {
<<<<<<< const doc = { name: 'task1', title: 'task999' }; Task.collection.insert(doc, function(error) { ======= var doc = { name: 'task1', title: 'task999' }; Task.collection.insertOne(doc, function(error) { >>>>>>> const doc = { name: 'task1', title: 'task999' }; Task.collection.insertOne(doc, function(error) { <<<<<<< const badUpdate = {$set: {'user.email': 'a'}}; const options = {runValidators: true}; Event.update({}, badUpdate, options, function(error) { ======= var badUpdate = {$set: {'user.email': 'a'}}; var options = {runValidators: true}; Event.updateOne({}, badUpdate, options, function(error) { >>>>>>> const badUpdate = {$set: {'user.email': 'a'}}; const options = {runValidators: true}; Event.updateOne({}, badUpdate, options, function(error) { <<<<<<< const nestedUpdate = {name: 'test'}; const options = {upsert: true, setDefaultsOnInsert: true}; Event.update({}, nestedUpdate, options, function(error) { ======= var nestedUpdate = {name: 'test'}; var options = {upsert: true, setDefaultsOnInsert: true}; Event.updateOne({}, nestedUpdate, options, function(error) { >>>>>>> const nestedUpdate = {name: 'test'}; const options = {upsert: true, setDefaultsOnInsert: true}; Event.updateOne({}, nestedUpdate, options, function(error) {
<<<<<<< function Shape(pathArrayOrFunctionOrSAT){ if (type(pathArrayOrFunctionOrSAT) === 'function'){ this._draw = pathArrayOrFunctionOrSAT; }else if (type(pathArrayOrFunctionOrSAT) === 'array'){ for(var i =0; i < pathArrayOrFunctionOrSAT.length; i++){ if(!(pathArrayOrFunctionOrSAT[i] instanceof Path)){ throw new Error('Only paths may be added to a Shape, ' + pathArrayOrFunctionOrSAT[i] + " is not."); } } this.pathArray = pathArrayOrFunctionOrSAT; }else if (type(pathArrayOrFunctionOrSAT) === 'polygon'){ this.satPolygon = pathArrayOrFunctionOrSAT; }else if (type(pathArrayOrFunctionOrSAT) === 'circle'){ this.satCircle = pathArrayOrFunctionOrSAT; }else{ debugger; ======= function Shape(pathArrayOrFunction, pointsArray){ if (type(pathArrayOrFunction) === 'function'){ this._draw = pathArrayOrFunction; if (pointsArray != undefined) this.pointsArray = pointsArray; } else if (type(pathArrayOrFunction) === 'array'){ this.pathArray = pathArrayOrFunction; } else if (pathArrayOrFunction instanceof Path) { this.path = pathArrayOrFunction; } else{ >>>>>>> function Shape(pathArrayOrFunctionOrSAT, pointsArray){ if (type(pathArrayOrFunctionOrSAT) === 'function'){ this._draw = pathArrayOrFunctionOrSAT; if (pointsArray != undefined) this.pointsArray = pointsArray; } else if (type(pathArrayOrFunctionOrSAT) === 'array'){ this.pathArray = pathArrayOrFunctionOrSAT; } else if (pathArrayOrFunctionOrSAT instanceof Path) { this.path = pathArrayOrFunctionOrSAT; }else if (type(pathArrayOrFunctionOrSAT) === 'polygon'){ this.satPolygon = pathArrayOrFunctionOrSAT; }else if (type(pathArrayOrFunctionOrSAT) === 'circle'){ this.satCircle = pathArrayOrFunctionOrSAT; }else{ <<<<<<< else if (this.satPolygon){ ctx.beginPath(); ctx.moveTo(this.satPolygon.points[0].x, this.satPolygon.points[0].y); for (var i = 1; i < this.satPolygon.points.length; i++) { ctx.lineTo(this.satPolygon.points[i].x, this.satPolygon.points[i].y); }; ctx.lineTo(this.satPolygon.points[0].x, this.satPolygon.points[0].y); } else if (this.satCircle){ ctx.beginPath(); ctx.arc(0, 0, this.satCircle.r, 0, Math.PI * 2, true); } ======= >>>>>>> else if (this.satPolygon){ var x = this.satPolygon.points[0].x; var y = this.satPolygon.points[0].y; if (!util.isDrawingPath()){ ctx.beginPath(); ctx.moveTo(x, y); } else{ ctx.lineTo(x, y); } for (var i = 1; i < this.satPolygon.points.length; i++) { ctx.lineTo(this.satPolygon.points[i].x, this.satPolygon.points[i].y); }; ctx.lineTo(this.satPolygon.points[0].x, this.satPolygon.points[0].y); } else if (this.satCircle){ ctx.beginPath(); ctx.arc(0, 0, this.satCircle.r, 0, Math.PI * 2, true); } <<<<<<< Sprite.prototype.angle = function(){ return atan2(this.facing.y, this.facing.x); } ======= Sprite.prototype.toString = function(){ return 'Sprite pos: ' + this.position + ', vel: ' + this.velocity; }; >>>>>>> Sprite.prototype.angle = function(){ return atan2(this.facing.y, this.facing.x); } Sprite.prototype.toString = function(){ return 'Sprite pos: ' + this.position + ', vel: ' + this.velocity; };
<<<<<<< var SchemaType = require('../schematype') , ArrayType = require('./array') , MongooseDocumentArray = require('../types/documentarray') , Subdocument = require('../types/embedded') , Document = require('../document'); var utils = require('../utils.js'); ======= var ArrayType = require('./array'); var Document = require('../document'); var MongooseDocumentArray = require('../types/documentarray'); var SchemaType = require('../schematype'); var Subdocument = require('../types/embedded'); >>>>>>> var utils = require('../utils.js'); var ArrayType = require('./array'); var Document = require('../document'); var MongooseDocumentArray = require('../types/documentarray'); var SchemaType = require('../schematype'); var Subdocument = require('../types/embedded');
<<<<<<< , capped: false // { size, max, autoIndexId } ======= , versionKey: '__v' >>>>>>> , capped: false // { size, max, autoIndexId } , versionKey: '__v'
<<<<<<< it('supports cross-db populate with refPath (gh-6520)', function() { return co(function*() { const db2 = yield mongoose.createConnection(start.uri2); const bookSchema = new Schema({ title: String }); const movieSchema = new Schema({ title: String }); const userSchema = new Schema({ name: String, kind: String, hobby: { type: Schema.Types.ObjectId, refPath: 'kind' } }); const User = db.model('gh6520_User', userSchema); const Book = db2.model('Book', bookSchema); const Movie = db2.model('Movie', movieSchema); const book = yield Book.create({ title: 'Legacy of the Force: Revelation' }); const movie = yield Movie.create({ title: 'A New Hope' }); yield User.create([ { name: 'test1', kind: 'Book', hobby: book._id }, { name: 'test2', kind: 'Movie', hobby: movie._id } ]); const docs = yield User.find().sort({ name: 1 }).populate({ path: 'hobby', connection: db2 }); assert.equal(docs[0].hobby.title, 'Legacy of the Force: Revelation'); assert.equal(docs[1].hobby.title, 'A New Hope'); }); }); it('ref function for conventional populate (gh-7669)', function() { const schema = new mongoose.Schema({ kind: String, media: { type: mongoose.Schema.Types.ObjectId, ref: doc => doc.kind } }); const Model = db.model('gh7669', schema); const Movie = db.model('gh7669_Movie', new Schema({ name: String })); const Book = db.model('gh7669_Book', new Schema({ title: String })); return co(function*() { const docs = yield [ Movie.create({ name: 'The Empire Strikes Back' }), Book.create({ title: 'New Jedi Order' }) ]; yield Model.create([ { kind: 'gh7669_Movie', media: docs[0]._id }, { kind: 'gh7669_Book', media: docs[1]._id } ]); const res = yield Model.find().sort({ kind: -1 }).populate('media'); assert.equal(res[0].kind, 'gh7669_Movie'); assert.equal(res[0].media.name, 'The Empire Strikes Back'); assert.equal(res[1].kind, 'gh7669_Book'); assert.equal(res[1].media.title, 'New Jedi Order'); }); }); ======= it('virtual refPath (gh-7848)', function() { const Child = db.model('gh7848_Child', Schema({ name: String, parentId: Number })); const parentSchema = Schema({ _id: Number, kind: String }); parentSchema.virtual('childDocs', { refPath: 'kind', localField: '_id', foreignField: 'parentId', justOne: false }); const Parent = db.model('gh7848_Parent', parentSchema); return co(function*() { yield Parent.create({ _id: 1, kind: 'gh7848_Child' }); yield Child.create({ name: 'test', parentId: 1 }); const doc = yield Parent.findOne().populate('childDocs'); assert.equal(doc.childDocs.length, 1); assert.equal(doc.childDocs[0].name, 'test'); }); }); >>>>>>> it('supports cross-db populate with refPath (gh-6520)', function() { return co(function*() { const db2 = yield mongoose.createConnection(start.uri2); const bookSchema = new Schema({ title: String }); const movieSchema = new Schema({ title: String }); const userSchema = new Schema({ name: String, kind: String, hobby: { type: Schema.Types.ObjectId, refPath: 'kind' } }); const User = db.model('gh6520_User', userSchema); const Book = db2.model('Book', bookSchema); const Movie = db2.model('Movie', movieSchema); const book = yield Book.create({ title: 'Legacy of the Force: Revelation' }); const movie = yield Movie.create({ title: 'A New Hope' }); yield User.create([ { name: 'test1', kind: 'Book', hobby: book._id }, { name: 'test2', kind: 'Movie', hobby: movie._id } ]); const docs = yield User.find().sort({ name: 1 }).populate({ path: 'hobby', connection: db2 }); assert.equal(docs[0].hobby.title, 'Legacy of the Force: Revelation'); assert.equal(docs[1].hobby.title, 'A New Hope'); }); }); it('ref function for conventional populate (gh-7669)', function() { const schema = new mongoose.Schema({ kind: String, media: { type: mongoose.Schema.Types.ObjectId, ref: doc => doc.kind } }); const Model = db.model('gh7669', schema); const Movie = db.model('gh7669_Movie', new Schema({ name: String })); const Book = db.model('gh7669_Book', new Schema({ title: String })); return co(function*() { const docs = yield [ Movie.create({ name: 'The Empire Strikes Back' }), Book.create({ title: 'New Jedi Order' }) ]; yield Model.create([ { kind: 'gh7669_Movie', media: docs[0]._id }, { kind: 'gh7669_Book', media: docs[1]._id } ]); const res = yield Model.find().sort({ kind: -1 }).populate('media'); assert.equal(res[0].kind, 'gh7669_Movie'); assert.equal(res[0].media.name, 'The Empire Strikes Back'); assert.equal(res[1].kind, 'gh7669_Book'); assert.equal(res[1].media.title, 'New Jedi Order'); }); }); it('virtual refPath (gh-7848)', function() { const Child = db.model('gh7848_Child', Schema({ name: String, parentId: Number })); const parentSchema = Schema({ _id: Number, kind: String }); parentSchema.virtual('childDocs', { refPath: 'kind', localField: '_id', foreignField: 'parentId', justOne: false }); const Parent = db.model('gh7848_Parent', parentSchema); return co(function*() { yield Parent.create({ _id: 1, kind: 'gh7848_Child' }); yield Child.create({ name: 'test', parentId: 1 }); const doc = yield Parent.findOne().populate('childDocs'); assert.equal(doc.childDocs.length, 1); assert.equal(doc.childDocs[0].name, 'test'); }); });
<<<<<<< }, 'Model#save should emit an error as its default error handler if a callback is not passed to it': function () { var db = start(); var DefaultErrSchema = new Schema({}); DefaultErrSchema.pre('save', function (next, fn) { next(new Error()); }); var DefaultErr = db.model('DefaultErr', DefaultErrSchema, 'default_err_' + random()); var e = new DefaultErr(); e.on('error', function (err) { err.should.be.an.instanceof(Error); db.close(); }); e.save(); ======= }, 'backward compatibility with conflicted data in the db': function () { var db = start(); var M = db.model('backwardDataConflict', new Schema({ namey: { first: String, last: String }})); var m = new M({ namey: "[object Object]" }); m.namey = { first: 'GI', last: 'Joe' };// <-- should overwrite the string m.save(function (err) { db.close(); should.strictEqual(err, null); should.strictEqual('GI', m.namey.first); should.strictEqual('Joe', m.namey.last); }); >>>>>>> }, 'Model#save should emit an error as its default error handler if a callback is not passed to it': function () { var db = start(); var DefaultErrSchema = new Schema({}); DefaultErrSchema.pre('save', function (next, fn) { next(new Error()); }); var DefaultErr = db.model('DefaultErr', DefaultErrSchema, 'default_err_' + random()); var e = new DefaultErr(); e.on('error', function (err) { err.should.be.an.instanceof(Error); db.close(); }); e.save(); }, 'backward compatibility with conflicted data in the db': function () { var db = start(); var M = db.model('backwardDataConflict', new Schema({ namey: { first: String, last: String }})); var m = new M({ namey: "[object Object]" }); m.namey = { first: 'GI', last: 'Joe' };// <-- should overwrite the string m.save(function (err) { db.close(); should.strictEqual(err, null); should.strictEqual('GI', m.namey.first); should.strictEqual('Joe', m.namey.last); });
<<<<<<< exports.sessionNewDocuments = Symbol('mongoose:ClientSession#newDocuments'); ======= exports.scopeSymbol = Symbol('mongoose#Document#scope'); >>>>>>> exports.sessionNewDocuments = Symbol('mongoose:ClientSession#newDocuments'); exports.scopeSymbol = Symbol('mongoose#Document#scope');
<<<<<<< it('save() depopulates pushed arrays (gh-6048)', function() { const blogPostSchema = new Schema({ comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'gh6048_0' }] }); const BlogPost = db.model('gh6048', blogPostSchema); const commentSchema = new Schema({ text: String }); const Comment = db.model('gh6048_0', commentSchema); return co(function*() { let blogPost = yield BlogPost.create({}); const comment = yield Comment.create({ text: 'Hello' }); blogPost = yield BlogPost.findById(blogPost); blogPost.comments.push(comment); yield blogPost.save(); const savedBlogPost = yield BlogPost.collection. findOne({ _id: blogPost._id }); assert.equal(savedBlogPost.comments.length, 1); assert.equal(savedBlogPost.comments[0].constructor.name, 'ObjectID'); assert.equal(savedBlogPost.comments[0].toString(), blogPost.comments[0]._id.toString()); }); }); ======= it('Handles setting populated path set via `Document#populate()` (gh-7302)', function() { var authorSchema = new Schema({ name: String }); var bookSchema = new Schema({ author: { type: mongoose.Schema.Types.ObjectId, ref: 'gh7302_Author' } }); var Author = db.model('gh7302_Author', authorSchema); var Book = db.model('gh7302_Book', bookSchema); return Author.create({ name: 'Victor Hugo' }). then(author => Book.create({ author: author._id })). then(() => Book.findOne()). then(doc => doc.populate('author').execPopulate()). then(doc => { doc.author = {}; assert.ok(!doc.author.name); assert.ifError(doc.validateSync()); }); }); >>>>>>> it('save() depopulates pushed arrays (gh-6048)', function() { const blogPostSchema = new Schema({ comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'gh6048_0' }] }); const BlogPost = db.model('gh6048', blogPostSchema); const commentSchema = new Schema({ text: String }); const Comment = db.model('gh6048_0', commentSchema); return co(function*() { let blogPost = yield BlogPost.create({}); const comment = yield Comment.create({ text: 'Hello' }); blogPost = yield BlogPost.findById(blogPost); blogPost.comments.push(comment); yield blogPost.save(); const savedBlogPost = yield BlogPost.collection. findOne({ _id: blogPost._id }); assert.equal(savedBlogPost.comments.length, 1); assert.equal(savedBlogPost.comments[0].constructor.name, 'ObjectID'); assert.equal(savedBlogPost.comments[0].toString(), blogPost.comments[0]._id.toString()); }); }); it('Handles setting populated path set via `Document#populate()` (gh-7302)', function() { var authorSchema = new Schema({ name: String }); var bookSchema = new Schema({ author: { type: mongoose.Schema.Types.ObjectId, ref: 'gh7302_Author' } }); var Author = db.model('gh7302_Author', authorSchema); var Book = db.model('gh7302_Book', bookSchema); return Author.create({ name: 'Victor Hugo' }). then(author => Book.create({ author: author._id })). then(() => Book.findOne()). then(doc => doc.populate('author').execPopulate()). then(doc => { doc.author = {}; assert.ok(!doc.author.name); assert.ifError(doc.validateSync()); }); });
<<<<<<< it('does not apply toObject functions of subdocuments to root document', function( done ){ var subdocSchema = new Schema({ test: String, wow: String }); subdocSchema.options.toObject = {}; subdocSchema.options.toObject.transform = function (doc, ret, options) { delete ret.wow; }; var docSchema = new Schema({ foo: String, wow: Boolean, sub: [subdocSchema] }); var db = start() , Doc = db.model('Doc', docSchema) , Subdoc = db.model('Subdoc', subdocSchema); Doc.create({ foo: 'someString', wow: true, sub: [{ test: 'someOtherString', wow: 'thisIsAString' }] }, function( err, doc ){ var obj = doc.toObject({ transform: function (doc, ret) { ret.phew = 'new'; } }); assert.equal(obj.phew, 'new'); assert.ok(!doc.sub.wow); done(); }); }); ======= it('handles child schema transforms', function(done) { var db = start(); var userSchema = new Schema({ name: String, email: String }); var topicSchema = new Schema({ title: String, email: String, followers: [userSchema] }); userSchema.options.toObject = { transform: function(doc, ret, options) { delete ret.email; } }; topicSchema.options.toObject = { transform: function(doc, ret, options) { ret.title = ret.title.toLowerCase(); } }; var Topic = db.model('gh2691', topicSchema, 'gh2691'); var topic = new Topic({ title: 'Favorite Foods', email: '[email protected]', followers: [{ name: 'Val', email: '[email protected]' }] }); var expectedOutput = { _id: topic._id.toString(), title: 'favorite foods', email: '[email protected]', followers: [{ name: 'Val', _id: topic.followers[0]._id.toString() }] }; var output = topic.toObject({ transform: true }); assert.equal('favorite foods', output.title); assert.equal('[email protected]', output.email); assert.equal('Val', output.followers[0].name); assert.equal(undefined, output.followers[0].email); done(); }); >>>>>>> it('does not apply toObject functions of subdocuments to root document', function( done ){ var subdocSchema = new Schema({ test: String, wow: String }); subdocSchema.options.toObject = {}; subdocSchema.options.toObject.transform = function (doc, ret, options) { delete ret.wow; }; var docSchema = new Schema({ foo: String, wow: Boolean, sub: [subdocSchema] }); var db = start() , Doc = db.model('Doc', docSchema) , Subdoc = db.model('Subdoc', subdocSchema); Doc.create({ foo: 'someString', wow: true, sub: [{ test: 'someOtherString', wow: 'thisIsAString' }] }, function( err, doc ){ var obj = doc.toObject({ transform: function (doc, ret) { ret.phew = 'new'; } }); assert.equal(obj.phew, 'new'); assert.ok(!doc.sub.wow); done(); }); }); it('handles child schema transforms', function(done) { var db = start(); var userSchema = new Schema({ name: String, email: String }); var topicSchema = new Schema({ title: String, email: String, followers: [userSchema] }); userSchema.options.toObject = { transform: function(doc, ret, options) { delete ret.email; } }; topicSchema.options.toObject = { transform: function(doc, ret, options) { ret.title = ret.title.toLowerCase(); } }; var Topic = db.model('gh2691', topicSchema, 'gh2691'); var topic = new Topic({ title: 'Favorite Foods', email: '[email protected]', followers: [{ name: 'Val', email: '[email protected]' }] }); var expectedOutput = { _id: topic._id.toString(), title: 'favorite foods', email: '[email protected]', followers: [{ name: 'Val', _id: topic.followers[0]._id.toString() }] }; var output = topic.toObject({ transform: true }); assert.equal('favorite foods', output.title); assert.equal('[email protected]', output.email); assert.equal('Val', output.followers[0].name); assert.equal(undefined, output.followers[0].email); done(); });
<<<<<<< describe('#remove()', function() { let B; ======= describe.skip('#remove()', function() { var B; >>>>>>> describe.skip('#remove()', function() { let B; <<<<<<< it('count()', function(done) { const BlogPost = db.model('BlogPost' + random(), bpSchema); ======= it.skip('count()', function(done) { var BlogPost = db.model('BlogPost' + random(), bpSchema); >>>>>>> it.skip('count()', function(done) { const BlogPost = db.model('BlogPost' + random(), bpSchema); <<<<<<< it('update()', function(done) { const col = 'BlogPost' + random(); const BlogPost = db.model(col, bpSchema); ======= it.skip('update()', function(done) { var col = 'BlogPost' + random(); var BlogPost = db.model(col, bpSchema); >>>>>>> it.skip('update()', function(done) { const col = 'BlogPost' + random(); const BlogPost = db.model(col, bpSchema); <<<<<<< it('remove()', function(done) { const BlogPost = db.model('BlogPost' + random(), bpSchema); ======= it.skip('remove()', function(done) { var BlogPost = db.model('BlogPost' + random(), bpSchema); >>>>>>> it.skip('remove()', function(done) { const BlogPost = db.model('BlogPost' + random(), bpSchema); <<<<<<< it('count()', function(done) { const BlogPost = db.model('BlogPost' + random(), bpSchema); ======= it.skip('count()', function(done) { var BlogPost = db.model('BlogPost' + random(), bpSchema); >>>>>>> it.skip('count()', function(done) { const BlogPost = db.model('BlogPost' + random(), bpSchema); <<<<<<< it('update()', function(done) { const col = 'BlogPost' + random(); const BlogPost = db.model(col, bpSchema); ======= it.skip('update()', function(done) { var col = 'BlogPost' + random(); var BlogPost = db.model(col, bpSchema); >>>>>>> it.skip('update()', function(done) { const col = 'BlogPost' + random(); const BlogPost = db.model(col, bpSchema); <<<<<<< const schema = new Schema({title: {type: 'string', index: true}}); const T = db.model('T', schema); T.collection.insert({title: 234}, {safe: true}, function(err) { ======= var schema = new Schema({title: {type: 'string', index: true}}); var T = db.model('T', schema); T.collection.insertOne({title: 234}, {safe: true}, function(err) { >>>>>>> const schema = new Schema({title: {type: 'string', index: true}}); const T = db.model('T', schema); T.collection.insertOne({title: 234}, {safe: true}, function(err) { <<<<<<< const M = db.model('758', new Schema({s: String, n: Number, a: Array})); M.collection.insert({}, {safe: true}, function(err) { ======= var M = db.model('758', new Schema({s: String, n: Number, a: Array})); M.collection.insertOne({}, {safe: true}, function(err) { >>>>>>> const M = db.model('758', new Schema({s: String, n: Number, a: Array})); M.collection.insertOne({}, {safe: true}, function(err) {
<<<<<<< it('populate with Decimal128 as ref (gh-4759)', function(done) { start.mongodVersion(function(err, version) { if (err) { done(err); return; } var mongo34 = version[0] > 3 || (version[0] === 3 && version[1] >= 4); if (!mongo34) { done(); return; } test(); }); function test() { var parentSchema = new Schema({ name: String, child: { type: 'Decimal128', ref: 'gh4759' } }); var childSchema = new Schema({ _id: 'Decimal128', name: String }); var Child = db.model('gh4759', childSchema); var Parent = db.model('gh4759_0', parentSchema); var decimal128 = childSchema.path('_id').cast('1.337e+3'); Child.create({ name: 'Luke', _id: '1.337e+3' }). then(function() { return Parent.create({ name: 'Anakin', child: decimal128.bytes }); }). then(function(parent) { return Parent.findById(parent._id).populate('child'); }). then(function(parent) { assert.equal(parent.child.name, 'Luke'); assert.equal(parent.child._id.toString(), '1337'); done(); }). catch(done); } }); ======= it('handles nested virtuals (gh-4851)', function(done) { var AuthorSchema = new Schema({ name: String }); var BookSchema = new Schema({ title: String, author: { id: mongoose.Schema.Types.ObjectId } }); BookSchema.virtual('author.doc', { ref: 'Author', foreignField: '_id', localField: 'author.id', justOne: true }); var Author = db.model('Author', AuthorSchema); var Book = db.model('Book', BookSchema); Author.create({ name: 'Val' }). then(function(author) { return Book.create({ title: 'Professional AngularJS', author: { id: author._id } }); }). then(function(book) { return Book.findById(book).populate('author.doc'); }). then(function(doc) { assert.equal(doc.author.doc.name, 'Val'); doc = doc.toObject({ virtuals: true }); assert.equal(doc.author.doc.name, 'Val'); done(); }). catch(done); }); >>>>>>> it('populate with Decimal128 as ref (gh-4759)', function(done) { start.mongodVersion(function(err, version) { if (err) { done(err); return; } var mongo34 = version[0] > 3 || (version[0] === 3 && version[1] >= 4); if (!mongo34) { done(); return; } test(); }); function test() { var parentSchema = new Schema({ name: String, child: { type: 'Decimal128', ref: 'gh4759' } }); var childSchema = new Schema({ _id: 'Decimal128', name: String }); var Child = db.model('gh4759', childSchema); var Parent = db.model('gh4759_0', parentSchema); var decimal128 = childSchema.path('_id').cast('1.337e+3'); Child.create({ name: 'Luke', _id: '1.337e+3' }). then(function() { return Parent.create({ name: 'Anakin', child: decimal128.bytes }); }). then(function(parent) { return Parent.findById(parent._id).populate('child'); }). then(function(parent) { assert.equal(parent.child.name, 'Luke'); assert.equal(parent.child._id.toString(), '1337'); done(); }). catch(done); } }); it('handles nested virtuals (gh-4851)', function(done) { var AuthorSchema = new Schema({ name: String }); var BookSchema = new Schema({ title: String, author: { id: mongoose.Schema.Types.ObjectId } }); BookSchema.virtual('author.doc', { ref: 'Author', foreignField: '_id', localField: 'author.id', justOne: true }); var Author = db.model('Author', AuthorSchema); var Book = db.model('Book', BookSchema); Author.create({ name: 'Val' }). then(function(author) { return Book.create({ title: 'Professional AngularJS', author: { id: author._id } }); }). then(function(book) { return Book.findById(book).populate('author.doc'); }). then(function(doc) { assert.equal(doc.author.doc.name, 'Val'); doc = doc.toObject({ virtuals: true }); assert.equal(doc.author.doc.name, 'Val'); done(); }). catch(done); });
<<<<<<< scratchpad = document.querySelector('.scratchpad'); ======= var scratchpad= document.querySelector('.scratchpad'); // <- WB >>>>>>> var scratchpad= document.querySelector('.scratchpad'); // <- WB <<<<<<< Event.on('.content', 'touchstart', '.block', initDrag); Event.on('.content', 'touchmove', null, drag); Event.on('.content', 'touchend', null, endDrag); // TODO: A way to cancel touch drag? Event.on('.content', 'mousedown', '.block', initDrag); Event.on('.content', 'mousemove', null, drag); Event.on(document.body, 'mouseup', null, endDrag); Event.on(document.body, 'keyup', null, cancelDrag); ======= if (Event.isTouch){ Event.on('.content', 'touchstart', '.block', initDrag); Event.on('.content', 'touchmove', null, drag); Event.on('.content', 'touchend', null, endDrag); // TODO: A way to cancel the drag? // Event.on('.scripts_workspace', 'tap', '.socket', selectSocket); }else{ Event.on('.content', 'mousedown', '.block', initDrag); Event.on(document.body, 'mousemove', null, drag); Event.on('.content', 'mouseup', null, endDrag); Event.on(document.body, 'keyup', null, cancelDrag); // Event.on('.scripts_workspace', 'click', '.socket', selectSocket); } >>>>>>> Event.on('.content', 'touchstart', '.block', initDrag); Event.on('.content', 'touchmove', null, drag); Event.on('.content', 'touchend', null, endDrag); // TODO: A way to cancel touch drag? Event.on('.content', 'mousedown', '.block', initDrag); Event.on('.content', 'mousemove', null, drag); Event.on(document.body, 'mouseup', null, endDrag); Event.on(document.body, 'keyup', null, cancelDrag); <<<<<<< var workspace = document.querySelector('.scripts_workspace') ======= var workspace = document.querySelector('.workspace > .scripts_workspace') var path = location.href.split('?')[0]; history.pushState(null, '', path); >>>>>>> var workspace = document.querySelector('.scripts_workspace') var path = location.href.split('?')[0]; history.pushState(null, '', path);
<<<<<<< console.log('Inbox: ', pos); var x = pos[0]; var z = pos[1]; engine.setMove(x, z); var clickedSquare = new THREE.Vector3(x*sz, sz/2+0.1, z*sz); engine.translateDir = clickedSquare.clone(); engine.translateDir.sub(engine.controls.target0); engine.translateState = 0.0; //engine.controls.saveState(); engine.controls.target0.copy(clickedSquare); var x = engine.moveTarg[0]; var z = engine.moveTarg[1]; //engine.setMove(x, z); ======= //console.log(pos); handler.receiveMoves( pos ); >>>>>>> console.log('Inbox: ', pos); var x = pos[0]; var z = pos[1]; engine.setMove(x, z); var clickedSquare = new THREE.Vector3(x*sz, sz/2+0.1, z*sz); engine.translateDir = clickedSquare.clone(); engine.translateDir.sub(engine.controls.target0); engine.translateState = 0.0; //engine.controls.saveState(); engine.controls.target0.copy(clickedSquare); var x = engine.moveTarg[0]; var z = engine.moveTarg[1]; //engine.setMove(x, z); //console.log(pos); handler.receiveMoves( pos );
<<<<<<< import * as entityM from './entitybox.js'; ======= import * as textsprite from './textsprite.js'; >>>>>>> import * as entityM from './entitybox.js'; import * as textsprite from './textsprite.js';
<<<<<<< ======= if ( !title ) return; >>>>>>> if ( !title ) return; <<<<<<< ======= if( !name ) return; >>>>>>> if( !name ) return; <<<<<<< "suffix": "movement direction" ======= "value": null }, { "name": "movement vector" >>>>>>> "suffix": "movement vector"
<<<<<<< const quantity = (acc[current.sku]?.quantity ?? 0) + 1 const value = (acc[current.sku]?.value ?? 0) + current.price const formattedValue = toCurrency({ value, currency, language }) ======= const quantity = (acc[current.sku]?.quantity ?? 0) + 1; const value = (acc[current.sku]?.value ?? 0) + current.price; const formattedValue = formatCurrencyString({ value, currency, language }); >>>>>>> const quantity = (acc[current.sku]?.quantity ?? 0) + 1 const value = (acc[current.sku]?.value ?? 0) + current.price const formattedValue = formatCurrencyString({ value, currency, language })
<<<<<<< let result; beforeEach(() => { const wrapper = createWrapper(); result = renderHook(() => useStripeCart(), { wrapper }).result; }); ======= >>>>>>> let result; beforeEach(() => { const wrapper = createWrapper(); result = renderHook(() => useStripeCart(), { wrapper }).result; }); <<<<<<< it('addItem should add one copy of the item and one unit of cost', () => { act(() => { result.current.addItem(mockSku); result.current.addItem(mockSku); result.current.addItem(mockSku); }); }); ======= it('reduceItemByOne reduces the cartItem amount of the target SKU by one', () => { act(() => { result.current.addItem(mockSku); result.current.addItem(mockSku); result.current.addItem(mockSku); }); expect(result.current.cartItems.length).toEqual(3); act(() => { result.current.reduceItemByOne(mockSku.sku); }); expect(result.current.cartItems.length).toEqual(2); }); it('reduceItemByOne reduces the cartItems amount of the target SKU by one even when other SKUs are present', () => { act(() => { result.current.addItem(mockSku); result.current.addItem(mockSku); result.current.addItem(mockSku); result.current.addItem(mockSku2); }); expect(result.current.cartItems.length).toEqual(4); act(() => { result.current.reduceItemByOne(mockSku.sku); }); expect(result.current.cartItems.length).toEqual(3); }); }); describe('useStripeCart redirectToCheckout', () => { beforeEach(() => { stripeMock.redirectToCheckout.mockClear(); }); it('should send the correct default values', () => { const wrapper = createWrapper(); const { result } = renderHook(() => useStripeCart(), { wrapper }); result.current.redirectToCheckout(); expect(stripeMock.redirectToCheckout).toHaveBeenCalled(); expect(stripeMock.redirectToCheckout.mock.calls[0][0]).toEqual({ items: [], successUrl: 'https://egghead.io/success', cancelUrl: 'https://egghead.io/cancel', billingAddressCollection: 'auto', submitType: 'auto', }); }); it('should send all formatted items', () => { const wrapper = createWrapper(); const { result } = renderHook(() => useStripeCart(), { wrapper }); act(() => { result.current.addItem(mockSku); result.current.addItem(mockSku); }); result.current.redirectToCheckout(); const expectedItems = [ { sku: mockSku.sku, quantity: 2 }, ]; expect(stripeMock.redirectToCheckout).toHaveBeenCalled(); expect(result.current.checkoutData).toEqual(expectedItems); expect(stripeMock.redirectToCheckout.mock.calls[0][0].items) .toEqual(expectedItems); }); it('should send correct billingAddressCollection', () => { const wrapper = createWrapper({ billingAddressCollection: true }); const { result } = renderHook(() => useStripeCart(), { wrapper }); result.current.redirectToCheckout(); expect(stripeMock.redirectToCheckout).toHaveBeenCalled(); expect(stripeMock.redirectToCheckout.mock.calls[0][0].billingAddressCollection).toBe('required'); }); it('should send correct shippingAddressCollection', () => { const wrapper = createWrapper({ allowedCountries: ['US', 'CA'] }); const { result } = renderHook(() => useStripeCart(), { wrapper }); result.current.redirectToCheckout(); expect(stripeMock.redirectToCheckout).toHaveBeenCalled(); expect(stripeMock.redirectToCheckout.mock.calls[0][0].shippingAddressCollection.allowedCountries).toEqual(['US', 'CA']); }); >>>>>>> it('reduceItemByOne reduces the cartItem amount of the target SKU by one', () => { act(() => { result.current.addItem(mockSku); result.current.addItem(mockSku); result.current.addItem(mockSku); }); expect(result.current.cartItems.length).toEqual(3); act(() => { result.current.reduceItemByOne(mockSku.sku); }); expect(result.current.cartItems.length).toEqual(2); }); it('reduceItemByOne reduces the cartItems amount of the target SKU by one even when other SKUs are present', () => { act(() => { result.current.addItem(mockSku); result.current.addItem(mockSku); result.current.addItem(mockSku); result.current.addItem(mockSku2); }); expect(result.current.cartItems.length).toEqual(4); act(() => { result.current.reduceItemByOne(mockSku.sku); }); expect(result.current.cartItems.length).toEqual(3); }); }); describe('useStripeCart redirectToCheckout', () => { beforeEach(() => { stripeMock.redirectToCheckout.mockClear(); }); it('should send the correct default values', () => { const wrapper = createWrapper(); const { result } = renderHook(() => useStripeCart(), { wrapper }); result.current.redirectToCheckout(); expect(stripeMock.redirectToCheckout).toHaveBeenCalled(); expect(stripeMock.redirectToCheckout.mock.calls[0][0]).toEqual({ items: [], successUrl: 'https://egghead.io/success', cancelUrl: 'https://egghead.io/cancel', billingAddressCollection: 'auto', submitType: 'auto', }); }); it('should send all formatted items', () => { const wrapper = createWrapper(); const { result } = renderHook(() => useStripeCart(), { wrapper }); act(() => { result.current.addItem(mockSku); result.current.addItem(mockSku); }); result.current.redirectToCheckout(); const expectedItems = [{ sku: mockSku.sku, quantity: 2 }]; expect(stripeMock.redirectToCheckout).toHaveBeenCalled(); expect(result.current.checkoutData).toEqual(expectedItems); expect(stripeMock.redirectToCheckout.mock.calls[0][0].items).toEqual( expectedItems ); }); it('should send correct billingAddressCollection', () => { const wrapper = createWrapper({ billingAddressCollection: true }); const { result } = renderHook(() => useStripeCart(), { wrapper }); result.current.redirectToCheckout(); expect(stripeMock.redirectToCheckout).toHaveBeenCalled(); expect( stripeMock.redirectToCheckout.mock.calls[0][0].billingAddressCollection ).toBe('required'); }); it('should send correct shippingAddressCollection', () => { const wrapper = createWrapper({ allowedCountries: ['US', 'CA'] }); const { result } = renderHook(() => useStripeCart(), { wrapper }); result.current.redirectToCheckout(); expect(stripeMock.redirectToCheckout).toHaveBeenCalled(); expect( stripeMock.redirectToCheckout.mock.calls[0][0].shippingAddressCollection .allowedCountries ).toEqual(['US', 'CA']); });
<<<<<<< const [channels, setChannels] = useState(/** @type {Channel[]} */ ([])); ======= const [channels, setChannels] = useState([]); >>>>>>> const [channels, setChannels] = useState(/** @type {Channel[]} */ ([])); <<<<<<< /** * @param {string} [queryType] */ ======= >>>>>>> /** * @param {string} [queryType] */ <<<<<<< const channelQueryResponse = await client.queryChannels(filters, sort, { ...newOptions, offset, }); const newChannels = [...channels, ...channelQueryResponse]; ======= const channelQueryResponse = await client.queryChannels( filters, sort, newOptions, ); let newChannels; if (queryType === 'reload') { newChannels = channelQueryResponse; } else { newChannels = [...channels, ...channelQueryResponse]; } >>>>>>> const channelQueryResponse = await client.queryChannels( filters, sort || {}, newOptions, ); let newChannels; if (queryType === 'reload') { newChannels = channelQueryResponse; } else { newChannels = [...channels, ...channelQueryResponse]; } <<<<<<< setOffset(newChannels.length); ======= setRefreshing(false); >>>>>>> setRefreshing(false); <<<<<<< if (channels.length <= (options?.limit || MAX_QUERY_CHANNELS_LIMIT)) { activeChannelHandler?.(newChannels, setChannels); ======= if (offset === 0) { activeChannelHandler(newChannels); >>>>>>> if (offset === 0 && activeChannelHandler) { activeChannelHandler(newChannels, setChannels);
<<<<<<< default_lifetime = 3600, options = { "debug": false }; ======= default_lifetime = 3600, >>>>>>> default_lifetime = 3600, options = { "debug": false }, <<<<<<< /* * ------ SECTION: Utilities */ /* * Returns a random string used for state */ var uuid = function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } /** * A log wrapper, that only logs if logging is turned on in the config * @param {string} msg Log message */ var log = function(msg) { if (!options.debug) return; if (!console) return; if (!console.log) return; // console.log("LOG(), Arguments", arguments, msg) if (arguments.length > 1) { console.log(arguments); } else { console.log(msg); } } /** * Set the global options. */ var setOptions = function(opts) { if (!opts) return; for(var k in opts) { if (opts.hasOwnProperty(k)) { options[k] = opts[k]; } } log("Options is set to ", options); } /* * Takes an URL as input and a params object. * Each property in the params is added to the url as query string parameters */ var encodeURL = function(url, params) { var res = url; var k, i = 0; var firstSeparator = (url.indexOf("?") === -1) ? '?' : '&'; for(k in params) { res += (i++ === 0 ? firstSeparator : '&') + encodeURIComponent(k) + '=' + encodeURIComponent(params[k]); } return res; } ======= internalStates = []; >>>>>>> internalStates = []; /* * ------ SECTION: Utilities */ /* * Returns a random string used for state */ var uuid = function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } /** * A log wrapper, that only logs if logging is turned on in the config * @param {string} msg Log message */ var log = function(msg) { if (!options.debug) return; if (!console) return; if (!console.log) return; // console.log("LOG(), Arguments", arguments, msg) if (arguments.length > 1) { console.log(arguments); } else { console.log(msg); } } /** * Set the global options. */ var setOptions = function(opts) { if (!opts) return; for(var k in opts) { if (opts.hasOwnProperty(k)) { options[k] = opts[k]; } } log("Options is set to ", options); } /* * Takes an URL as input and a params object. * Each property in the params is added to the url as query string parameters */ var encodeURL = function(url, params) { var res = url; var k, i = 0; var firstSeparator = (url.indexOf("?") === -1) ? '?' : '&'; for(k in params) { res += (i++ === 0 ? firstSeparator : '&') + encodeURIComponent(k) + '=' + encodeURIComponent(params[k]); } return res; } <<<<<<< var saveState = function(state, obj) { log("SaveState (" + state+ ")"); ======= Api_default_storage.prototype.saveState = function (state, obj) { >>>>>>> Api_default_storage.prototype.saveState = function (state, obj) { <<<<<<< var getState = function(state) { log("getState (" + state+ ")"); ======= Api_default_storage.prototype.getState = function(state) { // console.log("getState (" + state+ ")"); >>>>>>> Api_default_storage.prototype.getState = function(state) { // log("getState (" + state+ ")"); <<<<<<< var saveTokens = function(provider, tokens) { log("Save Tokens (" + provider+ ")"); ======= Api_default_storage.prototype.saveTokens = function(provider, tokens) { // console.log("Save Tokens (" + provider+ ")"); >>>>>>> Api_default_storage.prototype.saveTokens = function(provider, tokens) { // log("Save Tokens (" + provider+ ")"); <<<<<<< var getTokens = function(provider) { log("Get Tokens (" + provider+ ")"); ======= Api_default_storage.prototype.getTokens = function(provider) { // console.log("Get Tokens (" + provider+ ")"); >>>>>>> Api_default_storage.prototype.getTokens = function(provider) { // log("Get Tokens (" + provider+ ")"); <<<<<<< log(atoken); ======= if (internalStates[atoken.state] && typeof internalStates[atoken.state] === 'function') { // console.log("InternalState is set, calling it now!"); internalStates[atoken.state](); delete internalStates[atoken.state]; } if (typeof callback === 'function') { callback(); } // console.log(atoken); >>>>>>> log(atoken); if (internalStates[atoken.state] && typeof internalStates[atoken.state] === 'function') { // log("InternalState is set, calling it now!"); internalStates[atoken.state](); delete internalStates[atoken.state]; } if (typeof callback === 'function') { callback(); } // log(atoken); <<<<<<< log("Saving state [" + state+ "]"); log(JSON.parse(JSON.stringify(request))); saveState(state, request); redirect(authurl); ======= // console.log("Saving state [" + state+ "]"); // console.log(JSON.parse(JSON.stringify(request))); api_storage.saveState(state, request); api_redirect(authurl); >>>>>>> log("Saving state [" + state+ "]"); log(JSON.parse(JSON.stringify(request))); api_storage.saveState(state, request); api_redirect(authurl); <<<<<<< var def = jso_findDefaultEntry(c); log("jso_configure() about to check for token for this entry", def); jso_checkfortoken(def); ======= exp.jso_checkfortoken(jso_findDefaultEntry(c)); >>>>>>> var def = jso_findDefaultEntry(c); log("jso_configure() about to check for token for this entry", def); exp.jso_checkfortoken(def); <<<<<<< log("=====> Processing provider [" + key + "]"); log("=] Config"); log(config[key]); log("=] Tokens") log(getTokens(key)); ======= console.log("=====> Processing provider [" + key + "]"); console.log("=] Config"); console.log(config[key]); console.log("=] Tokens") console.log(api_storage.getTokens(key)); >>>>>>> log("=====> Processing provider [" + key + "]"); log("=] Config"); log(config[key]); log("=] Tokens") log(getTokens(key)); <<<<<<< if (typeof $ === 'undefined') return; /* * From now on, we only perform tasks that require jQuery. * Like adding the $.oajax function. */ ======= exp.jso_registerRedirectHandler = function(callback) { api_redirect = callback; }; exp.jso_registerStorageHandler = function(object) { api_storage = object; }; >>>>>>> exp.jso_registerRedirectHandler = function(callback) { api_redirect = callback; }; exp.jso_registerStorageHandler = function(object) { api_storage = object; }; /* * From now on, we only perform tasks that require jQuery. * Like adding the $.oajax function. */ if (typeof $ === 'undefined') return; <<<<<<< log("Token expired. About to delete this token"); log(token); wipeTokens(providerid); ======= console.log("Token expired. About to delete this token"); console.log(token); api_storage.wipeTokens(providerid); >>>>>>> log("Token expired. About to delete this token"); log(token); api_storage.wipeTokens(providerid);
<<<<<<< status_stub = sinon.stub(status, 'get_status').callsFake((cb) => { return cb(null, {}); }); ======= server_stub = sinon.stub(server, 'create_server').callsFake(() => { return; }); >>>>>>> status_stub = sinon.stub(status, 'get_status').callsFake((cb) => { return cb(null, {}); }); server_stub = sinon.stub(server, 'create_server').callsFake(() => { return; });
<<<<<<< "INCLUDE_INSTRUCTIONS": "Les polices Edge Web Fonts sont chargées dans le navigateur de l’utilisateur via JavaScript. Pour vérifier que les polices sont correctement chargées, vous devez ajouter une balise de script à votre document HTML. Copiez la balise de script qui suit, et collez-la dans tous les fichiers HTML qui font référence à ce fichier CSS :", ======= "WEBFONTS_OFFLINE": "L’extension Edge Web Fonts est désactivée car le serveur de Web Fonts est inaccessible. Vérifiez votre connexion Internet ou réessayez ultérieurement.", "INCLUDE_INSTRUCTIONS_1": "Les polices Edge Web Fonts sont chargées dans le navigateur de l’utilisateur via JavaScript. Pour vérifier que les polices sont correctement chargées, vous devez ajouter une balise de script à votre document HTML.", "INCLUDE_INSTRUCTIONS_2": "Copiez la balise de script qui suit, et collez-la dans tous les fichiers HTML qui font référence à ce fichier CSS :", >>>>>>> "WEBFONTS_OFFLINE": "L’extension Edge Web Fonts est désactivée car le serveur de Web Fonts est inaccessible. Vérifiez votre connexion Internet ou réessayez ultérieurement.", "INCLUDE_INSTRUCTIONS": "Les polices Edge Web Fonts sont chargées dans le navigateur de l’utilisateur via JavaScript. Pour vérifier que les polices sont correctement chargées, vous devez ajouter une balise de script à votre document HTML. Copiez la balise de script qui suit, et collez-la dans tous les fichiers HTML qui font référence à ce fichier CSS :",
<<<<<<< ======= // use the emitter to emit the appropriate events >>>>>>> // use the emitter to emit the appropriate events <<<<<<< 'are json': function(error, result) { assert.isObject(result); }, 'have the right structure': function(error, result) { assert.deepEqual(result, {is: {some: 'xml'}}); ======= 'works': function(error, result) { assert.isObject(state); }, 'has the right structure': function(error, result) { assertObject(state.this) >>>>>>> 'are json': function(error, result) { assert.isObject(result); }, 'have the right structure': function(error, result) { assert.deepEqual(result, {is: {some: 'xml'}});
<<<<<<< const fs = require('fs'); ======= const prereleaseRegex = /\d+\.\d+\.\d+-pre-b\d+/; >>>>>>> const fs = require('fs'); const prereleaseRegex = /\d+\.\d+\.\d+-pre-b\d+/;
<<<<<<< modulus.commands.addons = require('./commands/addOn'); ======= modulus.commands.mongo = require('./commands/mongo'); modulus.commands.config = require('./commands/config') >>>>>>> modulus.commands.addons = require('./commands/addOn'); modulus.commands.mongo = require('./commands/mongo'); modulus.commands.config = require('./commands/config') <<<<<<< require('./routes/addOn')(modulus), ======= require('./routes/mongo')(modulus), require('./routes/config')(modulus), >>>>>>> require('./routes/addOn')(modulus), require('./routes/mongo')(modulus), require('./routes/config')(modulus),
<<<<<<< // http://www.graphicsmagick.org/GraphicsMagick.html#details-flatten proto.flatten = function flatten () { return this.out("-flatten"); } ======= // http://www.graphicsmagick.org/GraphicsMagick.html#details-background proto.background = function background (color) { return this.out("-background", color); } >>>>>>> // http://www.graphicsmagick.org/GraphicsMagick.html#details-flatten proto.flatten = function flatten () { return this.out("-flatten"); } // http://www.graphicsmagick.org/GraphicsMagick.html#details-background proto.background = function background (color) { return this.out("-background", color); }
<<<<<<< import { types as CompanyTypes, queries as CompanyQueries, mutations as CompanyMutations, } from './company'; import { types as ChannelTypes, queries as ChannelQueries } from './channel'; ======= import { types as ChannelTypes, queries as ChannelQueries, mutations as ChannelMutations, } from './channel'; >>>>>>> import { types as CompanyTypes, queries as CompanyQueries, mutations as CompanyMutations, } from './company'; import { types as ChannelTypes, queries as ChannelQueries, mutations as ChannelMutations, } from './channel'; <<<<<<< import { types as FieldTypes, queries as FieldQueries, mutations as FieldMutations } from './field'; import { types as FormTypes, queries as FormQueries } from './form'; ======= import { types as FormTypes, queries as FormQueries, mutations as FormMutatons } from './form'; >>>>>>> import { types as FieldTypes, queries as FieldQueries, mutations as FieldMutations } from './field'; import { types as FormTypes, queries as FormQueries, mutations as FormMutatons } from './form'; <<<<<<< ${InternalNoteMutations} ${CustomerMutations} ${SegmentMutations} ${FieldMutations} ======= ${ChannelMutations} ${FormMutatons} ${IntegrationMutations} ${NotificationMutations} >>>>>>> ${InternalNoteMutations} ${CustomerMutations} ${SegmentMutations} ${FieldMutations} ${ChannelMutations} ${FormMutatons} ${IntegrationMutations} ${NotificationMutations}
<<<<<<< }; export const MESSENGER_KINDS = { CHAT: 'chat', NOTE: 'note', POST: 'post', ALL_LIST: ['chat', 'note', 'post'], }; export const SENT_AS_CHOICES = { BADGE: 'badge', SNIPPET: 'snippet', FULL_MESSAGE: 'fullMessage', ALL_LIST: ['badge', 'snippet', 'fullMessage'], }; export const MESSAGE_KINDS = { AUTO: 'auto', VISITOR_AUTO: 'visitorAuto', MANUAL: 'manual', ALL_LIST: ['auto', 'visitorAuto', 'manual'], }; export const METHODS = { MESSENGER: 'messenger', EMAIL: 'email', ALL_LIST: ['messenger', 'email'], ======= }; export const FORM_LOAD_TYPES = { SHOUTBOX: 'shoutbox', POPUP: 'popup', EMBEDDED: 'embedded', ALL: ['', 'shoutbox', 'popup', 'embedded'], }; export const FORM_SUCCESS_ACTIONS = { EMAIL: 'email', REDIRECT: 'redirect', ONPAGE: 'onPage', ALL_LIST: ['', 'email', 'redirect', 'onPage'], }; export const KIND_CHOICES = { MESSENGER: 'messenger', FORM: 'form', TWITTER: 'twitter', FACEBOOK: 'facebook', ALL: ['messenger', 'form', 'twitter', 'facebook'], }; // module constants export const MODULES = { CHANNEL_MEMBERS_CHANGE: 'channelMembersChange', CONVERSATION_ADD_MESSAGE: 'conversationAddMessage', CONVERSATION_ASSIGNEE_CHANGE: 'conversationAssigneeChange', CONVERSATION_STATE_CHANGE: 'conversationStateChange', ALL: [ 'channelMembersChange', 'conversationAddMessage', 'conversationAssigneeChange', 'conversationStateChange', ], }; export const FORM_FIELDS = { TYPES: { INPUT: 'input', TEXT_AREA: 'textarea', RADIO: 'radio', CHECK: 'check', SELECT: 'select', DIVIDER: 'divider', EMAIL: 'email', FIRST_NAME: 'firstName', LAST_NAME: 'lastName', ALL: [ 'input', 'textarea', 'radio', 'check', 'select', 'divider', 'email', 'firstName', 'lastName', ], }, VALIDATION: { BLANK: '', NUMBER: 'number', DATE: 'date', EMAIL: 'email', ALL: ['', 'number', 'date', 'email'], }, }; // messenger data availability constants export const MESSENGER_DATA_AVAILABILITY = { MANUAL: 'manual', AUTO: 'auto', ALL: ['manual', 'auto'], >>>>>>> }; export const MESSENGER_KINDS = { CHAT: 'chat', NOTE: 'note', POST: 'post', ALL_LIST: ['chat', 'note', 'post'], }; export const SENT_AS_CHOICES = { BADGE: 'badge', SNIPPET: 'snippet', FULL_MESSAGE: 'fullMessage', ALL_LIST: ['badge', 'snippet', 'fullMessage'], }; export const MESSAGE_KINDS = { AUTO: 'auto', VISITOR_AUTO: 'visitorAuto', MANUAL: 'manual', ALL_LIST: ['auto', 'visitorAuto', 'manual'], }; export const METHODS = { MESSENGER: 'messenger', EMAIL: 'email', ALL_LIST: ['messenger', 'email'], }; export const FORM_LOAD_TYPES = { SHOUTBOX: 'shoutbox', POPUP: 'popup', EMBEDDED: 'embedded', ALL: ['', 'shoutbox', 'popup', 'embedded'], }; export const FORM_SUCCESS_ACTIONS = { EMAIL: 'email', REDIRECT: 'redirect', ONPAGE: 'onPage', ALL_LIST: ['', 'email', 'redirect', 'onPage'], }; export const KIND_CHOICES = { MESSENGER: 'messenger', FORM: 'form', TWITTER: 'twitter', FACEBOOK: 'facebook', ALL: ['messenger', 'form', 'twitter', 'facebook'], }; // module constants export const MODULES = { CHANNEL_MEMBERS_CHANGE: 'channelMembersChange', CONVERSATION_ADD_MESSAGE: 'conversationAddMessage', CONVERSATION_ASSIGNEE_CHANGE: 'conversationAssigneeChange', CONVERSATION_STATE_CHANGE: 'conversationStateChange', ALL: [ 'channelMembersChange', 'conversationAddMessage', 'conversationAssigneeChange', 'conversationStateChange', ], }; export const FORM_FIELDS = { TYPES: { INPUT: 'input', TEXT_AREA: 'textarea', RADIO: 'radio', CHECK: 'check', SELECT: 'select', DIVIDER: 'divider', EMAIL: 'email', FIRST_NAME: 'firstName', LAST_NAME: 'lastName', ALL: [ 'input', 'textarea', 'radio', 'check', 'select', 'divider', 'email', 'firstName', 'lastName', ], }, VALIDATION: { BLANK: '', NUMBER: 'number', DATE: 'date', EMAIL: 'email', ALL: ['', 'number', 'date', 'email'], }, }; // messenger data availability constants export const MESSENGER_DATA_AVAILABILITY = { MANUAL: 'manual', AUTO: 'auto', ALL: ['manual', 'auto'],
<<<<<<< import { types as InsightTypes, queries as InsightQueries } from './insight'; ======= import { types as KnowledgeBaseTypes, queries as KnowledgeBaseQueries } from './knowledgeBase'; >>>>>>> import { types as InsightTypes, queries as InsightQueries } from './insight'; import { types as KnowledgeBaseTypes, queries as KnowledgeBaseQueries } from './knowledgeBase'; <<<<<<< ${InsightTypes} ======= ${KnowledgeBaseTypes} >>>>>>> ${InsightTypes} ${KnowledgeBaseTypes} <<<<<<< ${InsightQueries} ======= ${KnowledgeBaseQueries} >>>>>>> ${InsightQueries} ${KnowledgeBaseQueries}
<<<<<<< import conversations from './conversations'; ======= import conversation from './conversation'; import tags from './tags'; import engages from './engages'; >>>>>>> import conversations from './conversations'; import tags from './tags'; import engages from './engages'; <<<<<<< ...conversations, ======= ...conversation, ...tags, ...engages, >>>>>>> ...conversations, ...tags, ...engages,
<<<<<<< import Random from 'meteor-random'; import { COC_CONTENT_TYPES } from '../../data/constants'; ======= import { INTERNAL_NOTE_CONTENT_TYPES } from '../../data/constants'; import { field } from './utils'; >>>>>>> import { field } from './utils'; import { COC_CONTENT_TYPES } from '../../data/constants'; <<<<<<< enum: COC_CONTENT_TYPES.ALL, }, contentTypeId: String, content: { ======= enum: INTERNAL_NOTE_CONTENT_TYPES.ALL, }), contentTypeId: field({ type: String }), content: field({ >>>>>>> enum: COC_CONTENT_TYPES.ALL, }), contentTypeId: field({ type: String }), content: field({
<<<<<<< export const FACEBOOK_DATA_KINDS = { FEED: 'feed', MESSENGER: 'messenger', ALL_LIST: ['feed', 'messenger'], }; ======= export const MESSENGER_KINDS = { CHAT: 'chat', NOTE: 'note', POST: 'post', ALL_LIST: ['chat', 'note', 'post'], }; export const SENT_AS_CHOICES = { BADGE: 'badge', SNIPPET: 'snippet', FULL_MESSAGE: 'fullMessage', ALL_LIST: ['badge', 'snippet', 'fullMessage'], }; export const MESSAGE_KINDS = { AUTO: 'auto', VISITOR_AUTO: 'visitorAuto', MANUAL: 'manual', ALL_LIST: ['auto', 'visitorAuto', 'manual'], }; export const METHODS = { MESSENGER: 'messenger', EMAIL: 'email', ALL_LIST: ['messenger', 'email'], }; >>>>>>> export const FACEBOOK_DATA_KINDS = { FEED: 'feed', MESSENGER: 'messenger', ALL_LIST: ['feed', 'messenger'], }; export const MESSENGER_KINDS = { CHAT: 'chat', NOTE: 'note', POST: 'post', ALL_LIST: ['chat', 'note', 'post'], }; export const SENT_AS_CHOICES = { BADGE: 'badge', SNIPPET: 'snippet', FULL_MESSAGE: 'fullMessage', ALL_LIST: ['badge', 'snippet', 'fullMessage'], }; export const MESSAGE_KINDS = { AUTO: 'auto', VISITOR_AUTO: 'visitorAuto', MANUAL: 'manual', ALL_LIST: ['auto', 'visitorAuto', 'manual'], }; export const METHODS = { MESSENGER: 'messenger', EMAIL: 'email', ALL_LIST: ['messenger', 'email'], };
<<<<<<< InternalNotes, Customers, ======= ConversationMessages, Conversations, Integrations, Tags, Segments, EngageMessages, >>>>>>> InternalNotes, Customers, ConversationMessages, Conversations, Integrations, Tags, Segments, EngageMessages, <<<<<<< export const segmentFactory = (params = {}) => { const defaultConditions = [ { field: 'messengerData.sessionCount', operator: 'e', value: '10', dateUnit: 'days', type: 'string', }, ]; const segment = new Segments({ name: faker.random.word(), description: params.description || faker.random.word(), subOf: params.subOf || 'DFSAFDFDSFDSF', color: params.color || '#ffff', connector: params.connector || 'any', conditions: params.conditions || defaultConditions, }); return segment.save(); }; export const internalNoteFactory = (params = {}) => { const internalNote = new InternalNotes({ contentType: params.contentType || 'customer', contentTypeId: params.contentTypeId || 'DFASFDFSDAFDF', content: params.content || faker.random.word(), }); return internalNote.save(); }; export const companyFactory = (params = {}) => { const company = new Companies({ name: params.name || faker.random.word(), size: params.size || faker.random.number(), industry: params.industry || Random.id(), website: params.website || Random.id(), }); return company.save(); }; export const customerFactory = (params = {}) => { const customer = new Customers({ name: params.name || faker.random.word(), email: params.email || faker.internet.email(), phone: params.phone || faker.random.word(), messengerData: params.messengerData || {}, customFieldsData: params.customFieldsData || {}, }); return customer.save(); }; export const fieldFactory = (params = {}) => { const field = new Fields({ type: params.type || 'input', validation: params.validation || 'number', text: params.text || faker.random.word(), description: params.description || faker.random.word(), isRequired: params.isRequired || false, order: params.order || 0, }); return field.save(); }; export const integrationFactory = params => { ======= export const conversationFactory = (params = {}) => { const conversation = new Conversations({ content: params.content || faker.lorem.sentence(), customerId: params.customerId || Random.id(), integrationId: params.integrationId || Random.id(), status: CONVERSATION_STATUSES.NEW, }); return conversation.save(); }; export const conversationMessageFactory = (params = {}) => { const conversationMessage = new ConversationMessages({ content: params.content || faker.random.word(), attachments: {}, mentionedUserIds: params.mentionedUserIds || [Random.id()], conversationId: params.conversationId || Random.id(), internal: params.internal || true, customerId: params.customerId || Random.id(), userId: params.userId || Random.id(), createdAt: new Date(), isCustomerRead: params.isCustomerRead || true, engageData: params.engageData || {}, formWidgetData: params.formWidgetData || {}, facebookData: params.facebookData || {}, }); return conversationMessage.save(); }; export const integrationFactory = (params = {}) => { >>>>>>> export const segmentFactory = (params = {}) => { const defaultConditions = [ { field: 'messengerData.sessionCount', operator: 'e', value: '10', dateUnit: 'days', type: 'string', }, ]; const segment = new Segments({ name: faker.random.word(), description: params.description || faker.random.word(), subOf: params.subOf || 'DFSAFDFDSFDSF', color: params.color || '#ffff', connector: params.connector || 'any', conditions: params.conditions || defaultConditions, }); return segment.save(); }; export const internalNoteFactory = (params = {}) => { const internalNote = new InternalNotes({ contentType: params.contentType || 'customer', contentTypeId: params.contentTypeId || 'DFASFDFSDAFDF', content: params.content || faker.random.word(), }); return internalNote.save(); }; export const companyFactory = (params = {}) => { const company = new Companies({ name: params.name || faker.random.word(), size: params.size || faker.random.number(), industry: params.industry || Random.id(), website: params.website || Random.id(), }); return company.save(); }; export const customerFactory = (params = {}) => { const customer = new Customers({ name: params.name || faker.random.word(), email: params.email || faker.internet.email(), phone: params.phone || faker.random.word(), messengerData: params.messengerData || {}, customFieldsData: params.customFieldsData || {}, }); return customer.save(); }; export const fieldFactory = (params = {}) => { const field = new Fields({ type: params.type || 'input', validation: params.validation || 'number', text: params.text || faker.random.word(), description: params.description || faker.random.word(), isRequired: params.isRequired || false, order: params.order || 0, }); return field.save(); }; export const conversationFactory = (params = {}) => { const conversation = new Conversations({ content: params.content || faker.lorem.sentence(), customerId: params.customerId || Random.id(), integrationId: params.integrationId || Random.id(), status: CONVERSATION_STATUSES.NEW, }); return conversation.save(); }; export const conversationMessageFactory = (params = {}) => { const conversationMessage = new ConversationMessages({ content: params.content || faker.random.word(), attachments: {}, mentionedUserIds: params.mentionedUserIds || [Random.id()], conversationId: params.conversationId || Random.id(), internal: params.internal || true, customerId: params.customerId || Random.id(), userId: params.userId || Random.id(), createdAt: new Date(), isCustomerRead: params.isCustomerRead || true, engageData: params.engageData || {}, formWidgetData: params.formWidgetData || {}, facebookData: params.facebookData || {}, }); return conversationMessage.save(); }; export const integrationFactory = (params = {}) => {
<<<<<<< import { Users, Brands, EmailTemplates, ResponseTemplates, ConversationMessages, Conversations, } from './models'; import { CONVERSATION_STATUSES } from '../data/constants'; ======= import { Users, Integrations, Brands, EmailTemplates, ResponseTemplates, Tags, Forms, FormFields, NotificationConfigurations, Notifications, } from './models'; >>>>>>> import { Users, Brands, EmailTemplates, ResponseTemplates, ConversationMessages, Conversations, Integrations, Tags, Forms, FormFields, NotificationConfigurations, Notifications, } from './models'; <<<<<<< }; export const conversationFactory = (params = {}) => { const conversation = new Conversations({ content: params.content || faker.lorem.sentence(), customerId: params.customerId || Random.id(), integrationId: params.integrationId || Random.id(), status: CONVERSATION_STATUSES.NEW, }); return conversation.save(); }; export const conversationMessageFactory = (params = {}) => { const conversationMessage = new ConversationMessages({ content: params.content || faker.random.word(), attachments: {}, mentionedUserIds: params.mentionedUserIds || [Random.id()], conversationId: params.conversationId || Random.id(), internal: params.internal || true, customerId: params.customerId || Random.id(), userId: params.userId || Random.id(), createdAt: new Date(), isCustomerRead: params.isCustomerRead || true, engageData: params.engageData || {}, formWidgetData: params.formWidgetData || {}, facebookData: params.facebookData || {}, }); return conversationMessage.save(); ======= }; export const integrationFactory = params => { const kind = params.kind || 'messenger'; return Integrations.create({ name: faker.random.word(), kind: kind, brandId: params.brandId || Random.id(), formId: params.formId || Random.id(), messengerData: params.messengerData || { welcomeMessage: 'welcome' }, formData: params.formData === 'form' ? params.formData : kind === 'form' ? { thankContent: 'thankContent' } : null, }); }; export const tagsFactory = (params = {}) => { const tag = new Tags({ name: faker.random.word(), type: params.type || faker.random.word(), colorCode: params.colorCode || Random.id(), userId: Random.id(), }); return tag.save(); }; export const formFactory = async ({ title, code, description, createdUserId }) => { return Forms.createForm( { title: title || faker.random.word(), description: description || faker.random.word(), code: code || Random.id(), }, createdUserId || (await userFactory({})), ); }; export const formFieldFactory = (formId, params) => { return FormFields.createFormField(formId || Random.id(), { type: params.type || 'input', name: faker.random.word(), validation: params.validation || 'number', text: faker.random.word(), description: faker.random.word(), isRequired: params.isRequired || false, number: faker.random.word(), }); }; export const notificationConfigurationFactory = params => { let { isAllowed } = params; if (isAllowed == null) { isAllowed = true; } return NotificationConfigurations.createOrUpdateConfiguration( { notifType: params.notifType || MODULES.CHANNEL_MEMBERS_CHANGE, // which module's type it is. For example: indocuments isAllowed, }, params.user || userFactory({}), ); }; export const notificationFactory = params => { return Notifications.createNotification({ notifType: params.notifType || MODULES.CHANNEL_MEMBERS_CHANGE, createdUser: params.createdUser || userFactory({}), title: params.title || 'new Notification title', content: params.content || 'new Notification content', link: params.link || 'new Notification link', receiver: params.receiver || userFactory({}), }); >>>>>>> }; export const conversationFactory = (params = {}) => { const conversation = new Conversations({ content: params.content || faker.lorem.sentence(), customerId: params.customerId || Random.id(), integrationId: params.integrationId || Random.id(), status: CONVERSATION_STATUSES.NEW, }); return conversation.save(); }; export const conversationMessageFactory = (params = {}) => { const conversationMessage = new ConversationMessages({ content: params.content || faker.random.word(), attachments: {}, mentionedUserIds: params.mentionedUserIds || [Random.id()], conversationId: params.conversationId || Random.id(), internal: params.internal || true, customerId: params.customerId || Random.id(), userId: params.userId || Random.id(), createdAt: new Date(), isCustomerRead: params.isCustomerRead || true, engageData: params.engageData || {}, formWidgetData: params.formWidgetData || {}, facebookData: params.facebookData || {}, }); return conversationMessage.save(); }; export const integrationFactory = params => { const kind = params.kind || 'messenger'; return Integrations.create({ name: faker.random.word(), kind: kind, brandId: params.brandId || Random.id(), formId: params.formId || Random.id(), messengerData: params.messengerData || { welcomeMessage: 'welcome' }, formData: params.formData === 'form' ? params.formData : kind === 'form' ? { thankContent: 'thankContent' } : null, }); }; export const tagsFactory = (params = {}) => { const tag = new Tags({ name: faker.random.word(), type: params.type || faker.random.word(), colorCode: params.colorCode || Random.id(), userId: Random.id(), }); return tag.save(); }; export const formFactory = async ({ title, code, description, createdUserId }) => { return Forms.createForm( { title: title || faker.random.word(), description: description || faker.random.word(), code: code || Random.id(), }, createdUserId || (await userFactory({})), ); }; export const formFieldFactory = (formId, params) => { return FormFields.createFormField(formId || Random.id(), { type: params.type || 'input', name: faker.random.word(), validation: params.validation || 'number', text: faker.random.word(), description: faker.random.word(), isRequired: params.isRequired || false, number: faker.random.word(), }); }; export const notificationConfigurationFactory = params => { let { isAllowed } = params; if (isAllowed == null) { isAllowed = true; } return NotificationConfigurations.createOrUpdateConfiguration( { notifType: params.notifType || MODULES.CHANNEL_MEMBERS_CHANGE, // which module's type it is. For example: indocuments isAllowed, }, params.user || userFactory({}), ); }; export const notificationFactory = params => { return Notifications.createNotification({ notifType: params.notifType || MODULES.CHANNEL_MEMBERS_CHANGE, createdUser: params.createdUser || userFactory({}), title: params.title || 'new Notification title', content: params.content || 'new Notification content', link: params.link || 'new Notification link', receiver: params.receiver || userFactory({}), });
<<<<<<< import insights from './insights'; ======= import knowledgeBase from './knowledgeBase'; >>>>>>> import insights from './insights'; import knowledgeBase from './knowledgeBase'; <<<<<<< ...insights, ======= ...knowledgeBase, >>>>>>> ...insights, ...knowledgeBase,
<<<<<<< ======= Tags, Segments, >>>>>>> <<<<<<< ConversationMessages, Conversations, Integrations, Tags, ======= EngageMessages, Integrations, >>>>>>> ConversationMessages, Conversations, Integrations, Tags, Segments, EngageMessages,
<<<<<<< var on = function on(elem, eventname, selector, handler, onceOnly){ ======= function on(elem, eventname, selector, handler){ >>>>>>> function on(elem, eventname, selector, handler, onceOnly){ <<<<<<< var once = function(elem, eventname, selector, handler){ return Event.on(elem, eventname, selector, handler, true); ======= function once(elem, eventname, selector, handler){ var listener = function listener(event){ handler(event); Event.off(elem, eventname, listener); }; return Event.on(elem, eventname, selector, listener); >>>>>>> var once = function(elem, eventname, selector, handler){ return Event.on(elem, eventname, selector, handler, true); <<<<<<< // console.log(potentialDropTargets.length); ======= >>>>>>> <<<<<<< Event.on('.content', 'mousemove', null, drag); //Event.on('.scratchpad', '', null, endDragInScratchpad); Event.on(document.body, 'mouseup', null, endDrag); ======= Event.on(document, 'mousemove', null, drag); Event.on('.content', 'mouseup', null, endDrag); >>>>>>> Event.on('.content', 'mousemove', null, drag); //Event.on('.scratchpad', '', null, endDragInScratchpad); Event.on(document.body, 'mouseup', null, endDrag); <<<<<<< ======= Event.on(document.body, 'wb-remove', '.block', removeBlock); Event.on(document.body, 'wb-add', '.block', addBlock); Event.on(document.body, 'wb-delete', '.block', deleteBlock); wb.blockRegistry = blockRegistry; >>>>>>> Event.on(document.body, 'wb-remove', '.block', removeBlock); Event.on(document.body, 'wb-add', '.block', addBlock); Event.on(document.body, 'wb-delete', '.block', deleteBlock); wb.blockRegistry = blockRegistry; <<<<<<< // Event.on('.tabbar', 'click', '.chrome_tab', tabSelect); if (document.body.clientWidth < 361){ // console.log('mobile view'); Event.on('.show-files', 'click', null, showFiles); Event.on('.show-blocks', 'click', null, showBlocks); Event.on('.show-script', 'click', null, showScript); Event.on('.show-result', 'click', null, showResult); document.querySelector('.show-script').classList.add('current-button'); document.querySelector('.workspace').classList.add('current-view'); } if (document.body.clientWidth > 360){ // console.log('desktop view'); Event.on(document.body, 'change', 'input', updateScriptsView); Event.on(document.body, 'wb-modified', null, updateScriptsView); } ======= Event.on('.tabbar', 'click', '.chrome_tab', tabSelect); wb.showWorkspace = showWorkspace; wb.menu = menu; >>>>>>> // Event.on('.tabbar', 'click', '.chrome_tab', tabSelect); if (document.body.clientWidth < 361){ // console.log('mobile view'); Event.on('.show-files', 'click', null, showFiles); Event.on('.show-blocks', 'click', null, showBlocks); Event.on('.show-script', 'click', null, showScript); Event.on('.show-result', 'click', null, showResult); document.querySelector('.show-script').classList.add('current-button'); document.querySelector('.workspace').classList.add('current-view'); } if (document.body.clientWidth > 360){ // console.log('desktop view'); Event.on(document.body, 'change', 'input', updateScriptsView); Event.on(document.body, 'wb-modified', null, updateScriptsView); } <<<<<<< Event.on('.clear_scripts', 'click', null, wb.clearScripts); Event.on('.edit-script', 'click', null, function(event){ wb.historySwitchState('editor'); }); Event.on(document.body, 'click', '.load-example', function(evt){ console.log('load example ' + evt.target.dataset.example); ======= function loadExample(event){ >>>>>>> function loadExample(event){ <<<<<<< Event.on('.save_scripts', 'click', null, wb.saveCurrentScriptsToGist); Event.on('.download_scripts', 'click', null, wb.createDownloadUrl); Event.on('.load_from_gist', 'click', null, wb.loadScriptsFromGistId); Event.on('.restore_scripts', 'click', null, wb.loadScriptsFromFilesystem); wb.loaded = false; ======= >>>>>>> <<<<<<< Event.once(document.body, 'wb-workspace-initialized', null, wb.initializeDragHandlers); function handleDragover(evt){ ======= function handleDragover(event){ >>>>>>> function handleDragover(evt){ <<<<<<< function runFullSize(){ ['#block_menu', '.workspace', '.scripts_text_view'].forEach(function(sel){ wb.hide(wb.find(document.body, sel)); }); wb.show(wb.find(document.body, '.stage')); } function runWithLayout(){ ['#block_menu', '.workspace'].forEach(function(sel){ wb.show(wb.find(document.body, sel)); }); ['stage', 'scripts_text_view', 'tutorial', 'scratchpad', 'scripts_workspace'].forEach(function(name){ toggleComponent({detail: {name: name, state: wb.toggleState[name]}}); }); } function toggleComponent(evt){ var component = wb.find(document.body, '.' + evt.detail.name); if (!component) return; evt.detail.state ? wb.show(component) : wb.hide(component); var results = wb.find(document.body, '.results'); // Special cases switch(evt.detail.name){ case 'stage': if (evt.detail.state){ wb.show(results); }else{ wb.clearStage(); if (!wb.toggleState.scripts_text_view){ wb.hide(results); } } break; case 'scripts_text_view': if (evt.detail.state){ wb.show(results); wb.updateScriptsView(); }else{ if (!wb.toggleState.stage){ wb.hide(results); } } break; case 'tutorial': case 'scratchpad': case 'scripts_workspace': if (! (wb.toggleState.tutorial || wb.toggleState.scratchpad || wb.toggleState.scripts_workspace)){ wb.hide(wb.find(document.body, '.workspace')); }else{ wb.show(wb.find(document.body, '.workspace')); } default: // do nothing break; } if (wb.toggleState.stage){ // restart script on any toggle // so it runs at the new size wb.runCurrentScripts(); } } Event.on(document.body, 'wb-toggle', null, toggleComponent); window.addEventListener('popstate', function(evt){ console.log('popstate event'); ======= window.addEventListener('popstate', function(event){ // console.log('popstate event'); >>>>>>> function runFullSize(){ ['#block_menu', '.workspace', '.scripts_text_view'].forEach(function(sel){ wb.hide(wb.find(document.body, sel)); }); wb.show(wb.find(document.body, '.stage')); } function runWithLayout(){ ['#block_menu', '.workspace'].forEach(function(sel){ wb.show(wb.find(document.body, sel)); }); ['stage', 'scripts_text_view', 'tutorial', 'scratchpad', 'scripts_workspace'].forEach(function(name){ toggleComponent({detail: {name: name, state: wb.toggleState[name]}}); }); } function toggleComponent(evt){ var component = wb.find(document.body, '.' + evt.detail.name); if (!component) return; evt.detail.state ? wb.show(component) : wb.hide(component); var results = wb.find(document.body, '.results'); // Special cases switch(evt.detail.name){ case 'stage': if (evt.detail.state){ wb.show(results); }else{ wb.clearStage(); if (!wb.toggleState.scripts_text_view){ wb.hide(results); } } break; case 'scripts_text_view': if (evt.detail.state){ wb.show(results); wb.updateScriptsView(); }else{ if (!wb.toggleState.stage){ wb.hide(results); } } break; case 'tutorial': case 'scratchpad': case 'scripts_workspace': if (! (wb.toggleState.tutorial || wb.toggleState.scratchpad || wb.toggleState.scripts_workspace)){ wb.hide(wb.find(document.body, '.workspace')); }else{ wb.show(wb.find(document.body, '.workspace')); } default: // do nothing break; } if (wb.toggleState.stage){ // restart script on any toggle // so it runs at the new size wb.runCurrentScripts(); } } Event.on(document.body, 'wb-toggle', null, toggleComponent); window.addEventListener('popstate', function(evt){ console.log('popstate event'); <<<<<<< }); ======= }, false); Event.on('.clear_scripts', 'click', null, clearScripts); Event.on('.edit-script', 'click', null, function(event){ wb.historySwitchState('editor'); }); Event.on('.content', 'click', '.load-example', loadExample); Event.on(document.body, 'wb-state-change', null, handleStateChange); Event.on('.save_scripts', 'click', null, wb.saveCurrentScriptsToGist); Event.on('.download_scripts', 'click', null, wb.createDownloadUrl); Event.on('.load_from_gist', 'click', null, wb.loadScriptsFromGistId); Event.on('.restore_scripts', 'click', null, wb.loadScriptsFromFilesystem); Event.on('.workspace', 'click', '.disclosure', disclosure); Event.on('.workspace', 'dblclick', '.locals .name', wb.changeName); Event.on('.workspace', 'keypress', 'input', wb.resize); Event.on('.workspace', 'change', 'input, select', function(event){ Event.trigger(document.body, 'wb-modified', {block: event.wbTarget, type: 'valueChanged'}); }); Event.on(document.body, 'wb-script-loaded', null, handleScriptLoad); Event.on(document.body, 'wb-modified', null, handleScriptModify); wb.language = location.pathname.match(/\/([^/.]*)\.html/)[1]; wb.loaded = false; wb.clearScripts = clearScripts; wb.historySwitchState = historySwitchState; wb.createWorkspace = createWorkspace; wb.wireUpWorkspace = wireUpWorkspace; >>>>>>> }, false); Event.once(document.body, 'wb-workspace-initialized', null, wb.initializeDragHandlers); Event.on('.clear_scripts', 'click', null, clearScripts); Event.on('.edit-script', 'click', null, function(event){ wb.historySwitchState('editor'); }); Event.on('.content', 'click', '.load-example', loadExample); Event.on(document.body, 'wb-state-change', null, handleStateChange); Event.on('.save_scripts', 'click', null, wb.saveCurrentScriptsToGist); Event.on('.download_scripts', 'click', null, wb.createDownloadUrl); Event.on('.load_from_gist', 'click', null, wb.loadScriptsFromGistId); Event.on('.restore_scripts', 'click', null, wb.loadScriptsFromFilesystem); Event.on('.workspace', 'click', '.disclosure', disclosure); Event.on('.workspace', 'dblclick', '.locals .name', wb.changeName); Event.on('.workspace', 'keypress', 'input', wb.resize); Event.on('.workspace', 'change', 'input, select', function(event){ Event.trigger(document.body, 'wb-modified', {block: event.wbTarget, type: 'valueChanged'}); }); Event.on(document.body, 'wb-script-loaded', null, handleScriptLoad); Event.on(document.body, 'wb-modified', null, handleScriptModify); wb.language = location.pathname.match(/\/([^/.]*)\.html/)[1]; wb.loaded = false; wb.clearScripts = clearScripts; wb.historySwitchState = historySwitchState; wb.createWorkspace = createWorkspace; wb.wireUpWorkspace = wireUpWorkspace;
<<<<<<< import { useChannelHiddenListener } from './hooks/useChannelHiddenListener'; ======= import { useChannelVisibleListener } from './hooks/useChannelVisibleListener'; >>>>>>> import { useChannelHiddenListener } from './hooks/useChannelHiddenListener'; import { useChannelVisibleListener } from './hooks/useChannelVisibleListener'; <<<<<<< useChannelHiddenListener(setChannels, props.onChannelHidden); ======= useChannelVisibleListener(setChannels, props.onChannelVisible); >>>>>>> useChannelHiddenListener(setChannels, props.onChannelHidden); useChannelVisibleListener(setChannels, props.onChannelVisible);
<<<<<<< try { augur.web.importAccount(name, password, keystore, (loginAccount) => { const importedAccount = { ...loginAccount, id: loginAccount.address, loginID: account.loginID || account.secureLoginID }; if (!importedAccount || !importedAccount.keystore) { return; } if (rememberMe && localStorageRef && localStorageRef.setItem) { const persistentAccount = Object.assign({}, importedAccount); if (Buffer.isBuffer(persistentAccount.privateKey)) { persistentAccount.privateKey = persistentAccount.privateKey.toString('hex'); } localStorageRef.setItem('account', JSON.stringify(persistentAccount)); } dispatch(loadLoginAccountLocalStorage(importedAccount.id)); dispatch(updateLoginAccount(importedAccount)); dispatch(loadLoginAccountDependents()); if (links && links.marketsLink) { return links.marketsLink.onClick(links.marketsLink.href); } ======= AugurJS.importAccount(name, password, keystore, (err, loginAccount) => { if (err) { dispatch(authError(err)); return; } if (!loginAccount || !loginAccount.id) { >>>>>>> augur.web.importAccount(name, password, keystore, (loginAccount) => { const importedAccount = { ...loginAccount, id: loginAccount.address, loginID: account.loginID || account.secureLoginID }; if (!importedAccount || !importedAccount.keystore) {
<<<<<<< ======= import authForm from 'modules/auth/selectors/auth-form'; import topics from 'modules/topics/selectors/topics'; >>>>>>> import topics from 'modules/topics/selectors/topics';