"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextAsTree = exports.charactersFromString = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const alpha_1 = require("@fluidframework/type-factory/alpha");
const internal_2 = require("@fluidframework/type-factory/internal");
const index_js_1 = require("../core/index.js");
const index_js_2 = require("../simple-tree/index.js");
const sf = new index_js_2.SchemaFactoryAlpha("com.fluidframework.text");
class TextNode extends sf.object("Text", {
    content: index_js_2.SchemaFactory.required([() => StringArray], { key: index_js_1.EmptyKey }),
}) {
    static [alpha_1.exposeMethodsSymbol](methods) {
        methods.exposeMethod(TextNode, "insertAt", (0, alpha_1.buildFunc)({
            description: "Insert characters into the text at the given character index (Unicode code points).",
            returns: internal_2.typeFactory.void(),
        }, ["index", internal_2.typeFactory.number()], ["additionalCharacters", internal_2.typeFactory.string()]));
        methods.exposeMethod(TextNode, "removeRange", (0, alpha_1.buildFunc)({
            description: "Remove a range of characters from the text by character index (Unicode code points). startIndex defaults to 0 and endIndex defaults to the length of the text.",
            returns: internal_2.typeFactory.void(),
        }, ["startIndex", internal_2.typeFactory.union([internal_2.typeFactory.number(), internal_2.typeFactory.undefined()])], ["endIndex", internal_2.typeFactory.union([internal_2.typeFactory.number(), internal_2.typeFactory.undefined()])]));
        methods.exposeMethod(TextNode, "fullString", (0, alpha_1.buildFunc)({
            description: "Return a copy of this text node's content as a string.",
            returns: internal_2.typeFactory.string(),
        }));
        methods.exposeMethod(TextNode, "characterCount", (0, alpha_1.buildFunc)({
            description: "Gets the number of characters (Unicode code points) currently in the text. Joined emojis and other grapheme clusters count as multiple characters.",
            returns: internal_2.typeFactory.number(),
        }));
        methods.exposeMethod(TextNode, "charactersCopy", (0, alpha_1.buildFunc)({
            description: "Returns all characters in the text as an array, where each element is a single Unicode code point. Joined emojis and other grapheme clusters are split into separate elements.",
            returns: internal_2.typeFactory.array(internal_2.typeFactory.string()),
        }));
    }
    [alpha_1.exposeMethodsSymbol](methods) {
        TextNode[alpha_1.exposeMethodsSymbol](methods);
    }
    insertAt(index, additionalCharacters) {
        this.content.insertAt(index, index_js_2.TreeArrayNode.spread(charactersFromString(additionalCharacters)));
    }
    removeRange(index, end) {
        this.content.removeRange(index, end);
    }
    characters() {
        return this.content[Symbol.iterator]();
    }
    characterCount() {
        return this.content.length;
    }
    charactersCopy() {
        const result = this.content.charactersCopy();
        (0, internal_1.debugAssert)(() => (0, internal_1.compareArrays)(result, this.charactersCopy_reference()) ||
            "invalid charactersCopy optimizations");
        return result;
    }
    fullString() {
        const result = this.content.fullString();
        (0, internal_1.debugAssert)(() => result === this.fullString_reference() || "invalid fullString optimizations");
        return result;
    }
    /**
     * Unoptimized trivially correct implementation of fullString.
     */
    fullString_reference() {
        return this.content.join("");
    }
    /**
     * Unoptimized trivially correct implementation of charactersCopy.
     */
    charactersCopy_reference() {
        return [...this.content];
    }
    static fromString(value) {
        // Constructing an ArrayNode from an iterator is supported, so creating an array from the iterable of characters seems like its not necessary here,
        // but to reduce the risk of incorrect data interpretation, we actually ban this in the special case where the iterable is a string directly, which is the case here.
        // Thus the array construction here is necessary to avoid a runtime error.
        return new TextNode({ content: [...charactersFromString(value)] });
    }
}
/**
 * Interpret a string as an iterable of characters.
 * @remarks
 * This mostly exists to clearly document where the code is interpreting a string as characters,
 * and provide a centralized place where validation could be added in the future if desired.
 * Additionally using this function consistently will make any refactors to support alternative character boundaries easier.
 */
function charactersFromString(value) {
    // Uses the string as an iterable of characters, so utf-16 surrogate pairs get grouped together correctly.
    // Might be nice to call isWellFormed or toWellFormed here (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toWellFormed)
    // But those are not widely supported yet.
    return value;
}
exports.charactersFromString = charactersFromString;
class StringArray extends sf.array("StringArray", index_js_2.SchemaFactory.string) {
    withBorrowedSequenceCursor(f) {
        const cursor = (0, index_js_2.getInnerNode)(this).borrowCursor();
        cursor.enterField(index_js_1.EmptyKey);
        const result = f(cursor);
        cursor.exitField();
        return result;
    }
    charactersCopy() {
        return this.withBorrowedSequenceCursor((cursor) => (0, index_js_1.mapCursorField)(cursor, () => cursor.value));
    }
    fullString() {
        return this.charactersCopy().join("");
    }
}
/**
 * A collection of text related types, schema and utilities for working with text beyond the basic {@link SchemaStatics.string}.
 * @privateRemarks
 * Currently this API only supports a really minimal feature set, and has no support for more advanced features like:
 * - Alternative character boundaries (e.g. grapheme clusters, paragraphs, tokens, etc.).
 * We may want to provide either ways to create strings with application controlled character boundaries since there is not a clear single answer on how to break a string into atomic units.
 * - Character attributes (e.g. bold, italic, etc):
 * Properties that can be set on any character independently with optimizations for runs of characters with the same attributes.
 * - Inline objects (e.g. images, embedded components, etc):
 * These would be logically part of the text, generalizing characters to allow inline objects in character ranges.
 * How character attributes apply to inline objects is an open question
 * (there could be a kind of object which gets them, and one that doesn't for example).
 * - Annotations (e.g. comments, suggestions, etc).
 * Objects which can be associated with a range of characters but are not logically part of the text.
 * These would need to have the logical range they apply to updated by edits.
 * How edits which overlap annotation boundaries are handled may require hints from the application for optimal behavior (mainly inserts at the boundaries).
 * These get a lifetime tied to the text node, not any of the characters the annotation covers,
 * however it might be desirable to have a way for a range edit to (optionally) also remove any annotations which are fully covered by the edit.
 * Annotations over an empty range should also be supported and behave well (for example not end up with characters inside the range after edits unless specifically structured so that makes sense).
 * - Anchors (e.g. positions in the text which survive edits).
 * These would be useful for ephemeral state like cursor positions, but should match the behaviors with respect to edits exhibited by the ends of Annotations.
 *
 * How these features will be represented in the schema and API should be determined before any of this is stabilized so the simple more limited version can neatly fit into the larger design.
 *
 * There are various optimizations that should be implemented to make this performant for large texts and common usage patterns.
 * These include:
 * - Optimized persisted format.
 * - Optimized in memory representation (via chunked forest).
 * - Optimized edit persisted format (e.g. combining adjacent inserts/removes into single operations as well as support for efficient attribute editing of ranges).
 * - Optimized edit application (e.g. applying the above noted optimizable edit cases efficiently).
 * This applies to the revision manager, the forest, and any flex or simple-tree nodes and user events.
 *
 * There are also additional features required for ensuring the invariants of collaborative text editing are maintained through concurrent edits.
 * The main challenges here are related to annotations, but some policies for what to do in the case of corrupt/invalid text should also be included.
 * There are quite a few ways invariants could break, including:
 * - concurrent edits without proper constraints.
 * - collaboration with clients using compatible schema with different constraints.
 * - opening documents which contain invalid content (e.g. from older versions of the software, manual edits to the persisted format, or simply an existing corrupt case which was saved).
 * - a user inserting/constructing/importing invalid content.
 *
 * These cases could break constraints causing issues like invalided characters (empty, a utf-16 surrogate pair alone, etc) or
 * annotations which reference out of bounds character ranges.
 * Addressing these issues mainly falls into these categories:
 * - Handling of invalid content on import/construction of unhydrated nodes and/or insertion into the document (hydration).
 * - Handling of invalid content which is already part of the document (live). This should ideally include both detection and repair.
 * - Constraints on edits to prevent invalid content from being created by merges.
 * - Optimization of the constraints to reduce cases in which edits are rejected due to conflicts.
 *
 * Note that these cases of invariant violations are the same cases any component should handle, so ideally there would be a general framework or pattern for documenting and enforcing such constraints.
 *
 * Another area for future work is improved APIs for import, export and non-schema-aware use. This includes a variety of cases, including but not limited to:
 * - Insertable content format (taken by the constructor and import APIs).
 * - Customizable export formats (like a way to make exportVerbose and exportConcise flatten the text nodes to strings automatically).
 * - Customizable toJson behavior (e.g. flattening to strings, possibly via tools or patterns for custom tree stringifier).
 * - Ensure JS object APIs (like iteration, own vs inherited properties, etc) provide a good and consistent experience with respect to other nodes.
 * - Support in generateSchemaFromSimpleSchema for recognizing text nodes and generating the appropriate schema.
 * - Ensure above features work well enough to support important scenarios like AI assisted editing and document indexing for search.
 *
 * Part of that work will be establishing and documenting those patterns so other components with complex encodings can follow them,
 * in addition to implementing them for text.
 * @alpha
 */
var TextAsTree;
(function (TextAsTree) {
    /**
     * Schema for a {@link TextAsTree.(Tree:variable)} node.
     * @remarks
     * See {@link TextAsTree.Statics} for static APIs on this schema, including construction.
     * @alpha
     */
    TextAsTree.Tree = (0, index_js_2.eraseSchemaDetails)()(TextNode);
})(TextAsTree || (exports.TextAsTree = TextAsTree = {}));
//# sourceMappingURL=textDomain.js.map