diff --git a/src/edge/stacks.ts b/src/edge/stacks.ts index 0ea4253..3b1f381 100644 --- a/src/edge/stacks.ts +++ b/src/edge/stacks.ts @@ -73,6 +73,30 @@ export default class Stacks { return this } + /** + * Push content to the top inside a given stack. + * Content can be pre-seeded without creating a stack + */ + pushToTop(name: string, contents: string) { + let placeholder = this.#placeholders.get(name) + + if (!placeholder) { + if (!this.#seededPlaceholders.has(name)) { + this.#seededPlaceholders.set(name, []) + } + const seededPlaceholder = this.#seededPlaceholders.get(name)! + seededPlaceholder.unshift(contents) + return this + } + + /** + * Defined content for the unique key inside a given + * stack + */ + placeholder.unshift(contents) + return this + } + /** * Push contents to a stack with a unique source id. A * source can only push once to a given stack. @@ -95,6 +119,28 @@ export default class Stacks { } } + /** + * Push contents to the top of a stack with a unique source id. + * A source can only push once to a given stack. + */ + pushOnceToTop(name: string, sourceId: string, contents: string) { + const contentSources = this.#contentSources.get(name) + if (contentSources && contentSources.has(sourceId)) { + return + } + + this.pushToTop(name, contents) + + /** + * Track source + */ + if (contentSources) { + contentSources.add(sourceId) + } else { + this.#contentSources.set(name, new Set([sourceId])) + } + } + /** * Fill placeholders with their actual content */ diff --git a/tests/stacks.spec.ts b/tests/stacks.spec.ts index 261c662..d018652 100644 --- a/tests/stacks.spec.ts +++ b/tests/stacks.spec.ts @@ -58,4 +58,43 @@ test.group('Stacks', () => { assert.equal(stacks.fillPlaceholders(contents), `hello world${EOL}hi world`) }) + + test('push contents to the top of a stack', ({ assert }) => { + const stacks = new Stacks() + + const contents = stacks.create('js') + stacks.pushToTop('js', 'hello world') + + assert.equal(stacks.fillPlaceholders(contents), 'hello world') + }) + + test('push contents to the top of a stack that was already pushed to', ({ assert }) => { + const stacks = new Stacks() + + const contents = stacks.create('js') + stacks.pushTo('js', 'world') + stacks.pushToTop('js', 'hello') + + assert.equal(stacks.fillPlaceholders(contents), 'hello\nworld') + }) + + test('push contents multiple times to stack', ({ assert }) => { + const stacks = new Stacks() + + const contents = stacks.create('js') + stacks.pushToTop('js', 'world') + stacks.pushToTop('js', 'hello') + + assert.equal(stacks.fillPlaceholders(contents), `hello\nworld`) + }) + + test('push contents to the top before creating the stack', ({ assert }) => { + const stacks = new Stacks() + + stacks.pushToTop('js', 'hello world') + stacks.pushToTop('js', 'hi world') + const contents = stacks.create('js') + + assert.equal(stacks.fillPlaceholders(contents), `hi world${EOL}hello world`) + }) })