diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..58a4dbe Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c6bba59 --- /dev/null +++ b/.gitignore @@ -0,0 +1,130 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# vuepress v2.x temp and cache directory +.temp +.cache + +# Docusaurus cache and generated files +.docusaurus + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* diff --git a/README.md b/README.md new file mode 100644 index 0000000..ad0d3a0 --- /dev/null +++ b/README.md @@ -0,0 +1,386 @@ +# notion-helper + +This is a little library of functions I use to work more easily with the Notion API. + +It's mainly built to help you create pages and blocks without writing so many nested objects and arrays by hand. + +All functions and methods have [JSDoc](https://jsdoc.app/) markup to support IntelliSense. + +## Installation + +This package is [ESM-only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). + +Install via [npm](https://docs.npmjs.com/cli/v10/commands/npm-install): + +``` +npm install notion-helper +``` + +## Usage + +Import the package: + +```js +import NotionHelper from "notion-helper"; +``` + +From here, you can destructure the functions to use them directly, or just call NotionHelper. + +```js +const { makeParagraphBlocks } = NotionHelper; + +const quotes = [ + "Dear frozen yogurt, you are the celery of desserts. Be ice cream, or be nothing.", + "Give me all the bacon and eggs you have.", + "There is no quiet anymore. There is only Doc McStuffins.", +]; + +const paragraphBlocks = makeParagraphBlocks(quotes); + +// or... + +const paragraphBlocks = NotionHelper.makeParagraphBlocks(quotes); +``` + +Notion Helper currently contains four direct functions you can use: + +- `quickPages()` - lets you easily create valid page objects with property values and child blocks using very simple JSON objects. This is the highest-level function in the library – you can see its documentation below. +- `makeParagraphBlocks()` - takes an array of strings and returns an array of [Paragraph blocks](https://developers.notion.com/reference/block#paragraph) without any special formatting or links. Provides a very quick way to prep a lot of text for sending to Notion. +- `buildRichTextObj()` - takes a string, options array, and URL and creates a [Rich Text Object](https://developers.notion.com/reference/rich-text) array (use [flatMap()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) if you're inserting its output into another array). Splits strings over the [character limit](https://developers.notion.com/reference/request-limits#limits-for-property-values) for you as well. _Currently only works for text objects; mentions and equations aren't supported yet._. +- `setIcon()` - takes a string, which should be a single emoji (🌡) or an image URL and returns the correct object (emoji or external) value for an `icon` property. + +### Using `quickPages()` + +Often you'll have an array of relatively simple data that you want to turn into Notion pages: + +```js +const tasks = [ + { + icon: "πŸ”¨", + task: "Build Standing Desk", + due: "2024-09-10", + status: "Not started", + }, + { + task: "Mount Overhead Lights", + due: "2024-09-11", + status: "Not started", + children: [ + "Mount clamp to joist and tighten", + "Attach arm to clamp", + "Mount video light to arm", + "Run power cable through ceiling panels" + ], + }, + { task: "Set Up Camera", due: "2024-09-11", status: "Not started" }, +]; +``` + +Say you want to create a page in a Tasks database for each of these, setting the relevant properties and creating a list of To-Do blocks in the page body for any that have a `children` array. + +
+The Notion API requires a much more verbose page data object for each of these: + +```js +[ + { + parent: { type: 'database_id', database_id: 'abcdefghijklmnopqrstuvwxyz' }, + icon: { type: 'emoji', emoji: 'πŸ”¨' }, + properties: { + Name: { + title: [ + { + type: 'text', + text: { content: 'Build Standing Desk' }, + annotations: {} + } + ] + }, + 'Due Date': { date: { start: '2024-09-10', end: null } }, + Status: { status: { name: 'Not started' } } + } + }, + { + parent: { type: 'database_id', database_id: 'abcdefghijklmnopqrstuvwxyz' }, + properties: { + Name: { + title: [ + { + type: 'text', + text: { content: 'Mount Overhead Lights' }, + annotations: {} + } + ] + }, + 'Due Date': { date: { start: '2024-09-11', end: null } }, + Status: { status: { name: 'Not started' } } + }, + children: [ + { + type: 'to_do', + to_do: { + rich_text: [ + { + type: 'text', + text: { content: 'Mount clamp to joist and tighten' }, + annotations: {} + } + ], + checked: false, + color: 'default', + children: [] + } + }, + { + type: 'to_do', + to_do: { + rich_text: [ + { + type: 'text', + text: { content: 'Attach arm to clamp' }, + annotations: {} + } + ], + checked: false, + color: 'default', + children: [] + } + }, + { + type: 'to_do', + to_do: { + rich_text: [ + { + type: 'text', + text: { content: 'Mount video light to arm' }, + annotations: {} + } + ], + checked: false, + color: 'default', + children: [] + } + }, + { + type: 'to_do', + to_do: { + rich_text: [ + { + type: 'text', + text: { content: 'Run power cable through ceiling panels' }, + annotations: {} + } + ], + checked: false, + color: 'default', + children: [] + } + } + ] + }, + { + parent: { type: 'database_id', database_id: 'abcdefghijklmnopqrstuvwxyz' }, + properties: { + Name: { + title: [ + { + type: 'text', + text: { content: 'Set Up Camera' }, + annotations: {} + } + ] + }, + 'Due Date': { date: { start: '2024-09-11', end: null } }, + Status: { status: { name: 'Not started' } } + } + } +] +``` +
+ +Using `quickPages()`, you can create an array of valid page objects like the one in the toggle above. + +With it, you can pass an options object with: + +- `parent`: A parent page/database +- `parent_type`: The parent's type ("page_id" or "database_id") +- `pages`: Your array of objects +- `schema`: A schema describing how your object's properties map to Notion property names and types +- `childrenFn`: An optional callback that will be excuted on all array elements in any object's `children` property, creating a `children` array within the Notion page object + +> [!TIP] +> You can also pass a single object, but you'll still get an array back. + +The schema object should contain a property for each property in the Notion database you'd like to edit. For each, the key should map to a key present in at least one of your objects, and its value should be an array containing the matching Notion database property's name and type. + +Valid property types include all those listed in the `page_props` section below. + +> [!NOTE] +> If the `parent` has the type `page_id` (i.e. it's a page, not a database), the only valid value will be `["title", "title"]`, which represent's the page's title. + +Here's an example of simple usage, operating on the `tasks` array shown above: + +```js +const propertySchema = { + task: ["Name", "title"], + due: ["Due Date", "date"], + status: ["Status", "status"], +} + +const pages = quickPages({ + parent: database_id, + parent_type: "database_id", + pages: tasks, + schema: propertySchema, +}) + +/* Create a page for each returned page object */ +const responses = await Promise.all( + pages.map((page) => notion.pages.create(page)) +) +``` + +Optionally, your schema can also include custom properties that represent the icon, cover, and children. If you want to specify these, use the convention below to tell the function which properties correspond to the `icon`, `cover`, and `children` properties. + +By default, the function will look for `icon`, `cover`, and `children` in your pages object, so you don't need to specify those keys in your schema if they're named that way. + +```js +const schema = [ + favicon: ["Icon", "icon"], + bg_image: ["Cover", "cover"], + body: ["Children", "children"] +] +``` + +By default, if you have a string or an array of strings in any object's `children` property, those strings will be turned into [Paragraph](https://developers.notion.com/reference/block#paragraph) blocks. + +However, you can use the `childrenFn` parameter to pass a callback function. All array elements in each object's `children` property (if present) will be run through this callback. `childrenFn` should take in an array as its argument and return an array. The returned array will be used directly as the `children` array in the final page object. + +In the example below, `childrenFn` is used to create a [To-Do](https://developers.notion.com/reference/block#to-do) block for each children item: + +```js +const pages = quickPages({ + parent: database_id, + parent_type: "database_id", + pages: tasks, + schema: propertySchema, + childrenFn: (value) => value.map((line) => NotionHelper.block.to_do.createBlock({rtArray: NotionHelper.buildRichTextObj(line)})) +}) +``` + +Note how other Notion Helper functions are used in this example callback to easily construct the To-Do blocks. + +If an object's `children` property already contains an array of prepared Block objects, simply make it the return value of `childrenFn`. Otherwise, `quickPages()` will treat it as invalid children content and strip it out. Without a `childrenFn`, `quickPages()` will only automatically process a string or array of strings in a `children` property. + +```js +const pages = quickPages({ + parent: database_id, + parent_type: "database_id", + pages: tasks, + schema: propertySchema, + childrenFn: (value) => value +}) +``` + +This library also provides objects with methods for quickly creating pages and blocks: + +### `block` + +The `block` object lets you create most supported block types while writing less code. It supports these block types: + +- Bookmark +- Bulleted List Item +- Callout +- Code +- Divider +- Embed +- File +- Heading 1 +- Heading 2 +- Heading 3 +- Image +- Numbered List Item +- Paragraph +- PDF +- Quote +- Table +- Table Row +- Table of Contents +- To-Do +- Toggle +- Video + +_Some block types will return a `null` if they are provided with invalid input. You should filter `null` entries out of your `children` array before adding it to an API call._ + +Each block type has a createBlock() method you can call, which takes an object containing properties specific to that block type. Most take an `rtArray`, which is an array of Rich Text objects you can easily create with `builtRichTextObj()`. + +Examples: + +```js +const headerText = "How to Play Guitar with Your Teeth"; + +const heading1 = NotionHelper.block.heading_1.createBlock({ + rtArray: buildRichTextObj(headerText), +}); +``` + +### `page_meta` + +The `page_meta` object lets you quickly set the parent, icon, and cover for a page. Pages can be standalone or within a database. + +The `parent` property's `createMeta()` method takes an object containing the parent page ID and type, while the `icon` and `cover` properties require only a string representing an externally-hosted image file (or single emoji 🀠 in the case of `icon`). + +```js +const page = { + parent: NotionHelper.page_meta.parent.createMeta({ + id: parentID, + type: "database", + }), + icon: NotionHelper.page_meta.icon.createMeta("πŸŽƒ"), + cover: NotionHelper.page_meta.cover.createMeta( + "https://i.imgur.com/5vSShIw.jpeg" + ), +}; +``` + +### `page_props` + +The `page_props` object lets you quickly set the property values of a Notion page. Pages can be standalone or in a database, though standalone pages can only have a `title` property. + +Each property represents a database property type. All **writeable** properties are supported: + +- Title +- Rich Text +- Checkbox +- Date +- Email +- Files +- Multi-Select +- Number +- People +- Phone Number +- Relation +- Select +- Status +- URL + +Each property's `setProp()` takes an argument as specified by the [Page Properties](https://developers.notion.com/reference/page-property-values) specification of the Notion API. (E.g. Checkbox props take a `boolean`, Rich Text props take an array of Rich Text objects, Date props take an [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) date-time string, etc.) + +```js + +const page = { + /* parent, icon, cover */ + properties: { + Name: NotionHelper.page_props.title.setProp(buildRichTextObj("Flylighter - Notion Web Clipper")), + Capture Date: NotionHelper.page_props.date.setProp(new Date().toISOString()) + URL: NotionHelper.page_props.url.setProp("https://flylighter.com/") + } +} + +``` + +## Learn More + +If you'd like to learn the Notion API from scratch, start with my free [Notion API crash course](https://thomasjfrank.com/notion-api-crash-course/). + +Questions? [Ask me on Twitter!](https://twitter.com/TomFrankly) diff --git a/assets/anchor.js b/assets/anchor.js new file mode 100644 index 0000000..1f573dc --- /dev/null +++ b/assets/anchor.js @@ -0,0 +1,350 @@ +/*! + * AnchorJS - v4.0.0 - 2017-06-02 + * https://github.com/bryanbraun/anchorjs + * Copyright (c) 2017 Bryan Braun; Licensed MIT + */ +/* eslint-env amd, node */ + +// https://github.com/umdjs/umd/blob/master/templates/returnExports.js +(function (root, factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([], factory); + } else if (typeof module === 'object' && module.exports) { + // Node. Does not work with strict CommonJS, but + // only CommonJS-like environments that support module.exports, + // like Node. + module.exports = factory(); + } else { + // Browser globals (root is window) + root.AnchorJS = factory(); + root.anchors = new root.AnchorJS(); + } +})(this, function () { + 'use strict'; + function AnchorJS(options) { + this.options = options || {}; + this.elements = []; + + /** + * Assigns options to the internal options object, and provides defaults. + * @param {Object} opts - Options object + */ + function _applyRemainingDefaultOptions(opts) { + opts.icon = opts.hasOwnProperty('icon') ? opts.icon : '\ue9cb'; // Accepts characters (and also URLs?), like '#', 'ΒΆ', '❑', or 'Β§'. + opts.visible = opts.hasOwnProperty('visible') ? opts.visible : 'hover'; // Also accepts 'always' & 'touch' + opts.placement = opts.hasOwnProperty('placement') + ? opts.placement + : 'right'; // Also accepts 'left' + opts.class = opts.hasOwnProperty('class') ? opts.class : ''; // Accepts any class name. + // Using Math.floor here will ensure the value is Number-cast and an integer. + opts.truncate = opts.hasOwnProperty('truncate') + ? Math.floor(opts.truncate) + : 64; // Accepts any value that can be typecast to a number. + } + + _applyRemainingDefaultOptions(this.options); + + /** + * Checks to see if this device supports touch. Uses criteria pulled from Modernizr: + * https://github.com/Modernizr/Modernizr/blob/da22eb27631fc4957f67607fe6042e85c0a84656/feature-detects/touchevents.js#L40 + * @returns {Boolean} - true if the current device supports touch. + */ + this.isTouchDevice = function () { + return !!( + 'ontouchstart' in window || + (window.DocumentTouch && document instanceof DocumentTouch) + ); + }; + + /** + * Add anchor links to page elements. + * @param {String|Array|Nodelist} selector - A CSS selector for targeting the elements you wish to add anchor links + * to. Also accepts an array or nodeList containing the relavant elements. + * @returns {this} - The AnchorJS object + */ + this.add = function (selector) { + var elements, + elsWithIds, + idList, + elementID, + i, + index, + count, + tidyText, + newTidyText, + readableID, + anchor, + visibleOptionToUse, + indexesToDrop = []; + + // We reapply options here because somebody may have overwritten the default options object when setting options. + // For example, this overwrites all options but visible: + // + // anchors.options = { visible: 'always'; } + _applyRemainingDefaultOptions(this.options); + + visibleOptionToUse = this.options.visible; + if (visibleOptionToUse === 'touch') { + visibleOptionToUse = this.isTouchDevice() ? 'always' : 'hover'; + } + + // Provide a sensible default selector, if none is given. + if (!selector) { + selector = 'h2, h3, h4, h5, h6'; + } + + elements = _getElements(selector); + + if (elements.length === 0) { + return this; + } + + _addBaselineStyles(); + + // We produce a list of existing IDs so we don't generate a duplicate. + elsWithIds = document.querySelectorAll('[id]'); + idList = [].map.call(elsWithIds, function assign(el) { + return el.id; + }); + + for (i = 0; i < elements.length; i++) { + if (this.hasAnchorJSLink(elements[i])) { + indexesToDrop.push(i); + continue; + } + + if (elements[i].hasAttribute('id')) { + elementID = elements[i].getAttribute('id'); + } else if (elements[i].hasAttribute('data-anchor-id')) { + elementID = elements[i].getAttribute('data-anchor-id'); + } else { + tidyText = this.urlify(elements[i].textContent); + + // Compare our generated ID to existing IDs (and increment it if needed) + // before we add it to the page. + newTidyText = tidyText; + count = 0; + do { + if (index !== undefined) { + newTidyText = tidyText + '-' + count; + } + + index = idList.indexOf(newTidyText); + count += 1; + } while (index !== -1); + index = undefined; + idList.push(newTidyText); + + elements[i].setAttribute('id', newTidyText); + elementID = newTidyText; + } + + readableID = elementID.replace(/-/g, ' '); + + // The following code builds the following DOM structure in a more effiecient (albeit opaque) way. + // ''; + anchor = document.createElement('a'); + anchor.className = 'anchorjs-link ' + this.options.class; + anchor.href = '#' + elementID; + anchor.setAttribute('aria-label', 'Anchor link for: ' + readableID); + anchor.setAttribute('data-anchorjs-icon', this.options.icon); + + if (visibleOptionToUse === 'always') { + anchor.style.opacity = '1'; + } + + if (this.options.icon === '\ue9cb') { + anchor.style.font = '1em/1 anchorjs-icons'; + + // We set lineHeight = 1 here because the `anchorjs-icons` font family could otherwise affect the + // height of the heading. This isn't the case for icons with `placement: left`, so we restore + // line-height: inherit in that case, ensuring they remain positioned correctly. For more info, + // see https://github.com/bryanbraun/anchorjs/issues/39. + if (this.options.placement === 'left') { + anchor.style.lineHeight = 'inherit'; + } + } + + if (this.options.placement === 'left') { + anchor.style.position = 'absolute'; + anchor.style.marginLeft = '-1em'; + anchor.style.paddingRight = '0.5em'; + elements[i].insertBefore(anchor, elements[i].firstChild); + } else { + // if the option provided is `right` (or anything else). + anchor.style.paddingLeft = '0.375em'; + elements[i].appendChild(anchor); + } + } + + for (i = 0; i < indexesToDrop.length; i++) { + elements.splice(indexesToDrop[i] - i, 1); + } + this.elements = this.elements.concat(elements); + + return this; + }; + + /** + * Removes all anchorjs-links from elements targed by the selector. + * @param {String|Array|Nodelist} selector - A CSS selector string targeting elements with anchor links, + * OR a nodeList / array containing the DOM elements. + * @returns {this} - The AnchorJS object + */ + this.remove = function (selector) { + var index, + domAnchor, + elements = _getElements(selector); + + for (var i = 0; i < elements.length; i++) { + domAnchor = elements[i].querySelector('.anchorjs-link'); + if (domAnchor) { + // Drop the element from our main list, if it's in there. + index = this.elements.indexOf(elements[i]); + if (index !== -1) { + this.elements.splice(index, 1); + } + // Remove the anchor from the DOM. + elements[i].removeChild(domAnchor); + } + } + return this; + }; + + /** + * Removes all anchorjs links. Mostly used for tests. + */ + this.removeAll = function () { + this.remove(this.elements); + }; + + /** + * Urlify - Refine text so it makes a good ID. + * + * To do this, we remove apostrophes, replace nonsafe characters with hyphens, + * remove extra hyphens, truncate, trim hyphens, and make lowercase. + * + * @param {String} text - Any text. Usually pulled from the webpage element we are linking to. + * @returns {String} - hyphen-delimited text for use in IDs and URLs. + */ + this.urlify = function (text) { + // Regex for finding the nonsafe URL characters (many need escaping): & +$,:;=?@"#{}|^~[`%!'<>]./()*\ + var nonsafeChars = /[& +$,:;=?@"#{}|^~[`%!'<>\]\.\/\(\)\*\\]/g, + urlText; + + // The reason we include this _applyRemainingDefaultOptions is so urlify can be called independently, + // even after setting options. This can be useful for tests or other applications. + if (!this.options.truncate) { + _applyRemainingDefaultOptions(this.options); + } + + // Note: we trim hyphens after truncating because truncating can cause dangling hyphens. + // Example string: // " ⚑⚑ Don't forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." + urlText = text + .trim() // "⚑⚑ Don't forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." + .replace(/\'/gi, '') // "⚑⚑ Dont forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." + .replace(nonsafeChars, '-') // "⚑⚑-Dont-forget--URL-fragments-should-be-i18n-friendly--hyphenated--short--and-clean-" + .replace(/-{2,}/g, '-') // "⚑⚑-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated-short-and-clean-" + .substring(0, this.options.truncate) // "⚑⚑-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated-" + .replace(/^-+|-+$/gm, '') // "⚑⚑-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated" + .toLowerCase(); // "⚑⚑-dont-forget-url-fragments-should-be-i18n-friendly-hyphenated" + + return urlText; + }; + + /** + * Determines if this element already has an AnchorJS link on it. + * Uses this technique: http://stackoverflow.com/a/5898748/1154642 + * @param {HTMLElemnt} el - a DOM node + * @returns {Boolean} true/false + */ + this.hasAnchorJSLink = function (el) { + var hasLeftAnchor = + el.firstChild && + (' ' + el.firstChild.className + ' ').indexOf(' anchorjs-link ') > -1, + hasRightAnchor = + el.lastChild && + (' ' + el.lastChild.className + ' ').indexOf(' anchorjs-link ') > -1; + + return hasLeftAnchor || hasRightAnchor || false; + }; + + /** + * Turns a selector, nodeList, or array of elements into an array of elements (so we can use array methods). + * It also throws errors on any other inputs. Used to handle inputs to .add and .remove. + * @param {String|Array|Nodelist} input - A CSS selector string targeting elements with anchor links, + * OR a nodeList / array containing the DOM elements. + * @returns {Array} - An array containing the elements we want. + */ + function _getElements(input) { + var elements; + if (typeof input === 'string' || input instanceof String) { + // See https://davidwalsh.name/nodelist-array for the technique transforming nodeList -> Array. + elements = [].slice.call(document.querySelectorAll(input)); + // I checked the 'input instanceof NodeList' test in IE9 and modern browsers and it worked for me. + } else if (Array.isArray(input) || input instanceof NodeList) { + elements = [].slice.call(input); + } else { + throw new Error('The selector provided to AnchorJS was invalid.'); + } + return elements; + } + + /** + * _addBaselineStyles + * Adds baseline styles to the page, used by all AnchorJS links irregardless of configuration. + */ + function _addBaselineStyles() { + // We don't want to add global baseline styles if they've been added before. + if (document.head.querySelector('style.anchorjs') !== null) { + return; + } + + var style = document.createElement('style'), + linkRule = + ' .anchorjs-link {' + + ' opacity: 0;' + + ' text-decoration: none;' + + ' -webkit-font-smoothing: antialiased;' + + ' -moz-osx-font-smoothing: grayscale;' + + ' }', + hoverRule = + ' *:hover > .anchorjs-link,' + + ' .anchorjs-link:focus {' + + ' opacity: 1;' + + ' }', + anchorjsLinkFontFace = + ' @font-face {' + + ' font-family: "anchorjs-icons";' + // Icon from icomoon; 10px wide & 10px tall; 2 empty below & 4 above + ' src: url(data:n/a;base64,AAEAAAALAIAAAwAwT1MvMg8yG2cAAAE4AAAAYGNtYXDp3gC3AAABpAAAAExnYXNwAAAAEAAAA9wAAAAIZ2x5ZlQCcfwAAAH4AAABCGhlYWQHFvHyAAAAvAAAADZoaGVhBnACFwAAAPQAAAAkaG10eASAADEAAAGYAAAADGxvY2EACACEAAAB8AAAAAhtYXhwAAYAVwAAARgAAAAgbmFtZQGOH9cAAAMAAAAAunBvc3QAAwAAAAADvAAAACAAAQAAAAEAAHzE2p9fDzz1AAkEAAAAAADRecUWAAAAANQA6R8AAAAAAoACwAAAAAgAAgAAAAAAAAABAAADwP/AAAACgAAA/9MCrQABAAAAAAAAAAAAAAAAAAAAAwABAAAAAwBVAAIAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAMCQAGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAg//0DwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAAIAAAACgAAxAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEADAAAAAIAAgAAgAAACDpy//9//8AAAAg6cv//f///+EWNwADAAEAAAAAAAAAAAAAAAAACACEAAEAAAAAAAAAAAAAAAAxAAACAAQARAKAAsAAKwBUAAABIiYnJjQ3NzY2MzIWFxYUBwcGIicmNDc3NjQnJiYjIgYHBwYUFxYUBwYGIwciJicmNDc3NjIXFhQHBwYUFxYWMzI2Nzc2NCcmNDc2MhcWFAcHBgYjARQGDAUtLXoWOR8fORYtLTgKGwoKCjgaGg0gEhIgDXoaGgkJBQwHdR85Fi0tOAobCgoKOBoaDSASEiANehoaCQkKGwotLXoWOR8BMwUFLYEuehYXFxYugC44CQkKGwo4GkoaDQ0NDXoaShoKGwoFBe8XFi6ALjgJCQobCjgaShoNDQ0NehpKGgobCgoKLYEuehYXAAAADACWAAEAAAAAAAEACAAAAAEAAAAAAAIAAwAIAAEAAAAAAAMACAAAAAEAAAAAAAQACAAAAAEAAAAAAAUAAQALAAEAAAAAAAYACAAAAAMAAQQJAAEAEAAMAAMAAQQJAAIABgAcAAMAAQQJAAMAEAAMAAMAAQQJAAQAEAAMAAMAAQQJAAUAAgAiAAMAAQQJAAYAEAAMYW5jaG9yanM0MDBAAGEAbgBjAGgAbwByAGoAcwA0ADAAMABAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAP) format("truetype");' + + ' }', + pseudoElContent = + ' [data-anchorjs-icon]::after {' + + ' content: attr(data-anchorjs-icon);' + + ' }', + firstStyleEl; + + style.className = 'anchorjs'; + style.appendChild(document.createTextNode('')); // Necessary for Webkit. + + // We place it in the head with the other style tags, if possible, so as to + // not look out of place. We insert before the others so these styles can be + // overridden if necessary. + firstStyleEl = document.head.querySelector('[rel="stylesheet"], style'); + if (firstStyleEl === undefined) { + document.head.appendChild(style); + } else { + document.head.insertBefore(style, firstStyleEl); + } + + style.sheet.insertRule(linkRule, style.sheet.cssRules.length); + style.sheet.insertRule(hoverRule, style.sheet.cssRules.length); + style.sheet.insertRule(pseudoElContent, style.sheet.cssRules.length); + style.sheet.insertRule(anchorjsLinkFontFace, style.sheet.cssRules.length); + } + } + + return AnchorJS; +}); diff --git a/assets/bass-addons.css b/assets/bass-addons.css new file mode 100644 index 0000000..c27e96d --- /dev/null +++ b/assets/bass-addons.css @@ -0,0 +1,12 @@ +.input { + font-family: inherit; + display: block; + width: 100%; + height: 2rem; + padding: .5rem; + margin-bottom: 1rem; + border: 1px solid #ccc; + font-size: .875rem; + border-radius: 3px; + box-sizing: border-box; +} diff --git a/assets/bass.css b/assets/bass.css new file mode 100644 index 0000000..2d860c5 --- /dev/null +++ b/assets/bass.css @@ -0,0 +1,544 @@ +/*! Basscss | http://basscss.com | MIT License */ + +.h1{ font-size: 2rem } +.h2{ font-size: 1.5rem } +.h3{ font-size: 1.25rem } +.h4{ font-size: 1rem } +.h5{ font-size: .875rem } +.h6{ font-size: .75rem } + +.font-family-inherit{ font-family:inherit } +.font-size-inherit{ font-size:inherit } +.text-decoration-none{ text-decoration:none } + +.bold{ font-weight: bold; font-weight: bold } +.regular{ font-weight:normal } +.italic{ font-style:italic } +.caps{ text-transform:uppercase; letter-spacing: .2em; } + +.left-align{ text-align:left } +.center{ text-align:center } +.right-align{ text-align:right } +.justify{ text-align:justify } + +.nowrap{ white-space:nowrap } +.break-word{ word-wrap:break-word } + +.line-height-1{ line-height: 1 } +.line-height-2{ line-height: 1.125 } +.line-height-3{ line-height: 1.25 } +.line-height-4{ line-height: 1.5 } + +.list-style-none{ list-style:none } +.underline{ text-decoration:underline } + +.truncate{ + max-width:100%; + overflow:hidden; + text-overflow:ellipsis; + white-space:nowrap; +} + +.list-reset{ + list-style:none; + padding-left:0; +} + +.inline{ display:inline } +.block{ display:block } +.inline-block{ display:inline-block } +.table{ display:table } +.table-cell{ display:table-cell } + +.overflow-hidden{ overflow:hidden } +.overflow-scroll{ overflow:scroll } +.overflow-auto{ overflow:auto } + +.clearfix:before, +.clearfix:after{ + content:" "; + display:table +} +.clearfix:after{ clear:both } + +.left{ float:left } +.right{ float:right } + +.fit{ max-width:100% } + +.max-width-1{ max-width: 24rem } +.max-width-2{ max-width: 32rem } +.max-width-3{ max-width: 48rem } +.max-width-4{ max-width: 64rem } + +.border-box{ box-sizing:border-box } + +.align-baseline{ vertical-align:baseline } +.align-top{ vertical-align:top } +.align-middle{ vertical-align:middle } +.align-bottom{ vertical-align:bottom } + +.m0{ margin:0 } +.mt0{ margin-top:0 } +.mr0{ margin-right:0 } +.mb0{ margin-bottom:0 } +.ml0{ margin-left:0 } +.mx0{ margin-left:0; margin-right:0 } +.my0{ margin-top:0; margin-bottom:0 } + +.m1{ margin: .5rem } +.mt1{ margin-top: .5rem } +.mr1{ margin-right: .5rem } +.mb1{ margin-bottom: .5rem } +.ml1{ margin-left: .5rem } +.mx1{ margin-left: .5rem; margin-right: .5rem } +.my1{ margin-top: .5rem; margin-bottom: .5rem } + +.m2{ margin: 1rem } +.mt2{ margin-top: 1rem } +.mr2{ margin-right: 1rem } +.mb2{ margin-bottom: 1rem } +.ml2{ margin-left: 1rem } +.mx2{ margin-left: 1rem; margin-right: 1rem } +.my2{ margin-top: 1rem; margin-bottom: 1rem } + +.m3{ margin: 2rem } +.mt3{ margin-top: 2rem } +.mr3{ margin-right: 2rem } +.mb3{ margin-bottom: 2rem } +.ml3{ margin-left: 2rem } +.mx3{ margin-left: 2rem; margin-right: 2rem } +.my3{ margin-top: 2rem; margin-bottom: 2rem } + +.m4{ margin: 4rem } +.mt4{ margin-top: 4rem } +.mr4{ margin-right: 4rem } +.mb4{ margin-bottom: 4rem } +.ml4{ margin-left: 4rem } +.mx4{ margin-left: 4rem; margin-right: 4rem } +.my4{ margin-top: 4rem; margin-bottom: 4rem } + +.mxn1{ margin-left: -.5rem; margin-right: -.5rem; } +.mxn2{ margin-left: -1rem; margin-right: -1rem; } +.mxn3{ margin-left: -2rem; margin-right: -2rem; } +.mxn4{ margin-left: -4rem; margin-right: -4rem; } + +.ml-auto{ margin-left:auto } +.mr-auto{ margin-right:auto } +.mx-auto{ margin-left:auto; margin-right:auto; } + +.p0{ padding:0 } +.pt0{ padding-top:0 } +.pr0{ padding-right:0 } +.pb0{ padding-bottom:0 } +.pl0{ padding-left:0 } +.px0{ padding-left:0; padding-right:0 } +.py0{ padding-top:0; padding-bottom:0 } + +.p1{ padding: .5rem } +.pt1{ padding-top: .5rem } +.pr1{ padding-right: .5rem } +.pb1{ padding-bottom: .5rem } +.pl1{ padding-left: .5rem } +.py1{ padding-top: .5rem; padding-bottom: .5rem } +.px1{ padding-left: .5rem; padding-right: .5rem } + +.p2{ padding: 1rem } +.pt2{ padding-top: 1rem } +.pr2{ padding-right: 1rem } +.pb2{ padding-bottom: 1rem } +.pl2{ padding-left: 1rem } +.py2{ padding-top: 1rem; padding-bottom: 1rem } +.px2{ padding-left: 1rem; padding-right: 1rem } + +.p3{ padding: 2rem } +.pt3{ padding-top: 2rem } +.pr3{ padding-right: 2rem } +.pb3{ padding-bottom: 2rem } +.pl3{ padding-left: 2rem } +.py3{ padding-top: 2rem; padding-bottom: 2rem } +.px3{ padding-left: 2rem; padding-right: 2rem } + +.p4{ padding: 4rem } +.pt4{ padding-top: 4rem } +.pr4{ padding-right: 4rem } +.pb4{ padding-bottom: 4rem } +.pl4{ padding-left: 4rem } +.py4{ padding-top: 4rem; padding-bottom: 4rem } +.px4{ padding-left: 4rem; padding-right: 4rem } + +.col{ + float:left; + box-sizing:border-box; +} + +.col-right{ + float:right; + box-sizing:border-box; +} + +.col-1{ + width:8.33333%; +} + +.col-2{ + width:16.66667%; +} + +.col-3{ + width:25%; +} + +.col-4{ + width:33.33333%; +} + +.col-5{ + width:41.66667%; +} + +.col-6{ + width:50%; +} + +.col-7{ + width:58.33333%; +} + +.col-8{ + width:66.66667%; +} + +.col-9{ + width:75%; +} + +.col-10{ + width:83.33333%; +} + +.col-11{ + width:91.66667%; +} + +.col-12{ + width:100%; +} +@media (min-width: 40em){ + + .sm-col{ + float:left; + box-sizing:border-box; + } + + .sm-col-right{ + float:right; + box-sizing:border-box; + } + + .sm-col-1{ + width:8.33333%; + } + + .sm-col-2{ + width:16.66667%; + } + + .sm-col-3{ + width:25%; + } + + .sm-col-4{ + width:33.33333%; + } + + .sm-col-5{ + width:41.66667%; + } + + .sm-col-6{ + width:50%; + } + + .sm-col-7{ + width:58.33333%; + } + + .sm-col-8{ + width:66.66667%; + } + + .sm-col-9{ + width:75%; + } + + .sm-col-10{ + width:83.33333%; + } + + .sm-col-11{ + width:91.66667%; + } + + .sm-col-12{ + width:100%; + } + +} +@media (min-width: 52em){ + + .md-col{ + float:left; + box-sizing:border-box; + } + + .md-col-right{ + float:right; + box-sizing:border-box; + } + + .md-col-1{ + width:8.33333%; + } + + .md-col-2{ + width:16.66667%; + } + + .md-col-3{ + width:25%; + } + + .md-col-4{ + width:33.33333%; + } + + .md-col-5{ + width:41.66667%; + } + + .md-col-6{ + width:50%; + } + + .md-col-7{ + width:58.33333%; + } + + .md-col-8{ + width:66.66667%; + } + + .md-col-9{ + width:75%; + } + + .md-col-10{ + width:83.33333%; + } + + .md-col-11{ + width:91.66667%; + } + + .md-col-12{ + width:100%; + } + +} +@media (min-width: 64em){ + + .lg-col{ + float:left; + box-sizing:border-box; + } + + .lg-col-right{ + float:right; + box-sizing:border-box; + } + + .lg-col-1{ + width:8.33333%; + } + + .lg-col-2{ + width:16.66667%; + } + + .lg-col-3{ + width:25%; + } + + .lg-col-4{ + width:33.33333%; + } + + .lg-col-5{ + width:41.66667%; + } + + .lg-col-6{ + width:50%; + } + + .lg-col-7{ + width:58.33333%; + } + + .lg-col-8{ + width:66.66667%; + } + + .lg-col-9{ + width:75%; + } + + .lg-col-10{ + width:83.33333%; + } + + .lg-col-11{ + width:91.66667%; + } + + .lg-col-12{ + width:100%; + } + +} +.flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } + +@media (min-width: 40em){ + .sm-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } +} + +@media (min-width: 52em){ + .md-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } +} + +@media (min-width: 64em){ + .lg-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } +} + +.flex-column{ -webkit-box-orient:vertical; -webkit-box-direction:normal; -webkit-flex-direction:column; -ms-flex-direction:column; flex-direction:column } +.flex-wrap{ -webkit-flex-wrap:wrap; -ms-flex-wrap:wrap; flex-wrap:wrap } + +.items-start{ -webkit-box-align:start; -webkit-align-items:flex-start; -ms-flex-align:start; -ms-grid-row-align:flex-start; align-items:flex-start } +.items-end{ -webkit-box-align:end; -webkit-align-items:flex-end; -ms-flex-align:end; -ms-grid-row-align:flex-end; align-items:flex-end } +.items-center{ -webkit-box-align:center; -webkit-align-items:center; -ms-flex-align:center; -ms-grid-row-align:center; align-items:center } +.items-baseline{ -webkit-box-align:baseline; -webkit-align-items:baseline; -ms-flex-align:baseline; -ms-grid-row-align:baseline; align-items:baseline } +.items-stretch{ -webkit-box-align:stretch; -webkit-align-items:stretch; -ms-flex-align:stretch; -ms-grid-row-align:stretch; align-items:stretch } + +.self-start{ -webkit-align-self:flex-start; -ms-flex-item-align:start; align-self:flex-start } +.self-end{ -webkit-align-self:flex-end; -ms-flex-item-align:end; align-self:flex-end } +.self-center{ -webkit-align-self:center; -ms-flex-item-align:center; align-self:center } +.self-baseline{ -webkit-align-self:baseline; -ms-flex-item-align:baseline; align-self:baseline } +.self-stretch{ -webkit-align-self:stretch; -ms-flex-item-align:stretch; align-self:stretch } + +.justify-start{ -webkit-box-pack:start; -webkit-justify-content:flex-start; -ms-flex-pack:start; justify-content:flex-start } +.justify-end{ -webkit-box-pack:end; -webkit-justify-content:flex-end; -ms-flex-pack:end; justify-content:flex-end } +.justify-center{ -webkit-box-pack:center; -webkit-justify-content:center; -ms-flex-pack:center; justify-content:center } +.justify-between{ -webkit-box-pack:justify; -webkit-justify-content:space-between; -ms-flex-pack:justify; justify-content:space-between } +.justify-around{ -webkit-justify-content:space-around; -ms-flex-pack:distribute; justify-content:space-around } + +.content-start{ -webkit-align-content:flex-start; -ms-flex-line-pack:start; align-content:flex-start } +.content-end{ -webkit-align-content:flex-end; -ms-flex-line-pack:end; align-content:flex-end } +.content-center{ -webkit-align-content:center; -ms-flex-line-pack:center; align-content:center } +.content-between{ -webkit-align-content:space-between; -ms-flex-line-pack:justify; align-content:space-between } +.content-around{ -webkit-align-content:space-around; -ms-flex-line-pack:distribute; align-content:space-around } +.content-stretch{ -webkit-align-content:stretch; -ms-flex-line-pack:stretch; align-content:stretch } +.flex-auto{ + -webkit-box-flex:1; + -webkit-flex:1 1 auto; + -ms-flex:1 1 auto; + flex:1 1 auto; + min-width:0; + min-height:0; +} +.flex-none{ -webkit-box-flex:0; -webkit-flex:none; -ms-flex:none; flex:none } +.fs0{ flex-shrink: 0 } + +.order-0{ -webkit-box-ordinal-group:1; -webkit-order:0; -ms-flex-order:0; order:0 } +.order-1{ -webkit-box-ordinal-group:2; -webkit-order:1; -ms-flex-order:1; order:1 } +.order-2{ -webkit-box-ordinal-group:3; -webkit-order:2; -ms-flex-order:2; order:2 } +.order-3{ -webkit-box-ordinal-group:4; -webkit-order:3; -ms-flex-order:3; order:3 } +.order-last{ -webkit-box-ordinal-group:100000; -webkit-order:99999; -ms-flex-order:99999; order:99999 } + +.relative{ position:relative } +.absolute{ position:absolute } +.fixed{ position:fixed } + +.top-0{ top:0 } +.right-0{ right:0 } +.bottom-0{ bottom:0 } +.left-0{ left:0 } + +.z1{ z-index: 1 } +.z2{ z-index: 2 } +.z3{ z-index: 3 } +.z4{ z-index: 4 } + +.border{ + border-style:solid; + border-width: 1px; +} + +.border-top{ + border-top-style:solid; + border-top-width: 1px; +} + +.border-right{ + border-right-style:solid; + border-right-width: 1px; +} + +.border-bottom{ + border-bottom-style:solid; + border-bottom-width: 1px; +} + +.border-left{ + border-left-style:solid; + border-left-width: 1px; +} + +.border-none{ border:0 } + +.rounded{ border-radius: 3px } +.circle{ border-radius:50% } + +.rounded-top{ border-radius: 3px 3px 0 0 } +.rounded-right{ border-radius: 0 3px 3px 0 } +.rounded-bottom{ border-radius: 0 0 3px 3px } +.rounded-left{ border-radius: 3px 0 0 3px } + +.not-rounded{ border-radius:0 } + +.hide{ + position:absolute !important; + height:1px; + width:1px; + overflow:hidden; + clip:rect(1px, 1px, 1px, 1px); +} + +@media (max-width: 40em){ + .xs-hide{ display:none !important } +} + +@media (min-width: 40em) and (max-width: 52em){ + .sm-hide{ display:none !important } +} + +@media (min-width: 52em) and (max-width: 64em){ + .md-hide{ display:none !important } +} + +@media (min-width: 64em){ + .lg-hide{ display:none !important } +} + +.display-none{ display:none !important } + diff --git a/assets/fonts/EOT/SourceCodePro-Bold.eot b/assets/fonts/EOT/SourceCodePro-Bold.eot new file mode 100755 index 0000000..d24cc39 Binary files /dev/null and b/assets/fonts/EOT/SourceCodePro-Bold.eot differ diff --git a/assets/fonts/EOT/SourceCodePro-Regular.eot b/assets/fonts/EOT/SourceCodePro-Regular.eot new file mode 100755 index 0000000..09e9473 Binary files /dev/null and b/assets/fonts/EOT/SourceCodePro-Regular.eot differ diff --git a/assets/fonts/LICENSE.txt b/assets/fonts/LICENSE.txt new file mode 100755 index 0000000..d154618 --- /dev/null +++ b/assets/fonts/LICENSE.txt @@ -0,0 +1,93 @@ +Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/OTF/SourceCodePro-Bold.otf b/assets/fonts/OTF/SourceCodePro-Bold.otf new file mode 100755 index 0000000..f4e576c Binary files /dev/null and b/assets/fonts/OTF/SourceCodePro-Bold.otf differ diff --git a/assets/fonts/OTF/SourceCodePro-Regular.otf b/assets/fonts/OTF/SourceCodePro-Regular.otf new file mode 100755 index 0000000..4e3b9d0 Binary files /dev/null and b/assets/fonts/OTF/SourceCodePro-Regular.otf differ diff --git a/assets/fonts/TTF/SourceCodePro-Bold.ttf b/assets/fonts/TTF/SourceCodePro-Bold.ttf new file mode 100755 index 0000000..e0c576f Binary files /dev/null and b/assets/fonts/TTF/SourceCodePro-Bold.ttf differ diff --git a/assets/fonts/TTF/SourceCodePro-Regular.ttf b/assets/fonts/TTF/SourceCodePro-Regular.ttf new file mode 100755 index 0000000..437f472 Binary files /dev/null and b/assets/fonts/TTF/SourceCodePro-Regular.ttf differ diff --git a/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff b/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff new file mode 100755 index 0000000..cf96099 Binary files /dev/null and b/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff differ diff --git a/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff b/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff new file mode 100755 index 0000000..395436e Binary files /dev/null and b/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff differ diff --git a/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff b/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff new file mode 100755 index 0000000..c65ba84 Binary files /dev/null and b/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff differ diff --git a/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff b/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff new file mode 100755 index 0000000..0af792a Binary files /dev/null and b/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff differ diff --git a/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 b/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 new file mode 100755 index 0000000..cbe3835 Binary files /dev/null and b/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 differ diff --git a/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 b/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 new file mode 100755 index 0000000..65cd591 Binary files /dev/null and b/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 differ diff --git a/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 b/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 new file mode 100755 index 0000000..b78d523 Binary files /dev/null and b/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 differ diff --git a/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 b/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 new file mode 100755 index 0000000..18d2199 Binary files /dev/null and b/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 differ diff --git a/assets/fonts/source-code-pro.css b/assets/fonts/source-code-pro.css new file mode 100755 index 0000000..3abb4f0 --- /dev/null +++ b/assets/fonts/source-code-pro.css @@ -0,0 +1,23 @@ +@font-face{ + font-family: 'Source Code Pro'; + font-weight: 400; + font-style: normal; + font-stretch: normal; + src: url('EOT/SourceCodePro-Regular.eot') format('embedded-opentype'), + url('WOFF2/TTF/SourceCodePro-Regular.ttf.woff2') format('woff2'), + url('WOFF/OTF/SourceCodePro-Regular.otf.woff') format('woff'), + url('OTF/SourceCodePro-Regular.otf') format('opentype'), + url('TTF/SourceCodePro-Regular.ttf') format('truetype'); +} + +@font-face{ + font-family: 'Source Code Pro'; + font-weight: 700; + font-style: normal; + font-stretch: normal; + src: url('EOT/SourceCodePro-Bold.eot') format('embedded-opentype'), + url('WOFF2/TTF/SourceCodePro-Bold.ttf.woff2') format('woff2'), + url('WOFF/OTF/SourceCodePro-Bold.otf.woff') format('woff'), + url('OTF/SourceCodePro-Bold.otf') format('opentype'), + url('TTF/SourceCodePro-Bold.ttf') format('truetype'); +} diff --git a/assets/github.css b/assets/github.css new file mode 100644 index 0000000..8852abb --- /dev/null +++ b/assets/github.css @@ -0,0 +1,123 @@ +/* + +github.com style (c) Vasily Polovnyov + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + color: #333; + background: #f8f8f8; + -webkit-text-size-adjust: none; +} + +.hljs-comment, +.diff .hljs-header, +.hljs-javadoc { + color: #998; + font-style: italic; +} + +.hljs-keyword, +.css .rule .hljs-keyword, +.hljs-winutils, +.nginx .hljs-title, +.hljs-subst, +.hljs-request, +.hljs-status { + color: #1184CE; +} + +.hljs-number, +.hljs-hexcolor, +.ruby .hljs-constant { + color: #ed225d; +} + +.hljs-string, +.hljs-tag .hljs-value, +.hljs-phpdoc, +.hljs-dartdoc, +.tex .hljs-formula { + color: #ed225d; +} + +.hljs-title, +.hljs-id, +.scss .hljs-preprocessor { + color: #900; + font-weight: bold; +} + +.hljs-list .hljs-keyword, +.hljs-subst { + font-weight: normal; +} + +.hljs-class .hljs-title, +.hljs-type, +.vhdl .hljs-literal, +.tex .hljs-command { + color: #458; + font-weight: bold; +} + +.hljs-tag, +.hljs-tag .hljs-title, +.hljs-rules .hljs-property, +.django .hljs-tag .hljs-keyword { + color: #000080; + font-weight: normal; +} + +.hljs-attribute, +.hljs-variable, +.lisp .hljs-body { + color: #008080; +} + +.hljs-regexp { + color: #009926; +} + +.hljs-symbol, +.ruby .hljs-symbol .hljs-string, +.lisp .hljs-keyword, +.clojure .hljs-keyword, +.scheme .hljs-keyword, +.tex .hljs-special, +.hljs-prompt { + color: #990073; +} + +.hljs-built_in { + color: #0086b3; +} + +.hljs-preprocessor, +.hljs-pragma, +.hljs-pi, +.hljs-doctype, +.hljs-shebang, +.hljs-cdata { + color: #999; + font-weight: bold; +} + +.hljs-deletion { + background: #fdd; +} + +.hljs-addition { + background: #dfd; +} + +.diff .hljs-change { + background: #0086b3; +} + +.hljs-chunk { + color: #aaa; +} diff --git a/assets/site.js b/assets/site.js new file mode 100644 index 0000000..a624be7 --- /dev/null +++ b/assets/site.js @@ -0,0 +1,168 @@ +/* global anchors */ + +// add anchor links to headers +anchors.options.placement = 'left'; +anchors.add('h3'); + +// Filter UI +var tocElements = document.getElementById('toc').getElementsByTagName('li'); + +document.getElementById('filter-input').addEventListener('keyup', function (e) { + var i, element, children; + + // enter key + if (e.keyCode === 13) { + // go to the first displayed item in the toc + for (i = 0; i < tocElements.length; i++) { + element = tocElements[i]; + if (!element.classList.contains('display-none')) { + location.replace(element.firstChild.href); + return e.preventDefault(); + } + } + } + + var match = function () { + return true; + }; + + var value = this.value.toLowerCase(); + + if (!value.match(/^\s*$/)) { + match = function (element) { + var html = element.firstChild.innerHTML; + return html && html.toLowerCase().indexOf(value) !== -1; + }; + } + + for (i = 0; i < tocElements.length; i++) { + element = tocElements[i]; + children = Array.from(element.getElementsByTagName('li')); + if (match(element) || children.some(match)) { + element.classList.remove('display-none'); + } else { + element.classList.add('display-none'); + } + } +}); + +var items = document.getElementsByClassName('toggle-sibling'); +for (var j = 0; j < items.length; j++) { + items[j].addEventListener('click', toggleSibling); +} + +function toggleSibling() { + var stepSibling = this.parentNode.getElementsByClassName('toggle-target')[0]; + var icon = this.getElementsByClassName('icon')[0]; + var klass = 'display-none'; + if (stepSibling.classList.contains(klass)) { + stepSibling.classList.remove(klass); + icon.innerHTML = 'β–Ύ'; + } else { + stepSibling.classList.add(klass); + icon.innerHTML = 'β–Έ'; + } +} + +function showHashTarget(targetId) { + if (targetId) { + var hashTarget = document.getElementById(targetId); + // new target is hidden + if ( + hashTarget && + hashTarget.offsetHeight === 0 && + hashTarget.parentNode.parentNode.classList.contains('display-none') + ) { + hashTarget.parentNode.parentNode.classList.remove('display-none'); + } + } +} + +function scrollIntoView(targetId) { + // Only scroll to element if we don't have a stored scroll position. + if (targetId && !history.state) { + var hashTarget = document.getElementById(targetId); + if (hashTarget) { + hashTarget.scrollIntoView(); + } + } +} + +function gotoCurrentTarget() { + showHashTarget(location.hash.substring(1)); + scrollIntoView(location.hash.substring(1)); +} + +window.addEventListener('hashchange', gotoCurrentTarget); +gotoCurrentTarget(); + +var toclinks = document.getElementsByClassName('pre-open'); +for (var k = 0; k < toclinks.length; k++) { + toclinks[k].addEventListener('mousedown', preOpen, false); +} + +function preOpen() { + showHashTarget(this.hash.substring(1)); +} + +var split_left = document.querySelector('#split-left'); +var split_right = document.querySelector('#split-right'); +var split_parent = split_left.parentNode; +var cw_with_sb = split_left.clientWidth; +split_left.style.overflow = 'hidden'; +var cw_without_sb = split_left.clientWidth; +split_left.style.overflow = ''; + +Split(['#split-left', '#split-right'], { + elementStyle: function (dimension, size, gutterSize) { + return { + 'flex-basis': 'calc(' + size + '% - ' + gutterSize + 'px)' + }; + }, + gutterStyle: function (dimension, gutterSize) { + return { + 'flex-basis': gutterSize + 'px' + }; + }, + gutterSize: 20, + sizes: [33, 67] +}); + +// Chrome doesn't remember scroll position properly so do it ourselves. +// Also works on Firefox and Edge. + +function updateState() { + history.replaceState( + { + left_top: split_left.scrollTop, + right_top: split_right.scrollTop + }, + document.title + ); +} + +function loadState(ev) { + if (ev) { + // Edge doesn't replace change history.state on popstate. + history.replaceState(ev.state, document.title); + } + if (history.state) { + split_left.scrollTop = history.state.left_top; + split_right.scrollTop = history.state.right_top; + } +} + +window.addEventListener('load', function () { + // Restore after Firefox scrolls to hash. + setTimeout(function () { + loadState(); + // Update with initial scroll position. + updateState(); + // Update scroll positions only after we've loaded because Firefox + // emits an initial scroll event with 0. + split_left.addEventListener('scroll', updateState); + split_right.addEventListener('scroll', updateState); + }, 1); +}); + +window.addEventListener('popstate', loadState); diff --git a/assets/split.css b/assets/split.css new file mode 100644 index 0000000..2d7779e --- /dev/null +++ b/assets/split.css @@ -0,0 +1,15 @@ +.gutter { + background-color: #f5f5f5; + background-repeat: no-repeat; + background-position: 50%; +} + +.gutter.gutter-vertical { + background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAFAQMAAABo7865AAAABlBMVEVHcEzMzMzyAv2sAAAAAXRSTlMAQObYZgAAABBJREFUeF5jOAMEEAIEEFwAn3kMwcB6I2AAAAAASUVORK5CYII='); + cursor: ns-resize; +} + +.gutter.gutter-horizontal { + background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAIklEQVQoU2M4c+bMfxAGAgYYmwGrIIiDjrELjpo5aiZeMwF+yNnOs5KSvgAAAABJRU5ErkJggg=='); + cursor: ew-resize; +} diff --git a/assets/split.js b/assets/split.js new file mode 100644 index 0000000..71f9a60 --- /dev/null +++ b/assets/split.js @@ -0,0 +1,782 @@ +/*! Split.js - v1.5.11 */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.Split = factory()); +}(this, (function () { 'use strict'; + + // The programming goals of Split.js are to deliver readable, understandable and + // maintainable code, while at the same time manually optimizing for tiny minified file size, + // browser compatibility without additional requirements, graceful fallback (IE8 is supported) + // and very few assumptions about the user's page layout. + var global = window; + var document = global.document; + + // Save a couple long function names that are used frequently. + // This optimization saves around 400 bytes. + var addEventListener = 'addEventListener'; + var removeEventListener = 'removeEventListener'; + var getBoundingClientRect = 'getBoundingClientRect'; + var gutterStartDragging = '_a'; + var aGutterSize = '_b'; + var bGutterSize = '_c'; + var HORIZONTAL = 'horizontal'; + var NOOP = function () { return false; }; + + // Figure out if we're in IE8 or not. IE8 will still render correctly, + // but will be static instead of draggable. + var isIE8 = global.attachEvent && !global[addEventListener]; + + // Helper function determines which prefixes of CSS calc we need. + // We only need to do this once on startup, when this anonymous function is called. + // + // Tests -webkit, -moz and -o prefixes. Modified from StackOverflow: + // http://stackoverflow.com/questions/16625140/js-feature-detection-to-detect-the-usage-of-webkit-calc-over-calc/16625167#16625167 + var calc = (['', '-webkit-', '-moz-', '-o-'] + .filter(function (prefix) { + var el = document.createElement('div'); + el.style.cssText = "width:" + prefix + "calc(9px)"; + + return !!el.style.length + }) + .shift()) + "calc"; + + // Helper function checks if its argument is a string-like type + var isString = function (v) { return typeof v === 'string' || v instanceof String; }; + + // Helper function allows elements and string selectors to be used + // interchangeably. In either case an element is returned. This allows us to + // do `Split([elem1, elem2])` as well as `Split(['#id1', '#id2'])`. + var elementOrSelector = function (el) { + if (isString(el)) { + var ele = document.querySelector(el); + if (!ele) { + throw new Error(("Selector " + el + " did not match a DOM element")) + } + return ele + } + + return el + }; + + // Helper function gets a property from the properties object, with a default fallback + var getOption = function (options, propName, def) { + var value = options[propName]; + if (value !== undefined) { + return value + } + return def + }; + + var getGutterSize = function (gutterSize, isFirst, isLast, gutterAlign) { + if (isFirst) { + if (gutterAlign === 'end') { + return 0 + } + if (gutterAlign === 'center') { + return gutterSize / 2 + } + } else if (isLast) { + if (gutterAlign === 'start') { + return 0 + } + if (gutterAlign === 'center') { + return gutterSize / 2 + } + } + + return gutterSize + }; + + // Default options + var defaultGutterFn = function (i, gutterDirection) { + var gut = document.createElement('div'); + gut.className = "gutter gutter-" + gutterDirection; + return gut + }; + + var defaultElementStyleFn = function (dim, size, gutSize) { + var style = {}; + + if (!isString(size)) { + if (!isIE8) { + style[dim] = calc + "(" + size + "% - " + gutSize + "px)"; + } else { + style[dim] = size + "%"; + } + } else { + style[dim] = size; + } + + return style + }; + + var defaultGutterStyleFn = function (dim, gutSize) { + var obj; + + return (( obj = {}, obj[dim] = (gutSize + "px"), obj )); + }; + + // The main function to initialize a split. Split.js thinks about each pair + // of elements as an independant pair. Dragging the gutter between two elements + // only changes the dimensions of elements in that pair. This is key to understanding + // how the following functions operate, since each function is bound to a pair. + // + // A pair object is shaped like this: + // + // { + // a: DOM element, + // b: DOM element, + // aMin: Number, + // bMin: Number, + // dragging: Boolean, + // parent: DOM element, + // direction: 'horizontal' | 'vertical' + // } + // + // The basic sequence: + // + // 1. Set defaults to something sane. `options` doesn't have to be passed at all. + // 2. Initialize a bunch of strings based on the direction we're splitting. + // A lot of the behavior in the rest of the library is paramatized down to + // rely on CSS strings and classes. + // 3. Define the dragging helper functions, and a few helpers to go with them. + // 4. Loop through the elements while pairing them off. Every pair gets an + // `pair` object and a gutter. + // 5. Actually size the pair elements, insert gutters and attach event listeners. + var Split = function (idsOption, options) { + if ( options === void 0 ) options = {}; + + var ids = idsOption; + var dimension; + var clientAxis; + var position; + var positionEnd; + var clientSize; + var elements; + + // Allow HTMLCollection to be used as an argument when supported + if (Array.from) { + ids = Array.from(ids); + } + + // All DOM elements in the split should have a common parent. We can grab + // the first elements parent and hope users read the docs because the + // behavior will be whacky otherwise. + var firstElement = elementOrSelector(ids[0]); + var parent = firstElement.parentNode; + var parentStyle = getComputedStyle ? getComputedStyle(parent) : null; + var parentFlexDirection = parentStyle ? parentStyle.flexDirection : null; + + // Set default options.sizes to equal percentages of the parent element. + var sizes = getOption(options, 'sizes') || ids.map(function () { return 100 / ids.length; }); + + // Standardize minSize to an array if it isn't already. This allows minSize + // to be passed as a number. + var minSize = getOption(options, 'minSize', 100); + var minSizes = Array.isArray(minSize) ? minSize : ids.map(function () { return minSize; }); + + // Get other options + var expandToMin = getOption(options, 'expandToMin', false); + var gutterSize = getOption(options, 'gutterSize', 10); + var gutterAlign = getOption(options, 'gutterAlign', 'center'); + var snapOffset = getOption(options, 'snapOffset', 30); + var dragInterval = getOption(options, 'dragInterval', 1); + var direction = getOption(options, 'direction', HORIZONTAL); + var cursor = getOption( + options, + 'cursor', + direction === HORIZONTAL ? 'col-resize' : 'row-resize' + ); + var gutter = getOption(options, 'gutter', defaultGutterFn); + var elementStyle = getOption( + options, + 'elementStyle', + defaultElementStyleFn + ); + var gutterStyle = getOption(options, 'gutterStyle', defaultGutterStyleFn); + + // 2. Initialize a bunch of strings based on the direction we're splitting. + // A lot of the behavior in the rest of the library is paramatized down to + // rely on CSS strings and classes. + if (direction === HORIZONTAL) { + dimension = 'width'; + clientAxis = 'clientX'; + position = 'left'; + positionEnd = 'right'; + clientSize = 'clientWidth'; + } else if (direction === 'vertical') { + dimension = 'height'; + clientAxis = 'clientY'; + position = 'top'; + positionEnd = 'bottom'; + clientSize = 'clientHeight'; + } + + // 3. Define the dragging helper functions, and a few helpers to go with them. + // Each helper is bound to a pair object that contains its metadata. This + // also makes it easy to store references to listeners that that will be + // added and removed. + // + // Even though there are no other functions contained in them, aliasing + // this to self saves 50 bytes or so since it's used so frequently. + // + // The pair object saves metadata like dragging state, position and + // event listener references. + + function setElementSize(el, size, gutSize, i) { + // Split.js allows setting sizes via numbers (ideally), or if you must, + // by string, like '300px'. This is less than ideal, because it breaks + // the fluid layout that `calc(% - px)` provides. You're on your own if you do that, + // make sure you calculate the gutter size by hand. + var style = elementStyle(dimension, size, gutSize, i); + + Object.keys(style).forEach(function (prop) { + // eslint-disable-next-line no-param-reassign + el.style[prop] = style[prop]; + }); + } + + function setGutterSize(gutterElement, gutSize, i) { + var style = gutterStyle(dimension, gutSize, i); + + Object.keys(style).forEach(function (prop) { + // eslint-disable-next-line no-param-reassign + gutterElement.style[prop] = style[prop]; + }); + } + + function getSizes() { + return elements.map(function (element) { return element.size; }) + } + + // Supports touch events, but not multitouch, so only the first + // finger `touches[0]` is counted. + function getMousePosition(e) { + if ('touches' in e) { return e.touches[0][clientAxis] } + return e[clientAxis] + } + + // Actually adjust the size of elements `a` and `b` to `offset` while dragging. + // calc is used to allow calc(percentage + gutterpx) on the whole split instance, + // which allows the viewport to be resized without additional logic. + // Element a's size is the same as offset. b's size is total size - a size. + // Both sizes are calculated from the initial parent percentage, + // then the gutter size is subtracted. + function adjust(offset) { + var a = elements[this.a]; + var b = elements[this.b]; + var percentage = a.size + b.size; + + a.size = (offset / this.size) * percentage; + b.size = percentage - (offset / this.size) * percentage; + + setElementSize(a.element, a.size, this[aGutterSize], a.i); + setElementSize(b.element, b.size, this[bGutterSize], b.i); + } + + // drag, where all the magic happens. The logic is really quite simple: + // + // 1. Ignore if the pair is not dragging. + // 2. Get the offset of the event. + // 3. Snap offset to min if within snappable range (within min + snapOffset). + // 4. Actually adjust each element in the pair to offset. + // + // --------------------------------------------------------------------- + // | | <- a.minSize || b.minSize -> | | + // | | | <- this.snapOffset || this.snapOffset -> | | | + // | | | || | | | + // | | | || | | | + // --------------------------------------------------------------------- + // | <- this.start this.size -> | + function drag(e) { + var offset; + var a = elements[this.a]; + var b = elements[this.b]; + + if (!this.dragging) { return } + + // Get the offset of the event from the first side of the + // pair `this.start`. Then offset by the initial position of the + // mouse compared to the gutter size. + offset = + getMousePosition(e) - + this.start + + (this[aGutterSize] - this.dragOffset); + + if (dragInterval > 1) { + offset = Math.round(offset / dragInterval) * dragInterval; + } + + // If within snapOffset of min or max, set offset to min or max. + // snapOffset buffers a.minSize and b.minSize, so logic is opposite for both. + // Include the appropriate gutter sizes to prevent overflows. + if (offset <= a.minSize + snapOffset + this[aGutterSize]) { + offset = a.minSize + this[aGutterSize]; + } else if ( + offset >= + this.size - (b.minSize + snapOffset + this[bGutterSize]) + ) { + offset = this.size - (b.minSize + this[bGutterSize]); + } + + // Actually adjust the size. + adjust.call(this, offset); + + // Call the drag callback continously. Don't do anything too intensive + // in this callback. + getOption(options, 'onDrag', NOOP)(); + } + + // Cache some important sizes when drag starts, so we don't have to do that + // continously: + // + // `size`: The total size of the pair. First + second + first gutter + second gutter. + // `start`: The leading side of the first element. + // + // ------------------------------------------------ + // | aGutterSize -> ||| | + // | ||| | + // | ||| | + // | ||| <- bGutterSize | + // ------------------------------------------------ + // | <- start size -> | + function calculateSizes() { + // Figure out the parent size minus padding. + var a = elements[this.a].element; + var b = elements[this.b].element; + + var aBounds = a[getBoundingClientRect](); + var bBounds = b[getBoundingClientRect](); + + this.size = + aBounds[dimension] + + bBounds[dimension] + + this[aGutterSize] + + this[bGutterSize]; + this.start = aBounds[position]; + this.end = aBounds[positionEnd]; + } + + function innerSize(element) { + // Return nothing if getComputedStyle is not supported (< IE9) + // Or if parent element has no layout yet + if (!getComputedStyle) { return null } + + var computedStyle = getComputedStyle(element); + + if (!computedStyle) { return null } + + var size = element[clientSize]; + + if (size === 0) { return null } + + if (direction === HORIZONTAL) { + size -= + parseFloat(computedStyle.paddingLeft) + + parseFloat(computedStyle.paddingRight); + } else { + size -= + parseFloat(computedStyle.paddingTop) + + parseFloat(computedStyle.paddingBottom); + } + + return size + } + + // When specifying percentage sizes that are less than the computed + // size of the element minus the gutter, the lesser percentages must be increased + // (and decreased from the other elements) to make space for the pixels + // subtracted by the gutters. + function trimToMin(sizesToTrim) { + // Try to get inner size of parent element. + // If it's no supported, return original sizes. + var parentSize = innerSize(parent); + if (parentSize === null) { + return sizesToTrim + } + + if (minSizes.reduce(function (a, b) { return a + b; }, 0) > parentSize) { + return sizesToTrim + } + + // Keep track of the excess pixels, the amount of pixels over the desired percentage + // Also keep track of the elements with pixels to spare, to decrease after if needed + var excessPixels = 0; + var toSpare = []; + + var pixelSizes = sizesToTrim.map(function (size, i) { + // Convert requested percentages to pixel sizes + var pixelSize = (parentSize * size) / 100; + var elementGutterSize = getGutterSize( + gutterSize, + i === 0, + i === sizesToTrim.length - 1, + gutterAlign + ); + var elementMinSize = minSizes[i] + elementGutterSize; + + // If element is too smal, increase excess pixels by the difference + // and mark that it has no pixels to spare + if (pixelSize < elementMinSize) { + excessPixels += elementMinSize - pixelSize; + toSpare.push(0); + return elementMinSize + } + + // Otherwise, mark the pixels it has to spare and return it's original size + toSpare.push(pixelSize - elementMinSize); + return pixelSize + }); + + // If nothing was adjusted, return the original sizes + if (excessPixels === 0) { + return sizesToTrim + } + + return pixelSizes.map(function (pixelSize, i) { + var newPixelSize = pixelSize; + + // While there's still pixels to take, and there's enough pixels to spare, + // take as many as possible up to the total excess pixels + if (excessPixels > 0 && toSpare[i] - excessPixels > 0) { + var takenPixels = Math.min( + excessPixels, + toSpare[i] - excessPixels + ); + + // Subtract the amount taken for the next iteration + excessPixels -= takenPixels; + newPixelSize = pixelSize - takenPixels; + } + + // Return the pixel size adjusted as a percentage + return (newPixelSize / parentSize) * 100 + }) + } + + // stopDragging is very similar to startDragging in reverse. + function stopDragging() { + var self = this; + var a = elements[self.a].element; + var b = elements[self.b].element; + + if (self.dragging) { + getOption(options, 'onDragEnd', NOOP)(getSizes()); + } + + self.dragging = false; + + // Remove the stored event listeners. This is why we store them. + global[removeEventListener]('mouseup', self.stop); + global[removeEventListener]('touchend', self.stop); + global[removeEventListener]('touchcancel', self.stop); + global[removeEventListener]('mousemove', self.move); + global[removeEventListener]('touchmove', self.move); + + // Clear bound function references + self.stop = null; + self.move = null; + + a[removeEventListener]('selectstart', NOOP); + a[removeEventListener]('dragstart', NOOP); + b[removeEventListener]('selectstart', NOOP); + b[removeEventListener]('dragstart', NOOP); + + a.style.userSelect = ''; + a.style.webkitUserSelect = ''; + a.style.MozUserSelect = ''; + a.style.pointerEvents = ''; + + b.style.userSelect = ''; + b.style.webkitUserSelect = ''; + b.style.MozUserSelect = ''; + b.style.pointerEvents = ''; + + self.gutter.style.cursor = ''; + self.parent.style.cursor = ''; + document.body.style.cursor = ''; + } + + // startDragging calls `calculateSizes` to store the inital size in the pair object. + // It also adds event listeners for mouse/touch events, + // and prevents selection while dragging so avoid the selecting text. + function startDragging(e) { + // Right-clicking can't start dragging. + if ('button' in e && e.button !== 0) { + return + } + + // Alias frequently used variables to save space. 200 bytes. + var self = this; + var a = elements[self.a].element; + var b = elements[self.b].element; + + // Call the onDragStart callback. + if (!self.dragging) { + getOption(options, 'onDragStart', NOOP)(getSizes()); + } + + // Don't actually drag the element. We emulate that in the drag function. + e.preventDefault(); + + // Set the dragging property of the pair object. + self.dragging = true; + + // Create two event listeners bound to the same pair object and store + // them in the pair object. + self.move = drag.bind(self); + self.stop = stopDragging.bind(self); + + // All the binding. `window` gets the stop events in case we drag out of the elements. + global[addEventListener]('mouseup', self.stop); + global[addEventListener]('touchend', self.stop); + global[addEventListener]('touchcancel', self.stop); + global[addEventListener]('mousemove', self.move); + global[addEventListener]('touchmove', self.move); + + // Disable selection. Disable! + a[addEventListener]('selectstart', NOOP); + a[addEventListener]('dragstart', NOOP); + b[addEventListener]('selectstart', NOOP); + b[addEventListener]('dragstart', NOOP); + + a.style.userSelect = 'none'; + a.style.webkitUserSelect = 'none'; + a.style.MozUserSelect = 'none'; + a.style.pointerEvents = 'none'; + + b.style.userSelect = 'none'; + b.style.webkitUserSelect = 'none'; + b.style.MozUserSelect = 'none'; + b.style.pointerEvents = 'none'; + + // Set the cursor at multiple levels + self.gutter.style.cursor = cursor; + self.parent.style.cursor = cursor; + document.body.style.cursor = cursor; + + // Cache the initial sizes of the pair. + calculateSizes.call(self); + + // Determine the position of the mouse compared to the gutter + self.dragOffset = getMousePosition(e) - self.end; + } + + // adjust sizes to ensure percentage is within min size and gutter. + sizes = trimToMin(sizes); + + // 5. Create pair and element objects. Each pair has an index reference to + // elements `a` and `b` of the pair (first and second elements). + // Loop through the elements while pairing them off. Every pair gets a + // `pair` object and a gutter. + // + // Basic logic: + // + // - Starting with the second element `i > 0`, create `pair` objects with + // `a = i - 1` and `b = i` + // - Set gutter sizes based on the _pair_ being first/last. The first and last + // pair have gutterSize / 2, since they only have one half gutter, and not two. + // - Create gutter elements and add event listeners. + // - Set the size of the elements, minus the gutter sizes. + // + // ----------------------------------------------------------------------- + // | i=0 | i=1 | i=2 | i=3 | + // | | | | | + // | pair 0 pair 1 pair 2 | + // | | | | | + // ----------------------------------------------------------------------- + var pairs = []; + elements = ids.map(function (id, i) { + // Create the element object. + var element = { + element: elementOrSelector(id), + size: sizes[i], + minSize: minSizes[i], + i: i, + }; + + var pair; + + if (i > 0) { + // Create the pair object with its metadata. + pair = { + a: i - 1, + b: i, + dragging: false, + direction: direction, + parent: parent, + }; + + pair[aGutterSize] = getGutterSize( + gutterSize, + i - 1 === 0, + false, + gutterAlign + ); + pair[bGutterSize] = getGutterSize( + gutterSize, + false, + i === ids.length - 1, + gutterAlign + ); + + // if the parent has a reverse flex-direction, switch the pair elements. + if ( + parentFlexDirection === 'row-reverse' || + parentFlexDirection === 'column-reverse' + ) { + var temp = pair.a; + pair.a = pair.b; + pair.b = temp; + } + } + + // Determine the size of the current element. IE8 is supported by + // staticly assigning sizes without draggable gutters. Assigns a string + // to `size`. + // + // IE9 and above + if (!isIE8) { + // Create gutter elements for each pair. + if (i > 0) { + var gutterElement = gutter(i, direction, element.element); + setGutterSize(gutterElement, gutterSize, i); + + // Save bound event listener for removal later + pair[gutterStartDragging] = startDragging.bind(pair); + + // Attach bound event listener + gutterElement[addEventListener]( + 'mousedown', + pair[gutterStartDragging] + ); + gutterElement[addEventListener]( + 'touchstart', + pair[gutterStartDragging] + ); + + parent.insertBefore(gutterElement, element.element); + + pair.gutter = gutterElement; + } + } + + setElementSize( + element.element, + element.size, + getGutterSize( + gutterSize, + i === 0, + i === ids.length - 1, + gutterAlign + ), + i + ); + + // After the first iteration, and we have a pair object, append it to the + // list of pairs. + if (i > 0) { + pairs.push(pair); + } + + return element + }); + + function adjustToMin(element) { + var isLast = element.i === pairs.length; + var pair = isLast ? pairs[element.i - 1] : pairs[element.i]; + + calculateSizes.call(pair); + + var size = isLast + ? pair.size - element.minSize - pair[bGutterSize] + : element.minSize + pair[aGutterSize]; + + adjust.call(pair, size); + } + + elements.forEach(function (element) { + var computedSize = element.element[getBoundingClientRect]()[dimension]; + + if (computedSize < element.minSize) { + if (expandToMin) { + adjustToMin(element); + } else { + // eslint-disable-next-line no-param-reassign + element.minSize = computedSize; + } + } + }); + + function setSizes(newSizes) { + var trimmed = trimToMin(newSizes); + trimmed.forEach(function (newSize, i) { + if (i > 0) { + var pair = pairs[i - 1]; + + var a = elements[pair.a]; + var b = elements[pair.b]; + + a.size = trimmed[i - 1]; + b.size = newSize; + + setElementSize(a.element, a.size, pair[aGutterSize], a.i); + setElementSize(b.element, b.size, pair[bGutterSize], b.i); + } + }); + } + + function destroy(preserveStyles, preserveGutter) { + pairs.forEach(function (pair) { + if (preserveGutter !== true) { + pair.parent.removeChild(pair.gutter); + } else { + pair.gutter[removeEventListener]( + 'mousedown', + pair[gutterStartDragging] + ); + pair.gutter[removeEventListener]( + 'touchstart', + pair[gutterStartDragging] + ); + } + + if (preserveStyles !== true) { + var style = elementStyle( + dimension, + pair.a.size, + pair[aGutterSize] + ); + + Object.keys(style).forEach(function (prop) { + elements[pair.a].element.style[prop] = ''; + elements[pair.b].element.style[prop] = ''; + }); + } + }); + } + + if (isIE8) { + return { + setSizes: setSizes, + destroy: destroy, + } + } + + return { + setSizes: setSizes, + getSizes: getSizes, + collapse: function collapse(i) { + adjustToMin(elements[i]); + }, + destroy: destroy, + parent: parent, + pairs: pairs, + } + }; + + return Split; + +}))); diff --git a/assets/style.css b/assets/style.css new file mode 100644 index 0000000..0618f43 --- /dev/null +++ b/assets/style.css @@ -0,0 +1,147 @@ +.documentation { + font-family: Helvetica, sans-serif; + color: #666; + line-height: 1.5; + background: #f5f5f5; +} + +.black { + color: #666; +} + +.bg-white { + background-color: #fff; +} + +h4 { + margin: 20px 0 10px 0; +} + +.documentation h3 { + color: #000; +} + +.border-bottom { + border-color: #ddd; +} + +a { + color: #1184ce; + text-decoration: none; +} + +.documentation a[href]:hover { + text-decoration: underline; +} + +a:hover { + cursor: pointer; +} + +.py1-ul li { + padding: 5px 0; +} + +.max-height-100 { + max-height: 100%; +} + +.height-viewport-100 { + height: 100vh; +} + +section:target h3 { + font-weight: 700; +} + +.documentation td, +.documentation th { + padding: 0.25rem 0.25rem; +} + +h1:hover .anchorjs-link, +h2:hover .anchorjs-link, +h3:hover .anchorjs-link, +h4:hover .anchorjs-link { + opacity: 1; +} + +.fix-3 { + width: 25%; + max-width: 244px; +} + +.fix-3 { + width: 25%; + max-width: 244px; +} + +@media (min-width: 52em) { + .fix-margin-3 { + margin-left: 25%; + } +} + +.pre, +pre, +code, +.code { + font-family: Source Code Pro, Menlo, Consolas, Liberation Mono, monospace; + font-size: 14px; +} + +.fill-light { + background: #f9f9f9; +} + +.width2 { + width: 1rem; +} + +.input { + font-family: inherit; + display: block; + width: 100%; + height: 2rem; + padding: 0.5rem; + margin-bottom: 1rem; + border: 1px solid #ccc; + font-size: 0.875rem; + border-radius: 3px; + box-sizing: border-box; +} + +table { + border-collapse: collapse; +} + +.prose table th, +.prose table td { + text-align: left; + padding: 8px; + border: 1px solid #ddd; +} + +.prose table th:nth-child(1) { + border-right: none; +} +.prose table th:nth-child(2) { + border-left: none; +} + +.prose table { + border: 1px solid #ddd; +} + +.prose-big { + font-size: 18px; + line-height: 30px; +} + +.quiet { + opacity: 0.7; +} + +.minishadow { + box-shadow: 2px 2px 10px #f3f3f3; +} diff --git a/blocks.mjs b/blocks.mjs new file mode 100644 index 0000000..10e5030 --- /dev/null +++ b/blocks.mjs @@ -0,0 +1,1461 @@ +import { buildRichTextObj, enforceRichText } from "./rich-text.mjs"; +import { setIcon } from "./emoji-and-files.mjs"; +import { + isValidURL, + validateImageURL, + validatePDFURL, + validateVideoURL, + enforceStringLength, +} from "./utils.mjs"; + +/* + * TODO + * + * - Create a wrapper class that can give blocks internal labels. Will be useful for appending child block arrays to specific blocks, and editing blocks after creation but before they are sent to Notion + * - Remove undefined blocks from children arrays before making calls + */ + +/** + * Object with methods to construct the majority of block types supported by the Notion API. + * + * Block types include bookmark, bulleted list item, callout, code, divider, embed, file, heading, image, numbered list item, paragraph, pdf, quote, table, table row, table of contents, to-do, toggle, and video. Some block types return null if they are provided with invalid data; you should filter these out your final children array. + * + * Not implemented: Breadcrumb, column list, column, equation, link preview (unsupported), mention, synced block (unsupported) + * + * @namespace + */ +export const block = { + /** + * Methods for bookmark blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + bookmark: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: false, + + /** + * Creates a bookmark block. + * + * @function + * @param {string|Object} options - A string representing the URL, or an options object. + * @param {string} options.url - The URL to be bookmarked. + * @param {string|string[]|Array} [options.caption=[]] - The caption as a string, an array of strings, or an array of rich text objects. + * @returns {Object} A bookmark block object compatible with Notion's API. + * @example + * // Use with just a URL + * const simpleBookmark = block.bookmark.createBlock("https://www.flylighter.com"); + * + * // Use with options object + * const complexBookmark = block.bookmark.createBlock({ + * url: "https://www.flylighter.com", + * caption: "Flylighter is a super-rad web clipper for Notion." + * }); + * + * // Use with options object and array of strings for caption + * const multiLineBookmark = block.bookmark.createBlock({ + * url: "https://www.flylighter.com", + * caption: ["Flylighter is a web clipper for Notion...", "...and Obsidian, too."] + * }); + */ + createBlock(options) { + let url, caption; + if (typeof options === "string") { + url = options; + caption = []; + } else { + ({ url, caption = [] } = options); + } + return { + type: "bookmark", + bookmark: { + url: url, + caption: enforceRichText(caption), + }, + }; + }, + }, + + /** + * Methods for bulleted list item blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + bulleted_list_item: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: true, + + /** + * Creates a bulleted list item block. + * + * @function + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the list item content. + * @param {string|string[]|Array} [options.content=[]] - The content as a string, an array of strings, or an array of rich text objects. + * @param {Array} [options.children=[]] - An array of child block objects. + * @param {string} [options.color="default"] - Color for the text. + * @returns {Object} A bulleted list item block object compatible with Notion's API. + * @example + * // Use with a string + * const simpleItem = block.bulleted_list_item.createBlock("Simple list item"); + * + * // Use with an array of strings + * const multiLineItem = block.bulleted_list_item.createBlock(["Line 1", "Line 2"]); + * + * // Use with options object + * const complexItem = block.bulleted_list_item.createBlock({ + * content: "Complex item", + * color: "red", + * children: [ + * // Child blocks would go here + * ] + * }); + */ + createBlock(options) { + let content, children, color; + if (typeof options === "string" || Array.isArray(options)) { + content = options; + children = []; + color = "default"; + } else { + ({ content = [], children = [], color = "default" } = options); + } + return { + type: "bulleted_list_item", + bulleted_list_item: { + rich_text: enforceRichText(content), + color: color, + ...(children.length > 0 && { children }), + }, + }; + }, + }, + + /** + * Methods for callout blocks. + */ + callout: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: true, + /** + * Creates a callout block. + * + * @function + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the callout content. + * @param {string|string[]|Array} [options.content=[]] - The content as a string, an array of strings, or an array of rich text objects. + * @param {string} [options.icon=""] - An optional icon value (URL for "external" or emoji character for "emoji"). + * @param {Array} [options.children=[]] - An array of child block objects. + * @param {string} [options.color="default"] - Color for the callout background. + * @returns {Object} A callout block object compatible with Notion's API. + * @example + * // Use with a string + * const simpleCallout = block.callout.createBlock("I though I told you never to come in here, McFly!"); + * + * // Use with options object + * const complexCallout = block.callout.createBlock({ + * content: "Now make like a tree and get outta here.", + * icon: "πŸ’‘", + * color: "blue_background", + * children: [ + * // Child blocks would go here + * ] + * }); + */ + createBlock: (options) => { + let content, icon, children, color; + if (typeof options === "string" || Array.isArray(options)) { + content = options; + icon = ""; + children = []; + color = "default"; + } else { + ({ + content = [], + icon = "", + children = [], + color = "default", + } = options); + } + return { + type: "callout", + callout: { + rich_text: enforceRichText(content), + icon: setIcon(icon), + color: color, + ...(children.length > 0 && { children }), + }, + }; + }, + }, + + /** + * Methods for code blocks. + */ + code: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: false, + /** + * Creates a code block. + * + * @function + * @param {string|Object} options - A string representing the code content, or an options object. + * @param {string|string[]|Array} [options.content=[]] - The code content as a string, an array of strings, or an array of rich text objects. + * @param {string|string[]|Array} [options.caption=[]] - The caption as a string, an array of strings, or an array of rich text objects. + * @param {string} [options.language="plain text"] - Programming language of the code block. + * @returns {Object} A code block object compatible with Notion's API. + * @example + * // Use with a string + * const simpleCode = block.code.createBlock("console.log('Give me all the bacon and eggs you have.');"); + * + * // Use with options object + * const complexCode = block.code.createBlock({ + * content: "const name = 'Monkey D. Luffy'\n console.log(`My name is ${name} and I will be king of the pirates!`)", + * language: "JavaScript", + * caption: "A simple JavaScript greeting function" + * }); + */ + createBlock: (options) => { + let content, caption, language; + if (typeof options === "string") { + content = options; + caption = []; + language = "plain text"; + } else { + ({ + content = [], + caption = [], + language = "plain text", + } = options); + } + return { + type: "code", + code: { + rich_text: enforceRichText(content), + caption: enforceRichText(caption), + language: language, + }, + }; + }, + }, + + /** + * Methods for divider blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + divider: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: false, + /** + * Creates a divider block. + * + * @function + * @returns {Object} A divider block object compatible with Notion's API. + * @example + * const divider = block.divider.createBlock(); + */ + createBlock: () => ({ + type: "divider", + divider: {}, + }), + }, + + /** + * Methods for embed blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + embed: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: false, + /** + * Creates an embed block. + * + * @function + * @param {string|Object} options - A string representing the URL to be embedded, or an options object. + * @param {string} options.url - The URL to be embedded. + * @returns {Object} An embed block object compatible with Notion's API. + * @example + * // Use with a string + * const simpleEmbed = block.embed.createBlock("https://www.youtube.com/watch?v=ec5m6t77eYM"); + * + * // Use with options object + * const complexEmbed = block.embed.createBlock({ + * url: "https://www.youtube.com/watch?v=ec5m6t77eYM" + * }); + */ + createBlock: (options) => { + const url = typeof options === "string" ? options : options.url; + return { + type: "embed", + embed: { + url: url, + }, + }; + }, + }, + + /** + * Methods for file blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + file: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: false, + /** + * Creates a file block. + * + * @function + * @param {string|Object} options - A string representing the file URL, or an options object. + * @param {string} options.url - The URL for the file. + * @param {string} [options.name] - The name of the file. + * @param {string|string[]|Array} [options.caption=[]] - The caption as a string, an array of strings, or an array of rich text objects. + * @returns {Object|null} A file block object compatible with Notion's API, or null if the URL is invalid. + * @example + * // Use with a string + * const simpleFile = block.file.createBlock("https://collegeinfogeek.com/wp-content/uploads/2015/01/10steps-reddit.pdf"); + * + * // Use with options object + * const complexFile = block.file.createBlock({ + * url: "https://collegeinfogeek.com/wp-content/uploads/2015/01/10steps-reddit.pdf", + * name: "10 Steps to Earning Awesome Grades (preview)", + * caption: "The Reddit preview of the 10 Steps to Earning Awesome Grades book." + * }); + */ + createBlock: (options) => { + let url, name, caption; + if (typeof options === "string") { + url = options; + name = ""; + caption = []; + } else { + ({ url, name = "", caption = [] } = options); + } + const isValid = isValidURL(url); + return isValid + ? { + type: "file", + file: { + type: "external", + external: { + url: url, + }, + caption: enforceRichText(caption), + name: name && name !== "" ? name : undefined, + }, + } + : null; + }, + }, + + /** + * Methods for heading_1 blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + heading_1: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: true, + /** + * Creates a heading_1 block. + * + * Adding children will coerce headings to toggle headings. + * + * @function + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the heading content. + * @param {string|string[]|Array} [options.content=[]] - The content as a string, an array of strings, or an array of rich text objects. + * @param {string} [options.color="default"] - Color for the heading text. + * @param {boolean} [options.is_toggleable=false] - Whether the heading is toggleable. + * @param {Array} [options.children=[]] - An array of child block objects. + * @returns {Object} A heading_1 block object compatible with Notion's API. + * @example + * // Use with a string + * const simpleHeading = block.heading_1.createBlock("Simple Heading"); + * + * // Use with options object + * const complexHeading = block.heading_1.createBlock({ + * content: "Complex Heading", + * color: "red", + * is_toggleable: true, + * children: [ + * // Child blocks would go here + * ] + * }); + */ + createBlock: (options) => { + let content, color, is_toggleable, children; + if (typeof options === "string" || Array.isArray(options)) { + content = options; + color = "default"; + is_toggleable = false; + children = []; + } else { + ({ + content = [], + color = "default", + is_toggleable = false, + children = [], + } = options); + } + return { + type: "heading_1", + heading_1: { + rich_text: enforceRichText(content), + color: color, + is_toggleable: is_toggleable, + ...(children.length > 0 && { children }), + }, + }; + }, + }, + + /** + * Methods for heading_2 blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + heading_2: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: true, + /** + * Creates a heading_2 block. + * + * Adding children will coerce headings to toggle headings. + * + * @function + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the heading content. + * @param {string|string[]|Array} [options.content=[]] - The content as a string, an array of strings, or an array of rich text objects. + * @param {string} [options.color="default"] - Color for the heading text. + * @param {boolean} [options.is_toggleable=false] - Whether the heading is toggleable. + * @param {Array} [options.children=[]] - An array of child block objects. + * @returns {Object} A heading_2 block object compatible with Notion's API. + * @example + * // Use with a string + * const simpleHeading = block.heading_2.createBlock("Simple Heading"); + * + * // Use with options object + * const complexHeading = block.heading_2.createBlock({ + * content: "Complex Heading", + * color: "red", + * is_toggleable: true, + * children: [ + * // Child blocks would go here + * ] + * }); + */ + createBlock: (options) => { + let content, color, is_toggleable, children; + if (typeof options === "string" || Array.isArray(options)) { + content = options; + color = "default"; + is_toggleable = false; + children = []; + } else { + ({ + content = [], + color = "default", + is_toggleable = false, + children = [], + } = options); + } + return { + type: "heading_2", + heading_2: { + rich_text: enforceRichText(content), + color: color, + is_toggleable: is_toggleable, + ...(children.length > 0 && { children }), + }, + }; + }, + }, + + /** + * Methods for heading_3 blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + heading_3: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: true, + /** + * Creates a heading_3 block. + * + * Adding children will coerce headings to toggle headings. + * + * @function + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the heading content. + * @param {string|string[]|Array} [options.content=[]] - The content as a string, an array of strings, or an array of rich text objects. + * @param {string} [options.color="default"] - Color for the heading text. + * @param {boolean} [options.is_toggleable=false] - Whether the heading is toggleable. + * @param {Array} [options.children=[]] - An array of child block objects. + * @returns {Object} A heading_3 block object compatible with Notion's API. + * @example + * // Use with a string + * const simpleHeading = block.heading_3.createBlock("Simple Heading"); + * + * // Use with options object + * const complexHeading = block.heading_3.createBlock({ + * content: "Complex Heading", + * color: "red", + * is_toggleable: true, + * children: [ + * // Child blocks would go here + * ] + * }); + */ + createBlock: (options) => { + let content, color, is_toggleable, children; + if (typeof options === "string" || Array.isArray(options)) { + content = options; + color = "default"; + is_toggleable = false; + children = []; + } else { + ({ + content = [], + color = "default", + is_toggleable = false, + children = [], + } = options); + } + return { + type: "heading_3", + heading_3: { + rich_text: enforceRichText(content), + color: color, + is_toggleable: is_toggleable, + ...(children.length > 0 && { children }), + }, + }; + }, + }, + + /** + * Methods for image blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + image: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: false, + /** + * Creates an image block. + * + * @function + * @param {string|Object} options - A string representing the image URL, or an options object. + * @param {string} options.url - The URL for the image. + * @param {string|string[]|Array} [options.caption=[]] - The caption as a string, an array of strings, or an array of rich text objects. + * @returns {Object|null} An image block object compatible with Notion's API, or null if the URL is invalid. + * @example + * // Use with a string + * const simpleImage = block.image.createBlock("https://i.imgur.com/5vSShIw.jpeg"); + * + * // Use with options object + * const complexImage = block.image.createBlock({ + * url: "https://i.imgur.com/5vSShIw.jpeg", + * caption: "A beautiful landscape" + * }); + */ + createBlock: (options) => { + let url, caption; + if (typeof options === "string") { + url = options; + caption = []; + } else { + ({ url, caption = [] } = options); + } + const isValidImage = validateImageURL(url); + return isValidImage + ? { + type: "image", + image: { + type: "external", + external: { + url: url, + }, + caption: enforceRichText(caption), + }, + } + : null; + }, + }, + + /** + * Methods for numbered list item blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + numbered_list_item: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: true, + /** + * Creates a numbered list item block. + * + * @function + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the list item content. + * @param {string|string[]|Array} [options.content=[]] - The content as a string, an array of strings, or an array of rich text objects. + * @param {Array} [options.children=[]] - An array of child block objects. + * @param {string} [options.color="default"] - Color for the text. + * @returns {Object} A numbered list item block object compatible with Notion's API. + * @example + * // Use with a string + * const simpleItem = block.numbered_list_item.createBlock("Simple list item"); + * + * // Use with an array of strings + * const multiLineItem = block.numbered_list_item.createBlock(["Line 1", "Line 2"]); + * + * // Use with options object + * const complexItem = block.numbered_list_item.createBlock({ + * content: "Complex item", + * color: "red", + * children: [ + * // Child blocks would go here + * ] + * }); + */ + createBlock: (options) => { + let content, children, color; + if (typeof options === "string" || Array.isArray(options)) { + content = options; + children = []; + color = "default"; + } else { + ({ content = [], children = [], color = "default" } = options); + } + return { + type: "numbered_list_item", + numbered_list_item: { + rich_text: enforceRichText(content), + color: color, + ...(children.length > 0 && { children }), + }, + }; + }, + }, + + /** + * Methods for paragraph blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + paragraph: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: true, + /** + * Creates a paragraph block. + * + * @function + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the paragraph content. + * @param {string|string[]|Array} [options.content=[]] - The content as a string, an array of strings, or an array of rich text objects. + * @param {Array} [options.children=[]] - An array of child block objects. + * @param {string} [options.color="default"] - Color for the text. + * @returns {Object} A paragraph block object compatible with Notion's API. + * @example + * // Direct use with a string + * const paragraphBlock = block.paragraph.createBlock("Hello, World!"); + * + * // Direct use with an array of strings + * const multiLineParagraph = block.paragraph.createBlock(["I'm a line", "I'm also a line!"]); + * + * // Usage with options object + * const complexParagraph = block.paragraph.createBlock({ + * content: "Complex paragraph", + * color: "red", + * children: [ + * // Child blocks would go here + * ] + * }); + */ + createBlock: (options) => { + let content, children, color; + if (typeof options === "string" || Array.isArray(options)) { + content = options; + children = []; + color = "default"; + } else { + ({ content = [], children = [], color = "default" } = options); + } + return { + type: "paragraph", + paragraph: { + rich_text: enforceRichText(content), + color: color, + ...(children.length > 0 && { children }), + }, + }; + }, + }, + + /** + * Methods for PDF blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + pdf: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: false, + /** + * Creates a PDF block. + * + * @function + * @param {string|Object} options - A string representing the PDF URL, or an options object. + * @param {string} options.url - The URL for the PDF. + * @param {string|string[]|Array} [options.caption=[]] - The caption as a string, an array of strings, or an array of rich text objects. + * @returns {Object|null} A PDF block object compatible with Notion's API, or null if the URL is invalid. + * @example + * // Use with a string + * const simplePDF = block.pdf.createBlock("https://collegeinfogeek.com/wp-content/uploads/2015/01/10steps-reddit.pdf"); + * + * // Use with options object + * const complexPDF = block.pdf.createBlock({ + * url: "https://collegeinfogeek.com/wp-content/uploads/2015/01/10steps-reddit.pdf", + * caption: "The Reddit preview of the 10 Steps to Earning Awesome Grades book." + * }); + */ + createBlock: (options) => { + let url, caption; + if (typeof options === "string") { + url = options; + caption = []; + } else { + ({ url, caption = [] } = options); + } + const isValidPDF = validatePDFURL(url); + return isValidPDF + ? { + type: "pdf", + pdf: { + type: "external", + external: { + url: url, + }, + caption: enforceRichText(caption), + }, + } + : null; + }, + }, + + /** + * Methods for quote blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + quote: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: true, + /** + * Creates a quote block. + * + * @function + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the quote content. + * @param {string|string[]|Array} [options.content=[]] - The content as a string, an array of strings, or an array of rich text objects. + * @param {Array} [options.children=[]] - An array of child block objects. + * @param {string} [options.color="default"] - Color for the text. + * @returns {Object} A quote block object compatible with Notion's API. + * @example + * // Use with a string + * const simpleQuote = block.quote.createBlock("Simple quote"); + * + * // Use with an array of strings + * const multiLineQuote = block.quote.createBlock(["Line 1 of quote", "Line 2 of quote"]); + * + * // Use with options object + * const complexQuote = block.quote.createBlock({ + * content: "Complex quote", + * color: "gray", + * children: [ + * // Child blocks would go here + * ] + * }); + */ + createBlock: (options) => { + let content, children, color; + if (typeof options === "string" || Array.isArray(options)) { + content = options; + children = []; + color = "default"; + } else { + ({ content = [], children = [], color = "default" } = options); + } + return { + type: "quote", + quote: { + rich_text: enforceRichText(content), + color: color, + ...(children.length > 0 && { children }), + }, + }; + }, + }, + + /** + * Methods for table blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + table: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: true, + /** + * Creates a table block. + * + * @function + * @param {Object} options - Options for creating the table. + * @param {boolean} [options.has_column_header=false] - Whether the table has a column header. + * @param {boolean} [options.has_row_header=false] - Whether the table has a row header. + * @param {Array>|Array} options.rows - An array of rows. Each row can be an array of strings or a table_row object. + * @returns {Object} A table block object compatible with Notion's API. + * @example + * // Use with array of string arrays + * const simpleTable = block.table.createBlock({ + * rows: [ + * ["Header 1", "Header 2"], + * ["Row 1, Cell 1", "Row 1, Cell 2"], + * ["Row 2, Cell 1", "Row 2, Cell 2"] + * ], + * has_column_header: true + * }); + * + * // Use with array of table_row objects + * const complexTable = block.table.createBlock({ + * rows: [ + * block.table_row.createBlock(["Header 1", "Header 2"]), + * block.table_row.createBlock(["Row 1, Cell 1", "Row 1, Cell 2"]), + * block.table_row.createBlock(["Row 2, Cell 1", "Row 2, Cell 2"]) + * ], + * has_column_header: true, + * has_row_header: false + * }); + */ + createBlock: ({ + has_column_header = false, + has_row_header = false, + rows = [], + }) => { + const children = rows.map((row) => + Array.isArray(row) ? block.table_row.createBlock(row) : row + ); + return { + type: "table", + table: { + table_width: children[0].table_row.cells.length, + has_column_header: has_column_header, + has_row_header: has_row_header, + children: children, + }, + }; + }, + }, + + /** + * Methods for table row blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + table_row: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: false, + /** + * Creates a table row block. + * + * @function + * @param {Array>} cells - An array of cell contents. Each cell can be a string or an array of rich text objects. + * @returns {Object} A table row block object compatible with Notion's API. + * @example + * // Use with an array of strings + * const simpleRow = block.table_row.createBlock(["Cell 1", "Cell 2", "Cell 3"]); + * + * // Use with an array of rich text objects + * const complexRow = block.table_row.createBlock([ + * [{ type: "text", text: { content: "Cell 1" } }], + * [{ type: "text", text: { content: "Cell 2", annotations: { bold: true } } }], + * [{ type: "text", text: { content: "Cell 3" } }] + * ]); + */ + createBlock: (cells = []) => ({ + type: "table_row", + table_row: { + cells: cells.map((cell) => + typeof cell === "string" || typeof cell === "number" ? enforceRichText(cell) : cell + ), + }, + }), + }, + + /** + * Methods for table of contents blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + table_of_contents: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: false, + /** + * Creates a table of contents block. + * + * @function + * @param {string|Object} [options="default"] - A string representing the color, or an options object. + * @param {string} [options.color="default"] - Color for the table of contents. + * @returns {Object} A table of contents block object compatible with Notion's API. + * @example + * // Use with default settings + * const simpleTOC = block.table_of_contents.createBlock(); + * + * // Use with a color string + * const coloredTOC = block.table_of_contents.createBlock("red"); + * + * // Use with options object + * const complexTOC = block.table_of_contents.createBlock({ color: "blue" }); + */ + createBlock: (options = "default") => { + const color = + typeof options === "string" + ? options + : options.color || "default"; + return { + type: "table_of_contents", + table_of_contents: { + color: color, + }, + }; + }, + }, + + /** + * Methods for to-do list blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + to_do: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: true, + /** + * Creates a to-do list block. + * + * @function + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the to-do content. + * @param {string|string[]|Array} [options.content=[]] - The content as a string, an array of strings, or an array of rich text objects. + * @param {boolean} [options.checked=false] - Whether the to-do item is checked. + * @param {Array} [options.children=[]] - An array of child block objects. + * @param {string} [options.color="default"] - Color for the to-do text. + * @returns {Object} A to-do list block object compatible with Notion's API. + * @example + * // Use with a string + * const simpleToDo = block.to_do.createBlock("Simple task"); + * + * // Use with options object + * const complexToDo = block.to_do.createBlock({ + * content: "Complex task", + * checked: true, + * color: "green", + * children: [ + * // Child blocks would go here + * ] + * }); + */ + createBlock: (options) => { + let content, checked, children, color; + if (typeof options === "string" || Array.isArray(options)) { + content = options; + checked = false; + children = []; + color = "default"; + } else { + ({ + content = [], + checked = false, + children = [], + color = "default", + } = options); + } + return { + type: "to_do", + to_do: { + rich_text: enforceRichText(content), + checked: checked, + color: color, + ...(children.length > 0 && { children }), + }, + }; + }, + }, + + /** + * Methods for toggle blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + toggle: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: true, + /** + * Creates a toggle block. + * + * @function + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the toggle content. + * @param {string|string[]|Array} [options.content=[]] - The content as a string, an array of strings, or an array of rich text objects. + * @param {Array} [options.children=[]] - An array of child block objects. + * @param {string} [options.color="default"] - Color for the toggle text. + * @returns {Object} A toggle block object compatible with Notion's API. + * @example + * // Use with a string + * const simpleToggle = block.toggle.createBlock("Simple toggle"); + * + * // Use with options object + * const complexToggle = block.toggle.createBlock({ + * content: "Complex toggle", + * color: "blue", + * children: [ + * // Child blocks would go here + * ] + * }); + */ + createBlock: (options) => { + let content, children, color; + if (typeof options === "string" || Array.isArray(options)) { + content = options; + children = []; + color = "default"; + } else { + ({ content = [], children = [], color = "default" } = options); + } + return { + type: "toggle", + toggle: { + rich_text: enforceRichText(content), + color: color, + ...(children.length > 0 && { children }), + }, + }; + }, + }, + + /** + * Methods for video blocks. + * + * @namespace + * @property {boolean} supports_children - Indicates if the block supports child blocks. + */ + video: { + /** + * Indicates if the block supports child blocks. + * @type {boolean} + */ + supports_children: false, + /** + * Creates a video block. + * + * @function + * @param {string|Object} options - A string representing the video URL, or an options object. + * @param {string} options.url - The URL for the video. + * @param {string|string[]|Array} [options.caption=[]] - The caption as a string, an array of strings, or an array of rich text objects. + * @returns {Object|null} A video block object compatible with Notion's API, or null if the URL is invalid. + * @example + * // Use with a string + * const simpleVideo = block.video.createBlock("https://www.youtube.com/watch?v=ec5m6t77eYM"); + * + * // Use with options object + * const complexVideo = block.video.createBlock({ + * url: "https://www.youtube.com/watch?v=ec5m6t77eYM", + * caption: "Never gonna give you up" + * }); + */ + createBlock: (options) => { + let url, caption; + if (typeof options === "string") { + url = options; + caption = []; + } else { + ({ url, caption = [] } = options); + } + const isValidVideo = validateVideoURL(url); + return isValidVideo + ? { + type: "video", + video: { + type: "external", + external: { + url: url, + }, + caption: enforceRichText(caption), + }, + } + : null; + }, + }, +}; + +/* + * Quality-of-life functions for blocks: + */ + +/** + * Block shorthand methods – these allow you to call the createBlock() method for the properties of the block object more quickly. Import them directly into a file, or call them on NotionHelper. + * @namespace BlockShorthand + */ + +/** + * Creates a bookmark block. + * @memberof BlockShorthand + * @param {string|Object} options - A string representing the URL, or an options object. + * @see block.bookmark for full documentation + * @returns {Object} a bookmark block. + */ +export function bookmark(options) { + return block.bookmark.createBlock(options); +} + +/** + * Creates a bulleted list item block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the list item content. + * @see block.bulleted_list_item for full documentation + * @returns {Object} A bulleted list item block. + */ +export function bulletedListItem(options) { + return block.bulleted_list_item.createBlock(options); +} + +/** + * Shorthand alias for bulletedListItem(). Creates a bulleted list item block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the list item content. + * @see block.bulleted_list_item for full documentation + * @returns {Object} A bulleted list item block. + */ +export function bullet(options) { + return bulletedListItem(options); +} + +/** + * Creates a callout block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the callout content. + * @see block.callout for full documentation + * @returns {Object} A callout block. + */ +export function callout(options) { + return block.callout.createBlock(options); +} + +/** + * Creates a code block. + * @memberof BlockShorthand + * @param {string|Object} options - A string representing the code content, or an options object. + * @see block.code for full documentation + * @returns {Object} A code block. + */ +export function code(options) { + return block.code.createBlock(options); +} + +/** + * Creates a divider block. + * @memberof BlockShorthand + * @see block.divider for full documentation + * @returns {Object} A divider block. + */ +export function divider() { + return block.divider.createBlock(); +} + +/** + * Creates an embed block. + * @memberof BlockShorthand + * @param {string|Object} options - A string representing the URL to be embedded, or an options object. + * @see block.embed for full documentation + * @returns {Object} An embed block. + */ +export function embed(options) { + return block.embed.createBlock(options); +} + +/** + * Creates a file block. + * @memberof BlockShorthand + * @param {string|Object} options - A string representing the file URL, or an options object. + * @see block.file for full documentation + * @returns {Object|null} A file block or null if the URL is invalid. + */ +export function file(options) { + return block.file.createBlock(options); +} + +/** + * Creates a heading_1 block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the heading content. + * @see block.heading_1 for full documentation + * @returns {Object} A heading_1 block. + */ +export function heading1(options) { + return block.heading_1.createBlock(options); +} + +/** + * Creates a heading_2 block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the heading content. + * @see block.heading_2 for full documentation + * @returns {Object} A heading_2 block. + */ +export function heading2(options) { + return block.heading_2.createBlock(options); +} + +/** + * Creates a heading_3 block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the heading content. + * @see block.heading_3 for full documentation + * @returns {Object} A heading_3 block. + */ +export function heading3(options) { + return block.heading_3.createBlock(options); +} + +/** + * Creates an image block. + * @memberof BlockShorthand + * @param {string|Object} options - A string representing the image URL, or an options object. + * @see block.image for full documentation + * @returns {Object|null} An image block or null if the URL is invalid. + */ +export function image(options) { + return block.image.createBlock(options); +} + +/** + * Creates a numbered list item block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the list item content. + * @see block.numbered_list_item for full documentation + * @returns {Object} A numbered list item block. + */ +export function numberedListItem(options) { + return block.numbered_list_item.createBlock(options); +} + +/** + * Shorthand alias function for numberedListItem(). Creates a numbered list item block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the list item content. + * @see block.numbered_list_item for full documentation + * @returns {Object} A numbered list item block. + */ +export function num(options) { + return numberedListItem(options); +} + +/** + * Creates a paragraph block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the paragraph content. + * @see block.paragraph for full documentation + * @returns {Object} A paragraph block. + */ +export function paragraph(options) { + return block.paragraph.createBlock(options); +} + +/** + * Creates a PDF block. + * @memberof BlockShorthand + * @param {string|Object} options - A string representing the PDF URL, or an options object. + * @see block.pdf for full documentation + * @returns {Object|null} A PDF block or null if the URL is invalid. + */ +export function pdf(options) { + return block.pdf.createBlock(options); +} + +/** + * Creates a quote block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the quote content. + * @see block.quote for full documentation + * @returns {Object} A quote block. + */ +export function quote(options) { + return block.quote.createBlock(options); +} + +/** + * Creates a table block. + * @memberof BlockShorthand + * @param {Object} options - Options for creating the table. + * @see block.table for full documentation + * @returns {Object} A table block. + */ +export function table(options) { + return block.table.createBlock(options); +} + +/** + * Creates a table row block. + * @memberof BlockShorthand + * @param {Array>} cells - An array of cell contents. + * @see block.table_row for full documentation + * @returns {Object} A table row block. + */ +export function tableRow(cells) { + return block.table_row.createBlock(cells); +} + +/** + * Creates a table of contents block. + * @memberof BlockShorthand + * @param {string|Object} [options="default"] - A string representing the color, or an options object. + * @see block.table_of_contents for full documentation + * @returns {Object} A table of contents block. + */ +export function tableOfContents(options) { + return block.table_of_contents.createBlock(options); +} + +/** + * Creates a to-do list block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the to-do content. + * @see block.to_do for full documentation + * @returns {Object} A to-do list block. + */ +export function toDo(options) { + return block.to_do.createBlock(options); +} + +/** + * Creates a toggle block. + * @memberof BlockShorthand + * @param {string|string[]|Object} options - A string, an array of strings, or an options object representing the toggle content. + * @see block.toggle for full documentation + * @returns {Object} A toggle block. + */ +export function toggle(options) { + return block.toggle.createBlock(options); +} + +/** + * Creates a video block. + * @memberof BlockShorthand + * @param {string|Object} options - A string representing the video URL, or an options object. + * @see block.video for full documentation + * @returns {Object|null} A video block or null if the URL is invalid. + */ +export function video(options) { + return block.video.createBlock(options); +} + +/** + * Simple function to create standard Paragraph blocks from an array of strings without any special formatting. Each Paragraph block will contain a single Rich Text Object. + * + * @param {Array} strings - an array of strings. + * @returns {Array} - array of Paragraph blocks. + */ +export function makeParagraphBlocks(strings) { + if (!Array.isArray(strings) || strings.length < 1) { + console.error( + `Invalid argument passed to makeParagraphs(). Expected a non-empty array.` + ); + console.dir(strings); + throw new Error(`Invalid argument: Expected a non-empty array.`); + } + + /* Remove non-string elements */ + const validStrings = strings.filter((string) => typeof string === "string"); + + /* Check each string's length, get a new array of strings */ + const lengthCheckedStrings = validStrings.flatMap((string) => + enforceStringLength(string) + ); + + /* Turn each string into an array with a single Rich Text Object */ + const richTextObjects = lengthCheckedStrings.map((string) => + buildRichTextObj(string) + ); + + /* Create a Paragraph block for each Rich Text Object */ + return richTextObjects.map((richText) => + block.paragraph.createBlock({ content: richText }) + ); +} diff --git a/constants.mjs b/constants.mjs new file mode 100644 index 0000000..6b831a3 --- /dev/null +++ b/constants.mjs @@ -0,0 +1,19 @@ +const CONSTANTS = { + MAX_TEXT_LENGTH: 2000, + MAX_BLOCKS: 100, + IMAGE_SUPPORT: { + FORMATS: [ + 'bmp', 'gif', 'heic', 'jpeg', 'jpg', 'png', 'svg', 'tif', 'tiff' + ] + }, + VIDEO_SUPPORT: { + FORMATS: [ + 'amv', 'asf', 'avi', 'f4v', 'flv', 'gifv', 'mkv', 'mov', 'mpg', 'mpeg', 'mpv', 'mp4', 'm4v', 'qt', 'wmv' + ], + SITES: [ + 'youtube.com' + ] + } +} + +export default CONSTANTS \ No newline at end of file diff --git a/docs/assets/anchor.js b/docs/assets/anchor.js new file mode 100644 index 0000000..1f573dc --- /dev/null +++ b/docs/assets/anchor.js @@ -0,0 +1,350 @@ +/*! + * AnchorJS - v4.0.0 - 2017-06-02 + * https://github.com/bryanbraun/anchorjs + * Copyright (c) 2017 Bryan Braun; Licensed MIT + */ +/* eslint-env amd, node */ + +// https://github.com/umdjs/umd/blob/master/templates/returnExports.js +(function (root, factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([], factory); + } else if (typeof module === 'object' && module.exports) { + // Node. Does not work with strict CommonJS, but + // only CommonJS-like environments that support module.exports, + // like Node. + module.exports = factory(); + } else { + // Browser globals (root is window) + root.AnchorJS = factory(); + root.anchors = new root.AnchorJS(); + } +})(this, function () { + 'use strict'; + function AnchorJS(options) { + this.options = options || {}; + this.elements = []; + + /** + * Assigns options to the internal options object, and provides defaults. + * @param {Object} opts - Options object + */ + function _applyRemainingDefaultOptions(opts) { + opts.icon = opts.hasOwnProperty('icon') ? opts.icon : '\ue9cb'; // Accepts characters (and also URLs?), like '#', 'ΒΆ', '❑', or 'Β§'. + opts.visible = opts.hasOwnProperty('visible') ? opts.visible : 'hover'; // Also accepts 'always' & 'touch' + opts.placement = opts.hasOwnProperty('placement') + ? opts.placement + : 'right'; // Also accepts 'left' + opts.class = opts.hasOwnProperty('class') ? opts.class : ''; // Accepts any class name. + // Using Math.floor here will ensure the value is Number-cast and an integer. + opts.truncate = opts.hasOwnProperty('truncate') + ? Math.floor(opts.truncate) + : 64; // Accepts any value that can be typecast to a number. + } + + _applyRemainingDefaultOptions(this.options); + + /** + * Checks to see if this device supports touch. Uses criteria pulled from Modernizr: + * https://github.com/Modernizr/Modernizr/blob/da22eb27631fc4957f67607fe6042e85c0a84656/feature-detects/touchevents.js#L40 + * @returns {Boolean} - true if the current device supports touch. + */ + this.isTouchDevice = function () { + return !!( + 'ontouchstart' in window || + (window.DocumentTouch && document instanceof DocumentTouch) + ); + }; + + /** + * Add anchor links to page elements. + * @param {String|Array|Nodelist} selector - A CSS selector for targeting the elements you wish to add anchor links + * to. Also accepts an array or nodeList containing the relavant elements. + * @returns {this} - The AnchorJS object + */ + this.add = function (selector) { + var elements, + elsWithIds, + idList, + elementID, + i, + index, + count, + tidyText, + newTidyText, + readableID, + anchor, + visibleOptionToUse, + indexesToDrop = []; + + // We reapply options here because somebody may have overwritten the default options object when setting options. + // For example, this overwrites all options but visible: + // + // anchors.options = { visible: 'always'; } + _applyRemainingDefaultOptions(this.options); + + visibleOptionToUse = this.options.visible; + if (visibleOptionToUse === 'touch') { + visibleOptionToUse = this.isTouchDevice() ? 'always' : 'hover'; + } + + // Provide a sensible default selector, if none is given. + if (!selector) { + selector = 'h2, h3, h4, h5, h6'; + } + + elements = _getElements(selector); + + if (elements.length === 0) { + return this; + } + + _addBaselineStyles(); + + // We produce a list of existing IDs so we don't generate a duplicate. + elsWithIds = document.querySelectorAll('[id]'); + idList = [].map.call(elsWithIds, function assign(el) { + return el.id; + }); + + for (i = 0; i < elements.length; i++) { + if (this.hasAnchorJSLink(elements[i])) { + indexesToDrop.push(i); + continue; + } + + if (elements[i].hasAttribute('id')) { + elementID = elements[i].getAttribute('id'); + } else if (elements[i].hasAttribute('data-anchor-id')) { + elementID = elements[i].getAttribute('data-anchor-id'); + } else { + tidyText = this.urlify(elements[i].textContent); + + // Compare our generated ID to existing IDs (and increment it if needed) + // before we add it to the page. + newTidyText = tidyText; + count = 0; + do { + if (index !== undefined) { + newTidyText = tidyText + '-' + count; + } + + index = idList.indexOf(newTidyText); + count += 1; + } while (index !== -1); + index = undefined; + idList.push(newTidyText); + + elements[i].setAttribute('id', newTidyText); + elementID = newTidyText; + } + + readableID = elementID.replace(/-/g, ' '); + + // The following code builds the following DOM structure in a more effiecient (albeit opaque) way. + // ''; + anchor = document.createElement('a'); + anchor.className = 'anchorjs-link ' + this.options.class; + anchor.href = '#' + elementID; + anchor.setAttribute('aria-label', 'Anchor link for: ' + readableID); + anchor.setAttribute('data-anchorjs-icon', this.options.icon); + + if (visibleOptionToUse === 'always') { + anchor.style.opacity = '1'; + } + + if (this.options.icon === '\ue9cb') { + anchor.style.font = '1em/1 anchorjs-icons'; + + // We set lineHeight = 1 here because the `anchorjs-icons` font family could otherwise affect the + // height of the heading. This isn't the case for icons with `placement: left`, so we restore + // line-height: inherit in that case, ensuring they remain positioned correctly. For more info, + // see https://github.com/bryanbraun/anchorjs/issues/39. + if (this.options.placement === 'left') { + anchor.style.lineHeight = 'inherit'; + } + } + + if (this.options.placement === 'left') { + anchor.style.position = 'absolute'; + anchor.style.marginLeft = '-1em'; + anchor.style.paddingRight = '0.5em'; + elements[i].insertBefore(anchor, elements[i].firstChild); + } else { + // if the option provided is `right` (or anything else). + anchor.style.paddingLeft = '0.375em'; + elements[i].appendChild(anchor); + } + } + + for (i = 0; i < indexesToDrop.length; i++) { + elements.splice(indexesToDrop[i] - i, 1); + } + this.elements = this.elements.concat(elements); + + return this; + }; + + /** + * Removes all anchorjs-links from elements targed by the selector. + * @param {String|Array|Nodelist} selector - A CSS selector string targeting elements with anchor links, + * OR a nodeList / array containing the DOM elements. + * @returns {this} - The AnchorJS object + */ + this.remove = function (selector) { + var index, + domAnchor, + elements = _getElements(selector); + + for (var i = 0; i < elements.length; i++) { + domAnchor = elements[i].querySelector('.anchorjs-link'); + if (domAnchor) { + // Drop the element from our main list, if it's in there. + index = this.elements.indexOf(elements[i]); + if (index !== -1) { + this.elements.splice(index, 1); + } + // Remove the anchor from the DOM. + elements[i].removeChild(domAnchor); + } + } + return this; + }; + + /** + * Removes all anchorjs links. Mostly used for tests. + */ + this.removeAll = function () { + this.remove(this.elements); + }; + + /** + * Urlify - Refine text so it makes a good ID. + * + * To do this, we remove apostrophes, replace nonsafe characters with hyphens, + * remove extra hyphens, truncate, trim hyphens, and make lowercase. + * + * @param {String} text - Any text. Usually pulled from the webpage element we are linking to. + * @returns {String} - hyphen-delimited text for use in IDs and URLs. + */ + this.urlify = function (text) { + // Regex for finding the nonsafe URL characters (many need escaping): & +$,:;=?@"#{}|^~[`%!'<>]./()*\ + var nonsafeChars = /[& +$,:;=?@"#{}|^~[`%!'<>\]\.\/\(\)\*\\]/g, + urlText; + + // The reason we include this _applyRemainingDefaultOptions is so urlify can be called independently, + // even after setting options. This can be useful for tests or other applications. + if (!this.options.truncate) { + _applyRemainingDefaultOptions(this.options); + } + + // Note: we trim hyphens after truncating because truncating can cause dangling hyphens. + // Example string: // " ⚑⚑ Don't forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." + urlText = text + .trim() // "⚑⚑ Don't forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." + .replace(/\'/gi, '') // "⚑⚑ Dont forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." + .replace(nonsafeChars, '-') // "⚑⚑-Dont-forget--URL-fragments-should-be-i18n-friendly--hyphenated--short--and-clean-" + .replace(/-{2,}/g, '-') // "⚑⚑-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated-short-and-clean-" + .substring(0, this.options.truncate) // "⚑⚑-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated-" + .replace(/^-+|-+$/gm, '') // "⚑⚑-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated" + .toLowerCase(); // "⚑⚑-dont-forget-url-fragments-should-be-i18n-friendly-hyphenated" + + return urlText; + }; + + /** + * Determines if this element already has an AnchorJS link on it. + * Uses this technique: http://stackoverflow.com/a/5898748/1154642 + * @param {HTMLElemnt} el - a DOM node + * @returns {Boolean} true/false + */ + this.hasAnchorJSLink = function (el) { + var hasLeftAnchor = + el.firstChild && + (' ' + el.firstChild.className + ' ').indexOf(' anchorjs-link ') > -1, + hasRightAnchor = + el.lastChild && + (' ' + el.lastChild.className + ' ').indexOf(' anchorjs-link ') > -1; + + return hasLeftAnchor || hasRightAnchor || false; + }; + + /** + * Turns a selector, nodeList, or array of elements into an array of elements (so we can use array methods). + * It also throws errors on any other inputs. Used to handle inputs to .add and .remove. + * @param {String|Array|Nodelist} input - A CSS selector string targeting elements with anchor links, + * OR a nodeList / array containing the DOM elements. + * @returns {Array} - An array containing the elements we want. + */ + function _getElements(input) { + var elements; + if (typeof input === 'string' || input instanceof String) { + // See https://davidwalsh.name/nodelist-array for the technique transforming nodeList -> Array. + elements = [].slice.call(document.querySelectorAll(input)); + // I checked the 'input instanceof NodeList' test in IE9 and modern browsers and it worked for me. + } else if (Array.isArray(input) || input instanceof NodeList) { + elements = [].slice.call(input); + } else { + throw new Error('The selector provided to AnchorJS was invalid.'); + } + return elements; + } + + /** + * _addBaselineStyles + * Adds baseline styles to the page, used by all AnchorJS links irregardless of configuration. + */ + function _addBaselineStyles() { + // We don't want to add global baseline styles if they've been added before. + if (document.head.querySelector('style.anchorjs') !== null) { + return; + } + + var style = document.createElement('style'), + linkRule = + ' .anchorjs-link {' + + ' opacity: 0;' + + ' text-decoration: none;' + + ' -webkit-font-smoothing: antialiased;' + + ' -moz-osx-font-smoothing: grayscale;' + + ' }', + hoverRule = + ' *:hover > .anchorjs-link,' + + ' .anchorjs-link:focus {' + + ' opacity: 1;' + + ' }', + anchorjsLinkFontFace = + ' @font-face {' + + ' font-family: "anchorjs-icons";' + // Icon from icomoon; 10px wide & 10px tall; 2 empty below & 4 above + ' src: url(data:n/a;base64,AAEAAAALAIAAAwAwT1MvMg8yG2cAAAE4AAAAYGNtYXDp3gC3AAABpAAAAExnYXNwAAAAEAAAA9wAAAAIZ2x5ZlQCcfwAAAH4AAABCGhlYWQHFvHyAAAAvAAAADZoaGVhBnACFwAAAPQAAAAkaG10eASAADEAAAGYAAAADGxvY2EACACEAAAB8AAAAAhtYXhwAAYAVwAAARgAAAAgbmFtZQGOH9cAAAMAAAAAunBvc3QAAwAAAAADvAAAACAAAQAAAAEAAHzE2p9fDzz1AAkEAAAAAADRecUWAAAAANQA6R8AAAAAAoACwAAAAAgAAgAAAAAAAAABAAADwP/AAAACgAAA/9MCrQABAAAAAAAAAAAAAAAAAAAAAwABAAAAAwBVAAIAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAMCQAGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAg//0DwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAAIAAAACgAAxAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEADAAAAAIAAgAAgAAACDpy//9//8AAAAg6cv//f///+EWNwADAAEAAAAAAAAAAAAAAAAACACEAAEAAAAAAAAAAAAAAAAxAAACAAQARAKAAsAAKwBUAAABIiYnJjQ3NzY2MzIWFxYUBwcGIicmNDc3NjQnJiYjIgYHBwYUFxYUBwYGIwciJicmNDc3NjIXFhQHBwYUFxYWMzI2Nzc2NCcmNDc2MhcWFAcHBgYjARQGDAUtLXoWOR8fORYtLTgKGwoKCjgaGg0gEhIgDXoaGgkJBQwHdR85Fi0tOAobCgoKOBoaDSASEiANehoaCQkKGwotLXoWOR8BMwUFLYEuehYXFxYugC44CQkKGwo4GkoaDQ0NDXoaShoKGwoFBe8XFi6ALjgJCQobCjgaShoNDQ0NehpKGgobCgoKLYEuehYXAAAADACWAAEAAAAAAAEACAAAAAEAAAAAAAIAAwAIAAEAAAAAAAMACAAAAAEAAAAAAAQACAAAAAEAAAAAAAUAAQALAAEAAAAAAAYACAAAAAMAAQQJAAEAEAAMAAMAAQQJAAIABgAcAAMAAQQJAAMAEAAMAAMAAQQJAAQAEAAMAAMAAQQJAAUAAgAiAAMAAQQJAAYAEAAMYW5jaG9yanM0MDBAAGEAbgBjAGgAbwByAGoAcwA0ADAAMABAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAP) format("truetype");' + + ' }', + pseudoElContent = + ' [data-anchorjs-icon]::after {' + + ' content: attr(data-anchorjs-icon);' + + ' }', + firstStyleEl; + + style.className = 'anchorjs'; + style.appendChild(document.createTextNode('')); // Necessary for Webkit. + + // We place it in the head with the other style tags, if possible, so as to + // not look out of place. We insert before the others so these styles can be + // overridden if necessary. + firstStyleEl = document.head.querySelector('[rel="stylesheet"], style'); + if (firstStyleEl === undefined) { + document.head.appendChild(style); + } else { + document.head.insertBefore(style, firstStyleEl); + } + + style.sheet.insertRule(linkRule, style.sheet.cssRules.length); + style.sheet.insertRule(hoverRule, style.sheet.cssRules.length); + style.sheet.insertRule(pseudoElContent, style.sheet.cssRules.length); + style.sheet.insertRule(anchorjsLinkFontFace, style.sheet.cssRules.length); + } + } + + return AnchorJS; +}); diff --git a/docs/assets/bass-addons.css b/docs/assets/bass-addons.css new file mode 100644 index 0000000..c27e96d --- /dev/null +++ b/docs/assets/bass-addons.css @@ -0,0 +1,12 @@ +.input { + font-family: inherit; + display: block; + width: 100%; + height: 2rem; + padding: .5rem; + margin-bottom: 1rem; + border: 1px solid #ccc; + font-size: .875rem; + border-radius: 3px; + box-sizing: border-box; +} diff --git a/docs/assets/bass.css b/docs/assets/bass.css new file mode 100644 index 0000000..2d860c5 --- /dev/null +++ b/docs/assets/bass.css @@ -0,0 +1,544 @@ +/*! Basscss | http://basscss.com | MIT License */ + +.h1{ font-size: 2rem } +.h2{ font-size: 1.5rem } +.h3{ font-size: 1.25rem } +.h4{ font-size: 1rem } +.h5{ font-size: .875rem } +.h6{ font-size: .75rem } + +.font-family-inherit{ font-family:inherit } +.font-size-inherit{ font-size:inherit } +.text-decoration-none{ text-decoration:none } + +.bold{ font-weight: bold; font-weight: bold } +.regular{ font-weight:normal } +.italic{ font-style:italic } +.caps{ text-transform:uppercase; letter-spacing: .2em; } + +.left-align{ text-align:left } +.center{ text-align:center } +.right-align{ text-align:right } +.justify{ text-align:justify } + +.nowrap{ white-space:nowrap } +.break-word{ word-wrap:break-word } + +.line-height-1{ line-height: 1 } +.line-height-2{ line-height: 1.125 } +.line-height-3{ line-height: 1.25 } +.line-height-4{ line-height: 1.5 } + +.list-style-none{ list-style:none } +.underline{ text-decoration:underline } + +.truncate{ + max-width:100%; + overflow:hidden; + text-overflow:ellipsis; + white-space:nowrap; +} + +.list-reset{ + list-style:none; + padding-left:0; +} + +.inline{ display:inline } +.block{ display:block } +.inline-block{ display:inline-block } +.table{ display:table } +.table-cell{ display:table-cell } + +.overflow-hidden{ overflow:hidden } +.overflow-scroll{ overflow:scroll } +.overflow-auto{ overflow:auto } + +.clearfix:before, +.clearfix:after{ + content:" "; + display:table +} +.clearfix:after{ clear:both } + +.left{ float:left } +.right{ float:right } + +.fit{ max-width:100% } + +.max-width-1{ max-width: 24rem } +.max-width-2{ max-width: 32rem } +.max-width-3{ max-width: 48rem } +.max-width-4{ max-width: 64rem } + +.border-box{ box-sizing:border-box } + +.align-baseline{ vertical-align:baseline } +.align-top{ vertical-align:top } +.align-middle{ vertical-align:middle } +.align-bottom{ vertical-align:bottom } + +.m0{ margin:0 } +.mt0{ margin-top:0 } +.mr0{ margin-right:0 } +.mb0{ margin-bottom:0 } +.ml0{ margin-left:0 } +.mx0{ margin-left:0; margin-right:0 } +.my0{ margin-top:0; margin-bottom:0 } + +.m1{ margin: .5rem } +.mt1{ margin-top: .5rem } +.mr1{ margin-right: .5rem } +.mb1{ margin-bottom: .5rem } +.ml1{ margin-left: .5rem } +.mx1{ margin-left: .5rem; margin-right: .5rem } +.my1{ margin-top: .5rem; margin-bottom: .5rem } + +.m2{ margin: 1rem } +.mt2{ margin-top: 1rem } +.mr2{ margin-right: 1rem } +.mb2{ margin-bottom: 1rem } +.ml2{ margin-left: 1rem } +.mx2{ margin-left: 1rem; margin-right: 1rem } +.my2{ margin-top: 1rem; margin-bottom: 1rem } + +.m3{ margin: 2rem } +.mt3{ margin-top: 2rem } +.mr3{ margin-right: 2rem } +.mb3{ margin-bottom: 2rem } +.ml3{ margin-left: 2rem } +.mx3{ margin-left: 2rem; margin-right: 2rem } +.my3{ margin-top: 2rem; margin-bottom: 2rem } + +.m4{ margin: 4rem } +.mt4{ margin-top: 4rem } +.mr4{ margin-right: 4rem } +.mb4{ margin-bottom: 4rem } +.ml4{ margin-left: 4rem } +.mx4{ margin-left: 4rem; margin-right: 4rem } +.my4{ margin-top: 4rem; margin-bottom: 4rem } + +.mxn1{ margin-left: -.5rem; margin-right: -.5rem; } +.mxn2{ margin-left: -1rem; margin-right: -1rem; } +.mxn3{ margin-left: -2rem; margin-right: -2rem; } +.mxn4{ margin-left: -4rem; margin-right: -4rem; } + +.ml-auto{ margin-left:auto } +.mr-auto{ margin-right:auto } +.mx-auto{ margin-left:auto; margin-right:auto; } + +.p0{ padding:0 } +.pt0{ padding-top:0 } +.pr0{ padding-right:0 } +.pb0{ padding-bottom:0 } +.pl0{ padding-left:0 } +.px0{ padding-left:0; padding-right:0 } +.py0{ padding-top:0; padding-bottom:0 } + +.p1{ padding: .5rem } +.pt1{ padding-top: .5rem } +.pr1{ padding-right: .5rem } +.pb1{ padding-bottom: .5rem } +.pl1{ padding-left: .5rem } +.py1{ padding-top: .5rem; padding-bottom: .5rem } +.px1{ padding-left: .5rem; padding-right: .5rem } + +.p2{ padding: 1rem } +.pt2{ padding-top: 1rem } +.pr2{ padding-right: 1rem } +.pb2{ padding-bottom: 1rem } +.pl2{ padding-left: 1rem } +.py2{ padding-top: 1rem; padding-bottom: 1rem } +.px2{ padding-left: 1rem; padding-right: 1rem } + +.p3{ padding: 2rem } +.pt3{ padding-top: 2rem } +.pr3{ padding-right: 2rem } +.pb3{ padding-bottom: 2rem } +.pl3{ padding-left: 2rem } +.py3{ padding-top: 2rem; padding-bottom: 2rem } +.px3{ padding-left: 2rem; padding-right: 2rem } + +.p4{ padding: 4rem } +.pt4{ padding-top: 4rem } +.pr4{ padding-right: 4rem } +.pb4{ padding-bottom: 4rem } +.pl4{ padding-left: 4rem } +.py4{ padding-top: 4rem; padding-bottom: 4rem } +.px4{ padding-left: 4rem; padding-right: 4rem } + +.col{ + float:left; + box-sizing:border-box; +} + +.col-right{ + float:right; + box-sizing:border-box; +} + +.col-1{ + width:8.33333%; +} + +.col-2{ + width:16.66667%; +} + +.col-3{ + width:25%; +} + +.col-4{ + width:33.33333%; +} + +.col-5{ + width:41.66667%; +} + +.col-6{ + width:50%; +} + +.col-7{ + width:58.33333%; +} + +.col-8{ + width:66.66667%; +} + +.col-9{ + width:75%; +} + +.col-10{ + width:83.33333%; +} + +.col-11{ + width:91.66667%; +} + +.col-12{ + width:100%; +} +@media (min-width: 40em){ + + .sm-col{ + float:left; + box-sizing:border-box; + } + + .sm-col-right{ + float:right; + box-sizing:border-box; + } + + .sm-col-1{ + width:8.33333%; + } + + .sm-col-2{ + width:16.66667%; + } + + .sm-col-3{ + width:25%; + } + + .sm-col-4{ + width:33.33333%; + } + + .sm-col-5{ + width:41.66667%; + } + + .sm-col-6{ + width:50%; + } + + .sm-col-7{ + width:58.33333%; + } + + .sm-col-8{ + width:66.66667%; + } + + .sm-col-9{ + width:75%; + } + + .sm-col-10{ + width:83.33333%; + } + + .sm-col-11{ + width:91.66667%; + } + + .sm-col-12{ + width:100%; + } + +} +@media (min-width: 52em){ + + .md-col{ + float:left; + box-sizing:border-box; + } + + .md-col-right{ + float:right; + box-sizing:border-box; + } + + .md-col-1{ + width:8.33333%; + } + + .md-col-2{ + width:16.66667%; + } + + .md-col-3{ + width:25%; + } + + .md-col-4{ + width:33.33333%; + } + + .md-col-5{ + width:41.66667%; + } + + .md-col-6{ + width:50%; + } + + .md-col-7{ + width:58.33333%; + } + + .md-col-8{ + width:66.66667%; + } + + .md-col-9{ + width:75%; + } + + .md-col-10{ + width:83.33333%; + } + + .md-col-11{ + width:91.66667%; + } + + .md-col-12{ + width:100%; + } + +} +@media (min-width: 64em){ + + .lg-col{ + float:left; + box-sizing:border-box; + } + + .lg-col-right{ + float:right; + box-sizing:border-box; + } + + .lg-col-1{ + width:8.33333%; + } + + .lg-col-2{ + width:16.66667%; + } + + .lg-col-3{ + width:25%; + } + + .lg-col-4{ + width:33.33333%; + } + + .lg-col-5{ + width:41.66667%; + } + + .lg-col-6{ + width:50%; + } + + .lg-col-7{ + width:58.33333%; + } + + .lg-col-8{ + width:66.66667%; + } + + .lg-col-9{ + width:75%; + } + + .lg-col-10{ + width:83.33333%; + } + + .lg-col-11{ + width:91.66667%; + } + + .lg-col-12{ + width:100%; + } + +} +.flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } + +@media (min-width: 40em){ + .sm-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } +} + +@media (min-width: 52em){ + .md-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } +} + +@media (min-width: 64em){ + .lg-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } +} + +.flex-column{ -webkit-box-orient:vertical; -webkit-box-direction:normal; -webkit-flex-direction:column; -ms-flex-direction:column; flex-direction:column } +.flex-wrap{ -webkit-flex-wrap:wrap; -ms-flex-wrap:wrap; flex-wrap:wrap } + +.items-start{ -webkit-box-align:start; -webkit-align-items:flex-start; -ms-flex-align:start; -ms-grid-row-align:flex-start; align-items:flex-start } +.items-end{ -webkit-box-align:end; -webkit-align-items:flex-end; -ms-flex-align:end; -ms-grid-row-align:flex-end; align-items:flex-end } +.items-center{ -webkit-box-align:center; -webkit-align-items:center; -ms-flex-align:center; -ms-grid-row-align:center; align-items:center } +.items-baseline{ -webkit-box-align:baseline; -webkit-align-items:baseline; -ms-flex-align:baseline; -ms-grid-row-align:baseline; align-items:baseline } +.items-stretch{ -webkit-box-align:stretch; -webkit-align-items:stretch; -ms-flex-align:stretch; -ms-grid-row-align:stretch; align-items:stretch } + +.self-start{ -webkit-align-self:flex-start; -ms-flex-item-align:start; align-self:flex-start } +.self-end{ -webkit-align-self:flex-end; -ms-flex-item-align:end; align-self:flex-end } +.self-center{ -webkit-align-self:center; -ms-flex-item-align:center; align-self:center } +.self-baseline{ -webkit-align-self:baseline; -ms-flex-item-align:baseline; align-self:baseline } +.self-stretch{ -webkit-align-self:stretch; -ms-flex-item-align:stretch; align-self:stretch } + +.justify-start{ -webkit-box-pack:start; -webkit-justify-content:flex-start; -ms-flex-pack:start; justify-content:flex-start } +.justify-end{ -webkit-box-pack:end; -webkit-justify-content:flex-end; -ms-flex-pack:end; justify-content:flex-end } +.justify-center{ -webkit-box-pack:center; -webkit-justify-content:center; -ms-flex-pack:center; justify-content:center } +.justify-between{ -webkit-box-pack:justify; -webkit-justify-content:space-between; -ms-flex-pack:justify; justify-content:space-between } +.justify-around{ -webkit-justify-content:space-around; -ms-flex-pack:distribute; justify-content:space-around } + +.content-start{ -webkit-align-content:flex-start; -ms-flex-line-pack:start; align-content:flex-start } +.content-end{ -webkit-align-content:flex-end; -ms-flex-line-pack:end; align-content:flex-end } +.content-center{ -webkit-align-content:center; -ms-flex-line-pack:center; align-content:center } +.content-between{ -webkit-align-content:space-between; -ms-flex-line-pack:justify; align-content:space-between } +.content-around{ -webkit-align-content:space-around; -ms-flex-line-pack:distribute; align-content:space-around } +.content-stretch{ -webkit-align-content:stretch; -ms-flex-line-pack:stretch; align-content:stretch } +.flex-auto{ + -webkit-box-flex:1; + -webkit-flex:1 1 auto; + -ms-flex:1 1 auto; + flex:1 1 auto; + min-width:0; + min-height:0; +} +.flex-none{ -webkit-box-flex:0; -webkit-flex:none; -ms-flex:none; flex:none } +.fs0{ flex-shrink: 0 } + +.order-0{ -webkit-box-ordinal-group:1; -webkit-order:0; -ms-flex-order:0; order:0 } +.order-1{ -webkit-box-ordinal-group:2; -webkit-order:1; -ms-flex-order:1; order:1 } +.order-2{ -webkit-box-ordinal-group:3; -webkit-order:2; -ms-flex-order:2; order:2 } +.order-3{ -webkit-box-ordinal-group:4; -webkit-order:3; -ms-flex-order:3; order:3 } +.order-last{ -webkit-box-ordinal-group:100000; -webkit-order:99999; -ms-flex-order:99999; order:99999 } + +.relative{ position:relative } +.absolute{ position:absolute } +.fixed{ position:fixed } + +.top-0{ top:0 } +.right-0{ right:0 } +.bottom-0{ bottom:0 } +.left-0{ left:0 } + +.z1{ z-index: 1 } +.z2{ z-index: 2 } +.z3{ z-index: 3 } +.z4{ z-index: 4 } + +.border{ + border-style:solid; + border-width: 1px; +} + +.border-top{ + border-top-style:solid; + border-top-width: 1px; +} + +.border-right{ + border-right-style:solid; + border-right-width: 1px; +} + +.border-bottom{ + border-bottom-style:solid; + border-bottom-width: 1px; +} + +.border-left{ + border-left-style:solid; + border-left-width: 1px; +} + +.border-none{ border:0 } + +.rounded{ border-radius: 3px } +.circle{ border-radius:50% } + +.rounded-top{ border-radius: 3px 3px 0 0 } +.rounded-right{ border-radius: 0 3px 3px 0 } +.rounded-bottom{ border-radius: 0 0 3px 3px } +.rounded-left{ border-radius: 3px 0 0 3px } + +.not-rounded{ border-radius:0 } + +.hide{ + position:absolute !important; + height:1px; + width:1px; + overflow:hidden; + clip:rect(1px, 1px, 1px, 1px); +} + +@media (max-width: 40em){ + .xs-hide{ display:none !important } +} + +@media (min-width: 40em) and (max-width: 52em){ + .sm-hide{ display:none !important } +} + +@media (min-width: 52em) and (max-width: 64em){ + .md-hide{ display:none !important } +} + +@media (min-width: 64em){ + .lg-hide{ display:none !important } +} + +.display-none{ display:none !important } + diff --git a/docs/assets/fonts/EOT/SourceCodePro-Bold.eot b/docs/assets/fonts/EOT/SourceCodePro-Bold.eot new file mode 100755 index 0000000..d24cc39 Binary files /dev/null and b/docs/assets/fonts/EOT/SourceCodePro-Bold.eot differ diff --git a/docs/assets/fonts/EOT/SourceCodePro-Regular.eot b/docs/assets/fonts/EOT/SourceCodePro-Regular.eot new file mode 100755 index 0000000..09e9473 Binary files /dev/null and b/docs/assets/fonts/EOT/SourceCodePro-Regular.eot differ diff --git a/docs/assets/fonts/LICENSE.txt b/docs/assets/fonts/LICENSE.txt new file mode 100755 index 0000000..d154618 --- /dev/null +++ b/docs/assets/fonts/LICENSE.txt @@ -0,0 +1,93 @@ +Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/docs/assets/fonts/OTF/SourceCodePro-Bold.otf b/docs/assets/fonts/OTF/SourceCodePro-Bold.otf new file mode 100755 index 0000000..f4e576c Binary files /dev/null and b/docs/assets/fonts/OTF/SourceCodePro-Bold.otf differ diff --git a/docs/assets/fonts/OTF/SourceCodePro-Regular.otf b/docs/assets/fonts/OTF/SourceCodePro-Regular.otf new file mode 100755 index 0000000..4e3b9d0 Binary files /dev/null and b/docs/assets/fonts/OTF/SourceCodePro-Regular.otf differ diff --git a/docs/assets/fonts/TTF/SourceCodePro-Bold.ttf b/docs/assets/fonts/TTF/SourceCodePro-Bold.ttf new file mode 100755 index 0000000..e0c576f Binary files /dev/null and b/docs/assets/fonts/TTF/SourceCodePro-Bold.ttf differ diff --git a/docs/assets/fonts/TTF/SourceCodePro-Regular.ttf b/docs/assets/fonts/TTF/SourceCodePro-Regular.ttf new file mode 100755 index 0000000..437f472 Binary files /dev/null and b/docs/assets/fonts/TTF/SourceCodePro-Regular.ttf differ diff --git a/docs/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff b/docs/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff new file mode 100755 index 0000000..cf96099 Binary files /dev/null and b/docs/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff differ diff --git a/docs/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff b/docs/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff new file mode 100755 index 0000000..395436e Binary files /dev/null and b/docs/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff differ diff --git a/docs/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff b/docs/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff new file mode 100755 index 0000000..c65ba84 Binary files /dev/null and b/docs/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff differ diff --git a/docs/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff b/docs/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff new file mode 100755 index 0000000..0af792a Binary files /dev/null and b/docs/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff differ diff --git a/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 b/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 new file mode 100755 index 0000000..cbe3835 Binary files /dev/null and b/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 differ diff --git a/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 b/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 new file mode 100755 index 0000000..65cd591 Binary files /dev/null and b/docs/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 differ diff --git a/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 b/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 new file mode 100755 index 0000000..b78d523 Binary files /dev/null and b/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 differ diff --git a/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 b/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 new file mode 100755 index 0000000..18d2199 Binary files /dev/null and b/docs/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 differ diff --git a/docs/assets/fonts/source-code-pro.css b/docs/assets/fonts/source-code-pro.css new file mode 100755 index 0000000..3abb4f0 --- /dev/null +++ b/docs/assets/fonts/source-code-pro.css @@ -0,0 +1,23 @@ +@font-face{ + font-family: 'Source Code Pro'; + font-weight: 400; + font-style: normal; + font-stretch: normal; + src: url('EOT/SourceCodePro-Regular.eot') format('embedded-opentype'), + url('WOFF2/TTF/SourceCodePro-Regular.ttf.woff2') format('woff2'), + url('WOFF/OTF/SourceCodePro-Regular.otf.woff') format('woff'), + url('OTF/SourceCodePro-Regular.otf') format('opentype'), + url('TTF/SourceCodePro-Regular.ttf') format('truetype'); +} + +@font-face{ + font-family: 'Source Code Pro'; + font-weight: 700; + font-style: normal; + font-stretch: normal; + src: url('EOT/SourceCodePro-Bold.eot') format('embedded-opentype'), + url('WOFF2/TTF/SourceCodePro-Bold.ttf.woff2') format('woff2'), + url('WOFF/OTF/SourceCodePro-Bold.otf.woff') format('woff'), + url('OTF/SourceCodePro-Bold.otf') format('opentype'), + url('TTF/SourceCodePro-Bold.ttf') format('truetype'); +} diff --git a/docs/assets/github.css b/docs/assets/github.css new file mode 100644 index 0000000..8852abb --- /dev/null +++ b/docs/assets/github.css @@ -0,0 +1,123 @@ +/* + +github.com style (c) Vasily Polovnyov + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + color: #333; + background: #f8f8f8; + -webkit-text-size-adjust: none; +} + +.hljs-comment, +.diff .hljs-header, +.hljs-javadoc { + color: #998; + font-style: italic; +} + +.hljs-keyword, +.css .rule .hljs-keyword, +.hljs-winutils, +.nginx .hljs-title, +.hljs-subst, +.hljs-request, +.hljs-status { + color: #1184CE; +} + +.hljs-number, +.hljs-hexcolor, +.ruby .hljs-constant { + color: #ed225d; +} + +.hljs-string, +.hljs-tag .hljs-value, +.hljs-phpdoc, +.hljs-dartdoc, +.tex .hljs-formula { + color: #ed225d; +} + +.hljs-title, +.hljs-id, +.scss .hljs-preprocessor { + color: #900; + font-weight: bold; +} + +.hljs-list .hljs-keyword, +.hljs-subst { + font-weight: normal; +} + +.hljs-class .hljs-title, +.hljs-type, +.vhdl .hljs-literal, +.tex .hljs-command { + color: #458; + font-weight: bold; +} + +.hljs-tag, +.hljs-tag .hljs-title, +.hljs-rules .hljs-property, +.django .hljs-tag .hljs-keyword { + color: #000080; + font-weight: normal; +} + +.hljs-attribute, +.hljs-variable, +.lisp .hljs-body { + color: #008080; +} + +.hljs-regexp { + color: #009926; +} + +.hljs-symbol, +.ruby .hljs-symbol .hljs-string, +.lisp .hljs-keyword, +.clojure .hljs-keyword, +.scheme .hljs-keyword, +.tex .hljs-special, +.hljs-prompt { + color: #990073; +} + +.hljs-built_in { + color: #0086b3; +} + +.hljs-preprocessor, +.hljs-pragma, +.hljs-pi, +.hljs-doctype, +.hljs-shebang, +.hljs-cdata { + color: #999; + font-weight: bold; +} + +.hljs-deletion { + background: #fdd; +} + +.hljs-addition { + background: #dfd; +} + +.diff .hljs-change { + background: #0086b3; +} + +.hljs-chunk { + color: #aaa; +} diff --git a/docs/assets/site.js b/docs/assets/site.js new file mode 100644 index 0000000..a624be7 --- /dev/null +++ b/docs/assets/site.js @@ -0,0 +1,168 @@ +/* global anchors */ + +// add anchor links to headers +anchors.options.placement = 'left'; +anchors.add('h3'); + +// Filter UI +var tocElements = document.getElementById('toc').getElementsByTagName('li'); + +document.getElementById('filter-input').addEventListener('keyup', function (e) { + var i, element, children; + + // enter key + if (e.keyCode === 13) { + // go to the first displayed item in the toc + for (i = 0; i < tocElements.length; i++) { + element = tocElements[i]; + if (!element.classList.contains('display-none')) { + location.replace(element.firstChild.href); + return e.preventDefault(); + } + } + } + + var match = function () { + return true; + }; + + var value = this.value.toLowerCase(); + + if (!value.match(/^\s*$/)) { + match = function (element) { + var html = element.firstChild.innerHTML; + return html && html.toLowerCase().indexOf(value) !== -1; + }; + } + + for (i = 0; i < tocElements.length; i++) { + element = tocElements[i]; + children = Array.from(element.getElementsByTagName('li')); + if (match(element) || children.some(match)) { + element.classList.remove('display-none'); + } else { + element.classList.add('display-none'); + } + } +}); + +var items = document.getElementsByClassName('toggle-sibling'); +for (var j = 0; j < items.length; j++) { + items[j].addEventListener('click', toggleSibling); +} + +function toggleSibling() { + var stepSibling = this.parentNode.getElementsByClassName('toggle-target')[0]; + var icon = this.getElementsByClassName('icon')[0]; + var klass = 'display-none'; + if (stepSibling.classList.contains(klass)) { + stepSibling.classList.remove(klass); + icon.innerHTML = 'β–Ύ'; + } else { + stepSibling.classList.add(klass); + icon.innerHTML = 'β–Έ'; + } +} + +function showHashTarget(targetId) { + if (targetId) { + var hashTarget = document.getElementById(targetId); + // new target is hidden + if ( + hashTarget && + hashTarget.offsetHeight === 0 && + hashTarget.parentNode.parentNode.classList.contains('display-none') + ) { + hashTarget.parentNode.parentNode.classList.remove('display-none'); + } + } +} + +function scrollIntoView(targetId) { + // Only scroll to element if we don't have a stored scroll position. + if (targetId && !history.state) { + var hashTarget = document.getElementById(targetId); + if (hashTarget) { + hashTarget.scrollIntoView(); + } + } +} + +function gotoCurrentTarget() { + showHashTarget(location.hash.substring(1)); + scrollIntoView(location.hash.substring(1)); +} + +window.addEventListener('hashchange', gotoCurrentTarget); +gotoCurrentTarget(); + +var toclinks = document.getElementsByClassName('pre-open'); +for (var k = 0; k < toclinks.length; k++) { + toclinks[k].addEventListener('mousedown', preOpen, false); +} + +function preOpen() { + showHashTarget(this.hash.substring(1)); +} + +var split_left = document.querySelector('#split-left'); +var split_right = document.querySelector('#split-right'); +var split_parent = split_left.parentNode; +var cw_with_sb = split_left.clientWidth; +split_left.style.overflow = 'hidden'; +var cw_without_sb = split_left.clientWidth; +split_left.style.overflow = ''; + +Split(['#split-left', '#split-right'], { + elementStyle: function (dimension, size, gutterSize) { + return { + 'flex-basis': 'calc(' + size + '% - ' + gutterSize + 'px)' + }; + }, + gutterStyle: function (dimension, gutterSize) { + return { + 'flex-basis': gutterSize + 'px' + }; + }, + gutterSize: 20, + sizes: [33, 67] +}); + +// Chrome doesn't remember scroll position properly so do it ourselves. +// Also works on Firefox and Edge. + +function updateState() { + history.replaceState( + { + left_top: split_left.scrollTop, + right_top: split_right.scrollTop + }, + document.title + ); +} + +function loadState(ev) { + if (ev) { + // Edge doesn't replace change history.state on popstate. + history.replaceState(ev.state, document.title); + } + if (history.state) { + split_left.scrollTop = history.state.left_top; + split_right.scrollTop = history.state.right_top; + } +} + +window.addEventListener('load', function () { + // Restore after Firefox scrolls to hash. + setTimeout(function () { + loadState(); + // Update with initial scroll position. + updateState(); + // Update scroll positions only after we've loaded because Firefox + // emits an initial scroll event with 0. + split_left.addEventListener('scroll', updateState); + split_right.addEventListener('scroll', updateState); + }, 1); +}); + +window.addEventListener('popstate', loadState); diff --git a/docs/assets/split.css b/docs/assets/split.css new file mode 100644 index 0000000..2d7779e --- /dev/null +++ b/docs/assets/split.css @@ -0,0 +1,15 @@ +.gutter { + background-color: #f5f5f5; + background-repeat: no-repeat; + background-position: 50%; +} + +.gutter.gutter-vertical { + background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAFAQMAAABo7865AAAABlBMVEVHcEzMzMzyAv2sAAAAAXRSTlMAQObYZgAAABBJREFUeF5jOAMEEAIEEFwAn3kMwcB6I2AAAAAASUVORK5CYII='); + cursor: ns-resize; +} + +.gutter.gutter-horizontal { + background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAIklEQVQoU2M4c+bMfxAGAgYYmwGrIIiDjrELjpo5aiZeMwF+yNnOs5KSvgAAAABJRU5ErkJggg=='); + cursor: ew-resize; +} diff --git a/docs/assets/split.js b/docs/assets/split.js new file mode 100644 index 0000000..71f9a60 --- /dev/null +++ b/docs/assets/split.js @@ -0,0 +1,782 @@ +/*! Split.js - v1.5.11 */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.Split = factory()); +}(this, (function () { 'use strict'; + + // The programming goals of Split.js are to deliver readable, understandable and + // maintainable code, while at the same time manually optimizing for tiny minified file size, + // browser compatibility without additional requirements, graceful fallback (IE8 is supported) + // and very few assumptions about the user's page layout. + var global = window; + var document = global.document; + + // Save a couple long function names that are used frequently. + // This optimization saves around 400 bytes. + var addEventListener = 'addEventListener'; + var removeEventListener = 'removeEventListener'; + var getBoundingClientRect = 'getBoundingClientRect'; + var gutterStartDragging = '_a'; + var aGutterSize = '_b'; + var bGutterSize = '_c'; + var HORIZONTAL = 'horizontal'; + var NOOP = function () { return false; }; + + // Figure out if we're in IE8 or not. IE8 will still render correctly, + // but will be static instead of draggable. + var isIE8 = global.attachEvent && !global[addEventListener]; + + // Helper function determines which prefixes of CSS calc we need. + // We only need to do this once on startup, when this anonymous function is called. + // + // Tests -webkit, -moz and -o prefixes. Modified from StackOverflow: + // http://stackoverflow.com/questions/16625140/js-feature-detection-to-detect-the-usage-of-webkit-calc-over-calc/16625167#16625167 + var calc = (['', '-webkit-', '-moz-', '-o-'] + .filter(function (prefix) { + var el = document.createElement('div'); + el.style.cssText = "width:" + prefix + "calc(9px)"; + + return !!el.style.length + }) + .shift()) + "calc"; + + // Helper function checks if its argument is a string-like type + var isString = function (v) { return typeof v === 'string' || v instanceof String; }; + + // Helper function allows elements and string selectors to be used + // interchangeably. In either case an element is returned. This allows us to + // do `Split([elem1, elem2])` as well as `Split(['#id1', '#id2'])`. + var elementOrSelector = function (el) { + if (isString(el)) { + var ele = document.querySelector(el); + if (!ele) { + throw new Error(("Selector " + el + " did not match a DOM element")) + } + return ele + } + + return el + }; + + // Helper function gets a property from the properties object, with a default fallback + var getOption = function (options, propName, def) { + var value = options[propName]; + if (value !== undefined) { + return value + } + return def + }; + + var getGutterSize = function (gutterSize, isFirst, isLast, gutterAlign) { + if (isFirst) { + if (gutterAlign === 'end') { + return 0 + } + if (gutterAlign === 'center') { + return gutterSize / 2 + } + } else if (isLast) { + if (gutterAlign === 'start') { + return 0 + } + if (gutterAlign === 'center') { + return gutterSize / 2 + } + } + + return gutterSize + }; + + // Default options + var defaultGutterFn = function (i, gutterDirection) { + var gut = document.createElement('div'); + gut.className = "gutter gutter-" + gutterDirection; + return gut + }; + + var defaultElementStyleFn = function (dim, size, gutSize) { + var style = {}; + + if (!isString(size)) { + if (!isIE8) { + style[dim] = calc + "(" + size + "% - " + gutSize + "px)"; + } else { + style[dim] = size + "%"; + } + } else { + style[dim] = size; + } + + return style + }; + + var defaultGutterStyleFn = function (dim, gutSize) { + var obj; + + return (( obj = {}, obj[dim] = (gutSize + "px"), obj )); + }; + + // The main function to initialize a split. Split.js thinks about each pair + // of elements as an independant pair. Dragging the gutter between two elements + // only changes the dimensions of elements in that pair. This is key to understanding + // how the following functions operate, since each function is bound to a pair. + // + // A pair object is shaped like this: + // + // { + // a: DOM element, + // b: DOM element, + // aMin: Number, + // bMin: Number, + // dragging: Boolean, + // parent: DOM element, + // direction: 'horizontal' | 'vertical' + // } + // + // The basic sequence: + // + // 1. Set defaults to something sane. `options` doesn't have to be passed at all. + // 2. Initialize a bunch of strings based on the direction we're splitting. + // A lot of the behavior in the rest of the library is paramatized down to + // rely on CSS strings and classes. + // 3. Define the dragging helper functions, and a few helpers to go with them. + // 4. Loop through the elements while pairing them off. Every pair gets an + // `pair` object and a gutter. + // 5. Actually size the pair elements, insert gutters and attach event listeners. + var Split = function (idsOption, options) { + if ( options === void 0 ) options = {}; + + var ids = idsOption; + var dimension; + var clientAxis; + var position; + var positionEnd; + var clientSize; + var elements; + + // Allow HTMLCollection to be used as an argument when supported + if (Array.from) { + ids = Array.from(ids); + } + + // All DOM elements in the split should have a common parent. We can grab + // the first elements parent and hope users read the docs because the + // behavior will be whacky otherwise. + var firstElement = elementOrSelector(ids[0]); + var parent = firstElement.parentNode; + var parentStyle = getComputedStyle ? getComputedStyle(parent) : null; + var parentFlexDirection = parentStyle ? parentStyle.flexDirection : null; + + // Set default options.sizes to equal percentages of the parent element. + var sizes = getOption(options, 'sizes') || ids.map(function () { return 100 / ids.length; }); + + // Standardize minSize to an array if it isn't already. This allows minSize + // to be passed as a number. + var minSize = getOption(options, 'minSize', 100); + var minSizes = Array.isArray(minSize) ? minSize : ids.map(function () { return minSize; }); + + // Get other options + var expandToMin = getOption(options, 'expandToMin', false); + var gutterSize = getOption(options, 'gutterSize', 10); + var gutterAlign = getOption(options, 'gutterAlign', 'center'); + var snapOffset = getOption(options, 'snapOffset', 30); + var dragInterval = getOption(options, 'dragInterval', 1); + var direction = getOption(options, 'direction', HORIZONTAL); + var cursor = getOption( + options, + 'cursor', + direction === HORIZONTAL ? 'col-resize' : 'row-resize' + ); + var gutter = getOption(options, 'gutter', defaultGutterFn); + var elementStyle = getOption( + options, + 'elementStyle', + defaultElementStyleFn + ); + var gutterStyle = getOption(options, 'gutterStyle', defaultGutterStyleFn); + + // 2. Initialize a bunch of strings based on the direction we're splitting. + // A lot of the behavior in the rest of the library is paramatized down to + // rely on CSS strings and classes. + if (direction === HORIZONTAL) { + dimension = 'width'; + clientAxis = 'clientX'; + position = 'left'; + positionEnd = 'right'; + clientSize = 'clientWidth'; + } else if (direction === 'vertical') { + dimension = 'height'; + clientAxis = 'clientY'; + position = 'top'; + positionEnd = 'bottom'; + clientSize = 'clientHeight'; + } + + // 3. Define the dragging helper functions, and a few helpers to go with them. + // Each helper is bound to a pair object that contains its metadata. This + // also makes it easy to store references to listeners that that will be + // added and removed. + // + // Even though there are no other functions contained in them, aliasing + // this to self saves 50 bytes or so since it's used so frequently. + // + // The pair object saves metadata like dragging state, position and + // event listener references. + + function setElementSize(el, size, gutSize, i) { + // Split.js allows setting sizes via numbers (ideally), or if you must, + // by string, like '300px'. This is less than ideal, because it breaks + // the fluid layout that `calc(% - px)` provides. You're on your own if you do that, + // make sure you calculate the gutter size by hand. + var style = elementStyle(dimension, size, gutSize, i); + + Object.keys(style).forEach(function (prop) { + // eslint-disable-next-line no-param-reassign + el.style[prop] = style[prop]; + }); + } + + function setGutterSize(gutterElement, gutSize, i) { + var style = gutterStyle(dimension, gutSize, i); + + Object.keys(style).forEach(function (prop) { + // eslint-disable-next-line no-param-reassign + gutterElement.style[prop] = style[prop]; + }); + } + + function getSizes() { + return elements.map(function (element) { return element.size; }) + } + + // Supports touch events, but not multitouch, so only the first + // finger `touches[0]` is counted. + function getMousePosition(e) { + if ('touches' in e) { return e.touches[0][clientAxis] } + return e[clientAxis] + } + + // Actually adjust the size of elements `a` and `b` to `offset` while dragging. + // calc is used to allow calc(percentage + gutterpx) on the whole split instance, + // which allows the viewport to be resized without additional logic. + // Element a's size is the same as offset. b's size is total size - a size. + // Both sizes are calculated from the initial parent percentage, + // then the gutter size is subtracted. + function adjust(offset) { + var a = elements[this.a]; + var b = elements[this.b]; + var percentage = a.size + b.size; + + a.size = (offset / this.size) * percentage; + b.size = percentage - (offset / this.size) * percentage; + + setElementSize(a.element, a.size, this[aGutterSize], a.i); + setElementSize(b.element, b.size, this[bGutterSize], b.i); + } + + // drag, where all the magic happens. The logic is really quite simple: + // + // 1. Ignore if the pair is not dragging. + // 2. Get the offset of the event. + // 3. Snap offset to min if within snappable range (within min + snapOffset). + // 4. Actually adjust each element in the pair to offset. + // + // --------------------------------------------------------------------- + // | | <- a.minSize || b.minSize -> | | + // | | | <- this.snapOffset || this.snapOffset -> | | | + // | | | || | | | + // | | | || | | | + // --------------------------------------------------------------------- + // | <- this.start this.size -> | + function drag(e) { + var offset; + var a = elements[this.a]; + var b = elements[this.b]; + + if (!this.dragging) { return } + + // Get the offset of the event from the first side of the + // pair `this.start`. Then offset by the initial position of the + // mouse compared to the gutter size. + offset = + getMousePosition(e) - + this.start + + (this[aGutterSize] - this.dragOffset); + + if (dragInterval > 1) { + offset = Math.round(offset / dragInterval) * dragInterval; + } + + // If within snapOffset of min or max, set offset to min or max. + // snapOffset buffers a.minSize and b.minSize, so logic is opposite for both. + // Include the appropriate gutter sizes to prevent overflows. + if (offset <= a.minSize + snapOffset + this[aGutterSize]) { + offset = a.minSize + this[aGutterSize]; + } else if ( + offset >= + this.size - (b.minSize + snapOffset + this[bGutterSize]) + ) { + offset = this.size - (b.minSize + this[bGutterSize]); + } + + // Actually adjust the size. + adjust.call(this, offset); + + // Call the drag callback continously. Don't do anything too intensive + // in this callback. + getOption(options, 'onDrag', NOOP)(); + } + + // Cache some important sizes when drag starts, so we don't have to do that + // continously: + // + // `size`: The total size of the pair. First + second + first gutter + second gutter. + // `start`: The leading side of the first element. + // + // ------------------------------------------------ + // | aGutterSize -> ||| | + // | ||| | + // | ||| | + // | ||| <- bGutterSize | + // ------------------------------------------------ + // | <- start size -> | + function calculateSizes() { + // Figure out the parent size minus padding. + var a = elements[this.a].element; + var b = elements[this.b].element; + + var aBounds = a[getBoundingClientRect](); + var bBounds = b[getBoundingClientRect](); + + this.size = + aBounds[dimension] + + bBounds[dimension] + + this[aGutterSize] + + this[bGutterSize]; + this.start = aBounds[position]; + this.end = aBounds[positionEnd]; + } + + function innerSize(element) { + // Return nothing if getComputedStyle is not supported (< IE9) + // Or if parent element has no layout yet + if (!getComputedStyle) { return null } + + var computedStyle = getComputedStyle(element); + + if (!computedStyle) { return null } + + var size = element[clientSize]; + + if (size === 0) { return null } + + if (direction === HORIZONTAL) { + size -= + parseFloat(computedStyle.paddingLeft) + + parseFloat(computedStyle.paddingRight); + } else { + size -= + parseFloat(computedStyle.paddingTop) + + parseFloat(computedStyle.paddingBottom); + } + + return size + } + + // When specifying percentage sizes that are less than the computed + // size of the element minus the gutter, the lesser percentages must be increased + // (and decreased from the other elements) to make space for the pixels + // subtracted by the gutters. + function trimToMin(sizesToTrim) { + // Try to get inner size of parent element. + // If it's no supported, return original sizes. + var parentSize = innerSize(parent); + if (parentSize === null) { + return sizesToTrim + } + + if (minSizes.reduce(function (a, b) { return a + b; }, 0) > parentSize) { + return sizesToTrim + } + + // Keep track of the excess pixels, the amount of pixels over the desired percentage + // Also keep track of the elements with pixels to spare, to decrease after if needed + var excessPixels = 0; + var toSpare = []; + + var pixelSizes = sizesToTrim.map(function (size, i) { + // Convert requested percentages to pixel sizes + var pixelSize = (parentSize * size) / 100; + var elementGutterSize = getGutterSize( + gutterSize, + i === 0, + i === sizesToTrim.length - 1, + gutterAlign + ); + var elementMinSize = minSizes[i] + elementGutterSize; + + // If element is too smal, increase excess pixels by the difference + // and mark that it has no pixels to spare + if (pixelSize < elementMinSize) { + excessPixels += elementMinSize - pixelSize; + toSpare.push(0); + return elementMinSize + } + + // Otherwise, mark the pixels it has to spare and return it's original size + toSpare.push(pixelSize - elementMinSize); + return pixelSize + }); + + // If nothing was adjusted, return the original sizes + if (excessPixels === 0) { + return sizesToTrim + } + + return pixelSizes.map(function (pixelSize, i) { + var newPixelSize = pixelSize; + + // While there's still pixels to take, and there's enough pixels to spare, + // take as many as possible up to the total excess pixels + if (excessPixels > 0 && toSpare[i] - excessPixels > 0) { + var takenPixels = Math.min( + excessPixels, + toSpare[i] - excessPixels + ); + + // Subtract the amount taken for the next iteration + excessPixels -= takenPixels; + newPixelSize = pixelSize - takenPixels; + } + + // Return the pixel size adjusted as a percentage + return (newPixelSize / parentSize) * 100 + }) + } + + // stopDragging is very similar to startDragging in reverse. + function stopDragging() { + var self = this; + var a = elements[self.a].element; + var b = elements[self.b].element; + + if (self.dragging) { + getOption(options, 'onDragEnd', NOOP)(getSizes()); + } + + self.dragging = false; + + // Remove the stored event listeners. This is why we store them. + global[removeEventListener]('mouseup', self.stop); + global[removeEventListener]('touchend', self.stop); + global[removeEventListener]('touchcancel', self.stop); + global[removeEventListener]('mousemove', self.move); + global[removeEventListener]('touchmove', self.move); + + // Clear bound function references + self.stop = null; + self.move = null; + + a[removeEventListener]('selectstart', NOOP); + a[removeEventListener]('dragstart', NOOP); + b[removeEventListener]('selectstart', NOOP); + b[removeEventListener]('dragstart', NOOP); + + a.style.userSelect = ''; + a.style.webkitUserSelect = ''; + a.style.MozUserSelect = ''; + a.style.pointerEvents = ''; + + b.style.userSelect = ''; + b.style.webkitUserSelect = ''; + b.style.MozUserSelect = ''; + b.style.pointerEvents = ''; + + self.gutter.style.cursor = ''; + self.parent.style.cursor = ''; + document.body.style.cursor = ''; + } + + // startDragging calls `calculateSizes` to store the inital size in the pair object. + // It also adds event listeners for mouse/touch events, + // and prevents selection while dragging so avoid the selecting text. + function startDragging(e) { + // Right-clicking can't start dragging. + if ('button' in e && e.button !== 0) { + return + } + + // Alias frequently used variables to save space. 200 bytes. + var self = this; + var a = elements[self.a].element; + var b = elements[self.b].element; + + // Call the onDragStart callback. + if (!self.dragging) { + getOption(options, 'onDragStart', NOOP)(getSizes()); + } + + // Don't actually drag the element. We emulate that in the drag function. + e.preventDefault(); + + // Set the dragging property of the pair object. + self.dragging = true; + + // Create two event listeners bound to the same pair object and store + // them in the pair object. + self.move = drag.bind(self); + self.stop = stopDragging.bind(self); + + // All the binding. `window` gets the stop events in case we drag out of the elements. + global[addEventListener]('mouseup', self.stop); + global[addEventListener]('touchend', self.stop); + global[addEventListener]('touchcancel', self.stop); + global[addEventListener]('mousemove', self.move); + global[addEventListener]('touchmove', self.move); + + // Disable selection. Disable! + a[addEventListener]('selectstart', NOOP); + a[addEventListener]('dragstart', NOOP); + b[addEventListener]('selectstart', NOOP); + b[addEventListener]('dragstart', NOOP); + + a.style.userSelect = 'none'; + a.style.webkitUserSelect = 'none'; + a.style.MozUserSelect = 'none'; + a.style.pointerEvents = 'none'; + + b.style.userSelect = 'none'; + b.style.webkitUserSelect = 'none'; + b.style.MozUserSelect = 'none'; + b.style.pointerEvents = 'none'; + + // Set the cursor at multiple levels + self.gutter.style.cursor = cursor; + self.parent.style.cursor = cursor; + document.body.style.cursor = cursor; + + // Cache the initial sizes of the pair. + calculateSizes.call(self); + + // Determine the position of the mouse compared to the gutter + self.dragOffset = getMousePosition(e) - self.end; + } + + // adjust sizes to ensure percentage is within min size and gutter. + sizes = trimToMin(sizes); + + // 5. Create pair and element objects. Each pair has an index reference to + // elements `a` and `b` of the pair (first and second elements). + // Loop through the elements while pairing them off. Every pair gets a + // `pair` object and a gutter. + // + // Basic logic: + // + // - Starting with the second element `i > 0`, create `pair` objects with + // `a = i - 1` and `b = i` + // - Set gutter sizes based on the _pair_ being first/last. The first and last + // pair have gutterSize / 2, since they only have one half gutter, and not two. + // - Create gutter elements and add event listeners. + // - Set the size of the elements, minus the gutter sizes. + // + // ----------------------------------------------------------------------- + // | i=0 | i=1 | i=2 | i=3 | + // | | | | | + // | pair 0 pair 1 pair 2 | + // | | | | | + // ----------------------------------------------------------------------- + var pairs = []; + elements = ids.map(function (id, i) { + // Create the element object. + var element = { + element: elementOrSelector(id), + size: sizes[i], + minSize: minSizes[i], + i: i, + }; + + var pair; + + if (i > 0) { + // Create the pair object with its metadata. + pair = { + a: i - 1, + b: i, + dragging: false, + direction: direction, + parent: parent, + }; + + pair[aGutterSize] = getGutterSize( + gutterSize, + i - 1 === 0, + false, + gutterAlign + ); + pair[bGutterSize] = getGutterSize( + gutterSize, + false, + i === ids.length - 1, + gutterAlign + ); + + // if the parent has a reverse flex-direction, switch the pair elements. + if ( + parentFlexDirection === 'row-reverse' || + parentFlexDirection === 'column-reverse' + ) { + var temp = pair.a; + pair.a = pair.b; + pair.b = temp; + } + } + + // Determine the size of the current element. IE8 is supported by + // staticly assigning sizes without draggable gutters. Assigns a string + // to `size`. + // + // IE9 and above + if (!isIE8) { + // Create gutter elements for each pair. + if (i > 0) { + var gutterElement = gutter(i, direction, element.element); + setGutterSize(gutterElement, gutterSize, i); + + // Save bound event listener for removal later + pair[gutterStartDragging] = startDragging.bind(pair); + + // Attach bound event listener + gutterElement[addEventListener]( + 'mousedown', + pair[gutterStartDragging] + ); + gutterElement[addEventListener]( + 'touchstart', + pair[gutterStartDragging] + ); + + parent.insertBefore(gutterElement, element.element); + + pair.gutter = gutterElement; + } + } + + setElementSize( + element.element, + element.size, + getGutterSize( + gutterSize, + i === 0, + i === ids.length - 1, + gutterAlign + ), + i + ); + + // After the first iteration, and we have a pair object, append it to the + // list of pairs. + if (i > 0) { + pairs.push(pair); + } + + return element + }); + + function adjustToMin(element) { + var isLast = element.i === pairs.length; + var pair = isLast ? pairs[element.i - 1] : pairs[element.i]; + + calculateSizes.call(pair); + + var size = isLast + ? pair.size - element.minSize - pair[bGutterSize] + : element.minSize + pair[aGutterSize]; + + adjust.call(pair, size); + } + + elements.forEach(function (element) { + var computedSize = element.element[getBoundingClientRect]()[dimension]; + + if (computedSize < element.minSize) { + if (expandToMin) { + adjustToMin(element); + } else { + // eslint-disable-next-line no-param-reassign + element.minSize = computedSize; + } + } + }); + + function setSizes(newSizes) { + var trimmed = trimToMin(newSizes); + trimmed.forEach(function (newSize, i) { + if (i > 0) { + var pair = pairs[i - 1]; + + var a = elements[pair.a]; + var b = elements[pair.b]; + + a.size = trimmed[i - 1]; + b.size = newSize; + + setElementSize(a.element, a.size, pair[aGutterSize], a.i); + setElementSize(b.element, b.size, pair[bGutterSize], b.i); + } + }); + } + + function destroy(preserveStyles, preserveGutter) { + pairs.forEach(function (pair) { + if (preserveGutter !== true) { + pair.parent.removeChild(pair.gutter); + } else { + pair.gutter[removeEventListener]( + 'mousedown', + pair[gutterStartDragging] + ); + pair.gutter[removeEventListener]( + 'touchstart', + pair[gutterStartDragging] + ); + } + + if (preserveStyles !== true) { + var style = elementStyle( + dimension, + pair.a.size, + pair[aGutterSize] + ); + + Object.keys(style).forEach(function (prop) { + elements[pair.a].element.style[prop] = ''; + elements[pair.b].element.style[prop] = ''; + }); + } + }); + } + + if (isIE8) { + return { + setSizes: setSizes, + destroy: destroy, + } + } + + return { + setSizes: setSizes, + getSizes: getSizes, + collapse: function collapse(i) { + adjustToMin(elements[i]); + }, + destroy: destroy, + parent: parent, + pairs: pairs, + } + }; + + return Split; + +}))); diff --git a/docs/assets/style.css b/docs/assets/style.css new file mode 100644 index 0000000..0618f43 --- /dev/null +++ b/docs/assets/style.css @@ -0,0 +1,147 @@ +.documentation { + font-family: Helvetica, sans-serif; + color: #666; + line-height: 1.5; + background: #f5f5f5; +} + +.black { + color: #666; +} + +.bg-white { + background-color: #fff; +} + +h4 { + margin: 20px 0 10px 0; +} + +.documentation h3 { + color: #000; +} + +.border-bottom { + border-color: #ddd; +} + +a { + color: #1184ce; + text-decoration: none; +} + +.documentation a[href]:hover { + text-decoration: underline; +} + +a:hover { + cursor: pointer; +} + +.py1-ul li { + padding: 5px 0; +} + +.max-height-100 { + max-height: 100%; +} + +.height-viewport-100 { + height: 100vh; +} + +section:target h3 { + font-weight: 700; +} + +.documentation td, +.documentation th { + padding: 0.25rem 0.25rem; +} + +h1:hover .anchorjs-link, +h2:hover .anchorjs-link, +h3:hover .anchorjs-link, +h4:hover .anchorjs-link { + opacity: 1; +} + +.fix-3 { + width: 25%; + max-width: 244px; +} + +.fix-3 { + width: 25%; + max-width: 244px; +} + +@media (min-width: 52em) { + .fix-margin-3 { + margin-left: 25%; + } +} + +.pre, +pre, +code, +.code { + font-family: Source Code Pro, Menlo, Consolas, Liberation Mono, monospace; + font-size: 14px; +} + +.fill-light { + background: #f9f9f9; +} + +.width2 { + width: 1rem; +} + +.input { + font-family: inherit; + display: block; + width: 100%; + height: 2rem; + padding: 0.5rem; + margin-bottom: 1rem; + border: 1px solid #ccc; + font-size: 0.875rem; + border-radius: 3px; + box-sizing: border-box; +} + +table { + border-collapse: collapse; +} + +.prose table th, +.prose table td { + text-align: left; + padding: 8px; + border: 1px solid #ddd; +} + +.prose table th:nth-child(1) { + border-right: none; +} +.prose table th:nth-child(2) { + border-left: none; +} + +.prose table { + border: 1px solid #ddd; +} + +.prose-big { + font-size: 18px; + line-height: 30px; +} + +.quiet { + opacity: 0.7; +} + +.minishadow { + box-shadow: 2px 2px 10px #f3f3f3; +} diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..c27e96d --- /dev/null +++ b/docs/index.html @@ -0,0 +1,12 @@ +.input { + font-family: inherit; + display: block; + width: 100%; + height: 2rem; + padding: .5rem; + margin-bottom: 1rem; + border: 1px solid #ccc; + font-size: .875rem; + border-radius: 3px; + box-sizing: border-box; +} diff --git a/emoji-and-files.mjs b/emoji-and-files.mjs new file mode 100644 index 0000000..72f72d3 --- /dev/null +++ b/emoji-and-files.mjs @@ -0,0 +1,66 @@ +import { isSingleEmoji, isValidURL, validateImageURL } from "./utils.mjs" + +/** + * + * @param {string} value - either an emoji character or a URL for an externally-hosted image file. + * @returns {Object} - An object representing the icon. + */ +export function setIcon(value) { + if (typeof value !== "string") { + return {} + } + + const isEmoji = isSingleEmoji(value) + const isImageURL = validateImageURL(value) + + if (isImageURL) { + return createExternal(value) + } else if (isEmoji) { + return createEmoji(value) + } else { + return undefined + } +} + +/** + * Creates a representation of an external link. + * + * @param {string} url - The URL of the external link. + * @returns {Object} An object containing the external URL. + */ +export function createExternal(url) { + return { + type: "external", + external: { + url: url + } + } +} + +/** + * Creates a representation of an emoji. + * + * @param {string} emoji - The emoji character. + * @returns {Object} An object containing the emoji. + */ +export function createEmoji(emoji) { + return { + type: "emoji", + emoji: emoji + } +} + +/** + * Creates a representation of a file link. + * + * @param {string} url - The URL of the file. + * @returns {Object} An object containing the file URL. + */ +function createFile(url) { + return { + type: "file", + file: { + url: url + } + } +} \ No newline at end of file diff --git a/guides/Factory Function.md b/guides/Factory Function.md new file mode 100644 index 0000000..8266e25 --- /dev/null +++ b/guides/Factory Function.md @@ -0,0 +1,105 @@ +# Quick Guide: Using the createNotion Factory Function + +The `createNotion` factory function provides a powerful interface for quickly creating Notion pages, block arrays, or property objects. Here's how to use it: + +## Basic Usage + +Import and create a builder instance: + +```javascript +import NotionHelper from "notion-helper"; +const { createNotion } = NotionHelper; +const notion = createNotion(); +``` + +Chain methods to build your page or block structure: + +```js +notion + .dbId("your-database-id") + .title("Page Title", "My New Page") + .paragraph("This is a paragraph.") + .build(); +``` + +The build() method returns an object with content and additionalBlocks properties. + +## Examples + +### Simple Example: Creating a basic page + +```js +const notion = createNotion(); + +const result = notion + .dbId('your-database-id') + .title('Page Title', 'My First Notion Page') + .richText('Description', 'This is a page created with the Notion builder.') + .date('Due Date', '2023-12-31') + .heading1('Welcome to My Page') + .paragraph('This is the first paragraph of my page.') + .bulletedListItem('First item in a list') + .bulletedListItem('Second item in a list') + .build(); + +console.log(result.content); +``` + +### Block Nesting Example + +```js +const notion = createNotion(); + +const result = notion + .dbId('your-database-id') + .title('Page Title', 'Nested Blocks Example') + .heading1('Top Level Heading') + .paragraph('This is a top-level paragraph.') + .startParent('toggle', 'Click to expand') + .paragraph('This paragraph is inside the toggle.') + .startParent('bulleted_list_item', 'Nested list') + .paragraph('This paragraph is inside a bullet point.') + .endParent() + .paragraph('Back to toggle level.') + .endParent() + .paragraph('Back to top level.') + .build(); + +console.log(result.content); +``` + +### Chaining with Input Data + +```js +const notion = createNotion(); + +const todoItems = [ + { task: 'Buy groceries', due: '2023-06-01', status: 'Not started' }, + { task: 'Finish project', due: '2023-06-15', status: 'In progress' }, + { task: 'Call mom', due: '2023-06-02', status: 'Not started' }, +]; + +const result = notion + .dbId('your-database-id') + .title('Page Title', 'My Todo List') + .heading1('Tasks') + .paragraph('Here are my upcoming tasks:'); + +todoItems.forEach(item => { + notion + .toDo(item.task) + .date('Due Date', item.due) + .select('Status', item.status); +}); + +const finalResult = notion.build(); + +console.log(finalResult.content); +``` + +Remember: + +- Use startParent() and endParent() for nested blocks. +- The build() method returns the final result and resets the builder. +- Check result.additionalBlocks for any blocks exceeding the maximum limit per request. +- Refer to the specific block type documentation for detailed options. \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..c27e96d --- /dev/null +++ b/index.html @@ -0,0 +1,12 @@ +.input { + font-family: inherit; + display: block; + width: 100%; + height: 2rem; + padding: .5rem; + margin-bottom: 1rem; + border: 1px solid #ccc; + font-size: .875rem; + border-radius: 3px; + box-sizing: border-box; +} diff --git a/index.mjs b/index.mjs new file mode 100644 index 0000000..12ca59f --- /dev/null +++ b/index.mjs @@ -0,0 +1,88 @@ +import { buildRichTextObj } from "./rich-text.mjs"; +import { + block, + makeParagraphBlocks, + bookmark, + bulletedListItem, + bullet, + callout, + code, + divider, + embed, + file, + heading1, + heading2, + heading3, + image, + numberedListItem, + num, + paragraph, + pdf, + quote, + table, + tableRow, + tableOfContents, + toDo, + toggle, + video +} from "./blocks.mjs" +import { setIcon } from "./emoji-and-files.mjs"; +import { page_meta, page_props, parentDb, parentPage, pageId, blockId, propertyId, cover, icon, title, richText, checkbox, date, email, files, multiSelect, number, people, phoneNumber, relation, select, status, url } from "./page-meta.mjs"; +import { quickPages, createNotion } from "./pages.mjs"; + +const NotionHelper = { + buildRichTextObj, + makeParagraphBlocks, + block, + setIcon, + page_meta, + page_props, + quickPages, + createNotion, + parentDb, + parentPage, + pageId, + blockId, + propertyId, + cover, + icon, + title, + richText, + checkbox, + date, + email, + files, + multiSelect, + number, + people, + phoneNumber, + relation, + select, + status, + url, + bookmark, + bulletedListItem, + bullet, + callout, + code, + divider, + embed, + file, + heading1, + heading2, + heading3, + image, + numberedListItem, + num, + paragraph, + pdf, + quote, + table, + tableRow, + tableOfContents, + toDo, + toggle, + video +} + +export default NotionHelper \ No newline at end of file diff --git a/license.md b/license.md new file mode 100644 index 0000000..2f8114b --- /dev/null +++ b/license.md @@ -0,0 +1,7 @@ +Copyright (c) 2024 Thomas Frank (thomas@thomasjfrank.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the β€œSoftware”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED β€œAS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..20932fe --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "notion-helper", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..15c48e5 --- /dev/null +++ b/package.json @@ -0,0 +1,24 @@ +{ + "name": "notion-helper", + "description": "A library of functions for working more easily with the Notion API", + "version": "1.1.18", + "type": "module", + "main": "index.mjs", + "devDependencies": {}, + "author": "Thomas Frank (https://thomasjfrank.com)", + "license": "MIT", + "keywords": [ + "notion", + "notion api", + "notionapi", + "notion-api" + ], + "repository": { + "type": "git", + "url": "https://github.com/TomFrankly/notion-helper" + }, + "scripts": { + "docs": "documentation build *.mjs -f html --github -o docs" + }, + "homepage": "https://github.com/TomFrankly/notion-helper" +} diff --git a/page-meta.mjs b/page-meta.mjs new file mode 100644 index 0000000..8082ed7 --- /dev/null +++ b/page-meta.mjs @@ -0,0 +1,824 @@ +import { setIcon } from "./emoji-and-files.mjs"; +import { enforceRichText } from "./rich-text.mjs"; +import { isValidURL, validateDate } from "./utils.mjs"; + +/** + * Object with methods for constructing Notion page metadata, including parent, page, block, property, cover, and icon. + * + * Parent creates a parent object. Page, block, and property create ID objects. Cover creates an external image object, while icon can create an external image object or an emoji object. + * + * @namespace + */ +export const page_meta = { + /** + * Metadata definition for a parent entity. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + parent: { + type: "string", + /** + * Creates a parent object with a database_id or page_id. + * @function + * @param {Object} params - Parameters for creating parent metadata. + * @param {string} params.id - The ID of the parent. + * @param {string} params.type - The type of the parent ("database_id" or "page_id"). + * @returns {Object} A parent metadata object. + */ + createMeta: ({ id, type }) => ({ + type: type, + [type]: id, + }), + }, + + /** + * Metadata definition for a page ID property. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + page: { + type: "string", + /** + * Creates a page_id object. + * @function + * @param {string} page_id - The ID of the page. + * @returns {string} A string-validated page ID. + */ + createMeta: (page_id) => ({ + page_id: validateValue(page_id), + }), + }, + + /** + * Metadata definition for a block ID property. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + block: { + type: "string", + /** + * Creates a block_id object. + * @function + * @param {string} block_id - The ID of the block. + * @returns {string} A string-validated block ID. + */ + createMeta: (block_id) => ({ + block_id: validateValue(block_id), + }), + }, + + /** + * Metadata definition for a property ID property. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + property: { + type: "string", + /** + * Creates a property_id object. + * @function + * @param {string} property_id - The ID of the property. + * @returns {string} A string-validated property ID. + */ + createMeta: (property_id) => ({ + propety_id: validateValue(property_id), + }), + }, + + /** + * Metadata definition for an icon. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + icon: { + type: "string", + /** + * Creates an icon object. + * @function + * @param {string} value - The icon value (URL for "external" or emoji character). + * @returns {Object} An icon metadata object. + */ + createMeta: (value) => ({ + icon: setIcon(value), + }), + }, + + /** + * Metadata definition for a page cover. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + cover: { + type: "string", + /** + * Creates a page cover object. + * @function + * @param {string} value - The URL of the cover image. + * @returns {Object} A cover metadata object. + */ + createMeta: (value) => ({ + cover: setIcon(value), + }), + }, +}; + +/* + * Quality-of-life functions for page meta: + */ + +/** + * Page shorthand methods - these allow you to call the createMeta() method for the properties of the page_meta object more quickly. Import them directly into a file, or call them on NotionHelper. + * @namespace PageShorthand + */ + +/** + * Creates a parent database object. + * @memberof PageShorthand + * @param {string} database_id - The ID of the parent database. + * @returns {Object} A parent database object. + */ +export function parentDb(database_id) { + return page_meta.parent.createMeta({ + id: database_id, + type: "database_id", + }); +} + +/** + * Creates a parent page object. + * @memberof PageShorthand + * @param {string} page_id - The ID of the parent page. + * @returns {Object} A parent page object. + */ +export function parentPage(page_id) { + return page_meta.parent.createMeta({ id: page_id, type: "page_id" }); +} + +/** + * Creates a page_id object. Used for retrieving pages and page properties, updating page properties, and trashing pages. + * @memberof PageShorthand + * @param {string} page_id - The ID of the page to be read/updated/archived. + * @returns {Object} A page_id object. + */ +export function pageId(page_id) { + return page_meta.page.createMeta(page_id); +} + +/** + * Creates a block_id object. Used for all block endpoints. + * @memberof PageShorthand + * @param {string} block_id + * @returns {Object} A block_id object. + */ +export function blockId(block_id) { + return page_meta.block.createMeta(block_id); +} + +/** + * Creates a property_id object. Used for retrieving a page property item. + * @memberof PageShorthand + * @param {string} property_id + * @returns {Object} A property_id object. + */ +export function propertyId(property_id) { + return page_meta.property.createMeta(property_id); +} + +/** + * Creates a cover object. + * @memberof PageShorthand + * @param {string} url - The URL of the cover image. + * @returns {Object} A cover object. + */ +export function cover(url) { + return page_meta.cover.createMeta(url); +} + +/** + * Creates an icon object. + * @memberof PageShorthand + * @param {string} url - The URL of the icon image or an emoji character. + * @returns {Object} An icon object. + */ +export function icon(url) { + return page_meta.icon.createMeta(url); +} + +/** + * Object with methods for constructing each of the possible property types within a Notion database page. + * + * Property types include title, rich_text, checkbox, date, email, files, multi_select, number, people, phone_number, relation, select, status, and url. + * + * @namespace + */ +export const page_props = { + /** + * Methods for title properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + title: { + type: "string[]", + /** + * Sets a title property's value. + * @function + * @param {Object[]} value - The array of Rich Text Objects for the title content. + * @returns {Object} A title property object. + * + * Notion API will throw an error if title doesn't contain an array of Rich Text object(s) (RTOs). + * setProp() will convert a string, or array of strings, to an array of Rich Text object(s). + * On other invalid input, it will throw an error. + */ + setProp: (value) => ({ + title: validateValue(value, "rich_text"), + }), + }, + + /** + * Methods for rich text properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + rich_text: { + type: "string[]", + returns: "rich_text", + /** + * Sets a rich text property's value. + * @function + * @param {Object[]} value - The array of Rich Text Objects for the rich text content. + * @returns {Object} A rich text property object. + */ + setProp: (value) => ({ + rich_text: validateValue(value, "rich_text"), + }), + }, + + /** + * Methods for checkbox properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + checkbox: { + type: "boolean", + returns: "boolean", + /** + * Sets a checkbox property's value. + * @function + * @param {boolean} value - The boolean value for the checkbox state. + * @returns {Object} A checkbox property object. + */ + setProp: (value) => ({ + checkbox: validateValue(value, "boolean"), + }), + }, + + /** + * Methods for date properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + date: { + type: "string", + returns: "date", + /** + * Sets a date property's value. + * @function + * @param {string} start - The start date. + * @param {string} [end=null] - The optional end date. + * @returns {Object} A date property object. + */ + setProp: (start, end = null) => { + const date = { + date: { + start: validateValue(start, "date"), + end: end ? validateValue(end, "date") : null, + }, + }; + + if (!date || !date.date || date.date.start == null) { + return { + date: null, + }; + } + + return date; + }, + }, + + /** + * Methods for email properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + email: { + type: "string", + returns: "email", + /** + * Sets an email property's value. + * @function + * @param {string} value - The email address. + * @returns {Object} An email property object. + */ + setProp: (value) => ({ + email: validateValue(value, "string"), + }), + }, + + /** + * Methods for files properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + files: { + type: "string[]", + returns: "array", // Type not currently used for validation + /** + * Sets a files property's value. + * @function + * @param {Array<{name: string, url: string}>} fileArray - The array of file objects. + * @returns {Object} A files property object. + */ + setProp: (fileArray) => { + const files = fileArray.map((file) => { + if (!validateValue(file.url, "url")) { + return null; + } else { + return { + name: validateValue(file.name, "string"), + external: { + url: validateValue(file.url, "url"), + }, + }; + } + }); + + if (files.every((file) => file === null)) { + return { + files: null, + }; + } else { + return { + files: files, + }; + } + }, + }, + + /** + * Methods for multi_select properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + multi_select: { + type: "string[]", + returns: "array", // Not currently used for validation + /** + * Sets a multi_select property's value. + * @function + * @param {string[]} valuesArray - The array of selected values. + * @returns {Object} A multi-select property object. + */ + setProp: (valuesArray) => ({ + multi_select: valuesArray.map((value) => ({ + name: validateValue(value, "string"), + })), + }), + }, + + /** + * Methods for number properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + number: { + type: "number", + returns: "number", + /** + * Sets a number property's value. + * @function + * @param {(number|string)} value - The numeric value. A string may also be passed, and setProp() will attempt to convert it to a number. + * @returns {Object} A number property object. + */ + setProp: (value) => ({ + number: validateValue(value, "number"), + }), + }, + + /** + * Methods for people properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + people: { + type: "string[]", + returns: "array", // Not currently used for validation + /** + * Sets a people property's value. + * @function + * @param {string[]} personArray - The array of person IDs. + * @returns {Object} A people property object. + */ + setProp: (personArray) => { + const people = personArray.map((person) => { + if (!validateValue(person, "string")) { + return null; + } else { + return { + object: "user", + id: validateValue(person, "string"), + }; + } + }); + + if (people.every((person) => person === null)) { + return null; + } else { + return { + people: people, + }; + } + }, + }, + + /** + * Methods for phone_number properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + phone_number: { + type: "string", + returns: "string", + /** + * Sets a phone number property's value. + * @function + * @param {string} value - The phone number. + * @returns {Object} A phone number property object. + */ + setProp: (value) => ({ + phone_number: validateValue(value, "string"), + }), + }, + + /** + * Methods for relation properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + relation: { + type: "string[]", + /** + * Sets a relation property's value. + * @function + * @param {string[]} pageArray - The array of related page IDs. + * @returns {Object} A relation property object. + */ + setProp: (pageArray) => { + const pages = pageArray.map((page) => { + if (!validateValue(page, "string")) { + return null; + } else { + return { + id: validateValue(page, "string"), + }; + } + }); + + if (pages.every((page) => page === null)) { + return null; + } else { + return { + relation: pages, + }; + } + }, + }, + + /** + * Methods for select properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + select: { + type: "string", + returns: "string", + /** + * Sets a select property's value. + * @function + * @param {string} value - The selected value. + * @returns {Object} A select property object. + */ + setProp: (value) => ({ + select: { + name: validateValue(value, "string"), + }, + }), + }, + + /** + * Methods for status properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + status: { + type: "string", + returns: "string", + /** + * Sets a status property's value. + * @function + * @param {string} value - The status value. + * @returns {Object} A status property object. + */ + setProp: (value) => ({ + status: { + name: validateValue(value, "string"), + }, + }), + }, + + /** + * Methods for URL properties. + * + * @namespace + * @property {string} type - The data type the property accepts. + */ + url: { + type: "string", + returns: "string", + /** + * Sets a URL property's value. + * @function + * @param {string} value - The URL. + * @returns {Object} A URL property object. + */ + setProp: (value) => ({ + url: validateValue(value, "string"), + }), + }, +}; + +/* + * Quality-of-life functions for page props: + */ + +/** + * Property shorthand methods - these allow you to call the setProp() method for the properties of the page_props object more quickly. Import them directly into a file, or call them on NotionHelper. + * @namespace PropertyShorthand + */ + +/** + * Creates a title property object. + * @memberof PropertyShorthand + * @param {string|string[]} value - The title content, either a string or an array of strings. + * @returns {Object} A title property object. + */ +export function title(value) { + return page_props.title.setProp(value); +} + +/** + * Creates a rich text property object. + * @memberof PropertyShorthand + * @param {string|string[]} value - The rich text content, either a string or an array of strings. + * @returns {Object} A rich text property object. + */ +export function richText(value) { + return page_props.rich_text.setProp(value); +} + +/** + * Creates a checkbox property object. + * @memberof PropertyShorthand + * @param {boolean} value - The boolean value for the checkbox state. + * @returns {Object} A checkbox property object. + */ +export function checkbox(value) { + return page_props.checkbox.setProp(value); +} + +/** + * Creates a date property object. + * @memberof PropertyShorthand + * @param {string} start - The start date in ISO 8601 format. + * @param {string} [end] - The optional end date in ISO 8601 format. + * @returns {Object} A date property object. + */ +export function date(start, end) { + return page_props.date.setProp(start, end); +} + +/** + * Creates an email property object. + * @memberof PropertyShorthand + * @param {string} value - The email address. + * @returns {Object} An email property object. + */ +export function email(value) { + return page_props.email.setProp(value); +} + +/** + * Creates a files property object. + * @memberof PropertyShorthand + * @param {Array<{name: string, url: string}>} fileArray - The array of file objects. + * @returns {Object} A files property object. + */ +export function files(fileArray) { + return page_props.files.setProp(fileArray); +} + +/** + * Creates a multi-select property object. + * @memberof PropertyShorthand + * @param {string[]} valuesArray - The array of selected values. + * @returns {Object} A multi-select property object. + */ +export function multiSelect(valuesArray) { + return page_props.multi_select.setProp(valuesArray); +} + +/** + * Creates a number property object. + * @memberof PropertyShorthand + * @param {number|string} value - The numeric value. A string may also be passed, and it will be converted to a number if possible. + * @returns {Object} A number property object. + */ +export function number(value) { + return page_props.number.setProp(value); +} + +/** + * Creates a people property object. + * @memberof PropertyShorthand + * @param {string[]} personArray - The array of person IDs. + * @returns {Object} A people property object. + */ +export function people(personArray) { + return page_props.people.setProp(personArray); +} + +/** + * Creates a phone number property object. + * @memberof PropertyShorthand + * @param {string} value - The phone number. + * @returns {Object} A phone number property object. + */ +export function phoneNumber(value) { + return page_props.phone_number.setProp(value); +} + +/** + * Creates a relation property object. + * @memberof PropertyShorthand + * @param {string[]} pageArray - The array of related page IDs. + * @returns {Object} A relation property object. + */ +export function relation(pageArray) { + return page_props.relation.setProp(pageArray); +} + +/** + * Creates a select property object. + * @memberof PropertyShorthand + * @param {string} value - The selected value. + * @returns {Object} A select property object. + */ +export function select(value) { + return page_props.select.setProp(value); +} + +/** + * Creates a status property object. + * @memberof PropertyShorthand + * @param {string} value - The status value. + * @returns {Object} A status property object. + */ +export function status(value) { + return page_props.status.setProp(value); +} + +/** + * Creates a URL property object. + * @memberof PropertyShorthand + * @param {string} value - The URL. + * @returns {Object} A URL property object. + */ +export function url(value) { + return page_props.url.setProp(value); +} + +/** + * Validates values passed to the setProp() methods above. Performs some transformation in certain cases. + * + * @param {*} value - the value being passed to setProp(), which invokes this function + * @param {string} type - the type of value expected by this Notion API property + * @returns + */ +function validateValue(value, type) { + if ( + value === undefined || + value === null || + !type || + typeof type !== "string" + ) { + console.error( + `Invalid value or type variable provided to validateValue().` + ); + throw new Error( + `Invalid value or type variable provided to validateValue().` + ); + } + + if (type === "rich_text") { + return enforceRichText(value); + } + + if (type === "number") { + if (typeof value === "string") { + console.warn( + `String data passed to a number property. Attempting to convert to a number.` + ); + const num = Number(value); + + if (!isNaN(num)) { + return num; + } else { + return null; + } + } + + if (typeof value !== "number") { + console.warn( + `Invalid data type passed to a number property. Returning null.` + ); + return null; + } + + return value; + } + + if (type === "boolean") { + if (typeof value !== "boolean") { + console.warn( + `Invalid data type passed to a boolean property. Returning null.` + ); + return null; + } + + return value; + } + + if (type === "date") { + return validateDate(value); + } + + if (type === "string") { + if (typeof value !== "string") { + console.warn( + `Invalid data type passed to a string property. Returning null.` + ); + return null; + } + + return value; + } + + if (type === "url") { + if (typeof value !== "string") { + console.warn( + `Invalid data type passed to a url property. Returning null.` + ); + return null; + } + + if (isValidURL(value)) { + return value; + } else { + console.warn(`Invalid URL. Returning null.`); + return null; + } + } + + console.warn( + `Type specified to validateValue is not a valid type. Returning the input...` + ); + return value; +} diff --git a/pages.mjs b/pages.mjs new file mode 100644 index 0000000..f716586 --- /dev/null +++ b/pages.mjs @@ -0,0 +1,913 @@ +import { buildRichTextObj } from "./rich-text.mjs"; +import { makeParagraphBlocks } from "./blocks.mjs"; +import { page_meta, page_props } from "./page-meta.mjs"; +import { block } from "./blocks.mjs"; +import CONSTANTS from "./constants.mjs"; +// TODO - allow passing in a Notion db response in order to validate against the db itself +// TODO - probably split out schema validation as its own function + +/** + * + * @param {Object} options + * @param {string} parent - The ID of the parent page or database. + * @param {string} parent_type - "page_id" or "database_id". + * @param {(Array|Object)} pages - an array of simple objects, each of which will be turned into a valid page object. Each can have property types that match to valid Notion page properties, as well as a "cover", "icon", and "children" property. The "children" prop's value should be either a string or an array. You can also pass a single object, but the function will still return an array. + * @param {Object} schema - an object that maps the schema of the pages objects to property names and types in the parent. Saves you from needing to specify the property name and type from the target Notion database for every entry in your pages object. For each property in your pages object that should map to a Notion database property, specify the key as the property name in the pages object and set the value as an array with the Notion property name as the first element and the property type as the second. Non-valid property types will be filtered out. Optionall, you can specify custom keys for the icon (["Icon", "icon"]), cover (["Cover", "cover"]), and children array (["Children", "children"]). + * @param {function} childrenFn - a callback you can specify that will run on any array elements present in a "children" property of any object in the pages array. If that "children" property contains a single string, it'll run on that as well. If omitted, any "children" values will be converted to Paragraph blocks by default. + * + * @example + * const database = "abcdefghijklmnopqrstuvwxyz" + * + * const tasks = [ { + * icon: "πŸ˜›", + * task: "Build Standing Desk", + * due: "2024-09-10", + * status: "Not started" + * } ] + * + * const schema = { + * task: [ "Name", "title" ], + * due: [ "Due Date", "date"], + * status: [ "Status", "status" ] + * } + * + * const pageObjects = quickPages({ + * parent: database, + * parent_type: "database_id", + * pages: tasks, + * schema: schema, + * childrenFn: (value) => NotionHelper.makeParagraphs(value) + * }) + * @returns {Array} - An array of page objects, each of which can be directly passed as the children for a POST request to https://api.notion.com/v1/pages (or as the single argument to notion.pages.create() when using the SDK). + */ +export function quickPages({ parent, parent_type, pages, schema, childrenFn }) { + let pageArray; + + if (Array.isArray(pages)) { + pageArray = pages; + } else { + pageArray[pages]; + } + + return pages.map((page) => { + const iconSchema = Object.fromEntries( + Object.entries(schema).filter( + ([propName, propDef]) => propDef[1] === "icon" + ) + ); + + const coverSchema = Object.fromEntries( + Object.entries(schema).filter( + ([propName, propDef]) => propDef[1] === "cover" + ) + ); + + let icon; + if (Object.entries(iconSchema).length === 1) { + let entry = page[Object.keys(iconSchema)[0]]; + if (entry && typeof entry === "string" && entry !== "") { + icon = entry; + } + } else if ( + page.icon && + typeof page.icon === "string" && + page.icon !== "" + ) { + icon = page.icon; + } + + let cover; + if (Object.entries(coverSchema).length === 1) { + let entry = page[Object.keys(coverSchema)[0]]; + if (entry && typeof entry === "string" && entry !== "") { + cover = entry; + } + } else if ( + page.cover && + typeof page.cover === "string" && + page.cover !== "" + ) { + cover = page.cover; + } + + const finalPage = { + parent: page_meta.parent.createMeta({ + id: parent, + type: parent_type, + }), + ...(icon && page_meta.icon.createMeta(icon)), + ...(cover && page_meta.cover.createMeta(cover)), + }; + + const validatedSchema = Object.fromEntries( + Object.entries(schema).filter(([propName, propDef]) => + Object.keys(page_props).includes(propDef[1]) + ) + ); + + finalPage.properties = Object.entries(page) + .filter(([key]) => key in validatedSchema) + .reduce((acc, [key, val]) => { + const [propName, propType] = validatedSchema[key]; + let value; + + if ( + ["title", "rich_text"].includes(propType) && + typeof val === "string" + ) { + value = buildRichTextObj(val); + } else { + value = val; + } + + const propResult = page_props[propType].setProp(value); + + const propKey = Object.keys(propResult)[0]; + if (propResult[propKey] !== null) { + acc[propName] = propResult; + } + + return acc; + }, {}); + + let pageChildren; + + const childrenSchema = Object.fromEntries( + Object.entries(schema).filter( + ([propName, propDef]) => propDef[1] === "children" + ) + ); + + let childrenProp; + if (Object.entries(childrenSchema).length === 1) { + childrenProp = page[Object.keys(childrenSchema)[0]]; + } else if (page.children) { + childrenProp = page.children; + } + + if (childrenProp) { + if (typeof childrenProp === "string" && childrenProp.trim()) { + pageChildren = [childrenProp]; + } else if (Array.isArray(childrenProp) && childrenProp.length > 0) { + pageChildren = childrenProp; + } else { + console.warn( + `Invalid page children data type submitted for the page object below. Children data will be omitted.` + ); + console.dir(page); + pageChildren = []; + } + + console.log(typeof childrenFn); + if (typeof childrenFn === "function") { + finalPage.children = childrenFn(pageChildren); + } else if (typeof pageChildren[0] === "string") { + finalPage.children = makeParagraphBlocks(pageChildren); + } + } + + return finalPage; + }); +} + +/** + * A builder object for Notion content. + * @typedef {Object} NotionBuilder + * + * @property {function(string): this} parentDb - Sets the parent database for the page. + * @property {function(string): this} parentPage - Sets the parent page for the page. + * // Add more properties here for each method in the builder + */ + +/** + * A factory function that provides methods for building Notion objects, including pages, properties, and blocks. It adds an unhealthily-large spoonful of syntactic sugar onto the Notion API. + * + * Returns an object with two possible properties: + * + * 1. content (always returned) - can be a full page object, an array of blocks, or a properties object. + * + * 2. addititionalBlocks - array containing arrays of blocks passed to the builder function that go over Notion's limit for the number of blocks that can be in a children array. This allows you to add these to the returned page or block in further requests. + * + * This builder supports chaining methods so you can build pages or structures incrementally. It also supports block-nesting with the startParent() and endParent() methods. + * + * After adding all your blocks and properties, call build() to return the final object. It can be passed directly as the data object in Notion API requests. + * + * @namespace + * @function createNotion + * @returns {NotionBuilder} A builder object with methods for constructing and managing Notion content. The builder includes methods to set page and property details, add various block types, manage nested structures, and ultimately build Notion-compatible objects. + * + * @example + * const notionBuilder = createNotion(); + * + * // Build a new Notion page with various blocks + * const result = notionBuilder + * .parentDb('database-id') + * .title('Page Title', 'Hello World') + * .paragraph('This is the first paragraph.') + * .heading1('Main Heading') + * .build(); + * + * // Access the built content and handle additional blocks if they exist + * console.log(result.content); // The main Notion page content + * console.log(result.additionalBlocks); // Any blocks that need separate requests due to size constraints + * + * // Create a page in Notion with the result (assumes you've installed and imported the Notion SDK and instantiated a client bound to a 'notion' variable) + * const response = await notion.pages.create(result.content) + */ +export function createNotion() { + let data, + currentBlockStack, + nestingLevel, + hasPageParent, + hasProperty, + hasBlock; + + /** + * Resets the builder to its initial state. + * @private + */ + function resetBuilder() { + data = { + properties: {}, + children: [], + }; + currentBlockStack = [{ block: data, children: data.children }]; + nestingLevel = 0; + hasPageParent = false; + hasProperty = false; + hasBlock = false; + } + + /** + * Splits an array of blocks if it exceeds the maximum size allowed by the Notion API. + * @private + * @param {Array} blocks - The array of blocks to chunk. + * @param {number} [chunkSize=CONSTANTS.MAX_BLOCKS] - The maximum size of each chunk. + * @returns {Array} An array of block chunks. + */ + function chunkBlocks(blocks, chunkSize = CONSTANTS.MAX_BLOCKS) { + const chunkedBlocks = []; + for (let i = 0; i < blocks.length; i += chunkSize) { + chunkBlocks.push(blocks.slice(i, i + chunkSize)); + } + return chunkBlocks; + } + + resetBuilder(); + + /** + * @namespace + * @type {NotionBuilder} */ + const builder = { + // Page Methods + /** + * Sets the parent database for the page. + * @param {string} database_id - The ID of the parent database. + * @returns {this} The builder instance for method chaining. + */ + parentDb(database_id) { + data.parent = page_meta.parent.createMeta({ + id: database_id, + type: "database_id", + }); + hasPageParent = true; + nestingLevel++; + return this; + }, + + /** + * Sets the parent page for the page. + * @param {string} page_id - The ID of the parent page. + * @returns {this} The builder instance for method chaining. + */ + parentPage(page_id) { + data.parent = page_meta.parent.createMeta({ + id: page_id, + type: "page_id", + }); + hasPageParent = true; + nestingLevel++; + return this; + }, + + /** + * Adds a page_id property. Used for updating page properties or doing read operations. + * @param {string} page_id - The ID of the page + * @returns {this} The builder instance for method chaining. + */ + pageId(page_id) { + data.page_id = page_meta.page.createMeta(page_id); + return this; + }, + + /** + * Adds a property_id property. Used for fetching a page property item. + * @param {string} property_id - The ID of the property to be fetched. + * @returns {this} The builder instance for method chaining. + */ + propertyId(property_id) { + data.property_id = page_meta.property.createMeta(property_id); + return this; + }, + + /** + * Adds a block_id property. Used for all Block endpoints. + * @param {string} block_id - The ID of the block + * @returns {this} The builder instance for method chaining. + */ + blockId(block_id) { + data.block_id = page_meta.block.createMeta(block_id); + hasPageParent = true; + nestingLevel++; + return this; + }, + + /** + * Sets the cover image for the page. + * @param {string} url - The URL of the cover image. + * @returns {this} The builder instance for method chaining. + */ + cover(url) { + data.cover = page_meta.cover.createMeta(url); + return this; + }, + + /** + * Sets the icon for the page. + * @param {string} url - The URL of the icon image or an emoji. + * @returns {this} The builder instance for method chaining. + */ + icon(url) { + data.icon = page_meta.icon.createMeta(url); + return this; + }, + + // Property Methods + /** + * Adds a custom property to the page. + * @param {string} name - The name of the property. + * @param {string} type - The type of the property. + * @param {*} value - The value of the property. + * @throws {Error} If the property type is invalid. + * @returns {this} The builder instance for method chaining. + */ + property(name, type, value) { + if (!page_props[type]) { + const error = `Invalid property type: ${type}`; + console.error(error); + throw new Error(error); + } + data.properties[name] = page_props[type].setProp(value); + hasProperty = true; + return this; + }, + + /** + * Sets a title property value for the page. + * @param {string} name - The name of the property. + * @param {string|Array} value - The title value. + * @returns {this} The builder instance for method chaining. + */ + title(name, value) { + data.properties[name] = page_props.title.setProp(value); + hasProperty = true; + return this; + }, + + /** + * Sets a rich text property value for the page. + * @param {string} name - The name of the property. + * @param {string|Array} value - The rich text value. + * @returns {this} The builder instance for method chaining. + */ + richText(name, value) { + data.properties[name] = page_props.rich_text.setProp(value); + hasProperty = true; + return this; + }, + + /** + * Sets a checkbox property value for the page. + * @param {string} name - The name of the property. + * @param {boolean} value - The checkbox value. + * @returns {this} The builder instance for method chaining. + */ + checkbox(name, value) { + data.properties[name] = page_props.checkbox.setProp(value); + hasProperty = true; + return this; + }, + + /** + * Sets a date property value for the page. + * @param {string} name - The name of the property. + * @param {string} start - The start date. + * @param {string} [end=null] - The end date (optional). + * @returns {this} The builder instance for method chaining. + */ + date(name, start, end = null) { + data.properties[name] = page_props.date.setProp(start, end); + hasProperty = true; + return this; + }, + + /** + * Sets a email property value for the page. + * @param {string} name - The name of the property. + * @param {string} value - The email value. + * @returns {this} The builder instance for method chaining. + */ + email(name, value) { + data.properties[name] = page_props.email.setProp(value); + hasProperty = true; + return this; + }, + + /** + * Sets a files property value for the page. + * + * NOTE: The separate file() method creates a file block. + * + * @param {string} name - The name of the property. + * @param {Array} fileArray - An array of file objects. + * @returns {this} The builder instance for method chaining. + */ + files(name, fileArray) { + data.properties[name] = page_props.files.setProp(fileArray); + hasProperty = true; + return this; + }, + + /** + * Sets a multi-select property value for the page. + * @param {string} name - The name of the property. + * @param {Array} valuesArray - An array of selected values. + * @returns {this} The builder instance for method chaining. + */ + multiSelect(name, valuesArray) { + data.properties[name] = + page_props.multi_select.setProp(valuesArray); + hasProperty = true; + return this; + }, + + /** + * Sets a number property value for the page. + * @param {string} name - The name of the property. + * @param {number} value - The number value. + * @returns {this} The builder instance for method chaining. + */ + number(name, value) { + data.properties[name] = page_props.number.setProp(value); + hasProperty = true; + return this; + }, + + /** + * Sets a people property value for the page. + * @param {string} name - The name of the property. + * @param {Array} personArray - An array of person IDs. + * @returns {this} The builder instance for method chaining. + */ + people(name, personArray) { + data.properties[name] = page_props.people.setProp(personArray); + hasProperty = true; + return this; + }, + + /** + * Sets a phone number property value for the page. + * @param {string} name - The name of the property. + * @param {string} value - The phone number value. + * @returns {this} The builder instance for method chaining. + */ + phoneNumber(name, value) { + data.properties[name] = page_props.phone_number.setProp(value); + hasProperty = true; + return this; + }, + + /** + * Sets a relation property value for the page. + * @param {string} name - The name of the property. + * @param {Array} pageArray - An array of related page IDs. + * @returns {this} The builder instance for method chaining. + */ + relation(name, pageArray) { + data.properties[name] = page_props.relation.setProp(pageArray); + hasProperty = true; + return this; + }, + + /** + * Sets a select property value for the page. + * @param {string} name - The name of the property. + * @param {string} value - The selected value. + * @returns {this} The builder instance for method chaining. + */ + select(name, value) { + data.properties[name] = page_props.select.setProp(value); + hasProperty = true; + return this; + }, + + /** + * Sets a status property value for the page. + * @param {string} name - The name of the property. + * @param {string} value - The status value. + * @returns {this} The builder instance for method chaining. + */ + status(name, value) { + data.properties[name] = page_props.status.setProp(value); + hasProperty = true; + return this; + }, + + /** + * Sets a URL property value for the page. + * @param {string} name - The name of the property. + * @param {string} value - The URL value. + * @returns {this} The builder instance for method chaining. + */ + url(name, value) { + data.properties[name] = page_props.url.setProp(value); + hasProperty = true; + return this; + }, + + // Block Methods + /** + * Starts a new parent block that can contain child blocks. + * + * @param {string} blockType - The type of block to create as a parent. + * @param {Object} [options={}] - Options for creating the block, specific to the block type. + * @throws {Error} If the nesting level exceeds 2 or if the block type doesn't support children. + * @returns {this} The builder instance for method chaining. + * @example + * notion.startParent('toggle', 'Click to expand') + * .paragraph('This is inside the toggle') + * .endParent(); + */ + startParent(blockType, options = {}) { + if (nestingLevel > 2) { + const error = `Nesting level exceeded. Requests can only have 2 levels of nested child blocks.`; + console.error(error); + throw new Error(error); + } + + const newBlock = block[blockType].createBlock(options); + if (!block[blockType].supports_children) { + const error = `startParent() called with type ${blockType}, which does not support child blocks.`; + console.error(error); + throw new Error(error); + } + + if (!newBlock[blockType].children) { + newBlock[blockType].children = []; + } + + currentBlockStack[currentBlockStack.length - 1].children.push( + newBlock + ); + currentBlockStack.push({ + block: newBlock, + children: newBlock[blockType].children, + }); + nestingLevel++; + hasBlock = true; + return this; + }, + + /** + * Ends the current parent block and moves up one level in the block hierarchy. + * + * @returns {this} The builder instance for method chaining. + * @example + * notion.startParent('toggle', 'Click to expand') + * .paragraph('This is inside the toggle') + * .endParent(); + */ + endParent() { + if (currentBlockStack.length > 1) { + currentBlockStack.pop(); + nestingLevel--; + } + return this; + }, + + /** + * Adds a new block to the current level in the block hierarchy. + * + * @param {string} blockType - The type of block to add. + * @param {Object} [options={}] - Options for creating the block, specific to the block type. + * @returns {this} The builder instance for method chaining. + * @example + * notion.addBlock('paragraph', 'This is a paragraph.'); + * + * // Or using the shorthand method: + * notion.paragraph('This is a paragraph.'); + */ + addBlock(blockType, options = {}) { + const newBlock = block[blockType].createBlock(options); + currentBlockStack[currentBlockStack.length - 1].children.push( + newBlock + ); + hasBlock = true; + return this; + }, + + /** + * Adds a paragraph block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.paragraph.createBlock for full documentation + */ + paragraph(options) { + return this.addBlock("paragraph", options); + }, + + /** + * Adds a heading_1 block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.heading_1.createBlock for full documentation + */ + heading1(options) { + return this.addBlock("heading_1", options); + }, + + /** + * Adds a heading_2 block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.heading_2.createBlock for full documentation + */ + heading2(options) { + return this.addBlock("heading_2", options); + }, + + /** + * Adds a heading_3 block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.heading_3.createBlock for full documentation + */ + heading3(options) { + return this.addBlock("heading_3", options); + }, + + /** + * Adds a bulleted_list_item block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.bulleted_list_item.createBlock for full documentation + */ + bulletedListItem(options) { + return this.addBlock("bulleted_list_item", options); + }, + + /** + * Shorthand alias for bulletedListItem(). Adds a bulleted_list_item block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.bulleted_list_item.createBlock for full documentation + */ + bullet(options) { + return this.bulletedListItem(options); + }, + + /** + * Adds a numbered_list_item block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.numbered_list_item.createBlock for full documentation + */ + numberedListItem(options) { + return this.addBlock("numbered_list_item", options); + }, + + /** + * Shorthand alias for numberedListItem(). Added a numbered_list_item block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.numbered_list_item.createBlock for full documentation + */ + num(options) { + return this.numberedListItem(options); + }, + + /** + * Adds a to_do block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.to_do.createBlock for full documentation + */ + toDo(options) { + return this.addBlock("to_do", options); + }, + + /** + * Adds a toggle block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.toggle.createBlock for full documentation + */ + toggle(options) { + return this.addBlock("toggle", options); + }, + + /** + * Adds a code block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.code.createBlock for full documentation + */ + code(options) { + return this.addBlock("code", options); + }, + + /** + * Adds a quote block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.quote.createBlock for full documentation + */ + quote(options) { + return this.addBlock("quote", options); + }, + + /** + * Adds a callout block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.callout.createBlock for full documentation + */ + callout(options) { + return this.addBlock("callout", options); + }, + + /** + * Adds a divider block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.divider.createBlock for full documentation + */ + divider() { + return this.addBlock("divider", {}); + }, + + /** + * Adds an image block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.image.createBlock for full documentation + */ + image(options) { + return this.addBlock("image", options); + }, + + /** + * Adds a video block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.video.createBlock for full documentation + */ + video(options) { + return this.addBlock("video", options); + }, + + /** + * Adds a file block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.file.createBlock for full documentation + */ + file(options) { + return this.addBlock("file", options); + }, + + /** + * Adds a pdf block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.pdf.createBlock for full documentation + */ + pdf(options) { + return this.addBlock("pdf", options); + }, + + /** + * Adds a bookmark block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.bookmark.createBlock for full documentation + */ + bookmark(options) { + return this.addBlock("bookmark", options); + }, + + /** + * Adds an embed block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.embed.createBlock for full documentation + */ + embed(options) { + return this.addBlock("embed", options); + }, + + /** + * Adds a table_of_contents block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.table_of_contents.createBlock for full documentation + */ + tableOfContents(options) { + return this.addBlock("table_of_contents", options); + }, + + /** + * Adds a table block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.table.createBlock for full documentation + */ + table(options) { + return this.addBlock("table", options); + }, + + /** + * Adds a table_row block to the current stack. + * @returns {this} The builder instance for method chaining. + * @see block.table_row.createBlock for full documentation + */ + tableRow(options) { + return this.addBlock("table_row", options); + }, + + /** + * Builds and returns the final Notion object based on the current state of the builder. + * + * @returns {this} An object containing the built content and any additional blocks. + * @property {Object|Array} content - The main content of the built object. This can be a full page object, a properties object, or an array of blocks, depending on what was added to the builder. + * @property {Array} additionalBlocks - Any blocks that exceed Notion's maximum block limit per request. These will need to be added in subsequent requests. + * @throws {Error} If no data was added to the builder. + * @example + * const notion = createNotion(); + * const result = notion + * .dbId('your-database-id') + * .title('Page Title', 'My New Page') + * .paragraph('This is a paragraph.') + * .build(); + * + * console.log(result.content); // The main page content + * console.log(result.additionalBlocks); // Any blocks that couldn't fit in the initial request + */ + build() { + let result = { + content: null, + additionalBlocks: [], + }; + + if (hasPageParent) { + if (data.children.length > CONSTANTS.MAX_BLOCKS) { + const chunkedBlocks = chunkBlocks(data.children); + data.children = chunkedBlocks[0]; + result.additionalBlocks = chunkedBlocks.slice(1); + } + const { parent, ...rest } = data; + result.content = parent ? { parent, ...rest } : data; + } else if (hasProperty && !hasBlock) { + result.content = data.properties; + } else if (hasBlock && !hasProperty) { + if (data.children.length > CONSTANTS.MAX_BLOCKS) { + const chunkedBlocks = chunkBlocks(data.children); + result.content = chunkedBlocks[0]; + result.additionalBlocks = chunkedBlocks.slice(1); + } else { + result.content = data.children; + } + } else if (!hasPageParent && hasProperty && hasBlock) { + console.warn( + `Properties and blocks were added, so a full page object will be returned. However, it has no parent page or database specified.` + ); + if (data.children.length > CONSTANTS.MAX_BLOCKS) { + const chunkedBlocks = chunkBlocks(data.children); + data.children = chunkedBlocks[0]; + result.additionalBlocks = chunkedBlocks.slice(1); + } + result.content = data; + } else if (!hasPageParent && !hasProperty && !hasBlock) { + const error = `No data was added to the builder.`; + console.error(error); + throw new Error(error); + } + + resetBuilder(); + return result; + }, + + /** + * Resets the builder to its initial state, clearing all added content. + * + * @returns {this} The builder instance for method chaining. + * @example + * const notion = createNotion(); + * notion + * .dbId('your-database-id') + * .title('Page Title', 'My New Page') + * .paragraph('This is a paragraph.') + * .build(); + * + * // Reset the builder for a new page + * notion.reset() + * .dbId('another-database-id') + * .title('Page Title', 'Another New Page') + * .build(); + */ + reset() { + resetBuilder(); + return this; + }, + }; + + return builder; +} diff --git a/rich-text.mjs b/rich-text.mjs new file mode 100644 index 0000000..44c0594 --- /dev/null +++ b/rich-text.mjs @@ -0,0 +1,133 @@ +/** + * Builds a Rich Text Object. See: https://developers.notion.com/reference/rich-text + * @param {(string|Object)} input - The text content or input object. If string, the input can be normal text or an equation. If object, it can be a text, equation, or mention object. + * @param {Object} opts - Options for the Annotation object. + * @param {boolean} opts.bold - Bold text + * @param {boolean} opts.italic - Italic text + * @param {boolean} opts.strikethrough - Strikethrough text + * @param {boolean} opts.underline - Underlined text + * @param {boolean} opts.code - Code-style text + * @param {string} opts.color - String specifying the text's color or background color. Opts: "blue", "brown", "default", "gray", "green", "orange", "pink", "purple", "red", "yellow". All except "default" can also be used as a background color with "[color]_background" - example: "blue_background". See: https://developers.notion.com/reference/rich-text#the-annotation-object + * @param {string} url - The URL for this object, if any. Creates a clickable link. + * @param {string} [type=text] - An optional type for the Rich Text Object. Supports text, equation, and mention. + * @returns {Array} - Array with a single Rich Text Object + */ +export function buildRichTextObj(input, annotations = {}, url, type = "text") { + if (typeof input === "string") { + switch (type) { + case "text": + return [ + { + type: "text", + text: { + content: input, + link: url ? { url: url } : null, + }, + }, + ]; + case "equation": + return [ + { + type: "equation", + equation: { + expression: input, + }, + }, + ]; + } + } + + if (typeof input === "object") { + if (type === "text" || !type) { + return [ + { + type: "text", + text: input, + }, + ]; + } else { + switch (type) { + case "equation": + return [ + { + type: "equation", + equation: input, + annotations: { + ...annotations, + }, + }, + ]; + case "mention": + return [ + { + type: "mention", + mention: input, + annotations: { + ...annotations, + }, + }, + ]; + default: + const error = `Unsupported rich text type: ${input.type}`; + console.error(error); + throw new Error(error); + } + } + } + + const error = `Invalid input send to buildRichTextObj()`; + console.error(error); + throw new Error(error); +} + +/** + * Enforces Rich Text format for content. + * @param {string|Object|Array} content - The content to be enforced as Rich Text. + * @returns {Array} An array of Rich Text Objects. + */ +export function enforceRichText(content) { + if (!content) { + return []; + } + + if (Array.isArray(content)) { + return content.flatMap((item) => + typeof item === "string" + ? buildRichTextObj(item) + : enforceRichTextObject(item) + ); + } + + if (typeof content === "string") { + return buildRichTextObj(content); + } + + if (typeof content === "number") { + return buildRichTextObj(content.toString()) + } + + if (typeof content === "object") { + return [enforceRichTextObject(content)]; + } + + console.warn(`Invalid input for rich text. Returning empty array.`); + return []; +} + +/** + * Enforces a single Rich Text Object format. + * @param {string|Object} obj - The object to be enforced as a Rich Text Object. + * @returns {Object} A Rich Text Object. + */ +export function enforceRichTextObject(obj) { + if (typeof obj === "string") { + return buildRichTextObj(obj)[0]; + } + + if (obj.type && obj.text && typeof obj.text.content === "string") { + return obj; + } + + console.warn(`Invalid rich text object. Returning empty rich text object.`); + return buildRichTextObj("")[0]; +} diff --git a/utils.mjs b/utils.mjs new file mode 100644 index 0000000..364b0f7 --- /dev/null +++ b/utils.mjs @@ -0,0 +1,177 @@ +import CONSTANTS from "./constants.mjs"; + +/** + * Checks if a string contains only a single emoji. + * + * @param {string} string + * @returns {boolean} + */ +export function isSingleEmoji(string) { + const regex = /^\p{Emoji}$/u; + return regex.test(string.trim()); +} + +/** + * Checks if a string is a valid URL. + * + * @param {string} string + * @returns {boolean} + */ +export function isValidURL(string) { + try { + const url = new URL(string); + return url.protocol === "http:" || url.protocol === "https:"; + } catch (e) { + return false; + } +} + +/** + * Checks if an image URL is both a valid URL and has a supported image file type. + * + * @param {url} url - the URL to be checked + * @returns {boolean} + */ +export function validateImageURL(url) { + try { + const supportedFormats = CONSTANTS.IMAGE_SUPPORT.FORMATS.join("|"); + const formatRegex = new RegExp(`\\.(${supportedFormats})$`, 'i'); + return formatRegex.test(url) && isValidURL(url); + } catch (e) { + console.error(`${url} is not a valid image URL.`) + return false; + } +} + +/** + * Checks if a video URL is both a valid URL and will be accepted by the API, based on a list of supported file extensions and embed websites. + * + * @param {url} url - the URL to be checked + * @returns {boolean} + */ +export function validateVideoURL(url) { + try { + const supportedFormats = CONSTANTS.VIDEO_SUPPORT.FORMATS.join("|"); + const formatRegex = new RegExp(`\\.(${supportedFormats})$`, i); + const supportedSites = CONSTANTS.VIDEO_SUPPORT.SITES.join("|"); + const siteRegex = new RegExp(`(${supportedSites})`, i); + return ( + (formatRegex.test(url) || siteRegex.test(url)) && isValidURL(url) + ); + } catch (e) { + return false; + } +} + +/** + * Checks if a PDF URL is both a valid URL and ends with the .pdf extension. + * + * @param {url} url - the URL to be checked + * @returns {boolean} + */ +export function validatePDFURL(url) { + try { + const formatRegex = new RegExp(`\\.pdf$`, i); + return formatRegex.test(url) && isValidURL(url); + } catch (e) { + return false; + } +} + +/** + * Enforces a length limit on a string. Returns the original string in a single-element array if it is under the limit. If not, returns an array with string chunks under the limit. + * + * @param {string} string - the string to be tested + * @param {number} limit - optional string-length limit + * @returns {Array} - array with the original string, or chunks of the string if it was over the limit. + */ +export function enforceStringLength(string, limit) { + if (typeof string !== "string") { + console.error( + "Invalid input sent to enforceStringLength(). Expected a string, got: ", + string, + typeof string + ); + throw new Error("Invalid input: Expected a string."); + } + + const charLimit = CONSTANTS.MAX_TEXT_LENGTH; + const softLimit = limit && limit > 0 ? limit : charLimit * 0.8; + + if (string.length < charLimit) { + return [string]; + } else { + let chunks = []; + let currentIndex = 0; + + while (currentIndex < string.length) { + let nextCutIndex = Math.min( + currentIndex + softLimit, + string.length + ); + + let nextSpaceIndex = string.indexOf(" ", nextCutIndex); + + if ( + nextSpaceIndex === -1 || + nextSpaceIndex - currentIndex > softLimit + ) { + nextSpaceIndex = nextCutIndex; + } + + // Don't split high-surrogate characters + while ( + nextSpaceIndex > 0 && + string.charCodeAt(nextSpaceIndex - 1) >= 0xd800 && + string.charCodeAt(nextSpaceIndex - 1) <= 0xdbff + ) { + nextSpaceIndex--; + } + + chunks.push(string.substring(currentIndex, nextSpaceIndex)); + currentIndex = nextSpaceIndex + 1; + } + + return chunks; + } +} + +/** + * Validates Date object or string input that represents a date, and converts it to an ISO-8601 date string if possible. + * + * @param {(string|Date)} date - a Date object or string representing a date + * @returns {string} + */ +export function validateDate(dateInput) { + let date + + if (dateInput === null) { + return null + } + + if (dateInput instanceof Date) { + date = dateInput + } + + else if (typeof dateInput === 'string') { + date = new Date(dateInput) + } + + else { + console.warn(`Invalid input: Expected a Date object or string representing a date. Returning null.`) + return null + } + + if (!isNaN(date.getTime())) { + const isoString = date.toISOString() + + if (typeof dateInput === 'string' && !dateInput.includes(':') && !dateInput.includes('T')) { + return isoString.split('T')[0] + } else { + return isoString + } + } else { + console.warn(`Invalid date string or Date object provided. Returning null.`) + return null + } +} \ No newline at end of file