/*! * Copyright (c) Microsoft Corporation and contributors. All rights reserved. * Licensed under the MIT License. */ import { PureDataObjectFactory, TreeDataObject, createDataObjectKind, } from "@fluidframework/aqueduct/internal"; import type { IFluidLoadable } from "@fluidframework/core-interfaces"; import type { IFluidDataStoreFactory } from "@fluidframework/runtime-definitions/internal"; import type { SharedObjectKind } from "@fluidframework/shared-object-base"; import type { SchemaCompatibilityStatus, TreeViewConfiguration, TreeFieldFromImplicitField, TreeView, ImplicitFieldSchema, InsertableTreeFieldFromImplicitField, } from "@fluidframework/tree"; import { configuredSharedTree, FormatValidatorBasic } from "@fluidframework/tree/internal"; import { type FC, type JSX, useCallback, useEffect, useState } from "react"; import { toPropTreeNode, type PropTreeValue } from "./propNode.js"; /** * Opt into extra validation to detect encoding bugs and data corruption. * As long as this is an experimental package, opting into extra validation (at a small perf and bundle size cost) seems reasonable. */ const SharedTree = configuredSharedTree({ jsonValidator: FormatValidatorBasic, }); /** * Defines a DataObject for a {@link @fluidframework/tree#SharedTree} with a built in {@link @fluidframework/tree#TreeViewConfiguration}. * @param treeConfiguration - See {@link IReactTreeDataObject.config}. * @param createInitialTree - Function which populates the tree with initial data on document create. * @returns A {@link @fluidframework/fluid-static#DataObjectClass} to allow easy use of a SharedTree in a ContainerSchema. * @alpha */ export function treeDataObject( treeConfiguration: TreeViewConfiguration, createInitialTree: () => InsertableTreeFieldFromImplicitField, ): SharedObjectKind & IFluidLoadable> { return treeDataObjectInternal(treeConfiguration, createInitialTree); } /** * Defines a DataObject for a {@link @fluidframework/tree#SharedTree} with a built in {@link @fluidframework/tree#TreeViewConfiguration}. * @param treeConfiguration - See {@link IReactTreeDataObject.config}. * @param createInitialTree - Function which populates the tree with initial data on document create. * @returns A {@link @fluidframework/fluid-static#DataObjectClass} to allow easy use of a SharedTree in a ContainerSchema. * @internal */ export function treeDataObjectInternal( treeConfiguration: TreeViewConfiguration, createInitialTree: () => InsertableTreeFieldFromImplicitField, ): SharedObjectKind & IFluidLoadable & TreeDataObject> & { readonly factory: IFluidDataStoreFactory; } { class SchemaAwareTreeDataObject extends ReactTreeDataObject { public override readonly config = treeConfiguration; public static readonly factory = new PureDataObjectFactory>( `TreeDataObject`, SchemaAwareTreeDataObject, [SharedTree.getFactory()], {}, ); #treeView: TreeView | undefined; /** * The schema-aware view of the tree. */ public get treeView(): TreeView { if (this.#treeView === undefined) { throw new Error("treeView has not been initialized."); } return this.#treeView; } /** * Converts the underlying ITree into a typed TreeView using the provided schema configuration. * * @param tree - The ITree instance to view. * @returns A typed TreeView using the TodoList schema. */ private initializeView(): void { this.#treeView = this.tree.viewWith(this.config); } protected override async initializingFirstTime(): Promise { this.initializeView(); this.treeView.initialize(createInitialTree()); } protected override async initializingFromExisting(): Promise { this.initializeView(); } } return createDataObjectKind(SchemaAwareTreeDataObject); } /** * A schema-aware tree-backed DataObject, extended with a React Component to view the tree. * @remarks Allows for the Tree's schema to be baked into the container schema. * @sealed @alpha */ export interface IReactTreeDataObject { /** * The configuration used to initialize new documents, as well as to interpret (schematize) existing ones. * * @remarks * The fact that a single view schema is provided here (on the data object) makes it impossible to try and apply multiple different schema. * Since the view schema currently does not provide any adapters for handling differences between view and stored schema, * it's also impossible for this single view schema to handle multiple different stored schema. * Therefore, with this current API, two different applications (or different versions of the same application) * with differing stored schema requirements (as implied by their view schema) can not collaborate on the same tree. * The only schema evolution that's currently possible is upgrading the schema to one that supports a superset of what the old schema allowed, * and collaborating between clients which have view schema that exactly correspond to that stored schema. * Future work on tree as well as these utilities should address this limitation. */ readonly config: TreeViewConfiguration; /** * The schema-aware view of the tree. */ readonly treeView: TreeView; /** * React component which handles schematizing trees. * This includes displaying errors when the document can not be viewed using the view schema. * * @privateRemarks * This is exposed as a member rather than a free function since type inference for the schema doesn't work when used as a free function, * and thus making it a member avoids the user of this from having to explicitly provide the type parameter. * This is an arrow function not a method so it gets the correct this when not called as a member. */ readonly TreeViewComponent: (props: TreeViewProps) => JSX.Element; } /** * React props for viewing a tree. * @input @alpha */ export interface TreeViewProps { /** * Component to display the tree content. */ readonly viewComponent: FC<{ root: PropTreeValue>; }>; /** * Component to display instead of the {@link TreeViewProps.viewComponent} * when tree content is not compatible with the {@link @fluidframework/tree#TreeViewConfiguration}. * * @defaultValue Component which describes the situation (in English) and allows the user to upgrade the schema to match the {@link @fluidframework/tree#TreeViewConfiguration} if possible. */ readonly errorComponent?: FC; // TODO: Once its possible to query the status of individual schema upgrades, provide more options here for handling such cases. } /** * Generic DataObject for shared trees. * @internal */ export abstract class ReactTreeDataObject< TSchema extends ImplicitFieldSchema = ImplicitFieldSchema, > extends TreeDataObject implements IReactTreeDataObject { public abstract readonly config: TreeViewConfiguration; readonly #treeView: TreeView | undefined; /** * The schema-aware view of the tree. */ public get treeView(): TreeView { if (this.#treeView === undefined) { throw new Error("treeView has not been initialized."); } return this.#treeView; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type public readonly TreeViewComponent = ({ viewComponent, errorComponent, }: TreeViewProps) => TreeViewComponent({ tree: this, viewComponent, errorComponent, }); } function useViewCompatibility( view: TreeView, ): SchemaCompatibilityStatus { const [compatibility, setCompatibility] = useState( view.compatibility, ); useEffect(() => { const updateCompatibility = (): void => { setCompatibility(view.compatibility); }; updateCompatibility(); return view.events.on("schemaChanged", updateCompatibility); }, [view]); return compatibility; } function useViewRoot( view: TreeView, ): TreeFieldFromImplicitField | undefined { const [root, setRoot] = useState | undefined>(undefined); useEffect(() => { const updateRoot = (): void => { if (view.compatibility.canView) { setRoot(view.root); } else { setRoot(undefined); } }; updateRoot(); return view.events.on("rootChanged", updateRoot); }, [view]); return root; } /** * React component which handles schematizing trees. * This includes displaying errors when the document can not be schematized. * @alpha */ export function TreeViewComponent({ tree, viewComponent: ViewComponent, errorComponent, }: TreeViewProps & { tree: Pick, "treeView">; }): JSX.Element { const view = tree.treeView; const compatibility = useViewCompatibility(view); const root = useViewRoot(view); const upgradeSchema = useCallback((): void => view.upgradeSchema(), [view]); if (!compatibility.canView) { const Error = errorComponent ?? TreeErrorComponent; return ; } if (root === undefined) { return
View not set
; } return ; } /** * React Props for displaying when the opened document is incompatible with the required view schema. * @alpha */ export interface SchemaIncompatibleProps { /** * Information about the view schema's compatibility with the stored schema. */ readonly compatibility: SchemaCompatibilityStatus; /** * Callback to request that the stored schema in the document be upgraded. */ readonly upgradeSchema: () => void; } /** * React component which displays schema errors and allows upgrading schema when possible. */ function TreeErrorComponent({ compatibility, upgradeSchema, }: { compatibility: SchemaCompatibilityStatus; upgradeSchema: () => void; }): JSX.Element { // eslint-disable-next-line unicorn/prefer-ternary if (compatibility.canUpgrade) { return (
Document is incompatible with current version of the application, but the document format can be updated. This may prevent other versions of the application from opening this document.
;
); } else { return (
Document is incompatible with current version of the application, and the document format cannot be updated. The document is likely from a newer or otherwise incompatible version of the application, or a different application.
); } }