yswift

yjs 的 Swift 版本。

y-uniffi 是一个很棒的 yjs Swift 实现,尽管如此,我还是创建了一个完全用 Swift 重新实现的 yjs,因为 y-uniffi 还没有嵌套 Map、UndoManager 等实现。

重要提示

现在这个库是基于 yjs,用 Swift 实现的,用于个人用途,并不打算完全兼容 yjs。

安装

dependencies: [
    .package(url: "https://github.com/ObuchiYuki/yswift.git", branch: "1.0.0"),
]

特性

对象

YArray

YArray 的 Swift 实现

final public class YArray<Element: YElement> 
示例
// init with array literal
let intArray: YArray<Int> = [1, 2] 
print(intArray) // [1, 2]
// index access
print(intArray[1]) // 2

// append Element
intArray.append(3) 
print(intArray) // [1, 2, 3]

// append Sequence
intArray.append(contentsOf: [4, 5]) 
print(intArray) // [1, 2, 3, 4, 5]

// range access
print(intArray[2...]) // [3, 4, 5]

// use as Sequence
for i in intArray { 
    print(i) // 1, 2 ...
}

// YArray with YMap type
let mapArray: YArray<YMap<Int>> = [
    ["Apple": 160]
]

mapArray.append(["Banana": 240])

YMap

YMap 的 Swift 实现

final public class YMap<Value: YElement> 
示例
// init with dictionary literal
let intMap: YMap<Int> = [
    "Apple": 160
] 

// subscript access
intMap["Banana"] = 240
print(intMap["Apple"]) // 160

// nested map
let arrayMap: YMap<YArray<Int>> [
    "Alice": [12, 24],
    "Bob": [24, 64, 75]
]

YObject

绑定到基于 YMap 的类

open class YObject: YOpaqueObject
示例
class Person: YObject {
    // Syncronized property
    @Property var name: String = ""
    // nested proeprty
    @WProperty var children: YArray<Person> = []
    
    required init() {
        super.init()
        self.register(_name, "name")
        self.register(_children, "children")
    }
    
    convenience init(name: String) {
        self.init()
        self.name = name
    }
}

let person = Person(name: "Alice")

// can use as Combine Publisher
person.$name
	.sink{ print("name is \($0)") }.store(in: &bag)

person.$children
	.sink{ print("children is \($0)") }.store(in: &bag)

// update to property to sync
person.name = "Bob"

// update nested type to sync
person.children.append(Person(name: "Bobson"))
YRefrence

存储对对象的引用。

class Layer: YObject {
    @Property var parent: YReference<Layer>? = nil
    @WProperty var children: YArray<Person> = []
    
    func addChild(_ child: Layer) {
        self.children.append(child)
        // make Reference
        child.parent = YReference(self)
    }
    ...
}

let root = Layer("root")
root.addChild(Layer("child0"))

// copy dosen't change a reference.
let copiedRoot = root.copy()
// fail
assert(copiedRoot.children[0].parent.value === copiedRoot) 

// smart copy changes a reference.
let smartCopiedRoot = root.smartCopy()
// success
assert(smartCopiedRoot.children[0].parent.value === smartCopiedRoot)
YElement

YElement 是一个协议,可以被 YArrayYMap 值和 YObject 属性继承。

public protocol YElement {
    /// Make opaque data concrete.
    static func fromOpaque(_ opaque: Any?) -> Self
    
    /// Make concrete data opaque.
    func toOpaque() -> Any?
}

您可以使用 YCodableCodable 值转换为 YElement,或者使用 YRawRepresentable 将枚举转换为 YElement

struct Point: YCodable {
    var x: CGFloat
    var y: CGFloat
}

let array = YArray<Point>()
array.append(Point(x: 1, y: 3))

enum LayerKind: String, YRawRepresentable {
    case rect
    case text
    case path
}

let map = YMap<LayerKind>()
map["rect"] = .rect
map["text"] = .text

或者您可以通过定义自己的编码和解码来创建 YElement

enum Delta<T: YElement>: YElement {
    case by(T)
    case to(T)
    
    public func toOpaque() -> Any? { 
        switch self {
        case .by(let value): return ["by": value.toOpaque()]
        case .to(let value): return ["to": value.toOpaque()]
        }
    }
    
    public static func fromOpaque(_ opaque: Any?) -> Self {
        let (key, value) = (opaque as! [String: Any?]).first
        if (key == "by") { return .by(T.fromOpaque(value)) }
        if (key == "to") { return .to(T.fromOpaque(value)) }
        fatalError("Unexpected case.")
    }
}