Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 | 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 94x 81x 81x 66x 15x 188x 3x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 117x 3x 114x 114x 114x 114x 19x 19x 114x 120x 120x 114x 114x 3x 108x 60x 61x 108x 37x 36x 37x 108x 21x 22x 108x 12x 12x 12x 12x 108x 108x 108x 108x 108x 94x 1709x 1709x 60x 60x 60x 60x 60x 13x 13x 60x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 56x 1709x 94x 94x 94x 94x 94x 94x 60x 63x 5x | /** * ## Specification for the HTML API for triggers * * The following describes the general syntax when using the HTML API and * automatic widgets * ({@link Settings.settings.autoWidgets | settings.autoWidgets} is true) * specifically for triggers and actions. * * A trigger specification should be given as a * `data-lisn-on-<TriggerName>="<TriggerSpecList>"` attribute. * A fallback option of using a CSS class of the form * `lisn-on-<TriggerName>--<TriggerSpec>` is also supported if needed but is not * recommended and may be deprecated in future. * * The general specification for a trigger is of the form: * * ``` * <TriggerSpecList> ::= <TriggerSpec> { ";" <TriggerSpec> } * * <TriggerSpec> ::= [ <TriggerArg> { "," <TriggerArg> } ] * "@" <ActionSpec> { "@" <ActionSpec> } * { "+" <TriggerOption> } * * <TriggerOption> ::= * <BooleanOptionName> [ "=" ( "false" | "true" ) ] | * <OptionName> "=" <OptionValue> * * <ActionSpec> ::= <ActionName> [ ":" <ActionArgsAndOptions> ] * * <ActionArgsAndOptions> ::= <ActionArgs> [ "," <ActionOptions> ] | * <ActionOptions> * * <ActionArgs> ::= <Arg> { "," <Arg> } * * <ActionOptions> ::= <OptionName> = <OptionValue> { "," <OptionName> = <OptionValue> } * ``` * * Some triggers or actions accept both arguments as well as `=` separated * key=value options. Some accept only arguments or only options. See each * trigger or actions's specification for their accepted or required arguments * and options. When specifying action arguments and options, place the * arguments first. * * **NOTE:** * * There can be 0 or more spaces around any of the separator characters. * * At least one action (with a preceding `@` character) is always required. * * The characters `;`, `,`, `=`, `@`, `+` and `:` are reserved separators and * cannot be used literally as part of an argument or option value. * * See documentation on a specific trigger or action for examples. * * @module Triggers * * @categoryDescription Manual run * {@link Trigger} is the base trigger class that you can extend when building * custom triggers and it also registers a trigger that needs to be run * manually (by e.g. the {@link Actions.Run | Run} action). */ // [TODO v2]: Perhaps remove support for trigger spec as part of CSS classes? import * as MC from "@lisn/globals/minification-constants"; import * as MH from "@lisn/globals/minification-helpers"; import { LisnUsageError } from "@lisn/globals/errors"; import { wrapCallback } from "@lisn/modules/callback"; import { getData } from "@lisn/utils/css-alter"; import { waitForReferenceElement } from "@lisn/utils/dom-search"; import { waitForDelay } from "@lisn/utils/tasks"; import { formatAsString, randId, splitOn } from "@lisn/utils/text"; import { validateString, validateNumber, validateBoolean, } from "@lisn/utils/validation"; import { Action, fetchAction } from "@lisn/actions/action"; import { Widget, WidgetConfigValidator, WidgetConfigValidatorFunc, WidgetConfigAsyncValidatorObject, registerWidget, fetchWidgetConfig, } from "@lisn/widgets/widget"; import debug from "@lisn/debug/debug"; /** * {@link Trigger} is the base trigger class that you can extend when building * custom triggers and it also registers a trigger that needs to be run * manually (by e.g. the {@link Actions.Run | Run} action). * * ------- * * To use with auto-widgets (HTML API), see {@link registerTrigger} for the * specification. * * @example * Show the element 1000ms after the first time the trigger is run. * * ```html * <div data-lisn-on-run="@show +once +delay=1000"></div> * ``` * * @category Manual run */ export class Trigger extends Widget { /** * "Do"es all the {@link Action}s linked to the trigger. */ readonly run: () => Promise<void>; /** * "Undo"es all the {@link Action}s linked to the trigger. */ readonly reverse: () => Promise<void>; /** * "Toggle"s all the {@link Action}s linked to the trigger. */ readonly toggle: () => Promise<void>; /** * Returns the trigger's actions. */ readonly getActions: () => Action[]; /** * Returns the trigger config. */ readonly getConfig: () => TriggerConfig; static get(element: Element, id: string): Trigger | null { const instance = super.get(element, id); if (MH.isInstanceOf(instance, Trigger)) { return instance; } return null; } static register() { registerTrigger( "run", (element, a, actions, config) => new Trigger(element, actions, config), {}, ); } /** * If no actions are supplied, nothing is done. * * @throws {@link Errors.LisnUsageError | LisnUsageError} * If the config is invalid. */ constructor(element: Element, actions: Action[], config?: TriggerConfig) { config ??= {}; super(element, config); const logger = debug ? new debug.Logger({ name: `Trigger-${formatAsString(element)}`, logAtCreation: { actions, config }, }) : null; const once = config.once ?? false; const oneWay = config.oneWay ?? false; const delay = config.delay ?? 0; const doDelay = config.doDelay ?? delay; const undoDelay = config.undoDelay ?? delay; let lastCallId: string; // false if next should be do; true if next should be undo. // Used for determining delays only. let toggleState = false; const callActions = async ( delay: number, callFn: (action: Action) => void, newToggleState: boolean, ) => { if (this.isDisabled()) { return; } const myCallId = randId(); lastCallId = myCallId; debug: logger?.debug10( `callActions [${myCallId}] (new toggle state ${newToggleState})`, callFn, ); if (delay) { await waitForDelay(delay); Iif (lastCallId !== myCallId) { // overriden by subsequent call debug: logger?.debug10( `callActions [${myCallId}]: overriden by ${lastCallId}`, ); return; } } for (const action of actions) { debug: logger?.debug10(`callActions [${myCallId}]`, action); callFn(action); } toggleState = newToggleState; if (toggleState && once) { this.destroy(); } }; const run = wrapCallback(() => { callActions( doDelay, (action) => { action.do(); }, true, ); // don't await }); const reverse = wrapCallback(() => { if (!oneWay) { callActions( undoDelay, (action) => { action.undo(); }, false, ); // don't await } }); const toggle = wrapCallback(() => { callActions( toggleState ? undoDelay : doDelay, (action) => { action[MC.S_TOGGLE](); }, !toggleState, ); // don't await }); // ---------- this.onDestroy(() => { debug: logger?.debug5("Removing callbacks"); MH.remove(run); MH.remove(reverse); MH.remove(toggle); }); this.run = run.invoke; this.reverse = reverse.invoke; this[MC.S_TOGGLE] = oneWay ? run.invoke : toggle.invoke; this.getActions = () => [...actions]; // copy this.getConfig = () => MH.copyObject(config); } } /** * @interface */ export type TriggerConfig = { /** * An ID for the trigger so that it can be looked up by ID. It has to be * unique for each element, but you can use the same ID on different * elements. * * @defaultValue undefined */ id?: string; /** * If true, the trigger will run at most once. This will result in the `run` * or `toggle` methods removing all three of `run`, `reverse` and `toggle` * when called, so that the actions are done at most once. * * @defaultValue false */ once?: boolean; /** * If true, then the `reverse` method of the trigger will do nothing and the * `toggle` method will always do the actions, i.e. will be equivalent to * `run`. * * @defaultValue false */ oneWay?: boolean; /** * Delay in milliseconds before doing, undoing or toggling actions. * * @defaultValue 0 */ delay?: number; /** * Delay in milliseconds before doing actions. * * @defaultValue {@link TriggerConfig.delay} */ doDelay?: number; /** * Delay in milliseconds before undoing actions. * * @defaultValue {@link TriggerConfig.delay} */ undoDelay?: number; /** * The element to instantiate all actions on this trigger for. * * @defaultValue The element on which the {@link Trigger} is defined */ actOn?: Element; }; export type TriggerCreateFn<Config extends TriggerConfig> = ( element: Element, args: string[], actions: Action[], config: Config, ) => Trigger | Promise<Trigger>; /** * Registers the given trigger as a widget to be automatically configured for * all elements that have a trigger specification with the given name. * * See the {@link Triggers} page for an explanation of the string specification * syntax. * * **IMPORTANT:** If a trigger by that name is already registered, the current * call does nothing, even if the remaining arguments differ. * * @param name The name of the trigger. Should be in kebab-case. * @param newTrigger Called for every trigger specification on any element * that has one or more trigger specifications. * @param configValidator * A validator object, or a function that returns such an * object, for all options that are specific to the * trigger. Base options (in {@link TriggerConfig}) will * be parsed automatically and don't need to be handled by * `configValidator`. * If the parameter is a function, it will be called with * the element on which the trigger is being defined. * * @see {@link registerWidget} */ export const registerTrigger = <Config extends TriggerConfig = TriggerConfig>( name: string, newTrigger: TriggerCreateFn<Config>, configValidator?: null | WidgetConfigValidator<Config>, ) => { const clsPref = MH.prefixName(`on-${name}`); const newWidget = async (element: Element) => { const widgets: Widget[] = []; const baseConfigValidator = newBaseConfigValidator(element); const thisConfigValidator = MH.isFunction(configValidator) ? await configValidator(element) : configValidator; const allSpecs = splitOn( getData(element, MH.prefixName(`on-${name}`)) ?? "", TRIGGER_SEP_CHAR, true, ); for (const cls of MH.classList(element)) { if (cls.startsWith(`${clsPref}--`)) { allSpecs.push(cls.slice(MH.lengthOf(clsPref) + 2)); } } for (const spec of allSpecs) { const [tmp, configSpec] = splitOn(spec, OPTION_PREF_CHAR, true, 1); const [argSpec, allActionSpecs] = splitOn(tmp, ACTION_PREF_CHAR, true, 1); const args = MH.filterBlank(splitOn(argSpec, ARGS_SEP_CHAR, true)) || []; const config = await fetchWidgetConfig( configSpec, MH.assign( baseConfigValidator, thisConfigValidator, ) as WidgetConfigAsyncValidatorObject<Required<TriggerConfig> & Config>, OPTION_PREF_CHAR, ); const actionTarget = config.actOn ?? element; const actions = []; for (const actionSpec of splitOn( allActionSpecs ?? "", ACTION_PREF_CHAR, true, )) { const [name, actionArgsAndOptions] = splitOn( actionSpec, ACTION_ARGS_PREF_CHAR, true, 1, ); try { actions.push( await fetchAction(actionTarget, name, actionArgsAndOptions ?? ""), ); } catch (err) { Iif (MH.isInstanceOf(err, LisnUsageError)) { // fetchAction would have logged an error continue; } throw err; } } widgets.push(await newTrigger(element, args, actions, config)); } return widgets; }; registerWidget(name, newWidget, null, { selector: `[class^="${clsPref}--"],[class*=" ${clsPref}--"],[data-${clsPref}]`, }); }; // -------------------- const TRIGGER_SEP_CHAR = ";"; const ARGS_SEP_CHAR = ","; const OPTION_PREF_CHAR = "+"; const ACTION_PREF_CHAR = "@"; const ACTION_ARGS_PREF_CHAR = ":"; const newBaseConfigValidator: WidgetConfigValidatorFunc<TriggerConfig> = ( element, ) => { return { id: validateString, once: validateBoolean, oneWay: validateBoolean, delay: validateNumber, doDelay: validateNumber, undoDelay: validateNumber, actOn: (key, value) => MH.isLiteralString(value) ? waitForReferenceElement(value, element).then((v) => v ?? undefined) // ugh, typescript... : undefined, }; }; |