<commit_before>"use strict";

var Rule = require('./peasy').Rule;
var BusinessService = require('./peasy').BusinessService;
var Command = require('./peasy').Command;

var AgeRule = Rule.extend({
  association: "age",
  params: ['birthdate'],
  onValidate: function(done) {
    if (new Date().getFullYear() - this.birthdate.getFullYear() < 50) {
      this.__invalidate("You are too young");
    }
    var time = Math.floor((Math.random() * 3000) + 1);
    setTimeout(() => done(this), time);
  }
});

var NameRule = Rule.extend({
  association: "name",
  params: ['name'],
  onValidate: function(done) {
    if (this.name === "Aaron") {
      this.__invalidate("Name cannot be Aaron");
    }
    var time = Math.floor((Math.random() * 3000) + 1);
    setTimeout(() => done(this), time);
  }
});

var FieldRequiredRule = Rule.extend({
  params: ['field', 'data'],
  onValidate: function(done) {
    if (!this.data[this.field]) {
      this.association = this.field;
      this.__invalidate(this.field + " is required");
    }
    var time = Math.floor((Math.random() * 3000) + 1);
    setTimeout(() => done(this), time);
  }
});

var PersonService = BusinessService.extend().service;

function getRulesForInsert(person, context, done) {

  //done([
      //new AgeRule(person.age),
      //new NameRule(person.name),
      //new FieldRequiredRule("address", person)
  //]);

  done([new AgeRule(person.age)
                .ifValidThenExecute(() => console.log("Age succeeded"))
                .ifInvalidThenExecute(() => console.log("Age failed"))
                .ifValidThenValidate(new NameRule(person.name)
                                          .ifValidThenExecute(() => console.log("Name succeeeded"))
                                          .ifInvalidThenExecute(() => console.log("Name failed"))
                                          .ifValidThenValidate(new FieldRequiredRule("address", person)
                                                                    .ifValidThenExecute(() => console.log("Address succeeeded"))
                                                                    .ifInvalidThenExecute(() => console.log("Address failed"))
                                                              ))]);
}

var PersonDataProxy = function() { }

PersonDataProxy.prototype = {
  constructor: PersonDataProxy,
  insert: function(data, done) {
    data.id = 5;
    done(data);
  }
};

var service = new PersonService(new PersonDataProxy());

[
  service.insertCommand({name: "Aaron", age: new Date('2/3/1975')}),
  service.insertCommand({name: "Aarons", age: new Date('2/3/1975'), address: 'aa'}),
  service.insertCommand({name: "Aaron", age: new Date('2/3/1925'), address: 'aa'}),
  service.insertCommand({name: "Aarons", age: new Date('2/3/1925')}),
  service.insertCommand({name: "aAaron", age: new Date('2/3/1925'), address: 'aaa'})
]
.forEach(function(command) {
  command.execute((result) => {
    console.log('---------------');
    console.log(result);
  });
});

module.exports = service;
<commit_msg>change service creation args<commit_after>"use strict";

var Rule = require('./peasy').Rule;
var BusinessService = require('./peasy').BusinessService;
var Command = require('./peasy').Command;

var AgeRule = Rule.extend({
  association: "age",
  params: ['birthdate'],
  onValidate: function(done) {
    if (new Date().getFullYear() - this.birthdate.getFullYear() < 50) {
      this.__invalidate("You are too young");
    }
    var time = Math.floor((Math.random() * 3000) + 1);
    setTimeout(() => done(this), time);
  }
});

var NameRule = Rule.extend({
  association: "name",
  params: ['name'],
  onValidate: function(done) {
    if (this.name === "Aaron") {
      this.__invalidate("Name cannot be Aaron");
    }
    var time = Math.floor((Math.random() * 3000) + 1);
    setTimeout(() => done(this), time);
  }
});

var FieldRequiredRule = Rule.extend({
  params: ['field', 'data'],
  onValidate: function(done) {
    if (!this.data[this.field]) {
      this.association = this.field;
      this.__invalidate(this.field + " is required");
    }
    var time = Math.floor((Math.random() * 3000) + 1);
    setTimeout(() => done(this), time);
  }
});

var PersonService = BusinessService.extend({
  functions: [{
    '__getRulesForInsert': getRulesForInsert
  }]
}).service;

function getRulesForInsert(person, context, done) {

  //done([
      //new AgeRule(person.age),
      //new NameRule(person.name),
      //new FieldRequiredRule("address", person)
  //]);

  done([new AgeRule(person.age)
                .ifValidThenExecute(() => console.log("Age succeeded"))
                .ifInvalidThenExecute(() => console.log("Age failed"))
                .ifValidThenValidate(new NameRule(person.name)
                                          .ifValidThenExecute(() => console.log("Name succeeeded"))
                                          .ifInvalidThenExecute(() => console.log("Name failed"))
                                          .ifValidThenValidate(new FieldRequiredRule("address", person)
                                                                    .ifValidThenExecute(() => console.log("Address succeeeded"))
                                                                    .ifInvalidThenExecute(() => console.log("Address failed"))
                                                              ))]);
}

var PersonDataProxy = function() { }

PersonDataProxy.prototype = {
  constructor: PersonDataProxy,
  insert: function(data, done) {
    data.id = 5;
    done(data);
  }
};

var service = new PersonService(new PersonDataProxy());

[
  service.insertCommand({name: "Aaron", age: new Date('2/3/1975')}),
  service.insertCommand({name: "Aarons", age: new Date('2/3/1975'), address: 'aa'}),
  service.insertCommand({name: "Aaron", age: new Date('2/3/1925'), address: 'aa'}),
  service.insertCommand({name: "Aarons", age: new Date('2/3/1925')}),
  service.insertCommand({name: "aAaron", age: new Date('2/3/1925'), address: 'aaa'})
]
.forEach(function(command) {
  command.execute((result) => {
    console.log('---------------');
    console.log(result);
  });
});

module.exports = service;
<|endoftext|>


<commit_before>// keywords: js, javascript, function prototype bind

/**
 * Creates a new function that, when called, has its `this` keyword set to the
 * provided value, with a given sequence of arguments preceding any provided
 * when the new function is called. See Mozilla Developer Network:
 * Function.prototype.bind
 *
 * In PhantomJS, their is a bug with `Function.prototype.bind`. You can
 * reproduce this bug by testing this code:
 *
 *     function a(str) { console.log(this, str); }
 *     var b = a.bind({"a": "b"}, "test");
 *     b();
 *
 * @param {Function} fun The function to bind
 *
 * @param {Object} thisArg The value to be passed as the `this` parameter to
 *   the target function when the bound function is called. The value is
 *   ignored if the bound function is constructed using the `new` operator.
 *
 * @param {Any} [arg]* Arguments to prepend to arguments provided to the
 *   bound function when invoking the target function.
 *
 * @return {Function} The bound function.
 */
function bind(fun, thisArg) {
  var args = [].slice.call(arguments, 2);
  return function () {
    args.push.apply(args, arguments);
    return fun.apply(thisArg, args);
  };
}
// or
Function.prototype.bind = function (thisArg) {
  var fun = this, args = [].slice.call(arguments, 1);
  return function () {
    args.push.apply(args, arguments);
    return fun.apply(thisArg, args);
  };
};

//////////////////////////////////////////////////////////////////////
// Tests

if (!module.parent) {
  (function () {
    var _1 = {}, _2 = {}, o = {
      "m": function (a, b) {
        this.a = a;
        this.b = b;
      }
    };
    o.m.bind(_1, 1)(2);
    bind(o.m, _2, 1)(2);
    console.log("fun.bind(..) === bind(fun, ...)");
    console.log('   ', JSON.stringify(_1) === JSON.stringify(_2));
    console.log("check fun owner");
    console.log('   ', JSON.stringify(o) === "{}");
  }());
}
<commit_msg>bind.js +1<commit_after>/*jslint indent: 2, sloppy: true */

// keywords: js, javascript, function prototype bind

/**
 * Creates a new function that, when called, has its `this` keyword set to the
 * provided value, with a given sequence of arguments preceding any provided
 * when the new function is called. See Mozilla Developer Network:
 * Function.prototype.bind
 *
 * In PhantomJS, their is a bug with `Function.prototype.bind`. You can
 * reproduce this bug by testing this code:
 *
 *     function a(str) { console.log(this, str); }
 *     var b = a.bind({"a": "b"}, "test");
 *     b();
 *
 * @param {Function} fun The function to bind
 *
 * @param {Object} thisArg The value to be passed as the `this` parameter to
 *   the target function when the bound function is called. The value is
 *   ignored if the bound function is constructed using the `new` operator.
 *
 * @param {Any} [arg]* Arguments to prepend to arguments provided to the
 *   bound function when invoking the target function.
 *
 * @return {Function} The bound function.
 */
function bind(fun, thisArg) {
  var args = [].slice.call(arguments, 2);
  return function () {
    args.push.apply(args, arguments);
    return fun.apply(thisArg, args);
  };
}

//////////////////////////////////////////////////////////////////////
// is equal to above, if Function.prototype.bind exists

// var bind = Function.prototype.call.bind(Function.prototype.bind);

//////////////////////////////////////////////////////////////////////
// other, if Function.prototype.bind doesn't exist

// Function.prototype.bind = function (thisArg) {
//   var fun = this, args = [].slice.call(arguments, 1);
//   return function () {
//     args.push.apply(args, arguments);
//     return fun.apply(thisArg, args);
//   };
// };

//////////////////////////////////////////////////////////////////////
// Tests

if (!module.parent) {
  (function () {
    var _1 = {}, _2 = {}, o = {
      "m": function (a, b) {
        this.a = a;
        this.b = b;
      }
    };
    o.m.bind(_1, 1)(2);
    bind(o.m, _2, 1)(2);
    console.log("fun.bind(..) === bind(fun, ...)");
    console.log('   ', JSON.stringify(_1) === JSON.stringify(_2));
    console.log("check fun owner");
    console.log('   ', JSON.stringify(o) === "{}");
  }());
}
<|endoftext|>


<commit_before>animate = function() {
	var canvas = document.getElementById('myCanvas');
	var context = canvas.getContext('2d');

	// update
	y += dir;
	if (y > 600 - imgLogo.height || y < 0) {
		dir *= -1;
	}
	// clear
	// context.clearRect(0, 0, canvas.width, canvas.height);

	// draw stuff
	context.drawImage(imgBackground, 0, 0);
	context.drawImage(imgMiddleground, 0, 0);
	context.drawImage(imgLogo, 0, y);
	// request new frame
	requestAnimFrame(function() {
		animate();
	});
}
window.requestAnimFrame = (function(callback) {
	return window.requestAnimationFrame || window.webkitRequestAnimationFrame
			|| window.mozRequestAnimationFrame || window.oRequestAnimationFrame
			|| window.msRequestAnimationFrame || function(callback) {
				window.setTimeout(callback, 1000 / 60);
			};
})();
var y = 0;
var dir = 1;
var imgLogo = new Image();
imgLogo.src = 'gfx/menu/logo.png';
var imgMiddleground = new Image();
imgMiddleground.src = "gfx/menu/menu_middleground.png";
var imgBackground = new Image();
imgBackground.src = "gfx/menu/menu_background.png";
var music = new Audio("sounds/music/Chiptune_2step_mp3.mp3");

main = function() {
	animate();
	music.loop = true;
	music.volume = .25;
	music.load();
}
<commit_msg>added very rudimentary mouse position tracking<commit_after>animate = function() {
	var canvas = document.getElementById('myCanvas');
	var context = canvas.getContext('2d');

	// update
	y += dir;
	if (y > 600 - imgLogo.height || y < 0) {
		dir *= -1;
	}
	// clear
	// context.clearRect(0, 0, canvas.width, canvas.height);

	// draw stuff
	context.drawImage(imgBackground, 0, 0);
	context.drawImage(imgMiddleground, 0, 0);
	context.drawImage(imgLogo, 0, y);
	context.font = '18pt Calibri';
	context.fillStyle = 'white';
	context.fillText(mouseX + ", " + mouseY, 10, 25);
	// request new frame
	requestAnimFrame(function() {
		animate();
	});
}
window.requestAnimFrame = (function(callback) {
	return window.requestAnimationFrame || window.webkitRequestAnimationFrame
			|| window.mozRequestAnimationFrame || window.oRequestAnimationFrame
			|| window.msRequestAnimationFrame || function(callback) {
				window.setTimeout(callback, 1000 / 60);
			};
})();
function writeMessage(canvas, message) {
	var context = canvas.getContext('2d');
	// context.clearRect(0, 0, canvas.width, canvas.height);
	context.font = '18pt Calibri';
	context.fillStyle = 'white';
	context.fillText(message, 10, 25);
}
function getMousePos(canvas, evt) {
	var rect = canvas.getBoundingClientRect();
	return {
		x : evt.clientX - rect.left,
		y : evt.clientY - rect.top
	};
}

var y = 0;
var dir = 1;
var mouseX = 0;
var mouseY = 0;
var imgLogo = new Image();
imgLogo.src = 'gfx/menu/logo.png';
var imgMiddleground = new Image();
imgMiddleground.src = "gfx/menu/menu_middleground.png";
var imgBackground = new Image();
imgBackground.src = "gfx/menu/menu_background.png";
var music = new Audio("sounds/music/Chiptune_2step_mp3.mp3");

main = function() {
	animate();
	var canvas = document.getElementById('myCanvas');
	var context = canvas.getContext('2d');
	canvas.addEventListener('mousemove', function(evt) {
		//update global mouse position. TODO: globals are bad
		var mousePos = getMousePos(canvas, evt);
		mouseX = mousePos.x;
		mouseY = mousePos.y;
	}, false);

	music.loop = true;
	music.volume = .25;
	music.load();
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import CoreTranslations from '../public/javascripts/translations/en.json'
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import {filterUselessConsoleMessages} from '@instructure/js-utils'
import rceFormatMessage from '@instructure/canvas-rce/lib/format-message'
import plannerFormatMessage from '@instructure/canvas-planner/lib/format-message'
import {up as configureDateTime} from '../ui/boot/initializers/configureDateTime'
import {up as configureDateTimeMomentParser} from '../ui/boot/initializers/configureDateTimeMomentParser'
import {useTranslations} from '@canvas/i18n'

useTranslations('en', CoreTranslations)

rceFormatMessage.setup({
  locale: 'en',
  missingTranslation: 'ignore',
})

plannerFormatMessage.setup({
  locale: 'en',
  missingTranslation: 'ignore',
})

/**
 * We want to ensure errors and warnings get appropriate eyes. If
 * you are seeing an exception from here, it probably means you
 * have an unintended consequence from your changes. If you expect
 * the warning/error, add it to the ignore list below.
 */
/* eslint-disable no-console */
const globalError = global.console.error
const ignoredErrors = [
  /\[object Object\]/,
  /%s has a method called shouldComponentUpdate/,
  /`NaN` is an invalid value for the `%s` css style property/,
  /<Provider> does not support changing `store` on the fly/,
  /A component is changing a controlled input of type %s to be uncontrolled/,
  /A theme registry has already been initialized/,
  /An update to (%s|DefaultToolForm) inside a test was not wrapped in act/,
  /Can't perform a React state update on an unmounted component/,
  /Cannot read property '(activeElement|useRealTimers)' of undefined/,
  /Cannot read property 'name' of null/,
  /Cannot update during an existing state transition/,
  /ColorPicker: isMounted is deprecated/,
  /contextType was defined as an instance property on %s/,
  /Error writing result to store for query/,
  /Expected one of Group, Option in Select but found 'option'/,
  /Expected one of ListItem in List but found 'ProfileTab/,
  /Failed loading the language file for/,
  /Function components cannot be given refs/,
  /Functions are not valid as a React child/,
  /invalid messageType: (notSupported|undefined)/,
  /Invalid prop `children` supplied to `(Option|View)`/,
  /Invalid prop `editorOptions.plugins` of type `string` supplied to `(ForwardRef|RCEWrapper)`/, // https://instructure.atlassian.net/browse/MAT-453
  /Invalid prop `editorOptions.toolbar\[0\]` of type `string` supplied to `(ForwardRef|RCEWrapper)`/, // https://instructure.atlassian.net/browse/MAT-453
  /Invalid prop `heading` of type `object` supplied to `Billboard`/, // https://instructure.atlassian.net/browse/QUIZ-8870
  /Invalid prop `returnFocusTo` of type `DeprecatedComponent` supplied to `HomePagePromptContainer`/,
  /Invalid prop `selectedDate` of type `date` supplied to `CanvasDateInput`/,
  /Invariant Violation/,
  /It looks like you're using the wrong act/,
  /Prop `children` should be supplied unless/,
  /React does not recognize the `%s` prop on a DOM element/,
  /Render methods should be a pure function of props and state/,
  /The 'screenReaderOnly' prop must be used in conjunction with 'liveRegion'/,
  /The above error occurred in the <.*> component/,
  /The prop `currentUserRoles` is marked as required in `ObserverOptions`/,
  /The prop `focusOnInit` is marked as required in `(FileUpload|TextEntry|UrlEntry)`/,
  /The prop `groupTitle` is marked as required in `SearchBreadcrumb`/,
  /The prop `id` is marked as required in `(ColHeader|DashboardCard|FormField|Option)`/,
  /The prop `label` is marked as required in `(FormField|FormFieldLayout|Modal)`/,
  /The prop `renderLabel` is marked as required in `(NumberInput|Select)`/,
  /Unexpected keys "searchPermissions", "filterRoles", "tabChanged", "setAndOpenAddTray" found in preloadedState argument passed to createStore/,
  /validateDOMNesting\(...\): %s cannot appear as a child of <%s>/,
  /WARNING: heuristic fragment matching going on!/,
  /Warning: Failed prop type: Expected one of Checkbox in CheckboxGroup but found `View`/,
  /You are using the simple \(heuristic\) fragment matcher, but your queries contain union or interface types./,
  /You seem to have overlapping act\(\) calls/,
]
const globalWarn = global.console.warn
const ignoredWarnings = [
  /\[View|Button|Text\] .* in version 8.0.0/i,
  /Error getting \/media_objects\/dummy_media_id\/info/,
  /Exactly one focusable child is required/,
  /Please update the following components: %s/,
  /shared_brand_configs.* not called/,
  /value provided is not in a recognized RFC2822 or ISO format/,
]
global.console = {
  log: console.log,
  error: error => {
    if (ignoredErrors.some(regex => regex.test(error))) {
      return
    }
    globalError(error)
    throw new Error(
      `Looks like you have an unhandled error. Keep our test logs clean by handling or filtering it. ${error}`
    )
  },
  warn: warning => {
    if (ignoredWarnings.some(regex => regex.test(warning))) {
      return
    }
    globalWarn(warning)
    throw new Error(
      `Looks like you have an unhandled warning. Keep our test logs clean by handling or filtering it. ${warning}`
    )
  },
  info: console.info,
  debug: console.debug,
}
/* eslint-enable no-console */
filterUselessConsoleMessages(global.console)

require('jest-fetch-mock').enableFetchMocks()

window.scroll = () => {}
window.ENV = {
  use_rce_enhancements: true,
  FEATURES: {
    extended_submission_state: true,
  },
}

Enzyme.configure({adapter: new Adapter()})

// because InstUI themeable components need an explicit "dir" attribute on the <html> element
document.documentElement.setAttribute('dir', 'ltr')

configureDateTime()
configureDateTimeMomentParser()

// because everyone implements `flat()` and `flatMap()` except JSDOM 🤦🏼♂
if (!Array.prototype.flat) {
  // eslint-disable-next-line no-extend-native
  Object.defineProperty(Array.prototype, 'flat', {
    configurable: true,
    value: function flat(depth = 1) {
      if (depth === 0) return this.slice()
      return this.reduce(function (acc, cur) {
        if (Array.isArray(cur)) {
          acc.push(...flat.call(cur, depth - 1))
        } else {
          acc.push(cur)
        }
        return acc
      }, [])
    },
    writable: true,
  })
}

if (!Array.prototype.flatMap) {
  // eslint-disable-next-line no-extend-native
  Object.defineProperty(Array.prototype, 'flatMap', {
    configurable: true,
    value: function flatMap(_cb) {
      return Array.prototype.map.apply(this, arguments).flat()
    },
    writable: true,
  })
}

require('@instructure/ui-themes')

// set up mocks for native APIs
if (!('MutationObserver' in window)) {
  Object.defineProperty(window, 'MutationObserver', {
    value: require('@sheerun/mutationobserver-shim'),
  })
}

if (!('IntersectionObserver' in window)) {
  Object.defineProperty(window, 'IntersectionObserver', {
    writable: true,
    configurable: true,
    value: class IntersectionObserver {
      disconnect() {
        return null
      }

      observe() {
        return null
      }

      takeRecords() {
        return null
      }

      unobserve() {
        return null
      }
    },
  })
}

if (!('ResizeObserver' in window)) {
  Object.defineProperty(window, 'ResizeObserver', {
    writable: true,
    configurable: true,
    value: class IntersectionObserver {
      observe() {
        return null
      }

      unobserve() {
        return null
      }
    },
  })
}

if (!('matchMedia' in window)) {
  window.matchMedia = () => ({
    matches: false,
    addListener: () => {},
    removeListener: () => {},
  })
  window.matchMedia._mocked = true
}

if (!('scrollIntoView' in window.HTMLElement.prototype)) {
  window.HTMLElement.prototype.scrollIntoView = () => {}
}

// Suppress errors for APIs that exist in JSDOM but aren't implemented
Object.defineProperty(window, 'scrollTo', {configurable: true, writable: true, value: () => {}})

const locationProperties = Object.getOwnPropertyDescriptors(window.location)
Object.defineProperty(window, 'location', {
  configurable: true,
  enumerable: true,
  get: () =>
    Object.defineProperties(
      {},
      {
        ...locationProperties,
        href: {
          ...locationProperties.href,
          // Prevents JSDOM errors from doing window.location.href = ...
          set: () => {},
        },
        reload: {
          configurable: true,
          enumerable: true,
          writeable: true,
          // Prevents JSDOM errors from doing window.location.reload()
          value: () => {},
        },
      }
    ),
  // Prevents JSDOM errors from doing window.location = ...
  set: () => {},
})
<commit_msg>remove unnecessary function as children warning supression<commit_after>/*
 * Copyright (C) 2018 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import CoreTranslations from '../public/javascripts/translations/en.json'
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import {filterUselessConsoleMessages} from '@instructure/js-utils'
import rceFormatMessage from '@instructure/canvas-rce/lib/format-message'
import plannerFormatMessage from '@instructure/canvas-planner/lib/format-message'
import {up as configureDateTime} from '../ui/boot/initializers/configureDateTime'
import {up as configureDateTimeMomentParser} from '../ui/boot/initializers/configureDateTimeMomentParser'
import {useTranslations} from '@canvas/i18n'

useTranslations('en', CoreTranslations)

rceFormatMessage.setup({
  locale: 'en',
  missingTranslation: 'ignore',
})

plannerFormatMessage.setup({
  locale: 'en',
  missingTranslation: 'ignore',
})

/**
 * We want to ensure errors and warnings get appropriate eyes. If
 * you are seeing an exception from here, it probably means you
 * have an unintended consequence from your changes. If you expect
 * the warning/error, add it to the ignore list below.
 */
/* eslint-disable no-console */
const globalError = global.console.error
const ignoredErrors = [
  /\[object Object\]/,
  /%s has a method called shouldComponentUpdate/,
  /`NaN` is an invalid value for the `%s` css style property/,
  /<Provider> does not support changing `store` on the fly/,
  /A component is changing a controlled input of type %s to be uncontrolled/,
  /A theme registry has already been initialized/,
  /An update to (%s|DefaultToolForm) inside a test was not wrapped in act/,
  /Can't perform a React state update on an unmounted component/,
  /Cannot read property '(activeElement|useRealTimers)' of undefined/,
  /Cannot read property 'name' of null/,
  /Cannot update during an existing state transition/,
  /ColorPicker: isMounted is deprecated/,
  /contextType was defined as an instance property on %s/,
  /Error writing result to store for query/,
  /Expected one of Group, Option in Select but found 'option'/,
  /Expected one of ListItem in List but found 'ProfileTab/,
  /Failed loading the language file for/,
  /Function components cannot be given refs/,
  /invalid messageType: (notSupported|undefined)/,
  /Invalid prop `children` supplied to `(Option|View)`/,
  /Invalid prop `editorOptions.plugins` of type `string` supplied to `(ForwardRef|RCEWrapper)`/, // https://instructure.atlassian.net/browse/MAT-453
  /Invalid prop `editorOptions.toolbar\[0\]` of type `string` supplied to `(ForwardRef|RCEWrapper)`/, // https://instructure.atlassian.net/browse/MAT-453
  /Invalid prop `heading` of type `object` supplied to `Billboard`/, // https://instructure.atlassian.net/browse/QUIZ-8870
  /Invalid prop `returnFocusTo` of type `DeprecatedComponent` supplied to `HomePagePromptContainer`/,
  /Invalid prop `selectedDate` of type `date` supplied to `CanvasDateInput`/,
  /Invariant Violation/,
  /It looks like you're using the wrong act/,
  /Prop `children` should be supplied unless/,
  /React does not recognize the `%s` prop on a DOM element/,
  /Render methods should be a pure function of props and state/,
  /The 'screenReaderOnly' prop must be used in conjunction with 'liveRegion'/,
  /The above error occurred in the <.*> component/,
  /The prop `currentUserRoles` is marked as required in `ObserverOptions`/,
  /The prop `focusOnInit` is marked as required in `(FileUpload|TextEntry|UrlEntry)`/,
  /The prop `groupTitle` is marked as required in `SearchBreadcrumb`/,
  /The prop `id` is marked as required in `(ColHeader|DashboardCard|FormField|Option)`/,
  /The prop `label` is marked as required in `(FormField|FormFieldLayout|Modal)`/,
  /The prop `renderLabel` is marked as required in `(NumberInput|Select)`/,
  /Unexpected keys "searchPermissions", "filterRoles", "tabChanged", "setAndOpenAddTray" found in preloadedState argument passed to createStore/,
  /validateDOMNesting\(...\): %s cannot appear as a child of <%s>/,
  /WARNING: heuristic fragment matching going on!/,
  /Warning: Failed prop type: Expected one of Checkbox in CheckboxGroup but found `View`/,
  /You are using the simple \(heuristic\) fragment matcher, but your queries contain union or interface types./,
  /You seem to have overlapping act\(\) calls/,
]
const globalWarn = global.console.warn
const ignoredWarnings = [
  /\[View|Button|Text\] .* in version 8.0.0/i,
  /Error getting \/media_objects\/dummy_media_id\/info/,
  /Exactly one focusable child is required/,
  /Please update the following components: %s/,
  /shared_brand_configs.* not called/,
  /value provided is not in a recognized RFC2822 or ISO format/,
]
global.console = {
  log: console.log,
  error: error => {
    if (ignoredErrors.some(regex => regex.test(error))) {
      return
    }
    globalError(error)
    throw new Error(
      `Looks like you have an unhandled error. Keep our test logs clean by handling or filtering it. ${error}`
    )
  },
  warn: warning => {
    if (ignoredWarnings.some(regex => regex.test(warning))) {
      return
    }
    globalWarn(warning)
    throw new Error(
      `Looks like you have an unhandled warning. Keep our test logs clean by handling or filtering it. ${warning}`
    )
  },
  info: console.info,
  debug: console.debug,
}
/* eslint-enable no-console */
filterUselessConsoleMessages(global.console)

require('jest-fetch-mock').enableFetchMocks()

window.scroll = () => {}
window.ENV = {
  use_rce_enhancements: true,
  FEATURES: {
    extended_submission_state: true,
  },
}

Enzyme.configure({adapter: new Adapter()})

// because InstUI themeable components need an explicit "dir" attribute on the <html> element
document.documentElement.setAttribute('dir', 'ltr')

configureDateTime()
configureDateTimeMomentParser()

// because everyone implements `flat()` and `flatMap()` except JSDOM 🤦🏼♂
if (!Array.prototype.flat) {
  // eslint-disable-next-line no-extend-native
  Object.defineProperty(Array.prototype, 'flat', {
    configurable: true,
    value: function flat(depth = 1) {
      if (depth === 0) return this.slice()
      return this.reduce(function (acc, cur) {
        if (Array.isArray(cur)) {
          acc.push(...flat.call(cur, depth - 1))
        } else {
          acc.push(cur)
        }
        return acc
      }, [])
    },
    writable: true,
  })
}

if (!Array.prototype.flatMap) {
  // eslint-disable-next-line no-extend-native
  Object.defineProperty(Array.prototype, 'flatMap', {
    configurable: true,
    value: function flatMap(_cb) {
      return Array.prototype.map.apply(this, arguments).flat()
    },
    writable: true,
  })
}

require('@instructure/ui-themes')

// set up mocks for native APIs
if (!('MutationObserver' in window)) {
  Object.defineProperty(window, 'MutationObserver', {
    value: require('@sheerun/mutationobserver-shim'),
  })
}

if (!('IntersectionObserver' in window)) {
  Object.defineProperty(window, 'IntersectionObserver', {
    writable: true,
    configurable: true,
    value: class IntersectionObserver {
      disconnect() {
        return null
      }

      observe() {
        return null
      }

      takeRecords() {
        return null
      }

      unobserve() {
        return null
      }
    },
  })
}

if (!('ResizeObserver' in window)) {
  Object.defineProperty(window, 'ResizeObserver', {
    writable: true,
    configurable: true,
    value: class IntersectionObserver {
      observe() {
        return null
      }

      unobserve() {
        return null
      }
    },
  })
}

if (!('matchMedia' in window)) {
  window.matchMedia = () => ({
    matches: false,
    addListener: () => {},
    removeListener: () => {},
  })
  window.matchMedia._mocked = true
}

if (!('scrollIntoView' in window.HTMLElement.prototype)) {
  window.HTMLElement.prototype.scrollIntoView = () => {}
}

// Suppress errors for APIs that exist in JSDOM but aren't implemented
Object.defineProperty(window, 'scrollTo', {configurable: true, writable: true, value: () => {}})

const locationProperties = Object.getOwnPropertyDescriptors(window.location)
Object.defineProperty(window, 'location', {
  configurable: true,
  enumerable: true,
  get: () =>
    Object.defineProperties(
      {},
      {
        ...locationProperties,
        href: {
          ...locationProperties.href,
          // Prevents JSDOM errors from doing window.location.href = ...
          set: () => {},
        },
        reload: {
          configurable: true,
          enumerable: true,
          writeable: true,
          // Prevents JSDOM errors from doing window.location.reload()
          value: () => {},
        },
      }
    ),
  // Prevents JSDOM errors from doing window.location = ...
  set: () => {},
})
<|endoftext|>


<commit_before>var _ = require("underscore");
var path = require("path");

var helper_utils = require("punch").Utils.Helper;
var blog_content_handler = require("punch-blog-content-handler");

var homepage_posts = 10;
var teaser_length = 2;
var recent_posts = [];
var last_modified = null;

var fetch_content = function(callback) {
	recent_posts = [];

	//reset posts list
	blog_content_handler.allPosts = {};

	blog_content_handler.getAllPosts(function(err, posts_obj, posts_last_modified) {
		if (!err) {
			var all_posts = _.values(posts_obj).reverse();
			last_modified = posts_last_modified;

			var recent_posts_list = all_posts.slice(all_posts.length - homepage_posts);

			var fetch_full_posts = function() {
				if (recent_posts_list.length) {
					blog_content_handler.getPost(path.join(recent_posts_list.shift().permalink, "index"), function(err, post_contents, modified_date) {
						var post_paras = post_contents.content.replace(/\n/g, "").match(/(<p[^>]*>.*?<\/p>)/g);

						if (teaser_length < 1) {
							paras_to_show = post_paras.length;
							post_contents.is_teaser = false;
						} else {
							paras_to_show = teaser_length;
							post_contents.is_teaser = true;
						}

						post_contents.content = post_paras.slice(0, paras_to_show).join("");

						if (!err) {
							recent_posts.push(post_contents);
						}

						return fetch_full_posts()

					});
				} else {
					return callback();
				}
			}

			return fetch_full_posts();

		} else {
			console.log(err);
			return callback();
		}
	});
}

var tag_helpers = {

	recent_posts: function() {
		return recent_posts;
	}

};

module.exports = {

	setup: function(config) {
		if (config.blog) {
			teaser_length = config.blog.teaser_length;
			homepage_posts = config.blog.homepage_posts;
		}
	},

	directAccess: function(){
		return { "block_helpers": {}, "tag_helpers": {}, "options": {} };
	},

	get: function(basepath, file_extension, options, callback){
		var self = this;

		if (basepath !== "/index") {
			return callback(null, {}, {}, null);
		}

		fetch_content(function() {
			return callback(null, { "tag": tag_helpers }, {}, last_modified);
		});
	}

}
<commit_msg>Don't squash words together<commit_after>var _ = require("underscore");
var path = require("path");

var helper_utils = require("punch").Utils.Helper;
var blog_content_handler = require("punch-blog-content-handler");

var homepage_posts = 10;
var teaser_length = 2;
var recent_posts = [];
var last_modified = null;

var fetch_content = function(callback) {
	recent_posts = [];

	//reset posts list
	blog_content_handler.allPosts = {};

	blog_content_handler.getAllPosts(function(err, posts_obj, posts_last_modified) {
		if (!err) {
			var all_posts = _.values(posts_obj).reverse();
			last_modified = posts_last_modified;

			var recent_posts_list = all_posts.slice(all_posts.length - homepage_posts);

			var fetch_full_posts = function() {
				if (recent_posts_list.length) {
					blog_content_handler.getPost(path.join(recent_posts_list.shift().permalink, "index"), function(err, post_contents, modified_date) {
						var post_paras = post_contents.content.replace(/\n/g, " ").match(/(<p[^>]*>.*?<\/p>)/g);

						if (teaser_length < 1) {
							paras_to_show = post_paras.length;
							post_contents.is_teaser = false;
						} else {
							paras_to_show = teaser_length;
							post_contents.is_teaser = true;
						}

						post_contents.content = post_paras.slice(0, paras_to_show).join("");

						if (!err) {
							recent_posts.push(post_contents);
						}

						return fetch_full_posts()

					});
				} else {
					return callback();
				}
			}

			return fetch_full_posts();

		} else {
			console.log(err);
			return callback();
		}
	});
}

var tag_helpers = {

	recent_posts: function() {
		return recent_posts;
	}

};

module.exports = {

	setup: function(config) {
		if (config.blog) {
			teaser_length = config.blog.teaser_length;
			homepage_posts = config.blog.homepage_posts;
		}
	},

	directAccess: function(){
		return { "block_helpers": {}, "tag_helpers": {}, "options": {} };
	},

	get: function(basepath, file_extension, options, callback){
		var self = this;

		if (basepath !== "/index") {
			return callback(null, {}, {}, null);
		}

		fetch_content(function() {
			return callback(null, { "tag": tag_helpers }, {}, last_modified);
		});
	}

}
<|endoftext|>


<commit_before>'use strict';

module.exports = function(dust) {

 /*
  * @description Detect whether the upgrade type is car parking for conditional rendering in confirmation template
  * @param upgradeName is the name of the upgrade type which is used to check if it is car parking
  * @example {@_isCarParking upgradeName=content.name /} returns true if Car Parking otherwise false
  */

  dust.helpers._isCarParking = function(chunk, context, bodies, params) {
    // strip the whitespace and lowercase content.name just to be safe and return true or false appropriately
    if (typeof params !== 'undefined' && params.upgradeName) {
      return (params.upgradeName.toLowerCase().replace(/ /g, '') === 'carparking');
    }
    return false;
  };

};
<commit_msg>Use index of instead of string compare<commit_after>'use strict';

module.exports = function(dust) {

 /*
  * @description Detect whether the upgrade type is car parking for conditional rendering in confirmation template
  * @param upgradeName is the name of the upgrade type which is used to check if it is car parking
  * @example {@_isCarParking upgradeName=content.name /} returns true if Car Parking otherwise false
  */

  dust.helpers._isCarParking = function(chunk, context, bodies, params) {
    // strip the whitespace and lowercase content.name just to be safe and return true or false appropriately
    if (typeof params !== 'undefined' && params.upgradeName) {
      return (params.upgradeName.toLowerCase().replace(/ /g, '').indexOf('carparking')) !== -1 ? true : false;
    }
    return false;
  };

};
<|endoftext|>


<commit_before>var Promise = require('bluebird');
var request = Promise.promisifyAll(require('request'));
var cheerio = require('cheerio');
var db = require('../storage/db');
var utilities = require('./utilities');
var logger = require('./logger').FIDI.forModule(__filename);
var _ = require('lodash');

module.exports = function(emailSender) {
  if (!emailSender) {
    throw new Error('An email sender instance is required.');
  }

  function ItemService(item) {
    this.item = item;
    this.content = null;
  }

  ItemService.prototype.loadDataFromUrl = function() {
    logger.debug('Loading document from url: ' + this.item.url);
    return request.getAsync(this.item.url)
      .bind(this)
      .then(function(res) {
        this.content = res[1];
      })
      .catch(function(ex) {
        logger.debug('Could not load url. Details: ' + ex);
      });
  };

  ItemService.prototype.loadUsersFullInfo = function() {
    logger.debug('Loading users full info.');
    var ids = _.pluck(this.item.users, 'id');

    return db.users.getUsers(ids)
      .bind(this)
      .then(populateUsersDetails)
      .catch(function(ex) {
        logger.debug('Could not load users. Details: ' + ex);
      });

    function populateUsersDetails(users) {
      var _users = {};
      users.forEach(function(user) {
        _users[user.id] = user;
      });
      this.item.users.forEach(function(user) {
        user.email = _users[user.id].email;
      });
    }
  };

  ItemService.prototype.parseData = function() {
    if (!this.content) {
      throw new Error('The content is not available.');
    }
    if (!this.item.selector) {
      throw new Error('The selector is not available.');
    }
    var $ = cheerio.load(this.content);
    var contentOfPriceElement = $(this.item.selector).text();
    this.price = utilities.getPrice(contentOfPriceElement);

    this.item.snapshots.push({
      date: Date(),
      price: this.price
    });

    return this.item.saveAsync();
  };

  ItemService.prototype.sendEmails = function() {
    logger.debug('Sending emails to users.');

    var self = this,
      item = this.item,
      lastSnapshot = item.snapshots[item.snapshots.length - 1],
      usersToNotify = getUsersToNotify();

    usersToNotify.forEach(function(user) {
      emailSender.sendPriceNotification(
        user.email,
        self.item.url,
        self.price
      );
      saveUserLastSendDate(user);
    });

    function getUsersToNotify() {
      return _.filter(item.users, function(user) {
        return mustSendToUser(user, lastSnapshot);
      });
    }

    function mustSendToUser(user, lastSnapshot) {
      var isRightPrice = lastSnapshot.price <= user.maxPrice,
        isRightDate = false;

      if (!user.lastDate) {
        isRightDate = true;
      } else if (Date(user.lastSent) < Date(lastSnapshot.date)) {
        isRightDate = true;
      }

      return isRightPrice && isRightDate;
    }

    function saveUserLastSendDate(user) {
      user.lastSent = Date();
      self.item.saveAsync();
    }

    return usersToNotify;
  };

  return function(item, options) {
    var itemService = new ItemService(item);
    var returnPromise;

    //if content is not then load the content and users info in parallel
    if (!options || !options.content) {
      returnPromise = Promise.settle([
          itemService.loadDataFromUrl(),
          itemService.loadUsersFullInfo()
        ]);
    } else {
      itemService.content = options.content;
      returnPromise = itemService.loadUsersFullInfo().bind(itemService);
    }

    return returnPromise.bind(itemService)
      .then(itemService.parseData)
      .return(itemService);
  };
};
<commit_msg>add comments<commit_after>var Promise = require('bluebird');
var request = Promise.promisifyAll(require('request'));
var cheerio = require('cheerio');
var db = require('../storage/db');
var utilities = require('./utilities');
var logger = require('./logger').FIDI.forModule(__filename);
var _ = require('lodash');

/**
 * Decorator for mongoose ItemModel. Given an ItemModel object, this decorator
 * will perform certain async tasks detailed below.
 * @param  {object} emailSender an emailSender instance must be injected when
 *                              creating the decorator.
 * @return {Promise}            which gets resolve when all the async operations
 *                              are completed.
 */
module.exports = function(emailSender) {
  if (!emailSender) {
    throw new Error('An email sender instance is required.');
  }

  function ItemService(item) {
    this.item = item;
    this.content = null;
  }

  /**
   * Given an ItemModel, this method will fetch the content from the url in the
   * url property.
   * @return {Promise}
   */
  ItemService.prototype.loadDataFromUrl = function() {
    logger.debug('Loading document from url: ' + this.item.url);
    return request.getAsync(this.item.url)
      .bind(this)
      .then(function(res) {
        this.content = res[1];
      })
      .catch(function(ex) {
        logger.debug('Could not load url. Details: ' + ex);
      });
  };

  /**
   * Given an ItemModel, this method will fetch and populate all the user
   * details for users in the users property of the ItemModel object.
   * @return {[type]} [description]
   */
  ItemService.prototype.loadUsersFullInfo = function() {
    logger.debug('Loading users full info.');
    var ids = _.pluck(this.item.users, 'id');

    return db.users.getUsers(ids)
      .bind(this)
      .then(populateUsersDetails)
      .catch(function(ex) {
        logger.debug('Could not load users. Details: ' + ex);
      });

    function populateUsersDetails(users) {
      var _users = {};
      users.forEach(function(user) {
        _users[user.id] = user;
      });
      this.item.users.forEach(function(user) {
        user.email = _users[user.id].email;
      });
    }
  };

  /**
   * Given the HTML content of a page, this function will grab the text content
   * of the element matching the selector specified in ItemModel object's
   * selector property, will create a new snapshot of the item and will save the
   * item to the database.
   * @return {Promise}
   */
  ItemService.prototype.parseData = function() {
    if (!this.content) {
      throw new Error('The content is not available.');
    }
    if (!this.item.selector) {
      throw new Error('The selector is not available.');
    }
    var $ = cheerio.load(this.content);
    var contentOfPriceElement = $(this.item.selector).text();
    this.price = utilities.getPrice(contentOfPriceElement);

    this.item.snapshots.push({
      date: Date(),
      price: this.price
    });

    return this.item.saveAsync();
  };

  ItemService.prototype.sendEmails = function() {
    logger.debug('Sending emails to users.');

    var self = this,
      item = this.item,
      lastSnapshot = item.snapshots[item.snapshots.length - 1],
      usersToNotify = getUsersToNotify();

    usersToNotify.forEach(function(user) {
      emailSender.sendPriceNotification(
        user.email,
        self.item.url,
        self.price
      );
      saveUserLastSendDate(user);
    });

    function getUsersToNotify() {
      return _.filter(item.users, function(user) {
        return mustSendToUser(user, lastSnapshot);
      });
    }

    function mustSendToUser(user, lastSnapshot) {
      var isRightPrice = lastSnapshot.price <= user.maxPrice,
        isRightDate = false;

      if (!user.lastDate) {
        isRightDate = true;
      } else if (Date(user.lastSent) < Date(lastSnapshot.date)) {
        isRightDate = true;
      }

      return isRightPrice && isRightDate;
    }

    function saveUserLastSendDate(user) {
      user.lastSent = Date();
      self.item.saveAsync();
    }

    return usersToNotify;
  };

  return function(item, options) {
    var itemService = new ItemService(item);
    var returnPromise;

    //if content is not then load the content and users info in parallel
    if (!options || !options.content) {
      returnPromise = Promise.settle([
          itemService.loadDataFromUrl(),
          itemService.loadUsersFullInfo()
        ]);
    } else {
      itemService.content = options.content;
      returnPromise = itemService.loadUsersFullInfo().bind(itemService);
    }

    return returnPromise.bind(itemService)
      .then(itemService.parseData)
      .return(itemService);
  };
};
<|endoftext|>


<commit_before>// 2キー処理ではないキーの各処理の最後にmodifyCode=0を入れておくこと。
(function($) {
	$.fn.vixtarea = function(options){
       var options = jQuery.extend({
			size: '14px',
			color: 'black',
			backgroundColor: 'white',
			method: undefined
        }, options);

		var permitKeyCode = [186, 191, 65, 79, 68, 73, 88, 85, 82, 90, 72, 74, 75, 76, 89, 71, 82, 52, 54, 80];

		var MAXUNDO = 256 + 1;

		var mode = "view";
		var modifyCode = 0;
		var undobuffer = [this.val()];
		var undopoint = 0;
		var undotop = 0;
		var undonew = 0;
		var prevKey = 0;
		var yankbuffer = "";
		var horizontal = 0;

		this.css("font-size", options.size);
		this.css("line-height", options.size);
		this.css("font-family", "Osaka-Mono");
		this.css("color", options.color);
		this.css("background-color", options.backgroundColor);

		this.keyup(function(e) {
			if (prevKey == 17 && e.keyCode == 17) {
				prevKey = 0;
			} else if (prevKey == 17) {
				prevKey = 17;
			}
			//console.log("prevKey="+prevKey+", keyup:"+e.keyCode);
		});
		this.keydown(function(e) {
			var elm = e.target;
			//console.log("keydown="+e.keyCode);
			switch (mode) {
				case "view":
					permit = permitKeyCode.indexOf(e.keyCode);
					if (permit == -1) {
						e.preventDefault();
					}

					if (prevKey == 17 && (e.keyCode != 82)) {
						e.preventDefault();
						prevKey = 17;
					} else {
						prevKey = e.keyCode;
					}

					break;

				// 編集モード ##############################################################
				case "edit":
					if (e.keyCode === 9) { // TAB
						//console.log("tab");
						e.preventDefault();
						var val = elm.value;
						var pos = elm.selectionStart;
						elm.value = val.substr(0, pos) + '\t' + val.substr(pos, val.length);
						elm.setSelectionRange(pos + 1, pos + 1);
					}

					break;

				case "command":
					break;
			}
			if (e.keyCode == 27 && (mode == "edit" || mode == "command")) {
				modifyCode = 0;
				switch (mode) {
					case "edit":
						undopoint++;
						if (undopoint == MAXUNDO) {
							undopoint = 0;
						}
						undonew = undopoint;
						if (undopoint == undotop) {
							undotop++;
							if (undotop == MAXUNDO) {
								undotop = 0;
							}
						}
						undobuffer[undopoint] = elm.value;
						var val = elm.value;
						var pos = elm.selectionStart;
						ch = val.substr(pos, 1);
						code = ch.charCodeAt(0);
						if (code == 10) {
							pos--;
							elm.setSelectionRange(pos, pos);
						}
						break;
				}
				mode = "view";
			}
		});
		this.keypress(function(e) {
			//console.log("keypress="+e.keyCode);
			var elm = e.target;
			switch (mode) {
				case "view":
					e.preventDefault();
					var pos = elm.selectionStart;
					switch (e.keyCode) {
						// エディター操作 ##################################################

						case 104: // h
							elm.focus();
							var tl = getLineText(this);
							horizontal = tl.currLineText.length;
							var val = elm.value;
							var pos = elm.selectionStart;
							ch = val.substr(pos - 1, 1);
							code = ch.charCodeAt(0);
							if (code != 10) {
								elm.setSelectionRange(elm.value.length, pos - 1);
							}
							modifyCode = 0;
							break;

						case 106: // j
							var tl = getLineText(this);
							if (tl.nextLineText != undefined) {
								var pos = elm.selectionStart;
								var move = pos - tl.currLineText.length + tl.currLineTextAll.length + 1;
								if (horizontal < tl.nextLineText.length) {
									move += horizontal;
								} else {
									if (tl.nextLineText.length == 0) {
										move += tl.nextLineText.length;
									} else {
										move += tl.nextLineText.length - 1;
									}
								}
								elm.focus();
								elm.setSelectionRange(move, move);
							}
							modifyCode = 0;
							break;

						case 107: // k
							var tl = getLineText(this);
							if (tl.prevLineText != undefined) {
								var pos = elm.selectionStart;
								var move = pos - tl.currLineText.length - tl.prevLineText.length - 1;
								if (horizontal < tl.prevLineText.length) {
									move += horizontal;
								} else {
									if (tl.prevLineText.length == 0) {
										move += tl.prevLineText.length;
									} else {
										move += tl.prevLineText.length - 1;
									}
								}
								elm.focus();
								elm.setSelectionRange(move, move);
							}
							modifyCode = 0;
							break;

						case 108: // l
							elm.focus();
							var tl = getLineText(this);
							horizontal = tl.currLineText.length;
							var val = elm.value;
							var pos = elm.selectionStart;
							ch1 = val.substr(pos, 1);
							ch2 = val.substr(pos + 1, 1);
							code1 = ch1.charCodeAt(0);
							code2 = ch2.charCodeAt(0);
							if (code1 != 10 && code2 != 10) {
								elm.setSelectionRange(elm.value.length, pos + 1);
							}
							modifyCode = 0;
							break;

						case 58: // :
							mode = "command";
							modifyCode = 0;
							break;

						// 編集操作 #########################################################

						case 105: // i
							mode = "edit";
							modifyCode = 0;
							break;

						case 97: // a
							mode = "edit";
							var pos = elm.selectionStart;
							elm.setSelectionRange(pos+1, pos+1);
							modifyCode = 0;
							break;

						case 111: // o
							mode = "edit";
							var tl = getLineText(this);
							var pos = elm.selectionStart;
							var nl = pos - tl.currLineText.length + tl.currLineTextAll.length + 1;
							var val = elm.value;
							elm.value = val.substr(0, nl) + '\n' + val.substr(nl, val.length);
							elm.setSelectionRange(nl, nl);
							modifyCode = 0;
							break;

						case 79: // O
							mode = "edit";
							var tl = getLineText(this);
							var pos = elm.selectionStart;
							var nl = pos - tl.currLineText.length;
							var val = elm.value;
							elm.value = val.substr(0, nl) + '\n' + val.substr(nl, val.length);
							elm.setSelectionRange(nl, nl);
							modifyCode = 0;
							break;

						case 121: // y
							if (modifyCode == 121) {
								modifyCode = 0;
								var tl = getLineText(this);
								var val = elm.value;
								yankbuffer = val.substr(pos - tl.currLineText.length, tl.currLineTextAll.length + 1);
							} else {
								modifyCode = e.keyCode;
							}
							break;

						case 100: // dd
							if (modifyCode == 100) {
								modifyCode = 0;
								undopoint++;
								if (undopoint == MAXUNDO) {
									undopoint = 0;
								}
								undonew = undopoint;
								if (undopoint == undotop) {
									undotop++;
									if (undotop == MAXUNDO) {
										undotop = 0;
									}
								}
								var tl = getLineText(this);
								var pos = elm.selectionStart;
								var nl = pos - tl.currLineText.length;
								var nl2 = pos - tl.currLineText.length + tl.currLineTextAll.length + 1;
								var val = elm.value;
								yankbuffer = val.substr(pos - tl.currLineText.length, tl.currLineTextAll.length + 1);
								elm.value = val.substr(0, nl) + val.substr(nl2, val.length);
								elm.setSelectionRange(nl, nl);
								undobuffer[undopoint] = elm.value
							} else {
								modifyCode = e.keyCode;
							}
							break;

						case 112: // p
							e.preventDefault();
							undopoint++;
							if (undopoint == MAXUNDO) {
								undopoint = 0;
							}
							undonew = undopoint;
							if (undopoint == undotop) {
								undotop++;
								if (undotop == MAXUNDO) {
									undotop = 0;
								}
							}
							var tl = getLineText(this);
							var val = elm.value;
							var pos = elm.selectionStart;
							var nl = pos - tl.currLineText.length + tl.currLineTextAll.length + 1;
							elm.value = val.substr(0, nl) + yankbuffer + val.substr(nl, val.length);
							elm.setSelectionRange(nl, nl);
							undobuffer[undopoint] = elm.value
							modifyCode = 0;
							break;

						case 80: // P
							e.preventDefault();
							undopoint++;
							if (undopoint == MAXUNDO) {
								undopoint = 0;
							}
							undonew = undopoint;
							if (undopoint == undotop) {
								undotop++;
								if (undotop == MAXUNDO) {
									undotop = 0;
								}
							}
							var val = elm.value;
							var pos = elm.selectionStart;
							elm.value = val.substr(0, pos) + yankbuffer + val.substr(pos, val.length);
							elm.setSelectionRange(pos, pos);
							undobuffer[undopoint] = elm.value
							modifyCode = 0;
							break;

						case 120: // x
							undopoint++;
							if (undopoint == MAXUNDO) {
								undopoint = 0;
							}
							undonew = undopoint;
							if (undopoint == undotop) {
								undotop++;
								if (undotop == MAXUNDO) {
									undotop = 0;
								}
							}
							var val = elm.value;
							var pos = elm.selectionStart;
							elm.value = val.substr(0, pos) + val.substr(pos + 1, val.length);
							elm.setSelectionRange(pos, pos);
							undobuffer[undopoint] = elm.value;
							modifyCode = 0;
							break;

						case 103: // g
							if (modifyCode == 103) {
								modifyCode = 0;
								elm.setSelectionRange(0, 0);
							} else {
								modifyCode = 103;
							}
							break;

						case 71: // shift+g
							pos = elm.value.length;
							elm.setSelectionRange(pos, pos);
							modifyCode = 0;
							break;

						case 117: // u
							if (undopoint != undotop) {
								var pos = elm.selectionStart;
								if (--undopoint < 0) {
									undopoint = MAXUNDO - 1;
								}
								var str = undobuffer[undopoint];
								if (str != undefined) {
									elm.value = str;
									elm.setSelectionRange(pos, pos);
								} else {
									if (++undopoint == MAXUNDO) {
										undopoint = 0;
									}
								}
							}
							modifyCode = 0;
							break;

						case 18: // ctrl+r
							if (undopoint != undonew) {
								var pos = elm.selectionStart;
								if (++undopoint == MAXUNDO) {
									undopoint = 0;
								}
								elm.value = undobuffer[undopoint];
								elm.setSelectionRange(pos, pos);
							}
							modifyCode = 0;
							break;

						case 36: // shift+4
							tl = getLineText(this);
							var pos = elm.selectionStart;
							var nl = pos + tl.currLineTextAll.length - tl.currLineText.length;
							elm.setSelectionRange(nl, nl);
							modifyCode = 0;
							break;

						case 94: // shift+6
							tl = getLineText(this);
							var pos = elm.selectionStart;
							var nl = pos - tl.currLineText.length;
							elm.setSelectionRange(nl, nl);
							modifyCode = 0;
							break;

					}
					break;

				// コマンドモード ##########################################################
				case "command":
					e.preventDefault();
					break;
			}
			var tl = getLineText(this);
			var currLine = tl.currLine - 5;
			if (currLine < 0) {
				currLine = 0;
			}
			pos = currLine * parseFloat(jQuery(this).css("line-height"));
			jQuery(this).scrollTop(pos);
		});
		return this;
	}

	var getLineText = function(object) {
		var textAreaElement = jQuery(object)[0];
		textAreaElement.selectionStart = 0;
		var sel = document.getSelection() + "";
		textAreaElement.selectionStart = textAreaElement.selectionEnd;
		var retvalue = [];
		var lines = sel.split("\n");
		var alllines = jQuery(object).val().split("\n");
		retvalue['currLine'] = lines.length - 1;
		retvalue['maxLine'] = alllines.length - 1;
		retvalue['prevLineText'] = lines[retvalue.currLine - 1];
		retvalue['currLineText'] = lines[retvalue.currLine];
		retvalue['currLineTextAll'] = alllines[retvalue.currLine];
		retvalue['nextLineText'] = alllines[retvalue.currLine + 1];
		return retvalue;
	}

})(jQuery);

<commit_msg>line number memory implement<commit_after>// 2キー処理ではないキーの各処理の最後にmodifyCode=0を入れておくこと。
(function($) {
	$.fn.vixtarea = function(options){
       var options = jQuery.extend({
			size: '14px',
			color: 'black',
			backgroundColor: 'white',
			method: undefined
        }, options);

		var permitKeyCode = [186, 191, 65, 79, 68, 73, 88, 85, 82, 90, 72, 74, 75, 76, 89, 71, 82, 52, 54, 80, 77, 222];

		var MAXUNDO = 256 + 1;

		var mode = "view";
		var modifyCode = 0;
		var undobuffer = [this.val()];
		var undopoint = 0;
		var undotop = 0;
		var undonew = 0;
		var prevKey = 0;
		var yankbuffer = "";
		var horizontal = 0;
		var memoryline = [];

		this.css("font-size", options.size);
		this.css("line-height", options.size);
		this.css("font-family", "Osaka-Mono");
		this.css("color", options.color);
		this.css("background-color", options.backgroundColor);

		// keyup ######################################################################################################
		this.keyup(function(e) {
			if (prevKey == 17 && e.keyCode == 17) {
				prevKey = 0;
			} else if (prevKey == 17) {
				prevKey = 17;
			}
			//console.log("prevKey="+prevKey+", keyup:"+e.keyCode);
		});

		// keydown ######################################################################################################
		this.keydown(function(e) {
			var elm = e.target;
			//console.log("keydown="+e.keyCode);
			switch (mode) {
				case "view":
					permit = permitKeyCode.indexOf(e.keyCode);
					if (permit == -1 && modifyCode != 109 && modifyCode != 222) {
						//console.log("preventDefault:"+e.keyCode);
						e.preventDefault();
					}

					if (e.keyCode == 222 || e.keyCode == 77) {
						modifyCode = e.keyCode;
					}

					if (prevKey == 17 && (e.keyCode != 82)) {
						e.preventDefault();
						prevKey = 17;
					} else {
						prevKey = e.keyCode;
					}
					break;

				// 編集モード ##############################################################
				case "edit":
					if (e.keyCode === 9) { // TAB
						//console.log("tab");
						e.preventDefault();
						var val = elm.value;
						var pos = elm.selectionStart;
						elm.value = val.substr(0, pos) + '\t' + val.substr(pos, val.length);
						elm.setSelectionRange(pos + 1, pos + 1);
					}

					break;

				case "command":
					break;
			}
			if (e.keyCode == 27 && (mode == "edit" || mode == "command")) {
				modifyCode = 0;
				switch (mode) {
					case "edit":
						undopoint++;
						if (undopoint == MAXUNDO) {
							undopoint = 0;
						}
						undonew = undopoint;
						if (undopoint == undotop) {
							undotop++;
							if (undotop == MAXUNDO) {
								undotop = 0;
							}
						}
						undobuffer[undopoint] = elm.value;
						var val = elm.value;
						var pos = elm.selectionStart;
						ch = val.substr(pos - 1, 1);
						code = ch.charCodeAt(0);
						if (code != 10) {
							pos--;
							elm.setSelectionRange(pos, pos);
						}
						break;
				}
				mode = "view";
			}
		});

		// keypress ######################################################################################################
		this.keypress(function(e) {
			//console.log("keypress="+e.keyCode);
			var elm = e.target;
			switch (mode) {
				case "view":
					e.preventDefault();
					var pos = elm.selectionStart;
					// 行記憶
					if (modifyCode == 109 && e.keyCode >= 97 && e.keyCode <= 122) {
						tl = getLineText(this);
						memoryline[e.keyCode] = {pos: pos - tl.currLineText.length, line: tl.currLine};
						modifyCode = 0;
						e.keyCode = 0;
					}
					// 行復帰
					if (modifyCode == 222 && e.keyCode >= 97 && e.keyCode <= 122) {
						if (memoryline[e.keyCode] != undefined) {
							linenum = memoryline[e.keyCode].line - 5;
							if (linenum < 0) {
								linenum = 0;
							}
							jump = memoryline[e.keyCode].pos;
							elm.setSelectionRange(jump, jump);
							currpos = linenum * parseFloat(jQuery(this).css("line-height"));
							jQuery(this).scrollTop(currpos);
							modifyCode = 0;
							e.keyCode = 0;
						}
					}
					switch (e.keyCode) {
						// エディター操作 ##################################################

						case 104: // h
							elm.focus();
							var tl = getLineText(this);
							horizontal = tl.currLineText.length;
							var val = elm.value;
							ch = val.substr(pos - 1, 1);
							code = ch.charCodeAt(0);
							if (code != 10) {
								elm.setSelectionRange(elm.value.length, pos - 1);
							}
							modifyCode = 0;
							break;

						case 106: // j
							var tl = getLineText(this);
							if (tl.nextLineText != undefined) {
								var move = pos - tl.currLineText.length + tl.currLineTextAll.length + 1;
								if (horizontal < tl.nextLineText.length) {
									move += horizontal;
								} else {
									if (tl.nextLineText.length == 0) {
										move += tl.nextLineText.length;
									} else {
										move += tl.nextLineText.length - 1;
									}
								}
								elm.focus();
								elm.setSelectionRange(move, move);
							}
							modifyCode = 0;
							break;

						case 107: // k
							var tl = getLineText(this);
							if (tl.prevLineText != undefined) {
								var move = pos - tl.currLineText.length - tl.prevLineText.length - 1;
								if (horizontal < tl.prevLineText.length) {
									move += horizontal;
								} else {
									if (tl.prevLineText.length == 0) {
										move += tl.prevLineText.length;
									} else {
										move += tl.prevLineText.length - 1;
									}
								}
								elm.focus();
								elm.setSelectionRange(move, move);
							}
							modifyCode = 0;
							break;

						case 108: // l
							elm.focus();
							var tl = getLineText(this);
							horizontal = tl.currLineText.length;
							var val = elm.value;
							ch1 = val.substr(pos, 1);
							ch2 = val.substr(pos + 1, 1);
							code1 = ch1.charCodeAt(0);
							code2 = ch2.charCodeAt(0);
							if (code1 != 10 && code2 != 10) {
								elm.setSelectionRange(elm.value.length, pos + 1);
							}
							modifyCode = 0;
							break;

						case 58: // :
							mode = "command";
							modifyCode = 0;
							break;

						case 109: // m
							modifyCode = e.keyCode;
							break;

						// 編集操作 #########################################################

						case 105: // i
							mode = "edit";
							modifyCode = 0;
							break;

						case 97: // a
							mode = "edit";
							elm.setSelectionRange(pos+1, pos+1);
							modifyCode = 0;
							break;

						case 111: // o
							mode = "edit";
							var tl = getLineText(this);
							var nl = pos - tl.currLineText.length + tl.currLineTextAll.length + 1;
							var val = elm.value;
							elm.value = val.substr(0, nl) + '\n' + val.substr(nl, val.length);
							elm.setSelectionRange(nl, nl);
							modifyCode = 0;
							break;

						case 79: // O
							mode = "edit";
							var tl = getLineText(this);
							var nl = pos - tl.currLineText.length;
							var val = elm.value;
							elm.value = val.substr(0, nl) + '\n' + val.substr(nl, val.length);
							elm.setSelectionRange(nl, nl);
							modifyCode = 0;
							break;

						case 121: // y
							if (modifyCode == 121) {
								modifyCode = 0;
								var tl = getLineText(this);
								var val = elm.value;
								yankbuffer = val.substr(pos - tl.currLineText.length, tl.currLineTextAll.length + 1);
							} else {
								modifyCode = e.keyCode;
							}
							break;

						case 100: // dd
							if (modifyCode == 100) {
								modifyCode = 0;
								undopoint++;
								if (undopoint == MAXUNDO) {
									undopoint = 0;
								}
								undonew = undopoint;
								if (undopoint == undotop) {
									undotop++;
									if (undotop == MAXUNDO) {
										undotop = 0;
									}
								}
								var tl = getLineText(this);
								var nl = pos - tl.currLineText.length;
								var nl2 = pos - tl.currLineText.length + tl.currLineTextAll.length + 1;
								var val = elm.value;
								yankbuffer = val.substr(pos - tl.currLineText.length, tl.currLineTextAll.length + 1);
								elm.value = val.substr(0, nl) + val.substr(nl2, val.length);
								elm.setSelectionRange(nl, nl);
								undobuffer[undopoint] = elm.value
							} else {
								modifyCode = e.keyCode;
							}
							break;

						case 112: // p
							e.preventDefault();
							undopoint++;
							if (undopoint == MAXUNDO) {
								undopoint = 0;
							}
							undonew = undopoint;
							if (undopoint == undotop) {
								undotop++;
								if (undotop == MAXUNDO) {
									undotop = 0;
								}
							}
							var tl = getLineText(this);
							var val = elm.value;
							var nl = pos - tl.currLineText.length + tl.currLineTextAll.length + 1;
							elm.value = val.substr(0, nl) + yankbuffer + val.substr(nl, val.length);
							elm.setSelectionRange(nl, nl);
							undobuffer[undopoint] = elm.value
							modifyCode = 0;
							break;

						case 80: // P
							e.preventDefault();
							undopoint++;
							if (undopoint == MAXUNDO) {
								undopoint = 0;
							}
							undonew = undopoint;
							if (undopoint == undotop) {
								undotop++;
								if (undotop == MAXUNDO) {
									undotop = 0;
								}
							}
							var val = elm.value;
							elm.value = val.substr(0, pos) + yankbuffer + val.substr(pos, val.length);
							elm.setSelectionRange(pos, pos);
							undobuffer[undopoint] = elm.value
							modifyCode = 0;
							break;

						case 120: // x
							undopoint++;
							if (undopoint == MAXUNDO) {
								undopoint = 0;
							}
							undonew = undopoint;
							if (undopoint == undotop) {
								undotop++;
								if (undotop == MAXUNDO) {
									undotop = 0;
								}
							}
							var val = elm.value;
							elm.value = val.substr(0, pos) + val.substr(pos + 1, val.length);
							elm.setSelectionRange(pos, pos);
							undobuffer[undopoint] = elm.value;
							modifyCode = 0;
							break;

						case 103: // g
							if (modifyCode == 103) {
								modifyCode = 0;
								elm.setSelectionRange(0, 0);
							} else {
								modifyCode = 103;
							}
							break;

						case 71: // shift+g
							pos = elm.value.length;
							elm.setSelectionRange(pos, pos);
							modifyCode = 0;
							break;

						case 117: // u
							if (undopoint != undotop) {
								if (--undopoint < 0) {
									undopoint = MAXUNDO - 1;
								}
								var str = undobuffer[undopoint];
								if (str != undefined) {
									elm.value = str;
									elm.setSelectionRange(pos, pos);
								} else {
									if (++undopoint == MAXUNDO) {
										undopoint = 0;
									}
								}
							}
							modifyCode = 0;
							break;

						case 18: // ctrl+r
							if (undopoint != undonew) {
								if (++undopoint == MAXUNDO) {
									undopoint = 0;
								}
								elm.value = undobuffer[undopoint];
								elm.setSelectionRange(pos, pos);
							}
							modifyCode = 0;
							break;

						case 36: // shift+4
							tl = getLineText(this);
							var nl = pos + tl.currLineTextAll.length - tl.currLineText.length;
							elm.setSelectionRange(nl, nl);
							modifyCode = 0;
							break;

						case 94: // shift+6
							tl = getLineText(this);
							var nl = pos - tl.currLineText.length;
							elm.setSelectionRange(nl, nl);
							modifyCode = 0;
							break;

					}
					break;

				// コマンドモード ##########################################################
				case "command":
					e.preventDefault();
					break;
			}

			if (e.keyCode != 0) {
				var tl = getLineText(this);
				var currLine = tl.currLine - 5;
				if (currLine < 0) {
					currLine = 0;
				}
				currpos = currLine * parseFloat(jQuery(this).css("line-height"));
				jQuery(this).scrollTop(currpos);
			}
		});
		return this;
	}

	var getLineText = function(object) {
		var textAreaElement = jQuery(object)[0];
		textAreaElement.selectionStart = 0;
		var sel = document.getSelection() + "";
		textAreaElement.selectionStart = textAreaElement.selectionEnd;
		var retvalue = [];
		var lines = sel.split("\n");
		var alllines = jQuery(object).val().split("\n");
		retvalue['currLine'] = lines.length - 1;
		retvalue['maxLine'] = alllines.length - 1;
		retvalue['prevLineText'] = lines[retvalue.currLine - 1];
		retvalue['currLineText'] = lines[retvalue.currLine];
		retvalue['currLineTextAll'] = alllines[retvalue.currLine];
		retvalue['nextLineText'] = alllines[retvalue.currLine + 1];
		return retvalue;
	}

})(jQuery);

<|endoftext|>


<commit_before>function slideHeaderUp () {
  const main = document.getElementById('main')
  if (main.className !== 'show-content') {
    main.className = 'show-content'
  }
}

function setActiveButton (id) {
  Array.from(document.getElementsByClassName('menu-item')).forEach(x => {
    x.className = x.hash === `#${id}`
      ? `${x.className} active`
      : x.className.replace('active', '')
  })
}

function setContent (id) {
  if (!id) return
  slideHeaderUp()
  document.getElementById('content').innerHTML = document.getElementById(id).innerHTML
}

function updateSite (id) {
  setContent(id)
  setActiveButton(id)
}

function closeModal (e) {
  if (e.target.tagName.toLowerCase() === 'img') return
  const main = document.getElementById('main')
  const modal = document.getElementById('modal')
  main.removeChild(modal)
}

function openModal (e) {
  const main = document.getElementById('main')
  const oldModal = document.getElementById('modal')
  if (oldModal) main.removeChild(oldModal)
  const modal = document.createElement('div')
  const image = document.createElement('img')
  modal.id = "modal"
  image.src = e.target.src
  image.addEventListener('click', _ => window.open(e.target.src, '_blank'))
  modal.addEventListener('click', closeModal)
  modal.appendChild(image)
  main.appendChild(modal)
}

document.addEventListener('DOMContentLoaded', () => {
  // Set state from url hash
  updateSite(window.location.hash.substr(1))

  // Add event listeners to images
  Array.from(document.getElementsByClassName('art')).forEach(el => {
    el.addEventListener('click', openModal)
  })

  // Set event listener to show content on click
  document.getElementById('nav').addEventListener('click', e => {
    if (e.target.tagName.toLowerCase() !== 'a') return
    updateSite(e.target.hash.substr(1))
  })
})
<commit_msg>Make sure modal always opens correctly<commit_after>function slideHeaderUp () {
  const main = document.getElementById('main')
  if (main.className !== 'show-content') {
    main.className = 'show-content'
  }
}

function setActiveButton (id) {
  Array.from(document.getElementsByClassName('menu-item')).forEach(x => {
    x.className = x.hash === `#${id}`
      ? `${x.className} active`
      : x.className.replace('active', '')
  })
}

function setContent (id) {
  if (!id) return
  slideHeaderUp()
  document.getElementById('content').innerHTML = document.getElementById(id).innerHTML
}

function updateSite (id) {
  setContent(id)
  setActiveButton(id)
}

function closeModal (e) {
  if (e.target.tagName.toLowerCase() === 'img') return
  const main = document.getElementById('main')
  const modal = document.getElementById('modal')
  main.removeChild(modal)
}

function openModal (e) {
  const main = document.getElementById('main')
  const oldModal = document.getElementById('modal')
  if (oldModal) main.removeChild(oldModal)
  const modal = document.createElement('div')
  const image = document.createElement('img')
  modal.id = "modal"
  image.src = e.target.src
  image.addEventListener('click', _ => window.open(e.target.src, '_blank'))
  modal.addEventListener('click', closeModal)
  modal.appendChild(image)
  main.appendChild(modal)
}

function addModalEventListeners (e) {
  // Only update on relevant url
  if (e && e.newURL.indexOf('#gallery') === -1) return
  // Add event listeners to images
  Array.from(document.getElementsByClassName('art')).forEach(el => {
    el.addEventListener('click', openModal)
  })
}

document.addEventListener('DOMContentLoaded', () => {
  // Set state from url hash
  updateSite(window.location.hash.substr(1))

  // Make sure clicking images works
  window.addEventListener('hashchange',  addModalEventListeners)
  addModalEventListeners()

  // Set event listener to show content on click
  document.getElementById('nav').addEventListener('click', e => {
    if (e.target.tagName.toLowerCase() !== 'a') return
    updateSite(e.target.hash.substr(1))
  })
})
<|endoftext|>


<commit_before>(function(ext) {
    ext._shutdown = function() {};
    ext._getStatus = function() {
        return {status: 2, msg: 'Ready'};
    };

    ext.create = function(name, params, js, type, desc) {
        eval("\(function\(ext\) \{ext\._shutdown \= function\(\) \{\}; ext\._getStatus \= function\(\) \{return \{status\: 2, msg\: \'Ready\'\};\}; ext\." + name + " \= function\(" + params + "\) \{" + js + "\}; var descriptor \= \{blocks: \[\[\'" + type + "\', \'" + desc + "'\, \'" + name + "\'\]\,\]\,\};ScratchExtensions\.register\(\'" + name + "\'\, descriptor\, ext\)\;\}\)\(\{\}\)\;")
    };

    ext.jar = function(script) {
        eval(script);
    }

    ext.jar2 = function(script) {
        return eval(script);
    }

    ext.jar3 = function(script) {
        return eval(script);
    }
     ext.commentget = function() {
         return document.getElementsByName("fname")[0].value
     };

    var descriptor = {
        blocks: [
            [' ', 'create block: name %s params %s js %s type %s desc %s', 'create', "custom", "hello", "return true", "r", "true %s"],
            [' ', 'eval %s', 'jar', 'return true'],
            ['r', 'eval %s', 'jar2', 'return true'],
            ['b', 'eval %s', 'jar3', 'return true'],
            ["r", "comment value", "commentget"]
        ],
    };

    ScratchExtensions.register('Mod - script', descriptor, ext);
})({});
<commit_msg>Update script.js<commit_after>(function(ext) {
    ext._shutdown = function() {};
    ext._getStatus = function() {
        return {status: 2, msg: 'Ready'};
    };

    ext.create = function(name, params, js, type, desc) {
        eval("\(function\(ext\) \{ext\._shutdown \= function\(\) \{\}; ext\._getStatus \= function\(\) \{return \{status\: 2, msg\: \'Ready\'\};\}; ext\." + name + " \= function\(" + params + "\) \{" + js + "\}; var descriptor \= \{blocks: \[\[\'" + type + "\', \'" + desc + "'\, \'" + name + "\'\]\,\]\,\};ScratchExtensions\.register\(\'" + name + "\'\, descriptor\, ext\)\;\}\)\(\{\}\)\;")
    };

    ext.jar = function(script) {
        eval(script);
    }

    ext.jar2 = function(script) {
        return eval(script);
    }

    ext.jar3 = function(script) {
        return eval(script);
    }
    ext.commentget = function() {
        return document.getElementsByName("content")[0].value;
    };

    ext.commentset = function(value) {
        document.getElementsByName("content")[0].value = value;
    };

    var descriptor = {
        blocks: [
            [' ', 'create block: name %s params %s js %s type %s desc %s', 'create', "custom", "hello", "return true", "r", "true %s"],
            [' ', 'eval %s', 'jar', 'return true'],
            ['r', 'eval %s', 'jar2', 'return true'],
            ['b', 'eval %s', 'jar3', 'return true'],
            ["r", "comment value", "commentget"]
            [" ", "set comment to %s", "commentset", "comment"]
        ],
    };

    ScratchExtensions.register('Mod - script', descriptor, ext);
})({});
<|endoftext|>