@m2c2kit/core 0.3.28 → 0.3.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,13 @@
1
- MIT License
1
+ Copyright 2023 Scott T. Yabiku
2
2
 
3
- Copyright (c) 2023 Scott T. Yabiku
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
4
6
 
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
7
+ http://www.apache.org/licenses/LICENSE-2.0
11
8
 
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @m2c2kit/core
2
2
 
3
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
3
+ [![License: Apache-2.0](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://opensource.org/license/apache-2-0)
4
4
  [![CI/CD](https://github.com/m2c2-project/m2c2kit/actions/workflows/ci.yml/badge.svg)](https://github.com/m2c2-project/m2c2kit/actions/workflows/ci.yml)
5
5
  [![npm version](https://img.shields.io/npm/v/@m2c2kit/core.svg)](https://www.npmjs.com/package/@m2c2kit/core)
6
6
 
package/dist/index.d.ts CHANGED
@@ -937,6 +937,15 @@ interface LocalizationOptions {
937
937
  additionalTranslation?: Translation;
938
938
  }
939
939
 
940
+ /**
941
+ * ScoringSchema defines the data that are generated by the scoring code. They
942
+ * are key-value pairs in which the key is the variable name, and the value is
943
+ * JSON Schema that defines the type of the variable.
944
+ */
945
+ interface ScoringSchema {
946
+ [key: string]: JsonSchema;
947
+ }
948
+
940
949
  /**
941
950
  * Options to specify HTML canvas, set game canvas size, and load game assets.
942
951
  */
@@ -965,6 +974,8 @@ interface GameOptions extends LocalizationOptions {
965
974
  stretch?: boolean;
966
975
  /** Schema of trial data; JSON object where key is variable name, value is data type */
967
976
  trialSchema?: TrialSchema;
977
+ /** Schema of scoring data; JSON object where key is variable name, value is data type */
978
+ scoringSchema?: ScoringSchema;
968
979
  /** Default game parameters; JSON object where key is the game parameter, value is default value */
969
980
  parameters?: GameParameters;
970
981
  /** Font assets to use. The first element will be the default font */
@@ -997,6 +1008,7 @@ interface GameOptions extends LocalizationOptions {
997
1008
 
998
1009
  interface GameData extends ActivityKeyValueData {
999
1010
  trials: Array<TrialData>;
1011
+ scoring: ActivityKeyValueData;
1000
1012
  }
1001
1013
 
1002
1014
  /**
@@ -1846,7 +1858,9 @@ declare class Game implements Activity {
1846
1858
  /**
1847
1859
  * Adds a scene to the game.
1848
1860
  *
1849
- * @remarks A scene, and its children nodes, cannot be presented unless it has been added to the game object.
1861
+ * @remarks A scene, and its children nodes, cannot be presented unless it
1862
+ * has been added to the game object. A scene can be added to the game
1863
+ * only once.
1850
1864
  *
1851
1865
  * @param scene
1852
1866
  */
@@ -1972,20 +1986,43 @@ declare class Game implements Activity {
1972
1986
  */
1973
1987
  dispose(): void;
1974
1988
  private initData;
1989
+ private validateSchema;
1975
1990
  private propertySchemaDataTypeIsValid;
1976
1991
  private getDeviceMetadata;
1977
1992
  /**
1978
1993
  * Adds data to the game's TrialData object.
1979
1994
  *
1980
- * @remarks The variableName must be previously defined in the trialSchema
1981
- * object passed in during game initialization through
1982
- * {@link GameInitOptions.trialSchema}. The type of the value must match
1983
- * what was defined in the trialSchema, otherwise an error is thrown.
1995
+ * @remarks `variableName` must be previously defined in the
1996
+ * {@link TrialSchema} object in {@link GameOptions}. The type of the value
1997
+ * must match what was defined in the trial schema, otherwise an error is
1998
+ * thrown.
1984
1999
  *
1985
2000
  * @param variableName - variable to be set
1986
2001
  * @param value - value of the variable to set
1987
2002
  */
1988
2003
  addTrialData(variableName: string, value: JsonSchemaDataTypeScriptTypes): void;
2004
+ /**
2005
+ * Adds data to the game's scoring data.
2006
+ *
2007
+ * @remarks The variable name (or object property names) must be previously
2008
+ * defined in the {@link ScoringSchema} object in {@link GameOptions}.
2009
+ * The type of the value must match what was defined in the scoring schema,
2010
+ * otherwise an error is thrown.
2011
+ *
2012
+ * @param variableNameOrObject - Either a variable name (string) or an object
2013
+ * containing multiple key-value pairs to add all at once.
2014
+ * @param value - Value of the variable to set (only used when
2015
+ * variableNameOrObject is a variable name string).
2016
+ */
2017
+ addScoringData(variableNameOrObject: string | Record<string, JsonSchemaDataTypeScriptTypes> | Array<Record<string, JsonSchemaDataTypeScriptTypes>>, value?: JsonSchemaDataTypeScriptTypes): void;
2018
+ /**
2019
+ * Helper method to validate and set a single scoring variable
2020
+ *
2021
+ * @param variableName - Name of the variable to set
2022
+ * @param value - Value to set
2023
+ * @private
2024
+ */
2025
+ private validateAndSetScoringVariable;
1989
2026
  /**
1990
2027
  * Adds custom trial schema to the game's trialSchema object.
1991
2028
  *
@@ -2034,6 +2071,22 @@ declare class Game implements Activity {
2034
2071
  * the appropriate time. It is not triggered automatically.
2035
2072
  */
2036
2073
  trialComplete(): void;
2074
+ /**
2075
+ * Marks scoring as complete.
2076
+ *
2077
+ * @remarks This method must be called after the game has finished adding
2078
+ * scores using addScoringData(). Calling will trigger the onActivityResults
2079
+ * callback function, if one was provided in SessionOptions. This is how the
2080
+ * game communicates scoring data to the parent session, which can then save
2081
+ * or process the data. It is the responsibility of the the game programmer
2082
+ * to call this at the appropriate time. It is not triggered automatically.
2083
+ */
2084
+ scoringComplete(): void;
2085
+ /**
2086
+ * The m2c2kit engine will automatically include these schema and their
2087
+ * values in the scoring data.
2088
+ */
2089
+ private readonly automaticScoringSchema;
2037
2090
  /**
2038
2091
  * The m2c2kit engine will automatically include these schema and their
2039
2092
  * values in the trial data.
@@ -2050,6 +2103,7 @@ declare class Game implements Activity {
2050
2103
  */
2051
2104
  private makeGameActivityConfiguration;
2052
2105
  private makeGameActivityConfigurationSchema;
2106
+ private makeScoringDataSchema;
2053
2107
  /**
2054
2108
  * Should be called when current game has ended successfully.
2055
2109
  *
@@ -2296,14 +2350,69 @@ declare class I18n {
2296
2350
  private localeTranslationAvailable;
2297
2351
  switchToLocale(locale: string): void;
2298
2352
  /**
2353
+ * Returns the localized text and font information for the given key in the
2354
+ * current locale.
2299
2355
  *
2300
2356
  * @param key - Translation key
2301
2357
  * @param interpolation - Interpolation keys and values to replace
2302
- * placeholders in the translated text
2303
- * @returns a `TextLocalizationResult` object with the localized text, font
2304
- * information, and whether the translation is a fallback.
2358
+ * string interpolation placeholders in the translated text
2359
+ * @returns object with the localized text, font information, and whether the
2360
+ * translation is a fallback.
2305
2361
  */
2306
2362
  getTextLocalization(key: string, interpolation?: StringInterpolationMap): TextLocalizationResult;
2363
+ /**
2364
+ *
2365
+ * @param key - Translation key to be translated
2366
+ * @param interpolation - String interpolation keys and values to replace
2367
+ * @returns result object with the localized text, font
2368
+ */
2369
+ private attemptTranslation;
2370
+ /**
2371
+ * Handles translation placeholders in a string.
2372
+ *
2373
+ * @remarks The value of a translation placeholder (text within `[[]]`)
2374
+ * may also contain string interpolation placeholders (`{{}}`), so we need
2375
+ * to handle that as well.
2376
+ *
2377
+ * @param key - Translation key for the string to be localized
2378
+ * @param initialResult - Initial translation result for the string
2379
+ * @param interpolation - Interpolation keys and values to replace
2380
+ * interpolation placeholders in the translated text
2381
+ * @returns result object with the localized text,
2382
+ */
2383
+ private handleTranslationPlaceholders;
2384
+ /**
2385
+ * Translates a translation placeholder key to its text and collects font properties.
2386
+ *
2387
+ * @param placeholderKey - Translation key for the placeholder
2388
+ * @param fontProps - Font properties sets to collect font information
2389
+ * @param interpolation - Interpolation keys and values to replace
2390
+ * string interpolation placeholders in the translated text
2391
+ * @returns result object with the translated text and whether it is a fallback translation
2392
+ */
2393
+ private translatePlaceholder;
2394
+ /**
2395
+ * Extracts translation key placeholders from a string.
2396
+ *
2397
+ * @remarks Translation key placeholders are denoted by double square brackets,
2398
+ * e.g., "The translated word is [[RED]]", and RED is a key for translation.
2399
+ *
2400
+ * @param s - string to search for placeholders
2401
+ * @returns an array of placeholders found in the string, without the square
2402
+ * brackets
2403
+ */
2404
+ private getTranslationPlaceholders;
2405
+ /**
2406
+ * Logs warnings if the string to be localized has conflicting font
2407
+ * properties.
2408
+ *
2409
+ * @remarks This can happen due to multiple placeholders in the string
2410
+ * that specify different font sizes, font names, or font names arrays.
2411
+ *
2412
+ * @param key - Translation key for which the string is being localized
2413
+ * @param fontProps - font properties sets collected from the placeholders
2414
+ */
2415
+ private warnConflictingFontProperties;
2307
2416
  /**
2308
2417
  * Returns the translation text for the given key in the current locale.
2309
2418
  *
@@ -3759,6 +3868,13 @@ declare enum Dimensions {
3759
3868
  MatchConstraint = 0
3760
3869
  }
3761
3870
 
3871
+ /**
3872
+ * Custom error class for m2c2kit errors.
3873
+ */
3874
+ declare class M2Error extends Error {
3875
+ constructor(...params: string[]);
3876
+ }
3877
+
3762
3878
  type M2NodeConstructor = new (options?: M2NodeOptions) => M2Node;
3763
3879
 
3764
3880
  /**
@@ -4195,6 +4311,8 @@ declare enum LabelHorizontalAlignmentMode {
4195
4311
  }
4196
4312
 
4197
4313
  interface LabelOptions extends M2NodeOptions, DrawableOptions, TextOptions {
4314
+ /** Text to be displayed. When operating with localization, text within double square brackets will be replaced with the value of the key in the translation. For example, if the text is `The translated word is [[RED]]`, `[[RED]]` will be replaced with the translation. If no localization is used, or a translation for the key is missing, then the text will be rendered as is. Tags for bold (`b`), italic (`i`), underline (`u`), overline(`o`), and strikethrough (`s`) are supported, e.g., `<b><u>Bold and underline</u></b>`. Note that while bold and italic and be combined, only one of underline, overline, and strikethrough can be used on a text segment. */
4315
+ text?: string;
4198
4316
  /** Horizontal alignment of label text. see {@link LabelHorizontalAlignmentMode}. Default is LabelHorizontalAlignmentMode.center */
4199
4317
  horizontalAlignmentMode?: LabelHorizontalAlignmentMode;
4200
4318
  /** Maximum width of label text before wrapping occurs. Default is the canvas width */
@@ -4229,10 +4347,14 @@ declare class Label extends M2Node implements IDrawable, IText, LabelOptions {
4229
4347
  private localizedFontSize;
4230
4348
  private localizedFontName;
4231
4349
  private localizedFontNames;
4350
+ private textAfterLocalization;
4351
+ private plainText;
4352
+ private styleSegments;
4232
4353
  /**
4233
4354
  * Single or multi-line text formatted and rendered on the screen.
4234
4355
  *
4235
- * @remarks Label (in contrast to TextLine) has enhanced text support for line wrapping, centering/alignment, and background colors.
4356
+ * @remarks Label (in contrast to TextLine) has enhanced text support for
4357
+ * line wrapping, centering/alignment, and background colors.
4236
4358
  *
4237
4359
  * @param options - {@link LabelOptions}
4238
4360
  */
@@ -4263,6 +4385,35 @@ declare class Label extends M2Node implements IDrawable, IText, LabelOptions {
4263
4385
  suppressEvents?: boolean;
4264
4386
  };
4265
4387
  initialize(): void;
4388
+ /**
4389
+ * Parses text with formatting tags and returns plain text and style segments.
4390
+ * Supports <b> for bold, <i> for italics, and <u> for underline.
4391
+ * Properly handles nested tags like <b><u>bold and underlined</u></b>.
4392
+ * Throws errors for malformed tags, but treats unknown tags as plain text.
4393
+ *
4394
+ * @param text - The text with formatting tags
4395
+ * @returns The parsed text result
4396
+ * @throws Error if tags are improperly nested or unclosed
4397
+ */
4398
+ private parseFormattedText;
4399
+ /**
4400
+ * Adds text segments with consistent styling to the paragraph builder.
4401
+ *
4402
+ * @param builder - {@link ParagraphBuilder}
4403
+ * @param styleSegments - Segments of text with consistent styling
4404
+ * @param defaultStyle - Default style to apply
4405
+ */
4406
+ private addStyleSegmentsToParagraphBuilder;
4407
+ /**
4408
+ * Helper that adds text to the paragraph builder with the specified style.
4409
+ *
4410
+ * @param builder - {@link ParagraphBuilder}
4411
+ * @param text - The text to add
4412
+ * @param defaultStyle - The default style to apply
4413
+ * @param styleModifiers - Additional style modifications
4414
+ * @returns void
4415
+ */
4416
+ private addTextWithStyle;
4266
4417
  /**
4267
4418
  * Determines the M2Font objects that need to be ready in order to draw
4268
4419
  * the Label.
@@ -4510,12 +4661,27 @@ declare class RandomDraws {
4510
4661
  }
4511
4662
 
4512
4663
  /**
4513
- * ScoringSchema defines the data that are generated by the scoring code. They
4514
- * are key-value pairs in which the key is the variable name, and the value is
4515
- * JSON Schema that defines the type of the variable.
4664
+ * Assessments that generate scoring data must implement the ScoringProvider
4665
+ * interface
4516
4666
  */
4517
- interface ScoringSchema {
4518
- [key: string]: JsonSchema;
4667
+ interface ScoringProvider {
4668
+ /**
4669
+ * Calculates scores based on the provided activity data and optional
4670
+ * additional parameters.
4671
+ *
4672
+ * @param data - Activity data from which to calculate scores.
4673
+ * @param extras - Optional additional parameters that are needed for an
4674
+ * activity's scoring calculations. This can include things like
4675
+ * game parameters, user context, or other metadata that is relevant
4676
+ * to the scoring logic. The structure of this object is not
4677
+ * defined by this interface, as it can vary widely between different
4678
+ * activities.
4679
+ * @returns The calculated scores object or an array of such objects. If an
4680
+ * array of is returned, it should have length 1.
4681
+ */
4682
+ calculateScores(data: ActivityKeyValueData[], extras?: {
4683
+ [key: string]: unknown;
4684
+ }): ActivityKeyValueData | Array<ActivityKeyValueData>;
4519
4685
  }
4520
4686
 
4521
4687
  declare enum ShapeType {
@@ -5341,4 +5507,5 @@ declare class WebGlInfo {
5341
5507
  static dispose(): void;
5342
5508
  }
5343
5509
 
5344
- export { Action, type Activity, type ActivityCallbacks, type ActivityEvent, type ActivityEventListener, type ActivityKeyValueData, type ActivityLifecycleEvent, type ActivityResultsEvent, ActivityType, type BrowserImage, type BrowserImageDataReadyEvent, type CallbackOptions, CanvasKitHelpers, ColorfulMutablePath, Composite, type CompositeEvent, type CompositeOptions, Constants, ConstraintType, type Constraints, CustomAction, type CustomActionOptions, type DefaultParameter, Dimensions, type DomPointerDownEvent, type DrawableOptions, type EasingFunction, Easings, Equal, Equals, EventStore, EventStoreMode, FadeAlphaAction, type FadeAlphaActionOptions, type FontAsset, type FontData, FontManager, Game, type GameData, type GameEvent, type GameOptions, type GameParameters, type GlobalVariables, GroupAction, I18n, type I18nDataReadyEvent, type IDataStore, type IDrawable, type IText, ImageManager, Label, LabelHorizontalAlignmentMode, type LabelOptions, type Layout, LayoutConstraint, LegacyTimer, type LocaleSvg, type M2ColorfulPath, type M2DragEvent, type M2Event, type M2EventListener, M2EventType, type M2Image, M2ImageStatus, type M2KeyboardEvent, M2Node, type M2NodeAddChildEvent, type M2NodeConstructor, type M2NodeEvent, type M2NodeEventListener, M2NodeFactory, type M2NodeNewEvent, type M2NodeOptions, type M2NodePropertyChangeEvent, type M2NodeRemoveChildEvent, M2NodeType, type M2Path, type M2PointerEvent, type M2Sound, M2SoundStatus, M2c2KitHelpers, MoveAction, type MoveActionOptions, MutablePath, NoneTransition, PlayAction, type PlayActionOptions, type Plugin, type PluginEvent, type Point, RandomDraws, type RectOptions, RepeatAction, RepeatForeverAction, type RgbaColor, RotateAction, ScaleAction, type ScaleActionOptions, Scene, type SceneOptions, type ScenePresentEvent, SceneTransition, type ScoringSchema, SequenceAction, Shape, type ShapeOptions, ShapeType, type Size, SlideTransition, type SlideTransitionOptions, type SoundAsset, SoundManager, SoundPlayer, type SoundPlayerOptions, SoundRecorder, type SoundRecorderOptions, type SoundRecorderResults, Sprite, type SpriteOptions, Story, type StoryOptions, type StringInterpolationMap, type TapEvent, type TextAndFont, TextLine, type TextLineOptions, type TextLocalizationResult, type TextOptions, type TextWithFontCustomization, Timer, Transition, TransitionDirection, TransitionType, type Translation, type TranslationConfiguration, type TranslationOptions, type TrialData, type TrialSchema, Uuid, WaitAction, type WaitActionOptions, WebColors, WebGlInfo, handleInterfaceOptions };
5510
+ export { Action, ActivityType, CanvasKitHelpers, ColorfulMutablePath, Composite, Constants, ConstraintType, CustomAction, Dimensions, Easings, Equal, Equals, EventStore, EventStoreMode, FadeAlphaAction, FontManager, Game, GroupAction, I18n, ImageManager, Label, LabelHorizontalAlignmentMode, LayoutConstraint, LegacyTimer, M2Error, M2EventType, M2ImageStatus, M2Node, M2NodeFactory, M2NodeType, M2SoundStatus, M2c2KitHelpers, MoveAction, MutablePath, NoneTransition, PlayAction, RandomDraws, RepeatAction, RepeatForeverAction, RotateAction, ScaleAction, Scene, SceneTransition, SequenceAction, Shape, ShapeType, SlideTransition, SoundManager, SoundPlayer, SoundRecorder, Sprite, Story, TextLine, Timer, Transition, TransitionDirection, TransitionType, Uuid, WaitAction, WebColors, WebGlInfo, handleInterfaceOptions };
5511
+ export type { Activity, ActivityCallbacks, ActivityEvent, ActivityEventListener, ActivityKeyValueData, ActivityLifecycleEvent, ActivityResultsEvent, BrowserImage, BrowserImageDataReadyEvent, CallbackOptions, CompositeEvent, CompositeOptions, Constraints, CustomActionOptions, DefaultParameter, DomPointerDownEvent, DrawableOptions, EasingFunction, FadeAlphaActionOptions, FontAsset, FontData, GameData, GameEvent, GameOptions, GameParameters, GlobalVariables, I18nDataReadyEvent, IDataStore, IDrawable, IText, LabelOptions, Layout, LocaleSvg, M2ColorfulPath, M2DragEvent, M2Event, M2EventListener, M2Image, M2KeyboardEvent, M2NodeAddChildEvent, M2NodeConstructor, M2NodeEvent, M2NodeEventListener, M2NodeNewEvent, M2NodeOptions, M2NodePropertyChangeEvent, M2NodeRemoveChildEvent, M2Path, M2PointerEvent, M2Sound, MoveActionOptions, PlayActionOptions, Plugin, PluginEvent, Point, RectOptions, RgbaColor, ScaleActionOptions, SceneOptions, ScenePresentEvent, ScoringProvider, ScoringSchema, ShapeOptions, Size, SlideTransitionOptions, SoundAsset, SoundPlayerOptions, SoundRecorderOptions, SoundRecorderResults, SpriteOptions, StoryOptions, StringInterpolationMap, TapEvent, TextAndFont, TextLineOptions, TextLocalizationResult, TextOptions, TextWithFontCustomization, Translation, TranslationConfiguration, TranslationOptions, TrialData, TrialSchema, WaitActionOptions };