<commit_before>define(function(){
   return function(){

       // mailBox.html
       //////////     MAIL  COLLAPSE     //////////
       $(".mail-collapse").off('click');
       $(".mail-collapse").on('click',function(){
           $("#main").toggleClass( "in" );
       });

       //////////     MAIL FAVOURITE      //////////
       $("a.mail-favourite").off('click');
       $("a.mail-favourite").on('click',function(){
           $(this).toggleClass( "active" );
           var star=$(this).find(".fa");
       });

       //map.html
       //////////     MAP GOOGLE      //////////
       $(".mapTools").off('click');
       $(".mapTools").on('click',function(){
           $("#mapSetting").toggleClass( "active" );
       });
       $(".map-control-min").off('click');
       $(".map-control-min").on('click',function(){
           $("#mapControl").toggleClass( "active" );
           $(this).find("i").toggleClass( "fa-chevron-down" );
           $(this).find("i").toggleClass( "fa-chevron-up" );
       });

       //dashboard.html
       //////////     CAPLET CLOCK    //////////
       $('div#clock').capletClock();

       //calendar.html
       $(".slide-trash").off('click.openbizcustom');
       $(".slide-trash").on('click',function(){
           $("#slide-trash").toggleClass( "active" );
       });

       //chartOther.html
       $('.knob_save').off('click');
       $('.knob_save').on('click', function() {
           alert("Save  "+$("#add_item").val()+" Item");
       });

       //////////     COLOR PALET     //////////
       $('#colorpalette1').colorPalette().off('selectColor');
       $('#colorpalette1').colorPalette().on('selectColor', function(e) {
           $('#selected-color1').val(e.color);
           $('#selected-color1').parent().find(".ico").css("color", e.color );
       });
       //////////     COLOR PALET  IN  ADD EVENT CALENDAR    //////////
       var cc_color= new Array();
       $.each(cepletColor, function(key,val) {
           cc_color.push(val) //put color for ceplet color
       });
       $('#colorpalette_events').colorPalette({ colors:[cc_color] }).off('selectColor');
       $('#colorpalette_events').colorPalette({ colors:[cc_color] }).on('selectColor', function(e) {
           var data=$(this).data();
           $(data.returnColor).val(e.color);
           $(this).parents(".input-group").find(".ico").css("color", e.color );
       });

       //////////     DATE TIME RANG      //////////
       $.('#daterange').daterangepicker();
       $('#reportrange').daterangepicker({
               startDate: moment().subtract('days', 29),
               endDate: moment(),
               minDate: '01/01/2012',
               maxDate: '12/31/2014',
               dateLimit: { days: 60 },
               /*parentEl:"#main",*/
               timePicker: false,
               timePickerIncrement: 1,
               timePicker12Hour: true,
               ranges: {
                   'Today': [moment(), moment()],
                   'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
                   'Last 7 Days': [moment().subtract('days', 6), moment()],
                   'This Month': [moment().startOf('month'), moment().endOf('month')],
                   'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
               },
               opens: 'left',
               buttonClasses: ['btn-sm'],
               applyClass: 'btn-inverse',
               cancelClass: 'btn-inverse',
               format: 'MM/DD/YYYY',
               separator: ' to ',
               locale: {
                   fromLabel: 'From',
                   toLabel: 'To',
                   customRangeLabel: 'Custom Range',
                   daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr','Sa'],
                   monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                   firstDay: 1
               }
           },
           function(start, end) {
               console.log("Callback has been called!");
               $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
           }
       );
       $('#reportrange span').html(moment().subtract('days', 29).format('MMMM D, YYYY') + ' - ' + moment().format('MMMM D, YYYY'));

   }
});<commit_msg>update ui<commit_after>define(function(){
   return function(){

       // mailBox.html
       //////////     MAIL  COLLAPSE     //////////
       $(".mail-collapse").off('click.openbizcustom');
       $(".mail-collapse").on('click.openbizcustom',function(){
           $("#main").toggleClass( "in" );
       });

       //////////     MAIL FAVOURITE      //////////
       $("a.mail-favourite").off('click.openbizcustom');
       $("a.mail-favourite").on('click.openbizcustom',function(){
           $(this).toggleClass( "active" );
           var star=$(this).find(".fa");
       });

       //map.html
       //////////     MAP GOOGLE      //////////
       $(".mapTools").off('click.openbizcustom');
       $(".mapTools").on('click.openbizcustom',function(){
           $("#mapSetting").toggleClass( "active" );
       });
       $(".map-control-min").off('click.openbizcustom');
       $(".map-control-min").on('click.openbizcustom',function(){
           $("#mapControl").toggleClass( "active" );
           $(this).find("i").toggleClass( "fa-chevron-down" );
           $(this).find("i").toggleClass( "fa-chevron-up" );
       });

       //dashboard.html
       //////////     CAPLET CLOCK    //////////
       $('div#clock').capletClock();

       //calendar.html
       $(".slide-trash").off('click.openbizcustom');
       $(".slide-trash").on('click.openbizcustom',function(){
           $("#slide-trash").toggleClass( "active" );
       });

       //chartOther.html
       $('.knob_save').off('click.openbizcustom');
       $('.knob_save').on('click.openbizcustom', function() {
           alert("Save  "+$("#add_item").val()+" Item");
       });

       //////////     COLOR PALET     //////////
       $('#colorpalette1').colorPalette().off('selectColor.openbizcustom');
       $('#colorpalette1').colorPalette().on('selectColor.openbizcustom', function(e) {
           $('#selected-color1').val(e.color);
           $('#selected-color1').parent().find(".ico").css("color", e.color );
       });
       //////////     COLOR PALET  IN  ADD EVENT CALENDAR    //////////
       var cc_color= new Array();
       $.each(cepletColor, function(key,val) {
           cc_color.push(val) //put color for ceplet color
       });
       $('#colorpalette_events').colorPalette({ colors:[cc_color] }).off('selectColor.openbizcustom');
       $('#colorpalette_events').colorPalette({ colors:[cc_color] }).on('selectColor.openbizcustom', function(e) {
           var data=$(this).data();
           $(data.returnColor).val(e.color);
           $(this).parents(".input-group").find(".ico").css("color", e.color );
       });

       //////////     DATE TIME RANG      //////////
       $.('#daterange').daterangepicker();
       $('#reportrange').daterangepicker({
               startDate: moment().subtract('days', 29),
               endDate: moment(),
               minDate: '01/01/2012',
               maxDate: '12/31/2014',
               dateLimit: { days: 60 },
               /*parentEl:"#main",*/
               timePicker: false,
               timePickerIncrement: 1,
               timePicker12Hour: true,
               ranges: {
                   'Today': [moment(), moment()],
                   'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
                   'Last 7 Days': [moment().subtract('days', 6), moment()],
                   'This Month': [moment().startOf('month'), moment().endOf('month')],
                   'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
               },
               opens: 'left',
               buttonClasses: ['btn-sm'],
               applyClass: 'btn-inverse',
               cancelClass: 'btn-inverse',
               format: 'MM/DD/YYYY',
               separator: ' to ',
               locale: {
                   fromLabel: 'From',
                   toLabel: 'To',
                   customRangeLabel: 'Custom Range',
                   daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr','Sa'],
                   monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                   firstDay: 1
               }
           },
           function(start, end) {
               console.log("Callback has been called!");
               $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
           }
       );
       $('#reportrange span').html(moment().subtract('days', 29).format('MMMM D, YYYY') + ' - ' + moment().format('MMMM D, YYYY'));

   }
});<|endoftext|>


<commit_before>chrome.runtime.sendMessage({ method: "test" }, function ( res ) {
  var storage = res.storage;

  if ( storage && storage.rules ) {
    var rules = JSON.parse(storage.rules);
    for ( var i = 0, len = rules.length; i < len; i++ ) {
      var rule = rules[i];
      var regExp = buildRegExp(rule.url);
      if ( regExp.test(document.location.href) ) {
        if ( rule.enabled ) {
          if ( rule.type === 'url' ) {
            injectRule(rule);
          }
          else if ( rule.type === 'execute' ) {
            evalRule(rule);
          }
        } else {
          console.log('Skipping rule for %s because it is disabled', rule.url);
        }
      }
    }
  }
});

chrome.runtime.onMessage.addListener(function ( request, sender, sendResponse ) {
  if ( request.action === "expire-session" ) {
    var script = document.createElement("script");
    script.async = true;
    script.src = chrome.extension.getURL("src/expire-session.js");
    console.log('inject', script);
    document.body.appendChild(script);
  }
  else if ( request.action === "show-session-key" ) {
    var script = document.createElement("script");
    script.async = true;
    script.src = chrome.extension.getURL("src/show-session-key.js");
    console.log('inject', script);
    document.body.appendChild(script);
  }
});

function buildRegExp ( url ) {
  var match = url.match(/^\/(.+?)\/(.*)$/);
  if ( match ) {
    return new RegExp(match[1], match[2]);
  }
  url = url.replace(/([\.\?\[\]\(\)\{\}\\\/\^\$])/g, '\\$1');
  url = url.replace(/\*/g, '.*?');
  return new RegExp('^' + url + '$', 'i');
}

function evalRule ( rule ) {
  // console.log('Executing Fanplayr Integration script: ' + rule.content);
  console.log('Executing Fanplayr Integration script...');
  var script = document.createElement('script');
  script.innerHTML = rule.content;
  document.body.appendChild(script);
}

function injectRule ( rule ) {
  var url = rule.content || '';

  // Prevent caching.
  url += (url.indexOf('?') >= 0 ? '&' : '?') + 'cache_kill=' + (new Date().getTime());

  console.log('Injecting Fanplayr Integration script: ' + url);
  var first = document.getElementsByTagName('script')[0];
  var script = document.createElement('script');
  script.async = true;
  script.src = url;

  first.parentNode.insertBefore(script, first);
}
<commit_msg>removed more logs<commit_after>chrome.runtime.sendMessage({ method: "test" }, function ( res ) {
  var storage = res.storage;

  if ( storage && storage.rules ) {
    var rules = JSON.parse(storage.rules);
    for ( var i = 0, len = rules.length; i < len; i++ ) {
      var rule = rules[i];
      var regExp = buildRegExp(rule.url);
      if ( regExp.test(document.location.href) ) {
        if ( rule.enabled ) {
          if ( rule.type === 'url' ) {
            injectRule(rule);
          }
          else if ( rule.type === 'execute' ) {
            evalRule(rule);
          }
        } else {
          console.log('Skipping rule for %s because it is disabled', rule.url);
        }
      }
    }
  }
});

chrome.runtime.onMessage.addListener(function ( request, sender, sendResponse ) {
  if ( request.action === "expire-session" ) {
    var script = document.createElement("script");
    script.async = true;
    script.src = chrome.extension.getURL("src/expire-session.js");
    document.body.appendChild(script);
  }
  else if ( request.action === "show-session-key" ) {
    var script = document.createElement("script");
    script.async = true;
    script.src = chrome.extension.getURL("src/show-session-key.js");
    document.body.appendChild(script);
  }
});

function buildRegExp ( url ) {
  var match = url.match(/^\/(.+?)\/(.*)$/);
  if ( match ) {
    return new RegExp(match[1], match[2]);
  }
  url = url.replace(/([\.\?\[\]\(\)\{\}\\\/\^\$])/g, '\\$1');
  url = url.replace(/\*/g, '.*?');
  return new RegExp('^' + url + '$', 'i');
}

function evalRule ( rule ) {
  console.log('Executing Fanplayr Integration script...');
  var script = document.createElement('script');
  script.innerHTML = rule.content;
  document.body.appendChild(script);
}

function injectRule ( rule ) {
  var url = rule.content || '';

  // Prevent caching.
  url += (url.indexOf('?') >= 0 ? '&' : '?') + 'cache_kill=' + (new Date().getTime());

  console.log('Injecting Fanplayr Integration script: ' + url);
  var first = document.getElementsByTagName('script')[0];
  var script = document.createElement('script');
  script.async = true;
  script.src = url;

  first.parentNode.insertBefore(script, first);
}
<|endoftext|>


<commit_before>/* @flow */
import type { RecordFactory, RecordOf } from "immutable";
import type { Subject } from "rxjs";
import type {
  DesktopHostRecordProps,
  JupyterHostRecordProps,
  LocalKernelProps,
  RemoteKernelProps
} from "./hosts";

import { List, Map, Record, Set } from "immutable";

export { makeLocalKernelRecord, makeDesktopHostRecord } from "./hosts";

/*

This is the definition of JSON that Flow provides

type JSON = | string | number | boolean | null | JSONObject | JSONArray;
type JSONObject = { [key:string]: JSON };
type JSONArray = Array<JSON>;

Which we'll adapt for our use of Immutable.js

*/
export type ImmutableJSON =
  | string
  | number
  | boolean
  | null
  | ImmutableJSONMap
  | ImmutableJSONList; // eslint-disable-line no-use-before-define

export type ImmutableJSONMap = Map<string, ImmutableJSON>;

export type ImmutableJSONList = List<ImmutableJSON>;

export type ExecutionCount = number | null;

export type MimeBundle = Map<string, ImmutableJSON>;

export type ExecuteResult = {
  output_type: "execute_result",
  execution_count: ExecutionCount,
  data: MimeBundle,
  metadata: ImmutableJSONMap
};

export type DisplayData = {
  output_type: "display_data",
  data: MimeBundle,
  metadata: ImmutableJSONMap
};

export type StreamOutput = {
  output_type: "stream",
  name: "stdout" | "stderr",
  text: string
};

export type ErrorOutput = {
  output_type: "error",
  ename: string,
  evalue: string,
  traceback: List<string>
};

export type Output = ExecuteResult | DisplayData | StreamOutput | ErrorOutput;

export type CodeCell = {
  cell_type: "code",
  metadata: ImmutableJSONMap,
  execution_count: ExecutionCount,
  source: string,
  outputs: List<Output>
};

export type MarkdownCell = {
  cell_type: "markdown",
  source: string,
  metadata: ImmutableJSONMap
};

export type Cell = MarkdownCell | CodeCell;

export type KernelspecMetadata = {
  name: string,
  display_name: string,
  language: string
};

// Note: this is the kernelspec as formed by spawnteract and jupyter kernelspecs --json
export type KernelInfo = {
  name: string,
  spec: KernelspecMetadata
};

export type LanguageInfoMetadata = {
  name: string,
  codemirror_mode?: string | ImmutableJSONMap,
  file_extension?: string,
  mimetype?: string,
  pygments_lexer?: string
};

export type NotebookMetadata = {
  kernelspec: KernelspecMetadata,
  language_info: LanguageInfoMetadata
  // NOTE: We're not currently using orig_nbformat in nteract. Based on the comment
  // in the schema, we won't:
  //
  //   > Original notebook format (major number) before converting the notebook between versions. This should never be written to a file
  //
  //   from https://github.com/jupyter/nbformat/blob/62d6eb8803616d198eaa2024604d1fe923f2a7b3/nbformat/v4/nbformat.v4.schema.json#L58-L61
  //
  // It seems like an intermediate/in-memory representation that bled its way into the spec, when it should have been
  // handled as separate state.
  //
  // orig_nbformat?: number,
};

export type Notebook = {
  cellMap: Map<string, Cell>,
  cellOrder: List<string>,
  nbformat: 4,
  nbformat_minor: 0 | 1 | 2 | 3 | 4,
  metadata: NotebookMetadata
};

// Parts of AppRecord should become
// ElectronAppRecord
// Basically, anything that's only for desktop should have its own record & reducers
type AppRecordProps = {
  kernel: ?RecordOf<RemoteKernelProps | LocalKernelProps>,
  host: ?RecordOf<DesktopHostRecordProps | JupyterHostRecordProps>,
  githubToken: ?string,
  notificationSystem: ?Object,
  isSaving: boolean,
  lastSaved: ?Date,
  configLastSaved: ?Date,
  error: any
};

export const makeAppRecord: RecordFactory<AppRecordProps> = Record({
  kernel: null,
  host: null,
  githubToken: null, // Electron specific (ish...)
  notificationSystem: null, // Should be available for all I assume
  isSaving: false, // All -- ?
  lastSaved: null, // All
  configLastSaved: null, // ?
  error: null // All
});

export type AppRecord = RecordOf<AppRecordProps>;

type DocumentRecordProps = {
  notebook: ?Notebook,
  transient: Map<string, any>, // has the keypaths for updating displays
  // transient should be more fully typed (be a record itself)
  // right now it's keypaths and then it looks like it's able to handle any per
  // cell transient data that will be deleted when the kernel is restarted
  cellPagers: any,
  stickyCells: ?Set<any>,
  editorFocused: any,
  cellFocused: any,
  copied: Map<any, any>
};

export const makeDocumentRecord: RecordFactory<DocumentRecordProps> = Record({
  notebook: null,
  savedNotebook: null,
  // $FlowFixMe: Immutable
  transient: new Map({
    keyPathsForDisplays: new Map()
  }),
  cellPagers: new Map(),
  stickyCells: new Set(),
  editorFocused: null,
  cellFocused: null,
  copied: new Map(),
  filename: ""
});
export type DocumentRecord = RecordOf<DocumentRecordProps>;

type CommsRecordProps = {
  targets: Map<any, any>,
  info: Map<any, any>,
  models: Map<any, any>
};

export const CommsRecord = Record({
  targets: new Map(),
  info: new Map(),
  models: new Map()
});

export type AppState = {
  app: RecordOf<AppRecordProps>,
  document: RecordOf<DocumentRecordProps>,
  comms: RecordOf<CommsRecordProps>,
  config: Map<string, any>
};
<commit_msg>refactor: export refs from `records`.<commit_after>/* @flow */
import type { RecordFactory, RecordOf } from "immutable";
import type { Subject } from "rxjs";
import type {
  DesktopHostRecordProps,
  JupyterHostRecordProps,
  LocalKernelProps,
  RemoteKernelProps
} from "./hosts";

import { List, Map, Record, Set } from "immutable";

export { HostRef, makeLocalKernelRecord, makeDesktopHostRecord } from "./hosts";
export { KernelspecsRef } from "./kernelspecs";

/*

This is the definition of JSON that Flow provides

type JSON = | string | number | boolean | null | JSONObject | JSONArray;
type JSONObject = { [key:string]: JSON };
type JSONArray = Array<JSON>;

Which we'll adapt for our use of Immutable.js

*/
export type ImmutableJSON =
  | string
  | number
  | boolean
  | null
  | ImmutableJSONMap
  | ImmutableJSONList; // eslint-disable-line no-use-before-define

export type ImmutableJSONMap = Map<string, ImmutableJSON>;

export type ImmutableJSONList = List<ImmutableJSON>;

export type ExecutionCount = number | null;

export type MimeBundle = Map<string, ImmutableJSON>;

export type ExecuteResult = {
  output_type: "execute_result",
  execution_count: ExecutionCount,
  data: MimeBundle,
  metadata: ImmutableJSONMap
};

export type DisplayData = {
  output_type: "display_data",
  data: MimeBundle,
  metadata: ImmutableJSONMap
};

export type StreamOutput = {
  output_type: "stream",
  name: "stdout" | "stderr",
  text: string
};

export type ErrorOutput = {
  output_type: "error",
  ename: string,
  evalue: string,
  traceback: List<string>
};

export type Output = ExecuteResult | DisplayData | StreamOutput | ErrorOutput;

export type CodeCell = {
  cell_type: "code",
  metadata: ImmutableJSONMap,
  execution_count: ExecutionCount,
  source: string,
  outputs: List<Output>
};

export type MarkdownCell = {
  cell_type: "markdown",
  source: string,
  metadata: ImmutableJSONMap
};

export type Cell = MarkdownCell | CodeCell;

export type KernelspecMetadata = {
  name: string,
  display_name: string,
  language: string
};

// Note: this is the kernelspec as formed by spawnteract and jupyter kernelspecs --json
export type KernelInfo = {
  name: string,
  spec: KernelspecMetadata
};

export type LanguageInfoMetadata = {
  name: string,
  codemirror_mode?: string | ImmutableJSONMap,
  file_extension?: string,
  mimetype?: string,
  pygments_lexer?: string
};

export type NotebookMetadata = {
  kernelspec: KernelspecMetadata,
  language_info: LanguageInfoMetadata
  // NOTE: We're not currently using orig_nbformat in nteract. Based on the comment
  // in the schema, we won't:
  //
  //   > Original notebook format (major number) before converting the notebook between versions. This should never be written to a file
  //
  //   from https://github.com/jupyter/nbformat/blob/62d6eb8803616d198eaa2024604d1fe923f2a7b3/nbformat/v4/nbformat.v4.schema.json#L58-L61
  //
  // It seems like an intermediate/in-memory representation that bled its way into the spec, when it should have been
  // handled as separate state.
  //
  // orig_nbformat?: number,
};

export type Notebook = {
  cellMap: Map<string, Cell>,
  cellOrder: List<string>,
  nbformat: 4,
  nbformat_minor: 0 | 1 | 2 | 3 | 4,
  metadata: NotebookMetadata
};

// Parts of AppRecord should become
// ElectronAppRecord
// Basically, anything that's only for desktop should have its own record & reducers
type AppRecordProps = {
  kernel: ?RecordOf<RemoteKernelProps | LocalKernelProps>,
  host: ?RecordOf<DesktopHostRecordProps | JupyterHostRecordProps>,
  githubToken: ?string,
  notificationSystem: ?Object,
  isSaving: boolean,
  lastSaved: ?Date,
  configLastSaved: ?Date,
  error: any
};

export const makeAppRecord: RecordFactory<AppRecordProps> = Record({
  kernel: null,
  host: null,
  githubToken: null, // Electron specific (ish...)
  notificationSystem: null, // Should be available for all I assume
  isSaving: false, // All -- ?
  lastSaved: null, // All
  configLastSaved: null, // ?
  error: null // All
});

export type AppRecord = RecordOf<AppRecordProps>;

type DocumentRecordProps = {
  notebook: ?Notebook,
  transient: Map<string, any>, // has the keypaths for updating displays
  // transient should be more fully typed (be a record itself)
  // right now it's keypaths and then it looks like it's able to handle any per
  // cell transient data that will be deleted when the kernel is restarted
  cellPagers: any,
  stickyCells: ?Set<any>,
  editorFocused: any,
  cellFocused: any,
  copied: Map<any, any>
};

export const makeDocumentRecord: RecordFactory<DocumentRecordProps> = Record({
  notebook: null,
  savedNotebook: null,
  // $FlowFixMe: Immutable
  transient: new Map({
    keyPathsForDisplays: new Map()
  }),
  cellPagers: new Map(),
  stickyCells: new Set(),
  editorFocused: null,
  cellFocused: null,
  copied: new Map(),
  filename: ""
});
export type DocumentRecord = RecordOf<DocumentRecordProps>;

type CommsRecordProps = {
  targets: Map<any, any>,
  info: Map<any, any>,
  models: Map<any, any>
};

export const CommsRecord = Record({
  targets: new Map(),
  info: new Map(),
  models: new Map()
});

export type AppState = {
  app: RecordOf<AppRecordProps>,
  document: RecordOf<DocumentRecordProps>,
  comms: RecordOf<CommsRecordProps>,
  config: Map<string, any>
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Insert the text at the cursor into the active element. Note that we're
 * intentionally not appending or simply replacing the value of the editable
 * field, as we want to allow normal pasting conventions. If you paste at the
 * beginning, you shouldn't see all your text be replaced.
 * Taken from:
 * http://stackoverflow.com/questions/7404366/how-do-i-insert-some-text-where-the-cursor-is
 */
function insertTextAtCursor(text) {
    var el = document.activeElement;
    var val = el.value;
    var startIndex;
    var endIndex;
    var range;
    var doc = el.ownerDocument;
    var sel;
    if (typeof el.selectionStart === 'number' &&
        typeof el.selectionEnd === 'number') {
        startIndex = el.selectionStart;
        endIndex = el.selectionEnd;
        el.value = val.slice(0, startIndex) + text + val.slice(endIndex);
        // standard behavior is move to the end of the selection
        el.selectionEnd = startIndex + text.length;
    } else if (doc.selection !== undefined && doc.selection.createRange) {
        el.focus();
        range = doc.selection.createRange();
        range.collapse(false);
        range.text = text;
        range.select();
    } else if (el.tagName === 'DIV') {
        // We're pasting into an editable div, like gmail.
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
                var pastedText = document.createTextNode(text);
                range.insertNode(pastedText);
                range.setStartAfter(pastedText);
                sel.removeAllRanges();
                sel.addRange(range);
            } else {
                console.log('getRangeAt or rangeCount not defined');
            }
        } else if (document.selection && document.selection.createRange) {
            document.selection.createRange().text = text;
        }
    } else {
        // We aren't imitating pasting for this tag yet.
        console.log('Not handling paste for tag type: ' + el.tagName);
    }
}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.data) {
        insertTextAtCursor(request.data);
    }
});

<commit_msg>remove unnecessary IE support<commit_after>'use strict';

/**
 * Insert the text at the cursor into the active element. Note that we're
 * intentionally not appending or simply replacing the value of the editable
 * field, as we want to allow normal pasting conventions. If you paste at the
 * beginning, you shouldn't see all your text be replaced.
 * Taken from:
 * http://stackoverflow.com/questions/7404366/how-do-i-insert-some-text-where-the-cursor-is
 */
function insertTextAtCursor(text) {
    var el = document.activeElement;
    var val = el.value;
    var startIndex;
    var endIndex;
    var range;
    var doc = el.ownerDocument;
    var sel;
    if (typeof el.selectionStart === 'number' &&
        typeof el.selectionEnd === 'number') {
        // input and textarea
        startIndex = el.selectionStart;
        endIndex = el.selectionEnd;
        el.value = val.slice(0, startIndex) + text + val.slice(endIndex);
        // standard behavior is move to the end of the selection
        el.selectionEnd = startIndex + text.length;
    } else if (el.tagName === 'DIV') {
        // We're pasting into an editable div, like gmail.
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
                var pastedText = document.createTextNode(text);
                range.insertNode(pastedText);
                range.setStartAfter(pastedText);
                sel.removeAllRanges();
                sel.addRange(range);
            } else {
                console.log('getRangeAt or rangeCount not defined');
            }
        } else if (document.selection && document.selection.createRange) {
            document.selection.createRange().text = text;
        }
    } else {
        // We aren't imitating pasting for this tag yet.
        console.log('Not handling paste for tag type: ' + el.tagName);
    }
}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.data) {
        insertTextAtCursor(request.data);
    }
});

<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router';
import MG from 'metrics-graphics';

import Fetching from './fetching';

export default class extends React.Component {
  constructor(props) {
    super(props);

    this.chartLoaded = false;

    // Number of x-axis ticks on the chart list page.
    this.numXTicksSmall = 4;

    // After how many characters should the x-axis labels get ellipsised?
    this.xLabelsChopLength = 8;
  }

  componentDidMount() {
    // On the chart detail page, points are loaded after the component mounts
    if (this.props.points) {
      this.loadChart();
    }
  }

  componentWillUpdate(nextProps) {
    // Load the chart if it can be loaded and hasn't been already. Otherwise,
    // it just needs to be updated.
    if (!this.chartLoaded && nextProps.points) {
      this.loadChart(nextProps);
    } else if (this.chartLoaded) {
      this.insertOrUpdateChart();
    }
  }

  render() {
    const chart = (
      <div className={`chart is-fetching chart-${this.props.id}`}>
        <Fetching />

              x

              y

              proportion

    );

    if (!this.props.isDetail) {
      return <Link className="chart-link" to={`/chart/${this.props.id}/`}>{chart}</Link>;
    } else {
      return chart;
    }
  }

  loadChart(props = this.props) {
    this.pointsMeta = this.buildPointsMeta(props.points);
    this.insertOrUpdateChart();
    document.querySelector(`.chart-${props.id}`).classList.remove('is-fetching');
    this.chartLoaded = true;
  }

  buildPointsMeta(dataPoints) {
    var pointsMeta = [];

    for (let i = 0; i < dataPoints.length; i++) {
      pointsMeta.push({
        x: dataPoints[i]['refRank'] || parseFloat(dataPoints[i]['b']),
        y: dataPoints[i]['c'] * 100,
        p: dataPoints[i]['p'] * 100,
        label: dataPoints[i]['b']
      });
    }

    return pointsMeta;
  }

  getShortLabel(lbl) {
    if (lbl.length > this.xLabelsChopLength) {
      return `${lbl.substring(0, this.xLabelsChopLength - 1)}…`;
    }
    return lbl;
  }

  insertOrUpdateChart() {
    const refLabels = {};
    const infoElm = document.querySelector(`.chart-${this.props.id} .chart-rollover-table`);
    const pointsMetaLength = this.pointsMeta.length;

    this.pointsMeta.map(chartItem => {
      refLabels['' + chartItem.x] = chartItem.label;
    });

    /* eslint-disable camelcase */
    const graphOptions = {
      target: '.chart-' + this.props.id,

      // Data
      data: this.pointsMeta,
      x_accessor: 'x',
      y_accessor: 'y',
      show_rollover_text: false,

      // General display
      title: this.props.metric,
      full_width: true,
      area: false,
      missing_is_hidden: true,

      // y-axis
      min_y: 0,
      max_y: 100,
      yax_count: 5,
      mouseover: data => {
        infoElm.classList.add('show');
        infoElm.querySelector('.value-x').textContent = refLabels[data.x];
        infoElm.querySelector('.value-y').textContent = `${data.y.toFixed(4)}%`;
        infoElm.querySelector('.value-p').textContent = `${data.p.toFixed(4)}%`;
      },
      mouseout: () => {
        infoElm.classList.remove('show');
      },
      yax_units: '%',
      yax_units_append: true
    };

    if (this.props.type === 'category') {
      graphOptions.xax_format = d => this.getShortLabel(refLabels[d]);
      graphOptions.xax_count = this.props.isDetail ? pointsMetaLength : this.numXTicksSmall;
    }

    if (!this.props.isDetail) {
      graphOptions.height = 250;
    } else {
      graphOptions.full_height = true;
    }

    if (this.props.showOutliers) {
      graphOptions.min_x = this.pointsMeta[0].x;
      graphOptions.max_x = this.pointsMeta[pointsMetaLength - 1].x;
    } else {
      graphOptions.min_x = this.pointsMeta[Math.max(Math.round(pointsMetaLength * 0.005) - 1, 0)].x;
      graphOptions.max_x = this.pointsMeta[Math.min(Math.round(pointsMetaLength * 0.995) - 1, pointsMetaLength - 1)].x;
    }

    MG.data_graphic(graphOptions);
    /* eslint-enable camelcase */
  }
}
<commit_msg>Fix broken "Show outliers" button<commit_after>import React from 'react';
import { Link } from 'react-router';
import MG from 'metrics-graphics';

import Fetching from './fetching';

export default class extends React.Component {
  constructor(props) {
    super(props);

    this.chartLoaded = false;

    // Number of x-axis ticks on the chart list page.
    this.numXTicksSmall = 4;

    // After how many characters should the x-axis labels get ellipsised?
    this.xLabelsChopLength = 8;
  }

  componentDidMount() {
    // On the chart detail page, points are loaded after the component mounts
    if (this.props.points) {
      this.loadChart();
    }
  }

  componentDidUpdate() {
    // Load the chart if it can be loaded and hasn't been already. Otherwise,
    // it just needs to be updated.
    if (!this.chartLoaded && this.props.points) {
      this.loadChart();
    } else if (this.chartLoaded) {
      this.insertOrUpdateChart();
    }
  }

  render() {
    const chart = (
      <div className={`chart is-fetching chart-${this.props.id}`}>
        <Fetching />

              x

              y

              proportion

    );

    if (!this.props.isDetail) {
      return <Link className="chart-link" to={`/chart/${this.props.id}/`}>{chart}</Link>;
    } else {
      return chart;
    }
  }

  loadChart() {
    this.pointsMeta = this.buildPointsMeta(this.props.points);
    this.insertOrUpdateChart();
    document.querySelector(`.chart-${this.props.id}`).classList.remove('is-fetching');
    this.chartLoaded = true;
  }

  buildPointsMeta(dataPoints) {
    var pointsMeta = [];

    for (let i = 0; i < dataPoints.length; i++) {
      pointsMeta.push({
        x: dataPoints[i]['refRank'] || parseFloat(dataPoints[i]['b']),
        y: dataPoints[i]['c'] * 100,
        p: dataPoints[i]['p'] * 100,
        label: dataPoints[i]['b']
      });
    }

    return pointsMeta;
  }

  getShortLabel(lbl) {
    if (lbl.length > this.xLabelsChopLength) {
      return `${lbl.substring(0, this.xLabelsChopLength - 1)}…`;
    }
    return lbl;
  }

  insertOrUpdateChart() {
    const refLabels = {};
    const infoElm = document.querySelector(`.chart-${this.props.id} .chart-rollover-table`);
    const pointsMetaLength = this.pointsMeta.length;

    this.pointsMeta.map(chartItem => {
      refLabels['' + chartItem.x] = chartItem.label;
    });

    /* eslint-disable camelcase */
    const graphOptions = {
      target: '.chart-' + this.props.id,

      // Data
      data: this.pointsMeta,
      x_accessor: 'x',
      y_accessor: 'y',
      show_rollover_text: false,

      // General display
      title: this.props.metric,
      full_width: true,
      area: false,
      missing_is_hidden: true,

      // y-axis
      min_y: 0,
      max_y: 100,
      yax_count: 5,
      mouseover: data => {
        infoElm.classList.add('show');
        infoElm.querySelector('.value-x').textContent = refLabels[data.x];
        infoElm.querySelector('.value-y').textContent = `${data.y.toFixed(4)}%`;
        infoElm.querySelector('.value-p').textContent = `${data.p.toFixed(4)}%`;
      },
      mouseout: () => {
        infoElm.classList.remove('show');
      },
      yax_units: '%',
      yax_units_append: true
    };

    if (this.props.type === 'category') {
      graphOptions.xax_format = d => this.getShortLabel(refLabels[d]);
      graphOptions.xax_count = this.props.isDetail ? pointsMetaLength : this.numXTicksSmall;
    }

    if (!this.props.isDetail) {
      graphOptions.height = 250;
    } else {
      graphOptions.full_height = true;
    }

    if (this.props.showOutliers) {
      graphOptions.min_x = this.pointsMeta[0].x;
      graphOptions.max_x = this.pointsMeta[pointsMetaLength - 1].x;
    } else {
      graphOptions.min_x = this.pointsMeta[Math.max(Math.round(pointsMetaLength * 0.005) - 1, 0)].x;
      graphOptions.max_x = this.pointsMeta[Math.min(Math.round(pointsMetaLength * 0.995) - 1, pointsMetaLength - 1)].x;
    }

    MG.data_graphic(graphOptions);
    /* eslint-enable camelcase */
  }
}
<|endoftext|>


<commit_before>function onLinksAdded(links) {
	var listLinks = links[0].added;
	listLinks.forEach(buildLink);

	var detailsLinks = links[1].added;
	detailsLinks.forEach(buildTitleListener);
};

function buildLink(element) {
	var issueNumber = element.innerText.match(/\b\d{8,9}\b/);
	if (issueNumber) {
		element.innerHTML = element.innerHTML.replace(
			/\b(\d{8,9})\b/,
			'$1'
		);
	}
}

function buildTitleListener(titleElement) {
	new MutationSummary({
		rootNode: titleElement,
		callback: function(changes) {
			buildLink(titleElement);
		},
		queries: [
			{ characterData: true }
		]
	});
}

var observer = new MutationSummary({
	callback: onLinksAdded,
	queries: [
		{ element: 'span[ng-bind="s.title"]' },
		{ element: 'p[ng-bind="details.title"]' }
	]
});<commit_msg>Highlight leading number sign (#) in the links<commit_after>function onLinksAdded(links) {
	var listLinks = links[0].added;
	listLinks.forEach(buildLink);

	var detailsLinks = links[1].added;
	detailsLinks.forEach(buildTitleListener);
};

function buildLink(element) {
	var issueNumber = element.innerText.match(/#\d{8,9}\b/);
	if (issueNumber) {
		element.innerHTML = element.innerHTML.replace(
			/#(\d{8,9})\b/,
			'#$1'
		);
	}
}

function buildTitleListener(titleElement) {
	new MutationSummary({
		rootNode: titleElement,
		callback: function(changes) {
			buildLink(titleElement);
		},
		queries: [
			{ characterData: true }
		]
	});
}

var observer = new MutationSummary({
	callback: onLinksAdded,
	queries: [
		{ element: 'span[ng-bind="s.title"]' },
		{ element: 'p[ng-bind="details.title"]' }
	]
});<|endoftext|>


<commit_before>'use strict';

var elements = document.querySelectorAll('.record');
if (elements.length) {
  var line = Array.prototype.filter.call(elements,function(record) {
    return record.textContent.indexOf('文章網址') !== -1;
  })[0].textContent;
  var matched = line.match(/(https*:\/\/[\w\.\/]+)/);
  if (matched) {
    window.location.href = matched[1];
  }
}
<commit_msg>add support for webptt.com<commit_after>'use strict';

var elements = document.querySelectorAll('.record');
if (elements.length) {
  var line = Array.prototype.filter.call(elements,function(record) {
    return record.textContent.indexOf('文章網址') !== -1;
  })[0].textContent;
  var matched = line.match(/(https*:\/\/[\w\.\/]+)/);
  if (matched) {
    window.location.href = matched[1];
  }
}
if (window.location.hostname == "webptt.com") {
  var search = window.location.search.split("n=");
  if (search.length > 1) {
    window.location.href = "https://www.ptt.cc/" + search[1];
  }
}
<|endoftext|>


<commit_before>var URL       = require("url");
var Cookies   = require("@rill/cookies");
var HttpError = require("@rill/error");
var Request   = require("./request");
var Response  = require("./response");

module.exports = Context;

function Context (app, req, res) {
	this.app      = app;
	this.req      = req;
	this.res      = res;
	this.request  = new Request(this);
	this.response = new Response(this);

	this.cookies           =
	this.request.cookies   =
	this.response.cookies  = new Cookies(req.headers.cookie);

	this.request.redirect  =
	this.response.redirect = this.redirect.bind(this);
}

var context = Context.prototype;

context.throw = function throwHttp (code, message, meta) {
	error = new HttpError(code, message, meta);
	this.response.status = error.code;
	throw error;
};

context.assert = function assertHttp (val, code, message, meta) {
	if (!val) this.throw(code, message, meta);
};

context.redirect = function redirect (url, alt) {
	url = (url === "back")
		? this.response.headers["referrer"] || alt
		: url;

	this.response.headers["location"] = URL.resolve(this.request.href, url);
}

context.refresh = function refresh (url, delay) {
	delay = delay || 0;
	url   = URL.resolve(this.request.href, url || this.request.href);

	this.response.headers["refresh"] = delay + "; url=" + url;
};<commit_msg>Better error message for invalid redirect<commit_after>var URL       = require("url");
var Cookies   = require("@rill/cookies");
var HttpError = require("@rill/error");
var Request   = require("./request");
var Response  = require("./response");

module.exports = Context;

function Context (app, req, res) {
	this.app      = app;
	this.req      = req;
	this.res      = res;
	this.request  = new Request(this);
	this.response = new Response(this);

	this.cookies           =
	this.request.cookies   =
	this.response.cookies  = new Cookies(req.headers.cookie);

	this.request.redirect  =
	this.response.redirect = this.redirect.bind(this);
}

var context = Context.prototype;

context.throw = function throwHttp (code, message, meta) {
	error = new HttpError(code, message, meta);
	this.response.status = error.code;
	throw error;
};

context.assert = function assertHttp (val, code, message, meta) {
	if (!val) this.throw(code, message, meta);
};

context.redirect = function redirect (url, alt) {
	url = (url === "back")
		? this.request.headers["referrer"]
		: url;

	url = url || alt;

	if (!url)
		throw new TypeError("Rill#redirect: Cannot redirect, url not specified and alternative not provided.");

	this.response.headers["location"] = URL.resolve(this.request.href, url);
}

context.refresh = function refresh (url, delay) {
	delay = delay || 0;
	url   = URL.resolve(this.request.href, url || this.request.href);

	this.response.headers["refresh"] = delay + "; url=" + url;
};<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name vleApp.Spec
 * @description
 * # Spec
 * Service in the vleApp.
 */
angular.module('vleApp')
  .service('Spec', function (_, vl, tv4, Config, Dataset) {
    var Spec = {
      /** @type {Object} verbose spec edited by the UI */
      spec: vl.schema.instantiate(),
      /** @type {Object} concise spec generated */
      vlSpec: null,
      /** @type {String} jsonify-ed vlSpec */
      vlSpecJson: '',
      /** @type {Encoding} encoding object from the spec */
      encoding:null,
      /** @type {String} generated vl shorthand */
      shorthand:null,
      /** @type {Object} generated vega spec */
      vgSpec:null,
      /** @type {String} jsonify-ed vgSpec */
      vgSpecJson:null
    };

    Spec._removeEmptyFieldDefs = function(spec) {
      spec.enc = _.omit(spec.enc, function(fieldDef) {
        return !fieldDef || fieldDef.name === undefined;
      });
    };

    function deleteNulls(spec) {
      for (var i in spec) {
        if (_.isObject(spec[i])) {
          deleteNulls(spec[i]);
        }
        // This is why I hate js
        if (spec[i] === null ||
          spec[i] === undefined ||
          (_.isObject(spec[i]) && vl.keys(spec[i]).length === 0) ||
          spec[i] === []) {
          delete spec[i];
        }
      }
    }

    Spec.parseShorthand = function(newShorthand) {
      Spec.spec = vl.Encoding.parseShorthand(newShorthand, Config.config).toSpec();
      Spec.updateSpec(Spec.spec);
    };

    Spec.resetSpec = function() {
      Spec.spec = vl.schema.instantiate();
    };

    // TODO: should we call this `specChanged` ?
    Spec.updateSpec = function(newSpec) {
      var cleanSpec = _.cloneDeep(newSpec);

      Spec._removeEmptyFieldDefs(cleanSpec);
      deleteNulls(cleanSpec);

      // we may have removed enc
      if (!('enc' in cleanSpec)) {
        cleanSpec.enc = {};
      }

      // TODO: remove defaults

      var schema = vl.schema.schema;
      // now validate the spec
      var result = tv4.validateMultiple(cleanSpec, schema);

      if (result.errors.length > 0) {
        console.error(cleanSpec, result.errors);
      } else {
        Spec.vlSpec = cleanSpec;
        Spec.vlSpecJson = JSON.stringify(Spec.vlSpec, null, '  ', 80);
        Spec.encoding = vl.Encoding.fromSpec(cleanSpec, Config.config);
        Spec.shorthand = Spec.encoding.toShorthand();
        Spec.vgSpec = vl.compile(Spec.encoding, Dataset.stats);
        Spec.vgSpecJson = JSON.stringify(Spec.vgSpec, null, '  ', 80);
      }
    };

    Spec.updateSpec(Spec.spec);

    return Spec;
  });
<commit_msg>Add alerts to spec.js<commit_after>'use strict';

/**
 * @ngdoc service
 * @name vleApp.Spec
 * @description
 * # Spec
 * Service in the vleApp.
 */
angular.module('vleApp')
  .service('Spec', function (_, vl, tv4, Alerts, Config, Dataset) {
    var Spec = {
      /** @type {Object} verbose spec edited by the UI */
      spec: vl.schema.instantiate(),
      /** @type {Object} concise spec generated */
      vlSpec: null,
      /** @type {String} jsonify-ed vlSpec */
      vlSpecJson: '',
      /** @type {Encoding} encoding object from the spec */
      encoding:null,
      /** @type {String} generated vl shorthand */
      shorthand:null,
      /** @type {Object} generated vega spec */
      vgSpec:null,
      /** @type {String} jsonify-ed vgSpec */
      vgSpecJson:null
    };

    Spec._removeEmptyFieldDefs = function(spec) {
      spec.enc = _.omit(spec.enc, function(fieldDef) {
        return !fieldDef || fieldDef.name === undefined;
      });
    };

    function deleteNulls(spec) {
      for (var i in spec) {
        if (_.isObject(spec[i])) {
          deleteNulls(spec[i]);
        }
        // This is why I hate js
        if (spec[i] === null ||
          spec[i] === undefined ||
          (_.isObject(spec[i]) && vl.keys(spec[i]).length === 0) ||
          spec[i] === []) {
          delete spec[i];
        }
      }
    }

    Spec.parseShorthand = function(newShorthand) {
      Spec.spec = vl.Encoding.parseShorthand(newShorthand, Config.config).toSpec();
      Spec.updateSpec(Spec.spec);
    };

    Spec.resetSpec = function() {
      Spec.spec = vl.schema.instantiate();
    };

    // TODO: should we call this `specChanged` ?
    Spec.updateSpec = function(newSpec) {
      var cleanSpec = _.cloneDeep(newSpec);

      Spec._removeEmptyFieldDefs(cleanSpec);
      deleteNulls(cleanSpec);

      // we may have removed enc
      if (!('enc' in cleanSpec)) {
        cleanSpec.enc = {};
      }

      // TODO: remove defaults
      var schema = vl.schema.schema;
      // now validate the spec
      var result = tv4.validateMultiple(cleanSpec, schema);

      if (result.errors.length > 0) {
        //FIXME: move this dependency to directive/controller layer
        Alerts.add({
          msg: result.errors
        });
      } else {
        Spec.vlSpec = cleanSpec;
        Spec.vlSpecJson = JSON.stringify(Spec.vlSpec, null, '  ', 80);
        Spec.encoding = vl.Encoding.fromSpec(cleanSpec, Config.config);
        Spec.shorthand = Spec.encoding.toShorthand();
        Spec.vgSpec = vl.compile(Spec.encoding, Dataset.stats);
        Spec.vgSpecJson = JSON.stringify(Spec.vgSpec, null, '  ', 80);
      }
    };

    Spec.updateSpec(Spec.spec);

    return Spec;
  });
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.layout',
  name: 'SectionAxiom',
  properties: [
    {
      class: 'String',
      name: 'name'
    },
    {
      class: 'String',
      name: 'title',
      expression: function(name) {
        return foam.String.capitalize(name);
      }
    },
    {
      class: 'String',
      name: 'help'
    },
    {
      class: 'Int',
      name: 'order',
      value: Number.MAX_VALUE
    },
    {
      class: 'Boolean',
      name: 'permissionRequired'
    },
    {
      class: 'Function',
      name: 'isAvailable',
      value: function() { return true; }
    }
  ],
  methods: [
    function createIsAvailableFor(data$) {
      var slot = foam.core.ExpressionSlot.create({
        obj$: data$,
        code: this.isAvailable
      });

      if ( this.permissionRequired ) {
        var permSlot = data$.map(data => {
          if ( ! data || ! data.__subContext__.auth ) return false;
          return data.__subContext__.auth.check(null,
            `${data.cls_.id.toLowerCase()}.section.${this.name}`);
        });

        slot = foam.core.ArraySlot.create({slots: [slot, permSlot]}).map(arr => {
          return arr.every(b => b);
        });
      }

      return slot;
    }
  ]
});

foam.CLASS({
  package: 'foam.layout',
  name: 'PropertySectionRefine',
  refines: 'foam.core.Property',
  properties: [
    {
      class: 'String',
      name: 'section'
    }
  ]
});

foam.CLASS({
  package: 'foam.layout',
  name: 'ActionSectionRefine',
  refines: 'foam.core.Action',
  properties: [
    {
      class: 'String',
      name: 'section'
    }
  ]
});

foam.CLASS({
  package: 'foam.layout',
  name: 'ModelSectionRefine',
  refines: 'foam.core.Model',
  properties: [
    {
      class: 'AxiomArray',
      of: 'foam.layout.SectionAxiom',
      name: 'sections'
    }
  ]
});
<commit_msg>Added default section axiom<commit_after>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.layout',
  name: 'SectionAxiom',
  properties: [
    {
      class: 'String',
      name: 'name'
    },
    {
      class: 'String',
      name: 'title',
      expression: function(name) {
        if (name === '_defaultSection') return '';
        return foam.String.capitalize(name);
      }
    },
    {
      class: 'String',
      name: 'help'
    },
    {
      class: 'Int',
      name: 'order',
      value: Number.MAX_VALUE
    },
    {
      class: 'Boolean',
      name: 'permissionRequired'
    },
    {
      class: 'Function',
      name: 'isAvailable',
      value: function() { return true; }
    }
  ],
  methods: [
    function createIsAvailableFor(data$) {
      var slot = foam.core.ExpressionSlot.create({
        obj$: data$,
        code: this.isAvailable
      });

      if ( this.permissionRequired ) {
        var permSlot = data$.map(data => {
          if ( ! data || ! data.__subContext__.auth ) return false;
          return data.__subContext__.auth.check(null,
            `${data.cls_.id.toLowerCase()}.section.${this.name}`);
        });

        slot = foam.core.ArraySlot.create({slots: [slot, permSlot]}).map(arr => {
          return arr.every(b => b);
        });
      }

      return slot;
    }
  ]
});

foam.CLASS({
  package: 'foam.layout',
  name: 'PropertySectionRefine',
  refines: 'foam.core.Property',
  properties: [
    {
      class: 'String',
      name: 'section',
      value: '_defaultSection'
    }
  ]
});

foam.CLASS({
  package: 'foam.layout',
  name: 'ActionSectionRefine',
  refines: 'foam.core.Action',
  properties: [
    {
      class: 'String',
      name: 'section',
      value: '_defaultSection'
    }
  ]
});

foam.CLASS({
  package: 'foam.layout',
  name: 'ModelSectionRefine',
  refines: 'foam.core.Model',
  properties: [
    {
      class: 'AxiomArray',
      of: 'foam.layout.SectionAxiom',
      name: 'sections'
    }
  ]
});
<|endoftext|>


<commit_before>import Service from '@ember/service'
import { getName, getParams, getChild, getBlockSiblings, isOperator, isValue, isProcedureCall } from './block-utils'
import { createNode, createReference, createEmptyNode } from './pilas-ast'

export default Service.extend({

  parseAll(workspace) {
    return workspace.getTopBlocks().map(this.parse)
  },

  parse(mainBlock) {
    return buildBlockAst(mainBlock);
  },

});

function buildBlockAst(block) {
  let tag = mulangTag(block);
  return createNode(tag, mulangParsers[tag](block));
}

function buildSequenceAst(topLevelBlock) {
  if (!topLevelBlock) return createEmptyNode();
  let siblings = getBlockSiblings(topLevelBlock);
  if (siblings.length) {
    return createNode("Sequence", [topLevelBlock, ...siblings].map(b => buildBlockAst(b)))
  } else {
    return buildBlockAst(topLevelBlock);
  }
}

function mulangTag(block) {
  let tag = pilasToMulangTags[block.type]
  if (tag) return tag
  return isValue(block) ? "Reference" : "Application"
}

let pilasToMulangTags = {
  "al_empezar_a_ejecutar": "EntryPoint",
  "repetir": "Repeat",
  "Si": "If",
  "SiNo": "If",
  "Hasta": "While",
  "math_number": "MuNumber",
  "Numero": "MuNumber",
  "procedures_defnoreturn": "Procedure",
  "variables_get": "Reference", //TODO: Model each one with tag & parse
}

function parseMuNumber(block) {
  return parseFloat(block.getFieldValue("NUM"));
}

function parseEntryPoint(block) {
  return [
    block.type,
    buildSequenceAst(getChild(block))
  ]
}

function referenceName(block) {
  return  isProcedureCall(block) ? block.getFieldValue('NAME')
        : isOperator(block) ? block.getFieldValue('OP')
        : block.type
}

function parseApplication(block) {
  return [
    createReference(referenceName(block)),
    parseArguments(block)
  ]
}

function parseReference(block) {
  if (block.type == "variables_get") //TODO
    return parseVariable(block)
  else
    return block.type
}

function parseVariable(block) {
  return block.getFieldValue("VAR")
}

function parseArguments(block) {
  return block.inputList
    .filter(input => input.type == Blockly.INPUT_VALUE)
    .map(input => input.connection.targetBlock())
    .map(b => buildBlockAst(b))
    .concat(...parseText(block))
}

function parseText(block) {
  let text = block.getFieldValue("texto") // TODO: Mega-hard-coded?
  if (!text) return []
  return [createNode("MuString", text)]
}

function parseRepeat(block) {
  let countBlock = block.getInputTargetBlock("count")
  let statements = block.getInputTargetBlock("block")
  return [
    buildBlockAst(countBlock),
    buildSequenceAst(statements)
  ]
}

function parseWhile(block) {
  let condition = block.getInputTargetBlock("condition")
  let statements = block.getInputTargetBlock("block")
  return [
    buildBlockAst(condition),
    buildSequenceAst(statements)
  ]
}

function parseAbstractIf(block) {
  if (block.type == "Si")
    return parseIf(block)
  else
    return parseIfElse(block)
}

function parseIf(block) {
  let condition = block.getInputTargetBlock("condition")
  let statements = block.getInputTargetBlock("block")
  return [
    buildBlockAst(condition),
    buildSequenceAst(statements),
    createEmptyNode()
  ]
}

function parseIfElse(block) {
  let condition = block.getInputTargetBlock("condition")
  let statementsIf = block.getInputTargetBlock("block1")
  let statementsElse = block.getInputTargetBlock("block2")
  return [
    buildBlockAst(condition),
    buildSequenceAst(statementsIf),
    buildSequenceAst(statementsElse)
  ]
}

function parseProcedure(block) {
  return [
    getName(block),
    createNode("Equation", parseEquation(block))
  ];
}

function parseEquation(block) {
  return [
    parseEquationParams(block),
    parseEquationBody(block)
  ]
}

function parseEquationParams(block) {
  return getParams(block).map(argument => createNode("VariablePattern", argument));
}

function parseEquationBody(block) {
  let bodyContents = buildSequenceAst(getChild(block));
  return createNode("UnguardedBody", bodyContents);
}

let mulangParsers = {
  "Application": parseApplication,
  "Reference": parseReference,
  "Repeat": parseRepeat,
  "While": parseWhile,
  "If": parseAbstractIf,
  "Procedure": parseProcedure,
  "MuNumber": parseMuNumber,
  "EntryPoint": parseEntryPoint
}
<commit_msg>Ignoring shadows on parse ast<commit_after>import Service from '@ember/service'
import { getName, getParams, getChild, getBlockSiblings, isOperator, isValue, isProcedureCall } from './block-utils'
import { createNode, createReference, createEmptyNode } from './pilas-ast'

export default Service.extend({

  parseAll(workspace) {
    return workspace.getTopBlocks().map(this.parse)
  },

  parse(mainBlock) {
    return buildBlockAst(mainBlock)
  },

})

function buildBlockAst(block) {
  let tag = mulangTag(block)
  return createNode(tag, mulangParsers[tag](block))
}

function buildSequenceAst(firstBlock) {
  if (!firstBlock || firstBlock.isShadow()) return createEmptyNode()
  let siblings = getBlockSiblings(firstBlock).filter(block => !block.isShadow())
  if (siblings.length) {
    return createNode("Sequence", [firstBlock, ...siblings].map(b => buildBlockAst(b)))
  } else {
    return buildBlockAst(firstBlock)
  }
}

function mulangTag(block) {
  let tag = pilasToMulangTags[block.type]
  if (tag) return tag
  return isValue(block) ? "Reference" : "Application"
}

let pilasToMulangTags = {
  "al_empezar_a_ejecutar": "EntryPoint",
  "repetir": "Repeat",
  "Si": "If",
  "SiNo": "If",
  "Hasta": "While",
  "math_number": "MuNumber",
  "Numero": "MuNumber",
  "procedures_defnoreturn": "Procedure",
  "variables_get": "Reference", //TODO: Model each one with tag & parse
}

function parseMuNumber(block) {
  return parseFloat(block.getFieldValue("NUM"))
}

function parseEntryPoint(block) {
  return [
    block.type,
    buildSequenceAst(getChild(block))
  ]
}

function referenceName(block) {
  return  isProcedureCall(block) ? block.getFieldValue('NAME')
        : isOperator(block) ? block.getFieldValue('OP')
        : block.type
}

function parseApplication(block) {
  return [
    createReference(referenceName(block)),
    parseArguments(block)
  ]
}

function parseReference(block) {
  if (block.type == "variables_get") //TODO
    return parseVariable(block)
  else
    return block.type
}

function parseVariable(block) {
  return block.getFieldValue("VAR")
}

function parseArguments(block) {
  return block.inputList
    .filter(input => input.type == Blockly.INPUT_VALUE)
    .map(input => input.connection.targetBlock())
    .map(b => buildBlockAst(b))
    .concat(...parseText(block))
}

function parseText(block) {
  let text = block.getFieldValue("texto") // TODO: Mega-hard-coded?
  if (!text) return []
  return [createNode("MuString", text)]
}

function parseRepeat(block) {
  let countBlock = block.getInputTargetBlock("count")
  let statements = block.getInputTargetBlock("block")
  return [
    buildBlockAst(countBlock),
    buildSequenceAst(statements)
  ]
}

function parseWhile(block) {
  let condition = block.getInputTargetBlock("condition")
  let statements = block.getInputTargetBlock("block")
  return [
    buildBlockAst(condition),
    buildSequenceAst(statements)
  ]
}

function parseAbstractIf(block) {
  if (block.type == "Si")
    return parseIf(block)
  else
    return parseIfElse(block)
}

function parseIf(block) {
  let condition = block.getInputTargetBlock("condition")
  let statements = block.getInputTargetBlock("block")
  return [
    buildBlockAst(condition),
    buildSequenceAst(statements),
    createEmptyNode()
  ]
}

function parseIfElse(block) {
  let condition = block.getInputTargetBlock("condition")
  let statementsIf = block.getInputTargetBlock("block1")
  let statementsElse = block.getInputTargetBlock("block2")
  return [
    buildBlockAst(condition),
    buildSequenceAst(statementsIf),
    buildSequenceAst(statementsElse)
  ]
}

function parseProcedure(block) {
  return [
    getName(block),
    createNode("Equation", parseEquation(block))
  ]
}

function parseEquation(block) {
  return [
    parseEquationParams(block),
    parseEquationBody(block)
  ]
}

function parseEquationParams(block) {
  return getParams(block).map(argument => createNode("VariablePattern", argument))
}

function parseEquationBody(block) {
  let bodyContents = buildSequenceAst(getChild(block))
  return createNode("UnguardedBody", bodyContents)
}

let mulangParsers = {
  "Application": parseApplication,
  "Reference": parseReference,
  "Repeat": parseRepeat,
  "While": parseWhile,
  "If": parseAbstractIf,
  "Procedure": parseProcedure,
  "MuNumber": parseMuNumber,
  "EntryPoint": parseEntryPoint
}
<|endoftext|>


<commit_before>function getInheritedStateValue(inheritedStates, key) {
    for (var i = 0; i < inheritedStates.length; i++) {
        if (inheritedStates[i][key]) {
            return inheritedStates[i][key];
        }
    }
}

/*
function updateStyle(currentStyle, styles, inheritedStyles) {
    let style = '';
    for (var key in styles) {
        const value = (styles[key] && (styles[key] !== getInheritedStateValue(inheritedStyles, key))) ? styles[key] : undefined;
        if (value) {
            style += key + ': ' + value + ';'
        }
    }
    if (style !== currentStyle) {
        if (currentStyle) {
            res += '';
        }
        currentStyle = style;
        if (currentStyle) {
            res += '';
        }
    }
}*/

function format(data, inheritedStyles, context) {
    const styles = {};
    let currentStyle;
    let ignoreAll;
    let ignoreNextText;
    for (var i = 0; i < data.length; i++) {
        const item = data[i];
        if (Array.isArray(item)) {
            for (var j = 0; j < item.length; j++) {
                const code = item[j];
                switch (code) {
                    case 'par':
                        //context.res.push('
\n');
                        //context.divIndex = -1;
                        context.res.push('
');
                        break;
                    case 'tab':
                        //res += ''
                        /*if (!table) {
                            table = true;
                            inheritedStyles = [styles].concat(inheritedStyles);
                            styles = {};
                            insideTableRow = true;
                            res += '

';
                        }
                        res += '	';*/
                        break;
                    case 'colortbl':
                    case 'fonttbl':
                    case 'stylesheet':
                        ignoreAll = true;
                        break;
                    case 'expndtw':
                        ignoreNextText = true;
                        break;
                    case 'i': styles['font-style'] = 'italic'; break;
                    case 'i0': styles['font-style'] = 'normal'; break;
                    case 'b': styles['font-weight'] = 'bold'; break;
                    case 'b0': styles['font-weight'] = 'normal'; break;
                    case 'ql':
                    case 'qc':
                    case 'qr':
                        styles['text-align'] = (code === 'qc') ? 'center' : (code === 'qr') ? 'right' : 'left';
                        styles['display'] = 'block';
                        break;
                }
                let fontSize = code.match(/fs(\d+)/);
                if (fontSize) {
                    styles['font-size'] = fontSize[0].substring(2) + 'px';
                }
            }
        }
        else {
            let style = '';
            for (var key in styles) {
                const value = (styles[key] && (styles[key] !== getInheritedStateValue(inheritedStyles, key))) ? styles[key] : undefined;
                if (value) {
                    style += key + ': ' + value + ';'
                }
            }
            if (style !== currentStyle) {
                if (currentStyle) {
                    context.res.push('');
                }
                currentStyle = style;
                if (currentStyle && !ignoreAll) {
                    context.res.push('');
                }
            }
            /*if (context.divIndex === -1) {
                context.divIndex = context.res.length;
                context.res.push('
 ');
            }*/
            if (!ignoreAll) {
                if (typeof item === 'string') {
                    if (!ignoreNextText) {
                        context.res.push(item);
                    }
                    else {
                        ignoreNextText = false;
                    }
                }
                else {
                    format(item.group, [styles].concat(inheritedStyles), context);
                }
            }
        }
    }
    if (currentStyle) {
        context.res.push('\n');
    }
    return context.res;
}

export default function(parsedRtf) {
    return '
' + format(parsedRtf.group, [], {
        res: [],
        divIndex: -1
    }).join('') + '
';
};
<commit_msg>Largely working html formatter<commit_after>function getInheritedStateValue(inheritedStates, key) {
    for (var i = 0; i < inheritedStates.length; i++) {
        if (inheritedStates[i][key]) {
            return inheritedStates[i][key];
        }
    }
}

function inchToPx(inch) {
    return Math.floor(inch / 15);
}

function formatStyles(styles, inheritedStyles) {
    let style = '';
    for (var key in styles) {
        const value = (styles[key] && (styles[key] !== getInheritedStateValue(inheritedStyles, key))) ? styles[key] : undefined;
        if (value) {
            style += key + ': ' + value + ';'
        }
    }
    return style;
}

function pushStyles(context) {
    const formattedStyles = formatStyles(context.styles, context.inheritedStyles);
    if (formattedStyles) {
        context.res.push('');
    }
    context.inheritedStyles.unshift(context.styles);
    context.styles = {};
    context.lastFormattedStyles = formattedStyles;
}

function popStyles(context) {
    context.styles = context.inheritedStyles[0];
    context.inheritedStyles = context.inheritedStyles.slice(1);
    const formattedStyles = formatStyles(context.styles, context.inheritedStyles);
    if (formattedStyles) {
        context.res.push('');
    }
}

function applyStyles(context) {
    const formattedStyles = formatStyles(context.styles, context.inheritedStyles);
    if (context.lastFormattedStyles !== formattedStyles) {
        popStyles(context);
        pushStyles(context);
    }
}

function beginRightAlignedTab(context) {
    context.rightAlignedTab = true;
    pushStyles(context);
    context.res.push('');
}

function endRightAlignedTab(context) {
    if (context.rightAlignedTab) {
        context.rightAlignedTab = false;
        context.res.push('');
        popStyles(context);
    }
}

function getTabWidth(context) {
    const begin = (context.tabIndex === 0) ? 0 : context.tabs[context.tabIndex - 1].pos;
    const end = ((context.tabIndex + 1) < context.tabs.length) ? context.tabs[context.tabIndex + 1].pos : context.paperWidth;
    return end - begin;
}

function format(data, context) {
    let ignoreAll;
    let ignoreNextText;
    for (var i = 0; i < data.length; i++) {
        const item = data[i];
        if (Array.isArray(item)) {
            let resetTabs = true;
            let tabAlign;
            for (var j = 0; j < item.length; j++) {
                const code = item[j];
                switch (code) {
                    case 'par':
                        endRightAlignedTab(context);
                        if (context.divIndex >= 0) {
                            popStyles(context);
                            context.res.push('
');
                            context.divIndex = -1;
                        }
                        context.tabIndex = 0;
                        context.res.push('
\n');
                        break;
                    case 'tab':
                        if (context.tabIndex < context.tabs.length) {
                            if (context.divIndex < 0) {
                                context.divIndex = context.res.length;
                                context.res.push('
');
                                pushStyles(context);
                            }
                            if (context.rightAlignedTab) {
                                endRightAlignedTab(context);
                                popStyles(context);
                                context.res.push('
');
                                context.divIndex = context.res.length;
                                context.res.push('
');
                                pushStyles(context);
                            }
                            const tab = context.tabs[context.tabIndex];
                            context.res[context.divIndex] = '
';
                            if (tab.align === 'right') {
                                beginRightAlignedTab(context);
                            }
                            else {
                                popStyles(context);
                                context.res.push('
');
                                context.divIndex = context.res.length;
                                context.res.push('
');
                                pushStyles(context);
                            }
                            context.tabIndex++;
                        }
                        break;
                    case 'colortbl':
                    case 'fonttbl':
                    case 'stylesheet':
                        ignoreAll = true;
                        break;
                    case 'expndtw':
                        ignoreNextText = true;
                        break;
                    case 'tqr':
                        context.tabs = resetTabs ? [] : context.tabs;
                        resetTabs = false;
                        tabAlign = 'right';
                        break;
                    case 'i': context.styles['font-style'] = 'italic'; break;
                    case 'i0': context.styles['font-style'] = 'normal'; break;
                    case 'b': context.styles['font-weight'] = 'bold'; break;
                    case 'b0': context.styles['font-weight'] = 'normal'; break;
                    case 'ql':
                    case 'qc':
                    case 'qr':
                        context.styles['text-align'] = (code === 'qc') ? 'center' : (code === 'qr') ? 'right' : 'left';
                        break;
                }
                let fontSize = code.match(/fs(\d+)/);
                if (fontSize) {
                    context.styles['font-size'] = fontSize[0].substring(2) + 'px';
                }
                let paperWidth = code.match(/paperw(\d+)/);
                if (paperWidth) {
                    context.paperWidth = inchToPx(paperWidth[0].substring(6));
                    //console.log('paperWidth: ' + paperWidth[0].substring(6) + ' = ' + context.paperWidth + 'px');
                }
                let tabStop = code.match(/tx(\d+)/);
                if (tabStop) {
                    context.tabs = resetTabs ? [] : context.tabs;
                    resetTabs = false;
                    context.tabs.push({
                        pos: inchToPx(tabStop[0].substring(2)),
                        align: tabAlign || 'left'
                    });
                    tabAlign = undefined;
                }
                let leftIndent = code.match(/li(\d+)/);
                if (leftIndent) {
                    leftIndent = inchToPx(leftIndent[0].substring(2));
                    context.styles['text-indent'] = leftIndent ? (leftIndent + 'px') : 0;
                }
            }
        }
        else {
            if (!ignoreAll) {
                if (typeof item === 'string') {
                    if (!ignoreNextText) {
                        if (context.divIndex < 0) {
                            context.divIndex = context.res.length;
                            context.res.push('
');
                            pushStyles(context);
                        }
                        applyStyles(context);
                        context.res.push(item);
                    }
                    else {
                        ignoreNextText = false;
                    }
                }
                else {
                    pushStyles(context);
                    format(item.group, context);
                    popStyles(context);
                }
            }
        }
    }
    return context.res;
}

export default function(parsedRtf) {
    return '' +
        '<!DOCTYPE html>\n' +
        '\n' +
        '\n' +
        '\n' +
        '\n' +
        '\n' +
    format(parsedRtf.group, {
        res: [],
        divIndex: -1,
        inheritedStyles: [],
        styles: {},
        tabIndex: 0,
        tabs: []
    }).join('') + '\n' +
        '\n' +
        '\n';
};
<|endoftext|>


<commit_before>/* eslint-disable @typescript-eslint/no-var-requires */

const path = require('path')

module.exports = {
  theme: {
    extend: {
      colors: {
        green: {
          50: '#ecf8f7',
          100: '#d3f7ef',
          200: '#a5f2db',
          300: '#66e9c2',
          400: '#20d99b',
          500: '#42B983',
          600: '#09ab56',
          700: '#0f8c4a',
          800: '#126e41',
          900: '#115937'
        },
        purple: {
          50: '#f3f3fa',
          100: '#ece3fa',
          200: '#ddc3f9',
          300: '#cea3f9',
          400: '#c378f9',
          500: '#a44cf6',
          600: '#a331f7',
          700: '#8128e8',
          800: '#6523c4',
          900: '#521fa0'
        },
        bluegray: {
          50: '#f3f9fb',
          100: '#e4f4f9',
          200: '#c5e7f4',
          300: '#9cd5f0',
          400: '#89a9c9',
          500: '#328de3',
          600: '#266ad2',
          700: '#2653ae',
          800: '#224082',
          900: '#1d3564'
        },
        black: '#0b1015'
      },
      cursor: {
        'ew-resize': 'ew-resize',
        'ns-resize': 'ns-resize'
      },
      zIndex: {
        60: 60,
        70: 70,
        80: 80,
        90: 90,
        100: 100
      },
      fontFamily: {
        mono: '\'Roboto Mono\', monospace'
      },
      fontSize: {
        '2xs': '.65rem',
        '3xs': '.6rem'
      },
      spacing: {
        0.5: '0.125rem',
        72: '18rem',
        80: '20rem',
        96: '24rem'
      }
    }
  },
  variants: {
    backgroundColor: ['hover', 'group-hover', 'dark'],
    backgroundOpacity: ['hover', 'group-hover', 'dark'],
    textColor: ['hover', 'group-hover', 'dark'],
    visibility: ['group-hover']
  },
  darkMode: 'class',
  purge: {
    content: [
      path.resolve(__dirname, './packages/app-frontend/src/**/*.vue')
    ]
  }
}
<commit_msg>chore: enable tailwind jit<commit_after>/* eslint-disable @typescript-eslint/no-var-requires */

const path = require('path')

module.exports = {
  theme: {
    extend: {
      colors: {
        green: {
          50: '#ecf8f7',
          100: '#d3f7ef',
          200: '#a5f2db',
          300: '#66e9c2',
          400: '#20d99b',
          500: '#42B983',
          600: '#09ab56',
          700: '#0f8c4a',
          800: '#126e41',
          900: '#115937'
        },
        purple: {
          50: '#f3f3fa',
          100: '#ece3fa',
          200: '#ddc3f9',
          300: '#cea3f9',
          400: '#c378f9',
          500: '#a44cf6',
          600: '#a331f7',
          700: '#8128e8',
          800: '#6523c4',
          900: '#521fa0'
        },
        bluegray: {
          50: '#f3f9fb',
          100: '#e4f4f9',
          200: '#c5e7f4',
          300: '#9cd5f0',
          400: '#89a9c9',
          500: '#328de3',
          600: '#266ad2',
          700: '#2653ae',
          800: '#224082',
          900: '#1d3564'
        },
        black: '#0b1015'
      },
      cursor: {
        'ew-resize': 'ew-resize',
        'ns-resize': 'ns-resize'
      },
      zIndex: {
        60: 60,
        70: 70,
        80: 80,
        90: 90,
        100: 100
      },
      fontFamily: {
        mono: '\'Roboto Mono\', monospace'
      },
      fontSize: {
        '2xs': '.65rem',
        '3xs': '.6rem'
      },
      spacing: {
        0.5: '0.125rem',
        72: '18rem',
        80: '20rem',
        96: '24rem'
      }
    }
  },
  variants: {
    backgroundColor: ['hover', 'group-hover', 'dark'],
    backgroundOpacity: ['hover', 'group-hover', 'dark'],
    textColor: ['hover', 'group-hover', 'dark'],
    visibility: ['group-hover']
  },
  darkMode: 'class',
  mode: 'jit',
  purge: {
    content: [
      path.resolve(__dirname, './packages/app-frontend/src/**/*.vue')
    ]
  }
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';

let roleUrlRegex = new RegExp('/roles/([a-zA-Z0-9\-]+)$');

function getRoleIdFromPermission(permission){
  var roleUrl = permission.get('data.links.role');
  return roleUrlRegex.exec(roleUrl)[1];
}

export default DS.Model.extend({
  // properties
  name: DS.attr('string'),
  handle: DS.attr('string'),
  number: DS.attr('string'),
  type: DS.attr('string'),
  syslogHost: DS.attr('string'),
  syslogPort: DS.attr('string'),
  organizationUrl: DS.attr('string'),
  activated: DS.attr('boolean'),
  containerCount: DS.attr('number'),
  domainCount: DS.attr('number'),
  totalDiskSize: DS.attr('number'),

  // relationships
  apps: DS.hasMany('app', {async: true}),
  certificates: DS.hasMany('certificate', {async: true}),
  databases: DS.hasMany('database', {async: true}),
  permissions: DS.hasMany('permission', {async:true}),
  organization: DS.belongsTo('organization', {async:true}),
  logDrains: DS.hasMany('log-drain', {async:true}),
  vhosts: DS.hasMany('vhost', {async:true}),

  // computed properties
  pending: Ember.computed.not('activated'),
  allowPHI: Ember.computed.match('type', /production/),
  appContainerCentsPerHour: 8,

  getUsageByResourceType(type) {
    let usageAttr = { container: 'containerCount', disk: 'totalDiskSize',
                      domain: 'domainCount' }[type];
    return this.get(usageAttr);
  },

  permitsRole(role, scope){
    let permissions;

    if (role.get('privileged') &&
        role.get('data.links.organization') === this.get('data.links.organization')) {
      return new Ember.RSVP.Promise((resolve) => {
        resolve(true);
      });
    }

    return this.get('permissions').then(function(_permissions){
      permissions = _permissions;

      return permissions.map(function(perm){
        return {
          roleId: getRoleIdFromPermission(perm),
          scope:  perm.get('scope')
        };
      });
    }).then(function(stackRoleScopes){
      return Ember.A(Ember.A(stackRoleScopes).filter((stackRoleScope) => {
        return role.get('id') === stackRoleScope.roleId;
      })).any((stackRoleScope) => {
        return stackRoleScope.scope === 'manage' ||
          stackRoleScope.scope === scope;
      });
    });
  }
});
<commit_msg>add stack fields<commit_after>import Ember from 'ember';
import DS from 'ember-data';

let roleUrlRegex = new RegExp('/roles/([a-zA-Z0-9\-]+)$');

function getRoleIdFromPermission(permission){
  var roleUrl = permission.get('data.links.role');
  return roleUrlRegex.exec(roleUrl)[1];
}

export default DS.Model.extend({
  // properties
  name: DS.attr('string'),
  handle: DS.attr('string'),
  number: DS.attr('string'),
  type: DS.attr('string'),
  syslogHost: DS.attr('string'),
  syslogPort: DS.attr('string'),
  organizationUrl: DS.attr('string'),
  activated: DS.attr('boolean'),
  containerCount: DS.attr('number'),
  appContainerCount: DS.attr('number'),
  databaseContainerCount: DS.attr('number'),
  domainCount: DS.attr('number'),
  totalAppCount: DS.attr('number'),
  totalDatabaseCount: DS.attr('number'),
  totalDiskSize: DS.attr('number'),

  // relationships
  apps: DS.hasMany('app', {async: true}),
  certificates: DS.hasMany('certificate', {async: true}),
  databases: DS.hasMany('database', {async: true}),
  permissions: DS.hasMany('permission', {async:true}),
  organization: DS.belongsTo('organization', {async:true}),
  logDrains: DS.hasMany('log-drain', {async:true}),
  vhosts: DS.hasMany('vhost', {async:true}),

  // computed properties
  pending: Ember.computed.not('activated'),
  allowPHI: Ember.computed.match('type', /production/),
  appContainerCentsPerHour: 8,

  getUsageByResourceType(type) {
    let usageAttr = { container: 'containerCount', disk: 'totalDiskSize',
                      domain: 'domainCount' }[type];
    return this.get(usageAttr);
  },

  permitsRole(role, scope){
    let permissions;

    if (role.get('privileged') &&
        role.get('data.links.organization') === this.get('data.links.organization')) {
      return new Ember.RSVP.Promise((resolve) => {
        resolve(true);
      });
    }

    return this.get('permissions').then(function(_permissions){
      permissions = _permissions;

      return permissions.map(function(perm){
        return {
          roleId: getRoleIdFromPermission(perm),
          scope:  perm.get('scope')
        };
      });
    }).then(function(stackRoleScopes){
      return Ember.A(Ember.A(stackRoleScopes).filter((stackRoleScope) => {
        return role.get('id') === stackRoleScope.roleId;
      })).any((stackRoleScope) => {
        return stackRoleScope.scope === 'manage' ||
          stackRoleScope.scope === scope;
      });
    });
  }
});
<|endoftext|>


<commit_before>import browserify from 'browserify'
import rebundler from 'rebundler'
import SpawnStream from 'spawn-stream'

import {env} from '../config'
//import collapser from 'bundle-collapser/plugin'

import babelify from 'babelify'
import envify from 'envify'

function createBundle(entries) {

  return rebundler({noop: env !== 'development'}, (cache, pkgCache) => {
    return browserify(entries, {
      cache: cache,
      packageCache: pkgCache,
      extensions: ['.jsx'],
      debug: env == 'development',
      fullPaths: env == 'development'
    })
  })
}

const UGLIFY_CMD = require.resolve('uglify-js/bin/uglifyjs')

function uglify() {
  return SpawnStream(UGLIFY_CMD, [
    '--compress',
    '--mangle',
    '--screw-ie8'
  ])
}

const site = createBundle([
  //env === 'development' && require.resolve('../lib/react-a11y'),
  require.resolve('../bundles/site/entry.jsx')
].filter(Boolean))

const loader = createBundle([
  require.resolve('../bundles/loader.js')
].filter(Boolean))

const embeds = createBundle([
  require.resolve('../bundles/embeds/entry.jsx')
].filter(Boolean))

const embedsDebug = createBundle([
  require.resolve('../bundles/debug/embeds.jsx')
].filter(Boolean))

const test = createBundle(require.resolve('../docsite/bundle.jsx'))

export default {

  '/build/js/loader.js'() {
    console.time(';// Bundle') // eslint-disable-line no-console
    const bundle = loader()
      .transform(babelify)
      .transform(envify, {global: env !== 'development'})

    if (env !== 'development') {
      //bundle.plugin(collapser)
    }

    const stream = bundle.bundle()

    if (env !== 'development') {
      return stream.pipe(uglify())
    }

    stream.on('end', () => {
      console.timeEnd(';// Bundle') // eslint-disable-line no-console
    })
    return stream
  },
  '/build/js/embeds.js'() {
    console.time(';// Bundle') // eslint-disable-line no-console
    const bundle = embeds()
      .transform(babelify)
      .transform(envify, {global: env !== 'development'})

    if (env !== 'development') {
      //bundle.plugin(collapser)
    }

    const stream = bundle.bundle()

    if (env !== 'development') {
      return stream.pipe(uglify())
    }

    stream.on('end', () => {
      console.timeEnd(';// Bundle') // eslint-disable-line no-console
    })
    return stream
  },
  '/build/js/embeds-debug.js'() {
    console.time(';// Bundle') // eslint-disable-line no-console
    const bundle = embedsDebug()
      .transform(babelify)
      .transform(envify, {global: env !== 'development'})

    if (env !== 'development') {
      //bundle.plugin(collapser)
    }

    const stream = bundle.bundle()

    if (env !== 'development') {
      return stream.pipe(uglify())
    }

    stream.on('end', () => {
      console.timeEnd(';// Bundle') // eslint-disable-line no-console
    })
    return stream
  },
  '/build/js/site.js'() {
    console.time(';// Bundle') // eslint-disable-line no-console
    const bundle = site()
      .transform(babelify)
      .transform(envify, {global: env !== 'development'})

    if (env !== 'development') {
      //bundle.plugin(collapser)
    }

    const stream = bundle.bundle()

    if (env !== 'development') {
      return stream.pipe(uglify())
    }

    stream.on('end', () => {
      console.timeEnd(';// Bundle') // eslint-disable-line no-console
    })
    return stream
  },
  '/build/js/test.js'() {
    if (env !== 'development') {
      return '// only development'
    }
    return test()
      .transform('redocify')
      .transform(babelify)
      .transform(envify, {global: env !== 'development'})
      .bundle()
  }
}
<commit_msg>Use bundle-collapser<commit_after>import browserify from 'browserify'
import rebundler from 'rebundler'
import SpawnStream from 'spawn-stream'

import {env} from '../config'
import collapser from 'bundle-collapser/plugin'

import babelify from 'babelify'
import envify from 'envify'

function createBundle(entries) {

  return rebundler({noop: env !== 'development'}, (cache, pkgCache) => {
    return browserify(entries, {
      cache: cache,
      packageCache: pkgCache,
      extensions: ['.jsx'],
      debug: env == 'development',
      fullPaths: env == 'development'
    })
  })
}

const UGLIFY_CMD = require.resolve('uglify-js/bin/uglifyjs')

function uglify() {
  return SpawnStream(UGLIFY_CMD, [
    '--compress',
    '--mangle',
    '--screw-ie8'
  ])
}

const site = createBundle([
  //env === 'development' && require.resolve('../lib/react-a11y'),
  require.resolve('../bundles/site/entry.jsx')
].filter(Boolean))

const loader = createBundle([
  require.resolve('../bundles/loader.js')
].filter(Boolean))

const embeds = createBundle([
  require.resolve('../bundles/embeds/entry.jsx')
].filter(Boolean))

const embedsDebug = createBundle([
  require.resolve('../bundles/debug/embeds.jsx')
].filter(Boolean))

const test = createBundle(require.resolve('../docsite/bundle.jsx'))

export default {

  '/build/js/loader.js'() {
    console.time(';// Bundle') // eslint-disable-line no-console
    const bundle = loader()
      .transform(babelify)
      .transform(envify, {global: env !== 'development'})

    if (env !== 'development') {
      bundle.plugin(collapser)
    }

    const stream = bundle.bundle()

    if (env !== 'development') {
      return stream.pipe(uglify())
    }

    stream.on('end', () => {
      console.timeEnd(';// Bundle') // eslint-disable-line no-console
    })
    return stream
  },
  '/build/js/embeds.js'() {
    console.time(';// Bundle') // eslint-disable-line no-console
    const bundle = embeds()
      .transform(babelify)
      .transform(envify, {global: env !== 'development'})

    if (env !== 'development') {
      bundle.plugin(collapser)
    }

    const stream = bundle.bundle()

    if (env !== 'development') {
      return stream.pipe(uglify())
    }

    stream.on('end', () => {
      console.timeEnd(';// Bundle') // eslint-disable-line no-console
    })
    return stream
  },
  '/build/js/embeds-debug.js'() {
    console.time(';// Bundle') // eslint-disable-line no-console
    const bundle = embedsDebug()
      .transform(babelify)
      .transform(envify, {global: env !== 'development'})

    if (env !== 'development') {
      bundle.plugin(collapser)
    }

    const stream = bundle.bundle()

    if (env !== 'development') {
      return stream.pipe(uglify())
    }

    stream.on('end', () => {
      console.timeEnd(';// Bundle') // eslint-disable-line no-console
    })
    return stream
  },
  '/build/js/site.js'() {
    console.time(';// Bundle') // eslint-disable-line no-console
    const bundle = site()
      .transform(babelify)
      .transform(envify, {global: env !== 'development'})

    if (env !== 'development') {
      //bundle.plugin(collapser)
    }

    const stream = bundle.bundle()

    if (env !== 'development') {
      return stream.pipe(uglify())
    }

    stream.on('end', () => {
      console.timeEnd(';// Bundle') // eslint-disable-line no-console
    })
    return stream
  },
  '/build/js/test.js'() {
    if (env !== 'development') {
      return '// only development'
    }
    return test()
      .transform('redocify')
      .transform(babelify)
      .transform(envify, {global: env !== 'development'})
      .bundle()
  }
}
<|endoftext|>