<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * List of all FOAM files available to be loaded in a JSONP
 * format, so it can used from both nodejs scripts, and web
 * pages via script tags easily.
 */

FOAM_FILES([
  { name: "foam/core/lib" },
  { name: "foam/core/stdlib" },
  { name: "foam/core/events" },
  { name: "foam/core/Context" },
  { name: "foam/core/Boot" },
  { name: "foam/core/FObject" },
  { name: "foam/core/Model" },
  { name: "foam/core/Property" },
  { name: "foam/core/Method" },
  { name: "foam/core/Boolean" },
  { name: "foam/core/AxiomArray" },
  { name: "foam/core/EndBoot" },
  { name: "foam/core/FObjectArray" },
  { name: "foam/core/Constant" },
  { name: "foam/core/Validation" },
  { name: "foam/pattern/Faceted" },
  { name: "foam/core/types" },
  { name: "foam/core/Topic" },
  { name: "foam/core/InnerClass" },
  { name: "foam/core/InnerEnum" },
  { name: "foam/core/Implements" },
  { name: "foam/core/ImportsExports" },
  { name: "foam/core/Listener" },
  { name: "foam/core/IDSupport" },
  { name: "foam/core/Requires" },
  { name: "foam/core/Slot" },
  { name: "foam/core/Proxy" },
  { name: "foam/core/Promised" },
  { name: "foam/core/Interface" },
  { name: "foam/core/ContextMethod" },
  { name: "foam/core/Window" },
  { name: "foam/core/ContextMultipleInheritence" },
  { name: "foam/classloader/ClassLoader" },
  { name: "foam/core/Argument" },
  { name: "foam/core/MultiMethod" },
  { name: "foam/core/debug", flags: ['debug'] },
  { name: "foam/pattern/Singleton" },
  { name: "foam/pattern/Multiton" },
  { name: "foam/core/Enum" },
  { name: "foam/core/JSON" },
  { name: "foam/parse/parse" },
  { name: "foam/parse/json" },
  { name: "foam/parsers/FON" },
  { name: "foam/core/templates" },
  { name: "foam/i18n/Messages" },
  { name: "foam/core/Action" },
  { name: "foam/core/Reaction" },
  { name: "foam/core/Serializable" },
  { name: "foam/java/Argument", flags: ['java'] },
  { name: "foam/java/Class", flags: ['java'] },
  { name: "foam/java/ClassInfo", flags: ['java'] },
  { name: "foam/java/Code", flags: ['java'] },
  { name: "foam/java/CodeProperty", flags: ['java'] },
  { name: "foam/java/Field", flags: ['java'] },
  { name: "foam/java/Interface", flags: ['java'] },
  { name: "foam/java/InterfaceMethod", flags: ['java'] },
  { name: "foam/java/Method", flags: ['java'] },
  { name: "foam/java/Enum", flags: ['java'] },
  { name: "foam/java/MultiPartGetter", flags: ['java'] },
  { name: "foam/java/MultiPartSetter", flags: ['java'] },
  { name: "foam/java/Outputter", flags: ['java'] },
  { name: "foam/java/PropertyInfo", flags: ['java'] },
  { name: "foam/java/PropertyRefinement", flags: ['java'] },
  { name: "foam/java/Skeleton", flags: ['java'] },
  { name: "foam/java/JavaImport", flags: ['java'] },
  { name: "foam/java/refinements", flags: ['java'] },
  { name: "foam/util/Timer" },
  { name: "foam/memento/MementoMgr" },
  { name: "lib/input", flags: ['web'] },
  { name: "foam/u2/AttrSlot" },
  { name: "foam/u2/ViewSpec" },
  { name: "foam/u2/Element" },
//  { name: "foam/u2/AttrSlot", flags: ['web'] },
//  { name: "foam/u2/Element", flags: ['web'] },
  { name: "foam/u2/ProgressView", flags: ['web'] },
  { name: "foam/dao/Sink" },
  { name: "foam/dao/SinkJava", flags: ['java'] },
  { name: "foam/dao/DAO" },
  { name: "foam/dao/DAOJava", flags: ['java'] },
  { name: "foam/dao/daoUtils" },
  { name: "foam/dao/DAODecorator" },
  { name: "foam/dao/AbstractDAO" },
  { name: "foam/dao/DAOProperty" },
  { name: "foam/mlang/mlang" },
  { name: "foam/mlang/mlangJava", flags: ['java'] },
  { name: "foam/mlang/LabeledValue" },
  { name: "foam/dao/index/Plan" },
  { name: "foam/dao/index/Index" },
  { name: "foam/dao/index/ProxyIndex" },
  { name: "foam/dao/index/AltIndex" },
  { name: "foam/dao/index/ValueIndex" },
  { name: "foam/dao/index/AATree" },
  { name: "foam/dao/index/TreeIndex" },
  { name: "foam/dao/index/AutoIndex" },
  { name: "foam/dao/MDAO" },
  { name: "foam/dao/ArrayDAO" },
  { name: "foam/dao/TimestampDAO" },
  { name: "foam/dao/GUIDDAO" },
  { name: "foam/dao/ReadOnlyDAO" },
  { name: "foam/dao/JournaledDAO" },
  { name: "foam/dao/Relationship" },
  { name: "foam/dao/RelationshipDAO" },
  { name: "foam/dao/ManyToManyRelationshipDAO" },
  { name: "foam/dao/LazyCacheDAO" },
  { name: "foam/dao/CachingDAO" },
  { name: "foam/dao/DeDupDAO" },
  { name: "foam/dao/LRUDAOManager" },
  { name: "foam/dao/SequenceNumberDAO" },
  { name: "foam/dao/ContextualizingDAO" },
  { name: "foam/dao/SyncDAO" },
  { name: "foam/dao/EasyDAO" },
  { name: "foam/dao/NoSelectAllDAO" },
  { name: "foam/dao/NullDAO" },
  { name: "foam/dao/TimingDAO" },
  { name: "foam/dao/LoggingDAO" },
  { name: "foam/dao/IDBDAO", flags: ['web'] },
  { name: "foam/dao/RestDAO" },
  { name: "foam/dao/EnabledAwareDAO" },
  { name: "foam/dao/LastModifiedAwareDAO" },
  { name: "foam/dao/ValidationDAODecorator" },
  { name: "foam/dao/SQL", flags: ['sql'] },
  { name: "foam/parse/QueryParser" },
  { name: "foam/physics/Physical" },
  { name: "foam/physics/Collider" },
  { name: "foam/physics/PhysicsEngine" },
  { name: "foam/blob/Blob" },
  { name: "lib/node/json_dao", flags: ['node'] },
  { name: "lib/utf8" },
  { name: "lib/web/net" }, // No flags: ['web']: base classes for lib/node/net.
  { name: "lib/messageport", flags: ['web'] },
  { name: "lib/node/net", flags: ['node'] },
  { name: "lib/firebase" },
  { name: "lib/fcm" },
  { name: "lib/Stub" },
  { name: "lib/box" },
  { name: "lib/boxJava", flags: ['java'] },
  { name: "foam/core/async" },
  { name: "foam/u2/ViewFactory", flags: ['web'] },
  { name: "foam/u2/daos", flags: ['web'] },
  { name: "foam/u2/TableView", flags: ['web'] },
  { name: "foam/u2/TableSelection", flags: ['web'] },
  { name: "foam/u2/Scroller", flags: ['web'] },
  { name: "foam/u2/ActionView", flags: ['web'] },
  { name: "foam/u2/DetailPropertyView", flags: ['web'] },
  { name: "foam/u2/DetailView", flags: ['web'] },
  { name: "foam/u2/tag/Image", flags: ['web'] },
  { name: "foam/u2/tag/Input", flags: ['web'] },
  { name: "foam/u2/tag/TextArea", flags: ['web'] },
  { name: "foam/u2/TextField", flags: ['web'] },
  { name: "foam/u2/IntView", flags: ['web'] },
  { name: "foam/u2/FloatView", flags: ['web'] },
  { name: "foam/u2/CheckBox", flags: ['web'] },
  { name: "foam/u2/CitationView", flags: ['web'] },
  { name: "foam/u2/PopupView", flags: ['web'] },
  { name: "foam/u2/DateView", flags: ['web'] },
  { name: "foam/u2/DateTimeView", flags: ['web'] },
  { name: "foam/u2/RangeView", flags: ['web'] },
  { name: "foam/u2/ReadWriteView", flags: ['web'] },
  { name: "foam/u2/HTMLElement", flags: ['web'] },
  { name: "foam/u2/tag/Select", flags: ['web'] },
  { name: "foam/u2/Tabs", flags: ['web'] },
  { name: "foam/u2/view/ChoiceView", flags: ['web'] },
  { name: "foam/u2/view/RadioView", flags: ['web'] },
  { name: "foam/u2/view/TextField", flags: ['web'] },
  { name: "foam/u2/view/TreeView", flags: ['web'] },
  { name: "foam/u2/view/DualView", flags: ['web'] },
  { name: "foam/u2/view/ColorPicker", flags: ['web'] },
  { name: "foam/u2/view/TableView", flags: ['web'] },
  { name: "foam/u2/view/ScrollTableView", flags: ['web'] },
  { name: "foam/u2/view/BlobView", flags: ['web'] },
  { name: "foam/u2/view/StringArrayView", flags: ['web'] },
  { name: "foam/u2/view/ImageView", flags: ['web'] },
  { name: "foam/u2/EnumView", flags: ['web'] },
  { name: "foam/u2/ClassView", flags: ['web'] },
  { name: "foam/u2/view/ReferenceView", flags: ['web'] },
  { name: "foam/u2/tag/Card", flags: ['web'] },
  { name: "foam/u2/dialog/Popup", flags: ['web'] },
  { name: "foam/u2/Autocompleter", flags: ['web'] },
  { name: "foam/u2/search/FilterController", flags: ['web'] },
  { name: "foam/u2/search/GroupCompleter", flags: ['web'] },
  { name: "foam/u2/search/GroupAutocompleteSearchView", flags: ['web'] },
  { name: "foam/u2/search/GroupBySearchView", flags: ['web'] },
  { name: "foam/u2/search/SearchManager", flags: ['web'] },
  { name: "foam/u2/search/TextSearchView", flags: ['web'] },
  { name: "foam/u2/stack/Stack", flags: ['web'] },
  { name: "foam/u2/stack/StackView", flags: ['web'] },
  { name: "foam/u2/FoamTagLoader", flags: ['loader'] },
  { name: "foam/graphics/CView", flags: ['web'] },
  { name: "foam/graphics/ScrollCView", flags: ['web'] },
  { name: "foam/physics/PhysicalCircle", flags: ['web'] },
  { name: "foam/comics/DAOController" },
  { name: "foam/comics/DAOControllerView", flags: ['web'] },
  { name: "foam/comics/InlineDAOControllerView", flags: ['web'] },
  { name: "foam/comics/DAOCreateController" },
  { name: "foam/comics/DAOCreateControllerView", flags: ['web'] },
  { name: "foam/comics/DAOUpdateController" },
  { name: "foam/comics/DAOUpdateControllerView", flags: ['web'] },
  { name: "foam/comics/BrowserView", flags: ['web'] },
  { name: "foam/comics/InlineBrowserView", flags: ['web'] },
  { name: "foam/comics/RelationshipView", flags: ['web'] },
  { name: "foam/u2/view/RecipricalSearch", flags: ['web'] },
  { name: "lib/node/box", flags: ['node'] },
  { name: "foam/net/HTTPMethod" },
  { name: "lib/net" },
  { name: "foam/net/RetryHTTPRequest" },
  { name: "foam/net/auth/TokenBearerCredential" },
  { name: "foam/net/auth/AuthAwareHTTPRequest" },
  { name: "foam/net/auth/TokenBearerHTTPRequest" },
  { name: "foam/net/auth/AuthAgent" },
  { name: "foam/doc/DocBrowser", flags: ['debug'] },
  { name: "com/google/net/node/Google2LOAuthAgent", flags: ['node', 'gcloud'] },
  { name: "com/google/cloud/datastore/types", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/mlang", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/DatastoreDAO", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/BatchMutationDatastoreDAO", flags: ['gcloud'] },
  { name: "foam/net/node/Handler", flags: ['node'] },
  { name: "foam/net/node/FileHandler", flags: ['node'] },
  { name: "foam/net/node/StaticFileHandler", flags: ['node'] },
  { name: "foam/net/node/RestDAOHandler", flags: ['node'] },
  { name: "foam/net/node/Server", flags: ['node'] },
  { name: "foam/classloader/ClassLoader", flags: ['debug'] },
  { name: "foam/classloader/OrDAO", flags: ['debug'] },
  { name: "foam/classloader/WebModelFileDAO", flags: ['web', 'debug'] },
  { name: "foam/classloader/NodeModelFileDAO", flags: ['node', 'debug'] },
  { name: "foam/classloader/NodeJsModelExecutor", flags: ['node', 'debug'] },
  { name: "foam/parsers/html/lib" },
  { name: "foam/parsers/html/Attribute" },
  { name: "foam/parsers/html/TagType" },
  { name: "foam/parsers/html/Tag" },
  { name: "foam/parsers/html/HTMLLexer" },
  { name: "foam/core/ContextAware", flags: ['java'] },
  { name: "foam/dao/history/PropertyUpdate" },
  { name: "foam/dao/history/HistoryRecord" },
  { name: "foam/mop/MOP" },
  { name: "foam/mop/MOPJava", flags: ['java'] },
]);
<commit_msg>Added HistoryView and HistoryItemView to files.js<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * List of all FOAM files available to be loaded in a JSONP
 * format, so it can used from both nodejs scripts, and web
 * pages via script tags easily.
 */

FOAM_FILES([
  { name: "foam/core/lib" },
  { name: "foam/core/stdlib" },
  { name: "foam/core/events" },
  { name: "foam/core/Context" },
  { name: "foam/core/Boot" },
  { name: "foam/core/FObject" },
  { name: "foam/core/Model" },
  { name: "foam/core/Property" },
  { name: "foam/core/Method" },
  { name: "foam/core/Boolean" },
  { name: "foam/core/AxiomArray" },
  { name: "foam/core/EndBoot" },
  { name: "foam/core/FObjectArray" },
  { name: "foam/core/Constant" },
  { name: "foam/core/Validation" },
  { name: "foam/pattern/Faceted" },
  { name: "foam/core/types" },
  { name: "foam/core/Topic" },
  { name: "foam/core/InnerClass" },
  { name: "foam/core/InnerEnum" },
  { name: "foam/core/Implements" },
  { name: "foam/core/ImportsExports" },
  { name: "foam/core/Listener" },
  { name: "foam/core/IDSupport" },
  { name: "foam/core/Requires" },
  { name: "foam/core/Slot" },
  { name: "foam/core/Proxy" },
  { name: "foam/core/Promised" },
  { name: "foam/core/Interface" },
  { name: "foam/core/ContextMethod" },
  { name: "foam/core/Window" },
  { name: "foam/core/ContextMultipleInheritence" },
  { name: "foam/classloader/ClassLoader" },
  { name: "foam/core/Argument" },
  { name: "foam/core/MultiMethod" },
  { name: "foam/core/debug", flags: ['debug'] },
  { name: "foam/pattern/Singleton" },
  { name: "foam/pattern/Multiton" },
  { name: "foam/core/Enum" },
  { name: "foam/core/JSON" },
  { name: "foam/parse/parse" },
  { name: "foam/parse/json" },
  { name: "foam/parsers/FON" },
  { name: "foam/core/templates" },
  { name: "foam/i18n/Messages" },
  { name: "foam/core/Action" },
  { name: "foam/core/Reaction" },
  { name: "foam/core/Serializable" },
  { name: "foam/java/Argument", flags: ['java'] },
  { name: "foam/java/Class", flags: ['java'] },
  { name: "foam/java/ClassInfo", flags: ['java'] },
  { name: "foam/java/Code", flags: ['java'] },
  { name: "foam/java/CodeProperty", flags: ['java'] },
  { name: "foam/java/Field", flags: ['java'] },
  { name: "foam/java/Interface", flags: ['java'] },
  { name: "foam/java/InterfaceMethod", flags: ['java'] },
  { name: "foam/java/Method", flags: ['java'] },
  { name: "foam/java/Enum", flags: ['java'] },
  { name: "foam/java/MultiPartGetter", flags: ['java'] },
  { name: "foam/java/MultiPartSetter", flags: ['java'] },
  { name: "foam/java/Outputter", flags: ['java'] },
  { name: "foam/java/PropertyInfo", flags: ['java'] },
  { name: "foam/java/PropertyRefinement", flags: ['java'] },
  { name: "foam/java/Skeleton", flags: ['java'] },
  { name: "foam/java/JavaImport", flags: ['java'] },
  { name: "foam/java/refinements", flags: ['java'] },
  { name: "foam/util/Timer" },
  { name: "foam/memento/MementoMgr" },
  { name: "lib/input", flags: ['web'] },
  { name: "foam/u2/AttrSlot" },
  { name: "foam/u2/ViewSpec" },
  { name: "foam/u2/Element" },
//  { name: "foam/u2/AttrSlot", flags: ['web'] },
//  { name: "foam/u2/Element", flags: ['web'] },
  { name: "foam/u2/ProgressView", flags: ['web'] },
  { name: "foam/dao/Sink" },
  { name: "foam/dao/SinkJava", flags: ['java'] },
  { name: "foam/dao/DAO" },
  { name: "foam/dao/DAOJava", flags: ['java'] },
  { name: "foam/dao/daoUtils" },
  { name: "foam/dao/DAODecorator" },
  { name: "foam/dao/AbstractDAO" },
  { name: "foam/dao/DAOProperty" },
  { name: "foam/mlang/mlang" },
  { name: "foam/mlang/mlangJava", flags: ['java'] },
  { name: "foam/mlang/LabeledValue" },
  { name: "foam/dao/index/Plan" },
  { name: "foam/dao/index/Index" },
  { name: "foam/dao/index/ProxyIndex" },
  { name: "foam/dao/index/AltIndex" },
  { name: "foam/dao/index/ValueIndex" },
  { name: "foam/dao/index/AATree" },
  { name: "foam/dao/index/TreeIndex" },
  { name: "foam/dao/index/AutoIndex" },
  { name: "foam/dao/MDAO" },
  { name: "foam/dao/ArrayDAO" },
  { name: "foam/dao/TimestampDAO" },
  { name: "foam/dao/GUIDDAO" },
  { name: "foam/dao/ReadOnlyDAO" },
  { name: "foam/dao/JournaledDAO" },
  { name: "foam/dao/Relationship" },
  { name: "foam/dao/RelationshipDAO" },
  { name: "foam/dao/ManyToManyRelationshipDAO" },
  { name: "foam/dao/LazyCacheDAO" },
  { name: "foam/dao/CachingDAO" },
  { name: "foam/dao/DeDupDAO" },
  { name: "foam/dao/LRUDAOManager" },
  { name: "foam/dao/SequenceNumberDAO" },
  { name: "foam/dao/ContextualizingDAO" },
  { name: "foam/dao/SyncDAO" },
  { name: "foam/dao/EasyDAO" },
  { name: "foam/dao/NoSelectAllDAO" },
  { name: "foam/dao/NullDAO" },
  { name: "foam/dao/TimingDAO" },
  { name: "foam/dao/LoggingDAO" },
  { name: "foam/dao/IDBDAO", flags: ['web'] },
  { name: "foam/dao/RestDAO" },
  { name: "foam/dao/EnabledAwareDAO" },
  { name: "foam/dao/LastModifiedAwareDAO" },
  { name: "foam/dao/ValidationDAODecorator" },
  { name: "foam/dao/SQL", flags: ['sql'] },
  { name: "foam/parse/QueryParser" },
  { name: "foam/physics/Physical" },
  { name: "foam/physics/Collider" },
  { name: "foam/physics/PhysicsEngine" },
  { name: "foam/blob/Blob" },
  { name: "lib/node/json_dao", flags: ['node'] },
  { name: "lib/utf8" },
  { name: "lib/web/net" }, // No flags: ['web']: base classes for lib/node/net.
  { name: "lib/messageport", flags: ['web'] },
  { name: "lib/node/net", flags: ['node'] },
  { name: "lib/firebase" },
  { name: "lib/fcm" },
  { name: "lib/Stub" },
  { name: "lib/box" },
  { name: "lib/boxJava", flags: ['java'] },
  { name: "foam/core/async" },
  { name: "foam/u2/ViewFactory", flags: ['web'] },
  { name: "foam/u2/daos", flags: ['web'] },
  { name: "foam/u2/TableView", flags: ['web'] },
  { name: "foam/u2/TableSelection", flags: ['web'] },
  { name: "foam/u2/Scroller", flags: ['web'] },
  { name: "foam/u2/ActionView", flags: ['web'] },
  { name: "foam/u2/DetailPropertyView", flags: ['web'] },
  { name: "foam/u2/DetailView", flags: ['web'] },
  { name: "foam/u2/tag/Image", flags: ['web'] },
  { name: "foam/u2/tag/Input", flags: ['web'] },
  { name: "foam/u2/tag/TextArea", flags: ['web'] },
  { name: "foam/u2/TextField", flags: ['web'] },
  { name: "foam/u2/IntView", flags: ['web'] },
  { name: "foam/u2/FloatView", flags: ['web'] },
  { name: "foam/u2/CheckBox", flags: ['web'] },
  { name: "foam/u2/CitationView", flags: ['web'] },
  { name: "foam/u2/PopupView", flags: ['web'] },
  { name: "foam/u2/DateView", flags: ['web'] },
  { name: "foam/u2/DateTimeView", flags: ['web'] },
  { name: "foam/u2/RangeView", flags: ['web'] },
  { name: "foam/u2/ReadWriteView", flags: ['web'] },
  { name: "foam/u2/HTMLElement", flags: ['web'] },
  { name: "foam/u2/tag/Select", flags: ['web'] },
  { name: "foam/u2/Tabs", flags: ['web'] },
  { name: "foam/u2/history/HistoryItemView", flags: ['web'] },
  { name: "foam/u2/history/HistoryView", flags: ['web'] },
  { name: "foam/u2/view/ChoiceView", flags: ['web'] },
  { name: "foam/u2/view/RadioView", flags: ['web'] },
  { name: "foam/u2/view/TextField", flags: ['web'] },
  { name: "foam/u2/view/TreeView", flags: ['web'] },
  { name: "foam/u2/view/DualView", flags: ['web'] },
  { name: "foam/u2/view/ColorPicker", flags: ['web'] },
  { name: "foam/u2/view/TableView", flags: ['web'] },
  { name: "foam/u2/view/ScrollTableView", flags: ['web'] },
  { name: "foam/u2/view/BlobView", flags: ['web'] },
  { name: "foam/u2/view/StringArrayView", flags: ['web'] },
  { name: "foam/u2/view/ImageView", flags: ['web'] },
  { name: "foam/u2/EnumView", flags: ['web'] },
  { name: "foam/u2/ClassView", flags: ['web'] },
  { name: "foam/u2/view/ReferenceView", flags: ['web'] },
  { name: "foam/u2/tag/Card", flags: ['web'] },
  { name: "foam/u2/dialog/Popup", flags: ['web'] },
  { name: "foam/u2/Autocompleter", flags: ['web'] },
  { name: "foam/u2/search/FilterController", flags: ['web'] },
  { name: "foam/u2/search/GroupCompleter", flags: ['web'] },
  { name: "foam/u2/search/GroupAutocompleteSearchView", flags: ['web'] },
  { name: "foam/u2/search/GroupBySearchView", flags: ['web'] },
  { name: "foam/u2/search/SearchManager", flags: ['web'] },
  { name: "foam/u2/search/TextSearchView", flags: ['web'] },
  { name: "foam/u2/stack/Stack", flags: ['web'] },
  { name: "foam/u2/stack/StackView", flags: ['web'] },
  { name: "foam/u2/FoamTagLoader", flags: ['loader'] },
  { name: "foam/graphics/CView", flags: ['web'] },
  { name: "foam/graphics/ScrollCView", flags: ['web'] },
  { name: "foam/physics/PhysicalCircle", flags: ['web'] },
  { name: "foam/comics/DAOController" },
  { name: "foam/comics/DAOControllerView", flags: ['web'] },
  { name: "foam/comics/InlineDAOControllerView", flags: ['web'] },
  { name: "foam/comics/DAOCreateController" },
  { name: "foam/comics/DAOCreateControllerView", flags: ['web'] },
  { name: "foam/comics/DAOUpdateController" },
  { name: "foam/comics/DAOUpdateControllerView", flags: ['web'] },
  { name: "foam/comics/BrowserView", flags: ['web'] },
  { name: "foam/comics/InlineBrowserView", flags: ['web'] },
  { name: "foam/comics/RelationshipView", flags: ['web'] },
  { name: "foam/u2/view/RecipricalSearch", flags: ['web'] },
  { name: "lib/node/box", flags: ['node'] },
  { name: "foam/net/HTTPMethod" },
  { name: "lib/net" },
  { name: "foam/net/RetryHTTPRequest" },
  { name: "foam/net/auth/TokenBearerCredential" },
  { name: "foam/net/auth/AuthAwareHTTPRequest" },
  { name: "foam/net/auth/TokenBearerHTTPRequest" },
  { name: "foam/net/auth/AuthAgent" },
  { name: "foam/doc/DocBrowser", flags: ['debug'] },
  { name: "com/google/net/node/Google2LOAuthAgent", flags: ['node', 'gcloud'] },
  { name: "com/google/cloud/datastore/types", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/mlang", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/DatastoreDAO", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/BatchMutationDatastoreDAO", flags: ['gcloud'] },
  { name: "foam/net/node/Handler", flags: ['node'] },
  { name: "foam/net/node/FileHandler", flags: ['node'] },
  { name: "foam/net/node/StaticFileHandler", flags: ['node'] },
  { name: "foam/net/node/RestDAOHandler", flags: ['node'] },
  { name: "foam/net/node/Server", flags: ['node'] },
  { name: "foam/classloader/ClassLoader", flags: ['debug'] },
  { name: "foam/classloader/OrDAO", flags: ['debug'] },
  { name: "foam/classloader/WebModelFileDAO", flags: ['web', 'debug'] },
  { name: "foam/classloader/NodeModelFileDAO", flags: ['node', 'debug'] },
  { name: "foam/classloader/NodeJsModelExecutor", flags: ['node', 'debug'] },
  { name: "foam/parsers/html/lib" },
  { name: "foam/parsers/html/Attribute" },
  { name: "foam/parsers/html/TagType" },
  { name: "foam/parsers/html/Tag" },
  { name: "foam/parsers/html/HTMLLexer" },
  { name: "foam/core/ContextAware", flags: ['java'] },
  { name: "foam/dao/history/PropertyUpdate" },
  { name: "foam/dao/history/HistoryRecord" },
  { name: "foam/mop/MOP" },
  { name: "foam/mop/MOPJava", flags: ['java'] },
]);
<|endoftext|>


<commit_before>export default class MicroEmitter {
  constructor() {
    this._listeners = {};
  }

  /**
   * Adds a listener function to the specified event.
   * @param {String} type
   * @param {Function} listener
   * @param {Boolean} once
   */
  _addListener(type, listener, once) {
    this._listeners[type] = this._listeners[type] || [];
    this._listeners[type].push({ listener: listener, once: once });
    return this;
  }

  /**
   * Adds a listener function to the specified event.
   * @param {String} type
   * @param {Function} listener
   * @return {Object} Current instance of MicroEmitter for chaining.
   */
  addListener(type, listener) {
    return this._addListener(type, listener, false);
  }

  /* Alias of addListener */
  on(type, listener) {
    return this.addListener(type, listener);
  }

  addOnceListener(type, listener) {
    return this._addListener(type, listener, true);
  }

  /* Alias of addOnceListener */
  once(type, listener) {
    return this.addOnceListener(type, listener);
  }

  /**
   * Removes a listener function to the specified event.
   * @param {String} type
   * @param {Function} listener
   * @return {Object} Current instance of MicroEmitter for chaining.
   */
  removeListener(type, listener) { // alias
    let isRemoved = false;

    if (!this._listeners[type].length) return this;
    if (!listener) {
      delete this._listeners[type];
      return this;
    }
    for (let index = 0; index < this._listeners[type].length; index++) {
      if (this._listeners[type][index].listener === listener) {
        this._listeners[type].splice(index, 1);
        index--;
        isRemoved = true;
      }
    }
    if (!isRemoved) console.warn('not registered this listener.');
    return this;
  }

  /* Alias of removeListener */
  off(type, listener) {
    return this.removeListener(type, listener);
  }

  /**
   * Emits an specified event.
   * @param {String} type
   * @param {Object} payload
   * @return {Object} Current instance of MicroEmitter for chaining.
   */
  emit(type, payload) {
    if (!this._listeners[type]) return this;
    for (let index = 0; index < this._listeners[type].length; index++) {
      this._listeners[type][index].listener.apply(this, [payload]);
      if (this._listeners[type][index].once) {
        this.removeListener(type, this._listeners[type][index].listener);
        index--;
      }
    }
    return this;
  }

  /* Alias of emit */
  trigger(type, payload) {
    return this.emit(type, payload);
  }
}
<commit_msg>Refactor emit<commit_after>export default class MicroEmitter {
  constructor() {
    this._listeners = {};
  }

  /**
   * Adds a listener function to the specified event.
   * @param {String} type
   * @param {Function} listener
   * @param {Boolean} once
   */
  _addListener(type, listener, once) {
    this._listeners[type] = this._listeners[type] || [];
    this._listeners[type].push({ listener: listener, once: once });
    return this;
  }

  /**
   * Adds a listener function to the specified event.
   * @param {String} type
   * @param {Function} listener
   * @return {Object} Current instance of MicroEmitter for chaining.
   */
  addListener(type, listener) {
    return this._addListener(type, listener, false);
  }

  /* Alias of addListener */
  on(type, listener) {
    return this.addListener(type, listener);
  }

  addOnceListener(type, listener) {
    return this._addListener(type, listener, true);
  }

  /* Alias of addOnceListener */
  once(type, listener) {
    return this.addOnceListener(type, listener);
  }

  /**
   * Removes a listener function to the specified event.
   * @param {String} type
   * @param {Function} listener
   * @return {Object} Current instance of MicroEmitter for chaining.
   */
  removeListener(type, listener) { // alias
    let isRemoved = false;

    if (!this._listeners[type].length) return this;
    if (!listener) {
      delete this._listeners[type];
      return this;
    }
    for (let index = 0; index < this._listeners[type].length; index++) {
      if (this._listeners[type][index].listener === listener) {
        this._listeners[type].splice(index, 1);
        index--;
        isRemoved = true;
      }
    }
    if (!isRemoved) console.warn('not registered this listener.');
    return this;
  }

  /* Alias of removeListener */
  off(type, listener) {
    return this.removeListener(type, listener);
  }

  /**
   * Emits an specified event.
   * @param {String} type
   * @param {Object} payload
   * @return {Object} Current instance of MicroEmitter for chaining.
   */
  emit(type, payload) {
    if (!this._listeners[type]) return this;
    this._listeners[type].forEach((_listener) => {
      _listener.listener.apply(this, [payload]);
      if (_listener.once) {
        this.removeListener(type, _listener.listener);
      }
    });
    return this;
  }

  /* Alias of emit */
  trigger(type, payload) {
    return this.emit(type, payload);
  }
}
<|endoftext|>


<commit_before>/*
 * FRAME module/Object that consists of Core methods
 * @author Zafar Saleem
 */
var FRAME = {
	/**
	 * Main object that consists details for all modules upon registering.
	 * Modules are stored as
	 * modulesData: {
	 * 		modules: {
	 *			nameofmodule: object
	 * 		}
	 * }
	 */
	modulesData: {},

	/**
	 * Register method registers modules and stores them in
	 * modulesData object.
	 * @param {string} name of module
	 * @param {object} object of module
	 * @return {}
	 */
	register: function (module, obj) {
		if (this._isString(module) && this._isObject(obj)) {
			if (!this._isMethod(obj.init) && !this._isMethod(obj.destroy)) {
				this._log(3, 'Module does not have init and/or destroy methods');
				return;
			}
			// If modules object inside modulesData does not exist then create one
			if (typeof this.modulesData.modules === 'undefined') this.modulesData['modules'] = {};
			this.modulesData.modules[module] = obj; // Store module's object inside modulesData.modules

			if (typeof this.modulesData.$container === 'undefined') this.modulesData['$container'] = {};
			this.modulesData['$container'] = $('#' + module);

			if (obj.events && typeof obj.events === 'object') {
				FRAME.AggregatedEvents.init(obj);
			}
		} else {
			this._log(3, 'Module name should be String & obj should be Object');
		}
	},

	/**
	 * This method initialize single module stored in modulesData: {}
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	start: function (module) {
		if (this._isMethod(module)) return;
		module.init.bind(module).apply();
	},

	/**
	 * This method initializes all modules stored in modulesData: {}
	 * by calling start method
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	startAll: function () {
		var modules = this.modulesData.modules;

		if (typeof modules === 'undefined') return;
		if (Object.keys(modules).length <= 0) return; // if there are no modules registered then do nothing
		for (var keys in modules) {
			if (!modules.hasOwnProperty(keys)) return;
			this.start(modules[keys]);
		}
	},

	/**
	 * This method stop initialization of single modules stored in modulesData: {}
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	stop: function (module) {
		if (this._isMethod(module)) return;
		module.destory.bind(module).apply();
	},

	/**
	 * This method stop initialization of all modules stored in modulesData: {}
	 * by calling stop method
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	stopAll: function () {
		var modules = this.modulesData.modules;

		if (typeof modules === 'undefined') return;
		// if there are no modules registered then do nothing
		if (Object.keys(modules).length <= 0) return;
		for (var keys in modules) {
			if (!modules.hasOwnProperty(keys)) return;
			this.stop(modules[keys]);
		}
	},

	/**
	 * Object that adds events to selectors and call callback functions
	 * in a module. This modules is for following events object
	 * events: {
	 *		'click #selector': 'callback'
	 * }
	 */
	AggregatedEvents: {
		config: {
			context: null,
			callback: null
		},

		/**
		 * constructor function that initialize AggregatedEvents object,
		 * it gets callback function from events object and store it in config.callback,
		 * then calls applyEvents method.
		 * @param {object} context of modules where events object is defined
		 */
		init: function (context) {
			var events = context.events, keys;
			if (!FRAME._isObject(events)) return;

			this.config.context = context;
			for (keys in events) {
				if (!events.hasOwnProperty(keys)) return;
				this.config.callback = context[events[keys]];
	    		if (!FRAME._isMethod(this.config.callback)) return;
	    		this.applyEvents(keys);
			}
		},

		/**
		 * Checks for multiple selectors, if given then seperate them and put them
		 * in an array then bind events to all those selectors.
		 * If single selector is given then apply event to that selector.
		 * @param {string} properties of events object
		 * @return {}
		 */
		applyEvents: function (keys) {
			var i, len, selectors = this.getSelectors(keys.split(" "));

			if (selectors.length === 1) {
				this.bindEvents(keys.split(" ")[0], keys.split(" ")[1]);
				return;
			}

			for (i = 0, len = selectors.length; i < len; i++) {
				if (selectors[i] === 0) continue;
				this.bindEvents(keys.split(" ")[0], selectors[i]);
			}
		},

		/**
		 * It binds event to selector and call callback function
		 * @param {evt} event name e.g. click, hover etc that needs to attached to selector
		 * @param {string} selector on which event needs to be attached.
		 */
		bindEvents: function (evt, selector) {
	      	$(document).on(evt, selector, this.config.callback.bind(this.config.context));
	    },

		getSelectors: function (arr) {
			return arr.filter(function (item, index) {
				return (index !== 0) || item;
			});
	    }
	},

	/**
	 * Pub/Sub system that stores events in object and then triggers them when
	 * requires.
	 */
	Events: {
		eventsData: {}, // all events are stored here

		/**
		 * Stores events and context in eventsData object as key value pair
		 * @param {String} Event name
		 * @param {Object} Context(this) to module from where this events is triggered
		 * @return {}
		 */
		trigger: function (events, context) {
			if (!events && typeof events !== 'string') return;
			if (this.eventsData.hasOwnProperty(events)) {
				FRAME._log(2, 'This event name is already taken!');
				return;
			}
			this.eventsData[events] = context;
		},

		/**
		 * Calls events when required
		 * @param {String} Event name
		 * @param {Function} Callback function that needs to be called upon
		 * @param {Object} Context(this) to module from where listen() function id called
		 * @return {}
		 */
		listen: function (events, callback, context) {
			if (!events && typeof events !== 'string') return;
			if (this.eventsData.hasOwnProperty(events)) {
				if (typeof callback !== 'function') return;
				callback.bind(this.getContext(this.eventsData[events], context)).apply();
			}
		},

		/**
		 * Get context
		 * @param {Object} Context(this) to module from where this events is triggered
		 * @return {}
		 */
		getContext: function (context, module) {
			if (context && typeof context === 'object') return context;
			if (module && typeof module === 'object') return module;
		}
	},

	/**
	 * Check if paramter is a function
	 * @private
	 * @param {Function}
	 * @return {Boolean}
	 */
	_isMethod: function (method) {
		return (method && typeof method === 'function');
	},

	/**
	 * Check if paramter is an Object
	 * @private
	 * @param {Object}
	 * @return {Boolean}
	 */
	_isObject: function (object) {
		return (object && typeof object === 'object');
	},

	/**
	 * Check if paramter is a String
	 * @private
	 * @param {String}
	 * @return {Boolean}
	 */
	_isString: function (str) {
		return (str && typeof str === 'string');
	},

	/**
	 * Log function
	 * @private
	 * @param {Number} 1-3
	 * @param {String} Message
	 */
	_log: function (severity, message) {
		console[(severity === 1 ? 'log' : (severity === 2) ? 'warn' : 'error')](message);
	}
};
<commit_msg>Added createElement methods to frame API<commit_after>/*
 * FRAME module/Object that consists of Core methods
 * @author Zafar Saleem
 */
var FRAME = {
	/**
	 * Main object that consists details for all modules upon registering.
	 * Modules are stored as
	 * modulesData: {
	 * 		modules: {
	 *			nameofmodule: object
	 * 		}
	 * }
	 */
	modulesData: {},

	/**
	 * Register method registers modules and stores them in
	 * modulesData object.
	 * @param {string} name of module
	 * @param {object} object of module
	 * @return {}
	 */
	register: function (module, obj) {
		if (this._isString(module) && this._isObject(obj)) {
			if (!this._isMethod(obj.init) && !this._isMethod(obj.destroy)) {
				this._log(3, 'Module does not have init and/or destroy methods');
				return;
			}
			// If modules object inside modulesData does not exist then create one
			if (typeof this.modulesData.modules === 'undefined') this.modulesData['modules'] = {};
			this.modulesData.modules[module] = obj; // Store module's object inside modulesData.modules

			if (typeof this.modulesData.$container === 'undefined') this.modulesData['$container'] = {};
			this.modulesData['$container'] = $('#' + module);

			if (obj.events && typeof obj.events === 'object') {
				FRAME.AggregatedEvents.init(obj);
			}
		} else {
			this._log(3, 'Module name should be String & obj should be Object');
		}
	},

	/**
	 * This method initialize single module stored in modulesData: {}
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	start: function (module) {
		if (this._isMethod(module)) return;
		module.init.bind(module).apply();
	},

	/**
	 * This method initializes all modules stored in modulesData: {}
	 * by calling start method
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	startAll: function () {
		var modules = this.modulesData.modules;

		if (typeof modules === 'undefined') return;
		if (Object.keys(modules).length <= 0) return; // if there are no modules registered then do nothing
		for (var keys in modules) {
			if (!modules.hasOwnProperty(keys)) return;
			this.start(modules[keys]);
		}
	},

	/**
	 * This method stop initialization of single modules stored in modulesData: {}
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	stop: function (module) {
		if (this._isMethod(module)) return;
		module.destory.bind(module).apply();
	},

	/**
	 * This method stop initialization of all modules stored in modulesData: {}
	 * by calling stop method
	 * @param {object} Module that iscludes all methods
	 * @return {}
	 */
	stopAll: function () {
		var modules = this.modulesData.modules;

		if (typeof modules === 'undefined') return;
		// if there are no modules registered then do nothing
		if (Object.keys(modules).length <= 0) return;
		for (var keys in modules) {
			if (!modules.hasOwnProperty(keys)) return;
			this.stop(modules[keys]);
		}
	},

	createElement: function (el, config) {
        var i, text, child,
        el = this._create(el);
        if (!config) return;
        if (config.children && this._isArray(config.children)) {
            i = 0;
            while(child = config.children[i]) {
                el.appendChild(child);
                i++;
            }
            delete config.children;
        }
        if (config.text) {
            el.appendChild(document.createTextNode(config.text));
            delete config.text;
        }
        this._applyAttrs(el, config);
        return el;
    },

	/**
	 * Object that adds events to selectors and call callback functions
	 * in a module. This modules is for following events object
	 * events: {
	 *		'click #selector': 'callback'
	 * }
	 */
	AggregatedEvents: {
		config: {
			context: null,
			callback: null
		},

		/**
		 * constructor function that initialize AggregatedEvents object,
		 * it gets callback function from events object and store it in config.callback,
		 * then calls applyEvents method.
		 * @param {object} context of modules where events object is defined
		 */
		init: function (context) {
			var events = context.events, keys;
			if (!FRAME._isObject(events)) return;

			this.config.context = context;
			for (keys in events) {
				if (!events.hasOwnProperty(keys)) return;
				this.config.callback = context[events[keys]];
	    		if (!FRAME._isMethod(this.config.callback)) return;
	    		this.applyEvents(keys);
			}
		},

		/**
		 * Checks for multiple selectors, if given then seperate them and put them
		 * in an array then bind events to all those selectors.
		 * If single selector is given then apply event to that selector.
		 * @param {string} properties of events object
		 * @return {}
		 */
		applyEvents: function (keys) {
			var i, len, selectors = this.getSelectors(keys.split(" "));

			if (selectors.length === 1) {
				this.bindEvents(keys.split(" ")[0], keys.split(" ")[1]);
				return;
			}

			for (i = 0, len = selectors.length; i < len; i++) {
				if (selectors[i] === 0) continue;
				this.bindEvents(keys.split(" ")[0], selectors[i]);
			}
		},

		/**
		 * It binds event to selector and call callback function
		 * @param {evt} event name e.g. click, hover etc that needs to attached to selector
		 * @param {string} selector on which event needs to be attached.
		 */
		bindEvents: function (evt, selector) {
	      	$(document).on(evt, selector, this.config.callback.bind(this.config.context));
	    },

		getSelectors: function (arr) {
			return arr.filter(function (item, index) {
				return (index !== 0) || item;
			});
	    }
	},

	/**
	 * Pub/Sub system that stores events in object and then triggers them when
	 * requires.
	 */
	Events: {
		eventsData: {}, // all events are stored here

		/**
		 * Stores events and context in eventsData object as key value pair
		 * @param {String} Event name
		 * @param {Object} Context(this) to module from where this events is triggered
		 * @return {}
		 */
		trigger: function (events, context) {
			if (!events && typeof events !== 'string') return;
			if (this.eventsData.hasOwnProperty(events)) {
				FRAME._log(2, 'This event name is already taken!');
				return;
			}
			this.eventsData[events] = context;
		},

		/**
		 * Calls events when required
		 * @param {String} Event name
		 * @param {Function} Callback function that needs to be called upon
		 * @param {Object} Context(this) to module from where listen() function id called
		 * @return {}
		 */
		listen: function (events, callback, context) {
			if (!events && typeof events !== 'string') return;
			if (this.eventsData.hasOwnProperty(events)) {
				if (typeof callback !== 'function') return;
				callback.bind(this.getContext(this.eventsData[events], context)).apply();
			}
		},

		/**
		 * Get context
		 * @param {Object} Context(this) to module from where this events is triggered
		 * @return {}
		 */
		getContext: function (context, module) {
			if (context && typeof context === 'object') return context;
			if (module && typeof module === 'object') return module;
		}
	},

	/**
	 * Check if paramter is a function
	 * @private
	 * @param {Function}
	 * @return {Boolean}
	 */
	_isMethod: function (method) {
		return (method && typeof method === 'function');
	},

	/**
	 * Check if paramter is an Object
	 * @private
	 * @param {Object}
	 * @return {Boolean}
	 */
	_isObject: function (object) {
		return (object && typeof object === 'object');
	},

	/**
	 * Check if paramter is a String
	 * @private
	 * @param {String}
	 * @return {Boolean}
	 */
	_isString: function (str) {
		return (str && typeof str === 'string');
	},

	/**
	 * Log function
	 * @private
	 * @param {Number} 1-3
	 * @param {String} Message
	 */
	_log: function (severity, message) {
		console[(severity === 1 ? 'log' : (severity === 2) ? 'warn' : 'error')](message);
	}
};
<|endoftext|>


<commit_before>splasha.innerHTML = "Prossimo incontro: 31 maggio - prof. Frolli";
splashb.innerHTML = "Prossimo incontro: 31 maggio - prof. Frolli";
splashc.innerHTML = "Prossimo incontro: 31 maggio - prof. Frolli";
<commit_msg>Update splash.js<commit_after>splasha.innerHTML = "Prossimo incontro: 31 maggio - prof. Frolli
Nuovo Badge in palio: Badge navigatore.";
splashb.innerHTML = "Prossimo incontro: 31 maggio - prof. Frolli
Nuovo Badge in palio: Badge navigatore.";
splashc.innerHTML = "Prossimo incontro: 31 maggio - prof. Frolli
Nuovo Badge in palio: Badge navigatore.";
<|endoftext|>


<commit_before>/**
 * If the click happened outside our element, pass it along, otherwise stop!
 *
 * @param  {Function} handleEvent Click handler.
 * @param  {Object}   e           Click/touch Event.
 * @return {void}
 */
const handleClick = (handleEvent, e) => {
    let level = 0;

    for (let target = e.target; target; target = target.parentNode) {
        let found = this.elements.indexOf(target) > -1;

        if (found) {
            return;
        }

        level++;
    }

    handleEvent(e);
};

/**
 * @class     OutsideClick
 * @classdesc Utility class for handling clicks and touches outside of a specific element.
 *
 * @param {Array} elements DOM Nodes.
 */
class OutsideClick {

    constructor (...elements) {
        this.elements = elements;
        this.handlers = [];
    }

    /**
     * Add an event handler.
     *
     * @param  {Function} eventHandler Click handler.
     * @return {void}
     */
    addHandler (eventHandler) {
        let fn = handleClick.bind(this, eventHandler);
        this.handlers.push(fn);

        document.addEventListener('mousedown', fn);
        document.addEventListener('touchstart', fn);

        return fn;
    }

    /**
     * Remove an event handler.
     *
     * @param  {Function} eventHandler Click handler.
     * @return {Boolean} true on success
     */
    removeHandler (eventHandler) {
        let index = this.handlers.indexOf(eventHandler);

        if (index < 0) {
            return false;
        }

        this.handlers.splice(index, 1);

        document.removeEventListener('mousedown', eventHandler);
        document.removeEventListener('touchstart', eventHandler);
    }

    /**
     * Convenience method for remove all outside event handlers on the relevant element.
     *
     * @return {void}
     */
    removeAllHandlers () {
        this.handlers.forEach((elem) => {
            this.removeHandler(elem);
        });
    }

}

module.exports = OutsideClick;
<commit_msg>reverting to the original api<commit_after>/**
 * @class     OutsideClick
 * @classdesc Utility class for handling clicks and touches outside of a specific element.
 *
 * @param {Array} elements DOM Nodes.
 */
class OutsideClick {

    constructor (...elements) {
        this.elements = elements;
        this.handlers = [];
    }

    /**
     * Add an event handler.
     *
     * @param  {Function} eventHandler Click handler.
     * @return {void}
     */
    addHandler (eventHandler) {
        let fn = this._handleClick.bind(this, eventHandler);
        this.handlers.push(fn);

        document.addEventListener('mousedown', fn);
        document.addEventListener('touchstart', fn);

        return fn;
    }

    /**
     * Remove an event handler.
     *
     * @param  {Function} eventHandler Click handler.
     * @return {Boolean} true on success
     */
    removeHandler (eventHandler) {
        let index = this.handlers.indexOf(eventHandler);

        if (index < 0) {
            return false;
        }

        this.handlers.splice(index, 1);

        document.removeEventListener('mousedown', eventHandler);
        document.removeEventListener('touchstart', eventHandler);
    }

    /**
     * Convenience method for remove all outside event handlers on the relevant element.
     *
     * @return {void}
     */
    removeAllHandlers () {
        this.handlers.forEach((elem) => {
            this.removeHandler(elem);
        });
    }

    /**
     * If the click happened outside our element, pass it along, otherwise stop!
     *
     * @param  {Function} handleEvent Click handler.
     * @param  {Object}   e           Click/touch Event.
     * @return {void}
     */
    _handleClick (handleEvent, e) {
        let level = 0;

        for (let target = e.target; target; target = target.parentNode) {
            let found = this.elements.indexOf(target) > -1;

            if (found) {
                return;
            }

            level++;
        }

        handleEvent(e);
    }
}

module.exports = OutsideClick;
<|endoftext|>


<commit_before>'use strict';

function check(){
    // Check if every button has correct solution on it.
    var win = true;
    var loop_counter = 80;
    do{
        if(document.getElementById(loop_counter).value != puzzle[loop_counter]){
            win = false;
            break;
        }
    }while(loop_counter--);

    window.alert(
      win
        ? 'Correct! You win!'
        : 'Incorrect, try again.'
    );
}

function display_number_select(id){
    // Reset button zIndex values.
    var loop_counter = 80;
    do{
        document.getElementById(loop_counter).style.zIndex = 0;
    }while(loop_counter--);

    if(selected_button === -1
      || selected_button != id){
        selected_button = id;

        // Increase zIndex of selected button.
        document.getElementById(selected_button).style.zIndex = 2;

        // Display number-select behind selected button.
        update_number_select(id);
        document.getElementById('number-select').style.display = 'block';

    }else{
        // Hide number select.
        selected_button = -1;
        document.getElementById('number-select').style.display = 'none';
    }
}

function generate_puzzle(skip){
    if(!skip
      && !window.confirm('Generate new puzzle?')){
        return;
    }

    save();

    document.getElementById('game-area').style.marginTop =
      parseInt(document.getElementById('y-margin').value)
      + 'px';

    var first = 0;
    var second = 0;
    var which = 0;

    // Base sudoku puzzle.
    puzzle = [
      8,7,6, 5,4,3, 2,1,9,
      5,4,3, 2,1,9, 8,7,6,
      2,1,9, 8,7,6, 5,4,3,

      7,6,5, 4,3,2, 1,9,8,
      4,3,2, 1,9,8, 7,6,5,
      1,9,8, 7,6,5, 4,3,2,

      6,5,4, 3,2,1, 9,8,7,
      3,2,1, 9,8,7, 6,5,4,
      9,8,7, 6,5,4, 3,2,1,
    ];

    // Switch all instances of two random numbers 100 times.
    var loop_counter = 99;
    do{
        // Pick two different numbers between 1 and 9.
        first = Math.ceil(Math.random() * 9);
        do{
            second = Math.ceil(Math.random() * 9);
       }while(first === second);

        // Iterate through all buttons and switch those two numbers.
        times = 80;
        do{
            if(puzzle[times] === first){
                puzzle[times] = second;

            }else if(puzzle[times] === second){
                puzzle[times] = first;
            }
        }while(times--);
    }while(loop_counter--);

    // Switch columns between different blocks of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick a column number to switch.
        which = Math.floor(Math.random() * 3);

        // Pick two different blocks of 3 columns to switch the selected column number between.
        first = Math.floor(Math.random() * 3);
        do{
            second = Math.floor(Math.random() * 3);
        }while(first === second);

        // Iterate through each value in the selected column.
        // Swap them between the two selected blocks of 3 columns.
        times = 8;
        do{
            var temp = puzzle[9 * times + 3 * first + which];
            puzzle[9 * times + 3 * first + which] = puzzle[9 * times + 3 * second + which];
            puzzle[9 * times + 3 * second + which] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch columns within a block of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick the block of 3 columns in which to switch two columns.
        which = Math.floor(Math.random() * 3);

        // Pick two different columns to switch.
        first = Math.floor(Math.random() * 3);
        do{
            second = Math.floor(Math.random() * 3);
        }while(first === second);

        // Iterate through each value and swap the values between the two selected columns.
        times = 8;
        do{
            var temp = puzzle[9 * times + 3 * which + first];
            puzzle[9 * times + 3 * which + first] = puzzle[9 * times + 3 * which + second];
            puzzle[9 * times + 3 * which + second] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch random rows within a block of 3 rows 100 times.
    loop_counter = 99;
    do{
        // Pick one of the 3 blocks of 3 rows.
        which = Math.floor(Math.random() * 3);

        // Pick two different rows.
        first = Math.floor(Math.random() * 3);
        do{
            second = Math.floor(Math.random() * 3);
        }while(first === second);

        // Iterate through each value and swap the values between the two selected rows.
        times = 8;
        do{
            var temp = puzzle[which * 27 + first * 9 + times];
            puzzle[which * 27 + first * 9 + times] = puzzle[which * 27 + second * 9 + times];
            puzzle[which * 27 + second * 9 + times] = temp;
        }while(times--);
    }while(loop_counter--);

    // Reset all buttons.
    loop_counter = 80;
    do{
        var element = document.getElementById(loop_counter);
        element.disabled = false;
        element.style.background = '#333';
        element.style.color = '#aaa';
        element.value = '';
    }while(loop_counter--);

    // Add solutions to some random buttons.
    loop_counter = document.getElementById('locked').value - 1;
    if(loop_counter >= 0){
        do{
            first = Math.floor(Math.random() * 81);
            var first_element = document.getElementById(first);
            var element_80 = document.getElementById(80 - first);

            first_element.disabled = true;
            element_80.disabled = true;

            first_element.style.background = '#777';
            element_80.style.background = '#777';

            first_element.style.color = '#000';
            element_80.style.color = '#000';

            first_element.value = puzzle[first];
            element_80.value = puzzle[80 - first];
        }while(loop_counter--);
    }
}

function reset(){
    if(!window.confirm('Reset settings?')){
        return;
    }

    var ids = {
      'audio-volume': 1,
      'locked': 15,
      'y-margin': 50,
    };
    for(var id in ids){
        document.getElementById(id).value = ids[id];
    }

    save();
}

// Save settings into window.localStorage if they differ from default.
function save(){
    var ids = {
      'audio-volume': 1,
      'locked': 15,
      'y-margin': 50,
    };
    for(var id in ids){
        var value = document.getElementById(id).value;
        if(value == ids[id]
          || isNaN(value)){
            document.getElementById(id).value = ids[id];
            window.localStorage.removeItem('Sudoku.htm-' + id);

        }else{
            window.localStorage.setItem(
              'Sudoku.htm-' + id,
              value
            );
        }
    }
}

function select_number(number){
    document.getElementById(selected_button).value = number > 0
      ? number
      : '';
    selected_button = -1;
    document.getElementById('number-select').style.display = 'none';
}

function settings_toggle(state){
    state = state == void 0
      ? document.getElementById('settings-button').value === '+'
      : state;

    if(state){
        document.getElementById('settings').style.display = 'inline-block';
        document.getElementById('settings-button').value = '-';

    }else{
        document.getElementById('settings').style.display = 'none';
        document.getElementById('settings-button').value = '+';
    }
}

function update_number_select(id){
    // Make sure the number select box doesn't go past the left/right edges.
    var xpos = document.getElementById(id).offsetLeft - 50 - window.pageXOffset;
    if(xpos < 0){
        xpos = 0;

    }else if(xpos > window.innerWidth - 150){
        xpos = window.innerWidth - 150;
    }

    var number_select = document.getElementById('number-select');
    number_select.style.left = xpos + 'px';

    // There is no worry of the number select box going past the top/bottom edges.
    number_select.style.top  =
      (document.getElementById(id).offsetTop  - 50 - window.pageYOffset)
      + 'px';
}

var puzzle = [];
var selected_button = -1;
var times = 0;

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // G: generate a new puzzle.
    if(key === 71){
        generate_puzzle(false);

    // C: check puzzle correctness.
    }else if(key === 67){
        check();

    // ESC: hide number selection, if visible.
    }else if(selected_button != -1
      && key === 27){
        display_number_select(selected_button);

    // +: show settings.
    }else if(key === 187){
        settings_toggle(true);

    // -: hide settings.
    }else if(key === 189){
        settings_toggle(false);
    }
};

window.onload = function(){
    document.getElementById('audio-volume').value =
      window.localStorage.getItem('Sudoku.htm-audio-volume') !== null
        ? parseFloat(window.localStorage.getItem('Sudoku.htm-audio-volume'))
        : 1;
    document.getElementById('locked').value =
      window.localStorage.getItem('Sudoku.htm-locked') !== null
        ? parseFloat(window.localStorage.getItem('Sudoku.htm-locked'))
        : 15;
    document.getElementById('y-margin').value =
      window.localStorage.getItem('Sudoku.htm-y-margin') !== null
        ? parseFloat(window.localStorage.getItem('Sudoku.htm-y-margin'))
        : 50;

    // Create buttons and add to game-area.
    var loop_counter = 80;
    var output = '';

    do{
        output +=
          '<input class=buttons id='
          + loop_counter
          + ' onclick=display_number_select('
          + loop_counter
          + ') style=background:#333 type=button>';
        if(loop_counter % 9 === 0
          && loop_counter !== 0){
            output += '<br>';
        }
    }while(loop_counter--);
    document.getElementById('game-area').innerHTML = output;

    // Setup margins.
    loop_counter = 8;
    do{
        document.getElementById(3 + 9 * loop_counter).style.marginRight = '5px';
        document.getElementById(27 + loop_counter).style.marginBottom = '5px';
        document.getElementById(54 + loop_counter).style.marginBottom = '5px';
        document.getElementById(6 + 9 * loop_counter).style.marginRight = '5px';
    }while(loop_counter--);

    generate_puzzle(true);
};

window.onresize
  = window.onscroll = function(e){
    // Update position of number select if visible.
    if(selected_button != -1){
        update_number_select(selected_button);
    }
};
<commit_msg>added radix to parseInt()<commit_after>'use strict';

function check(){
    // Check if every button has correct solution on it.
    var win = true;
    var loop_counter = 80;
    do{
        if(document.getElementById(loop_counter).value != puzzle[loop_counter]){
            win = false;
            break;
        }
    }while(loop_counter--);

    window.alert(
      win
        ? 'Correct! You win!'
        : 'Incorrect, try again.'
    );
}

function display_number_select(id){
    // Reset button zIndex values.
    var loop_counter = 80;
    do{
        document.getElementById(loop_counter).style.zIndex = 0;
    }while(loop_counter--);

    if(selected_button === -1
      || selected_button != id){
        selected_button = id;

        // Increase zIndex of selected button.
        document.getElementById(selected_button).style.zIndex = 2;

        // Display number-select behind selected button.
        update_number_select(id);
        document.getElementById('number-select').style.display = 'block';

    }else{
        // Hide number select.
        selected_button = -1;
        document.getElementById('number-select').style.display = 'none';
    }
}

function generate_puzzle(skip){
    if(!skip
      && !window.confirm('Generate new puzzle?')){
        return;
    }

    save();

    document.getElementById('game-area').style.marginTop =
      parseInt(
        document.getElementById('y-margin').value,
        10
      ) + 'px';

    var first = 0;
    var second = 0;
    var which = 0;

    // Base sudoku puzzle.
    puzzle = [
      8,7,6, 5,4,3, 2,1,9,
      5,4,3, 2,1,9, 8,7,6,
      2,1,9, 8,7,6, 5,4,3,

      7,6,5, 4,3,2, 1,9,8,
      4,3,2, 1,9,8, 7,6,5,
      1,9,8, 7,6,5, 4,3,2,

      6,5,4, 3,2,1, 9,8,7,
      3,2,1, 9,8,7, 6,5,4,
      9,8,7, 6,5,4, 3,2,1,
    ];

    // Switch all instances of two random numbers 100 times.
    var loop_counter = 99;
    do{
        // Pick two different numbers between 1 and 9.
        first = Math.ceil(Math.random() * 9);
        do{
            second = Math.ceil(Math.random() * 9);
       }while(first === second);

        // Iterate through all buttons and switch those two numbers.
        times = 80;
        do{
            if(puzzle[times] === first){
                puzzle[times] = second;

            }else if(puzzle[times] === second){
                puzzle[times] = first;
            }
        }while(times--);
    }while(loop_counter--);

    // Switch columns between different blocks of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick a column number to switch.
        which = Math.floor(Math.random() * 3);

        // Pick two different blocks of 3 columns to switch the selected column number between.
        first = Math.floor(Math.random() * 3);
        do{
            second = Math.floor(Math.random() * 3);
        }while(first === second);

        // Iterate through each value in the selected column.
        // Swap them between the two selected blocks of 3 columns.
        times = 8;
        do{
            var temp = puzzle[9 * times + 3 * first + which];
            puzzle[9 * times + 3 * first + which] = puzzle[9 * times + 3 * second + which];
            puzzle[9 * times + 3 * second + which] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch columns within a block of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick the block of 3 columns in which to switch two columns.
        which = Math.floor(Math.random() * 3);

        // Pick two different columns to switch.
        first = Math.floor(Math.random() * 3);
        do{
            second = Math.floor(Math.random() * 3);
        }while(first === second);

        // Iterate through each value and swap the values between the two selected columns.
        times = 8;
        do{
            var temp = puzzle[9 * times + 3 * which + first];
            puzzle[9 * times + 3 * which + first] = puzzle[9 * times + 3 * which + second];
            puzzle[9 * times + 3 * which + second] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch random rows within a block of 3 rows 100 times.
    loop_counter = 99;
    do{
        // Pick one of the 3 blocks of 3 rows.
        which = Math.floor(Math.random() * 3);

        // Pick two different rows.
        first = Math.floor(Math.random() * 3);
        do{
            second = Math.floor(Math.random() * 3);
        }while(first === second);

        // Iterate through each value and swap the values between the two selected rows.
        times = 8;
        do{
            var temp = puzzle[which * 27 + first * 9 + times];
            puzzle[which * 27 + first * 9 + times] = puzzle[which * 27 + second * 9 + times];
            puzzle[which * 27 + second * 9 + times] = temp;
        }while(times--);
    }while(loop_counter--);

    // Reset all buttons.
    loop_counter = 80;
    do{
        var element = document.getElementById(loop_counter);
        element.disabled = false;
        element.style.background = '#333';
        element.style.color = '#aaa';
        element.value = '';
    }while(loop_counter--);

    // Add solutions to some random buttons.
    loop_counter = document.getElementById('locked').value - 1;
    if(loop_counter >= 0){
        do{
            first = Math.floor(Math.random() * 81);
            var first_element = document.getElementById(first);
            var element_80 = document.getElementById(80 - first);

            first_element.disabled = true;
            element_80.disabled = true;

            first_element.style.background = '#777';
            element_80.style.background = '#777';

            first_element.style.color = '#000';
            element_80.style.color = '#000';

            first_element.value = puzzle[first];
            element_80.value = puzzle[80 - first];
        }while(loop_counter--);
    }
}

function reset(){
    if(!window.confirm('Reset settings?')){
        return;
    }

    var ids = {
      'audio-volume': 1,
      'locked': 15,
      'y-margin': 50,
    };
    for(var id in ids){
        document.getElementById(id).value = ids[id];
    }

    save();
}

// Save settings into window.localStorage if they differ from default.
function save(){
    var ids = {
      'audio-volume': 1,
      'locked': 15,
      'y-margin': 50,
    };
    for(var id in ids){
        var value = document.getElementById(id).value;
        if(value == ids[id]
          || isNaN(value)){
            document.getElementById(id).value = ids[id];
            window.localStorage.removeItem('Sudoku.htm-' + id);

        }else{
            window.localStorage.setItem(
              'Sudoku.htm-' + id,
              value
            );
        }
    }
}

function select_number(number){
    document.getElementById(selected_button).value = number > 0
      ? number
      : '';
    selected_button = -1;
    document.getElementById('number-select').style.display = 'none';
}

function settings_toggle(state){
    state = state == void 0
      ? document.getElementById('settings-button').value === '+'
      : state;

    if(state){
        document.getElementById('settings').style.display = 'inline-block';
        document.getElementById('settings-button').value = '-';

    }else{
        document.getElementById('settings').style.display = 'none';
        document.getElementById('settings-button').value = '+';
    }
}

function update_number_select(id){
    // Make sure the number select box doesn't go past the left/right edges.
    var xpos = document.getElementById(id).offsetLeft - 50 - window.pageXOffset;
    if(xpos < 0){
        xpos = 0;

    }else if(xpos > window.innerWidth - 150){
        xpos = window.innerWidth - 150;
    }

    var number_select = document.getElementById('number-select');
    number_select.style.left = xpos + 'px';

    // There is no worry of the number select box going past the top/bottom edges.
    number_select.style.top  =
      (document.getElementById(id).offsetTop  - 50 - window.pageYOffset)
      + 'px';
}

var puzzle = [];
var selected_button = -1;
var times = 0;

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // G: generate a new puzzle.
    if(key === 71){
        generate_puzzle(false);

    // C: check puzzle correctness.
    }else if(key === 67){
        check();

    // ESC: hide number selection, if visible.
    }else if(selected_button != -1
      && key === 27){
        display_number_select(selected_button);

    // +: show settings.
    }else if(key === 187){
        settings_toggle(true);

    // -: hide settings.
    }else if(key === 189){
        settings_toggle(false);
    }
};

window.onload = function(){
    document.getElementById('audio-volume').value =
      window.localStorage.getItem('Sudoku.htm-audio-volume') !== null
        ? parseFloat(window.localStorage.getItem('Sudoku.htm-audio-volume'))
        : 1;
    document.getElementById('locked').value =
      window.localStorage.getItem('Sudoku.htm-locked') !== null
        ? parseFloat(window.localStorage.getItem('Sudoku.htm-locked'))
        : 15;
    document.getElementById('y-margin').value =
      window.localStorage.getItem('Sudoku.htm-y-margin') !== null
        ? parseFloat(window.localStorage.getItem('Sudoku.htm-y-margin'))
        : 50;

    // Create buttons and add to game-area.
    var loop_counter = 80;
    var output = '';

    do{
        output +=
          '<input class=buttons id='
          + loop_counter
          + ' onclick=display_number_select('
          + loop_counter
          + ') style=background:#333 type=button>';
        if(loop_counter % 9 === 0
          && loop_counter !== 0){
            output += '<br>';
        }
    }while(loop_counter--);
    document.getElementById('game-area').innerHTML = output;

    // Setup margins.
    loop_counter = 8;
    do{
        document.getElementById(3 + 9 * loop_counter).style.marginRight = '5px';
        document.getElementById(27 + loop_counter).style.marginBottom = '5px';
        document.getElementById(54 + loop_counter).style.marginBottom = '5px';
        document.getElementById(6 + 9 * loop_counter).style.marginRight = '5px';
    }while(loop_counter--);

    generate_puzzle(true);
};

window.onresize
  = window.onscroll = function(e){
    // Update position of number select if visible.
    if(selected_button != -1){
        update_number_select(selected_button);
    }
};
<|endoftext|>


<commit_before>(function() {
  var root = this,   // Root object, this is going to be the window for now
      document = this.document, // Safely store a document here for us to use
      editableNodes = document.querySelectorAll(".g-body article"),
      textMenu = document.querySelectorAll(".g-body .text-menu")[0],
      optionsNode = document.querySelectorAll(".g-body .text-menu .options")[0],
      urlInput = document.querySelectorAll(".g-body .text-menu .url-input")[0],

      previouslySelectedText,

      grande = {
        bind: function() {
          bindTextSelectionEvents();
          bindTextStylingEvents();
        },
        select: function() {
          triggerTextSelection();
        }
      },

      tagClassMap = {
        "b": "bold",
        "i": "italic",
        "h1": "header1",
        "h2": "header2",
        "a": "url",
        "blockquote": "quote"
      };

  function bindTextSelectionEvents() {
    var i,
        len,
        node;

    // Trigger on both mousedown and mouseup so that the click on the menu
    // feels more instantaneously active
    document.onmousedown = triggerTextSelection;
    document.onmouseup = function(event) {
      setTimeout(function() {
        triggerTextSelection(event);
      }, 1);
    };

    // Handle window resize events
    root.onresize = triggerTextSelection;

    urlInput.onblur = triggerUrlBlur;
    urlInput.onkeydown = triggerUrlSet;

    for (i = 0, len = editableNodes.length; i < len; i++) {
      node = editableNodes[i];
      node.onmousedown = node.onkeyup = node.onmouseup = triggerTextSelection;
      node.addEventListener('keyup', triggerTextParse, false);
    }
  }

  function iterateTextMenuButtons(callback) {
    var textMenuButtons = document.querySelectorAll(".g-body .text-menu button"),
        i,
        len,
        node;

    for (i = 0, len = textMenuButtons.length; i < len; i++) {
      node = textMenuButtons[i];

      (function(n) {
        callback(n);
      })(node);
    }
  }

  function bindTextStylingEvents() {
    iterateTextMenuButtons(function(node) {
      node.onmousedown = function(event) {
        triggerTextStyling(node);
      };
    });
  }

  function getFocusNode() {
    return root.getSelection().focusNode;
  }

  function reloadMenuState() {
    var className,
        focusNode = getFocusNode(),
        tagClass,
        reTag;

    iterateTextMenuButtons(function(node) {
      className = node.className;

      for (var tag in tagClassMap) {
        tagClass = tagClassMap[tag];
        reTag = new RegExp(tagClass);

        if (reTag.test(className)) {
          if (hasParentWithTag(focusNode, tag)) {
            node.className = tagClass + " active";
          } else {
            node.className = tagClass;
          }

          break;
        }
      }
    });
  }

  function triggerTextParse() {
    var sel = window.getSelection(),
        textProp,
        subject,
        insertedNode,
        unwrap,
        node,
        parent,
        range;

    if (!sel.isCollapsed) {
      return;
    }

    textProp = (sel.anchorNode.nodeType === 3) ? 'data' : 'innerText';
    subject = sel.anchorNode[textProp];

    if (subject.match(/^-\s/) && sel.anchorNode.parentNode.nodeName.toLocaleLowerCase() !== 'li') {
      document.execCommand('insertUnorderedList');
      sel.anchorNode[textProp] = sel.anchorNode[textProp].substring(2);

      insertedNode = sel.anchorNode;
      while (insertedNode.parentNode) {
        if (insertedNode.nodeName.toLowerCase() === 'ul') {
          break;
        }
        insertedNode = insertedNode.parentNode;
      }
    }

    if (subject.match(/^1\.\s/) && sel.anchorNode.parentNode.nodeName.toLocaleLowerCase() !== 'li') {
      document.execCommand('insertOrderedList');
      sel.anchorNode[textProp] = sel.anchorNode[textProp].substring(3);

      insertedNode = sel.anchorNode;
      while (insertedNode.parentNode) {
        if (insertedNode.nodeName.toLowerCase() === 'ol') {
          break;
        }
        insertedNode = insertedNode.parentNode;
      }
    }

    unwrap = insertedNode &&
            ['ul', 'ol'].indexOf(insertedNode.nodeName.toLocaleLowerCase()) >= 0 &&
            ['p', 'div'].indexOf(insertedNode.parentNode.nodeName.toLocaleLowerCase()) >= 0;

    if (unwrap) {
      node = sel.anchorNode;
      parent = insertedNode.parentNode;
      insertedNode.parentNode.parentNode.insertBefore(insertedNode, insertedNode.parentNode);
      parent.parentNode.removeChild(parent);

      range = document.createRange();
      range.setStart(node, 0);
      range.setEnd(node, 0);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }

  function triggerTextStyling(node) {
    var className = node.className,
        tagClass,
        reTag;

    for (var tag in tagClassMap) {
      tagClass = tagClassMap[tag];
      reTag = new RegExp(tagClass);

      if (reTag.test(className)) {
        switch(tag) {
          case "b":
          case "i":
            document.execCommand(tagClass, false);
            return;

          case "h1":
          case "h2":
          case "h3":
          case "blockquote":
            toggleFormatBlock(tag);
            return;

          case "a":
            toggleUrlInput();
            optionsNode.className = "options url-mode";
            return;
        }
      }
    }

    triggerTextSelection();
  }

  function triggerUrlBlur(event) {
    var url = urlInput.value;

    optionsNode.className = "options";
    window.getSelection().addRange(previouslySelectedText);

    document.execCommand("unlink", false);

    if (url === "") {
      return false;
    }

    if (!url.match("^(http|https)://")) {
      url = "http://" + url;
    }

    document.execCommand("createLink", false, url);

    urlInput.value = "";
  }

  function triggerUrlSet(event) {
    if (event.keyCode === 13) {
      event.preventDefault();
      event.stopPropagation();

      urlInput.blur();
    }
  }

  function toggleFormatBlock(tag) {
    if (hasParentWithTag(getFocusNode(), tag)) {
      document.execCommand("formatBlock", false, "p");
      document.execCommand("outdent");
    } else {
      document.execCommand("formatBlock", false, tag);
    }
  }

  function toggleUrlInput() {
    setTimeout(function() {
      var url = getParentHref(getFocusNode());

      if (typeof url !== "undefined") {
        urlInput.value = url;
      } else {
        document.execCommand("createLink", false, "/");
      }

      previouslySelectedText = window.getSelection().getRangeAt(0);

      urlInput.focus();
    }, 150);
  }

  function hasParentWithTag(node, nodeType) {
    while (node.parentNode) {
      if (node.nodeName.toLowerCase() === nodeType) {
        return true;
      }
      node = node.parentNode;
    }

    return false;
  }

  function getParentHref(node) {
    while (node.parentNode) {
      if (typeof node.href !== "undefined") {
        return node.href;
      }

      node = node.parentNode;
    }
  }

  function triggerTextSelection() {
      var selectedText = root.getSelection(),
          range,
          clientRectBounds;

      // The selected text is collapsed, push the menu out of the way
      if (selectedText.isCollapsed) {
        setTextMenuPosition(-999, -999);
      } else {
        range = selectedText.getRangeAt(0);
        clientRectBounds = range.getBoundingClientRect();

        // Every time we show the menu, reload the state
        reloadMenuState();
        setTextMenuPosition(
          clientRectBounds.top - 5 + root.pageYOffset,
          (clientRectBounds.left + clientRectBounds.right) / 2
        );
      }

  }

  function setTextMenuPosition(top, left) {
    textMenu.style.top = top + "px";
    textMenu.style.left = left + "px";
  }

  root.grande = grande;
}).call(this);
<commit_msg>bug: Fix event listener triggers on <article> element<commit_after>(function() {
  var root = this,   // Root object, this is going to be the window for now
      document = this.document, // Safely store a document here for us to use
      editableNodes = document.querySelectorAll(".g-body article"),
      textMenu = document.querySelectorAll(".g-body .text-menu")[0],
      optionsNode = document.querySelectorAll(".g-body .text-menu .options")[0],
      urlInput = document.querySelectorAll(".g-body .text-menu .url-input")[0],

      previouslySelectedText,

      grande = {
        bind: function() {
          bindTextSelectionEvents();
          bindTextStylingEvents();
        },
        select: function() {
          triggerTextSelection();
        }
      },

      tagClassMap = {
        "b": "bold",
        "i": "italic",
        "h1": "header1",
        "h2": "header2",
        "a": "url",
        "blockquote": "quote"
      };

  function bindTextSelectionEvents() {
    var i,
        len,
        node;

    // Trigger on both mousedown and mouseup so that the click on the menu
    // feels more instantaneously active
    document.onmousedown = triggerTextSelection;
    document.onmouseup = function(event) {
      setTimeout(function() {
        triggerTextSelection(event);
      }, 1);
    };
    document.onkeyup = triggerTextParse;

    // Handle window resize events
    root.onresize = triggerTextSelection;

    urlInput.onblur = triggerUrlBlur;
    urlInput.onkeydown = triggerUrlSet;

    for (i = 0, len = editableNodes.length; i < len; i++) {
      node = editableNodes[i];
      node.onmousedown = node.onkeyup = node.onmouseup = triggerTextSelection;
    }
  }

  function iterateTextMenuButtons(callback) {
    var textMenuButtons = document.querySelectorAll(".g-body .text-menu button"),
        i,
        len,
        node;

    for (i = 0, len = textMenuButtons.length; i < len; i++) {
      node = textMenuButtons[i];

      (function(n) {
        callback(n);
      })(node);
    }
  }

  function bindTextStylingEvents() {
    iterateTextMenuButtons(function(node) {
      node.onmousedown = function(event) {
        triggerTextStyling(node);
      };
    });
  }

  function getFocusNode() {
    return root.getSelection().focusNode;
  }

  function reloadMenuState() {
    var className,
        focusNode = getFocusNode(),
        tagClass,
        reTag;

    iterateTextMenuButtons(function(node) {
      className = node.className;

      for (var tag in tagClassMap) {
        tagClass = tagClassMap[tag];
        reTag = new RegExp(tagClass);

        if (reTag.test(className)) {
          if (hasParentWithTag(focusNode, tag)) {
            node.className = tagClass + " active";
          } else {
            node.className = tagClass;
          }

          break;
        }
      }
    });
  }

  function triggerTextParse(event) {
    var sel = window.getSelection(),
        textProp,
        subject,
        insertedNode,
        unwrap,
        node,
        parent,
        range;

    // FF will return sel.anchorNode to be the parentNode when the triggered keyCode is 13
    if (!sel.isCollapsed || sel.anchorNode.nodeName === "ARTICLE") {
      return;
    }

    if (sel.anchorNode.nodeType === Node.TEXT_NODE) {
      textProp = "data";
    } else {
      textProp = "innerText";
    }

    subject = sel.anchorNode[textProp];

    if (subject.match(/^-\s/) && sel.anchorNode.parentNode.nodeName !== 'LI') {
      document.execCommand('insertUnorderedList');
      sel.anchorNode[textProp] = sel.anchorNode[textProp].substring(2);

      insertedNode = sel.anchorNode;
      while (insertedNode.parentNode) {
        if (insertedNode.nodeName.toLowerCase() === 'ul') {
          break;
        }
        insertedNode = insertedNode.parentNode;
      }
    }

    if (subject.match(/^1\.\s/) && sel.anchorNode.parentNode.nodeName !== 'LI') {
      document.execCommand('insertOrderedList');
      sel.anchorNode[textProp] = sel.anchorNode[textProp].substring(3);

      insertedNode = sel.anchorNode;
      while (insertedNode.parentNode) {
        if (insertedNode.nodeName.toLowerCase() === 'ol') {
          break;
        }
        insertedNode = insertedNode.parentNode;
      }
    }

    unwrap = insertedNode &&
            ['ul', 'ol'].indexOf(insertedNode.nodeName.toLocaleLowerCase()) >= 0 &&
            ['p', 'div'].indexOf(insertedNode.parentNode.nodeName.toLocaleLowerCase()) >= 0;

    if (unwrap) {
      node = sel.anchorNode;
      parent = insertedNode.parentNode;
      insertedNode.parentNode.parentNode.insertBefore(insertedNode, insertedNode.parentNode);
      parent.parentNode.removeChild(parent);

      range = document.createRange();
      range.setStart(node, 0);
      range.setEnd(node, 0);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }

  function triggerTextStyling(node) {
    var className = node.className,
        tagClass,
        reTag;

    for (var tag in tagClassMap) {
      tagClass = tagClassMap[tag];
      reTag = new RegExp(tagClass);

      if (reTag.test(className)) {
        switch(tag) {
          case "b":
          case "i":
            document.execCommand(tagClass, false);
            return;

          case "h1":
          case "h2":
          case "h3":
          case "blockquote":
            toggleFormatBlock(tag);
            return;

          case "a":
            toggleUrlInput();
            optionsNode.className = "options url-mode";
            return;
        }
      }
    }

    triggerTextSelection();
  }

  function triggerUrlBlur(event) {
    var url = urlInput.value;

    optionsNode.className = "options";
    window.getSelection().addRange(previouslySelectedText);

    document.execCommand("unlink", false);

    if (url === "") {
      return false;
    }

    if (!url.match("^(http|https)://")) {
      url = "http://" + url;
    }

    document.execCommand("createLink", false, url);

    urlInput.value = "";
  }

  function triggerUrlSet(event) {
    if (event.keyCode === 13) {
      event.preventDefault();
      event.stopPropagation();

      urlInput.blur();
    }
  }

  function toggleFormatBlock(tag) {
    if (hasParentWithTag(getFocusNode(), tag)) {
      document.execCommand("formatBlock", false, "p");
      document.execCommand("outdent");
    } else {
      document.execCommand("formatBlock", false, tag);
    }
  }

  function toggleUrlInput() {
    setTimeout(function() {
      var url = getParentHref(getFocusNode());

      if (typeof url !== "undefined") {
        urlInput.value = url;
      } else {
        document.execCommand("createLink", false, "/");
      }

      previouslySelectedText = window.getSelection().getRangeAt(0);

      urlInput.focus();
    }, 150);
  }

  function hasParentWithTag(node, nodeType) {
    while (node.parentNode) {
      if (node.nodeName.toLowerCase() === nodeType) {
        return true;
      }
      node = node.parentNode;
    }

    return false;
  }

  function getParentHref(node) {
    while (node.parentNode) {
      if (typeof node.href !== "undefined") {
        return node.href;
      }

      node = node.parentNode;
    }
  }

  function triggerTextSelection() {
      var selectedText = root.getSelection(),
          range,
          clientRectBounds;

      // The selected text is collapsed, push the menu out of the way
      if (selectedText.isCollapsed) {
        setTextMenuPosition(-999, -999);
      } else {
        range = selectedText.getRangeAt(0);
        clientRectBounds = range.getBoundingClientRect();

        // Every time we show the menu, reload the state
        reloadMenuState();
        setTextMenuPosition(
          clientRectBounds.top - 5 + root.pageYOffset,
          (clientRectBounds.left + clientRectBounds.right) / 2
        );
      }
  }

  function setTextMenuPosition(top, left) {
    textMenu.style.top = top + "px";
    textMenu.style.left = left + "px";
  }

  root.grande = grande;
}).call(this);
<|endoftext|>


<commit_before>window.Tabata = (function (undefined) {
    'use strict';
    return function (opt) {
        var count;
        var timeout;
        var options = {
            name: 'time-number',
            bg: '.main'
        };

        for (var key in opt) {
            options[key] = opt[key];
        }

        var api = {
            init: initTabata,
            show: showTabata,
            hide: hideTabata,
            start: startTabata,
            stop: stopTabata
        };

        function initTabata () {
            options.count = Count({
                name: 'tabata',
                className: options.name,
                handler: '.time-cycle'
            }).init();

            return api;
        }

        function showTabata () {
            options.count.set(0).show();

            return api;
        }

        function hideTabata () {
            options.count.hide();

            return api;
        }

        function startTabata () {
            _train()
            return api;
        }

        function stopTabata () {
            _clear();
            return api;
        }

        function _clear () {
            clearInterval(timeout);
            document.querySelector(options.bg).classList.remove('positive');
            document.querySelector(options.bg).classList.remove('relax');
        }

        function _train () {
            _discount(20, 'positive', function () {
                _break();
            });
        }

        function _break () {
            _discount(10, 'relax', function () {
                _train();
            });
        }

        function _discount (p_limit, p_class, p_end) {
            options.count.set(0);
            _clear();
            timeout = setInterval(function () {
                var values = options.count.get();
                if (values[0] >= p_limit) {
                    document.querySelector(options.bg).classList.remove(p_class);
                    _clear();
                    p_end();
                } else {
                    values[0] += 1;
                    options.count.set(values);
                }
            }, 1000);
            document.querySelector(options.bg).classList.add(p_class);
        }

        return api;
    };
})();<commit_msg>change to discount not count for tabata<commit_after>window.Tabata = (function (undefined) {
    'use strict';
    return function (opt) {
        var count;
        var timeout;
        var options = {
            name: 'time-number',
            bg: '.main'
        };

        for (var key in opt) {
            options[key] = opt[key];
        }

        var api = {
            init: initTabata,
            show: showTabata,
            hide: hideTabata,
            start: startTabata,
            stop: stopTabata
        };

        function initTabata () {
            options.count = Count({
                name: 'tabata',
                className: options.name,
                handler: '.time-cycle'
            }).init();

            return api;
        }

        function showTabata () {
            options.count.set(0).show();

            return api;
        }

        function hideTabata () {
            options.count.hide();

            return api;
        }

        function startTabata () {
            _break()
            return api;
        }

        function stopTabata () {
            _clear();
            return api;
        }

        function _clear () {
            clearInterval(timeout);
            document.querySelector(options.bg).classList.remove('positive');
            document.querySelector(options.bg).classList.remove('relax');
        }

        function _train () {
            _discount(20, 'positive', function () {
                _break();
            });
        }

        function _break () {
            _discount(10, 'relax', function () {
                _train();
            });
        }

        function _discount (p_limit, p_class, p_end) {
            options.count.set(p_limit);
            _clear();
            timeout = setInterval(function () {
                var values = options.count.get();
                if (values[0] <= 0) {
                    document.querySelector(options.bg).classList.remove(p_class);
                    _clear();
                    p_end();
                } else {
                    values[0] -= 1;
                    options.count.set(values);
                }
            }, 1000);
            document.querySelector(options.bg).classList.add(p_class);
        }

        return api;
    };
})();<|endoftext|>


<commit_before>var Promise = require('promise');

var dataParser = require("./dataParser.js");
var schemaParser = require("./schemaParser.js");
var validator = require("./validator.js");
var shapeFinder = require("./shapeFinder.js");

var shexjs = require("shex");
var n3 = require("n3");

var DefaultBase = "";

function Validator(schemaText, dataText, callbacks, options) {
    this.callbacks = callbacks;
    this.options = options;

    this.updateSchema(location.origin + '/schema.shex', schemaText);
    this.updateData(dataText);

    // console.log("validator has instantiated");
    // console.log("callbacks:\n",callbacks);
    // console.log("options:\n",options);

}

Validator.prototype = {
    updateSchema: function (base, schemaText) {
        this.schema = parseSchema(base ,schemaText);
        // this.schema = schemaParser.parseSchema(schemaText);
        this.schema.done(this.callbacks.schemaParsed, this.callbacks.schemaParseError);
        // var _schema = shexjs.Parser.construct(DefaultBase).parse(schemaText);
        // console.log('UPDATING THE FUCKIGN Schema',this.schema, _schema);
    },
    updateData: function (dataText) {
        this.data = parseData(dataText);
        // this.data = dataParser.parseData(dataText);
        this.data.done(this.callbacks.dataParsed, this.callbacks.dataParseError);
    },
    findShapes: function () {
        var _this = this;
        return Promise.all([this.schema, this.data]).then(function (a) {
            console.log('showing shapes');
            console.log(this.schema);
            console.log(this.data);
        });
    },
    validate: function(startingNodes) {
        var _this = this;
        console.log('validate function',_this);
        return Promise.all([this.schema, this.data, this.options]).then(function (a) {
            console.log(a);
            var node = Object.keys(a[2].resourceShapeMap)[0];
            var result = shexjs.Validator.construct(a[0].schema).validate(a[1].db, node, a[2].resourceShapeMap[node]);
            console.log('validation results:',result);
            console.log();
            return validator.validate(
                a[0].schema,                       // Schema
                a[0].resolver,
                startingNodes,      // Starting Node
                a[1].db,                       // db
                a[1].resolver,
                _this.options.closedShapes,
                _this.callbacks.validationResult);
        });
    }
};

module.exports.Validator = Validator;

function parseData(dataText){
    return new Promise(function (resolve, reject) {

        var db = n3.Store();
        n3.Parser({documentIRI: DefaultBase, format: "text/turtle"}).parse(dataText, function (error, triple, prefixes) {
            if (error) {
                // throw Error("error parsing " + data + ": " + error);
                reject(parseN3Error(error));
            } else if (triple) {
                db.addTriple(triple)
            // console.log(triple.subject, triple.predicate, triple.object, '.');
            } else {
                resolve({db: db, triples:db.getTriples()});
            }
        });

    });
}

function parseSchema(base, schemaText) {
    return new Promise(function (resolve, reject) {
        var schema;
        try {
            schema = shexjs.Parser.construct(base).parse(schemaText);
        }
        catch (e) {
            reject(e);
        }
        resolve({schema: schema, shapes: schema.shapes});

    });
};
<commit_msg>added callback function printout<commit_after>var Promise = require('promise');

var dataParser = require("./dataParser.js");
var schemaParser = require("./schemaParser.js");
var validator = require("./validator.js");
var shapeFinder = require("./shapeFinder.js");

var shexjs = require("shex");
var n3 = require("n3");

var DefaultBase = "";

function Validator(schemaText, dataText, callbacks, options) {
    this.callbacks = callbacks;
    this.options = options;

    this.updateSchema(location.origin + '/schema.shex', schemaText);
    this.updateData(dataText);

    // console.log("validator has instantiated");
    // console.log("callbacks:\n",callbacks);
    // console.log("options:\n",options);

}

Validator.prototype = {
    updateSchema: function (base, schemaText) {
        this.schema = parseSchema(base ,schemaText);
        // this.schema = schemaParser.parseSchema(schemaText);
        this.schema.done(this.callbacks.schemaParsed, this.callbacks.schemaParseError);
        // var _schema = shexjs.Parser.construct(DefaultBase).parse(schemaText);
        // console.log('UPDATING THE FUCKIGN Schema',this.schema, _schema);
    },
    updateData: function (dataText) {
        this.data = parseData(dataText);
        // this.data = dataParser.parseData(dataText);
        this.data.done(this.callbacks.dataParsed, this.callbacks.dataParseError);
    },
    findShapes: function () {
        var _this = this;
        return Promise.all([this.schema, this.data]).then(function (a) {
            console.log('showing shapes');
            console.log(this.schema);
            console.log(this.data);
        });
    },
    validate: function(startingNodes) {
        var _this = this;
        console.log('validate function',_this);
        return Promise.all([this.schema, this.data, this.options]).then(function (a) {
            console.log(a);
            var node = Object.keys(a[2].resourceShapeMap)[0];
            var result = shexjs.Validator.construct(a[0].schema).validate(a[1].db, node, a[2].resourceShapeMap[node]);
            console.log('callbacks in validator',_this.callbacks);
            // console.log('validation results:',result);
            // return validator.validate(
            //     a[0].schema,                       // Schema
            //     a[0].resolver,
            //     startingNodes,      // Starting Node
            //     a[1].db,                       // db
            //     a[1].resolver,
            //     _this.options.closedShapes,
            //     _this.callbacks.validationResult);
            return result
        });
    }
};

module.exports.Validator = Validator;

function parseData(dataText){
    return new Promise(function (resolve, reject) {

        var db = n3.Store();
        n3.Parser({documentIRI: DefaultBase, format: "text/turtle"}).parse(dataText, function (error, triple, prefixes) {
            if (error) {
                // throw Error("error parsing " + data + ": " + error);
                reject(parseN3Error(error));
            } else if (triple) {
                db.addTriple(triple)
            // console.log(triple.subject, triple.predicate, triple.object, '.');
            } else {
                resolve({db: db, triples:db.getTriples()});
            }
        });

    });
}

function parseSchema(base, schemaText) {
    return new Promise(function (resolve, reject) {
        var schema;
        try {
            schema = shexjs.Parser.construct(base).parse(schemaText);
        }
        catch (e) {
            reject(e);
        }
        resolve({schema: schema, shapes: schema.shapes});

    });
};

function cleanResult(result, callback){
    console.log('validation result',result);
    return callback({
            errors: errors,
            matches: valRes.matches,
            startingResource: startingResource,
            passed: errors.length === 0
        });
}

function cleanupValidation(valRes, resolver, startingResource, cb) {

    return valRes.then(function(valRes) {
        var errors = valRes.errors.map(errorFormatter);

        cb({
            errors: errors,
            matches: valRes.matches,
            startingResource: startingResource,
            passed: errors.length === 0
        });
    });

}<|endoftext|>


<commit_before>function registerHeader(doc){
    class WuZhuHeader extends HTMLElement {
    createdCallback(){
      this._root = this.createShadowRoot();
      this._template = doc.querySelector('#headerTemplate');
      this._root.appendChild(doc.importNode(this._template.content, true));
      this._menu = this._root.querySelector('a');
      this._searchBar = this._root.querySelector('input');

      this._addEventHandlers();
    }

    get search(){
      return this._searchBar.value;
    }

    set search(v){
      this._searchBar.value = v;
    }

    _handleClick(evt){
      document.dispatchEvent(new Event("toggleNav"));
    }

    _handleInput(evt){
      document.dispatchEvent(new CustomEvent("search", {detail: evt.target.value}));
    }

    _addEventHandlers(){
      this._menu.addEventListener('click', this._handleClick);
      this._searchBar.addEventListener('input', this._handleInput);
    }

  }

  document.registerElement("wuzhu-header", WuZhuHeader);
}<commit_msg>Make using enter valid for submitting searches<commit_after>function registerHeader(doc){
    class WuZhuHeader extends HTMLElement {
    createdCallback(){
      this._root = this.createShadowRoot();
      this._template = doc.querySelector('#headerTemplate');
      this._root.appendChild(doc.importNode(this._template.content, true));
      this._menu = this._root.querySelector('a');
      this._searchBar = this._root.querySelector('input');
      this._handleKeyUp = this._handleKeyUp.bind(this);

      this._addEventHandlers();
    }

    get search(){
      return this._searchBar.value;
    }

    set search(v){
      this._searchBar.value = v;
    }

    _handleClick(evt){
      document.dispatchEvent(new Event("toggleNav"));
    }

    _handleInput(evt){
      document.dispatchEvent(new CustomEvent("search", {detail: evt.target.value}));
    }

    _handleKeyUp(evt){
      if (evt.keyCode === 13){
        this._handleInput(evt);
      }
      return true;
    }

    _addEventHandlers(){
      this._menu.addEventListener('click', this._handleClick);
      this._searchBar.addEventListener('input', this._handleInput);
      this._searchBar.addEventListener('keyup', this._handleKeyUp);
    }

  }

  document.registerElement("wuzhu-header", WuZhuHeader);
}<|endoftext|>