<commit_before>import { getIn, get, generateIdString } from "../utils";
import won from "../won-es6";
import { getRandomWonId } from "../won-utils";
import { actionTypes } from "./actions";
import { getOwnedAtomByConnectionUri } from "../selectors/general-selectors";
import { getOwnedConnectionByUri } from "../selectors/connection-selectors";
import { buildConnectMessage, buildCloseMessage } from "../won-message-utils";

export function createPersona(persona, nodeUri) {
  return (dispatch, getState) => {
    const state = getState();
    if (!nodeUri) {
      nodeUri = getIn(state, ["config", "defaultNodeUri"]);
    }

    const publishedContentUri = nodeUri + "/atom/" + getRandomWonId();
    const msgUri = nodeUri + "/event/" + getRandomWonId();

    //FIXME: THIS SHOULD NOT USE ANY OF THE CODE BELOW BUT EXECUTE OUR ALREADY PRESENT ATOM-CREATION WITH A GIVEN DRAFT INSTEAD
    const graph = {
      "@id": publishedContentUri,
      "@type": ["won:Atom", "won:Persona"],
      "won:socket": [
        {
          "@id": "#holderSocket",
          "won:socketDefinition": { "@id": "hold:HolderSocket" },
        },
        {
          "@id": "#reviewSocket",
          "won:socketDefinition": { "@id": "review:ReviewSocket" },
        },
        {
          "@id": "#buddySocket",
          "won:socketDefinition": { "@id": "buddy:BuddySocket" },
        },
      ],
      "match:flag": [
        { "@id": "match:NoHintForCounterpart" },
        { "@id": "match:NoHintForMe" },
      ],
      "s:name": persona.displayName,
      "s:description": persona.aboutMe || undefined,
      "s:url": persona.website || undefined,
    };
    const graphEnvelope = {
      "@graph": [graph],
    };

    const msg = won.buildMessageRdf(graphEnvelope, {
      recipientNode: nodeUri, //mandatory
      senderNode: nodeUri, //mandatory
      msgType: won.WONMSG.createMessage, //mandatory
      publishedContentUri: publishedContentUri, //mandatory
      msgUri: msgUri,
    });

    msg["@context"]["@base"] = publishedContentUri;

    dispatch({
      type: actionTypes.personas.create,
      payload: {
        eventUri: msgUri,
        message: msg,
        atomUri: publishedContentUri,
        persona: graph,
      },
    });
  };
}

async function connectReview(
  dispatch,
  ownPersona,
  foreignPersona,
  connectMessage,
  connectionUri = undefined
) {
  const getSocket = persona => {
    const reviewSocket = persona
      .getIn(["content", "sockets"])
      .filter(socketType => socketType === "review:ReviewSocket")
      .keySeq()
      .first();

    if (!reviewSocket) {
      throw new Error(
        `Persona ${persona.get("uri")} does not have a review socket`
      );
    }
    return reviewSocket;
  };

  const cnctMsg = buildConnectMessage({
    ownedAtomUri: ownPersona.get("uri"),
    theirAtomUri: foreignPersona.get("uri"),
    ownNodeUri: ownPersona.get("nodeUri"),
    theirNodeUri: foreignPersona.get("nodeUri"),
    connectMessage: connectMessage,
    optionalOwnConnectionUri: connectionUri,
    ownSocket: getSocket(ownPersona),
    theirSocket: getSocket(foreignPersona),
  });
  const optimisticEvent = await won.wonMessageFromJsonLd(cnctMsg.message);
  dispatch({
    type: actionTypes.atoms.connect,
    payload: {
      eventUri: cnctMsg.eventUri,
      message: cnctMsg.message,
      ownConnectionUri: connectionUri,
      optimisticEvent: optimisticEvent,
    },
  });
}

export function connectPersona(atomUri, personaUri) {
  return async dispatch => {
    const response = await fetch("rest/action/connect", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify([
        {
          pending: false,
          socket: `${personaUri}#holderSocket`,
        },
        {
          pending: false,
          socket: `${atomUri}#holdableSocket`,
        },
      ]),
      credentials: "include",
    });
    if (!response.ok) {
      const errorMsg = await response.text();
      throw new Error(`Could not connect identity: ${errorMsg}`);
    }
    dispatch({
      type: actionTypes.personas.connect,
      payload: {
        atomUri: atomUri,
        personaUri: personaUri,
      },
    });
  };
}

export function disconnectPersona(atomUri, personaUri) {
  return (dispatch, getState) => {
    const state = getState();
    const persona = state.getIn(["atoms", personaUri]);
    const atom = state.getIn(["atoms", atomUri]);

    const connectionUri = persona
      .get("connections")
      .filter(
        connection =>
          connection.get("targetAtomUri") == atom.get("uri") &&
          connection.get("socket") == won.HOLD.HolderSocketCompacted
      )
      .keySeq()
      .first();

    const connection = getOwnedConnectionByUri(state, connectionUri);

    buildCloseMessage(
      connectionUri,
      personaUri,
      atomUri,
      persona.get("nodeUri"),
      atom.get("nodeUri"),
      connection.get("targetConnectionUri")
    ).then(({ eventUri, message }) => {
      dispatch({
        type: actionTypes.connections.close,
        payload: {
          connectionUri,
          eventUri,
          message,
        },
      });
    });
  };
}

export function reviewPersona(reviewableConnectionUri, review) {
  return (dispatch, getState) => {
    const state = getState();
    const connection = getOwnedConnectionByUri(state, reviewableConnectionUri);

    const ownAtom = getOwnedAtomByConnectionUri(state, reviewableConnectionUri);
    const foreignAtomUri = get(connection, "targetAtomUri");
    const foreignAtom = getIn(state, ["atoms", foreignAtomUri]);

    const getPersona = atom => {
      const personaUri = get(atom, "heldBy");
      const persona = state.getIn(["atoms", personaUri]);

      return persona;
    };

    const getConnection = (ownPersona, foreignPersona) => {
      return ownPersona
        .get("connections")
        .filter(
          connection =>
            connection.get("targetAtomUri") == foreignPersona.get("uri") &&
            connection.get("socket") == won.REVIEW.ReviewSocket
        )
        .keySeq()
        .first();
    };

    const ownPersona = getPersona(ownAtom);
    const foreignPersona = getPersona(foreignAtom);
    const identifier = "review";
    const reviewRdf = {
      "s:review": {
        "@type": "s:Review",
        "@id":
          reviewableConnectionUri && identifier
            ? reviewableConnectionUri +
              "/" +
              identifier +
              "/" +
              generateIdString(10)
            : undefined,

        "s:about": foreignPersona.get("uri"),
        "s:author": ownPersona.get("uri"),
        "s:reviewRating": {
          "@type": "s:Rating",
          "@id":
            reviewableConnectionUri && identifier
              ? reviewableConnectionUri +
                "/" +
                identifier +
                "/" +
                generateIdString(10)
              : undefined,
          "s:bestRating": { "@value": 5, "@type": "xsd:int" }, //not necessary but possible
          "s:ratingValue": { "@value": review.value, "@type": "xsd:int" },
          "s:worstRating": { "@value": 1, "@type": "xsd:int" }, //not necessary but possible
        },
        "s:description": review.message,
      },
    };

    connectReview(
      dispatch,
      ownPersona,
      foreignPersona,
      reviewRdf,
      getConnection(ownPersona, foreignPersona)
    );
  };
}
<commit_msg>Use atomUtils method to get the review Facet Uri instead of the local function<commit_after>import { getIn, get, generateIdString } from "../utils";
import won from "../won-es6";
import { getRandomWonId } from "../won-utils";
import { actionTypes } from "./actions";
import { getOwnedAtomByConnectionUri } from "../selectors/general-selectors";
import { getOwnedConnectionByUri } from "../selectors/connection-selectors";
import { buildConnectMessage, buildCloseMessage } from "../won-message-utils";
import * as atomUtils from "../atom-utils.js";

export function createPersona(persona, nodeUri) {
  return (dispatch, getState) => {
    const state = getState();
    if (!nodeUri) {
      nodeUri = getIn(state, ["config", "defaultNodeUri"]);
    }

    const publishedContentUri = nodeUri + "/atom/" + getRandomWonId();
    const msgUri = nodeUri + "/event/" + getRandomWonId();

    //FIXME: THIS SHOULD NOT USE ANY OF THE CODE BELOW BUT EXECUTE OUR ALREADY PRESENT ATOM-CREATION WITH A GIVEN DRAFT INSTEAD
    const graph = {
      "@id": publishedContentUri,
      "@type": ["won:Atom", "won:Persona"],
      "won:socket": [
        {
          "@id": "#holderSocket",
          "won:socketDefinition": { "@id": "hold:HolderSocket" },
        },
        {
          "@id": "#reviewSocket",
          "won:socketDefinition": { "@id": "review:ReviewSocket" },
        },
        {
          "@id": "#buddySocket",
          "won:socketDefinition": { "@id": "buddy:BuddySocket" },
        },
      ],
      "match:flag": [
        { "@id": "match:NoHintForCounterpart" },
        { "@id": "match:NoHintForMe" },
      ],
      "s:name": persona.displayName,
      "s:description": persona.aboutMe || undefined,
      "s:url": persona.website || undefined,
    };
    const graphEnvelope = {
      "@graph": [graph],
    };

    const msg = won.buildMessageRdf(graphEnvelope, {
      recipientNode: nodeUri, //mandatory
      senderNode: nodeUri, //mandatory
      msgType: won.WONMSG.createMessage, //mandatory
      publishedContentUri: publishedContentUri, //mandatory
      msgUri: msgUri,
    });

    msg["@context"]["@base"] = publishedContentUri;

    dispatch({
      type: actionTypes.personas.create,
      payload: {
        eventUri: msgUri,
        message: msg,
        atomUri: publishedContentUri,
        persona: graph,
      },
    });
  };
}

async function connectReview(
  dispatch,
  ownPersona,
  foreignPersona,
  connectMessage,
  connectionUri = undefined
) {
  const ownSocketUri = atomUtils.getSocketUri(
    ownPersona,
    won.REVIEW.ReviewSocketCompacted
  );
  const theirSocketUri = atomUtils.getSocketUri(
    foreignPersona,
    won.REVIEW.ReviewSocketCompacted
  );

  if (!ownSocketUri) {
    throw new Error(
      `Persona ${ownPersona.get("uri")} does not have a review socket`
    );
  }

  if (!theirSocketUri) {
    throw new Error(
      `Persona ${foreignPersona.get("uri")} does not have a review socket`
    );
  }

  const cnctMsg = buildConnectMessage({
    ownedAtomUri: ownPersona.get("uri"),
    theirAtomUri: foreignPersona.get("uri"),
    ownNodeUri: ownPersona.get("nodeUri"),
    theirNodeUri: foreignPersona.get("nodeUri"),
    connectMessage: connectMessage,
    optionalOwnConnectionUri: connectionUri,
    ownSocket: ownSocketUri,
    theirSocket: theirSocketUri,
  });
  const optimisticEvent = await won.wonMessageFromJsonLd(cnctMsg.message);
  dispatch({
    type: actionTypes.atoms.connect,
    payload: {
      eventUri: cnctMsg.eventUri,
      message: cnctMsg.message,
      ownConnectionUri: connectionUri,
      optimisticEvent: optimisticEvent,
    },
  });
}

export function connectPersona(atomUri, personaUri) {
  return async dispatch => {
    const response = await fetch("rest/action/connect", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify([
        {
          pending: false,
          socket: `${personaUri}#holderSocket`,
        },
        {
          pending: false,
          socket: `${atomUri}#holdableSocket`,
        },
      ]),
      credentials: "include",
    });
    if (!response.ok) {
      const errorMsg = await response.text();
      throw new Error(`Could not connect identity: ${errorMsg}`);
    }
    dispatch({
      type: actionTypes.personas.connect,
      payload: {
        atomUri: atomUri,
        personaUri: personaUri,
      },
    });
  };
}

export function disconnectPersona(atomUri, personaUri) {
  return (dispatch, getState) => {
    const state = getState();
    const persona = state.getIn(["atoms", personaUri]);
    const atom = state.getIn(["atoms", atomUri]);

    const connectionUri = persona
      .get("connections")
      .filter(
        connection =>
          connection.get("targetAtomUri") == atom.get("uri") &&
          connection.get("socket") == won.HOLD.HolderSocketCompacted
      )
      .keySeq()
      .first();

    const connection = getOwnedConnectionByUri(state, connectionUri);

    buildCloseMessage(
      connectionUri,
      personaUri,
      atomUri,
      persona.get("nodeUri"),
      atom.get("nodeUri"),
      connection.get("targetConnectionUri")
    ).then(({ eventUri, message }) => {
      dispatch({
        type: actionTypes.connections.close,
        payload: {
          connectionUri,
          eventUri,
          message,
        },
      });
    });
  };
}

export function reviewPersona(reviewableConnectionUri, review) {
  return (dispatch, getState) => {
    const state = getState();
    const connection = getOwnedConnectionByUri(state, reviewableConnectionUri);

    const ownAtom = getOwnedAtomByConnectionUri(state, reviewableConnectionUri);
    const foreignAtomUri = get(connection, "targetAtomUri");
    const foreignAtom = getIn(state, ["atoms", foreignAtomUri]);

    const getPersona = atom => {
      const personaUri = get(atom, "heldBy");
      const persona = state.getIn(["atoms", personaUri]);

      return persona;
    };

    const getConnection = (ownPersona, foreignPersona) => {
      return ownPersona
        .get("connections")
        .filter(
          connection =>
            connection.get("targetAtomUri") == foreignPersona.get("uri") &&
            connection.get("socket") == won.REVIEW.ReviewSocket
        )
        .keySeq()
        .first();
    };

    const ownPersona = getPersona(ownAtom);
    const foreignPersona = getPersona(foreignAtom);
    const identifier = "review";
    const reviewRdf = {
      "s:review": {
        "@type": "s:Review",
        "@id":
          reviewableConnectionUri && identifier
            ? reviewableConnectionUri +
              "/" +
              identifier +
              "/" +
              generateIdString(10)
            : undefined,

        "s:about": foreignPersona.get("uri"),
        "s:author": ownPersona.get("uri"),
        "s:reviewRating": {
          "@type": "s:Rating",
          "@id":
            reviewableConnectionUri && identifier
              ? reviewableConnectionUri +
                "/" +
                identifier +
                "/" +
                generateIdString(10)
              : undefined,
          "s:bestRating": { "@value": 5, "@type": "xsd:int" }, //not necessary but possible
          "s:ratingValue": { "@value": review.value, "@type": "xsd:int" },
          "s:worstRating": { "@value": 1, "@type": "xsd:int" }, //not necessary but possible
        },
        "s:description": review.message,
      },
    };

    connectReview(
      dispatch,
      ownPersona,
      foreignPersona,
      reviewRdf,
      getConnection(ownPersona, foreignPersona)
    );
  };
}
<|endoftext|>


<commit_before>module.exports = {
  'env': {
    'es6': true
  },
  'parserOptions': {
    'ecmaVersion': 6,
    'sourceType': 'module',
    'ecmaFeatures': {
      'jsx': true,
      'generators': false,
      'objectLiteralDuplicateProperties': false
    }
  },
  'rules': {
    // enforces no braces where they can be omitted
    // http://eslint.org/docs/rules/arrow-body-style
    'arrow-body-style': [2, 'as-needed'],
    // require parens in arrow function arguments
    'arrow-parens': 0,
    // require space before/after arrow function's arrow
    // https://github.com/eslint/eslint/blob/master/docs/rules/arrow-spacing.md
    'arrow-spacing': [2, { 'before': true, 'after': true }],
    // require trailing commas in multiline object literals
    'comma-dangle': [2, 'always-multiline'],
    // verify super() callings in constructors
    'constructor-super': 0,
    // enforce the spacing around the * in generator functions
    'generator-star-spacing': 0,
    // disallow modifying variables of class declarations
    'no-class-assign': 0,
    // disallow arrow functions where they could be confused with comparisons
    // http://eslint.org/docs/rules/no-confusing-arrow
    'no-confusing-arrow': 0,
    // disallow modifying variables that are declared using const
    'no-const-assign': 2,
    // disallow symbol constructor
    // http://eslint.org/docs/rules/no-new-symbol
    'no-new-symbol': 2,
    // disallow specific globals
    'no-restricted-globals': 0,
    // disallow specific imports
    // http://eslint.org/docs/rules/no-restricted-imports
    'no-restricted-imports': 0,
    // disallow to use this/super before super() calling in constructors.
    'no-this-before-super': 0,
    // require let or const instead of var
    'no-var': 2,
    // disallow unnecessary constructor
    // http://eslint.org/docs/rules/no-useless-constructor
    'no-useless-constructor': 2,
    // require method and property shorthand syntax for object literals
    // https://github.com/eslint/eslint/blob/master/docs/rules/object-shorthand.md
    'object-shorthand': [2, 'always'],
    // suggest using arrow functions as callbacks
    'prefer-arrow-callback': 2,
    // suggest using of const declaration for variables that are never modified after declared
    'prefer-const': 2,
    // suggest using the spread operator instead of .apply()
    'prefer-spread': 0,
    // suggest using Reflect methods where applicable
    'prefer-reflect': 0,
    // use rest parameters instead of arguments
    // http://eslint.org/docs/rules/prefer-rest-params
    'prefer-rest-params': 2,
    // suggest using template literals instead of string concatenation
    // http://eslint.org/docs/rules/prefer-template
    'prefer-template': 2,
    // disallow generator functions that do not have yield
    'require-yield': 0,
    // import sorting
    // http://eslint.org/docs/rules/sort-imports
    'sort-imports': 0,
    // enforce usage of spacing in template strings
    // http://eslint.org/docs/rules/template-curly-spacing
    'template-curly-spacing': 2,
    // enforce spacing around the * in yield* expressions
    // http://eslint.org/docs/rules/yield-star-spacing
    'yield-star-spacing': [2, 'after']
  }
};
<commit_msg>[Fix] re-enable `no-confusing-arrow` rule, with `allowParens` option enabled.<commit_after>module.exports = {
  'env': {
    'es6': true
  },
  'parserOptions': {
    'ecmaVersion': 6,
    'sourceType': 'module',
    'ecmaFeatures': {
      'jsx': true,
      'generators': false,
      'objectLiteralDuplicateProperties': false
    }
  },
  'rules': {
    // enforces no braces where they can be omitted
    // http://eslint.org/docs/rules/arrow-body-style
    'arrow-body-style': [2, 'as-needed'],
    // require parens in arrow function arguments
    'arrow-parens': 0,
    // require space before/after arrow function's arrow
    // https://github.com/eslint/eslint/blob/master/docs/rules/arrow-spacing.md
    'arrow-spacing': [2, { 'before': true, 'after': true }],
    // require trailing commas in multiline object literals
    'comma-dangle': [2, 'always-multiline'],
    // verify super() callings in constructors
    'constructor-super': 0,
    // enforce the spacing around the * in generator functions
    'generator-star-spacing': 0,
    // disallow modifying variables of class declarations
    'no-class-assign': 0,
    // disallow arrow functions where they could be confused with comparisons
    // http://eslint.org/docs/rules/no-confusing-arrow
    'no-confusing-arrow': [2, {
      'allowParens': true,
    }],
    // disallow modifying variables that are declared using const
    'no-const-assign': 2,
    // disallow symbol constructor
    // http://eslint.org/docs/rules/no-new-symbol
    'no-new-symbol': 2,
    // disallow specific globals
    'no-restricted-globals': 0,
    // disallow specific imports
    // http://eslint.org/docs/rules/no-restricted-imports
    'no-restricted-imports': 0,
    // disallow to use this/super before super() calling in constructors.
    'no-this-before-super': 0,
    // require let or const instead of var
    'no-var': 2,
    // disallow unnecessary constructor
    // http://eslint.org/docs/rules/no-useless-constructor
    'no-useless-constructor': 2,
    // require method and property shorthand syntax for object literals
    // https://github.com/eslint/eslint/blob/master/docs/rules/object-shorthand.md
    'object-shorthand': [2, 'always'],
    // suggest using arrow functions as callbacks
    'prefer-arrow-callback': 2,
    // suggest using of const declaration for variables that are never modified after declared
    'prefer-const': 2,
    // suggest using the spread operator instead of .apply()
    'prefer-spread': 0,
    // suggest using Reflect methods where applicable
    'prefer-reflect': 0,
    // use rest parameters instead of arguments
    // http://eslint.org/docs/rules/prefer-rest-params
    'prefer-rest-params': 2,
    // suggest using template literals instead of string concatenation
    // http://eslint.org/docs/rules/prefer-template
    'prefer-template': 2,
    // disallow generator functions that do not have yield
    'require-yield': 0,
    // import sorting
    // http://eslint.org/docs/rules/sort-imports
    'sort-imports': 0,
    // enforce usage of spacing in template strings
    // http://eslint.org/docs/rules/template-curly-spacing
    'template-curly-spacing': 2,
    // enforce spacing around the * in yield* expressions
    // http://eslint.org/docs/rules/yield-star-spacing
    'yield-star-spacing': [2, 'after']
  }
};
<|endoftext|>


<commit_before>import base from "@siimple/preset-base";

// theme colors
export const colors = {
    primary: "#161b29",
    secondary: "#757789",
    muted: "#d8d9de",
    highlight: "#9394a3",
    white: "#fff",
};

export default {
    ...base,
    // Scales
    colors: {
        primary: colors.primary,
        secondary: colors.secondary,
        muted: colors.muted,
        text: colors.primary,
        heading: colors.primary,
        highlight: colors.highlight,
        background: colors.white,
    },
    fonts: {
        ...base.fonts,
        body: "Rubik, apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif",
        heading: "'EB Garamond', serif",
    },
    fontWeights: {
        body: "400",
        bold: "700",
        heading: "800",
    },
    // Mixins
    bordered: {
        borderColor: "primary",
        borderRadius: "0.5rem",
        borderStyle: "solid",
        borderWidth: "0.125rem",
    },
    shadowed: {
        boxShadow: [
            "0rem 1rem 1rem -0.5rem rgba(54,63,79,0.25)",
            "0 0 0 1px rgba(54,63,79,0.02)",
        ].join(","),
    },
    // Variants
    buttons: {
        outlined: {
            apply: "bordered",
            backgroundColor: colors.white,
            color: "primary",
            "&:hover": {
                backgroundColor: "primary",
                color: colors.white,
            },
        },
    },
    cards: {
        default: {
            apply: "bordered",
            backgroundColor: colors.white,
            boxShadow: ["none", "!important"],
        },
    },
    dialogs: {
        modal: {
            apply: "bordered",
            backgroundColor: colors.white,
        },
        scrim: {
            backdropFilter: "blur(2px)",
        },
    },
    forms: {
        input: {
            apply: "bordered",
            backgroundColor: colors.white,
        },
        select: {
            apply: "bordered",
            backgroundColor: colors.white,
        },
        textarea: {
            apply: "bordered",
            backgroundColor: colors.white,
        },
    },
};
<commit_msg>fix: some style fixes and improvements in noir preset<commit_after>import base from "@siimple/preset-base";

// theme colors
export const colors = {
    primary: "#161b29",
    secondary: "#757789",
    muted: "#d8d9de",
    highlight: "#9394a3",
    white: "#fff",
};

export default {
    ...base,
    // Scales
    colors: {
        primary: colors.primary,
        secondary: colors.secondary,
        muted: colors.muted,
        text: colors.primary,
        heading: colors.primary,
        highlight: colors.highlight,
        background: colors.white,
    },
    fonts: {
        ...base.fonts,
        body: "Rubik, apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif",
        heading: "'EB Garamond', serif",
    },
    fontWeights: {
        body: "400",
        bold: "700",
        heading: "800",
    },
    // Mixins
    bordered: {
        borderColor: "primary",
        borderRadius: "0.5rem",
        borderStyle: "solid",
        borderWidth: "0.125rem",
    },
    shadowed: {
        boxShadow: [
            "0rem 1rem 1rem -0.5rem rgba(54,63,79,0.25)",
            "0 0 0 1px rgba(54,63,79,0.02)",
        ].join(","),
    },
    // Variants
    badges: {
        outlined: {
            apply: "bordered",
            backgroundColor: colors.white,
            color: "primary",
            padding: ["0.125rem", "0.375rem"],
        },
    },
    buttons: {
        outlined: {
            apply: "bordered",
            backgroundColor: colors.white,
            color: "primary",
            padding: ["0.625rem", "1.375rem"],
            "&:hover": {
                backgroundColor: "primary",
                color: colors.white,
            },
        },
    },
    cards: {
        default: {
            apply: "bordered",
            backgroundColor: colors.white,
            boxShadow: ["none", "!important"],
        },
    },
    dialogs: {
        modal: {
            apply: "bordered",
            backgroundColor: colors.white,
        },
        scrim: {
            backdropFilter: "blur(2px)",
        },
    },
    forms: {
        input: {
            apply: "bordered",
            backgroundColor: colors.white,
            "&:focus": {
                borderColor: "primary",
            },
        },
        select: {
            apply: "bordered",
            backgroundColor: colors.white,
            "&:focus": {
                borderColor: "primary",
            },
        },
        textarea: {
            apply: "bordered",
            backgroundColor: colors.white,
            "&:focus": {
                borderColor: "primary",
            },
        },
    },
    links: {
        dropdown: {
            apply: "bordered",
            backgroundColor: colors.white,
        },
        navlink: {
            color: "primary",
            "&:hover": {
                backgroundColor: "highlight",
                color: colors.white,
            },
            "&.is-active": {
                backgroundColor: "highlight",
                color: colors.white,
            },
        },
    },
    styles: {
        hr: {
            backgroundColor: "primary",
        },
        // Additional helpers
        ".has-font-rubik": {
            fontFamily: "body",
        },
        ".has-font-garamond": {
            fontFamily: "heading",
        },
        ".is-bordered": {
            apply: "bordered",
        },
    },
};
<|endoftext|>


<commit_before>// AssessmentBuddy JavaScript functions.

window.ab = (function($) {
    // Init function.
    function init() {
        // Focus on the default element (if there is one).
        $("#focuselt").focus();
    }

    // For creating/editing a target.
    // When a rubric is selected, allow the user to select
    // the achievement levels for that rubric.
    function getAchievementLevelsForRubric(ajaxUrl) {
        var rubricId = $("#rubricId").val();
        console.log("Get achievement levels for rubric id=" + rubricId);
        $.ajax({
            url: ajaxUrl + '?id=' + rubricId,
            dataType: 'json',
            success: function(data, status, jqXHR) {
                console.log("Received " + data.length + " achievement level(s)");
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("Error receiving achievement levels: " + errorThrown);
            }
        });
    }

    // Return exported functions
    return {
        init: init,
        getAchievementLevelsForRubric: getAchievementLevelsForRubric
    };
})(jQuery);
<commit_msg>populate achievement levels when a rubric is selected<commit_after>// AssessmentBuddy JavaScript functions.

window.ab = (function($) {
    // Init function.
    function init() {
        // Focus on the default element (if there is one).
        $("#focuselt").focus();
    }

    // For creating/editing a target.
    // Update the achievement level selections based on the
    // specified array of AchievementLevel objects.
    function setAchievementLevels(achievementLevels) {
        var select = $("#achievementLevelId");
        // Remove all options but first
        select.find("option:gt(0)").remove();
        // Add options for achievement levels
        achievementLevels.forEach(function(val, index, arr) {
            console.log("appending id=" + val.id + ",name=" + val.name);
            select.append($("<option></option>").attr("value", val.id).text(val.name));
        });
    }

    // For creating/editing a target.
    // When a rubric is selected, allow the user to select
    // the achievement levels for that rubric.
    function getAchievementLevelsForRubric(ajaxUrl) {
        var rubricId = $("#rubricId").val();
        console.log("Get achievement levels for rubric id=" + rubricId);
        $.ajax({
            url: ajaxUrl + '?id=' + rubricId,
            dataType: 'json',
            success: function(data, status, jqXHR) {
                console.log("Received " + data.length + " achievement level(s)");
                setAchievementLevels(data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("Error receiving achievement levels: " + errorThrown);
            }
        });
    }

    // Return exported functions
    return {
        init: init,
        getAchievementLevelsForRubric: getAchievementLevelsForRubric,
        setAchievementLevels: setAchievementLevels
    };
})(jQuery);
<|endoftext|>


<commit_before>"use latest";

module.exports = function (context, req, res) {
    let templateLiteral = `<h1>Howdy, ${context.data.name}!</h1>`;

    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(templateLiteral);
}
<commit_msg>updated to const<commit_after>module.exports = function (context, req, res) {
    const templateLiteral = `<h1>Howdy, ${context.data.name}!</h1>`;

    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(templateLiteral);
}
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2016 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
/* global define, requirejs, _  */

var isFirefox = document.URL.indexOf( 'resource://' ) === 0;
var isFirefoxOS = document.URL.indexOf( 'app://' ) === 0;
var isChrome = document.URL.indexOf( 'chrome-extension://' ) === 0;
var isNode = false;
var isElectron = false;
var isCordovaAndroid = document.URL.indexOf( 'file:///android_asset' ) === 0;
var isCordovaiOS = /^file:\/{3}[^\/]/i.test(window.location.href) && /ios|iphone|ipod|ipad/i.test(navigator.userAgent);
var isCordova = isCordovaAndroid || isCordovaiOS;
var isWeb = document.URL.indexOf( 'http' ) === 0;
var isOSX = navigator.appVersion.indexOf("Mac")!==-1;
var isWin = navigator.appVersion.indexOf("Win")!==-1;

/**
 * The main loader module for the application
 * @name TSLoader
 */
(function () {
  // the value of this var is replaced to "true" by the build script
  var PRODUCTION = "@@PRODUCTION";
  var PRO = "@@PROVERSION";

  // Disabling all output to console in production mode
  if (PRODUCTION == "true") {
    console = console || {};
    console.log = function(){};
    console.warn = function(){};
    console.time = function(){};
    console.timeEnd = function(){};
    //console.error = function(){};
  }

  // Check for running in node-webkit
  try {
    require('nw.gui');
    isNode = true;
  } catch(e) {
    console.log("node-webkit not found!");
  }

  try {
    if (process.versions['electron']) {
      isElectron = true;
      //electron bug
      //https://github.com/atom/electron/issues/254
      window.$ = window.jQuery = require('./libs/jquery/dist/jquery.min.js');
    }
  } catch(e) {
    console.log(e.message);
  }
  var PRO_JS = "pro/js/pro.api";
  if(PRO.indexOf("@@PROVERS") == 0 || PRO == "false") { PRO_JS = 'js/pro'; }

  // Setting up the IO functionality according to the platform
  var IO_JS = "web/web.api";
  if( isFirefox ) {
    IO_JS = "mozilla/mozilla.api";
    PRO_JS = 'js/pro';
  } else if ( isChrome && !isNode ) {
    isNode = false;
    IO_JS = "chromium/chrome.api";
    PRO_JS = 'js/pro';
  } else if (isNode){
    isChrome = false;
    IO_JS = "node-webkit/node-webkit.api";
  } else if (isCordova){
    IO_JS = "cordova/cordova.api";
  } else if (isWeb){
    IO_JS = "web/web.api";
  } else if (isElectron) {
    IO_JS = "electron/electron.api"
  }

  console.log("Loading Loader - Firefox: "+isFirefox+" | ChromeExt: "+isChrome+" | Node: "+isNode+" | Cordova: "+isCordova+" | Web: "+isWeb+" | isWin: "+isWin+" | isElectron: "+isElectron);

  requirejs.config({
    map: {
      '*': {
        'css':   'libs/require-css/css.min',
        'text':  'libs/requiretext/index'
      }
    },
    paths: {
      jquery:                 'libs/jquery/dist/jquery.min',
      jqueryui:               'libs/jqueryui/jquery-ui.min',
      bootstrap:              'libs/bootstrap/dist/js/bootstrap.min',
      bootstrap3xeditable:    'libs/x-editable/dist/bootstrap3-editable/js/bootstrap-editable.min',
      bootstrapvalidator:     'libs/bootstrap-validator/dist/validator.min',
      jquerysimplecolorpicker:'libs/jquery-simplecolorpicker/jquery.simplecolorpicker',
      underscore:             'libs/underscore/index',
      d3:                     'libs/d3/d3.min',
      i18next:                'libs/i18next/i18next.amd.withJQuery.min',
      mousetrap:              'libs/mousetrap/mousetrap.min',
      mousetrapgb:            'libs/mousetrap/plugins/global-bind/mousetrap-global-bind.min',
      select2:                'libs/select2/select2.min',
      hammerjs:               'libs/hammerjs/hammer.min',
      jqueryhammerjs:         'libs/jquery.hammer.js/jquery.hammer',
      handlebarsjs:           'libs/handlebars/handlebars.min',
      pdfjs:                  'libs/pdfjs/build/pdf',
      webdavlib:              'web/webdavlib',
      jszip:                  'libs/jszip/dist/jszip.min',
      hopscotch:              'libs/hopscotch/dist/js/hopscotch.min',
      noty:                   'libs/noty/js/noty/packaged/jquery.noty.packaged.min',
      marked:                 'libs/marked/marked.min',
      webaudiorecording:      'libs/audio-record/WebAudioRecorder',
      offlinelib:             'web/offlinelib/offline.min',
      webdav:                 'web/webdavlib/webdavlib',
      leaflet:                'libs/leaflet/dist/leaflet',
      moment:                 'libs/moment/min/moment.min',
      momenttimezone:         'libs/moment-timezone/builds/moment-timezone.min',
      datetimepicker:         'libs/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min',

      tscore:                 'js/core.api',
      tssetting:              'js/settings.api',
      tssettingsdefault:      'js/settings.default',
      tsoptions:              'js/options.ui',
      tspersmanager:          'js/perspective.manager',
      tstagutils:             'js/tagutils',
      tssearch:               'js/search',
      tssearchui:             'js/search.ui',
      tsfileopener:           'js/fileopener',
      tstagsui:               'js/tags.ui',
      tsdirectoriesui:        'js/directories.ui',
      tscoreui:               'js/core.ui',
      tspostioapi:            'js/postioapi',
      tsdirectorybrowser:     'js/directorybrowser',
      tsutils:                'js/utils',
      tsioutils:              'js/ioutils',
      tsmeta:                 'js/meta',
      tsgettingstarted:       'js/gettingstarted',
      tsextapi:               'js/ext.api',
      tsextmanager:           'js/extension.manager',
      tsioapi:                 IO_JS,
      tspro:                   PRO_JS,
      tsaudiorecorderui:      'js/audiorecorder.ui',
      tsmapui:                'js/map.ui',
      tscalendarui:           'js/calendar.ui'
    },
    shim: {
      'underscore':               { exports: '_' },
      'bootstrap':                { deps: ['jquery'] },
      'jqueryui':                 { deps: ['jquery'] },
      'jquerysimplecolorpicker':  { deps: ['jquery','bootstrap'] },
      'bootstrap3xeditable':      { deps: ['jquery','bootstrap'] },
      'bootstrapvalidator':       { deps: ['jquery','bootstrap'] },
      'i18next':                  { deps: ['jquery'] },
      'select2':                  { deps: ['jquery'] },
      'hammerjs':                 { deps: ['jquery'] },
      'jqueryhammerjs':           { deps: ['hammerjs'] },
      'mousetrapgb':              { deps: ['mousetrap'] },
      'tscore':                   { deps: [
        'jquery',
        'jqueryui',
        'hammerjs',
        'jqueryhammerjs',
        'bootstrap',
        'bootstrap3xeditable',
        'bootstrapvalidator',
        'jquerysimplecolorpicker',
        'i18next',
        'mousetrap',
        'mousetrapgb',
        'select2',
        'handlebarsjs',
        'tssettingsdefault',
        'noty',
    ] }
    }
  });

  define(function (require) {
    requirejs(['tscore','underscore'], function (core) {
      if(isCordova) {
        require(["cordova.js"]);
      } else {
        core.initApp();
      }
    });
  });

})();
<commit_msg>update: transfer functions<commit_after>/* Copyright (c) 2012-2016 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
/* global define, requirejs, _  */

var isFirefox = document.URL.indexOf( 'resource://' ) === 0;
var isFirefoxOS = document.URL.indexOf( 'app://' ) === 0;
var isChrome = document.URL.indexOf( 'chrome-extension://' ) === 0;
var isNode = false;
var isElectron = false;
var isCordovaAndroid = document.URL.indexOf( 'file:///android_asset' ) === 0;
var isCordovaiOS = /^file:\/{3}[^\/]/i.test(window.location.href) && /ios|iphone|ipod|ipad/i.test(navigator.userAgent);
var isCordova = isCordovaAndroid || isCordovaiOS;
var isWeb = document.URL.indexOf( 'http' ) === 0;
var isOSX = navigator.appVersion.indexOf("Mac")!==-1;
var isWin = navigator.appVersion.indexOf("Win")!==-1;

/**
 * The main loader module for the application
 * @name TSLoader
 */
(function () {
  // the value of this var is replaced to "true" by the build script
  var PRODUCTION = "@@PRODUCTION";
  var PRO = "@@PROVERSION";

  // Disabling all output to console in production mode
  if (PRODUCTION == "true") {
    console = console || {};
    console.log = function(){};
    console.warn = function(){};
    console.time = function(){};
    console.timeEnd = function(){};
    //console.error = function(){};
  }

  // Check for running in node-webkit
  try {
    require('nw.gui');
    isNode = true;
  } catch(e) {
    console.log("node-webkit not found!");
  }

  try {
    if (process.versions['electron']) {
      isElectron = true;
      //electron bug
      //https://github.com/atom/electron/issues/254
      window.$ = window.jQuery = require('./libs/jquery/dist/jquery.min.js');
    }
  } catch(e) {
    console.log(e.message);
  }
  var PRO_JS = "pro/js/pro.api";
  //if(PRO.indexOf("@@PROVERS") == 0 || PRO == "false") { PRO_JS = 'js/pro'; }

  // Setting up the IO functionality according to the platform
  var IO_JS = "web/web.api";
  if( isFirefox ) {
    IO_JS = "mozilla/mozilla.api";
    PRO_JS = 'js/pro';
  } else if ( isChrome && !isNode ) {
    isNode = false;
    IO_JS = "chromium/chrome.api";
    PRO_JS = 'js/pro';
  } else if (isNode){
    isChrome = false;
    IO_JS = "node-webkit/node-webkit.api";
  } else if (isCordova){
    IO_JS = "cordova/cordova.api";
  } else if (isWeb){
    IO_JS = "web/web.api";
  } else if (isElectron) {
    IO_JS = "electron/electron.api"
  }

  console.log("Loading Loader - Firefox: "+isFirefox+" | ChromeExt: "+isChrome+" | Node: "+isNode+" | Cordova: "+isCordova+" | Web: "+isWeb+" | isWin: "+isWin+" | isElectron: "+isElectron);

  requirejs.config({
    map: {
      '*': {
        'css':   'libs/require-css/css.min',
        'text':  'libs/requiretext/index'
      }
    },
    paths: {
      jquery:                 'libs/jquery/dist/jquery.min',
      jqueryui:               'libs/jqueryui/jquery-ui.min',
      bootstrap:              'libs/bootstrap/dist/js/bootstrap.min',
      bootstrap3xeditable:    'libs/x-editable/dist/bootstrap3-editable/js/bootstrap-editable.min',
      bootstrapvalidator:     'libs/bootstrap-validator/dist/validator.min',
      jquerysimplecolorpicker:'libs/jquery-simplecolorpicker/jquery.simplecolorpicker',
      underscore:             'libs/underscore/index',
      d3:                     'libs/d3/d3.min',
      i18next:                'libs/i18next/i18next.amd.withJQuery.min',
      mousetrap:              'libs/mousetrap/mousetrap.min',
      mousetrapgb:            'libs/mousetrap/plugins/global-bind/mousetrap-global-bind.min',
      select2:                'libs/select2/select2.min',
      hammerjs:               'libs/hammerjs/hammer.min',
      jqueryhammerjs:         'libs/jquery.hammer.js/jquery.hammer',
      handlebarsjs:           'libs/handlebars/handlebars.min',
      pdfjs:                  'libs/pdfjs/build/pdf',
      webdavlib:              'web/webdavlib',
      jszip:                  'libs/jszip/dist/jszip.min',
      hopscotch:              'libs/hopscotch/dist/js/hopscotch.min',
      noty:                   'libs/noty/js/noty/packaged/jquery.noty.packaged.min',
      marked:                 'libs/marked/marked.min',
      webaudiorecording:      'libs/audio-record/WebAudioRecorder',
      offlinelib:             'web/offlinelib/offline.min',
      webdav:                 'web/webdavlib/webdavlib',
      moment:                 'libs/moment/min/moment.min',
      momenttimezone:         'libs/moment-timezone/builds/moment-timezone.min',
      datetimepicker:         'libs/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min',

      tscore:                 'js/core.api',
      tssetting:              'js/settings.api',
      tssettingsdefault:      'js/settings.default',
      tsoptions:              'js/options.ui',
      tspersmanager:          'js/perspective.manager',
      tstagutils:             'js/tagutils',
      tssearch:               'js/search',
      tssearchui:             'js/search.ui',
      tsfileopener:           'js/fileopener',
      tstagsui:               'js/tags.ui',
      tsdirectoriesui:        'js/directories.ui',
      tscoreui:               'js/core.ui',
      tspostioapi:            'js/postioapi',
      tsdirectorybrowser:     'js/directorybrowser',
      tsutils:                'js/utils',
      tsioutils:              'js/ioutils',
      tsmeta:                 'js/meta',
      tsgettingstarted:       'js/gettingstarted',
      tsextapi:               'js/ext.api',
      tsextmanager:           'js/extension.manager',
      tsioapi:                 IO_JS,
      tspro:                   PRO_JS,
      tsaudiorecorderui:      'js/audiorecorder.ui',
      tsmapui:                'js/map.ui',
      tscalendarui:           'js/calendar.ui'
    },
    shim: {
      'underscore':               { exports: '_' },
      'bootstrap':                { deps: ['jquery'] },
      'jqueryui':                 { deps: ['jquery'] },
      'jquerysimplecolorpicker':  { deps: ['jquery','bootstrap'] },
      'bootstrap3xeditable':      { deps: ['jquery','bootstrap'] },
      'bootstrapvalidator':       { deps: ['jquery','bootstrap'] },
      'i18next':                  { deps: ['jquery'] },
      'select2':                  { deps: ['jquery'] },
      'hammerjs':                 { deps: ['jquery'] },
      'jqueryhammerjs':           { deps: ['hammerjs'] },
      'mousetrapgb':              { deps: ['mousetrap'] },
      'tscore':                   { deps: [
        'jquery',
        'jqueryui',
        'hammerjs',
        'jqueryhammerjs',
        'bootstrap',
        'bootstrap3xeditable',
        'bootstrapvalidator',
        'jquerysimplecolorpicker',
        'i18next',
        'mousetrap',
        'mousetrapgb',
        'select2',
        'handlebarsjs',
        'tssettingsdefault',
        'noty',
    ] }
    }
  });

  define(function (require) {
    requirejs(['tscore','underscore'], function (core) {
      if(isCordova) {
        require(["cordova.js"]);
      } else {
        core.initApp();
      }
    });
  });

})();
<|endoftext|>


<commit_before>/* Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.*/

/**
 * @class Mobile.SalesLogix.Views._CardLayoutListMixin

 */
define('Mobile/SalesLogix/Views/_CardLayoutListMixin', [
    'dojo/_base/array',
    'dojo/_base/declare',
    'dojo/_base/event',
    'dojo/_base/lang',
    'dojo/dom-attr',
    'dojo/dom',
    'dojo/dom-construct',
    'dojo/query',
    'dojo/dom-class'

], function(
    array,
    declare,
    event,
    lang,
    domAttr,
    dom,
    domConstruct,
    query,
    domClass
) {

    return declare('Mobile.SalesLogix.Views._CardLayoutListMixin', null, {
        itemColorClass: 'color-default',
        itemIcon: 'content/images/icons/ContactProfile_48x48.png',
        itemIndicators:null,
        itemExts: null,
        itemTabValueProperty: '$descriptor',
        itemTabShowValue: false,
        itemTabShowGroupValue: false,
        itemIndicatorIconPath: 'content/images/icons/',
        itemIndicatorShowDisabled: true,
        itemIndicatorTemplate: new Simplate([
           '',
                '{% if ($.showIcon === false) { %}',
                     '{%: $.valueText %}',
                '{% } else { %}',
                      '',
                 '{% } %}',
           ''
        ]),
        itemExtTemplate: new Simplate([
            '

'
        ]),
        itemTabTemplate: new Simplate([
            '
',
            '

',
            '
{%: $$.getItemTabValue($) %}
',
            '

',
           '
'
        ]),
        itemRowContainerTemplate: new Simplate([
        '
',
            '{%! $$.itemRowContentTemplate %}',
        '
'
        ]),
        itemFooterTemplate: new Simplate([
            '
',
            '<button data-action="selectEntry" class="footer-item-selector button ">',
            '',
            '</button>',
            '
'
        ]),
        itemRowContentTemplate: new Simplate([
           '{%! $$.itemTabTemplate %}',
            '

',
            '<button data-action="selectEntry" class="list-item-selector button">',
            '',
            '</button>',
            '
{%! $$.itemTemplate %}
',
            '

',
            '
{%! $$.itemFooterTemplate %}
'
        ]),
        postMixInProperties: function() {
            this.inherited(arguments);
            this.cls = ' card-layout';
            this.rowTemplate = new Simplate([
             '{%! $$.itemRowContainerTemplate %}'
            ]);
            this.listActionTemplate = new Simplate([
                '

'
            ]),

            this.createIndicatorLayout();
        },
        getItemActionKey: function(entry) {
            return entry.$key
        },
        getItemDescriptor: function(entry) {
            return entry.$descriptor
        },
        getItemTabValue: function(entry)
        {
            var value = '';

            if (this.itemTabShowValue) {
                if (this.itemTabShowGroupValue) {
                    value = entry["$groupTitle"];
                } else {
                     value = entry[this.itemTabValueProperty];
                }
            }
            return value;

        },
        getItemColorClass: function(entry) {
            return this.itemColorClass;
        },
        getItemIconSource: function(entry) {
            return this.itemIcon || this.icon || this.selectIcon
        },
        createIndicatorLayout: function() {
            return this.itemIndicators || {};
        },
        createIndicators: function(topIndicatorsNode, bottomIndicatorsNode, indicators, entry) {
            var indicatorTemplate, indicator, options, indicatorHTML, i;
            for (i = 0; i < indicators.length; i++) {
                indicator = indicators[i];

                if (indicator.onApply) {
                    try{
                        indicator.onApply(entry, this);
                    }catch(err){
                        indicator.isEnabled = false;
                    }
                }
                options = {
                    indicatorIndex: i,
                    indicatorIcon: this.itemIndicatorIconPath + indicator.icon,
                };
                indicatorTemplate = indicator.template || this.itemIndicatorTemplate;

                lang.mixin(indicator, options);

                if (indicator.isEnabled === false) {
                    indicator.indicatorIcon = this.itemIndicatorIconPath + 'disabled_' + indicator.icon
                    indicator.label = '';
                } else {
                    indicator.indicatorIcon + indicator.icon;
                }

                if (indicator.isEnabled === false && indicator.showIcon === false) {
                    continue;
                }

                if (this.itemIndicatorShowDisabled || indicator.isEnabled) {

                    if (indicator.isEnabled === false && indicator.showIcon === false) {
                        continue;
                    } else {

                        indicatorHTML = indicatorTemplate.apply(indicator, indicator.id);
                        if (indicator.location === 'top') {
                            domConstruct.place(indicatorHTML, topIndicatorsNode, 'last');
                        } else {
                            domConstruct.place(indicatorHTML, bottomIndicatorsNode, 'last');
                        }
                    }
                }
            }
        },

        onApplyRowTemplate: function(entry, rowNode) {

            this.applyRowIndicators(entry, rowNode);

        },
        applyRowIndicators:function(entry, rowNode){
            var topIndicatorsNode, bottomIndicatorsNode;
            if (this.itemIndicators && this.itemIndicators.length > 0) {
                topIndicatorsNode = query('> #top_item_indicators', rowNode);
                bottomIndicatorsNode = query('> #bottom_item_indicators', rowNode);
                if (bottomIndicatorsNode[0] && topIndicatorsNode[0]) {
                    if (bottomIndicatorsNode[0].childNodes.length === 0 && topIndicatorsNode[0].childNodes.length === 0 ) {
                        this.createIndicators(topIndicatorsNode[0], bottomIndicatorsNode[0], this._createCustomizedLayout(this.itemIndicators, 'indicators'), entry);
                    }
                }
            }
        }
    });

});
<commit_msg>Fixing Formating<commit_after>/* Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.*/

/**
 * @class Mobile.SalesLogix.Views._CardLayoutListMixin

 */
define('Mobile/SalesLogix/Views/_CardLayoutListMixin', [
    'dojo/_base/array',
    'dojo/_base/declare',
    'dojo/_base/event',
    'dojo/_base/lang',
    'dojo/dom-attr',
    'dojo/dom',
    'dojo/dom-construct',
    'dojo/query',
    'dojo/dom-class'

], function(
    array,
    declare,
    event,
    lang,
    domAttr,
    dom,
    domConstruct,
    query,
    domClass
) {

    return declare('Mobile.SalesLogix.Views._CardLayoutListMixin', null, {
        itemColorClass: 'color-default',
        itemIcon: 'content/images/icons/ContactProfile_48x48.png',
        itemIndicators:null,
        itemExts: null,
        itemTabValueProperty: '$descriptor',
        itemTabShowValue: false,
        itemTabShowGroupValue: false,
        itemIndicatorIconPath: 'content/images/icons/',
        itemIndicatorShowDisabled: true,
        itemIndicatorTemplate: new Simplate([
           '',
                '{% if ($.showIcon === false) { %}',
                     '{%: $.valueText %}',
                '{% } else { %}',
                      '',
                 '{% } %}',
           ''
        ]),
        itemExtTemplate: new Simplate([
            '

'
        ]),
        itemTabTemplate: new Simplate([
            '
',
            '

',
            '
{%: $$.getItemTabValue($) %}
',
            '

',
           '
'
        ]),
        itemRowContainerTemplate: new Simplate([
        '
',
            '{%! $$.itemRowContentTemplate %}',
        '
'
        ]),
        itemFooterTemplate: new Simplate([
            '
',
            '<button data-action="selectEntry" class="footer-item-selector button ">',
            '',
            '</button>',
            '
'
        ]),
        itemRowContentTemplate: new Simplate([
           '{%! $$.itemTabTemplate %}',
            '

',
            '<button data-action="selectEntry" class="list-item-selector button">',
            '',
            '</button>',
            '
{%! $$.itemTemplate %}
',
            '

',
            '
{%! $$.itemFooterTemplate %}
'
        ]),
        postMixInProperties: function() {
            this.inherited(arguments);
            this.cls = ' card-layout';
            this.rowTemplate = new Simplate([
             '{%! $$.itemRowContainerTemplate %}'
            ]);
            this.listActionTemplate = new Simplate([
                '

'
            ]),

            this.createIndicatorLayout();
        },
        getItemActionKey: function(entry) {
            return entry.$key
        },
        getItemDescriptor: function(entry) {
            return entry.$descriptor
        },
        getItemTabValue: function(entry) {
            var value = '';

            if (this.itemTabShowValue) {
                if (this.itemTabShowGroupValue) {
                    value = entry["$groupTitle"];
                } else {
                     value = entry[this.itemTabValueProperty];
                }
            }
            return value;

        },
        getItemColorClass: function(entry) {
            return this.itemColorClass;
        },
        getItemIconSource: function(entry) {
            return this.itemIcon || this.icon || this.selectIcon
        },
        createIndicatorLayout: function() {
            return this.itemIndicators || {};
        },
        createIndicators: function(topIndicatorsNode, bottomIndicatorsNode, indicators, entry) {
            var indicatorTemplate, indicator, options, indicatorHTML, i;
            for (i = 0; i < indicators.length; i++) {
                indicator = indicators[i];

                if (indicator.onApply) {
                    try{
                        indicator.onApply(entry, this);
                    }catch(err){
                        indicator.isEnabled = false;
                    }
                }
                options = {
                    indicatorIndex: i,
                    indicatorIcon: this.itemIndicatorIconPath + indicator.icon,
                };
                indicatorTemplate = indicator.template || this.itemIndicatorTemplate;

                lang.mixin(indicator, options);

                if (indicator.isEnabled === false) {
                    indicator.indicatorIcon = this.itemIndicatorIconPath + 'disabled_' + indicator.icon
                    indicator.label = '';
                } else {
                    indicator.indicatorIcon + indicator.icon;
                }

                if (indicator.isEnabled === false && indicator.showIcon === false) {
                    continue;
                }

                if (this.itemIndicatorShowDisabled || indicator.isEnabled) {

                    if (indicator.isEnabled === false && indicator.showIcon === false) {
                        continue;
                    } else {

                        indicatorHTML = indicatorTemplate.apply(indicator, indicator.id);
                        if (indicator.location === 'top') {
                            domConstruct.place(indicatorHTML, topIndicatorsNode, 'last');
                        } else {
                            domConstruct.place(indicatorHTML, bottomIndicatorsNode, 'last');
                        }
                    }
                }
            }
        },

        onApplyRowTemplate: function(entry, rowNode) {

            this.applyRowIndicators(entry, rowNode);

        },
        applyRowIndicators:function(entry, rowNode){
            var topIndicatorsNode, bottomIndicatorsNode;
            if (this.itemIndicators && this.itemIndicators.length > 0) {
                topIndicatorsNode = query('> #top_item_indicators', rowNode);
                bottomIndicatorsNode = query('> #bottom_item_indicators', rowNode);
                if (bottomIndicatorsNode[0] && topIndicatorsNode[0]) {
                    if (bottomIndicatorsNode[0].childNodes.length === 0 && topIndicatorsNode[0].childNodes.length === 0 ) {
                        this.createIndicators(topIndicatorsNode[0], bottomIndicatorsNode[0], this._createCustomizedLayout(this.itemIndicators, 'indicators'), entry);
                    }
                }
            }
        }
    });

});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.MemoryStatistics}
 * @param {!WebInspector.TimelinePanel} timelinePanel
 * @param {!WebInspector.TimelineModel} model
 */
WebInspector.DOMCountersGraph = function(timelinePanel, model)
{
    WebInspector.MemoryStatistics.call(this, timelinePanel, model);
}

/**
 * @constructor
 * @extends {WebInspector.CounterUIBase}
 * @param {!WebInspector.DOMCountersGraph} memoryCountersPane
 * @param {string} title
 * @param {string} currentValueLabel
 * @param {!string} color
 * @param {function(!WebInspector.DOMCountersGraph.Counter):number} valueGetter
 */
WebInspector.DOMCounterUI = function(memoryCountersPane, title, currentValueLabel, color, valueGetter)
{
    WebInspector.CounterUIBase.call(this, memoryCountersPane, title, color, valueGetter)
    this._range = this._swatch.element.createChild("span");

    this._value = memoryCountersPane._currentValuesBar.createChild("span", "memory-counter-value");
    this._value.style.color = color;
    this._currentValueLabel = currentValueLabel;

    this.graphColor = color;
    this.graphYValues = [];
}

/**
 * @constructor
 * @extends {WebInspector.MemoryStatistics.Counter}
 * @param {number} time
 * @param {number} documentCount
 * @param {number} nodeCount
 * @param {number} listenerCount
 */
WebInspector.DOMCountersGraph.Counter = function(time, documentCount, nodeCount, listenerCount, usedGPUMemoryKBytes)
{
    WebInspector.MemoryStatistics.Counter.call(this, time);
    this.documentCount = documentCount;
    this.nodeCount = nodeCount;
    this.listenerCount = listenerCount;
    this.usedGPUMemoryKBytes = usedGPUMemoryKBytes;
}

WebInspector.DOMCounterUI.prototype = {
    /**
     * @param {number} minValue
     * @param {number} maxValue
     */
    setRange: function(minValue, maxValue)
    {
        this._range.textContent = WebInspector.UIString("[%d:%d]", minValue, maxValue);
    },

    updateCurrentValue: function(countersEntry)
    {
        this._value.textContent = WebInspector.UIString(this._currentValueLabel, this.valueGetter(countersEntry));
    },

    clearCurrentValueAndMarker: function(ctx)
    {
        this._value.textContent = "";
        this.restoreImageUnderMarker(ctx);
    },

    /**
     * @param {!CanvasRenderingContext2D} ctx
     * @param {number} x
     * @param {number} y
     * @param {number} radius
     */
    saveImageUnderMarker: function(ctx, x, y, radius)
    {
        const w = radius + 1;
        var imageData = ctx.getImageData(x - w, y - w, 2 * w, 2 * w);
        this._imageUnderMarker = {
            x: x - w,
            y: y - w,
            imageData: imageData
        };
    },

    /**
     * @param {!CanvasRenderingContext2D} ctx
     */
    restoreImageUnderMarker: function(ctx)
    {
        if (!this.visible)
            return;
        if (this._imageUnderMarker)
            ctx.putImageData(this._imageUnderMarker.imageData, this._imageUnderMarker.x, this._imageUnderMarker.y);
        this.discardImageUnderMarker();
    },

    discardImageUnderMarker: function()
    {
        delete this._imageUnderMarker;
    },

    __proto__: WebInspector.CounterUIBase.prototype
}

WebInspector.DOMCountersGraph.prototype = {
    _createCurrentValuesBar: function()
    {
        this._currentValuesBar = this._canvasContainer.createChild("div");
        this._currentValuesBar.id = "counter-values-bar";
        this._canvasContainer.classList.add("dom-counters");
    },

    /**
     * @return {!Element}
     */
    resizeElement: function()
    {
        return this._currentValuesBar;
    },

    /**
     * @return {!Array.<!WebInspector.DOMCounterUI>}
     */
    _createCounterUIList: function()
    {
        function getDocumentCount(entry)
        {
            return entry.documentCount;
        }
        function getNodeCount(entry)
        {
            return entry.nodeCount;
        }
        function getListenerCount(entry)
        {
            return entry.listenerCount;
        }
        function getUsedGPUMemoryKBytes(entry)
        {
            return entry.usedGPUMemoryKBytes || 0;
        }
        var counterUIs = [
            new WebInspector.DOMCounterUI(this, "Documents", "Documents: %d", "#d00", getDocumentCount),
            new WebInspector.DOMCounterUI(this, "Nodes", "Nodes: %d", "#0a0", getNodeCount),
            new WebInspector.DOMCounterUI(this, "Listeners", "Listeners: %d", "#00d", getListenerCount)
        ];
        if (WebInspector.experimentsSettings.gpuTimeline.isEnabled())
            counterUIs.push(new WebInspector.DOMCounterUI(this, "GPU Memory", "GPU Memory [KB]: %d", "#c0c", getUsedGPUMemoryKBytes));
        return counterUIs;
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _onRecordAdded: function(event)
    {
        /**
         * @param {!Array.<!T>} array
         * @param {!S} item
         * @param {!function(!T,!S):!number} comparator
         * @return {!number}
         * @template T,S
         */
        function findInsertionLocation(array, item, comparator)
        {
            var index = array.length;
            while (index > 0 && comparator(array[index - 1], item) > 0)
                --index;
            return index;
        }

        /**
         * @this {WebInspector.DOMCountersGraph}
         */
        function addStatistics(record)
        {
            var counters = record["counters"];
            var isGPURecord = record.data && typeof record.data["usedGPUMemoryBytes"] !== "undefined";
            if (isGPURecord) {
                counters = counters || {
                    "startTime": record.startTime,
                    "endTime": record.endTime
                };
                counters["usedGPUMemoryKBytes"] = Math.round(record.data["usedGPUMemoryBytes"] / 1024);
            }
            if (!counters)
                return;

            var time = record.endTime || record.startTime;
            var counter = new WebInspector.DOMCountersGraph.Counter(
                time,
                counters["documents"],
                counters["nodes"],
                counters["jsEventListeners"],
                counters["usedGPUMemoryKBytes"]
            );

            function compare(record, time)
            {
                return record.time - time;
            }
            var index = findInsertionLocation(this._counters, time, compare);
            this._counters.splice(index, 0, counter);
            if (isGPURecord) {
                // Populate missing values from preceeding records.
                // FIXME: Refactor the code to make each WebInspector.DOMCountersGraph.Counter
                // be responsible for a single graph to avoid such synchronizations.
                for (var i = index - 1; i >= 0 && typeof this._counters[i].usedGPUMemoryKBytes === "undefined"; --i) { }
                var usedGPUMemoryKBytes = this._counters[i >= 0 ? i : index].usedGPUMemoryKBytes;
                for (i = Math.max(i, 0); i < index; ++i)
                    this._counters[i].usedGPUMemoryKBytes = usedGPUMemoryKBytes;
                var copyFrom = index > 0 ? index - 1 : index + 1;
                if (copyFrom < this._counters.length) {
                    this._counters[index].documentCount = this._counters[copyFrom].documentCount;
                    this._counters[index].nodeCount = this._counters[copyFrom].nodeCount;
                    this._counters[index].listenerCount = this._counters[copyFrom].listenerCount;
                } else {
                    this._counters[index].documentCount =  0;
                    this._counters[index].nodeCount = 0;
                    this._counters[index].listenerCount = 0;
                }
            }
        }
        WebInspector.TimelinePresentationModel.forAllRecords([event.data], null, addStatistics.bind(this));
    },

    draw: function()
    {
        WebInspector.MemoryStatistics.prototype.draw.call(this);
        for (var i = 0; i < this._counterUI.length; i++)
            this._drawGraph(this._counterUI[i]);
    },

    /**
     * @param {!CanvasRenderingContext2D} ctx
     */
    _restoreImageUnderMarker: function(ctx)
    {
        for (var i = 0; i < this._counterUI.length; i++) {
            var counterUI = this._counterUI[i];
            if (!counterUI.visible)
                continue;
            counterUI.restoreImageUnderMarker(ctx);
        }
    },

    /**
     * @param {!CanvasRenderingContext2D} ctx
     * @param {number} x
     * @param {number} index
     */
    _saveImageUnderMarker: function(ctx, x, index)
    {
        const radius = 2;
        for (var i = 0; i < this._counterUI.length; i++) {
            var counterUI = this._counterUI[i];
            if (!counterUI.visible)
                continue;
            var y = counterUI.graphYValues[index];
            counterUI.saveImageUnderMarker(ctx, x, y, radius);
        }
    },

    /**
     * @param {!CanvasRenderingContext2D} ctx
     * @param {number} x
     * @param {number} index
     */
    _drawMarker: function(ctx, x, index)
    {
        this._saveImageUnderMarker(ctx, x, index);
        const radius = 2;
        for (var i = 0; i < this._counterUI.length; i++) {
            var counterUI = this._counterUI[i];
            if (!counterUI.visible)
                continue;
            var y = counterUI.graphYValues[index];
            ctx.beginPath();
            ctx.arc(x + 0.5, y + 0.5, radius, 0, Math.PI * 2, true);
            ctx.lineWidth = 1;
            ctx.fillStyle = counterUI.graphColor;
            ctx.strokeStyle = counterUI.graphColor;
            ctx.fill();
            ctx.stroke();
            ctx.closePath();
        }
    },

    /**
     * @param {!WebInspector.CounterUIBase} counterUI
     */
    _drawGraph: function(counterUI)
    {
        var canvas = this._canvas;
        var ctx = canvas.getContext("2d");
        var width = canvas.width;
        var height = this._clippedHeight;
        var originY = this._originY;
        var valueGetter = counterUI.valueGetter;

        if (!this._counters.length)
            return;

        var maxValue;
        var minValue;
        for (var i = this._minimumIndex; i <= this._maximumIndex; i++) {
            var value = valueGetter(this._counters[i]);
            if (minValue === undefined || value < minValue)
                minValue = value;
            if (maxValue === undefined || value > maxValue)
                maxValue = value;
        }

        counterUI.setRange(minValue, maxValue);

        if (!counterUI.visible)
            return;

        var yValues = counterUI.graphYValues;
        yValues.length = this._counters.length;

        var maxYRange = maxValue - minValue;
        var yFactor = maxYRange ? height / (maxYRange) : 1;

        ctx.save();
        ctx.translate(0.5, 0.5);
        ctx.beginPath();
        var currentY = Math.round(originY + (height - (valueGetter(this._counters[this._minimumIndex]) - minValue) * yFactor));
        ctx.moveTo(0, currentY);
        for (var i = this._minimumIndex; i <= this._maximumIndex; i++) {
             var x = Math.round(this._counters[i].x);
             ctx.lineTo(x, currentY);
             currentY = Math.round(originY + (height - (valueGetter(this._counters[i]) - minValue) * yFactor));
             ctx.lineTo(x, currentY);
             yValues[i] = currentY;
        }
        ctx.lineTo(width, currentY);
        ctx.lineWidth = 1;
        ctx.strokeStyle = counterUI.graphColor;
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    },

    _discardImageUnderMarker: function()
    {
        for (var i = 0; i < this._counterUI.length; i++)
            this._counterUI[i].discardImageUnderMarker();
    },

    __proto__: WebInspector.MemoryStatistics.prototype
}

<commit_msg>DevTools: Show the last valid value for GPU memory counter.<commit_after>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.MemoryStatistics}
 * @param {!WebInspector.TimelinePanel} timelinePanel
 * @param {!WebInspector.TimelineModel} model
 */
WebInspector.DOMCountersGraph = function(timelinePanel, model)
{
    WebInspector.MemoryStatistics.call(this, timelinePanel, model);
}

/**
 * @constructor
 * @extends {WebInspector.CounterUIBase}
 * @param {!WebInspector.DOMCountersGraph} memoryCountersPane
 * @param {string} title
 * @param {string} currentValueLabel
 * @param {!string} color
 * @param {function(!WebInspector.DOMCountersGraph.Counter):number} valueGetter
 */
WebInspector.DOMCounterUI = function(memoryCountersPane, title, currentValueLabel, color, valueGetter)
{
    WebInspector.CounterUIBase.call(this, memoryCountersPane, title, color, valueGetter)
    this._range = this._swatch.element.createChild("span");

    this._value = memoryCountersPane._currentValuesBar.createChild("span", "memory-counter-value");
    this._value.style.color = color;
    this._currentValueLabel = currentValueLabel;

    this.graphColor = color;
    this.graphYValues = [];
}

/**
 * @constructor
 * @extends {WebInspector.MemoryStatistics.Counter}
 * @param {number} time
 * @param {number} documentCount
 * @param {number} nodeCount
 * @param {number} listenerCount
 */
WebInspector.DOMCountersGraph.Counter = function(time, documentCount, nodeCount, listenerCount, usedGPUMemoryKBytes)
{
    WebInspector.MemoryStatistics.Counter.call(this, time);
    this.documentCount = documentCount;
    this.nodeCount = nodeCount;
    this.listenerCount = listenerCount;
    this.usedGPUMemoryKBytes = usedGPUMemoryKBytes;
}

WebInspector.DOMCounterUI.prototype = {
    /**
     * @param {number} minValue
     * @param {number} maxValue
     */
    setRange: function(minValue, maxValue)
    {
        this._range.textContent = WebInspector.UIString("[%d:%d]", minValue, maxValue);
    },

    updateCurrentValue: function(countersEntry)
    {
        this._value.textContent = WebInspector.UIString(this._currentValueLabel, this.valueGetter(countersEntry));
    },

    clearCurrentValueAndMarker: function(ctx)
    {
        this._value.textContent = "";
        this.restoreImageUnderMarker(ctx);
    },

    /**
     * @param {!CanvasRenderingContext2D} ctx
     * @param {number} x
     * @param {number} y
     * @param {number} radius
     */
    saveImageUnderMarker: function(ctx, x, y, radius)
    {
        const w = radius + 1;
        var imageData = ctx.getImageData(x - w, y - w, 2 * w, 2 * w);
        this._imageUnderMarker = {
            x: x - w,
            y: y - w,
            imageData: imageData
        };
    },

    /**
     * @param {!CanvasRenderingContext2D} ctx
     */
    restoreImageUnderMarker: function(ctx)
    {
        if (!this.visible)
            return;
        if (this._imageUnderMarker)
            ctx.putImageData(this._imageUnderMarker.imageData, this._imageUnderMarker.x, this._imageUnderMarker.y);
        this.discardImageUnderMarker();
    },

    discardImageUnderMarker: function()
    {
        delete this._imageUnderMarker;
    },

    __proto__: WebInspector.CounterUIBase.prototype
}

WebInspector.DOMCountersGraph.prototype = {
    _createCurrentValuesBar: function()
    {
        this._currentValuesBar = this._canvasContainer.createChild("div");
        this._currentValuesBar.id = "counter-values-bar";
        this._canvasContainer.classList.add("dom-counters");
    },

    /**
     * @return {!Element}
     */
    resizeElement: function()
    {
        return this._currentValuesBar;
    },

    /**
     * @return {!Array.<!WebInspector.DOMCounterUI>}
     */
    _createCounterUIList: function()
    {
        function getDocumentCount(entry)
        {
            return entry.documentCount;
        }
        function getNodeCount(entry)
        {
            return entry.nodeCount;
        }
        function getListenerCount(entry)
        {
            return entry.listenerCount;
        }
        function getUsedGPUMemoryKBytes(entry)
        {
            return entry.usedGPUMemoryKBytes;
        }
        var counterUIs = [
            new WebInspector.DOMCounterUI(this, "Documents", "Documents: %d", "#d00", getDocumentCount),
            new WebInspector.DOMCounterUI(this, "Nodes", "Nodes: %d", "#0a0", getNodeCount),
            new WebInspector.DOMCounterUI(this, "Listeners", "Listeners: %d", "#00d", getListenerCount)
        ];
        if (WebInspector.experimentsSettings.gpuTimeline.isEnabled())
            counterUIs.push(new WebInspector.DOMCounterUI(this, "GPU Memory", "GPU Memory [KB]: %d", "#c0c", getUsedGPUMemoryKBytes));
        return counterUIs;
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _onRecordAdded: function(event)
    {
        /**
         * @param {!Array.<!T>} array
         * @param {!S} item
         * @param {!function(!T,!S):!number} comparator
         * @return {!number}
         * @template T,S
         */
        function findInsertionLocation(array, item, comparator)
        {
            var index = array.length;
            while (index > 0 && comparator(array[index - 1], item) > 0)
                --index;
            return index;
        }

        /**
         * @this {WebInspector.DOMCountersGraph}
         */
        function addStatistics(record)
        {
            var counters = record["counters"];
            var isGPURecord = record.data && typeof record.data["usedGPUMemoryBytes"] !== "undefined";
            if (isGPURecord) {
                counters = counters || {
                    "startTime": record.startTime,
                    "endTime": record.endTime
                };
                counters["usedGPUMemoryKBytes"] = Math.round(record.data["usedGPUMemoryBytes"] / 1024);
            }
            if (!counters)
                return;

            var time = record.endTime || record.startTime;
            var counter = new WebInspector.DOMCountersGraph.Counter(
                time,
                counters["documents"],
                counters["nodes"],
                counters["jsEventListeners"],
                counters["usedGPUMemoryKBytes"]
            );

            function compare(record, time)
            {
                return record.time - time;
            }
            var index = findInsertionLocation(this._counters, time, compare);
            this._counters.splice(index, 0, counter);
            if (isGPURecord) {
                // Populate missing values from preceeding records.
                // FIXME: Refactor the code to make each WebInspector.DOMCountersGraph.Counter
                // be responsible for a single graph to avoid such synchronizations.
                for (var i = index - 1; i >= 0 && typeof this._counters[i].usedGPUMemoryKBytes === "undefined"; --i) { }
                var usedGPUMemoryKBytes = this._counters[i >= 0 ? i : index].usedGPUMemoryKBytes;
                for (i = Math.max(i, 0); i < index; ++i)
                    this._counters[i].usedGPUMemoryKBytes = usedGPUMemoryKBytes;
                var copyFrom = index > 0 ? index - 1 : index + 1;
                if (copyFrom < this._counters.length) {
                    this._counters[index].documentCount = this._counters[copyFrom].documentCount;
                    this._counters[index].nodeCount = this._counters[copyFrom].nodeCount;
                    this._counters[index].listenerCount = this._counters[copyFrom].listenerCount;
                } else {
                    this._counters[index].documentCount =  0;
                    this._counters[index].nodeCount = 0;
                    this._counters[index].listenerCount = 0;
                }
            }
        }
        WebInspector.TimelinePresentationModel.forAllRecords([event.data], null, addStatistics.bind(this));
    },

    draw: function()
    {
        WebInspector.MemoryStatistics.prototype.draw.call(this);
        for (var i = 0; i < this._counterUI.length; i++)
            this._drawGraph(this._counterUI[i]);
    },

    /**
     * @param {!CanvasRenderingContext2D} ctx
     */
    _restoreImageUnderMarker: function(ctx)
    {
        for (var i = 0; i < this._counterUI.length; i++) {
            var counterUI = this._counterUI[i];
            if (!counterUI.visible)
                continue;
            counterUI.restoreImageUnderMarker(ctx);
        }
    },

    /**
     * @param {!CanvasRenderingContext2D} ctx
     * @param {number} x
     * @param {number} index
     */
    _saveImageUnderMarker: function(ctx, x, index)
    {
        const radius = 2;
        for (var i = 0; i < this._counterUI.length; i++) {
            var counterUI = this._counterUI[i];
            if (!counterUI.visible)
                continue;
            var y = counterUI.graphYValues[index];
            counterUI.saveImageUnderMarker(ctx, x, y, radius);
        }
    },

    /**
     * @param {!CanvasRenderingContext2D} ctx
     * @param {number} x
     * @param {number} index
     */
    _drawMarker: function(ctx, x, index)
    {
        this._saveImageUnderMarker(ctx, x, index);
        const radius = 2;
        for (var i = 0; i < this._counterUI.length; i++) {
            var counterUI = this._counterUI[i];
            if (!counterUI.visible)
                continue;
            var y = counterUI.graphYValues[index];
            ctx.beginPath();
            ctx.arc(x + 0.5, y + 0.5, radius, 0, Math.PI * 2, true);
            ctx.lineWidth = 1;
            ctx.fillStyle = counterUI.graphColor;
            ctx.strokeStyle = counterUI.graphColor;
            ctx.fill();
            ctx.stroke();
            ctx.closePath();
        }
    },

    /**
     * @param {!WebInspector.CounterUIBase} counterUI
     */
    _drawGraph: function(counterUI)
    {
        var canvas = this._canvas;
        var ctx = canvas.getContext("2d");
        var width = canvas.width;
        var height = this._clippedHeight;
        var originY = this._originY;
        var valueGetter = counterUI.valueGetter;

        if (!this._counters.length)
            return;

        var maxValue;
        var minValue;
        for (var i = this._minimumIndex; i <= this._maximumIndex; i++) {
            var value = valueGetter(this._counters[i]);
            if (minValue === undefined || value < minValue)
                minValue = value;
            if (maxValue === undefined || value > maxValue)
                maxValue = value;
        }

        counterUI.setRange(minValue, maxValue);

        if (!counterUI.visible)
            return;

        var yValues = counterUI.graphYValues;
        yValues.length = this._counters.length;

        var maxYRange = maxValue - minValue;
        var yFactor = maxYRange ? height / (maxYRange) : 1;

        ctx.save();
        ctx.translate(0.5, 0.5);
        ctx.beginPath();
        var value = valueGetter(this._counters[this._minimumIndex]) || 0;
        var currentY = Math.round(originY + height - (value - minValue) * yFactor);
        ctx.moveTo(0, currentY);
        for (var i = this._minimumIndex; i <= this._maximumIndex; i++) {
             var x = Math.round(this._counters[i].x);
             ctx.lineTo(x, currentY);
             var currentValue = valueGetter(this._counters[i]);
             if (typeof currentValue !== "undefined")
                value = currentValue;
             currentY = Math.round(originY + height - (value - minValue) * yFactor);
             ctx.lineTo(x, currentY);
             yValues[i] = currentY;
        }
        ctx.lineTo(width, currentY);
        ctx.lineWidth = 1;
        ctx.strokeStyle = counterUI.graphColor;
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    },

    _discardImageUnderMarker: function()
    {
        for (var i = 0; i < this._counterUI.length; i++)
            this._counterUI[i].discardImageUnderMarker();
    },

    __proto__: WebInspector.MemoryStatistics.prototype
}

<|endoftext|>


<commit_before>'use strict'

const {
  angular,
  FileReader
} = window

angular.module('scegratooApp')
  .service('TreeNode', function Project (React, R, TreeNodeAttribute, Project, moveables) {
    const {
      __,
      always,
      complement,
      contains,
      eq,
      filter,
      flatten,
      ifElse,
      map,
      mergeAll,
      pipe,
      prop,
      toLower
    } = R
    const isInline = pipe(
        prop('nodeName'),
        toLower,
        eq('inline')
    )
    const isGUI = pipe(
      prop('className'),
      toLower,
      eq('gui')
    )
    const unlessInline = ifElse(
      isInline,
      always(undefined)
    )
    const bulletStyle = {
      width: '10px',
      height: '10px',
      borderRadius: '50%',
      fontSize: '20px',
      color: '#fff',
      lineHeight: '100px',
      textAlign: 'center',
      background: '#000',
      marginRight: '5px',
      cursor: 'pointer'
    }
    const collapsedStyle = {
      background: '#d9d9d9'
    }
    const removeStyle = {
      color: 'red',
      marginLeft: '10px',
      marginRight: '10px'
    }
    const syncStyle = {
      color: 'blue'
    }

    let viewPointPosition
    let viewPointOrientation

    const TreeNode = React.createClass({
      displayName: 'TreeNode',
      getInitialState: function () {
        return {
          collapsed: false,
          // these are necessary because the browser fires the dragEnter and dragLeave events interleaved:
          //   dragEnter, dragEnter, dragLeave, dragLeave
          // thus making it necessary to keep track of the number of enters and leaves (or at least two of them)
          // thanks to dragster for this idea (https://github.com/bensmithett/dragster/blob/gh-pages/src/dragster.coffee)
          dragEntered1: false,
          dragEntered2: false
        }
      },
      propTypes: {
        data: React.PropTypes.object.isRequired,
        runtime: React.PropTypes.object.isRequired
      },
      componentDidMount: function () {
        const node = this.props.data

        if (node.nodeName.toLowerCase() === 'viewpoint') {
          node.addEventListener('viewpointChanged', event => {
            viewPointPosition = event.position
            viewPointOrientation = event.orientation
          })
        }

      },
      clicked: function (event) {
        this.props.runtime.showObject(this.props.data, 'xAxis')
      },
      toggleVisibility: function (event) {
        const element = event.currentTarget.parentNode.nextSibling

        if (this.state.collapsed) {
          element.style.display = ''
          this.setState({
            collapsed: false
          })
        } else {
          element.style.display = 'none'
          this.setState({
            collapsed: true
          })
        }
      },
      syncViewpoint: function (event) {
        const node = this.props.data

        node.setAttribute('orientation', `${viewPointOrientation[0].toString()} ${viewPointOrientation[1]}`)
        node.setAttribute('position', viewPointPosition.toString())
      },
      dragStart: function (event) {
        this.getDOMNode().style.opacity = 0.4
        event.node = this.props.data
      },
      dragEnd: function (event) {
        this.getDOMNode().style.opacity = 1
      },
      drop: function (event) {
        const node = event.node
        event.node = undefined

        event.stopPropagation() // Stops some browsers from redirecting.
        event.preventDefault()

        if (node && !node.contains(this.props.data)) {
          node.parentElement.removeChild(node)
          this.props.data.appendChild(node)
        } else if (event.dataTransfer.files) {
          const files = flatten(event.dataTransfer.files) // turn into real array

          files.forEach(file => {
            const reader = new FileReader()

            reader.onload = event => {
              Project
                .uploadFile(file.name, event.target.result)
                .catch(() => window.alert('Upload failed.'))
                .then((result) => {
                  const transform = document.createElement('Transform')
                  const inline = document.createElement('Inline')
                  inline.setAttribute('url', result.data)
                  transform.appendChild(inline)
                  this.props.data.appendChild(transform)
                })
            }
            reader.readAsText(file)
          })
        } else if (event.dataTransfer.items.length > 0) {
          const url = event.dataTransfer.getData('text/plain')

          const transform = document.createElement('Transform')
          const inline = document.createElement('Inline')

          inline.setAttribute('url', url)
          transform.appendChild(inline)
          this.props.data.appendChild(transform)
        }
        this.getDOMNode().style.background = ''
      },
      dragEnter: function (event) {
        if (this.state.dragEntered1) {
          this.state.dragEntered2 = true
        } else {
          this.state.dragEntered1 = true
          this.getDOMNode().style.background = 'rgb(203, 169, 198)'
        }
      },
      dragLeave: function (event) {
        if (this.state.dragEntered2) {
          this.state.dragEntered2 = false
        } else {
          this.state.dragEntered1 = false
          this.getDOMNode().style.background = ''
        }
      },
      dragOver: function (event) {
        // enables the drop event at all, whoever thought of that api -.-
        event.preventDefault()
      },
      remove: function (event) {
        // detach the event handlers the moveable registered on the translation
        if (moveables.has(this.props.data)) {
          moveables.get(this.props.data).detachHandlers()
        }

        this.props.data.parentElement.removeChild(this.props.data)
      },
      render: function () {
        const node = this.props.data
        const runtime = this.props.runtime
        const children = filter(complement(isGUI), node.children)
        const collapsed = this.state.collapsed

        return (

                  {`<${node.nodeName}>`}

                {(node.nodeName.toLowerCase() !== 'scene') && X}
                {(node.nodeName.toLowerCase() === 'viewpoint') && Sync}

                {map(
                  a => [
                    <TreeNodeAttribute attribute={a} owner={node} />,

                  ],
                  filter(
                    pipe(
                      prop('name'),
                      toLower,
                      contains(__, [
                        'class',
                        'def',
                        'diffusecolor',
                        'orientation',
                        'position',
                        'render',
                        'rotation',
                        'translation'
                      ])
                    ),
                    node.attributes
                  )
                )}
                {unlessInline(node =>

                    {map(child =>
                      <TreeNode
                        data={child}
                        runtime={runtime}
                      />
                    )(children)}

                )(node)}

        )
      }
    })

    return TreeNode
  })
<commit_msg>skip branch if there are no files<commit_after>'use strict'

const {
  angular,
  FileReader
} = window

angular.module('scegratooApp')
  .service('TreeNode', function Project (React, R, TreeNodeAttribute, Project, moveables) {
    const {
      __,
      always,
      complement,
      contains,
      eq,
      filter,
      flatten,
      ifElse,
      map,
      mergeAll,
      pipe,
      prop,
      toLower
    } = R
    const isInline = pipe(
        prop('nodeName'),
        toLower,
        eq('inline')
    )
    const isGUI = pipe(
      prop('className'),
      toLower,
      eq('gui')
    )
    const unlessInline = ifElse(
      isInline,
      always(undefined)
    )
    const bulletStyle = {
      width: '10px',
      height: '10px',
      borderRadius: '50%',
      fontSize: '20px',
      color: '#fff',
      lineHeight: '100px',
      textAlign: 'center',
      background: '#000',
      marginRight: '5px',
      cursor: 'pointer'
    }
    const collapsedStyle = {
      background: '#d9d9d9'
    }
    const removeStyle = {
      color: 'red',
      marginLeft: '10px',
      marginRight: '10px'
    }
    const syncStyle = {
      color: 'blue'
    }

    let viewPointPosition
    let viewPointOrientation

    const TreeNode = React.createClass({
      displayName: 'TreeNode',
      getInitialState: function () {
        return {
          collapsed: false,
          // these are necessary because the browser fires the dragEnter and dragLeave events interleaved:
          //   dragEnter, dragEnter, dragLeave, dragLeave
          // thus making it necessary to keep track of the number of enters and leaves (or at least two of them)
          // thanks to dragster for this idea (https://github.com/bensmithett/dragster/blob/gh-pages/src/dragster.coffee)
          dragEntered1: false,
          dragEntered2: false
        }
      },
      propTypes: {
        data: React.PropTypes.object.isRequired,
        runtime: React.PropTypes.object.isRequired
      },
      componentDidMount: function () {
        const node = this.props.data

        if (node.nodeName.toLowerCase() === 'viewpoint') {
          node.addEventListener('viewpointChanged', event => {
            viewPointPosition = event.position
            viewPointOrientation = event.orientation
          })
        }

      },
      clicked: function (event) {
        this.props.runtime.showObject(this.props.data, 'xAxis')
      },
      toggleVisibility: function (event) {
        const element = event.currentTarget.parentNode.nextSibling

        if (this.state.collapsed) {
          element.style.display = ''
          this.setState({
            collapsed: false
          })
        } else {
          element.style.display = 'none'
          this.setState({
            collapsed: true
          })
        }
      },
      syncViewpoint: function (event) {
        const node = this.props.data

        node.setAttribute('orientation', `${viewPointOrientation[0].toString()} ${viewPointOrientation[1]}`)
        node.setAttribute('position', viewPointPosition.toString())
      },
      dragStart: function (event) {
        this.getDOMNode().style.opacity = 0.4
        event.node = this.props.data
      },
      dragEnd: function (event) {
        this.getDOMNode().style.opacity = 1
      },
      drop: function (event) {
        const node = event.node
        event.node = undefined

        event.stopPropagation() // Stops some browsers from redirecting.
        event.preventDefault()

        if (node && !node.contains(this.props.data)) {
          node.parentElement.removeChild(node)
          this.props.data.appendChild(node)
        } else if (event.dataTransfer.files.length > 0) {
          const files = flatten(event.dataTransfer.files) // turn into real array

          files.forEach(file => {
            const reader = new FileReader()

            reader.onload = event => {
              Project
                .uploadFile(file.name, event.target.result)
                .catch(() => window.alert('Upload failed.'))
                .then((result) => {
                  const transform = document.createElement('Transform')
                  const inline = document.createElement('Inline')
                  inline.setAttribute('url', result.data)
                  transform.appendChild(inline)
                  this.props.data.appendChild(transform)
                })
            }
            reader.readAsText(file)
          })
        } else if (event.dataTransfer.items.length > 0) {
          const url = event.dataTransfer.getData('text/plain')

          const transform = document.createElement('Transform')
          const inline = document.createElement('Inline')

          inline.setAttribute('url', url)
          transform.appendChild(inline)
          this.props.data.appendChild(transform)
        }
        this.getDOMNode().style.background = ''
      },
      dragEnter: function (event) {
        if (this.state.dragEntered1) {
          this.state.dragEntered2 = true
        } else {
          this.state.dragEntered1 = true
          this.getDOMNode().style.background = 'rgb(203, 169, 198)'
        }
      },
      dragLeave: function (event) {
        if (this.state.dragEntered2) {
          this.state.dragEntered2 = false
        } else {
          this.state.dragEntered1 = false
          this.getDOMNode().style.background = ''
        }
      },
      dragOver: function (event) {
        // enables the drop event at all, whoever thought of that api -.-
        event.preventDefault()
      },
      remove: function (event) {
        // detach the event handlers the moveable registered on the translation
        if (moveables.has(this.props.data)) {
          moveables.get(this.props.data).detachHandlers()
        }

        this.props.data.parentElement.removeChild(this.props.data)
      },
      render: function () {
        const node = this.props.data
        const runtime = this.props.runtime
        const children = filter(complement(isGUI), node.children)
        const collapsed = this.state.collapsed

        return (

                  {`<${node.nodeName}>`}

                {(node.nodeName.toLowerCase() !== 'scene') && X}
                {(node.nodeName.toLowerCase() === 'viewpoint') && Sync}

                {map(
                  a => [
                    <TreeNodeAttribute attribute={a} owner={node} />,

                  ],
                  filter(
                    pipe(
                      prop('name'),
                      toLower,
                      contains(__, [
                        'class',
                        'def',
                        'diffusecolor',
                        'orientation',
                        'position',
                        'render',
                        'rotation',
                        'translation'
                      ])
                    ),
                    node.attributes
                  )
                )}
                {unlessInline(node =>

                    {map(child =>
                      <TreeNode
                        data={child}
                        runtime={runtime}
                      />
                    )(children)}

                )(node)}

        )
      }
    })

    return TreeNode
  })
<|endoftext|>