Always clear unused attachments when updating cell source (#17840)

* Always clear unused attachments when updating cell source

* comment

* Fix eslint and improve regex

* Add more tests
This commit is contained in:
Charles Gagnon
2021-12-07 18:28:15 -08:00
committed by GitHub
parent 1651f3f8bc
commit 321a5b8a69
3 changed files with 108 additions and 2 deletions

View File

@@ -307,6 +307,7 @@ export class CellModel extends Disposable implements ICellModel {
}
public set source(newSource: string | string[]) {
this.cleanUnusedAttachments(Array.isArray(newSource) ? newSource.join() : newSource);
newSource = this.attachImageFromSource(newSource);
newSource = this.getMultilineSource(newSource);
if (this._source !== newSource) {
@@ -329,6 +330,22 @@ export class CellModel extends Disposable implements ICellModel {
}
return newSource;
}
/**
* Cleans up the attachments, removing any ones that aren't being currently used in the specified source string.
* @param source The new source string to check for attachments being used
*/
private cleanUnusedAttachments(source: string): void {
const originalAttachments = this._attachments;
this._attachments = {};
// Find existing attachments in the form ![...](attachment:...) so that we can make sure we keep those attachments
const attachmentRegex = /!\[.*?\]\(attachment:(.*?)\)/g;
let match;
while (match = attachmentRegex.exec(source)) { // eslint-disable-line no-cond-assign
this._attachments[match[1]] = originalAttachments[match[1]];
}
}
/**
* Gets unique attachment name to add to cell metadata
* @param imgName a string defining name of the image.