diff --git a/docs/how_tos/add-a-slot-version.md b/docs/how_tos/add-a-slot-version.md new file mode 100644 index 00000000..8f601658 --- /dev/null +++ b/docs/how_tos/add-a-slot-version.md @@ -0,0 +1,1182 @@ +# How to: Add a New Version of a Slot + +## Overview + +A change that would break a slot's API contract, as [ADR 0009](../decisions/0009-slot-naming-and-lifecycle.rst) defines it, cannot land without bumping the slot's version. Simply bumping the version would be a breaking change to the app. Ideally the new version can be added alongside the old one, with the old one deprecated and removed later. This guide provides examples of some ways to do that. The last two examples rename a slot, first with its contract unchanged and then with it changed. + +## Example: renaming a prop + +A greeting slot with one prop: + +```tsx +import { Slot } from '@openedx/frontend-base'; + +export interface GreetingSlotProps { + userName: string; +} + +const GreetingSlot = ({ userName }: GreetingSlotProps) => ( + +

Hello, {userName}

+
+); + +export default GreetingSlot; +``` + +`userName` is being renamed to `displayName`. Simply renaming it would break the slot's API contract: a widget that reads `userName` would get `undefined`, and a widget typed with `GreetingSlotProps` would stop compiling. + +```diff + export interface GreetingSlotProps { +- userName: string; ++ displayName: string; + } + +-const GreetingSlot = ({ userName }: GreetingSlotProps) => ( +- +-

Hello, {userName}

++const GreetingSlot = ({ displayName }: GreetingSlotProps) => ( ++ ++

Hello, {displayName}

+
+ ); +``` + +Bumping to `v2` at the same time removes `v1` from the app, which is a breaking change to the app. + +```diff + export interface GreetingSlotProps { +- userName: string; ++ displayName: string; + } + +-const GreetingSlot = ({ userName }: GreetingSlotProps) => ( +- +-

Hello, {userName}

++const GreetingSlot = ({ displayName }: GreetingSlotProps) => ( ++ ++

Hello, {displayName}

+
+ ); +``` + +The steps below add `v2` while leaving `v1` in place. + +### 1. Declare the new version's props as a new interface + +The old interface keeps every member it had, so that widgets typed against it still compile. Give the two interfaces versioned names, and keep the old unversioned name as an alias of the old one. + +```tsx +export interface GreetingSlotV1Props { + userName: string; +} + +export type GreetingSlotProps = GreetingSlotV1Props; + +export interface GreetingSlotV2Props { + displayName: string; +} +``` + +### 2. Render the new version around the old one + +The `v2` `` wraps the `v1` ``, and the default content stays inside `v1`. Each `` gets its own props. A value both versions need is passed under each version's name. + +```tsx +const GreetingSlot = ({ displayName }: GreetingSlotV2Props) => ( + + +

Hello, {displayName}

+
+
+); +``` + +This is what keeps both versions working at once: + +- The `v1` slot is the `v2` slot's default content. Every `v1` widget, layout and option applies exactly as before. +- A `v2` operation that replaces the default content replaces `v1` and everything in it. That is what an operator moving to `v2` expects. +- A `v2` layout receives `v1` as its `defaultContent` widget, the same as it would any default content. + +### 3. Mark the old props as deprecated + +Add a `@deprecated` note to the old interface and to each renamed member. + +```tsx +/** @deprecated Replaced by `GreetingSlotV2Props`, the props of `org.openedx.frontend.slot.example.greeting.v2`. */ +export interface GreetingSlotV1Props { + /** @deprecated Renamed to `displayName` in `GreetingSlotV2Props`. */ + userName: string; +} + +/** @deprecated Renamed to `GreetingSlotV1Props`. */ +export type GreetingSlotProps = GreetingSlotV1Props; +``` + +### 4. Give each version its own README + +Rename the slot's `README.md` to `README.v1.md`, and write a new `README.md` for `v2`. The new file should link to `README.v1.md` as the previous version, and it should carry over every `v1` example that still applies, updated for `v2`, alongside any new ones. The only change to `README.v1.md` is a note at the top: + +```markdown +> [!WARNING] +> `org.openedx.frontend.slot.example.greeting.v1` is deprecated and will be +> removed in a future release. Use `org.openedx.frontend.slot.example.greeting.v2` +> instead. +``` + +### 5. Commit as `feat:` + +Adding a version beside a working one is not a breaking change to the app, so this is `feat:` and not `feat!:`. The commit body should say which version is deprecated and what replaces it. + +```text +feat: add greeting slot v2, deprecate v1 + +org.openedx.frontend.slot.example.greeting.v1 is deprecated and will be +removed in a future release. Use +org.openedx.frontend.slot.example.greeting.v2 instead. +``` + +### 6. Remove the old version + +Once the deprecation process allows it, and at least one Open edX named release has shipped with both versions, remove `v1`: + +```diff + import { Slot } from '@openedx/frontend-base'; + +-/** @deprecated Replaced by `GreetingSlotV2Props`, the props of `org.openedx.frontend.slot.example.greeting.v2`. */ +-export interface GreetingSlotV1Props { +- /** @deprecated Renamed to `displayName` in `GreetingSlotV2Props`. */ +- userName: string; +-} +- +-/** @deprecated Renamed to `GreetingSlotV1Props`. */ +-export type GreetingSlotProps = GreetingSlotV1Props; +- + export interface GreetingSlotV2Props { + displayName: string; + } + + const GreetingSlot = ({ displayName }: GreetingSlotV2Props) => ( + +- +-

Hello, {displayName}

+-
++

Hello, {displayName}

+
+ ); + + export default GreetingSlot; +``` + +Delete `README.v1.md` and the link to it from `README.md`. + +Removing the old version is a breaking change to the app, so this commit is `feat!:`. + +```text +feat!: remove greeting slot v1 + +BREAKING CHANGE: org.openedx.frontend.slot.example.greeting.v1 and +GreetingSlotProps are removed. Use +org.openedx.frontend.slot.example.greeting.v2 and GreetingSlotV2Props +instead. +``` + +### Moving a widget to `v2` + +A widget written for `v1` keeps working unchanged for as long as `v1` exists. Moving it to `v2` is a change of slot id and prop name in the site config: + +```diff + { +- slotId: 'org.openedx.frontend.slot.example.greeting.v1', ++ slotId: 'org.openedx.frontend.slot.example.greeting.v2', + id: 'customGreeting', + op: WidgetOperationTypes.REPLACE, + relatedId: 'defaultContent', +- component: ({ userName }: GreetingSlotProps) =>

Welcome back, {userName}

, ++ component: ({ displayName }: GreetingSlotV2Props) =>

Welcome back, {displayName}

, + } +``` + +## Example: changing a prop's type + +A banner slot with one prop: + +```tsx +import { Slot } from '@openedx/frontend-base'; + +export interface BannerSlotProps { + message: string; +} + +const BannerSlot = ({ message }: BannerSlotProps) => ( + + + +); + +export default BannerSlot; +``` + +`message` is being replaced by a `notice` object that also carries a severity and a dismiss handler. + +### 1. Declare the new version's props as a new interface + +The member changes type instead of name. `Notice` is new, so it is declared here and exported from the app's `index.ts` beside the slot props, so that a widget can import it. + +```tsx +export interface BannerSlotV1Props { + message: string; +} + +export type BannerSlotProps = BannerSlotV1Props; + +export interface Notice { + message: string; + severity: 'info' | 'warning' | 'error'; + onDismiss: () => void; +} + +export interface BannerSlotV2Props { + notice: Notice; +} +``` + +### 2. Render the new version around the old one + +`v1` gets its value from the `v2` value instead of the same value under another name. + +```tsx +const BannerSlot = ({ notice }: BannerSlotV2Props) => ( + + + + + +); +``` + +### 3. Mark the old props as deprecated + +The member's `@deprecated` note says what replaces it and how to get the old value from the new one. + +```tsx +/** @deprecated Replaced by `BannerSlotV2Props`, the props of `org.openedx.frontend.slot.example.banner.v2`. */ +export interface BannerSlotV1Props { + /** @deprecated Replaced by `notice` in `BannerSlotV2Props`; this is `notice.message`. */ + message: string; +} +``` + +### 4. Give each version its own README + +Same as for the prop rename. + +### 5. Commit as `feat:` + +Same as for the prop rename. + +### 6. Remove the old version + +Same as for the prop rename. + +## Example: a prop that becomes a list + +A taggable item slot with one prop: + +```tsx +import { Slot } from '@openedx/frontend-base'; + +export interface TaggableItemSlotProps { + selectedTag: string; +} + +const TaggableItemSlot = ({ selectedTag }: TaggableItemSlotProps) => ( + +

Tagged {selectedTag}

+
+); + +export default TaggableItemSlot; +``` + +`selectedTag` is becoming a list, `selectedTags`. + +### 1. Declare the new version's props as a new interface + +Version and alias the old interface. + +```tsx +export interface TaggableItemSlotV1Props { + selectedTag: string; +} + +export type TaggableItemSlotProps = TaggableItemSlotV1Props; +``` + +Declare the new interface with only the list. + +```tsx +export interface TaggableItemSlotV2Props { + selectedTags: string[]; +} +``` + +`selectedTags` can also be added to `v1` so widgets in the `v1` slot can read the list. This is purely additive and non-breaking. + +```diff + export interface TaggableItemSlotV1Props { + selectedTag: string; ++ selectedTags: string[]; + } +``` + +Also update the slot's README. + +### 2. Render the new version around the old one + +Without a 1:1 mapping from the new props to the old ones, there is a choice to make about what the old slot gets. Here `v1` expects a single tag and `v2` has a list. + +```tsx +const TaggableItemSlot = ({ selectedTags }: TaggableItemSlotV2Props) => { + // v1 takes a single tag. This example gives it the first of the list, or an empty string when the list is empty. + const selectedTag = selectedTags[0] ?? ''; + return ( + + +

Tagged {selectedTags.join(', ')}

+
+
+ ); +}; +``` + +### 3. Mark the old props as deprecated + +Add the `@deprecated` notes as in the prop rename. + +```tsx +/** @deprecated Replaced by `TaggableItemSlotV2Props`, the props of `org.openedx.frontend.slot.example.taggableItem.v2`. */ +export interface TaggableItemSlotV1Props { + /** @deprecated This is the first of `selectedTags`, or an empty string when there are none. Read `selectedTags` instead. */ + selectedTag: string; + selectedTags: string[]; +} +``` + +### 4. Give each version its own README + +Same as for the prop rename. + +### 5. Commit as `feat:` + +Same as for the prop rename. + +### 6. Remove the old version + +Same as for the prop rename. + +## Example: a slot whose default widget takes options + +A tree list slot with one prop, whose default widget lists the trees by name and takes an option to replace or edit the list: + +```tsx +import { Slot, useWidgetOptions } from '@openedx/frontend-base'; + +export interface Tree { + id: string; + name: string; +} + +export interface TreeListSlotProps { + trees: Tree[]; +} + +interface TreeListOptions { + trees?: Tree[] | ((current: Tree[]) => Tree[]); +} + +const DefaultTreeListWidget = ({ trees }: { trees: Tree[] }) => { + const options = useWidgetOptions() as TreeListOptions; + const shown = typeof options.trees === 'function' + ? options.trees(trees) + : options.trees ?? trees; + return ( +
    + {shown.map(tree =>
  • {tree.name}
  • )} +
+ ); +}; + +const TreeListSlot = ({ trees }: TreeListSlotProps) => ( + + + +); + +export default TreeListSlot; +``` + +The app renders the slot with its default list of trees: + +```tsx + +``` + +An operator adds a tree from the site config: + +```ts +{ + slotId: 'org.openedx.frontend.slot.example.treeList.v1', + op: WidgetOperationTypes.OPTIONS, + relatedId: 'defaultContent', + options: { + trees: (current: Tree[]) => [...current, { id: 'quince', name: 'Quince' }], + }, +} +``` + +A new required `foliage` (`evergreen` or `deciduous`) field is being added. + +### 1. Declare the new version's props as a new interface + +Version and alias the old interfaces, including the types they are built from. + +```tsx +export interface TreeV1 { + id: string; + name: string; +} + +export type Tree = TreeV1; + +export interface TreeListSlotV1Props { + trees: TreeV1[]; +} + +export type TreeListSlotProps = TreeListSlotV1Props; +``` + +Declare the new ones with the field. + +```tsx +export type Foliage = 'evergreen' | 'deciduous'; + +export interface TreeV2 { + id: string; + name: string; + foliage: Foliage; +} + +export interface TreeListSlotV2Props { + trees: TreeV2[]; +} +``` + +Version the option's type with them. + +```tsx +type TreeListV1Option = TreeV1[] | ((current: TreeV1[]) => TreeV1[]); + +interface TreeListV1Options { + trees?: TreeListV1Option; +} + +interface TreeListV2Options { + trees?: TreeV2[] | ((current: TreeV2[]) => TreeV2[]); +} +``` + +### 2. Render the new version around the old one + +A `v1` widget or layout expects `v1` trees, so `v1` gets the list without foliage. + +```tsx +const toTreeV1 = ({ foliage, ...tree }: TreeV2): TreeV1 => tree; +``` + +```tsx +const TreeListSlot = ({ trees }: TreeListSlotV2Props) => ( + + + + + +); +``` + +The app's own list gains the field: + +```diff + +``` + +Rebuild the default widget for `v2`, as it will be once `v1` is gone. + +```tsx +const FOLIAGE_ICON: Record = { evergreen: '🌲', deciduous: '🌳' }; + +const DefaultTreeListWidget = ({ trees }: { trees: TreeV2[] }) => { + const options = useWidgetOptions() as TreeListV2Options; + const shown = typeof options.trees === 'function' + ? options.trees(trees) + : options.trees ?? trees; + return ( +
    + {shown.map(tree =>
  • {FOLIAGE_ICON[tree.foliage]} {tree.name}
  • )} +
+ ); +}; +``` + +`useWidgetOptions()` reads the options of the slot the widget is in. With `v2` wrapping `v1`, the widget is in `v1`, so it gets `v1`'s options instead of `v2`'s. This can be worked around by reading `v2`'s options by id. + +```diff + const DefaultTreeListWidget = ({ trees }: { trees: TreeV2[] }) => { +- const options = useWidgetOptions() as TreeListV2Options; ++ // While v1 is wrapped, this widget is v1's defaultContent, so useWidgetOptions() reads v1's options. ++ const v1Options = useWidgetOptions() as TreeListV1Options; ++ const v2Options = useWidgetOptionsForId('org.openedx.frontend.slot.example.treeList.v2', 'defaultContent') as TreeListV2Options; +``` + +Apply `v2`'s option first, to the list exactly as it will be once `v1` is gone, so a `v2` operator never sees a `v1` tree. + +```diff +- const shown = typeof options.trees === 'function' +- ? options.trees(trees) +- : options.trees ?? trees; ++ const v2Trees = typeof v2Options.trees === 'function' ++ ? v2Options.trees(trees) ++ : v2Options.trees ?? trees; +``` + +Put everything `v1` needs in one function. It gives a `v1` option `v1` trees, and gives each tree the option returns its foliage back by id. A tree the option added has none. + +```tsx +type ShownTree = TreeV1 & { foliage?: Foliage }; + +// A v1 option sees and returns v1 trees. A tree it kept gets its foliage back by id; a tree it added has none. +function applyV1Option(option: TreeListV1Option | undefined, trees: TreeV2[]): ShownTree[] { + const v1Trees = trees.map(toTreeV1); + const result = typeof option === 'function' ? option(v1Trees) : option ?? v1Trees; + const foliageOf = (id: string) => trees.find(tree => tree.id === id)?.foliage; + return result.map(tree => ({ ...tree, foliage: foliageOf(tree.id) })); +} +``` + +```diff + : v2Options.trees ?? trees; ++ const shown = applyV1Option(v1Options.trees, v2Trees); +``` + +Show a tree without foliage as 🪾. + +```diff +- {shown.map(tree =>
  • {FOLIAGE_ICON[tree.foliage]} {tree.name}
  • )} ++ {shown.map(tree =>
  • {tree.foliage ? FOLIAGE_ICON[tree.foliage] : '🪾'} {tree.name}
  • )} +``` + +### 3. Mark the old props as deprecated + +Add the `@deprecated` notes as in the prop rename, to the tree type as well as the props. + +```tsx +/** @deprecated Replaced by `TreeV2`, which adds `foliage`. */ +export interface TreeV1 { + id: string; + name: string; +} + +/** @deprecated Renamed to `TreeV1`. */ +export type Tree = TreeV1; +``` + +```tsx +/** @deprecated Replaced by `TreeListSlotV2Props`, the props of `org.openedx.frontend.slot.example.treeList.v2`. */ +export interface TreeListSlotV1Props { + /** @deprecated `trees` in `TreeListSlotV2Props` is `TreeV2[]`. A `v1` option cannot set a tree's foliage. */ + trees: TreeV1[]; +} +``` + +
    +The slot after step 3 + +```tsx +import { Slot, useWidgetOptions, useWidgetOptionsForId } from '@openedx/frontend-base'; + +/** @deprecated Replaced by `TreeV2`, which adds `foliage`. */ +export interface TreeV1 { + id: string; + name: string; +} + +/** @deprecated Renamed to `TreeV1`. */ +export type Tree = TreeV1; + +/** @deprecated Replaced by `TreeListSlotV2Props`, the props of `org.openedx.frontend.slot.example.treeList.v2`. */ +export interface TreeListSlotV1Props { + /** @deprecated `trees` in `TreeListSlotV2Props` is `TreeV2[]`. A `v1` option cannot set a tree's foliage. */ + trees: TreeV1[]; +} + +/** @deprecated Renamed to `TreeListSlotV1Props`. */ +export type TreeListSlotProps = TreeListSlotV1Props; + +export type Foliage = 'evergreen' | 'deciduous'; + +export interface TreeV2 { + id: string; + name: string; + foliage: Foliage; +} + +export interface TreeListSlotV2Props { + trees: TreeV2[]; +} + +type TreeListV1Option = TreeV1[] | ((current: TreeV1[]) => TreeV1[]); + +interface TreeListV1Options { + trees?: TreeListV1Option; +} + +interface TreeListV2Options { + trees?: TreeV2[] | ((current: TreeV2[]) => TreeV2[]); +} + +const toTreeV1 = ({ foliage, ...tree }: TreeV2): TreeV1 => tree; + +type ShownTree = TreeV1 & { foliage?: Foliage }; + +// A v1 option sees and returns v1 trees. A tree it kept gets its foliage back by id; a tree it added has none. +function applyV1Option(option: TreeListV1Option | undefined, trees: TreeV2[]): ShownTree[] { + const v1Trees = trees.map(toTreeV1); + const result = typeof option === 'function' ? option(v1Trees) : option ?? v1Trees; + const foliageOf = (id: string) => trees.find(tree => tree.id === id)?.foliage; + return result.map(tree => ({ ...tree, foliage: foliageOf(tree.id) })); +} + +const FOLIAGE_ICON: Record = { evergreen: '🌲', deciduous: '🌳' }; + +const DefaultTreeListWidget = ({ trees }: { trees: TreeV2[] }) => { + // While v1 is wrapped, this widget is v1's defaultContent, so useWidgetOptions() reads v1's options. + const v1Options = useWidgetOptions() as TreeListV1Options; + const v2Options = useWidgetOptionsForId('org.openedx.frontend.slot.example.treeList.v2', 'defaultContent') as TreeListV2Options; + const v2Trees = typeof v2Options.trees === 'function' + ? v2Options.trees(trees) + : v2Options.trees ?? trees; + const shown = applyV1Option(v1Options.trees, v2Trees); + return ( +
      + {shown.map(tree =>
    • {tree.foliage ? FOLIAGE_ICON[tree.foliage] : '🪾'} {tree.name}
    • )} +
    + ); +}; + +const TreeListSlot = ({ trees }: TreeListSlotV2Props) => ( + + + + + +); + +export default TreeListSlot; +``` + +
    + +### 4. Give each version its own README + +Same as for the prop rename. + +### 5. Commit as `feat:` + +Same as for the prop rename. + +### 6. Remove the old version + +Same as for the prop rename, and everything `v1` needed goes: + +```diff +-import { Slot, useWidgetOptions, useWidgetOptionsForId } from '@openedx/frontend-base'; ++import { Slot, useWidgetOptions } from '@openedx/frontend-base'; +- +-/** @deprecated Replaced by `TreeV2`, which adds `foliage`. */ +-export interface TreeV1 { +- id: string; +- name: string; +-} +- +-/** @deprecated Renamed to `TreeV1`. */ +-export type Tree = TreeV1; +- +-/** @deprecated Replaced by `TreeListSlotV2Props`, the props of `org.openedx.frontend.slot.example.treeList.v2`. */ +-export interface TreeListSlotV1Props { +- /** @deprecated `trees` in `TreeListSlotV2Props` is `TreeV2[]`. A `v1` option cannot set a tree's foliage. */ +- trees: TreeV1[]; +-} +- +-/** @deprecated Renamed to `TreeListSlotV1Props`. */ +-export type TreeListSlotProps = TreeListSlotV1Props; + + export type Foliage = 'evergreen' | 'deciduous'; + + export interface TreeV2 { + id: string; + name: string; + foliage: Foliage; + } + + export interface TreeListSlotV2Props { + trees: TreeV2[]; + } + +-type TreeListV1Option = TreeV1[] | ((current: TreeV1[]) => TreeV1[]); +- +-interface TreeListV1Options { +- trees?: TreeListV1Option; +-} +- + interface TreeListV2Options { + trees?: TreeV2[] | ((current: TreeV2[]) => TreeV2[]); +-} +- +-const toTreeV1 = ({ foliage, ...tree }: TreeV2): TreeV1 => tree; +- +-type ShownTree = TreeV1 & { foliage?: Foliage }; +- +-// A v1 option sees and returns v1 trees. A tree it kept gets its foliage back by id; a tree it added has none. +-function applyV1Option(option: TreeListV1Option | undefined, trees: TreeV2[]): ShownTree[] { +- const v1Trees = trees.map(toTreeV1); +- const result = typeof option === 'function' ? option(v1Trees) : option ?? v1Trees; +- const foliageOf = (id: string) => trees.find(tree => tree.id === id)?.foliage; +- return result.map(tree => ({ ...tree, foliage: foliageOf(tree.id) })); + } + + const FOLIAGE_ICON: Record = { evergreen: '🌲', deciduous: '🌳' }; + + const DefaultTreeListWidget = ({ trees }: { trees: TreeV2[] }) => { +- // While v1 is wrapped, this widget is v1's defaultContent, so useWidgetOptions() reads v1's options. +- const v1Options = useWidgetOptions() as TreeListV1Options; +- const v2Options = useWidgetOptionsForId('org.openedx.frontend.slot.example.treeList.v2', 'defaultContent') as TreeListV2Options; +- const v2Trees = typeof v2Options.trees === 'function' +- ? v2Options.trees(trees) +- : v2Options.trees ?? trees; +- const shown = applyV1Option(v1Options.trees, v2Trees); ++ const options = useWidgetOptions() as TreeListV2Options; ++ const shown = typeof options.trees === 'function' ++ ? options.trees(trees) ++ : options.trees ?? trees; + return ( +
      +- {shown.map(tree =>
    • {tree.foliage ? FOLIAGE_ICON[tree.foliage] : '🪾'} {tree.name}
    • )} ++ {shown.map(tree =>
    • {FOLIAGE_ICON[tree.foliage]} {tree.name}
    • )} +
    + ); + }; + + const TreeListSlot = ({ trees }: TreeListSlotV2Props) => ( + +- +- +- ++ + + ); + + export default TreeListSlot; +``` + +
    +The slot after step 6 + +```tsx +import { Slot, useWidgetOptions } from '@openedx/frontend-base'; + +export type Foliage = 'evergreen' | 'deciduous'; + +export interface TreeV2 { + id: string; + name: string; + foliage: Foliage; +} + +export interface TreeListSlotV2Props { + trees: TreeV2[]; +} + +interface TreeListV2Options { + trees?: TreeV2[] | ((current: TreeV2[]) => TreeV2[]); +} + +const FOLIAGE_ICON: Record = { evergreen: '🌲', deciduous: '🌳' }; + +const DefaultTreeListWidget = ({ trees }: { trees: TreeV2[] }) => { + const options = useWidgetOptions() as TreeListV2Options; + const shown = typeof options.trees === 'function' + ? options.trees(trees) + : options.trees ?? trees; + return ( +
      + {shown.map(tree =>
    • {FOLIAGE_ICON[tree.foliage]} {tree.name}
    • )} +
    + ); +}; + +const TreeListSlot = ({ trees }: TreeListSlotV2Props) => ( + + + +); + +export default TreeListSlot; +``` + +
    + +A `v2` operator's option was applied to the plain `v2` list before the removal and is applied to the same list after it, so a `v2` site config does not notice the removal. + +## Example: renaming a slot + +A song controls slot with two props: + +```tsx +import { Slot } from '@openedx/frontend-base'; + +export interface SongControlsSlotProps { + onPlay: () => void; + onPause: () => void; +} + +const SongControlsSlot = ({ onPlay, onPause }: SongControlsSlotProps) => ( + + + + +); + +export default SongControlsSlot; +``` + +Podcast episodes are being added beside the songs, so the slot is being renamed to `trackControls`. Its props, the place it renders and what it wraps stay the same, so nothing in its API contract changes and nothing calls for a new version. Simply renaming the id would still break every operator's site config: an operation written against the old id stops applying. + +```diff +-export interface SongControlsSlotProps { ++export interface TrackControlsSlotProps { + onPlay: () => void; + onPause: () => void; + } + +-const SongControlsSlot = ({ onPlay, onPause }: SongControlsSlotProps) => ( +- ++const TrackControlsSlot = ({ onPlay, onPause }: TrackControlsSlotProps) => ( ++ + + + + ); +``` + +The steps below rename the slot while leaving the old id working. + +### 1. Rename the component and its props interface + +Rename the component, its file and folder, and its props interface. The interface's name is an export, so keep the old name as an alias of the new one. + +```tsx +export interface TrackControlsSlotProps { + onPlay: () => void; + onPause: () => void; +} + +/** @deprecated Renamed to `TrackControlsSlotProps`. */ +export type SongControlsSlotProps = TrackControlsSlotProps; +``` + +### 2. Keep the old id as an alias + +Render under the new id, with the old id in `idAliases`. + +```tsx +const TrackControlsSlot = ({ onPlay, onPause }: TrackControlsSlotProps) => ( + + + + +); +``` + +### 3. Update the README + +Change the slot id in the README's title and examples, and add a note at the top: + +```markdown +> [!WARNING] +> `org.openedx.frontend.slot.example.songControls.v1` is deprecated and will be +> removed in a future release. Use `org.openedx.frontend.slot.example.trackControls.v1` +> instead. +``` + +### 4. Commit as `feat:` + +Adding an alias is not a breaking change to the app, so this is `feat:` and not `feat!:`. The commit body should say which id is deprecated and what replaces it. + +```text +feat: rename the song controls slot to track controls + +org.openedx.frontend.slot.example.songControls.v1 is deprecated and will +be removed in a future release. Use +org.openedx.frontend.slot.example.trackControls.v1 instead. +``` + +### 5. Remove the alias + +Once the deprecation process allows it, and at least one Open edX named release has shipped with the alias, remove it and the interface alias: + +```diff + import { Slot } from '@openedx/frontend-base'; + + export interface TrackControlsSlotProps { + onPlay: () => void; + onPause: () => void; + } + +-/** @deprecated Renamed to `TrackControlsSlotProps`. */ +-export type SongControlsSlotProps = TrackControlsSlotProps; +- + const TrackControlsSlot = ({ onPlay, onPause }: TrackControlsSlotProps) => ( + + + + + ); + + export default TrackControlsSlot; +``` + +Delete the note from `README.md`. + +Removing the alias is a breaking change to the app, so this commit is `feat!:`. + +```text +feat!: remove the song controls slot alias + +BREAKING CHANGE: org.openedx.frontend.slot.example.songControls.v1 and +SongControlsSlotProps are removed. Use +org.openedx.frontend.slot.example.trackControls.v1 and +TrackControlsSlotProps instead. +``` + +## Example: renaming a slot when its props change + +A song list slot with one prop: + +```tsx +import { Slot } from '@openedx/frontend-base'; + +export interface Song { + id: string; + title: string; +} + +export interface SongListSlotProps { + songs: Song[]; +} + +const SongListSlot = ({ songs }: SongListSlotProps) => ( + +
      + {songs.map(song =>
    • {song.title}
    • )} +
    +
    +); + +export default SongListSlot; +``` + +Podcast episodes are being added to the list. The slot's id and props are changing: + +```diff +-export interface SongListSlotProps { +- songs: Song[]; ++export interface TrackListSlotProps { ++ tracks: Track[]; + } + +-const SongListSlot = ({ songs }: SongListSlotProps) => ( +- ++const TrackListSlot = ({ tracks }: TrackListSlotProps) => ( ++ +
      +- {songs.map(song =>
    • {song.title}
    • )} ++ {tracks.map(track =>
    • {track.title}
    • )} +
    +
    + ); +``` + +### 1. Declare the new slot's props as a new interface + +`Track` and `TrackKind` are new, so they are declared here and exported from the app's `index.ts` beside the slot props. + +```tsx +export type TrackKind = 'song' | 'episode'; + +export interface Track { + id: string; + title: string; + kind: TrackKind; +} + +export interface TrackListSlotProps { + tracks: Track[]; +} +``` + +### 2. Render the new slot around the old one + +Rename the component, its file and its folder with the slot, and wrap the old `` in the new one. + +```tsx +const TrackListSlot = ({ tracks }: TrackListSlotProps) => { + // The old slot takes songs only, so it gets the songs out of the list. + const songs: Song[] = tracks.filter(track => track.kind === 'song'); + return ( + + +
      + {tracks.map(track =>
    • {track.title}
    • )} +
    +
    +
    + ); +}; +``` + +### 3. Mark the old props as deprecated + +Add a `@deprecated` note to the old interface and to each member whose replacement has another name. + +```tsx +/** @deprecated Replaced by `TrackListSlotProps`, the props of `org.openedx.frontend.slot.example.trackList.v1`. */ +export interface SongListSlotProps { + /** @deprecated These are the songs in `tracks` of `TrackListSlotProps`. */ + songs: Song[]; +} +``` + +### 4. Give each slot its own README + +Same as for the prop rename, with the old slot's `README.md` renamed to `README.songList.v1.md`. The note at its top: + +```markdown +> [!WARNING] +> `org.openedx.frontend.slot.example.songList.v1` is deprecated and will be +> removed in a future release. Use `org.openedx.frontend.slot.example.trackList.v1` +> instead. +``` + +### 5. Commit as `feat:` + +Adding a slot beside a working one is not a breaking change to the app, so this is `feat:` and not `feat!:`. The commit body should say which slot is deprecated and what replaces it. + +```text +feat: add track list slot, deprecate song list slot + +org.openedx.frontend.slot.example.songList.v1 is deprecated and will be +removed in a future release. Use +org.openedx.frontend.slot.example.trackList.v1 instead. +``` + +### 6. Remove the old slot + +Once the deprecation process allows it, and at least one Open edX named release has shipped with both slots, remove the old one and everything only it needed: + +```diff + import { Slot } from '@openedx/frontend-base'; + +-export interface Song { +- id: string; +- title: string; +-} +- + export type TrackKind = 'song' | 'episode'; + + export interface Track { + id: string; + title: string; + kind: TrackKind; + } + +-/** @deprecated Replaced by `TrackListSlotProps`, the props of `org.openedx.frontend.slot.example.trackList.v1`. */ +-export interface SongListSlotProps { +- /** @deprecated These are the songs in `tracks` of `TrackListSlotProps`. */ +- songs: Song[]; +-} +- + export interface TrackListSlotProps { + tracks: Track[]; + } + +-const TrackListSlot = ({ tracks }: TrackListSlotProps) => { +- // The old slot takes songs only, so it gets the songs out of the list. +- const songs: Song[] = tracks.filter(track => track.kind === 'song'); +- return ( +- +- +-
      +- {tracks.map(track =>
    • {track.title}
    • )} +-
    +-
    +-
    +- ); +-}; ++const TrackListSlot = ({ tracks }: TrackListSlotProps) => ( ++ ++
      ++ {tracks.map(track =>
    • {track.title}
    • )} ++
    ++
    ++); + + export default TrackListSlot; +``` + +Delete `README.songList.v1.md` and the link to it from `README.md`. + +Removing the old slot is a breaking change to the app, so this commit is `feat!:`. + +```text +feat!: remove the song list slot + +BREAKING CHANGE: org.openedx.frontend.slot.example.songList.v1, +SongListSlotProps and Song are removed. Use +org.openedx.frontend.slot.example.trackList.v1, TrackListSlotProps and +Track instead. +``` diff --git a/runtime/slots/howToExamples.drift.test.ts b/runtime/slots/howToExamples.drift.test.ts new file mode 100644 index 00000000..b9f4361e --- /dev/null +++ b/runtime/slots/howToExamples.drift.test.ts @@ -0,0 +1,177 @@ +// Guards docs/how_tos/add-a-slot-version.md against drifting from the fixtures that howToExamples.test.tsx runs. +// Every ts or tsx block under an example heading in the how-to, and both sides of every diff block, must appear in one of that example's fixtures. +// A block whose fence the guard does not read, such as "typescript" or an indented one, would drop out silently, so every fence opener is checked too. +import fs from 'fs'; +import path from 'path'; + +const HOW_TO = path.resolve(__dirname, '../../docs/how_tos/add-a-slot-version.md'); +const FIXTURES = path.resolve(__dirname, 'testMocks'); + +// Example heading in the how-to, exactly as written after "## Example: ", mapped to its fixture files. +const EXAMPLES: Record = { + 'renaming a prop': [ + 'GreetingSlotV1.tsx', + 'GreetingSlotV1V2.tsx', + 'GreetingSlotV2.tsx', + 'GreetingSlotRenamedInPlace.tsx', + 'GreetingSlotBumpedInPlace.tsx', + 'greetingWidgets.tsx', + ], + "changing a prop's type": ['BannerSlotV1.tsx', 'BannerSlotV1V2.tsx', 'BannerSlotV2.tsx'], + 'a slot whose default widget takes options': [ + 'TreeListSlotV1.tsx', + 'TreeListSlotV1V2.tsx', + 'TreeListSlotV2.tsx', + 'treeListOptions.ts', + 'TreeListPageV1.tsx', + 'TreeListPageV2.tsx', + ], + 'a prop that becomes a list': [ + 'TaggableItemSlotV1.tsx', + 'TaggableItemSlotV1V2FirstTagOnly.tsx', + 'TaggableItemSlotV1V2.tsx', + 'TaggableItemSlotV2.tsx', + ], + 'renaming a slot': [ + 'SongControlsSlot.tsx', + 'TrackControlsSlotNoAlias.tsx', + 'TrackControlsSlotAliased.tsx', + 'TrackControlsSlot.tsx', + ], + 'renaming a slot when its props change': [ + 'SongListSlot.tsx', + 'TrackListSlotWrappingSongList.tsx', + 'TrackListSlot.tsx', + ], +}; + +// Import lines differ by necessity: the how-to imports from the package, the fixtures from the repo. +// Comments are checked separately, line by line, because the how-to shows the interfaces both with and without their doc comments. +function normalize(code: string) { + return code + .split('\n') + .filter(line => !line.startsWith('import ') && !line.trim().startsWith('/**') && !line.trim().startsWith('//')) + .join('\n') + .replace(/\s+/g, ' ') + .trim(); +} + +function commentLines(code: string) { + return code.split('\n').map(line => line.trim()).filter(line => line.startsWith('/**') || line.startsWith('//')); +} + +interface Section { + text: string; + // The 1-based line of the heading in the how-to, so a block's label can say where it is. + startLine: number; +} + +function sectionsByExample(markdown: string) { + const sections: Record = {}; + let startLine = 1; + for (const text of markdown.split(/^(?=## )/m)) { + const match = /^## Example: (.+)\n/.exec(text); + if (match) { + sections[match[1].trim()] = { text, startLine }; + } + startLine += text.split('\n').length - 1; + } + return sections; +} + +const EMPTY_SECTION: Section = { text: '', startLine: 0 }; + +function lineOf(section: Section, index: number) { + return section.startLine + section.text.slice(0, index).split('\n').length - 1; +} + +// The fences the guard reads, plus "markdown" for the README excerpt and "text" for commit messages, which are prose. +const KNOWN_FENCES = ['ts', 'tsx', 'diff', 'markdown', 'text']; + +function fenceOpeners(section: Section) { + const openers: string[] = []; + let open = false; + for (const line of section.text.split('\n')) { + if (line.trimStart().startsWith('```')) { + if (!open) { + openers.push(line); + } + open = !open; + } + } + return openers; +} + +interface CodeBlock { + label: string; + code: string; +} + +function tsBlocks(section: Section): CodeBlock[] { + return [...section.text.matchAll(/^```(tsx?)\n([\s\S]*?)^```/gm)].map(m => ({ + label: `line ${lineOf(section, m.index)} ${m[1]} "${m[2].split('\n')[0]}"`, + code: m[2], + })); +} + +// A diff block's before state is its context and "-" lines; its after state is its context and "+" lines. +function diffBlocks(section: Section): CodeBlock[] { + return [...section.text.matchAll(/^```diff\n([\s\S]*?)^```/gm)].flatMap((m) => { + const lines = m[1].split('\n'); + const side = (dropped: string) => lines.filter(line => !line.startsWith(dropped)).map(line => line.slice(1)).join('\n'); + const first = lines.find(line => line.trim() !== '')?.slice(1) ?? ''; + const label = `line ${lineOf(section, m.index)} diff "${first}"`; + return [ + { label: `${label} before`, code: side('+') }, + { label: `${label} after`, code: side('-') }, + ]; + }); +} + +function codeBlocks(section: Section) { + return [...tsBlocks(section), ...diffBlocks(section)]; +} + +describe('the slot version how-to', () => { + const markdown = fs.readFileSync(HOW_TO, 'utf8'); + const sections = sectionsByExample(markdown); + + it('has a fixture mapping for every example, and an example for every mapping', () => { + const headings = Object.keys(sections).filter(name => codeBlocks(sections[name]).length > 0); + expect(headings.sort()).toEqual(Object.keys(EXAMPLES).sort()); + }); + + describe.each(Object.entries(EXAMPLES))('example "%s"', (name, fixtureFiles) => { + const fixtures = fixtureFiles.map(file => fs.readFileSync(path.join(FIXTURES, file), 'utf8')); + const normalizedFixtures = fixtures.map(normalize); + const section = sections[name] ?? EMPTY_SECTION; + const blocks = codeBlocks(section); + // One comment can appear in several blocks; it is checked once. + const comments = [...new Set(blocks.flatMap(block => commentLines(block.code)))]; + + it('has at least one code block', () => { + expect(blocks.length).toBeGreaterThan(0); + }); + + it('opens every code block with a fence the guard reads', () => { + expect(fenceOpeners(section).filter(line => !KNOWN_FENCES.includes(line.slice(3)))).toEqual([]); + }); + + it('writes every doc comment on one line', () => { + expect(comments.filter(line => line.startsWith('/**') && !line.endsWith('*/'))).toEqual([]); + }); + + // it.each throws on an empty table; the two tests above report those cases. + if (blocks.length > 0) { + it.each(blocks.map(block => [block.label, block.code]))('%s appears in a fixture', (_label, code) => { + expect(normalizedFixtures).toContainEqual(expect.stringContaining(normalize(code))); + }); + } + + if (comments.length > 0) { + it.each(comments.map(line => [line]))('comment %s appears in a fixture', (line) => { + expect(fixtures).toContainEqual(expect.stringContaining(line)); + }); + } + }); +}); diff --git a/runtime/slots/howToExamples.test.tsx b/runtime/slots/howToExamples.test.tsx new file mode 100644 index 00000000..b2c97c7e --- /dev/null +++ b/runtime/slots/howToExamples.test.tsx @@ -0,0 +1,644 @@ +// Exercises the example slots from docs/how_tos/add-a-slot-version.md the ways an operator can use them. +// howToExamples.drift.test.ts checks that the fixtures still match the markdown. +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter } from 'react-router-dom'; +import { ComponentType, ReactElement } from 'react'; +import { getSiteConfig, setSiteConfig } from '../config'; +import { LayoutOperationTypes, SlotOperation, useSlotContext, useWidgets, WidgetOperationTypes } from '.'; +import { useWidgetOptions, useWidgetOptionsForId } from './widget/hooks'; +import GreetingSlotV1 from './testMocks/GreetingSlotV1'; +import GreetingSlotV1V2, { GreetingSlotProps, GreetingSlotV2Props } from './testMocks/GreetingSlotV1V2'; +import GreetingSlotV2 from './testMocks/GreetingSlotV2'; +import GreetingSlotRenamedInPlace, { GreetingSlotProps as RenamedInPlaceProps } from './testMocks/GreetingSlotRenamedInPlace'; +import GreetingSlotBumpedInPlace from './testMocks/GreetingSlotBumpedInPlace'; +import { customGreetingV1, customGreetingV2 } from './testMocks/greetingWidgets'; +import BannerSlotV1 from './testMocks/BannerSlotV1'; +import BannerSlotV1V2, { BannerSlotProps, BannerSlotV2Props, Notice } from './testMocks/BannerSlotV1V2'; +import BannerSlotV2 from './testMocks/BannerSlotV2'; +import TaggableItemSlotV1 from './testMocks/TaggableItemSlotV1'; +import TaggableItemSlotV1V2, { TaggableItemSlotProps, TaggableItemSlotV2Props } from './testMocks/TaggableItemSlotV1V2'; +import TaggableItemSlotV2 from './testMocks/TaggableItemSlotV2'; +import TaggableItemSlotV1V2FirstTagOnly, { TaggableItemSlotProps as FirstTagOnlyProps } from './testMocks/TaggableItemSlotV1V2FirstTagOnly'; +import TreeListSlotV1 from './testMocks/TreeListSlotV1'; +import TreeListSlotV1V2, { Foliage, TreeListSlotProps, TreeListSlotV2Props, TreeV1, TreeV2 } from './testMocks/TreeListSlotV1V2'; +import TreeListSlotV2 from './testMocks/TreeListSlotV2'; +import { addQuinceV1 } from './testMocks/treeListOptions'; +import TreeListPageV1 from './testMocks/TreeListPageV1'; +import TreeListPageV2 from './testMocks/TreeListPageV2'; +import SongControlsSlot, { SongControlsSlotProps } from './testMocks/SongControlsSlot'; +import TrackControlsSlotNoAlias from './testMocks/TrackControlsSlotNoAlias'; +import TrackControlsSlotAliased, { TrackControlsSlotProps } from './testMocks/TrackControlsSlotAliased'; +import TrackControlsSlot from './testMocks/TrackControlsSlot'; +import SongListSlot from './testMocks/SongListSlot'; +import TrackListSlotWrappingSongList, { SongListSlotProps, Track, TrackListSlotProps } from './testMocks/TrackListSlotWrappingSongList'; +import TrackListSlot from './testMocks/TrackListSlot'; + +interface ExampleSpec { + v1Id: string; + v2Id: string; + // What the test names call the two slots. A new version is "v1" and "v2"; a renamed slot is its old and new identifier. + names?: [string, string]; + // The slot rendered in each state the how-to shows. + v1Only: ReactElement; + both: ReactElement; + v2Only: ReactElement; + // What the default content prints for the value under test. + defaultContentText: string | RegExp; + // A component widget written against each version's props, and what it prints. + v1Widget: ComponentType; + v1WidgetText: string; + v2Widget: ComponentType; + v2WidgetText: string; + // A replacement layout for each version that reads the slot's props through useSlotContext(), and what it prints. + v1Layout: ComponentType; + v1LayoutText: string; + v2Layout: ComponentType; + v2LayoutText: string; +} + +function configureSlots(slots: SlotOperation[]) { + setSiteConfig({ ...getSiteConfig(), apps: [{ appId: 'example-app', slots }] }); +} + +function renderSlot(element: ReactElement) { + return render({element}); +} + +const replaceDefaultContent = (slotId: string, element: ReactElement): SlotOperation => ({ + slotId, id: 'replacement', op: WidgetOperationTypes.REPLACE, relatedId: 'defaultContent', element, +}); + +const appendWidget = (slotId: string, id: string, component: ComponentType): SlotOperation => ({ + slotId, id, op: WidgetOperationTypes.APPEND, component, +}); + +const replaceLayout = (slotId: string, component: ComponentType): SlotOperation => ({ + slotId, op: LayoutOperationTypes.REPLACE, component, +}); + +const setOptions = (slotId: string, options: Record, widgetId = 'defaultContent'): SlotOperation => ({ + slotId, op: WidgetOperationTypes.OPTIONS, relatedId: widgetId, options, +}); + +function describeExample(name: string, spec: ExampleSpec) { + const [v1, v2] = spec.names ?? ['v1', 'v2']; + describe(name, () => { + afterEach(() => { + setSiteConfig({ ...getSiteConfig(), apps: [] }); + }); + + describe.each([ + [`${v1} only`, spec.v1Only], + [`${v2} wrapping ${v1}`, spec.both], + [`${v2} only`, spec.v2Only], + ])('%s', (_state, element) => { + it('renders the default content with no operations', () => { + renderSlot(element); + expect(screen.getByText(spec.defaultContentText)).toBeInTheDocument(); + }); + }); + + describe.each([ + [`${v1} only`, spec.v1Only], + [`${v2} wrapping ${v1}`, spec.both], + ])('%s', (_state, element) => { + it(`passes the ${v1} props to a ${v1} component widget`, () => { + configureSlots([appendWidget(spec.v1Id, 'v1Widget', spec.v1Widget)]); + renderSlot(element); + expect(screen.getByText(spec.v1WidgetText)).toBeInTheDocument(); + }); + + it(`lets a ${v1} operation replace the default content`, () => { + configureSlots([replaceDefaultContent(spec.v1Id,

    {`${v1} replacement`}

    )]); + renderSlot(element); + expect(screen.getByText(`${v1} replacement`)).toBeInTheDocument(); + expect(screen.queryByText(spec.defaultContentText)).not.toBeInTheDocument(); + }); + + it(`gives a ${v1} layout the ${v1} props through useSlotContext()`, () => { + configureSlots([replaceLayout(spec.v1Id, spec.v1Layout)]); + renderSlot(element); + expect(screen.getByText(spec.v1LayoutText)).toBeInTheDocument(); + expect(screen.getByText(spec.defaultContentText)).toBeInTheDocument(); + }); + }); + + describe.each([ + [`${v2} wrapping ${v1}`, spec.both], + [`${v2} only`, spec.v2Only], + ])('%s', (_state, element) => { + it(`passes the ${v2} props to a ${v2} component widget`, () => { + configureSlots([appendWidget(spec.v2Id, 'v2Widget', spec.v2Widget)]); + renderSlot(element); + expect(screen.getByText(spec.v2WidgetText)).toBeInTheDocument(); + }); + + it(`lets a ${v2} operation replace the default content`, () => { + configureSlots([replaceDefaultContent(spec.v2Id,

    {`${v2} replacement`}

    )]); + renderSlot(element); + expect(screen.getByText(`${v2} replacement`)).toBeInTheDocument(); + expect(screen.queryByText(spec.defaultContentText)).not.toBeInTheDocument(); + }); + + it(`gives a ${v2} layout the ${v2} props through useSlotContext()`, () => { + configureSlots([replaceLayout(spec.v2Id, spec.v2Layout)]); + renderSlot(element); + expect(screen.getByText(spec.v2LayoutText)).toBeInTheDocument(); + expect(screen.getByText(spec.defaultContentText)).toBeInTheDocument(); + }); + }); + + describe(`${v2} wrapping ${v1}`, () => { + it(`renders widgets appended to ${v1} and to ${v2} together`, () => { + configureSlots([ + appendWidget(spec.v1Id, 'v1Widget', spec.v1Widget), + appendWidget(spec.v2Id, 'v2Widget', spec.v2Widget), + ]); + renderSlot(spec.both); + expect(screen.getByText(spec.defaultContentText)).toBeInTheDocument(); + expect(screen.getByText(spec.v1WidgetText)).toBeInTheDocument(); + expect(screen.getByText(spec.v2WidgetText)).toBeInTheDocument(); + }); + + it(`takes ${v1} and its widgets away when a ${v2} operation replaces the default content`, () => { + configureSlots([ + appendWidget(spec.v1Id, 'v1Widget', spec.v1Widget), + replaceDefaultContent(spec.v2Id,

    {`${v2} replacement`}

    ), + ]); + renderSlot(spec.both); + expect(screen.getByText(`${v2} replacement`)).toBeInTheDocument(); + expect(screen.queryByText(spec.defaultContentText)).not.toBeInTheDocument(); + expect(screen.queryByText(spec.v1WidgetText)).not.toBeInTheDocument(); + }); + + it(`keeps ${v1} and its widgets inside a replaced ${v2} layout`, () => { + configureSlots([ + appendWidget(spec.v1Id, 'v1Widget', spec.v1Widget), + replaceLayout(spec.v2Id, spec.v2Layout), + ]); + renderSlot(spec.both); + expect(screen.getByText(spec.v2LayoutText)).toBeInTheDocument(); + expect(screen.getByText(spec.defaultContentText)).toBeInTheDocument(); + expect(screen.getByText(spec.v1WidgetText)).toBeInTheDocument(); + }); + }); + + describe(`${v2} only`, () => { + it(`ignores a ${v1} operation`, () => { + configureSlots([appendWidget(spec.v1Id, 'v1Widget', spec.v1Widget)]); + renderSlot(spec.v2Only); + expect(screen.getByText(spec.defaultContentText)).toBeInTheDocument(); + expect(screen.queryByText(spec.v1WidgetText)).not.toBeInTheDocument(); + }); + }); + }); +} + +// A layout reads the slot's props through SlotContext, whose type is its fixed members plus an index signature. +function useSlotProps() { + return useSlotContext() as unknown as Props; +} + +function LayoutPrinting({ text }: { text: string }) { + const widgets = useWidgets(); + return ( +
    +

    {text}

    + {widgets} +
    + ); +} + +// Renaming a prop: userName becomes displayName. +const GreetingV1Widget = ({ userName }: GreetingSlotProps) =>

    v1 widget: {userName}

    ; +const GreetingV2Widget = ({ displayName }: GreetingSlotV2Props) =>

    v2 widget: {displayName}

    ; +const GreetingV1Layout = () => { + const { userName } = useSlotProps(); + return ; +}; +const GreetingV2Layout = () => { + const { displayName } = useSlotProps(); + return ; +}; + +const greetingV1Only = ; +const greetingBoth = ; +const greetingV2Only = ; + +describeExample('renaming a prop', { + v1Id: 'org.openedx.frontend.slot.example.greeting.v1', + v2Id: 'org.openedx.frontend.slot.example.greeting.v2', + v1Only: greetingV1Only, + both: greetingBoth, + v2Only: greetingV2Only, + defaultContentText: 'Hello, Ada', + v1Widget: GreetingV1Widget, + v1WidgetText: 'v1 widget: Ada', + v2Widget: GreetingV2Widget, + v2WidgetText: 'v2 widget: Ada', + v1Layout: GreetingV1Layout, + v1LayoutText: 'v1 layout: Ada', + v2Layout: GreetingV2Layout, + v2LayoutText: 'v2 layout: Ada', +}); + +describe('renaming a prop', () => { + afterEach(() => { + setSiteConfig({ ...getSiteConfig(), apps: [] }); + }); + + describe("the operator's widget from the how-to", () => { + it.each([ + ['v1 only', greetingV1Only], + ['v2 wrapping v1', greetingBoth], + ])('replaces the default content of %s before the move', (_state, element) => { + configureSlots([customGreetingV1]); + renderSlot(element); + expect(screen.getByText('Welcome back, Ada')).toBeInTheDocument(); + expect(screen.queryByText('Hello, Ada')).not.toBeInTheDocument(); + }); + + it.each([ + ['v2 wrapping v1', greetingBoth], + ['v2 only', greetingV2Only], + ])('replaces the default content of %s after the move', (_state, element) => { + configureSlots([customGreetingV2]); + renderSlot(element); + expect(screen.getByText('Welcome back, Ada')).toBeInTheDocument(); + expect(screen.queryByText('Hello, Ada')).not.toBeInTheDocument(); + }); + + it('does nothing to v2 only before the move', () => { + configureSlots([customGreetingV1]); + renderSlot(greetingV2Only); + expect(screen.getByText('Hello, Ada')).toBeInTheDocument(); + expect(screen.queryByText('Welcome back, Ada')).not.toBeInTheDocument(); + }); + }); + + describe('renamed in place', () => { + it('gives a widget that reads userName undefined', () => { + // @ts-expect-error The typecheck verifies the other half of the how-to's claim: userName is no longer a member of GreetingSlotProps. + const ReadsUserName = ({ userName }: RenamedInPlaceProps) =>

    Welcome back, {String(userName)}

    ; + configureSlots([appendWidget('org.openedx.frontend.slot.example.greeting.v1', 'readsUserName', ReadsUserName)]); + renderSlot(); + expect(screen.getByText('Welcome back, undefined')).toBeInTheDocument(); + }); + }); + + describe('bumped in place', () => { + it('removes v1 from the app', () => { + configureSlots([customGreetingV1]); + renderSlot(); + expect(screen.getByText('Hello, Ada')).toBeInTheDocument(); + expect(screen.queryByText('Welcome back, Ada')).not.toBeInTheDocument(); + }); + }); +}); + +// Changing a prop's type: message becomes a notice object. +const notice: Notice = { message: 'Maintenance tonight', severity: 'warning', onDismiss: () => {} }; +const BannerV1Widget = ({ message }: BannerSlotProps) =>

    v1 widget: {message}

    ; +const BannerV2Widget = ({ notice: n }: BannerSlotV2Props) =>

    v2 widget: {n.severity} {n.message}

    ; +const BannerV1Layout = () => { + const { message } = useSlotProps(); + return ; +}; +const BannerV2Layout = () => { + const { notice: n } = useSlotProps(); + return ; +}; + +describeExample("changing a prop's type", { + v1Id: 'org.openedx.frontend.slot.example.banner.v1', + v2Id: 'org.openedx.frontend.slot.example.banner.v2', + v1Only: , + both: , + v2Only: , + defaultContentText: 'Maintenance tonight', + v1Widget: BannerV1Widget, + v1WidgetText: 'v1 widget: Maintenance tonight', + v2Widget: BannerV2Widget, + v2WidgetText: 'v2 widget: warning Maintenance tonight', + v1Layout: BannerV1Layout, + v1LayoutText: 'v1 layout: Maintenance tonight', + v2Layout: BannerV2Layout, + v2LayoutText: 'v2 layout: warning Maintenance tonight', +}); + +// A prop that becomes a list: selectedTag becomes selectedTags, and v1 gains the list too. +const TaggableItemV1Widget = ({ selectedTag }: TaggableItemSlotProps) =>

    v1 widget: {selectedTag}

    ; +const TaggableItemV2Widget = ({ selectedTags }: TaggableItemSlotV2Props) =>

    v2 widget: {selectedTags.join(', ')}

    ; +const TaggableItemV1Layout = () => { + const { selectedTag } = useSlotProps(); + return ; +}; +const TaggableItemV2Layout = () => { + const { selectedTags } = useSlotProps(); + return ; +}; + +describeExample('a prop that becomes a list', { + v1Id: 'org.openedx.frontend.slot.example.taggableItem.v1', + v2Id: 'org.openedx.frontend.slot.example.taggableItem.v2', + v1Only: , + both: , + v2Only: , + defaultContentText: 'Tagged red', + v1Widget: TaggableItemV1Widget, + v1WidgetText: 'v1 widget: red', + v2Widget: TaggableItemV2Widget, + v2WidgetText: 'v2 widget: red', + v1Layout: TaggableItemV1Layout, + v1LayoutText: 'v1 layout: red', + v2Layout: TaggableItemV2Layout, + v2LayoutText: 'v2 layout: red', +}); + +describe('a prop that becomes a list', () => { + afterEach(() => { + setSiteConfig({ ...getSiteConfig(), apps: [] }); + }); + + it('gives a v1 widget only the first tag before the list is added to v1', () => { + const PrintsProps = (props: FirstTagOnlyProps) =>

    v1 widget: {JSON.stringify(props)}

    ; + configureSlots([appendWidget('org.openedx.frontend.slot.example.taggableItem.v1', 'printsProps', PrintsProps)]); + renderSlot(); + expect(screen.getByText('v1 widget: {"selectedTag":"red"}')).toBeInTheDocument(); + }); + + it('gives a v1 widget an empty string when the list is empty', () => { + const ReadsTagLiterally = ({ selectedTag }: TaggableItemSlotProps) =>

    v1 widget: {JSON.stringify(selectedTag)}

    ; + configureSlots([appendWidget('org.openedx.frontend.slot.example.taggableItem.v1', 'readsTagLiterally', ReadsTagLiterally)]); + renderSlot(); + expect(screen.getByText('v1 widget: ""')).toBeInTheDocument(); + }); + + it('gives a v1 widget the first tag under the old name and the whole list under the new one', () => { + const ReadsBoth = ({ selectedTag, selectedTags }: TaggableItemSlotProps) =>

    v1 widget: {selectedTag} of {selectedTags.join(', ')}

    ; + configureSlots([appendWidget('org.openedx.frontend.slot.example.taggableItem.v1', 'readsBoth', ReadsBoth)]); + renderSlot(); + expect(screen.getByText('v1 widget: red of red, blue')).toBeInTheDocument(); + }); +}); + +// A slot whose default widget takes options: every tree gains a required foliage, shown as an icon. +const trees: TreeV2[] = [ + { id: 'teak', name: 'Teak', foliage: 'deciduous' }, + { id: 'sumac', name: 'Sumac', foliage: 'deciduous' }, + { id: 'redwood', name: 'Redwood', foliage: 'evergreen' }, +]; +const TreeListV1Widget = ({ trees: t }: TreeListSlotProps) =>

    v1 widget: {t.length}

    ; +const TreeListV2Widget = ({ trees: t }: TreeListSlotV2Props) =>

    v2 widget: {t.length}

    ; +const TreeListV1Layout = () => { + const { trees: t } = useSlotProps(); + return ; +}; +const TreeListV2Layout = () => { + const { trees: t } = useSlotProps(); + return ; +}; + +const treeListV1Only = ; +const treeListBoth = ; +const treeListV2Only = ; + +describeExample('a slot whose default widget takes options', { + v1Id: 'org.openedx.frontend.slot.example.treeList.v1', + v2Id: 'org.openedx.frontend.slot.example.treeList.v2', + v1Only: treeListV1Only, + both: treeListBoth, + v2Only: treeListV2Only, + defaultContentText: /Redwood$/, + v1Widget: TreeListV1Widget, + v1WidgetText: 'v1 widget: 3', + v2Widget: TreeListV2Widget, + v2WidgetText: 'v2 widget: 3', + v1Layout: TreeListV1Layout, + v1LayoutText: 'v1 layout: 3', + v2Layout: TreeListV2Layout, + v2LayoutText: 'v2 layout: 3', +}); + +describe('a slot whose default widget takes options', () => { + afterEach(() => { + setSiteConfig({ ...getSiteConfig(), apps: [] }); + }); + + const v1Id = 'org.openedx.frontend.slot.example.treeList.v1'; + const v2Id = 'org.openedx.frontend.slot.example.treeList.v2'; + const quince: TreeV2 = { id: 'quince', name: 'Quince', foliage: 'deciduous' }; + + it("renders the app's default list by name, before the change", () => { + renderSlot(); + expect(screen.getByText('Redwood')).toBeInTheDocument(); + expect(screen.getByText('Sumac')).toBeInTheDocument(); + expect(screen.getByText('Teak')).toBeInTheDocument(); + }); + + it("renders the app's default list with its foliage, after step 2", () => { + renderSlot(); + expect(screen.getByText('🌲 Redwood')).toBeInTheDocument(); + expect(screen.getByText('🌳 Sumac')).toBeInTheDocument(); + expect(screen.getByText('🌳 Teak')).toBeInTheDocument(); + }); + + it('gives a widget in v1 the options of v1 through useWidgetOptions() and of v2 through useWidgetOptionsForId(), on v2 wrapping v1', () => { + const PrintsOptions = () => ( +

    {JSON.stringify(useWidgetOptions())} {JSON.stringify(useWidgetOptionsForId(v2Id, 'printsOptions'))}

    + ); + configureSlots([ + appendWidget(v1Id, 'printsOptions', PrintsOptions), + setOptions(v1Id, { from: 'v1' }, 'printsOptions'), + setOptions(v2Id, { from: 'v2' }, 'printsOptions'), + ]); + renderSlot(treeListBoth); + expect(screen.getByText('{"from":"v1"} {"from":"v2"}')).toBeInTheDocument(); + }); + + it('gives a v1 widget trees without foliage, on v2 wrapping v1', () => { + const PrintsFirstTree = ({ trees: t }: TreeListSlotProps) =>

    {JSON.stringify(t[0])}

    ; + configureSlots([appendWidget(v1Id, 'printsFirstTree', PrintsFirstTree)]); + renderSlot(treeListBoth); + expect(screen.getByText('{"id":"teak","name":"Teak"}')).toBeInTheDocument(); + }); + + it("lists a tree the operator's v1 option added, on v1 only", () => { + configureSlots([addQuinceV1]); + renderSlot(treeListV1Only); + expect(screen.getByText('Quince')).toBeInTheDocument(); + }); + + it("marks a tree the operator's v1 option added as unknown foliage, on v2 wrapping v1", () => { + configureSlots([addQuinceV1]); + renderSlot(treeListBoth); + expect(screen.getByText('🪾 Quince')).toBeInTheDocument(); + }); + + it("ignores the operator's v1 option on v2 only", () => { + configureSlots([addQuinceV1]); + renderSlot(treeListV2Only); + expect(screen.getByText('🌲 Redwood')).toBeInTheDocument(); + expect(screen.queryByText(/Quince$/)).not.toBeInTheDocument(); + }); + + it.each([ + ['v2 wrapping v1', treeListBoth], + ['v2 only', treeListV2Only], + ])('lists a tree a v2 option added with its foliage, on %s', (_state, element) => { + configureSlots([setOptions(v2Id, { trees: (current: TreeV2[]) => [...current, quince] })]); + renderSlot(element); + expect(screen.getByText('🌳 Quince')).toBeInTheDocument(); + }); + + it('keeps the foliage of a tree a v1 option renamed, on v2 wrapping v1', () => { + const rename = (current: TreeV1[]) => current.map(tree => (tree.id === 'sumac' ? { ...tree, name: 'Staghorn Sumac' } : tree)); + configureSlots([setOptions(v1Id, { trees: rename })]); + renderSlot(treeListBoth); + expect(screen.getByText('🌳 Staghorn Sumac')).toBeInTheDocument(); + }); + + it('never shows a v2 option a tree a v1 option added, on v2 wrapping v1', () => { + let seen: Foliage[] = []; + const record = (current: TreeV2[]) => { + seen = current.map(tree => tree.foliage); + return current; + }; + configureSlots([addQuinceV1, setOptions(v2Id, { trees: record })]); + renderSlot(treeListBoth); + expect(seen).toEqual(['deciduous', 'deciduous', 'evergreen']); + }); +}); + +// Renaming a slot: songControls becomes trackControls, with the old id kept as an alias. +describe('renaming a slot', () => { + afterEach(() => { + setSiteConfig({ ...getSiteConfig(), apps: [] }); + }); + + const oldId = 'org.openedx.frontend.slot.example.songControls.v1'; + const newId = 'org.openedx.frontend.slot.example.trackControls.v1'; + const OldIdWidget = ({ onPlay }: SongControlsSlotProps) => ; + const NewIdWidget = ({ onPlay }: TrackControlsSlotProps) => ; + const onPlay = jest.fn(); + const onPause = jest.fn(); + + beforeEach(() => { + onPlay.mockClear(); + }); + + it('passes the props to a widget under the old id, before the rename', async () => { + configureSlots([appendWidget(oldId, 'oldIdWidget', OldIdWidget)]); + renderSlot(); + await userEvent.click(screen.getByText('old id widget')); + expect(onPlay).toHaveBeenCalledTimes(1); + }); + + it('ignores a widget under the old id, renamed without the alias', () => { + configureSlots([appendWidget(oldId, 'oldIdWidget', OldIdWidget)]); + renderSlot(); + expect(screen.getByText('Play')).toBeInTheDocument(); + expect(screen.queryByText('old id widget')).not.toBeInTheDocument(); + }); + + describe('with the alias', () => { + it.each([ + ['old id', oldId, OldIdWidget, 'old id widget'], + ['new id', newId, NewIdWidget, 'new id widget'], + ])('passes the props to a widget under the %s', async (_name, slotId, Widget, text) => { + configureSlots([appendWidget(slotId, 'widget', Widget)]); + renderSlot(); + await userEvent.click(screen.getByText(text)); + expect(onPlay).toHaveBeenCalledTimes(1); + }); + + it('renders widgets under the old id and the new id together', () => { + configureSlots([ + appendWidget(oldId, 'oldIdWidget', OldIdWidget), + appendWidget(newId, 'newIdWidget', NewIdWidget), + ]); + renderSlot(); + expect(screen.getByText('Play')).toBeInTheDocument(); + expect(screen.getByText('old id widget')).toBeInTheDocument(); + expect(screen.getByText('new id widget')).toBeInTheDocument(); + }); + + it.each([ + ['old id', oldId], + ['new id', newId], + ])('lets an operation under the %s replace the default content', (_name, slotId) => { + configureSlots([replaceDefaultContent(slotId,

    replacement

    )]); + renderSlot(); + expect(screen.getByText('replacement')).toBeInTheDocument(); + expect(screen.queryByText('Play')).not.toBeInTheDocument(); + }); + }); + + describe('after the alias is removed', () => { + it('ignores a widget under the old id', () => { + configureSlots([appendWidget(oldId, 'oldIdWidget', OldIdWidget)]); + renderSlot(); + expect(screen.getByText('Play')).toBeInTheDocument(); + expect(screen.queryByText('old id widget')).not.toBeInTheDocument(); + }); + + it('passes the props to a widget under the new id', async () => { + configureSlots([appendWidget(newId, 'newIdWidget', NewIdWidget)]); + renderSlot(); + await userEvent.click(screen.getByText('new id widget')); + expect(onPlay).toHaveBeenCalledTimes(1); + }); + }); +}); + +// Renaming a slot when its props change: songList becomes trackList, and songs becomes tracks. +const tracks: Track[] = [ + { id: 'overture', title: 'Overture', kind: 'song' }, + { id: 'episode-1', title: 'Episode 1', kind: 'episode' }, + { id: 'finale', title: 'Finale', kind: 'song' }, +]; +const songs = tracks.filter(track => track.kind === 'song'); +const SongListWidget = ({ songs: s }: SongListSlotProps) =>

    songList widget: {s.map(song => song.title).join(', ')}

    ; +const TrackListWidget = ({ tracks: t }: TrackListSlotProps) =>

    trackList widget: {t.map(track => track.title).join(', ')}

    ; +const SongListLayout = () => { + const { songs: s } = useSlotProps(); + return song.title).join(', ')}`} />; +}; +const TrackListLayout = () => { + const { tracks: t } = useSlotProps(); + return track.title).join(', ')}`} />; +}; + +const trackListWrapping = ; + +describeExample('renaming a slot when its props change', { + v1Id: 'org.openedx.frontend.slot.example.songList.v1', + v2Id: 'org.openedx.frontend.slot.example.trackList.v1', + names: ['songList', 'trackList'], + v1Only: , + both: trackListWrapping, + v2Only: , + defaultContentText: 'Finale', + v1Widget: SongListWidget, + v1WidgetText: 'songList widget: Overture, Finale', + v2Widget: TrackListWidget, + v2WidgetText: 'trackList widget: Overture, Episode 1, Finale', + v1Layout: SongListLayout, + v1LayoutText: 'songList layout: Overture, Finale', + v2Layout: TrackListLayout, + v2LayoutText: 'trackList layout: Overture, Episode 1, Finale', +}); + +describe('renaming a slot when its props change', () => { + afterEach(() => { + setSiteConfig({ ...getSiteConfig(), apps: [] }); + }); + + it('gives a songList widget only the songs, on trackList wrapping songList', () => { + const PrintsProps = (props: SongListSlotProps) =>

    songList widget: {JSON.stringify(props)}

    ; + configureSlots([appendWidget('org.openedx.frontend.slot.example.songList.v1', 'printsProps', PrintsProps)]); + renderSlot(trackListWrapping); + expect(screen.getByText('songList widget: {"songs":[{"id":"overture","title":"Overture","kind":"song"},{"id":"finale","title":"Finale","kind":"song"}]}')).toBeInTheDocument(); + }); +}); diff --git a/runtime/slots/testMocks/BannerSlotV1.tsx b/runtime/slots/testMocks/BannerSlotV1.tsx new file mode 100644 index 00000000..ac32e29a --- /dev/null +++ b/runtime/slots/testMocks/BannerSlotV1.tsx @@ -0,0 +1,17 @@ +// The "changing a prop's type" example from docs/how_tos/add-a-slot-version.md, before the change. +import Slot from '../Slot'; + +// Stands in for the app's banner component, which the how-to does not show. +const Banner = ({ message }: { message: string }) =>
    {message}
    ; + +export interface BannerSlotProps { + message: string; +} + +const BannerSlot = ({ message }: BannerSlotProps) => ( + + + +); + +export default BannerSlot; diff --git a/runtime/slots/testMocks/BannerSlotV1V2.tsx b/runtime/slots/testMocks/BannerSlotV1V2.tsx new file mode 100644 index 00000000..eb25a599 --- /dev/null +++ b/runtime/slots/testMocks/BannerSlotV1V2.tsx @@ -0,0 +1,34 @@ +// The "changing a prop's type" example from docs/how_tos/add-a-slot-version.md, after step 3: v2 wrapping v1. +import Slot from '../Slot'; + +/** @deprecated Replaced by `BannerSlotV2Props`, the props of `org.openedx.frontend.slot.example.banner.v2`. */ +export interface BannerSlotV1Props { + /** @deprecated Replaced by `notice` in `BannerSlotV2Props`; this is `notice.message`. */ + message: string; +} + +/** @deprecated Renamed to `BannerSlotV1Props`. */ +export type BannerSlotProps = BannerSlotV1Props; + +export interface Notice { + message: string; + severity: 'info' | 'warning' | 'error'; + onDismiss: () => void; +} + +export interface BannerSlotV2Props { + notice: Notice; +} + +// Stands in for the app's banner component, which the how-to does not show. +const Banner = ({ notice }: { notice: Notice }) =>
    {notice.message}
    ; + +const BannerSlot = ({ notice }: BannerSlotV2Props) => ( + + + + + +); + +export default BannerSlot; diff --git a/runtime/slots/testMocks/BannerSlotV2.tsx b/runtime/slots/testMocks/BannerSlotV2.tsx new file mode 100644 index 00000000..e245e82e --- /dev/null +++ b/runtime/slots/testMocks/BannerSlotV2.tsx @@ -0,0 +1,23 @@ +// The "changing a prop's type" example from docs/how_tos/add-a-slot-version.md, after step 6: v1 removed. +import Slot from '../Slot'; + +export interface Notice { + message: string; + severity: 'info' | 'warning' | 'error'; + onDismiss: () => void; +} + +export interface BannerSlotV2Props { + notice: Notice; +} + +// Stands in for the app's banner component, which the how-to does not show. +const Banner = ({ notice }: { notice: Notice }) =>
    {notice.message}
    ; + +const BannerSlot = ({ notice }: BannerSlotV2Props) => ( + + + +); + +export default BannerSlot; diff --git a/runtime/slots/testMocks/GreetingSlotBumpedInPlace.tsx b/runtime/slots/testMocks/GreetingSlotBumpedInPlace.tsx new file mode 100644 index 00000000..526573bb --- /dev/null +++ b/runtime/slots/testMocks/GreetingSlotBumpedInPlace.tsx @@ -0,0 +1,14 @@ +// The "renaming a prop" example from docs/how_tos/add-a-slot-version.md, the second thing it says not to do: the version bumped in place. +import Slot from '../Slot'; + +export interface GreetingSlotProps { + displayName: string; +} + +const GreetingSlot = ({ displayName }: GreetingSlotProps) => ( + +

    Hello, {displayName}

    +
    +); + +export default GreetingSlot; diff --git a/runtime/slots/testMocks/GreetingSlotRenamedInPlace.tsx b/runtime/slots/testMocks/GreetingSlotRenamedInPlace.tsx new file mode 100644 index 00000000..6c3dd2d1 --- /dev/null +++ b/runtime/slots/testMocks/GreetingSlotRenamedInPlace.tsx @@ -0,0 +1,14 @@ +// The "renaming a prop" example from docs/how_tos/add-a-slot-version.md, the first thing it says not to do: the prop renamed in place. +import Slot from '../Slot'; + +export interface GreetingSlotProps { + displayName: string; +} + +const GreetingSlot = ({ displayName }: GreetingSlotProps) => ( + +

    Hello, {displayName}

    +
    +); + +export default GreetingSlot; diff --git a/runtime/slots/testMocks/GreetingSlotV1.tsx b/runtime/slots/testMocks/GreetingSlotV1.tsx new file mode 100644 index 00000000..00e99699 --- /dev/null +++ b/runtime/slots/testMocks/GreetingSlotV1.tsx @@ -0,0 +1,14 @@ +// The "renaming a prop" example from docs/how_tos/add-a-slot-version.md, before the change. +import Slot from '../Slot'; + +export interface GreetingSlotProps { + userName: string; +} + +const GreetingSlot = ({ userName }: GreetingSlotProps) => ( + +

    Hello, {userName}

    +
    +); + +export default GreetingSlot; diff --git a/runtime/slots/testMocks/GreetingSlotV1V2.tsx b/runtime/slots/testMocks/GreetingSlotV1V2.tsx new file mode 100644 index 00000000..3e63be46 --- /dev/null +++ b/runtime/slots/testMocks/GreetingSlotV1V2.tsx @@ -0,0 +1,25 @@ +// The "renaming a prop" example from docs/how_tos/add-a-slot-version.md, after step 3: v2 wrapping v1. +import Slot from '../Slot'; + +/** @deprecated Replaced by `GreetingSlotV2Props`, the props of `org.openedx.frontend.slot.example.greeting.v2`. */ +export interface GreetingSlotV1Props { + /** @deprecated Renamed to `displayName` in `GreetingSlotV2Props`. */ + userName: string; +} + +/** @deprecated Renamed to `GreetingSlotV1Props`. */ +export type GreetingSlotProps = GreetingSlotV1Props; + +export interface GreetingSlotV2Props { + displayName: string; +} + +const GreetingSlot = ({ displayName }: GreetingSlotV2Props) => ( + + +

    Hello, {displayName}

    +
    +
    +); + +export default GreetingSlot; diff --git a/runtime/slots/testMocks/GreetingSlotV2.tsx b/runtime/slots/testMocks/GreetingSlotV2.tsx new file mode 100644 index 00000000..e1a989f4 --- /dev/null +++ b/runtime/slots/testMocks/GreetingSlotV2.tsx @@ -0,0 +1,14 @@ +// The "renaming a prop" example from docs/how_tos/add-a-slot-version.md, after step 6: v1 removed. +import Slot from '../Slot'; + +export interface GreetingSlotV2Props { + displayName: string; +} + +const GreetingSlot = ({ displayName }: GreetingSlotV2Props) => ( + +

    Hello, {displayName}

    +
    +); + +export default GreetingSlot; diff --git a/runtime/slots/testMocks/SongControlsSlot.tsx b/runtime/slots/testMocks/SongControlsSlot.tsx new file mode 100644 index 00000000..54dc1519 --- /dev/null +++ b/runtime/slots/testMocks/SongControlsSlot.tsx @@ -0,0 +1,16 @@ +// The "renaming a slot" example from docs/how_tos/add-a-slot-version.md, before the change. +import Slot from '../Slot'; + +export interface SongControlsSlotProps { + onPlay: () => void; + onPause: () => void; +} + +const SongControlsSlot = ({ onPlay, onPause }: SongControlsSlotProps) => ( + + + + +); + +export default SongControlsSlot; diff --git a/runtime/slots/testMocks/SongListSlot.tsx b/runtime/slots/testMocks/SongListSlot.tsx new file mode 100644 index 00000000..19512769 --- /dev/null +++ b/runtime/slots/testMocks/SongListSlot.tsx @@ -0,0 +1,21 @@ +// The "renaming a slot when its props change" example from docs/how_tos/add-a-slot-version.md, before the change. +import Slot from '../Slot'; + +export interface Song { + id: string; + title: string; +} + +export interface SongListSlotProps { + songs: Song[]; +} + +const SongListSlot = ({ songs }: SongListSlotProps) => ( + +
      + {songs.map(song =>
    • {song.title}
    • )} +
    +
    +); + +export default SongListSlot; diff --git a/runtime/slots/testMocks/TaggableItemSlotV1.tsx b/runtime/slots/testMocks/TaggableItemSlotV1.tsx new file mode 100644 index 00000000..4a1a69f6 --- /dev/null +++ b/runtime/slots/testMocks/TaggableItemSlotV1.tsx @@ -0,0 +1,14 @@ +// The "a prop that becomes a list" example from docs/how_tos/add-a-slot-version.md, before the change. +import Slot from '../Slot'; + +export interface TaggableItemSlotProps { + selectedTag: string; +} + +const TaggableItemSlot = ({ selectedTag }: TaggableItemSlotProps) => ( + +

    Tagged {selectedTag}

    +
    +); + +export default TaggableItemSlot; diff --git a/runtime/slots/testMocks/TaggableItemSlotV1V2.tsx b/runtime/slots/testMocks/TaggableItemSlotV1V2.tsx new file mode 100644 index 00000000..f543462c --- /dev/null +++ b/runtime/slots/testMocks/TaggableItemSlotV1V2.tsx @@ -0,0 +1,30 @@ +// The "a prop that becomes a list" example from docs/how_tos/add-a-slot-version.md, after step 3: v2 wrapping v1. +import Slot from '../Slot'; + +/** @deprecated Replaced by `TaggableItemSlotV2Props`, the props of `org.openedx.frontend.slot.example.taggableItem.v2`. */ +export interface TaggableItemSlotV1Props { + /** @deprecated This is the first of `selectedTags`, or an empty string when there are none. Read `selectedTags` instead. */ + selectedTag: string; + selectedTags: string[]; +} + +/** @deprecated Renamed to `TaggableItemSlotV1Props`. */ +export type TaggableItemSlotProps = TaggableItemSlotV1Props; + +export interface TaggableItemSlotV2Props { + selectedTags: string[]; +} + +const TaggableItemSlot = ({ selectedTags }: TaggableItemSlotV2Props) => { + // v1 takes a single tag. This example gives it the first of the list, or an empty string when the list is empty. + const selectedTag = selectedTags[0] ?? ''; + return ( + + +

    Tagged {selectedTags.join(', ')}

    +
    +
    + ); +}; + +export default TaggableItemSlot; diff --git a/runtime/slots/testMocks/TaggableItemSlotV1V2FirstTagOnly.tsx b/runtime/slots/testMocks/TaggableItemSlotV1V2FirstTagOnly.tsx new file mode 100644 index 00000000..bdf01d54 --- /dev/null +++ b/runtime/slots/testMocks/TaggableItemSlotV1V2FirstTagOnly.tsx @@ -0,0 +1,22 @@ +// The "a prop that becomes a list" example from docs/how_tos/add-a-slot-version.md, after step 1's first two blocks: v2 wrapping v1, before selectedTags is added to v1. +import Slot from '../Slot'; + +export interface TaggableItemSlotV1Props { + selectedTag: string; +} + +export type TaggableItemSlotProps = TaggableItemSlotV1Props; + +export interface TaggableItemSlotV2Props { + selectedTags: string[]; +} + +const TaggableItemSlot = ({ selectedTags }: TaggableItemSlotV2Props) => ( + + +

    Tagged {selectedTags.join(', ')}

    +
    +
    +); + +export default TaggableItemSlot; diff --git a/runtime/slots/testMocks/TaggableItemSlotV2.tsx b/runtime/slots/testMocks/TaggableItemSlotV2.tsx new file mode 100644 index 00000000..292627bd --- /dev/null +++ b/runtime/slots/testMocks/TaggableItemSlotV2.tsx @@ -0,0 +1,14 @@ +// The "a prop that becomes a list" example from docs/how_tos/add-a-slot-version.md, after step 6: v1 removed. +import Slot from '../Slot'; + +export interface TaggableItemSlotV2Props { + selectedTags: string[]; +} + +const TaggableItemSlot = ({ selectedTags }: TaggableItemSlotV2Props) => ( + +

    Tagged {selectedTags.join(', ')}

    +
    +); + +export default TaggableItemSlot; diff --git a/runtime/slots/testMocks/TrackControlsSlot.tsx b/runtime/slots/testMocks/TrackControlsSlot.tsx new file mode 100644 index 00000000..bf86f601 --- /dev/null +++ b/runtime/slots/testMocks/TrackControlsSlot.tsx @@ -0,0 +1,20 @@ +// The "renaming a slot" example from docs/how_tos/add-a-slot-version.md, after step 5: the alias removed. +import Slot from '../Slot'; + +export interface TrackControlsSlotProps { + onPlay: () => void; + onPause: () => void; +} + +const TrackControlsSlot = ({ onPlay, onPause }: TrackControlsSlotProps) => ( + + + + +); + +export default TrackControlsSlot; diff --git a/runtime/slots/testMocks/TrackControlsSlotAliased.tsx b/runtime/slots/testMocks/TrackControlsSlotAliased.tsx new file mode 100644 index 00000000..ed8e8679 --- /dev/null +++ b/runtime/slots/testMocks/TrackControlsSlotAliased.tsx @@ -0,0 +1,24 @@ +// The "renaming a slot" example from docs/how_tos/add-a-slot-version.md, after step 2: the old id kept as an alias. +import Slot from '../Slot'; + +export interface TrackControlsSlotProps { + onPlay: () => void; + onPause: () => void; +} + +/** @deprecated Renamed to `TrackControlsSlotProps`. */ +export type SongControlsSlotProps = TrackControlsSlotProps; + +const TrackControlsSlot = ({ onPlay, onPause }: TrackControlsSlotProps) => ( + + + + +); + +export default TrackControlsSlot; diff --git a/runtime/slots/testMocks/TrackControlsSlotNoAlias.tsx b/runtime/slots/testMocks/TrackControlsSlotNoAlias.tsx new file mode 100644 index 00000000..c11954af --- /dev/null +++ b/runtime/slots/testMocks/TrackControlsSlotNoAlias.tsx @@ -0,0 +1,16 @@ +// The "renaming a slot" example from docs/how_tos/add-a-slot-version.md, what it says not to do: the id renamed in place. +import Slot from '../Slot'; + +export interface TrackControlsSlotProps { + onPlay: () => void; + onPause: () => void; +} + +const TrackControlsSlot = ({ onPlay, onPause }: TrackControlsSlotProps) => ( + + + + +); + +export default TrackControlsSlot; diff --git a/runtime/slots/testMocks/TrackListSlot.tsx b/runtime/slots/testMocks/TrackListSlot.tsx new file mode 100644 index 00000000..3b1755a7 --- /dev/null +++ b/runtime/slots/testMocks/TrackListSlot.tsx @@ -0,0 +1,24 @@ +// The "renaming a slot when its props change" example from docs/how_tos/add-a-slot-version.md, after step 6: the old slot removed. +import Slot from '../Slot'; + +export type TrackKind = 'song' | 'episode'; + +export interface Track { + id: string; + title: string; + kind: TrackKind; +} + +export interface TrackListSlotProps { + tracks: Track[]; +} + +const TrackListSlot = ({ tracks }: TrackListSlotProps) => ( + +
      + {tracks.map(track =>
    • {track.title}
    • )} +
    +
    +); + +export default TrackListSlot; diff --git a/runtime/slots/testMocks/TrackListSlotWrappingSongList.tsx b/runtime/slots/testMocks/TrackListSlotWrappingSongList.tsx new file mode 100644 index 00000000..28d0f13a --- /dev/null +++ b/runtime/slots/testMocks/TrackListSlotWrappingSongList.tsx @@ -0,0 +1,41 @@ +// The "renaming a slot when its props change" example from docs/how_tos/add-a-slot-version.md, after step 3: the new slot wrapping the old one. +import Slot from '../Slot'; + +export interface Song { + id: string; + title: string; +} + +export type TrackKind = 'song' | 'episode'; + +export interface Track { + id: string; + title: string; + kind: TrackKind; +} + +/** @deprecated Replaced by `TrackListSlotProps`, the props of `org.openedx.frontend.slot.example.trackList.v1`. */ +export interface SongListSlotProps { + /** @deprecated These are the songs in `tracks` of `TrackListSlotProps`. */ + songs: Song[]; +} + +export interface TrackListSlotProps { + tracks: Track[]; +} + +const TrackListSlot = ({ tracks }: TrackListSlotProps) => { + // The old slot takes songs only, so it gets the songs out of the list. + const songs: Song[] = tracks.filter(track => track.kind === 'song'); + return ( + + +
      + {tracks.map(track =>
    • {track.title}
    • )} +
    +
    +
    + ); +}; + +export default TrackListSlot; diff --git a/runtime/slots/testMocks/TreeListPageV1.tsx b/runtime/slots/testMocks/TreeListPageV1.tsx new file mode 100644 index 00000000..3667ac3b --- /dev/null +++ b/runtime/slots/testMocks/TreeListPageV1.tsx @@ -0,0 +1,14 @@ +// The "a slot whose default widget takes options" example from docs/how_tos/add-a-slot-version.md: where the app renders the slot, before the change. +import TreeListSlot from './TreeListSlotV1'; + +const TreeListPage = () => ( + +); + +export default TreeListPage; diff --git a/runtime/slots/testMocks/TreeListPageV2.tsx b/runtime/slots/testMocks/TreeListPageV2.tsx new file mode 100644 index 00000000..7f263d47 --- /dev/null +++ b/runtime/slots/testMocks/TreeListPageV2.tsx @@ -0,0 +1,14 @@ +// The "a slot whose default widget takes options" example from docs/how_tos/add-a-slot-version.md: where the app renders the slot, after step 2. +import TreeListSlot from './TreeListSlotV1V2'; + +const TreeListPage = () => ( + +); + +export default TreeListPage; diff --git a/runtime/slots/testMocks/TreeListSlotV1.tsx b/runtime/slots/testMocks/TreeListSlotV1.tsx new file mode 100644 index 00000000..05a71643 --- /dev/null +++ b/runtime/slots/testMocks/TreeListSlotV1.tsx @@ -0,0 +1,36 @@ +// The "a slot whose default widget takes options" example from docs/how_tos/add-a-slot-version.md, before the change. +import Slot from '../Slot'; +import { useWidgetOptions } from '../widget/hooks'; + +export interface Tree { + id: string; + name: string; +} + +export interface TreeListSlotProps { + trees: Tree[]; +} + +interface TreeListOptions { + trees?: Tree[] | ((current: Tree[]) => Tree[]); +} + +const DefaultTreeListWidget = ({ trees }: { trees: Tree[] }) => { + const options = useWidgetOptions() as TreeListOptions; + const shown = typeof options.trees === 'function' + ? options.trees(trees) + : options.trees ?? trees; + return ( +
      + {shown.map(tree =>
    • {tree.name}
    • )} +
    + ); +}; + +const TreeListSlot = ({ trees }: TreeListSlotProps) => ( + + + +); + +export default TreeListSlot; diff --git a/runtime/slots/testMocks/TreeListSlotV1V2.tsx b/runtime/slots/testMocks/TreeListSlotV1V2.tsx new file mode 100644 index 00000000..735b5a09 --- /dev/null +++ b/runtime/slots/testMocks/TreeListSlotV1V2.tsx @@ -0,0 +1,82 @@ +// The "a slot whose default widget takes options" example from docs/how_tos/add-a-slot-version.md, after step 3: v2 wrapping v1. +import Slot from '../Slot'; +import { useWidgetOptions, useWidgetOptionsForId } from '../widget/hooks'; + +/** @deprecated Replaced by `TreeV2`, which adds `foliage`. */ +export interface TreeV1 { + id: string; + name: string; +} + +/** @deprecated Renamed to `TreeV1`. */ +export type Tree = TreeV1; + +/** @deprecated Replaced by `TreeListSlotV2Props`, the props of `org.openedx.frontend.slot.example.treeList.v2`. */ +export interface TreeListSlotV1Props { + /** @deprecated `trees` in `TreeListSlotV2Props` is `TreeV2[]`. A `v1` option cannot set a tree's foliage. */ + trees: TreeV1[]; +} + +/** @deprecated Renamed to `TreeListSlotV1Props`. */ +export type TreeListSlotProps = TreeListSlotV1Props; + +export type Foliage = 'evergreen' | 'deciduous'; + +export interface TreeV2 { + id: string; + name: string; + foliage: Foliage; +} + +export interface TreeListSlotV2Props { + trees: TreeV2[]; +} + +type TreeListV1Option = TreeV1[] | ((current: TreeV1[]) => TreeV1[]); + +interface TreeListV1Options { + trees?: TreeListV1Option; +} + +interface TreeListV2Options { + trees?: TreeV2[] | ((current: TreeV2[]) => TreeV2[]); +} + +const toTreeV1 = ({ foliage, ...tree }: TreeV2): TreeV1 => tree; + +type ShownTree = TreeV1 & { foliage?: Foliage }; + +// A v1 option sees and returns v1 trees. A tree it kept gets its foliage back by id; a tree it added has none. +function applyV1Option(option: TreeListV1Option | undefined, trees: TreeV2[]): ShownTree[] { + const v1Trees = trees.map(toTreeV1); + const result = typeof option === 'function' ? option(v1Trees) : option ?? v1Trees; + const foliageOf = (id: string) => trees.find(tree => tree.id === id)?.foliage; + return result.map(tree => ({ ...tree, foliage: foliageOf(tree.id) })); +} + +const FOLIAGE_ICON: Record = { evergreen: '🌲', deciduous: '🌳' }; + +const DefaultTreeListWidget = ({ trees }: { trees: TreeV2[] }) => { + // While v1 is wrapped, this widget is v1's defaultContent, so useWidgetOptions() reads v1's options. + const v1Options = useWidgetOptions() as TreeListV1Options; + const v2Options = useWidgetOptionsForId('org.openedx.frontend.slot.example.treeList.v2', 'defaultContent') as TreeListV2Options; + const v2Trees = typeof v2Options.trees === 'function' + ? v2Options.trees(trees) + : v2Options.trees ?? trees; + const shown = applyV1Option(v1Options.trees, v2Trees); + return ( +
      + {shown.map(tree =>
    • {tree.foliage ? FOLIAGE_ICON[tree.foliage] : '🪾'} {tree.name}
    • )} +
    + ); +}; + +const TreeListSlot = ({ trees }: TreeListSlotV2Props) => ( + + + + + +); + +export default TreeListSlot; diff --git a/runtime/slots/testMocks/TreeListSlotV2.tsx b/runtime/slots/testMocks/TreeListSlotV2.tsx new file mode 100644 index 00000000..90ead9de --- /dev/null +++ b/runtime/slots/testMocks/TreeListSlotV2.tsx @@ -0,0 +1,41 @@ +// The "a slot whose default widget takes options" example from docs/how_tos/add-a-slot-version.md, after step 6: v1 removed. +import Slot from '../Slot'; +import { useWidgetOptions } from '../widget/hooks'; + +export type Foliage = 'evergreen' | 'deciduous'; + +export interface TreeV2 { + id: string; + name: string; + foliage: Foliage; +} + +export interface TreeListSlotV2Props { + trees: TreeV2[]; +} + +interface TreeListV2Options { + trees?: TreeV2[] | ((current: TreeV2[]) => TreeV2[]); +} + +const FOLIAGE_ICON: Record = { evergreen: '🌲', deciduous: '🌳' }; + +const DefaultTreeListWidget = ({ trees }: { trees: TreeV2[] }) => { + const options = useWidgetOptions() as TreeListV2Options; + const shown = typeof options.trees === 'function' + ? options.trees(trees) + : options.trees ?? trees; + return ( +
      + {shown.map(tree =>
    • {FOLIAGE_ICON[tree.foliage]} {tree.name}
    • )} +
    + ); +}; + +const TreeListSlot = ({ trees }: TreeListSlotV2Props) => ( + + + +); + +export default TreeListSlot; diff --git a/runtime/slots/testMocks/greetingWidgets.tsx b/runtime/slots/testMocks/greetingWidgets.tsx new file mode 100644 index 00000000..e6712159 --- /dev/null +++ b/runtime/slots/testMocks/greetingWidgets.tsx @@ -0,0 +1,19 @@ +// The "renaming a prop" example from docs/how_tos/add-a-slot-version.md: the operator's widget before and after moving it to v2. +import { WidgetOperation, WidgetOperationTypes } from '../widget/types'; +import { GreetingSlotProps, GreetingSlotV2Props } from './GreetingSlotV1V2'; + +export const customGreetingV1: WidgetOperation = { + slotId: 'org.openedx.frontend.slot.example.greeting.v1', + id: 'customGreeting', + op: WidgetOperationTypes.REPLACE, + relatedId: 'defaultContent', + component: ({ userName }: GreetingSlotProps) =>

    Welcome back, {userName}

    , +}; + +export const customGreetingV2: WidgetOperation = { + slotId: 'org.openedx.frontend.slot.example.greeting.v2', + id: 'customGreeting', + op: WidgetOperationTypes.REPLACE, + relatedId: 'defaultContent', + component: ({ displayName }: GreetingSlotV2Props) =>

    Welcome back, {displayName}

    , +}; diff --git a/runtime/slots/testMocks/treeListOptions.ts b/runtime/slots/testMocks/treeListOptions.ts new file mode 100644 index 00000000..e0a544d0 --- /dev/null +++ b/runtime/slots/testMocks/treeListOptions.ts @@ -0,0 +1,12 @@ +// The "a slot whose default widget takes options" example from docs/how_tos/add-a-slot-version.md: the operator's options operation. +import { WidgetOperation, WidgetOperationTypes } from '../widget/types'; +import { Tree } from './TreeListSlotV1V2'; + +export const addQuinceV1: WidgetOperation = { + slotId: 'org.openedx.frontend.slot.example.treeList.v1', + op: WidgetOperationTypes.OPTIONS, + relatedId: 'defaultContent', + options: { + trees: (current: Tree[]) => [...current, { id: 'quince', name: 'Quince' }], + }, +};