aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/CollectionMulticolumnView.tsx
blob: 20923d8e631544967f51a95ff4d54752866b0586 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import { observer } from 'mobx-react';
import { makeInterface } from '../../new_fields/Schema';
import { documentSchema } from '../../new_fields/documentSchemas';
import { CollectionSubView } from './collections/CollectionSubView';
import { DragManager } from '../util/DragManager';
import * as React from "react";
import { Doc, DocListCast } from '../../new_fields/Doc';
import { NumCast, StrCast } from '../../new_fields/Types';
import { List } from '../../new_fields/List';
import { ContentFittingDocumentView } from './nodes/ContentFittingDocumentView';
import { Utils } from '../../Utils';
import "./collectionMulticolumnView.scss";
import { computed } from 'mobx';

type MulticolumnDocument = makeInterface<[typeof documentSchema]>;
const MulticolumnDocument = makeInterface(documentSchema);

interface Unresolved {
    config: Doc;
    target: Doc;
    magnitude: number;
    unit: string;
}

interface Resolved {
    config: Doc;
    target: Doc;
    pixels: number;
}

interface LayoutData {
    unresolved: Unresolved[];
    numFixed: number;
    numRatio: number;
    starSum: number;
}

const resolvedUnits = ["*", "px"];
const resizerWidth = 2;

@observer
export default class CollectionMulticolumnView extends CollectionSubView(MulticolumnDocument) {
    private _dropDisposer?: DragManager.DragDropDisposer;

    /**
     * Returns the list of so-called configuration documents.
     * Each one is a wrapper around what we typically think of as
     * the child document, just also encoding the magnitude and unit
     * of the specified width.
     */
    private get configuration() {
        const { Document } = this.props;
        if (!Document.multicolumnData) {
            Document.multicolumnData = new List<Doc>();
        }
        return DocListCast(this.Document.multicolumnData);
    }

    @computed
    private get resolvedLayoutInformation(): LayoutData {
        const unresolved: Unresolved[] = [];
        let starSum = 0, numFixed = 0, numRatio = 0;
        for (const config of this.configuration) {
            const { target, widthMagnitude, widthUnit } = config;
            if (target instanceof Doc) {
                const unit = StrCast(widthUnit);
                const magnitude = NumCast(widthMagnitude);
                if (unit && magnitude && magnitude > 0 && resolvedUnits.includes(unit)) {
                    if (unit === "*") {
                        starSum += magnitude;
                        numRatio++;
                    } else {
                        numFixed++;
                    }
                    unresolved.push({ config, target, magnitude, unit });
                }
                // otherwise, the particular configuration entry is ignored and the remaining
                // space is allocated as if the document were absent from the configuration list
            }
        }
        return { unresolved, numRatio, numFixed, starSum };
    }

    /**
     * This returns the total quantity, in pixels, that this
     * view needs to reserve for child documents that have
     * (with higher priority) requested a fixed pixel width.
     * 
     * If the underlying resolvedLayoutInformation returns null
     * because we're waiting on promises to resolve, this value will be undefined as well.
     */
    @computed
    private get totalFixedAllocation(): number | undefined {
        const layout = this.resolvedLayoutInformation;
        if (!layout) {
            return undefined;
        }
        let sum = 0;
        for (const { magnitude, unit } of layout.unresolved) {
            if (unit === "px") {
                sum += magnitude;
            }
        }
        return sum;
    }

    /**
     * This returns the total quantity, in pixels, that this
     * view needs to reserve for child documents that have
     * (with lower priority) requested a certain relative proportion of the
     * remaining pixel width not allocated for fixed widths.
     * 
     * If the underlying totalFixedAllocation returns undefined
     * because we're waiting indirectly on promises to resolve, this value will be undefined as well.
     */
    @computed
    private get totalRatioAllocation(): number | undefined {
        const { totalFixedAllocation } = this;
        const layout = this.resolvedLayoutInformation;
        if (!layout) {
            return undefined;
        }
        return totalFixedAllocation !== undefined ? this.props.PanelWidth() - (totalFixedAllocation + resizerWidth * (layout.unresolved.length - 1)) : undefined;
    }

    /**
     * This returns the total quantity, in pixels, that
     * 1* (relative / star unit) is worth. For example,
     * if the configuration has three documents, with, respectively,
     * widths of 2*, 2* and 1*, and the panel width returns 1000px,
     * this accessor returns 1000 / (2 + 2 + 1), or 200px.
     * Elsewhere, this is then multiplied by each relative-width
     * document's (potentially decimal) * count to compute its actual width (400px, 400px and 200px).
     * 
     * If the underlying totalRatioAllocation or this.resolveLayoutInformation return undefined
     * because we're waiting indirectly on promises to resolve, this value will be undefined as well.
     */
    @computed
    private get columnUnitLength(): number | undefined {
        const layout = this.resolvedLayoutInformation;
        const { totalRatioAllocation } = this;
        if (layout === null || totalRatioAllocation === undefined) {
            return undefined;
        }
        return totalRatioAllocation / layout.starSum;
    }

    @computed
    private get contents(): JSX.Element[] | null {
        const layout = this.resolvedLayoutInformation;
        const columnUnitLength = this.columnUnitLength;
        if (layout === null || columnUnitLength === undefined) {
            return (null); // we're still waiting on promises to resolve
        }
        const resolved: Resolved[] = [];
        layout.unresolved.forEach(item => {
            const { unit, magnitude, ...remaining } = item;
            let width = magnitude;
            if (unit === "*") {
                width = magnitude * columnUnitLength;
            }
            resolved.push({ pixels: width, ...remaining });
        });
        const collector: JSX.Element[] = [];
        for (let i = 0; i < resolved.length; i++) {
            const { target, pixels, config } = resolved[i];
            collector.push(
                <div className={"fish"}>
                    <ContentFittingDocumentView
                        {...this.props}
                        key={Utils.GenerateGuid()}
                        Document={target}
                        DataDocument={undefined}
                        PanelWidth={() => pixels}
                        getTransform={this.props.ScreenToLocalTransform}
                    />
                    <span className={"display"}>{NumCast(config.widthMagnitude).toFixed(3)} {StrCast(config.widthUnit)}</span>
                </div>,
                <ResizeBar
                    width={resizerWidth}
                    key={Utils.GenerateGuid()}
                    columnUnitLength={columnUnitLength}
                    toLeft={config}
                    toRight={resolved[i + 1]?.config}
                />
            );
        }
        collector.pop(); // removes the final extraneous resize bar
        return collector;
    }

    render(): JSX.Element {
        return (
            <div className={"collectionMulticolumnView_contents"}>
                {this.contents}
            </div>
        );
    }

}

interface SpacerProps {
    width: number;
    columnUnitLength: number;
    toLeft?: Doc;
    toRight?: Doc;
}

class ResizeBar extends React.Component<SpacerProps> {

    private registerResizing = (e: React.PointerEvent<HTMLDivElement>) => {
        e.stopPropagation();
        e.preventDefault();
        window.removeEventListener("pointermove", this.onPointerMove);
        window.removeEventListener("pointerup", this.onPointerUp);
        window.addEventListener("pointermove", this.onPointerMove);
        window.addEventListener("pointerup", this.onPointerUp);
    }

    private onPointerMove = ({ movementX }: PointerEvent) => {
        const { toLeft, toRight, columnUnitLength } = this.props;
        const target = movementX > 0 ? toRight : toLeft;
        if (target) {
            const { widthUnit, widthMagnitude } = target;
            if (widthUnit === "*") {
                target.widthMagnitude = NumCast(widthMagnitude) - Math.abs(movementX) / columnUnitLength;
            }
        }
    }

    private onPointerUp = () => {
        window.removeEventListener("pointermove", this.onPointerMove);
        window.removeEventListener("pointerup", this.onPointerUp);
    }

    render() {
        return (
            <div
                className={"spacer"}
                style={{ width: this.props.width }}
                onPointerDown={this.registerResizing}
            />
        );
    }

}