recital / core / src / tools / at-shorthand.ts
at-shorthand.ts
Raw
/**
 * Copyright (c) 2022 Amorphous
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

import { ObjectMeta } from '../types'

export const separateAtShorthand = (string: string): ObjectMeta => {
	if (!string.startsWith('@')) {
		throw new Error('@ shorthand must begin with an @ symbol')
	}
	const stringWithoutPrefix = string.slice(1)
	const divElements = stringWithoutPrefix.split('.')

	const div: ObjectMeta = {
		classes: [],
	}

	for (let str of divElements) {
		if (str.startsWith('#')) {
			div.id = str.slice(1)

			continue
		}

		if (!div.classes) {
			div.classes = []
		}
		div.classes.push(str)
	}

	return div
}