repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
libro
github_2023
weavefox
typescript
YNotebook.create
static create(options: ISharedNotebook.IOptions = {}): ISharedNotebook { return new YNotebook(options); }
/** * Create a new YNotebook. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1172-L1174
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.cellsChanged
get cellsChanged(): Event<IListChange> { return this._cellsChanged; }
/** * Signal triggered when the cells list changes. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1234-L1236
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.disableDocumentWideUndoRedo
get disableDocumentWideUndoRedo(): boolean { return this._disableDocumentWideUndoRedo; }
/** * Wether the undo/redo logic should be * considered on the full document across all cells. * * Default: false */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1244-L1246
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.metadata
get metadata(): INotebookMetadata { return this.getMetadata(); }
/** * Notebook metadata */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1251-L1253
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.nbformat
get nbformat(): number { return this.ymeta.get('nbformat'); }
/** * nbformat major version */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1268-L1270
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.nbformat_minor
get nbformat_minor(): number { return this.ymeta.get('nbformat_minor'); }
/** * nbformat minor version */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1280-L1282
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.dispose
override dispose(): void { if (this.isDisposed) { return; } this._ycells.unobserve(this._onYCellsChanged); this.ymeta.unobserve(this._onMetaChanged); this.undoManager.off('stack-item-updated', this.handleUndoChanged); this.undoManager.off('stack-item-added', this.handleUndoChanged); this.undoManager.off('stack-item-popped', this.handleUndoChanged); this.undoManager.off('stack-cleared', this.handleUndoChanged); super.dispose(); }
/** * Dispose of the resources. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1292-L1303
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.getCell
getCell(index: number): YCellType { return this.cells[index]; }
/** * Get a shared cell by index. * * @param index: Cell's position. * * @returns The requested shared cell. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1312-L1314
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.addCell
addCell(cell: SharedCell.Cell): YBaseCell<IBaseCellMetadata> { return this.insertCell(this._ycells.length, cell); }
/** * Add a shared cell at the notebook bottom. * * @param cell Cell to add. * * @returns The added cell. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1323-L1325
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.insertCell
insertCell(index: number, cell: SharedCell.Cell): YBaseCell<IBaseCellMetadata> { return this.insertCells(index, [cell])[0]; }
/** * Insert a shared cell into a specific position. * * @param index: Cell's position. * @param cell: Cell to insert. * * @returns The inserted cell. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1335-L1337
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.insertCells
insertCells(index: number, cells: SharedCell.Cell[]): YBaseCell<IBaseCellMetadata>[] { const yCells = cells.map((c) => { const cell = createCell(c, this); this._ycellMapping.set(cell.ymodel, cell); return cell; }); this.transact(() => { this._ycells.insert( index, yCells.map((cell) => cell.ymodel), ); }); yCells.forEach((c) => { c.setUndoManager(); }); return yCells; }
/** * Insert a list of shared cells into a specific position. * * @param index: Position to insert the cells. * @param cells: Array of shared cells to insert. * * @returns The inserted cells. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1347-L1366
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.moveCell
moveCell(fromIndex: number, toIndex: number): void { this.transact(() => { // FIXME we need to use yjs move feature to preserve undo history const clone = createCell(this.getCell(fromIndex).toJSON(), this); this._ycells.delete(fromIndex, 1); this._ycells.insert(toIndex, [clone.ymodel]); }); }
/** * Move a cell. * * @param fromIndex: Index of the cell to move. * @param toIndex: New position of the cell. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1374-L1381
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.deleteCell
deleteCell(index: number): void { this.deleteCellRange(index, index + 1); }
/** * Remove a cell. * * @param index: Index of the cell to remove. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1388-L1390
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.deleteCellRange
deleteCellRange(from: number, to: number): void { // Cells will be removed from the mapping in the model event listener. this.transact(() => { this._ycells.delete(from, to - from); }); }
/** * Remove a range of cells. * * @param from: The start index of the range to remove (inclusive). * @param to: The end index of the range to remove (exclusive). */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1398-L1403
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.deleteMetadata
deleteMetadata(key: string): void { const allMetadata = deepCopy(this.ymeta.get('metadata')); delete allMetadata[key]; this.setMetadata(allMetadata); }
/** * Delete a metadata notebook. * * @param key The key to delete */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1410-L1414
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.getMetadata
getMetadata(key?: string): INotebookMetadata { const meta = this.ymeta.get('metadata'); if (typeof key === 'string') { return deepCopy(meta[key]); } else { return deepCopy(meta ?? {}); } }
/** * Returns some metadata associated with the notebook. * * If no `key` is provided, it will return all metadata. * Else it will return the value for that key. * * @param key Key to get from the metadata * @returns Notebook's metadata. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1425-L1433
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.setMetadata
setMetadata(metadata: INotebookMetadata | string, value?: PartialJSONValue): void { if (typeof metadata === 'string') { if (typeof value === 'undefined') { throw new TypeError( `Metadata value for ${metadata} cannot be 'undefined'; use deleteMetadata.`, ); } const update: Partial<INotebookMetadata> = {}; update[metadata] = value; this.updateMetadata(update); } else { this.ymeta.set('metadata', deepCopy(metadata)); } }
/** * Sets some metadata associated with the notebook. * * If only one argument is provided, it will override all notebook metadata. * Otherwise a single key will be set to a new value. * * @param metadata All Notebook's metadata or the key to set. * @param value New metadata value */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1444-L1457
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
YNotebook.updateMetadata
updateMetadata(value: Partial<INotebookMetadata>): void { // TODO: Maybe modify only attributes instead of replacing the whole metadata? this.ymeta.set('metadata', { ...this.getMetadata(), ...value }); }
/** * Updates the metadata associated with the notebook. * * @param value: Metadata's attribute to update. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-shared-model/src/ymodels.ts#L1464-L1467
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection.constructor
constructor( @inject(TerminalOption) options: TerminalOption & { name: string }, @inject(ServerConnection) serverConnection: ServerConnection, ) { this._name = options.name; this.serverConnection = serverConnection; this._createSocket(); }
/** * Construct a new terminal session. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L42-L49
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection.messageReceived
get messageReceived(): Event<TerminalMessage> { return this._messageReceived.event; }
/** * A signal emitted when a message is received from the server. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L54-L56
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection.name
get name(): string { return this._name; }
/** * Get the name of the terminal session. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L65-L67
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection.model
get model(): TerminalModel { return { name: this._name }; }
/** * Get the model for the terminal session. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L72-L74
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection.serverSettings
get serverSettings() { return this.serverConnection.settings; }
/** * The server settings for the session. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L79-L81
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection.dispose
dispose(): void { if (this.disposed) { return; } this.disposed = true; this.shutdown().catch(console.error); this._updateConnectionStatus('disconnected'); this._clearSocket(); }
/** * Dispose of the resources held by the session. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L86-L94
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection.send
send(message: TerminalMessage): void { this._sendMessage(message); }
/** * Send a message to the terminal session. * * #### Notes * If the connection is down, the message will be queued for sending when * the connection comes back up. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L103-L105
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection._sendMessage
_sendMessage(message: TerminalMessage, queue = true): void { if (this.disposed || !message.content) { return; } if (this.connectionStatus === 'connected' && this._ws) { const msg = [message.type, ...message.content]; this._ws.send(JSON.stringify(msg)); } else if (queue) { this._pendingMessages.push(message); } else { throw new Error(`Could not send message: ${JSON.stringify(message)}`); } }
/** * Send a message on the websocket, or possibly queue for later sending. * * @param queue - whether to queue the message if it cannot be sent */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L112-L124
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection._sendPending
protected _sendPending(): void { // We check to make sure we are still connected each time. For // example, if a websocket buffer overflows, it may close, so we should // stop sending messages. while (this.connectionStatus === 'connected' && this._pendingMessages.length > 0) { this._sendMessage(this._pendingMessages[0], false); // We shift the message off the queue after the message is sent so that // if there is an exception, the message is still pending. this._pendingMessages.shift(); } }
/** * Send pending messages to the kernel. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L129-L140
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection._createSocket
reconnect = (): Promise<void> => { this._errorIfDisposed(); const result = new Deferred<void>(); // Set up a listener for the connection status changing, which accepts or // rejects after the retries are done. const fulfill = (status: TerminalConnectionStatus) => { if (status === 'connected') { result.resolve(); this.toDisposeOnReconnect?.dispose(); } else if (status === 'disconnected') { result.reject(new Error('Terminal connection disconnected')); this.toDisposeOnReconnect?.dispose(); } }; this.toDisposeOnReconnect = this.connectionStatusChanged(fulfill); // Reset the reconnect limit so we start the connection attempts fresh this._reconnectAttempt = 0; // Start the reconnection process, which will also clear any existing // connection. this._reconnect(); // Return the promise that should resolve on connection or reject if the // retries don't work. return result.promise; }
/** * Create the terminal websocket connection and add socket status handlers. * * #### Notes * You are responsible for updating the connection status as appropriate. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
fulfill
const fulfill = (status: TerminalConnectionStatus) => { if (status === 'connected') { result.resolve(); this.toDisposeOnReconnect?.dispose(); } else if (status === 'disconnected') { result.reject(new Error('Terminal connection disconnected')); this.toDisposeOnReconnect?.dispose(); } };
// Set up a listener for the connection status changing, which accepts or
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L152-L160
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection._reconnect
_reconnect(): void { this._errorIfDisposed(); // Clear any existing reconnection attempt clearTimeout(this._reconnectTimeout); // Update the connection status and schedule a possible reconnection. if (this._reconnectAttempt < this._reconnectLimit) { this._updateConnectionStatus('connecting'); // The first reconnect attempt should happen immediately, and subsequent // attempts should pick a random number in a growing range so that we // don't overload the server with synchronized reconnection attempts // across multiple kernels. const timeout = getRandomIntInclusive( 0, 1e3 * (Math.pow(2, this._reconnectAttempt) - 1), ); console.error( `Connection lost, reconnecting in ${Math.floor(timeout / 1000)} seconds.`, ); this._reconnectTimeout = setTimeout(this._createSocket, timeout); this._reconnectAttempt += 1; } else { this._updateConnectionStatus('disconnected'); } // Clear the websocket event handlers and the socket itself. this._clearSocket(); }
/** * Attempt a connection if we have not exhausted connection attempts. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L178-L207
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection._clearSocket
protected _clearSocket(): void { if (this._ws) { // Clear the websocket event handlers and the socket itself. this._ws.onopen = this._noOp; this._ws.onclose = this._noOp; this._ws.onerror = this._noOp; this._ws.onmessage = this._noOp; this._ws.close(); this._ws = undefined; } }
/** * Forcefully clear the socket state. * * #### Notes * This will clear all socket state without calling any handlers and will * not update the connection status. If you call this method, you are * responsible for updating the connection status as needed and recreating * the socket if you plan to reconnect. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L218-L228
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection.shutdown
async shutdown(): Promise<void> { await this.terminalRestAPI.shutdown(this.name, this.serverSettings); this.dispose(); }
/** * Shut down the terminal session. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L233-L236
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalConnection._updateConnectionStatus
protected _updateConnectionStatus(connectionStatus: TerminalConnectionStatus): void { if (this._connectionStatus === connectionStatus) { return; } this._connectionStatus = connectionStatus; // If we are not 'connecting', stop any reconnection attempts. if (connectionStatus !== 'connecting') { this._reconnectAttempt = 0; clearTimeout(this._reconnectTimeout); } // Send the pending messages if we just connected. if (connectionStatus === 'connected') { this._sendPending(); } // Notify others that the connection status changed. this._connectionStatusChanged.fire(connectionStatus); }
/** * Handle connection status changes. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/connection.ts#L314-L334
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.constructor
constructor(@inject(ServerConnection) serverConnection: ServerConnection) { this.serverConnection = serverConnection; // // Start polling with exponential backoff. this._pollModels = new Poll({ auto: false, factory: () => this.requestRunning(), frequency: { interval: 10 * 1000, backoff: true, max: 300 * 1000, }, name: `@jupyterlab/services:TerminalManager#models`, standby: 'when-hidden', }); // Initialize internal data. this._ready = (async () => { await this._pollModels.start(); await this._pollModels.tick; this._isReady = true; })(); }
/** * Construct a new terminal manager. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L50-L72
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.serverSettings
get serverSettings() { return this.serverConnection.settings; }
/** * The server settings of the manager. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L77-L79
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.isReady
get isReady(): boolean { return this._isReady; }
/** * Test whether the manager is ready. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L84-L86
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.ready
get ready(): Promise<void> { return this._ready; }
/** * A promise that fulfills when the manager is ready. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L91-L93
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.runningChanged
get runningChanged(): Event<TerminalModel[]> { return this._runningChanged.event; }
/** * A signal emitted when the running terminals change. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L98-L100
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.connectionFailure
get connectionFailure(): Event<Error> { return this._connectionFailure.event; }
/** * A signal emitted when there is a connection failure. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L105-L107
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.dispose
dispose(): void { if (this.disposed) { return; } this._names.length = 0; this._terminalConnections.forEach((x) => x.dispose()); this._pollModels.dispose(); this.disposed = true; }
/** * Dispose of the resources used by the manager. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L112-L120
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.connectTo
connectTo(options: { name: string }): TerminalConnection { const terminalConnection = this.terminalConnectionFactory(options); this._onStarted(terminalConnection); if (!this._names.includes(options.name)) { // We trust the user to connect to an existing session, but we verify // asynchronously. void this.refreshRunning().catch(() => { /* no-op */ }); } return terminalConnection; }
/* * Connect to a running terminal. * * @param options - The options used to connect to the terminal. * * @returns The new terminal connection instance. * * #### Notes * The manager `serverSettings` will be used. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L132-L143
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.running
running(): IterableIterator<TerminalModel> { return this._models[Symbol.iterator](); }
/** * Create an iterator over the most recent running terminals. * * @returns A new iterator over the running terminals. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L150-L152
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.refreshRunning
async refreshRunning(): Promise<void> { await this._pollModels.refresh(); await this._pollModels.tick; }
/** * Force a refresh of the running terminals. * * @returns A promise that with the list of running terminals. * * #### Notes * This is intended to be called only in response to a user action, * since the manager maintains its internal state. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L167-L170
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.startNew
async startNew(options: TerminalOption): Promise<TerminalConnection> { const model = await this.terminalRestAPI.startNew(options, this.serverSettings); await this.refreshRunning(); return this.connectTo({ ...options, name: model.name }); }
/** * Create a new terminal session. * * @param options - The options used to create the terminal. * * @returns A promise that resolves with the terminal connection instance. * * #### Notes * The manager `serverSettings` will be used unless overridden in the * options. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L183-L187
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.shutdown
async shutdown(name: string): Promise<void> { await this.terminalRestAPI.shutdown(name, this.serverSettings); await this.refreshRunning(); }
/** * Shut down a terminal session by name. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L192-L195
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.shutdownAll
async shutdownAll(): Promise<void> { // Update the list of models to make sure our list is current. await this.refreshRunning(); // Shut down all models. await Promise.all( this._names.map((name) => this.terminalRestAPI.shutdown(name, this.serverSettings), ), ); // Update the list of models to clear out our state. await this.refreshRunning(); }
/** * Shut down all terminal sessions. * * @returns A promise that resolves when all of the sessions are shut down. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L202-L215
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.requestRunning
async requestRunning(): Promise<void> { let models: TerminalModel[]; try { models = await this.terminalRestAPI.listRunning(this.serverSettings); } catch (err) { // Handle network errors, as well as cases where we are on a // JupyterHub and the server is not running. JupyterHub returns a // 503 (<2.0) or 424 (>2.0) in that case. if ( err instanceof NetworkError || (err as any).response?.status === 503 || (err as any).response?.status === 424 ) { this._connectionFailure.fire(err as any); } throw err; } if (this.disposed) { return; } const names = models.map(({ name }) => name).sort(); if (names === this._names) { // Identical models list, so just return return; } this._names = names; this._terminalConnections.forEach((tc) => { if (!names.includes(tc.name)) { tc.dispose(); } }); this._runningChanged.fire(this._models); }
/** * Execute a request to the server to poll running terminals and update state. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L220-L255
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager._onStarted
protected _onStarted(terminalConnection: TerminalConnection): void { this._terminalConnections.add(terminalConnection); terminalConnection.onDisposed(() => { this._onDisposed(terminalConnection); }); }
/** * Handle a session starting. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L260-L265
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager._onDisposed
protected _onDisposed(terminalConnection: TerminalConnection): void { this._terminalConnections.delete(terminalConnection); // Update the running models to make sure we reflect the server state void this.refreshRunning().catch(() => { /* no-op */ }); }
/** * Handle a session terminating. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts#L270-L276
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
TerminalManager.getTerminalArgs
getTerminalArgs = (name?: string) => { // 通过缓存值作为option创建终端 if (this.terminalOptionsCache.has(name)) { return this.terminalOptionsCache.get(name); } if (name) { return { name: name }; } else { return { id: v4() }; } }
// 新建和打开一个已有Terminal,二者所需参数不一样
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/manager.ts
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroTerminalView.dispose
override dispose(): void { if (!this.connection?.disposed) { this.connection?.shutdown().catch((reason) => { console.error(`Terminal not shut down: ${reason}`); }); } this.terminalManager.terminalOptionsCache.delete(this.name); super.dispose(); }
// todo merge options to initcommand
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/view.tsx#L265-L275
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroTerminalView.getTerminalRendererType
protected onMessage = (msg: TerminalMessage) => { switch (msg.type) { case 'stdout': if (msg.content) { this.term.write(msg.content[0] as string); } break; case 'disconnect': this.term.write(l10n.t('[Finished… Term Session]')); break; default: break; } }
/** * Returns given renderer type if it is valid and supported or default renderer otherwise. * * @param terminalRendererType desired terminal renderer type */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/view.tsx
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroTerminalView.initialTitle
protected initialTitle() { if (this.connection?.connectionStatus !== 'connected') { return; } const title = `Terminal ${this.connection.name}`; this.title.label = title; this.onTitleChangeEmitter.fire(title); }
// default title
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/view.tsx#L328-L335
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroTerminalView.setSessionSize
protected setSessionSize(): void { if (this.container && this.container.current) { const content = [ this.term.rows, this.term.cols, this.container.current.offsetHeight, this.container.current.offsetWidth, ]; if (!this.isDisposed && this.connection) { this.connection.send({ type: 'set_size', content }); } } }
/** * Set the size of the terminal in the session. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/view.tsx#L441-L454
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroTerminalView.createTerminal
protected createTerminal(options: ITerminalOptions): [Terminal, FitAddon] { const term = new Terminal(options); this.addRenderer(term); const fitAddon = new FitAddon(); term.loadAddon(fitAddon); term.loadAddon(new WebLinksAddon()); return [term, fitAddon]; }
/** * Create a xterm.js terminal */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/view.tsx#L532-L539
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroTerminalView.name
public get name() { return this.connection?.name || ''; }
/** * Terminal is ready event */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/view.tsx#L564-L566
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroTerminalView.hasSelection
public hasSelection(): boolean { if (!this.isDisposed && this._isReady) { return this.term.hasSelection(); } return false; }
/** * Check if terminal has any text selected. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/view.tsx#L573-L578
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroTerminalView.paste
public paste(data: string): void { if (!this.isDisposed && this._isReady) { return this.term.paste(data); } }
/** * Paste text into terminal. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/view.tsx#L583-L587
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
LibroTerminalView.getSelection
public getSelection(): string | null { if (!this.isDisposed && this._isReady) { return this.term.getSelection(); } return null; }
/** * Get selected text from terminal. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-terminal/src/view.tsx#L592-L597
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
parseHeading
function parseHeading(line: string, nextLine?: string): IHeader | null { // Case: Markdown heading let match = line.match(/^([#]{1,6}) (.*)/); if (match) { return { text: cleanTitle(match[2]), level: match[1].length, raw: line, skip: skipHeading.test(match[0]), }; } // Case: Markdown heading (alternative style) if (nextLine) { match = nextLine.match(/^ {0,3}([=]{2,}|[-]{2,})\s*$/); if (match) { return { text: cleanTitle(line), level: match[1][0] === '=' ? 1 : 2, raw: [line, nextLine].join('\n'), skip: skipHeading.test(line), }; } } // Case: HTML heading (WARNING: this is not particularly robust, as HTML headings can span multiple lines) match = line.match(/<h([1-6]).*>(.*)<\/h\1>/i); if (match) { return { text: match[2], level: parseInt(match[1], 10), skip: skipHeading.test(match[0]), raw: line, }; } return null; }
/** * Parses a heading, if one exists, from a provided string. * @param line - Line to parse * @param nextLine - The line after the one to parse * @returns heading info * * @example * ### Foo * const out = parseHeading('### Foo\n'); * // returns {'text': 'Foo', 'level': 3} * * @example * const out = parseHeading('Foo\n===\n'); * // returns {'text': 'Foo', 'level': 1} * * @example * <h4>Foo</h4> * const out = parseHeading('<h4>Foo</h4>\n'); * // returns {'text': 'Foo', 'level': 4} * * @example * const out = parseHeading('Foo'); * // returns null */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-toc/src/provider/markdown.ts#L140-L175
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
Grid.getOffsetForCell
getOffsetForCell({ alignment = this.props.scrollToAlignment, columnIndex = this.props.scrollToColumn, rowIndex = this.props.scrollToRow, }: { alignment?: Alignment; columnIndex?: number; rowIndex?: number; } = {}) { const offsetProps = { ...this.props, scrollToAlignment: alignment, scrollToColumn: columnIndex, scrollToRow: rowIndex, }; return { scrollLeft: this._getCalculatedScrollLeft(offsetProps), scrollTop: this._getCalculatedScrollTop(offsetProps), }; }
/** * Gets offsets for a given cell and alignment. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/grid.tsx#L414-L434
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
Grid.getTotalRowsHeight
getTotalRowsHeight() { return this.state.instanceProps.rowSizeAndPositionManager.getTotalSize(); }
/** * Gets estimated total rows' height. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/grid.tsx#L439-L441
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
Grid.getTotalColumnsWidth
getTotalColumnsWidth() { return this.state.instanceProps.columnSizeAndPositionManager.getTotalSize(); }
/** * Gets estimated total columns' width. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/grid.tsx#L446-L448
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
Grid.handleScrollEvent
handleScrollEvent({ scrollLeft: scrollLeftParam = 0, scrollTop: scrollTopParam = 0, }: ScrollPosition) { // On iOS, we can arrive at negative offsets by swiping past the start. // To prevent flicker here, we make playing in the negative offset zone cause nothing to happen. if (scrollTopParam < 0) { return; } // Prevent pointer events from interrupting a smooth scroll this._debounceScrollEnded(); const { autoHeight, autoWidth, height, width } = this.props; const { instanceProps } = this.state; // When this component is shrunk drastically, React dispatches a series of back-to-back scroll events, // Gradually converging on a scrollTop that is within the bounds of the new, smaller height. // This causes a series of rapid renders that is slow for long lists. // We can avoid that by doing some simple bounds checking to ensure that scroll offsets never exceed their bounds. const scrollbarSize = instanceProps.scrollbarSize; const totalRowsHeight = instanceProps.rowSizeAndPositionManager.getTotalSize(); const totalColumnsWidth = instanceProps.columnSizeAndPositionManager.getTotalSize(); const scrollLeft = Math.min( Math.max(0, totalColumnsWidth - width + scrollbarSize), scrollLeftParam, ); const scrollTop = Math.min( Math.max(0, totalRowsHeight - height + scrollbarSize), scrollTopParam, ); // Certain devices (like Apple touchpad) rapid-fire duplicate events. // Don't force a re-render if this is the case. // The mouse may move faster then the animation frame does. // Use requestAnimationFrame to avoid over-updating. if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) { // Track scrolling direction so we can more efficiently overscan rows to reduce empty space around the edges while scrolling. // Don't change direction for an axis unless scroll offset has changed. const scrollDirectionHorizontal = scrollLeft !== this.state.scrollLeft ? scrollLeft > this.state.scrollLeft ? SCROLL_DIRECTION_FORWARD : SCROLL_DIRECTION_BACKWARD : this.state.scrollDirectionHorizontal; const scrollDirectionVertical = scrollTop !== this.state.scrollTop ? scrollTop > this.state.scrollTop ? SCROLL_DIRECTION_FORWARD : SCROLL_DIRECTION_BACKWARD : this.state.scrollDirectionVertical; // if ( // scrollCache && // // scrollCache.direction !== scrollDirectionVertical && // Date.now() - scrollCache.timestamp < 150 // ) { // return; // } // // 更新缓存 // scrollCache = { // timestamp: Date.now(), // direction: scrollDirectionVertical, // }; const newState: any = { isScrolling: true, scrollDirectionHorizontal, scrollDirectionVertical, scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.OBSERVED, }; if (!autoHeight) { newState.scrollTop = scrollTop; } if (!autoWidth) { newState.scrollLeft = scrollLeft; } newState.needToResetStyleCache = false; this.setState(newState); } this._invokeOnScrollMemoizer({ scrollLeft, scrollTop, totalColumnsWidth, totalRowsHeight, }); }
/** * This method handles a scroll event originating from an external scroll control. * It's an advanced method and should probably not be used unless you're implementing a custom scroll-bar solution. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/grid.tsx#L454-L545
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
Grid.invalidateCellSizeAfterRender
invalidateCellSizeAfterRender({ columnIndex, rowIndex }: CellPosition) { this._deferredInvalidateColumnIndex = typeof this._deferredInvalidateColumnIndex === 'number' ? Math.min(this._deferredInvalidateColumnIndex, columnIndex) : columnIndex; this._deferredInvalidateRowIndex = typeof this._deferredInvalidateRowIndex === 'number' ? Math.min(this._deferredInvalidateRowIndex, rowIndex) : rowIndex; }
// @TODO (bvaughn) Add automated test coverage for this.
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/grid.tsx#L554-L563
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
Grid.measureAllCells
measureAllCells() { const { columnCount, rowCount } = this.props; const { instanceProps } = this.state; instanceProps.columnSizeAndPositionManager.getSizeAndPositionOfCell( columnCount - 1, ); instanceProps.rowSizeAndPositionManager.getSizeAndPositionOfCell(rowCount - 1); }
/** * Pre-measure all columns and rows in a Grid. * Typically cells are only measured as needed and estimated sizes are used for cells that have not yet been measured. * This method ensures that the next call to getTotalSize() returns an exact size (as opposed to just an estimated one). */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/grid.tsx#L570-L577
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
Grid.recomputeGridSize
recomputeGridSize( { columnIndex = 0, rowIndex = 0 }: CellPosition = { columnIndex: 0, rowIndex: 0 }, ) { const { scrollToColumn, scrollToRow } = this.props; const { instanceProps } = this.state; instanceProps.columnSizeAndPositionManager.resetCell(columnIndex); instanceProps.rowSizeAndPositionManager.resetCell(rowIndex); // Cell sizes may be determined by a function property. // In this case the cDU handler can't know if they changed. // Store this flag to let the next cDU pass know it needs to recompute the scroll offset. this._recomputeScrollLeftFlag = scrollToColumn >= 0 && (this.state.scrollDirectionHorizontal === SCROLL_DIRECTION_FORWARD ? columnIndex <= scrollToColumn : columnIndex >= scrollToColumn); this._recomputeScrollTopFlag = scrollToRow >= 0 && (this.state.scrollDirectionVertical === SCROLL_DIRECTION_FORWARD ? rowIndex <= scrollToRow : rowIndex >= scrollToRow); // Clear cell cache in case we are scrolling; // Invalid row heights likely mean invalid cached content as well. this._styleCache = {}; this._cellCache = {}; this.forceUpdate(); }
/** * Forced recompute of row heights and column widths. * This function should be called if dynamic column or row sizes have changed but nothing else has. * Since Grid only receives :columnCount and :rowCount it has no way of detecting when the underlying data changes. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/grid.tsx#L584-L613
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
Grid.scrollToCell
scrollToCell({ columnIndex, rowIndex }: CellPosition) { const { columnCount } = this.props; const props = this.props; // Don't adjust scroll offset for single-column grids (eg List, Table). // This can cause a funky scroll offset because of the vertical scrollbar width. if (columnCount > 1 && columnIndex !== undefined) { this._updateScrollLeftForScrollToColumn({ ...props, scrollToColumn: columnIndex, }); } if (rowIndex !== undefined) { this._updateScrollTopForScrollToRow({ ...props, scrollToRow: rowIndex, }); } }
/** * Ensure column and row are visible. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/grid.tsx#L635-L655
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
Grid.componentDidUpdate
override componentDidUpdate(prevProps: Props, prevState: State) { const { autoHeight, autoWidth, columnCount, height, rowCount, scrollToAlignment, scrollToColumn, scrollToRow, width, } = this.props; const { scrollLeft, scrollPositionChangeReason, scrollTop, instanceProps } = this.state; // If cell sizes have been invalidated (eg we are using CellMeasurer) then reset cached positions. // We must do this at the start of the method as we may calculate and update scroll position below. this._handleInvalidatedGridSize(); // Handle edge case where column or row count has only just increased over 0. // In this case we may have to restore a previously-specified scroll offset. // For more info see bvaughn/react-virtualized/issues/218 const columnOrRowCountJustIncreasedFromZero = (columnCount > 0 && prevProps.columnCount === 0) || (rowCount > 0 && prevProps.rowCount === 0); // Make sure requested changes to :scrollLeft or :scrollTop get applied. // Assigning to scrollLeft/scrollTop tells the browser to interrupt any running scroll animations, // And to discard any pending async changes to the scroll position that may have happened in the meantime (e.g. on a separate scrolling thread). // So we only set these when we require an adjustment of the scroll position. // See issue #2 for more information. if (scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED) { // @TRICKY :autoHeight and :autoWidth properties instructs Grid to leave :scrollTop and :scrollLeft management to an external HOC (eg WindowScroller). // In this case we should avoid checking scrollingContainer.scrollTop and scrollingContainer.scrollLeft since it forces layout/flow. if ( !autoWidth && scrollLeft >= 0 && (scrollLeft !== this._scrollingContainer.scrollLeft || columnOrRowCountJustIncreasedFromZero) ) { this._scrollingContainer.scrollLeft = scrollLeft; } if ( !autoHeight && scrollTop >= 0 && (scrollTop !== this._scrollingContainer.scrollTop || columnOrRowCountJustIncreasedFromZero) ) { this._scrollingContainer.scrollTop = scrollTop; } } // Special case where the previous size was 0: // In this case we don't show any windowed cells at all. // So we should always recalculate offset afterwards. const sizeJustIncreasedFromZero = (prevProps.width === 0 || prevProps.height === 0) && height > 0 && width > 0; // Update scroll offsets if the current :scrollToColumn or :scrollToRow values requires it // @TODO Do we also need this check or can the one in componentWillUpdate() suffice? if (this._recomputeScrollLeftFlag) { this._recomputeScrollLeftFlag = false; this._updateScrollLeftForScrollToColumn(this.props); } else { updateScrollIndexHelper({ cellSizeAndPositionManager: instanceProps.columnSizeAndPositionManager, previousCellsCount: prevProps.columnCount, previousCellSize: prevProps.columnWidth, previousScrollToAlignment: prevProps.scrollToAlignment, previousScrollToIndex: prevProps.scrollToColumn, previousSize: prevProps.width, scrollOffset: scrollLeft, scrollToAlignment, scrollToIndex: scrollToColumn, size: width, sizeJustIncreasedFromZero, updateScrollIndexCallback: () => this._updateScrollLeftForScrollToColumn(this.props), }); } if (this._recomputeScrollTopFlag) { this._recomputeScrollTopFlag = false; this._updateScrollTopForScrollToRow(this.props); } else { updateScrollIndexHelper({ cellSizeAndPositionManager: instanceProps.rowSizeAndPositionManager, previousCellsCount: prevProps.rowCount, previousCellSize: prevProps.rowHeight, previousScrollToAlignment: prevProps.scrollToAlignment, previousScrollToIndex: prevProps.scrollToRow, previousSize: prevProps.height, scrollOffset: scrollTop, scrollToAlignment, scrollToIndex: scrollToRow, size: height, sizeJustIncreasedFromZero, updateScrollIndexCallback: () => this._updateScrollTopForScrollToRow(this.props), }); } // Update onRowsRendered callback if start/stop indices have changed this._invokeOnGridRenderedHelper(); // Changes to :scrollLeft or :scrollTop should also notify :onScroll listeners if (scrollLeft !== prevState.scrollLeft || scrollTop !== prevState.scrollTop) { const totalRowsHeight = instanceProps.rowSizeAndPositionManager.getTotalSize(); const totalColumnsWidth = instanceProps.columnSizeAndPositionManager.getTotalSize(); this._invokeOnScrollMemoizer({ scrollLeft, scrollTop, totalColumnsWidth, totalRowsHeight, }); } this._maybeCallOnScrollbarPresenceChange(); }
/** * @private * This method updates scrollLeft/scrollTop in state for the following conditions: * 1) New scroll-to-cell props have been set */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/grid.tsx#L760-L880
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
Grid.getDerivedStateFromProps
static getDerivedStateFromProps(nextProps: Props, prevState: State) { const newState: any = {}; const { instanceProps } = prevState; if ( (nextProps.columnCount === 0 && prevState.scrollLeft !== 0) || (nextProps.rowCount === 0 && prevState.scrollTop !== 0) ) { newState.scrollLeft = 0; newState.scrollTop = 0; // only use scroll{Left,Top} from props if scrollTo{Column,Row} isn't specified // scrollTo{Column,Row} should override scroll{Left,Top} } else if ( (nextProps.scrollLeft !== instanceProps.prevScrollLeft && nextProps.scrollToColumn < 0) || (nextProps.scrollTop !== instanceProps.prevScrollTop && nextProps.scrollToRow < 0) ) { Object.assign( newState, Grid._getScrollToPositionStateUpdate({ prevState, scrollLeft: nextProps.scrollLeft, scrollTop: nextProps.scrollTop, }), ); } // Initially we should not clearStyleCache newState.needToResetStyleCache = false; if ( nextProps.columnWidth !== instanceProps.prevColumnWidth || nextProps.rowHeight !== instanceProps.prevRowHeight ) { // Reset cache. set it to {} in render newState.needToResetStyleCache = true; } instanceProps.columnSizeAndPositionManager.configure({ cellCount: nextProps.columnCount, estimatedCellSize: Grid._getEstimatedColumnSize(nextProps), cellSizeGetter: Grid._wrapSizeGetter(nextProps.columnWidth), }); instanceProps.rowSizeAndPositionManager.configure({ cellCount: nextProps.rowCount, estimatedCellSize: Grid._getEstimatedRowSize(nextProps), cellSizeGetter: Grid._wrapSizeGetter(nextProps.rowHeight), cellsHeight: nextProps.cellsHeight, editorAreaHeight: nextProps.editorAreaHeight, totalSize: nextProps.totalSize, editorsOffset: nextProps.editorsOffset, }); if (instanceProps.prevColumnCount === 0 || instanceProps.prevRowCount === 0) { instanceProps.prevColumnCount = 0; instanceProps.prevRowCount = 0; } // If scrolling is controlled outside this component, clear cache when scrolling stops if ( nextProps.autoHeight && nextProps.isScrolling === false && instanceProps.prevIsScrolling === true ) { Object.assign(newState, { isScrolling: false, }); } let maybeStateA: any; let maybeStateB: any; calculateSizeAndPositionDataAndUpdateScrollOffset({ cellCount: instanceProps.prevColumnCount, cellSize: typeof instanceProps.prevColumnWidth === 'number' ? instanceProps.prevColumnWidth : null, computeMetadataCallback: () => instanceProps.columnSizeAndPositionManager.resetCell(0), computeMetadataCallbackProps: nextProps, nextCellsCount: nextProps.columnCount, nextCellSize: typeof nextProps.columnWidth === 'number' ? nextProps.columnWidth : null, nextScrollToIndex: nextProps.scrollToColumn, scrollToIndex: instanceProps.prevScrollToColumn, updateScrollOffsetForScrollToIndex: () => { maybeStateA = Grid._getScrollLeftForScrollToColumnStateUpdate( nextProps, prevState, ); }, }); calculateSizeAndPositionDataAndUpdateScrollOffset({ cellCount: instanceProps.prevRowCount, cellSize: typeof instanceProps.prevRowHeight === 'number' ? instanceProps.prevRowHeight : null, computeMetadataCallback: () => instanceProps.rowSizeAndPositionManager.resetCell(0), computeMetadataCallbackProps: nextProps, nextCellsCount: nextProps.rowCount, nextCellSize: typeof nextProps.rowHeight === 'number' ? nextProps.rowHeight : null, nextScrollToIndex: nextProps.scrollToRow, scrollToIndex: instanceProps.prevScrollToRow, updateScrollOffsetForScrollToIndex: () => { maybeStateB = Grid._getScrollTopForScrollToRowStateUpdate(nextProps, prevState); }, }); instanceProps.prevColumnCount = nextProps.columnCount; instanceProps.prevColumnWidth = nextProps.columnWidth; instanceProps.prevIsScrolling = nextProps.isScrolling === true; instanceProps.prevRowCount = nextProps.rowCount; instanceProps.prevRowHeight = nextProps.rowHeight; instanceProps.prevScrollToColumn = nextProps.scrollToColumn; instanceProps.prevScrollToRow = nextProps.scrollToRow; instanceProps.prevScrollLeft = nextProps.scrollLeft; instanceProps.prevScrollTop = nextProps.scrollTop; // getting scrollBarSize (moved from componentWillMount) instanceProps.scrollbarSize = nextProps.getScrollbarSize(); if (instanceProps.scrollbarSize === undefined) { instanceProps.scrollbarSizeMeasured = false; instanceProps.scrollbarSize = 0; } else { instanceProps.scrollbarSizeMeasured = true; } newState.instanceProps = instanceProps; return { ...newState, ...maybeStateA, ...maybeStateB }; }
/** * This method updates scrollLeft/scrollTop in state for the following conditions: * 1) Empty content (0 rows or columns) * 2) New scroll props overriding the current state * 3) Cells-count or cells-size has changed, making previous scroll offsets invalid */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/grid.tsx#L898-L1033
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
RowCellSizeAndPositionManager.getSizeAndPositionOfCell
getSizeAndPositionOfCell(index: number): SizeAndPositionData { if (index < 0 || index >= this._cellCount) { throw Error(`Requested index ${index} is outside of range 0..${this._cellCount}`); } if (index > this._lastMeasuredIndex) { const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); let offset = lastMeasuredCellSizeAndPosition.offset; // + lastMeasuredCellSizeAndPosition.size; for (let i = this._lastMeasuredIndex + 1; i <= index; i++) { // const size = this._cellSizeGetter({ index: i }); const size = this._editorAreaHeight[i]; offset = this._editorsOffset[i]; // 上border高度 // undefined or NaN probably means a logic error in the size getter. // null means we're using CellMeasurer and haven't yet measured a given index. if (size === undefined || isNaN(size)) { throw Error(`Invalid size returned for cell ${i} of value ${size}`); } else if (size === null) { this._cellSizeAndPositionData[i] = { offset, size: 0, }; this._lastBatchedIndex = index; } else { this._cellSizeAndPositionData[i] = { offset, size, }; this._lastMeasuredIndex = index; } } } return this._cellSizeAndPositionData[index]; }
/** * This method returns the size and position for the cell at the specified index. * It just-in-time calculates (or used cached values) for cells leading up to the index. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/cell-size-and-position-manager-row.ts#L145-L183
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
RowCellSizeAndPositionManager.getTotalSize
getTotalSize(): number { return this._totalSize; // const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); // const totalSizeOfMeasuredCells = // lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size; // const numUnmeasuredCells = this._cellCount - this._lastMeasuredIndex - 1; // const totalSizeOfUnmeasuredCells = numUnmeasuredCells * this._estimatedCellSize; // return totalSizeOfMeasuredCells + totalSizeOfUnmeasuredCells; }
/** * Total size of all cells being measured. * This value will be completely estimated initially. * As cells are measured, the estimate will be updated. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/cell-size-and-position-manager-row.ts#L199-L208
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
RowCellSizeAndPositionManager.getUpdatedOffsetForIndex
getUpdatedOffsetForIndex({ align = 'auto', containerSize, currentOffset, targetIndex, }: GetUpdatedOffsetForIndex): number { if (containerSize <= 0) { return 0; } const datum = this.getSizeAndPositionOfCell(targetIndex); const minOffset = datum.offset; const maxOffset = datum.offset + datum.size - containerSize; let idealOffset; switch (align) { case 'start': idealOffset = minOffset; break; case 'end': idealOffset = maxOffset; break; case 'center': idealOffset = minOffset + datum.size / 2; break; default: idealOffset = minOffset; break; } const totalSize = this.getTotalSize(); return Math.max(0, Math.min(totalSize - containerSize, idealOffset)); }
/** * Determines a new offset that ensures a certain cell is visible, given the current offset. * If the cell is already visible then the current offset will be returned. * If the current offset is too great or small, it will be adjusted just enough to ensure the specified index is visible. * * @param align Desired alignment within container; one of "auto" (default), "start", or "end" * @param containerSize Size (width or height) of the container viewport * @param currentOffset Container's current (x or y) offset * @param totalSize Total size (width or height) of all cells * @return Offset to use to ensure the specified cell is visible */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/cell-size-and-position-manager-row.ts#L221-L256
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
RowCellSizeAndPositionManager.resetCell
resetCell(index: number): void { this._lastMeasuredIndex = Math.min(this._lastMeasuredIndex, index - 1); }
/** * Clear all cached values for cells after the specified index. * This method should be called for any cell that has changed its size. * It will not immediately perform any calculations; they'll be performed the next time getSizeAndPositionOfCell() is called. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/cell-size-and-position-manager-row.ts#L292-L294
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
RowCellSizeAndPositionManager._findNearestCell
_findNearestCell(offset: number): number { if (isNaN(offset)) { throw Error(`Invalid offset ${offset} specified`); } // Our search algorithms find the nearest match at or below the specified offset. // So make sure the offset is at least 0 or no match will be found. offset = Math.max(0, offset); const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); const lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex); if (lastMeasuredCellSizeAndPosition.offset >= offset) { // If we've already measured cells within this range just use a binary search as it's faster. return this._binarySearch(lastMeasuredIndex, 0, offset); } else { // If we haven't yet measured this high, fallback to an exponential search with an inner binary search. // The exponential search avoids pre-computing sizes for the full set of cells as a binary search would. // The overall complexity for this approach is O(log n). return this._exponentialSearch(lastMeasuredIndex, offset); } }
/** * Searches for the cell (index) nearest the specified offset. * * If no exact match is found the next lowest cell index will be returned. * This allows partially visible cells (with offsets just before/above the fold) to be visible. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/cell-size-and-position-manager-row.ts#L343-L364
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
CellSizeAndPositionManager.getSizeAndPositionOfCell
getSizeAndPositionOfCell(index: number): SizeAndPositionData { if (index < 0 || index >= this._cellCount) { throw Error(`Requested index ${index} is outside of range 0..${this._cellCount}`); } if (index > this._lastMeasuredIndex) { const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); let offset = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size; for (let i = this._lastMeasuredIndex + 1; i <= index; i++) { const size = this._cellSizeGetter({ index: i }); // undefined or NaN probably means a logic error in the size getter. // null means we're using CellMeasurer and haven't yet measured a given index. if (size === undefined || isNaN(size)) { throw Error(`Invalid size returned for cell ${i} of value ${size}`); } else if (size === null) { this._cellSizeAndPositionData[i] = { offset, size: 0, }; this._lastBatchedIndex = index; } else { this._cellSizeAndPositionData[i] = { offset, size, }; offset += size; this._lastMeasuredIndex = index; } } } return this._cellSizeAndPositionData[index]; }
/** * This method returns the size and position for the cell at the specified index. * It just-in-time calculates (or used cached values) for cells leading up to the index. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/cell-size-and-position-manager.ts#L93-L132
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
CellSizeAndPositionManager.getTotalSize
getTotalSize(): number { const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); const totalSizeOfMeasuredCells = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size; const numUnmeasuredCells = this._cellCount - this._lastMeasuredIndex - 1; const totalSizeOfUnmeasuredCells = numUnmeasuredCells * this._estimatedCellSize; return totalSizeOfMeasuredCells + totalSizeOfUnmeasuredCells; }
/** * Total size of all cells being measured. * This value will be completely estimated initially. * As cells are measured, the estimate will be updated. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/cell-size-and-position-manager.ts#L148-L155
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
CellSizeAndPositionManager.getUpdatedOffsetForIndex
getUpdatedOffsetForIndex({ align = 'auto', containerSize, currentOffset, targetIndex, }: GetUpdatedOffsetForIndex): number { if (containerSize <= 0) { return 0; } const datum = this.getSizeAndPositionOfCell(targetIndex); const maxOffset = datum.offset; const minOffset = maxOffset - containerSize + datum.size; let idealOffset; switch (align) { case 'start': idealOffset = maxOffset; break; case 'end': idealOffset = minOffset; break; case 'center': idealOffset = maxOffset - (containerSize - datum.size) / 2; break; default: idealOffset = Math.max(minOffset, Math.min(maxOffset, currentOffset)); break; } const totalSize = this.getTotalSize(); return Math.max(0, Math.min(totalSize - containerSize, idealOffset)); }
/** * Determines a new offset that ensures a certain cell is visible, given the current offset. * If the cell is already visible then the current offset will be returned. * If the current offset is too great or small, it will be adjusted just enough to ensure the specified index is visible. * * @param align Desired alignment within container; one of "auto" (default), "start", or "end" * @param containerSize Size (width or height) of the container viewport * @param currentOffset Container's current (x or y) offset * @param totalSize Total size (width or height) of all cells * @return Offset to use to ensure the specified cell is visible */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/cell-size-and-position-manager.ts#L168-L202
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
CellSizeAndPositionManager.resetCell
resetCell(index: number): void { this._lastMeasuredIndex = Math.min(this._lastMeasuredIndex, index - 1); }
/** * Clear all cached values for cells after the specified index. * This method should be called for any cell that has changed its size. * It will not immediately perform any calculations; they'll be performed the next time getSizeAndPositionOfCell() is called. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/cell-size-and-position-manager.ts#L238-L240
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
CellSizeAndPositionManager._findNearestCell
_findNearestCell(offset: number): number { if (isNaN(offset)) { throw Error(`Invalid offset ${offset} specified`); } // Our search algorithms find the nearest match at or below the specified offset. // So make sure the offset is at least 0 or no match will be found. offset = Math.max(0, offset); const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); const lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex); if (lastMeasuredCellSizeAndPosition.offset >= offset) { // If we've already measured cells within this range just use a binary search as it's faster. return this._binarySearch(lastMeasuredIndex, 0, offset); } else { // If we haven't yet measured this high, fallback to an exponential search with an inner binary search. // The exponential search avoids pre-computing sizes for the full set of cells as a binary search would. // The overall complexity for this approach is O(log n). return this._exponentialSearch(lastMeasuredIndex, offset); } }
/** * Searches for the cell (index) nearest the specified offset. * * If no exact match is found the next lowest cell index will be returned. * This allows partially visible cells (with offsets just before/above the fold) to be visible. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/cell-size-and-position-manager.ts#L287-L308
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
RowScalingCellSizeAndPositionManager.getOffsetAdjustment
getOffsetAdjustment({ containerSize, offset, // safe }: ContainerSizeAndOffset): number { const totalSize = this._cellSizeAndPositionManager.getTotalSize(); const safeTotalSize = this.getTotalSize(); const offsetPercentage = this._getOffsetPercentage({ containerSize, offset, totalSize: safeTotalSize, }); return Math.round(offsetPercentage * (safeTotalSize - totalSize)); }
/** * Number of pixels a cell at the given position (offset) should be shifted in order to fit within the scaled container. * The offset passed to this function is scaled (safe) as well. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/scaling-cell-size-and-position-manager-row.ts#L74-L87
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
RowScalingCellSizeAndPositionManager.getTotalSize
getTotalSize(): number { return Math.min( this._maxScrollSize, this._cellSizeAndPositionManager.getTotalSize(), ); }
/** See CellSizeAndPositionManager#getTotalSize */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/scaling-cell-size-and-position-manager-row.ts#L98-L103
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
RowScalingCellSizeAndPositionManager.getUpdatedOffsetForIndex
getUpdatedOffsetForIndex({ align = 'auto', containerSize, currentOffset, // safe targetIndex, }: { align: Alignment; containerSize: number; currentOffset: number; targetIndex: number; }) { currentOffset = this._safeOffsetToOffset({ containerSize, offset: currentOffset, }); const offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex({ align, containerSize, currentOffset, targetIndex, }); return this._offsetToSafeOffset({ containerSize, offset, }); }
/** See CellSizeAndPositionManager#getUpdatedOffsetForIndex */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/scaling-cell-size-and-position-manager-row.ts#L106-L133
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
RowScalingCellSizeAndPositionManager.getVisibleCellRange
getVisibleCellRange({ containerSize, offset, // safe }: ContainerSizeAndOffset): VisibleCellRange { offset = this._safeOffsetToOffset({ containerSize, offset, }); return this._cellSizeAndPositionManager.getVisibleCellRange({ containerSize, offset, }); }
/** See CellSizeAndPositionManager#getVisibleCellRange */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/scaling-cell-size-and-position-manager-row.ts#L136-L149
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
ScalingCellSizeAndPositionManager.getOffsetAdjustment
getOffsetAdjustment({ containerSize, offset, // safe }: ContainerSizeAndOffset): number { const totalSize = this._cellSizeAndPositionManager.getTotalSize(); const safeTotalSize = this.getTotalSize(); const offsetPercentage = this._getOffsetPercentage({ containerSize, offset, totalSize: safeTotalSize, }); return Math.round(offsetPercentage * (safeTotalSize - totalSize)); }
/** * Number of pixels a cell at the given position (offset) should be shifted in order to fit within the scaled container. * The offset passed to this function is scaled (safe) as well. */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/scaling-cell-size-and-position-manager.ts#L66-L79
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
ScalingCellSizeAndPositionManager.getTotalSize
getTotalSize(): number { return Math.min( this._maxScrollSize, this._cellSizeAndPositionManager.getTotalSize(), ); }
/** See CellSizeAndPositionManager#getTotalSize */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/scaling-cell-size-and-position-manager.ts#L90-L95
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
ScalingCellSizeAndPositionManager.getUpdatedOffsetForIndex
getUpdatedOffsetForIndex({ align = 'auto', containerSize, currentOffset, // safe targetIndex, }: { align: Alignment; containerSize: number; currentOffset: number; targetIndex: number; }) { currentOffset = this._safeOffsetToOffset({ containerSize, offset: currentOffset, }); const offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex({ align, containerSize, currentOffset, targetIndex, }); return this._offsetToSafeOffset({ containerSize, offset, }); }
/** See CellSizeAndPositionManager#getUpdatedOffsetForIndex */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/scaling-cell-size-and-position-manager.ts#L98-L125
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
ScalingCellSizeAndPositionManager.getVisibleCellRange
getVisibleCellRange({ containerSize, offset, // safe }: ContainerSizeAndOffset): VisibleCellRange { offset = this._safeOffsetToOffset({ containerSize, offset, }); return this._cellSizeAndPositionManager.getVisibleCellRange({ containerSize, offset, }); }
/** See CellSizeAndPositionManager#getVisibleCellRange */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/grid/utils/scaling-cell-size-and-position-manager.ts#L128-L141
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
List.getOffsetForRow
getOffsetForRow({ alignment, index }: { alignment: Alignment; index: number }) { if (this.Grid) { const { scrollTop } = this.Grid.getOffsetForCell({ alignment, rowIndex: index, columnIndex: 0, }); return scrollTop; } return 0; }
/** See Grid#getOffsetForCell */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/list/list.tsx#L136-L147
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
List.invalidateCellSizeAfterRender
invalidateCellSizeAfterRender({ columnIndex, rowIndex }: CellPosition) { if (this.Grid) { this.Grid.invalidateCellSizeAfterRender({ rowIndex, columnIndex, }); } }
/** CellMeasurer compatibility */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/list/list.tsx#L150-L157
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
List.measureAllRows
measureAllRows() { if (this.Grid) { this.Grid.measureAllCells(); } }
/** See Grid#measureAllCells */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/list/list.tsx#L160-L164
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
List.recomputeGridSize
recomputeGridSize( { columnIndex = 0, rowIndex = 0 }: CellPosition = { columnIndex: 0, rowIndex: 0 }, ) { if (this.Grid) { this.Grid.recomputeGridSize({ rowIndex, columnIndex, }); } }
/** CellMeasurer compatibility */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/list/list.tsx#L167-L176
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
List.recomputeRowHeights
recomputeRowHeights(index = 0) { if (this.Grid) { this.Grid.recomputeGridSize({ rowIndex: index, columnIndex: 0, }); } }
/** See Grid#recomputeGridSize */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/list/list.tsx#L179-L186
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
List.scrollToPosition
scrollToPosition(scrollTop = 0) { if (this.Grid) { this.Grid.scrollToPosition({ scrollTop }); } }
/** See Grid#scrollToPosition */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/list/list.tsx#L198-L202
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
List.scrollToRow
scrollToRow(index = 0) { if (this.Grid) { this.Grid.scrollToCell({ columnIndex: 0, rowIndex: index, }); } }
/** See Grid#scrollToCell */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/list/list.tsx#L205-L212
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
_GEA
function _GEA(a, l, h, y) { let i = h + 1; while (l <= h) { const m = (l + h) >>> 1, x = a[m]; if (x >= y) { i = m; h = m - 1; } else { l = m + 1; } } return i; }
/* eslint-disable @typescript-eslint/ban-ts-comment */
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/vendor/binary-search-bounds.ts#L14-L27
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
libro
github_2023
weavefox
typescript
IntervalTree
function IntervalTree(root) { this.root = root; }
//User friendly wrapper that makes it possible to support empty trees
https://github.com/weavefox/libro/blob/371f9fa4903254d60ed3142e335dbf3f6d8d03e4/packages/libro-virtualized/src/vendor/interval-tree.ts#L346-L348
371f9fa4903254d60ed3142e335dbf3f6d8d03e4
flappy
github_2023
pleisto
typescript
lanOutputSchema
const lanOutputSchema = (enableCoT: boolean) => { const baseStep = { id: z.number().int().positive().describe('Increment id starting from 1'), functionName: z.string(), args: z .record(z.any()) .describe( `an object encapsulating all arguments for a function call. If an argument's value is derived from the return of a previous step, it should be as '${STEP_PREFIX}' + the ID of the previous step (e.g. '${STEP_PREFIX}1'). If an argument's value is derived from the **previous** step's function's return value's properties, '.' should be used to access its properties, else just use id with prefix. This approach should remain compatible with the 'args' attribute in the function's JSON schema.` ) } const thought = enableCoT ? { thought: z.string().describe('The thought why this step is needed.') } : ({} as any) return z .array( z.object({ ...thought, ...baseStep }) ) .describe('An array storing the steps.') }
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
https://github.com/pleisto/flappy/blob/cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f/packages/nodejs/src/flappy-agent.ts#L12-L35
cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f
flappy
github_2023
pleisto
typescript
FlappyAgent.featuresDefinitions
public featuresDefinitions(): object[] { return this.config.features.map((fn: AnyFlappyFeature) => fn.callingSchema) }
/** * Get function definitions as a JSON Schema object array. */
https://github.com/pleisto/flappy/blob/cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f/packages/nodejs/src/flappy-agent.ts#L58-L60
cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f
flappy
github_2023
pleisto
typescript
FlappyAgent.findFeature
public findFeature<TName extends TNames, TFunction extends AnyFlappyFeature = FindFlappyFeature<TFeatures, TName>>( name: TName ): TFunction { const fn = this.config.features.find((fn: AnyFlappyFeature) => fn.define.name === name) if (!fn) throw new Error(`Function definition not found: ${name}`) return fn as TFunction }
/** * Find function by name. */
https://github.com/pleisto/flappy/blob/cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f/packages/nodejs/src/flappy-agent.ts#L65-L71
cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f