Beispiel #1
0
export function startUpload( importerStatus, file ) {
	let { importerId, site: { ID: siteId } } = importerStatus;

	wpcom
		.uploadExportFile( siteId, {
			importStatus: toApi( importerStatus ),
			file,

			onprogress: event => {
				setUploadProgress( importerId, {
					uploadLoaded: event.loaded,
					uploadTotal: event.total
				} );
			},

			onabort: () => cancelImport( siteId, importerId )
		} )
		.then( data => Object.assign( data, { siteId } ) )
		.then( fromApi )
		.then( partial( finishUpload, importerId ) )
		.catch( partial( failUpload, importerId ) );

	Dispatcher.handleViewAction( {
		type: actionTypes.START_UPLOAD,
		filename: file.name,
		importerId
	} );
}
  render() {

    const { title, artist, volume, songID, hasError } = this.props;
    const animate = {
      animation: `marquee ${this.state.marqueeDuration}s linear infinite`,
      animationDelay: '1s',
      animationDirection: 'alternate'
    };

    return (
      <div className="artist-info">

        {
          hasError &&
          <div className="artist-info__error">
            Error Playing Media
          </div>
        }

        <Swipeable
          onSwipedRight={partial(this.handleSwiping, 'right')}
          onSwipedLeft={partial(this.handleSwiping, 'left')}>
          <div className="artist-info__cover-container">
            <ReactCSSTransitionGroup
              transitionName="cover"
              transitionEnterTimeout={250}
              transitionLeaveTimeout={250}>
              <img key={songID} className="artist-info__cover" src={this.props.coverURL}
              onError={this.handleImageError} />
            </ReactCSSTransitionGroup>
          </div>
        </Swipeable>

        {
          !this.state.isMobile &&
          <ReactSlider
            onChange={this.onVolumeChange}
            value={volume}
            handle={<SpeakerHandle />} />
        }

        <div className="artist-info__song">
          <div className="artist-info_title">
            <div ref="marquee" className="marquee">
              <div className="marquee_content"
                   style={this.state.showMarquee ? animate : {}}>
                <h2 ref="title">{title}</h2>
              </div>
            </div>
          </div>
          <h6 className="truncate">{artist}</h6>
        </div>

      </div>
    );
  }
Beispiel #3
0
export default function() {
	[ 'keys', 'entries', 'values', 'findIndex', 'fill', 'find' ]
		.map( partial( wrapObjectFn, Array.prototype, 'Array#' ) );

	[ 'codePointAt', 'normalize', 'repeat', 'startsWith', 'endsWith', 'includes' ]
		.map( partial( wrapObjectFn, String.prototype, 'String#' ) );

	[ 'flags' ].map( partial( wrapObjectFn, RegExp.prototype, 'RegExp#' ) );

}
Beispiel #4
0
 {markers.map(marker =>
     React.createElement(component, {
         key: marker.index,
         ...marker,
         ...getPosition(marker),
         data: marker,
         onMouseEnter: partial(this.handleMouseEnter, marker),
         onMouseMove: partial(this.handleMouseEnter, marker),
         onMouseLeave: partial(this.handleMouseLeave, marker),
         onClick: partial(this.handleClick, marker),
     })
Beispiel #5
0
                        {interpolatedStyles.map(({ key, style, data: marker }) => {
                            const color = getInterpolatedColor(style)

                            return React.createElement(component, {
                                key,
                                ...marker,
                                ...style,
                                color,
                                data: marker,
                                onMouseEnter: partial(this.handleMouseEnter, marker),
                                onMouseMove: partial(this.handleMouseEnter, marker),
                                onMouseLeave: partial(this.handleMouseLeave, marker),
                                onClick: partial(this.handleClick, marker),
                            })
                        })}
Beispiel #6
0
    return function(blogIdentifier, params, callback) {
        params = extend({type: type}, params);

        if (isArray(validate)) {
            validate = partial(function(params, requireKeys) {
                if (requireKeys.length) {
                    var keyIntersection = intersection(keys(params), requireKeys);
                    if (requireKeys.length === 1 && !keyIntersection.length) {
                        throw new Error('Missing required field: ' + requireKeys[0]);
                    } else if (!keyIntersection.length) {
                        throw new Error('Missing one of: ' + requireKeys.join(', '));
                    } else if (keyIntersection.length > 1) {
                        throw new Error('Can only use one of: ' + requireKeys.join(', '));
                    }
                }
                return true;
            }, params, validate);
        }

        if (isFunction(validate)) {
            if (!validate(params)) {
                throw new Error('Error validating parameters');
            }
        }

        if (arguments.length > 2) {
            return this.createPost(blogIdentifier, params, callback);
        } else {
            return this.createPost(blogIdentifier, params);
        }
    };
Beispiel #7
0
 {({ showTooltip, hideTooltip }) => (
     <canvas
         ref={surface => {
             this.surface = surface
         }}
         width={outerWidth * pixelRatio}
         height={outerHeight * pixelRatio}
         style={{
             width: outerWidth,
             height: outerHeight,
         }}
         onMouseEnter={partial(this.handleMouseHover, showTooltip, hideTooltip)}
         onMouseMove={partial(this.handleMouseHover, showTooltip, hideTooltip)}
         onMouseLeave={partial(this.handleMouseLeave, hideTooltip)}
         onClick={this.handleClick}
     />
 )}
Beispiel #8
0
       EXPECTED_DATA_YEARS.forEach((year) => {
         this.CitySDK
           .doAPIRequest(craftRequest(year, undefined, newStateCode))
             .then(validateResponse)
 //            .then(printAPIResponse)
             .then(partial(this.setStateFromResponse, newStateCode))
             .catch(console.error.bind(console, 'CitySDK APIRequest ERR:'));
       });
Beispiel #9
0
function Detail({ item, colors, confirmFavorite, endFavorite, favorite, favoriteItem }) {
  const favorited = favorite && favorite.actionStatus !== 'ended' || false
  const favToggle = favorited ? partial(endFavorite, favorite) : partial(favoriteItem, item)

  return (
    <div id="wrapper">
      {favorite && favorite.actionStatus === 'created' &&
        <FavAlert item={item} favorite={favorite} onClick={partial(confirmFavorite, favorite)} />
      }
      <Info
        item={item}
        favorited={favorited}
        favoriteItem={favToggle}
      />
      <img src={item.img} alt={item.id} />
      <Related colors={colors} parent={item} />
    </div>
  )
}
Beispiel #10
0
 Object.keys(events).reduce((memo, eventName) => {
   /* eslint max-params: 0 */
   memo[eventName] = partial(
     events[eventName],
     partial.placeholder, // evt will still be the first argument for event handlers
     childProps, // event handlers will have access to data component props, including data
     eventKey, // used in setting a unique state property
     eventName // used in setting a unique state property
   );
   return memo;
 }, {}) :
Beispiel #11
0
const toGeoHash = (options = {}, cb) => {
  if (typeof options === 'function') {
    cb = options
    options = {}
  }

  const {key} = options
  const filledOptions = partial(fillOptions, options)

  waterfall([filledOptions, getCoordinates], (err, results) => {
    if (err) return cb(err)

    const {byDate, graticule, location} = results
    const milesFromLoc = (geo) => {
      return {distance: location.milesFrom(geo)}
    }
    debug(`Location: ${location}`)
    debug(`Graticule: ${graticule}`)

    const dates = transform(byDate, (result, hashes, date) => {
      const {global, geohashes} = hashes

      debug(`Global: ${global}`)
      debug(`Geohashes: ${geohashes}`)

      const map = geohashMap({
        key,
        location,
        geohashes,
        center: graticule.graticuleCenter().join(','),
        drawGraticulePaths: true,
        zoom: 7
      })

      const globalMap = geohashMap({
        key,
        location,
        geohashes: [global],
        center: location.toString(),
        drawGraticulePaths: false,
        zoom: null
      })

      result[date] = {
        map,
        globalMap,
        global: assign(milesFromLoc(global), global.toJSON()),
        geohashes: geohashes.map((hash) => assign(milesFromLoc(hash), hash.toJSON()))
      }
    })

    cb(null, {dates, location: location.toJSON()})
  })
}
Beispiel #12
0
 const masonryChildren = images.map((i, idx) => {
   return (
     <div key={idx} className="gallery_masonry-item">
       <img className="gallery_img" src={`${i.thumbnail}`} onClick={partial(this.showOverlay, idx)} />
       {!isEmpty(i.description) && <div className="gallery_desc" dangerouslySetInnerHTML={{__html:marked(i.description)}}></div>}
       {!isEmpty(i.client) &&
         <div className="gallery_client">
           <a href={i.clientLink} target="_blank">{i.client}&nbsp;&nbsp;<i className="fa fa-external-link" aria-hidden="true"></i></a>
         </div>}
     </div>
   );
 });
Beispiel #13
0
export default (el, event, callback) => {
  if (!el) return;

  var loader = partial(removeLoader, el);
  function eventAction(e) {
    e.preventDefault();
    addLoader(el);
    if (typeof callback === 'function') {
      callback(loader);
    }
    el.removeEventListener(event, eventAction, false);
  }
  el.addEventListener(event, eventAction, false);
};
Beispiel #14
0
 var result = new Bluebird(function withResponseTimeout(resolve, reject) {
   function onTimedOut() {
     var error = new Error('Fetching from ' + urlObj.hostname + ' timed out');
     error.code = 'ETIMEDOUT';
     error.timeout = options.timeout;
     reject(error);
   }
   var timeoutHandle = setTimeout(onTimedOut, timeout);
   function killTimeout(response) {
     clearTimeout(timeoutHandle);
     return response;
   }
   Bluebird.resolve(fetch(nativeUrl, nativeOptions))
     .then(killTimeout)
     .then(partial(verifyAndExtendResponse, nativeUrl, options))
     .then(resolve, reject);
 });
Beispiel #15
0
  render() {
    const notices = [];
    for (let notice of this.state.notices || []) {
      const Notice = TYPES[(notice && notice.type) || 'system'] || TYPES['system'];
      notices.push(
        <Notice
          key={notice.id}
          noticeId={notice.id}
          notice={notice}
          onDismiss={partial(this.onDismiss, notice)}
          callbacks={this.props.callbacks[notice.type]} />
      );
    }

    return (
      <div
        className={classnames('openstax-notifications-bar', this.props.className, { viewable: !isEmpty(this.state.notices) })}
      >
        {notices}
      </div>
    );
  }
Beispiel #16
0
 {values => (
     <g transform={`translate(${values.x},${values.y})`}>
         {rangeNodes}
         <BulletRects
             data={computedMeasures}
             scale={scale}
             layout={layout}
             reverse={reverse}
             x={0}
             y={values.measuresY}
             width={width}
             height={measureHeight}
             component={measureComponent}
             onMouseEnter={partial(this.handleMeasureTooltip, showTooltip)}
             onMouseLeave={hideTooltip}
             onClick={this.handleMeasureClick}
             {...motionProps}
         />
         {axis}
         {markerNodes}
         {titleNode}
     </g>
 )}
Beispiel #17
0
test.cb('handle multiple parallel calls', t => {
  async.parallel(
    {
      DOCUMENT_ROOT: partial(fn, 'env/DOCUMENT_ROOT.php'),
      PHP_SELF: partial(fn, 'env/PHP_SELF.php'),
      REQUEST_URI: partial(fn, 'env/REQUEST_URI.php'),
      SCRIPT_FILENAME: partial(fn, 'env/SCRIPT_FILENAME.php'),
      SCRIPT_NAME: partial(fn, 'env/SCRIPT_NAME.php'),
      SERVER_NAME: partial(fn, 'env/SERVER_NAME.php', {requestHost: 'sommerlaune.com:123'}),
      SERVER_PORT: partial(fn, 'env/SERVER_PORT.php', {requestHost: 'sommerlaune.com:123'}),
    },
    (err, data) => {
      t.falsy(err);
      t.is(data.DOCUMENT_ROOT, process.cwd());
      t.is(data.PHP_SELF, '/env/PHP_SELF.php');
      t.is(data.REQUEST_URI, '/env/REQUEST_URI.php');
      t.is(data.SCRIPT_FILENAME, path.join(process.cwd(), 'env/SCRIPT_FILENAME.php'));
      t.is(data.SCRIPT_NAME, '/env/SCRIPT_NAME.php');
      t.is(data.SERVER_NAME, 'sommerlaune.com');
      t.is(data.SERVER_PORT, '123');
      t.end();
    }
  );
});
Beispiel #18
0
function sequenceEventActions(props) {
  const {
    control,
    dispatch,
    model,
    updateOn,
    parser,
    changeAction,
  } = props;

  const {
    onChange = identity,
    onBlur = identity,
    onFocus = identity,
  } = control.props;

  const controlOnChange = persistEventWithCallback(onChange);
  const controlOnBlur = persistEventWithCallback(onBlur);
  const controlOnFocus = persistEventWithCallback(onFocus);

  const updateOnEventHandler = (typeof updateOn === 'function')
    ? 'onChange'
    : `on${capitalize(props.updateOn)}`;
  const validateOn = `on${capitalize(props.validateOn)}`;
  const asyncValidateOn = `on${capitalize(props.asyncValidateOn)}`;

  const updaterFn = (typeof updateOn === 'function')
    ? deprecateUpdateOn(updateOn)
    : identity;

  const eventActions = {
    onFocus: [() => dispatch(focus(model))],
    onBlur: [() => dispatch(blur(model))],
    onChange: [],
    onLoad: [], // pseudo-event
    onSubmit: [], // pseudo-event
  };

  const controlChangeMethod = partial(changeAction, model);
  const modelValueUpdater = modelValueUpdaterMap[control.props.type]
    || modelValueUpdaterMap.default;

  if (control.props.defaultValue) {
    eventActions.onLoad.push(() => dispatch(
      actions.change(model, control.props.defaultValue)));
  }

  if (props.validators || props.errors) {
    const dispatchValidate = value => {
      const fieldValidity = getValidity(props.validators, value);
      const fieldErrors = getValidity(props.errors, value);

      dispatch(setErrors(model, merge(
        invertValidity(fieldValidity),
        fieldErrors
      )));

      return value;
    };

    eventActions[validateOn].push(dispatchValidate);
    eventActions.onLoad.push(dispatchValidate);
  }

  if (props.asyncValidators) {
    const dispatchAsyncValidate = value => {
      mapValues(props.asyncValidators,
        (validator, key) => dispatch(asyncSetValidity(model,
          (_, done) => {
            const outerDone = valid => done({ [key]: valid });

            validator(getValue(value), outerDone);
          })
        )
      );

      return value;
    };

    eventActions[asyncValidateOn].push(dispatchAsyncValidate);
  }

  const dispatchChange = (event) => {
    const modelValue = isReadOnlyValue(control)
      ? modelValueUpdater(props, control.props.value)
      : event;

    dispatch(controlChangeMethod(modelValue));

    return modelValue;
  };

  eventActions.onSubmit.push(updaterFn(dispatchChange));

  if (!isReadOnlyValue(control)) {
    eventActions[updateOnEventHandler].push(
      compose(
        updaterFn(dispatchChange),
        partial(modelValueUpdater, props),
        parser,
        getValue,
        controlOnChange));
  } else {
    eventActions[updateOnEventHandler].push(updaterFn(dispatchChange));
  }
  eventActions.onBlur.push(controlOnBlur);
  eventActions.onFocus.push(controlOnFocus);

  return mapValues(eventActions, _actions => compose(..._actions));
}
Beispiel #19
0
    render() {
        const {
            id,

            scale,
            layout,
            reverse,
            axisPosition,
            x,
            y,
            width,
            height,

            title: _title,
            titlePosition,
            titleAlign,
            titleOffsetX,
            titleOffsetY,
            titleRotation,

            computedRanges,
            rangeComponent,

            computedMeasures,
            measureComponent,
            measureHeight,

            computedMarkers,
            markerComponent,
            markerHeight,

            theme,

            showTooltip,
            hideTooltip,

            animate, // eslint-disable-line react/prop-types
            motionStiffness, // eslint-disable-line react/prop-types
            motionDamping, // eslint-disable-line react/prop-types
        } = this.props

        const motionProps = {
            animate,
            motionStiffness,
            motionDamping,
        }

        const rangeNodes = (
            <BulletRects
                data={computedRanges}
                scale={scale}
                layout={layout}
                reverse={reverse}
                x={0}
                y={0}
                width={width}
                height={height}
                component={rangeComponent}
                onMouseEnter={partial(this.handleRangeTooltip, showTooltip)}
                onMouseLeave={hideTooltip}
                onClick={this.handleRangeClick}
                {...motionProps}
            />
        )

        const markerNodes = (
            <BulletMarkers
                markers={computedMarkers}
                scale={scale}
                layout={layout}
                reverse={reverse}
                height={height}
                markerSize={markerHeight}
                component={markerComponent}
                onMouseEnter={partial(this.handleMarkerTooltip, showTooltip)}
                onMouseLeave={hideTooltip}
                onClick={this.handleMarkerClick}
                {...motionProps}
            />
        )

        let axisX = 0
        let axisY = 0
        if (layout === 'horizontal' && axisPosition === 'after') {
            axisY = height
        } else if (layout === 'vertical' && axisPosition === 'after') {
            axisX = height
        }

        const axis = (
            <g transform={`translate(${axisX},${axisY})`}>
                <Axis
                    axis={layout === 'horizontal' ? 'x' : 'y'}
                    length={layout === 'horizontal' ? width : height}
                    scale={scale}
                    ticksPosition={axisPosition}
                    theme={theme}
                    {...motionProps}
                />
            </g>
        )

        const title = _title || id
        let titleX
        let titleY
        if (layout === 'horizontal') {
            titleX = titlePosition === 'before' ? titleOffsetX : width + titleOffsetX
            titleY = height / 2 + titleOffsetY
        } else {
            titleX = height / 2 + titleOffsetX
            titleY = titlePosition === 'before' ? titleOffsetY : width + titleOffsetY
        }

        const titleNode = (
            <g transform={`translate(${titleX},${titleY}) rotate(${titleRotation})`}>
                {isString(title) ? (
                    <text
                        style={{
                            ...theme.labels.text,
                            alignmentBaseline: 'central',
                            textAnchor: titleAlign,
                        }}
                    >
                        {title}
                    </text>
                ) : (
                    title
                )}
            </g>
        )

        if (animate !== true) {
            return (
                <g transform={`translate(${x},${y})`}>
                    {rangeNodes}
                    <BulletRects
                        data={computedMeasures}
                        scale={scale}
                        layout={layout}
                        reverse={reverse}
                        x={0}
                        y={(height - measureHeight) / 2}
                        width={width}
                        height={measureHeight}
                        component={measureComponent}
                        onMouseEnter={partial(this.handleMeasureTooltip, showTooltip)}
                        onMouseLeave={hideTooltip}
                        onClick={this.handleMeasureClick}
                        {...motionProps}
                    />
                    {axis}
                    {markerNodes}
                    {titleNode}
                </g>
            )
        }

        const springConfig = {
            damping: motionDamping,
            stiffness: motionStiffness,
        }

        return (
            <Motion
                style={{
                    x: spring(x, springConfig),
                    y: spring(y, springConfig),
                    measuresY: spring((height - measureHeight) / 2, springConfig),
                }}
            >
                {values => (
                    <g transform={`translate(${values.x},${values.y})`}>
                        {rangeNodes}
                        <BulletRects
                            data={computedMeasures}
                            scale={scale}
                            layout={layout}
                            reverse={reverse}
                            x={0}
                            y={values.measuresY}
                            width={width}
                            height={measureHeight}
                            component={measureComponent}
                            onMouseEnter={partial(this.handleMeasureTooltip, showTooltip)}
                            onMouseLeave={hideTooltip}
                            onClick={this.handleMeasureClick}
                            {...motionProps}
                        />
                        {axis}
                        {markerNodes}
                        {titleNode}
                    </g>
                )}
            </Motion>
        )
    }
function getBindingFunc(binding, context) {
    var type = binding.type || 'text';
    var isCustomBinding = typeof type === 'function';
    var selector = getSelector(binding);
    var firstMatchOnly = binding.firstMatchOnly;
    var yes = binding.yes;
    var no = binding.no;
    var hasYesNo = !!(yes || no);

    // storage variable for previous if relevant
    var previousValue;

    if (isCustomBinding) {
        return function (el, value) {
            getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                type.call(context, match, value, previousValue);
            });
            previousValue = value;
        };
    } else if (type === 'text') {
        return function (el, value) {
            getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                dom.text(match, value);
            });
        };
    } else if (type === 'class') {
        return function (el, value) {
            getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                dom.switchClass(match, previousValue, value);
            });
            previousValue = value;
        };
    } else if (type === 'attribute') {
        if (!binding.name) throw Error('attribute bindings must have a "name"');
        return function (el, value) {
            var names = makeArray(binding.name);
            getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                names.forEach(function (name) {
                    dom.setAttribute(match, name, value);
                });
            });
            previousValue = value;
        };
    } else if (type === 'value') {
        return function (el, value) {
            getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                if (!value && value !== 0) value = '';
                // only apply bindings if element is not currently focused
                if (document.activeElement !== match) match.value = value;
            });
            previousValue = value;
        };
    } else if (type === 'booleanClass') {
        // if there's a `no` case this is actually a switch
        if (hasYesNo) {
            yes = makeArray(yes || '');
            no = makeArray(no || '');
            return function (el, value) {
                var prevClass = value ? no : yes;
                var newClass = value ? yes : no;
                getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                    prevClass.forEach(function (pc) {
                        dom.removeClass(match, pc);
                    });
                    newClass.forEach(function (nc) {
                        dom.addClass(match, nc);
                    });
                });
            };
        } else {
            return function (el, value, keyName) {
                var name = makeArray(binding.name || keyName);
                var invert = (binding.invert || false);
                value = (invert ? (value ? false : true) : value);
                getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                    name.forEach(function (className) {
                        dom[value ? 'addClass' : 'removeClass'](match, className);
                    });
                });
            };
        }
    } else if (type === 'booleanAttribute') {
        // if there are `yes` and `no` selectors, this swaps between them
        if (hasYesNo) {
            yes = makeArray(yes || '');
            no = makeArray(no || '');
            return function (el, value) {
                var prevAttribute = value ? no : yes;
                var newAttribute = value ? yes : no;
                getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                    prevAttribute.forEach(function (pa) {
                        if (pa) {
                            dom.removeAttribute(match, pa);
                        }
                    });
                    newAttribute.forEach(function (na) {
                        if (na) {
                            dom.addAttribute(match, na);
                        }
                    });
                });
            };
        } else {
            return function (el, value, keyName) {
                var name = makeArray(binding.name || keyName);
                var invert = (binding.invert || false);
                value = (invert ? (value ? false : true) : value);
                getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                    name.forEach(function (attr) {
                        dom[value ? 'addAttribute' : 'removeAttribute'](match, attr);
                    });
                });
            };
        }
    } else if (type === 'toggle') {
        var mode = (binding.mode || 'display');
        var invert = (binding.invert || false);
        // this doesn't require a selector since we can pass yes/no selectors
        if (hasYesNo) {
            return function (el, value) {
                getMatches(el, yes, firstMatchOnly).forEach(function (match) {
                    dom[value ? 'show' : 'hide'](match, mode);
                });
                getMatches(el, no, firstMatchOnly).forEach(function (match) {
                    dom[value ? 'hide' : 'show'](match, mode);
                });
            };
        } else {
            return function (el, value) {
                value = (invert ? (value ? false : true) : value);
                getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                    dom[value ? 'show' : 'hide'](match, mode);
                });
            };
        }
    } else if (type === 'switch') {
        if (!binding.cases) throw Error('switch bindings must have "cases"');
        return partial(switchHandler, binding);
    } else if (type === 'innerHTML') {
        return function (el, value) {
            getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                dom.html(match, value);
            });
        };
    } else if (type === 'switchClass') {
        if (!binding.cases) throw Error('switchClass bindings must have "cases"');
        return function (el, value, keyName) {
            var name = makeArray(binding.name || keyName);
            for (var item in binding.cases) {
                getMatches(el, binding.cases[item], firstMatchOnly).forEach(function (match) {
                    name.forEach(function (className) {
                        dom[value === item ? 'addClass' : 'removeClass'](match, className);
                    });
                });
            }
        };
    } else if (type === 'switchAttribute') {
        if (!binding.cases) throw Error('switchAttribute bindings must have "cases"');
        return function (el, value, keyName) {
            getMatches(el, selector, firstMatchOnly).forEach(function (match) {
                if (previousValue) {
                    removeAttributes(match, previousValue);
                }

                if (value in binding.cases) {
                    var attrs = binding.cases[value];
                    if (typeof attrs === 'string') {
                        attrs = {};
                        attrs[binding.name || keyName] = binding.cases[value];
                    }
                    setAttributes(match, attrs);

                    previousValue = attrs;
                }
            });
        };
    } else {
        throw new Error('no such binding type: ' + type);
    }
}
Beispiel #21
0
	return data;
};
const apiFailure = data => {
	Dispatcher.handleViewAction( { type: actionTypes.API_FAILURE } );

	return data;
};
const setImportLock = ( shouldEnableLock, importerId ) => {
	const type = shouldEnableLock
		? actionTypes.LOCK_IMPORT
		: actionTypes.UNLOCK_IMPORT;

	Dispatcher.handleViewAction( { type, importerId } );
};
const lockImport = partial( setImportLock, true );
const unlockImport = partial( setImportLock, false );

const asArray = a => [].concat( a );

function receiveImporterStatus( importerStatus ) {
	Dispatcher.handleViewAction( {
		type: actionTypes.RECEIVE_IMPORT_STATUS,
		importerStatus
	} );
}

export function cancelImport( siteId, importerId ) {
	lockImport( importerId );

	Dispatcher.handleViewAction( {
Beispiel #22
0
import { fetchScript, fetchLink } from '../utils/fetch-and-cache.js';
import { compileHeadTail, setExt, transformContents } from '../utils/polyvinyl';

const htmlCatch = '\n<!--fcc-->\n';
const jsCatch = '\n;/*fcc*/\n';

const defaultTemplate = ({ source }) => `
  <body style='margin:8px;'>
    <!-- fcc-start-source -->
      ${source}
    <!-- fcc-end-source -->
  </body>
`;

const wrapInScript = partial(
  transformContents,
  content => `${htmlCatch}<script>${content}${jsCatch}</script>`
);
const wrapInStyle = partial(
  transformContents,
  content => `${htmlCatch}<style>${content}</style>`
);
const setExtToHTML = partial(setExt, 'html');
const padContentWithJsCatch = partial(compileHeadTail, jsCatch);
const padContentWithHTMLCatch = partial(compileHeadTail, htmlCatch);

export const jsToHtml = cond([
  [
    matchesProperty('ext', 'js'),
    flow(padContentWithJsCatch, wrapInScript, setExtToHTML)
  ],
  [stubTrue, identity]
const partial = require('lodash/partial');
const isAdmin = require('../middlewares/isAdmin');
const { EVENT_TAGS_TABLE } = require('../constants');
const { TYPE_TAG, modelResponse } = require('../utils/response');

// cached response
const response = partial(modelResponse, partial.placeholder, TYPE_TAG);

/**
 * @api {http} <prefix>.event.tags.create Create new tag
 * @apiVersion 1.0.0
 * @apiName event.tags.create
 * @apiGroup Tags
 * @apiSchema {jsonschema=../../schemas/event.tags.create.json} apiParam
 */
function EventTagsCreate({ params }) {
  return this.knex(EVENT_TAGS_TABLE)
    .insert(params.tag)
    .returning('*')
    .then(arr => response(arr[0]));
}

EventTagsCreate.allowed = isAdmin;
EventTagsCreate.auth = 'token';
EventTagsCreate.schema = 'event.tags.create';
EventTagsCreate.transports = ['http', 'amqp'];

module.exports = EventTagsCreate;
Beispiel #24
0
 {map(favorites, (fav) => (
   <FavItem key={fav.id} onClick={partial(endFavorite, fav)} item={fav.item} />
 ))}
Beispiel #25
0
	.add( 'calypso_reader_related_post_site_clicked' )
	.add( 'calypso_reader_article_liked' )
	.add( 'calypso_reader_article_commented_on' )
	.add( 'calypso_reader_article_opened' )
	.add( 'calypso_reader_startcard_clicked' )
	.add( 'calypso_reader_searchcard_clicked' )
;

export function recordTracksRailcar( action, eventName, railcar ) {
	// flatten the railcar down into the event props
	recordTrack( action, Object.assign( {
		action: eventName.replace( 'calypso_reader_', '' )
	}, railcar ) );
}

export const recordTracksRailcarRender = partial( recordTracksRailcar, 'calypso_traintracks_render' );
export const recordTracksRailcarInteract = partial( recordTracksRailcar, 'calypso_traintracks_interact' );

export function recordTrackForPost( eventName, post = {}, additionalProps = {} ) {
	recordTrack( eventName, assign( {
		blog_id: ! post.is_external && post.site_ID > 0 ? post.site_ID : undefined,
		post_id: ! post.is_external && post.ID > 0 ? post.ID : undefined,
		feed_id: post.feed_ID > 0 ? post.feed_ID : undefined,
		feed_item_id: post.feed_item_ID > 0 ? post.feed_item_ID : undefined,
		is_jetpack: post.is_jetpack
	}, additionalProps ) );
	if ( post.railcar && tracksRailcarEventWhitelist.has( eventName ) ) {
		recordTracksRailcarInteract( eventName, post.railcar );
	} else if ( process.env.NODE_ENV !== 'production' && post.railcar ) {
		console.warn( 'Consider whitelisting reader track', eventName ); //eslint-disable-line no-console
	}
Beispiel #26
0
const shouldRemove = importer => removableStates.some( partial( equals, importer.get( 'importerState' ) ) );
function changeMethod(model, value, action = change, parser = identity) {
  return compose(partial(action, model), parser, getValue);
}
Beispiel #28
0
 methods: {
   /**
    * @desc push a new type
    * @param {!MetaInfoType} type
    * @param {!Array.<Number>=} childrenIds - An array of numbers corresponding to children Ids of this type instance
    * @param {boolean=} forceId - If true, don't build up an inferred id.
    * @memberof MetaInfoTypes#
    * @instance
    */
   pushType (type, childrenIds = [], forceId = false) {
     const action = `${this.getTypeName()}#pushType`
     // perform security checks
     ensures(action, type, this.getTypeClass())
     ensures(action, childrenIds, Array)
     if (includes(this.getAllTypesIds(), type._id)) throw new TypeError('Cannot push a type which id already exists.')
     const depends = partial(includes, childrenIds)
     // infer id
     if (!forceId) {
       type._id = 0
       let ids = this.getAllTypesIds()
       ids.push(0)
       type._id = max(ids) + 1
       type.validate()
     } else {
       type.validate()
     }
     this._types.push(type)
     // refer children
     if (childrenIds.length) {
       _(this._types)
         .filter(depends)
Beispiel #29
0
    draw(props) {
        const {
            width,
            height,
            outerWidth,
            outerHeight,
            pixelRatio,
            margin,
            offsetX,
            offsetY,

            xScale,
            yScale,

            axisTop,
            axisRight,
            axisBottom,
            axisLeft,

            cellShape,

            enableLabels,

            theme,
        } = props

        this.surface.width = outerWidth * pixelRatio
        this.surface.height = outerHeight * pixelRatio

        this.ctx.scale(pixelRatio, pixelRatio)

        let renderNode
        if (cellShape === 'rect') {
            renderNode = partial(renderRect, this.ctx, { enableLabels, theme })
        } else {
            renderNode = partial(renderCircle, this.ctx, { enableLabels, theme })
        }

        const nodes = computeNodes(props)

        this.ctx.fillStyle = theme.background
        this.ctx.fillRect(0, 0, outerWidth, outerHeight)
        this.ctx.translate(margin.left + offsetX, margin.top + offsetY)

        renderAxesToCanvas(this.ctx, {
            xScale,
            yScale,
            width: width - offsetX * 2,
            height: height - offsetY * 2,
            top: axisTop,
            right: axisRight,
            bottom: axisBottom,
            left: axisLeft,
            theme,
        })

        this.ctx.textAlign = 'center'
        this.ctx.textBaseline = 'middle'

        nodes.forEach(renderNode)

        this.nodes = nodes
    }
Beispiel #30
0
export default function API(Platform, getState, dispatch) {
  const httpGet = partial(Platform.Network.http, 'GET')
  const httpPost = partial(Platform.Network.http, 'POST')
  Platform.Network.hook(
    (method, endpoint, status, error) => {
      if (status == 401) {
        dispatch(Action.User.auth.create({status: false}))
        throw new Error('You have to sign in to continue.')
      }
      if (error) {
        throw new Error(`${error}: ${method} ${endpoint}`)
      }
    }
  )

  const api = {}

  api.processAuth = async () => {
    const state = getState()
    const auth = state.user.auth
    if (auth.status) return
    if (auth.providers) {
      const {providers, selected} = auth
      const provider = providers.length == 1
        ? providers[0]
        : providers.find(provider => provider.id == selected)
      if (provider) {
        Platform.App.webview(Platform.Network.url('http', provider.url + '?'
          + `redirectUri=${encodeURIComponent(Platform.App.url())}`
        ))
      }
    } else {
      const data = await httpGet('/oauth/all')
      const providers = data.map(item => ({
        id: item.scheme,
        name: item.displayName,
        url: item.url
      }))
      dispatch(Action.User.auth.create({providers}))
    }
  }

  api.fetchUser = async () => {
    const data = await httpGet('/api/user/userinfo')
    const profile = Codec.User.decode(data)
    dispatch(Action.User.profile.create(profile))
  }

  api.fetchPreferences = async () => {
    const data = await httpGet('/api/user/configuration')
    const preferences = Codec.Preferences.decode(data)
    dispatch(Action.User.preferences.create(preferences))
  }

  api.fetchPlaylist = async () => {
    const state = getState()
    const sync = state.user.preferences.sync
    if (!sync) return
    const urls = sync.split('\n').filter(line => line)
    if (!urls.length) return
    const data = await Promise.all(urls.map(url =>
      httpPost('/provider/songListWithUrl', {
        url,
        withCookie: state.user.preferences.cookie
      })
    ))
    const songs = []
      .concat(...data.map(item => item.songs || []))
      .map(Codec.Song.decode)
    dispatch(Action.Song.assign.create(songs))
  }

  api.sendPreferences = async prevState => {
    const state = getState()
    const preferences = Codec.Preferences.encode(state.user.preferences)
    const prevPreferences = prevState &&
      Codec.Preferences.encode(prevState.user.preferences)
    if (prevState && isEqual(preferences, prevPreferences)) return
    await httpPost('/api/user/configuration',
      preferences
    )
  }

  api.sendChannel = async prevState => {
    const state = getState()
    const channel = state.channel.name
    if (!channel) return
    const prevChannel = prevState && prevState.channel.name
    if (channel == prevChannel) return
    await httpPost(`/api/channel/join/${channel}`)
  }

  api.sendUpnext = async prevState => {
    const state = getState()
    if (!state.channel.name) return
    const song = Codec.Song.encode(
      state.user.preferences.listenOnly
        ? undefined
        : state.song.playlist[0]
    )
    const prevSong = prevState && Codec.Song.encode(
      prevState.user.preferences.listenOnly
        ? undefined
        : prevState.song.playlist[0]
    )
    if (prevState && isEqual(song, prevSong)) return
    await httpPost('/api/channel/updateNextSong', {
      ...song,
      withCookie: state.user.preferences.cookie
    })
  }

  api.sendEnded = async () => {
    const state = getState()
    if (!state.channel.name) return
    const song = Codec.Song.encode(state.song.playing)
    await httpPost('/api/channel/finished',
      song.songId ? song : null
    )
  }

  api.sendDownvote = async () => {
    const state = getState()
    if (!state.channel.name) return
    const song = Codec.Song.encode(state.song.playing)
    await httpPost('/api/channel/downVote',
      song.songId ? song : null
    )
  }

  api.sendSearch = async () => {
    const state = getState()
    const keyword = state.search.keyword
    if (keyword) {
      const data = await httpPost('/provider/searchSongs', {
        key: keyword,
        withCookie: state.user.preferences.cookie
      })
      const results = data.map(Codec.Song.decode)
      dispatch(Action.Search.results.create(results))
    } else {
      dispatch(Action.Search.results.create([]))
    }
  }

  api.receiveMessage = callback => {
    Platform.Network.websocket('/api/ws', (connect, ping) => {
      let interval
      return (event, data) => {
        const state = getState()
        switch (event) {
          case 'open': {
            interval = Platform.Timer.setInterval(ping, 30 * 1000)
            callback('connected')
            break
          }
          case 'close': {
            Platform.Timer.clearInterval(interval)
            if (state.misc.connection.status) {
              Platform.Timer.setTimeout(connect, 5 * 1000)
              callback('interrupted')
            } else {
              callback('disconnected')
            }
            break
          }
          case 'error': {
            break
          }
          case 'UserListUpdated': {
            const members = data.users.map(Codec.User.decode)
            dispatch(Action.Channel.members.create(members))
            break
          }
          case 'Play': {
            const song = data.song && {
              ...Codec.Song.decode(data.song),
              player: data.user || '',
              time: (Date.now() / 1000) - (data.elapsed || 0)
            }
            const downvote = !!data.downvote
            dispatch(Action.Player.reset.create({downvote}))
            dispatch(Action.Song.play.create(song))
            if (song && state.user.profile.id == data.user) {
              const maxIndex = Number.MAX_SAFE_INTEGER
              dispatch(Action.Song.move.create(song.id, maxIndex))
            }
            break
          }
          case 'Preload': {
            const song = data.song && Codec.Song.decode(data.song)
            dispatch(Action.Song.preload.create(song))
            break
          }
          case 'Notification': {
            const notification = {
              message: data.notification.message
            }
            dispatch(Action.Misc.notification.create(notification))
            break
          }
          case 'Disconnect': {
            const connection = {
              status: false,
              message: data.cause
            }
            dispatch(Action.Misc.connection.create(connection))
            break
          }
        }
      }
    })
  }

  return api
}