1.0.0 • Published 2 years ago

@ct-note/embed v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

npm.io

Embed Tool

Provides Block tool for embedded content for the Editor.js. Tool uses Editor.js pasted patterns handling and inserts iframe with embedded content.

List of services supported

service — is a service name that will be saved to Tool's output JSON

Installation

Install via NPM

Get the package

npm i --save @editorjs/embed

Include module at your application

import Embed from '@editorjs/embed';

Load from CDN

You can load specific version of package from jsDelivr CDN.

https://cdn.jsdelivr.net/npm/@editorjs/embed@latest

Then require this script on page with Editor.js.

<script src="..."></script>

Usage

Add a new Tool to the tools property of the Editor.js initial config.

var editor = EditorJS({
  ...

  tools: {
    ...
    embed: Embed,
  },

  ...
});

Available configuration

Enabling / disabling services

Embed Tool supports some services by default (see above). You can specify services you would like to use:

var editor = EditorJS({
  ...

  tools: {
    ...
    embed: {
      class: Embed,
      config: {
        services: {
          youtube: true,
          coub: true
        }
      }
    },
  },

  ...
});

Note that if you pass services you want to use like in the example above, others will not be enabled.

Add more services

You can provide your own services using simple configuration.

First, you should create a Service configuration object. It contains following fields:

FieldTypeDescription
regexRegExpPattern of pasted URLs. You should use regexp groups to extract resource id
embedUrlstringUrl of resource`s embed page. Use <%= remote_id %> to substitute resource identifier
htmlstringHTML code of iframe with embedded content. embedUrl will be set as iframe src
heightnumberOptional. Height of inserted iframe
widthnumberOptional. Width of inserted iframe
idFunctionOptional. If your id is complex you can provide function to make the id from extraced regexp groups

Example:

{
  regex: /https?:\/\/codepen.io\/([^\/\?\&]*)\/pen\/([^\/\?\&]*)/,
  embedUrl: 'https://codepen.io/<%= remote_id %>?height=300&theme-id=0&default-tab=css,result&embed-version=2',
  html: "<iframe height='300' scrolling='no' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'></iframe>",
  height: 300,
  width: 600,
  id: (groups) => groups.join('/embed/')
}

When you create a Service configuration object, you can provide it with Tool`s configuration:

var editor = EditorJS({
  ...

  tools: {
    ...
    embed: {
      class: Embed,
      config: {
        services: {
          youtube: true,
          coub: true,
          codepen: {
            regex: /https?:\/\/codepen.io\/([^\/\?\&]*)\/pen\/([^\/\?\&]*)/,
            embedUrl: 'https://codepen.io/<%= remote_id %>?height=300&theme-id=0&default-tab=css,result&embed-version=2',
            html: "<iframe height='300' scrolling='no' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'></iframe>",
            height: 300,
            width: 600,
            id: (groups) => groups.join('/embed/')
          }
        }
      }
    },
  },

  ...
});

Inline Toolbar

Editor.js provides useful inline toolbar. You can allow it`s usage in the Embed Tool caption by providing inlineToolbar: true.

var editor = EditorJS({
  ...

  tools: {
    ...
    embed: {
      class: Embed,
      inlineToolbar: true
    },
  },

  ...
});

Output data

FieldTypeDescription
servicestringservice unique name
sourcestringsource URL
embedstringURL for source embed page
widthnumberembedded content width
heightnumberembedded content height
captionstringcontent caption
{
  "type" : "embed",
  "data" : {
    "service" : "coub",
    "source" : "https://coub.com/view/1czcdf",
    "embed" : "https://coub.com/embed/1czcdf",
    "width" : 580,
    "height" : 320,
    "caption" : "My Life"
  }
}

About CodeX

CodeX is a team of digital specialists around the world interested in building high-quality open source products on a global market. We are open for young people who want to constantly improve their skills and grow professionally with experiments in cutting-edge technologies.

🌐Join 👋TwitterInstagram
codex.socodex.so/join@codex_team@codex_team
acorn-jsxansi-colorsajv-errorsajvajv-keywordsacornansi-stylesansi-regexaprobaargparsearr-diffanymatcharr-flattenarray-includesarr-unionarray-unionarray-uniquearray.prototype.flatasn1.jsassertassertion-errorastral-regexassign-symbolsasync-eachbabel-plugin-dynamic-import-nodebaseatobbalanced-matchbase64-jsbig.jsbn.jsbinary-extensionsbracesbrace-expansionbluebirdbrorandbrowser-stdoutbrowserify-cipherbrowserify-aesbrowserify-zlibbrowserify-rsabrowserify-signbrowserslistbufferbrowserify-desbuffer-frombuffer-xorcacachebuiltin-status-codescache-basecall-bindcaller-callsitecaller-pathcallsitescamelcasecaniuse-litechalkchokidarcheck-errorchrome-trace-eventcipher-basechownrcliuiclass-utilscolor-namecollection-visitcolor-convertcolorettecommandercomment-parsercommondirconcat-mapcomponent-emitterconsole-browserifyconcat-streamconstants-browserifycontains-pathconvert-source-mapcopy-concurrentlycopy-descriptorcore-js-compatcreate-ecdhcross-spawncosmiconfigcreate-hmaccreate-hashcrypto-browserifycssesccyclistdebugcore-util-isdecamelizedeep-eqldeep-isdecode-uri-componentdefine-propertiesdefine-propertydes.jsdiffdetect-filediffie-hellmandoctrinedir-globdomain-browserduplexifyelectron-to-chromiumellipticemojis-listemoji-regexenhanced-resolveend-of-streamenquirererror-exerrnoes-abstractes-to-primitiveescaladeescape-string-regexpeslint-config-standardeslint-module-utilseslint-import-resolver-nodeeslint-plugin-importeslint-plugin-eseslint-plugin-jsdoceslint-plugin-nodeeslint-plugin-promiseeslint-plugin-standardeslint-scopeeslint-utilseslint-visitor-keysespreeesqueryesprimaesutilsestraverseeventsevp_bytestokeyesrecurseexpand-tildeexecaexpand-bracketsextend-shallowextglobfast-deep-equalfast-globfast-json-stable-stringifyfastqfiggy-puddingfast-levenshteinfile-entry-cachefill-rangefind-cache-dirfind-upflat-cacheflatfindup-syncflattedfragment-cachefor-infrom2flush-write-streamfs-write-stream-atomicfs.realpathfunction-bindfunctional-red-black-treegensyncget-caller-fileget-streamget-func-nameget-intrinsicget-valueglobglob-parentglobal-modulesglobal-prefixglobalsglobbygraceful-fsgrowlhashas-bigintshas-symbolshas-flaghas-valuehash-basehas-valueshash.jshehmac-drbghosted-git-infohomedir-polyfillhttps-browserifyicss-utilsieee754iferrignoreimport-freshimport-fromimport-cwdimport-localimurmurhashindexes-ofiniinfer-ownerinterpretinvariantinflightinvert-kvis-arrayishis-accessor-descriptoris-bigintis-binary-pathis-boolean-objectis-callableis-bufferinheritsis-data-descriptoris-core-moduleis-date-objectis-descriptoris-extendableis-directoryis-extglobis-fullwidth-code-pointis-globis-numberis-number-objectis-plain-objectis-streamis-symbolis-regexis-stringis-windowsis-wslisarrayisexejs-tokensisobjectjs-yamljsdoctypeparserjsescjson-parse-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjson5lcidkind-oflevenarylevenload-json-fileis-negative-zeroloader-runnerlevnloader-utilslodashlocate-pathlodash.flattenlodash.clonedeeplodash.truncatelog-symbolsloose-envifylru-cachemap-age-cleanermap-cachemake-dirmap-visitmd5.jsmemmemory-fsmerge2mimic-fnmiller-rabinmicromatchminimalistic-assertminimalistic-crypto-utilsminimatchminimistmississippimove-concurrentlymixin-deepmkdirpmsnanomatchnatural-compareneo-asyncnode-environment-flagsnice-trynode-modules-regexpnode-libs-browsernode-releasesnormalize-package-dataobject-assignnormalize-pathnpm-run-pathobject-inspectobject-copyobject-keysobject-visitobject.assignobject.getownpropertydescriptorsobject.pickobject.valuesoptionatoronceos-browserifyos-localep-deferp-is-promisep-finallyp-limitp-locatep-trypakoparallel-transformparent-moduleparse-asn1parse-passwdparse-jsonpascalcasepath-dirnamepath-browserifypath-existspath-is-absolutepath-parsepath-keypath-typepathvalpbkdf2picomatchpifypkg-dirpiratesposix-character-classespostcsspostcss-load-configpostcss-modules-extract-importspostcss-modules-local-by-defaultpostcss-modules-scopepostcss-modules-valuespostcss-resolve-nested-selectorpostcss-selector-parserprelude-lspostcss-value-parserprivateprocessprocess-nextick-argsprogresspromise-inflightprrpublic-encryptpumppumpifypunycodequerystringrandombytesquerystring-es3read-pkgrandomfillqueue-microtaskreadable-streamread-pkg-upregeneratereaddirpregenerator-transformregenerate-unicode-propertiesregenerator-runtimeregex-notregexppregextrasregexpu-coreregjsgenregjsparserremove-trailing-separatorrepeat-elementrepeat-stringrequire-from-stringrequire-directoryrequire-main-filenameresolveresolve-cwdresolve-dirresolve-fromresolve-urlretreusifyripemd160rimrafrun-parallelrun-queuesafe-buffersafe-regexschema-utilssemverserialize-javascriptset-blockingset-valuesetimmediatesha.jsshebang-commandsignal-exitslice-ansislashshebang-regexsnapdragon-nodesnapdragonsnapdragon-utilsource-mapsource-list-mapsource-map-resolvesource-map-supportsource-map-urlspdx-exceptionsspdx-correctspdx-expression-parsespdx-license-idssplit-stringsprintf-jsssristatic-extendstream-browserifystream-eachstream-shiftstream-httpstring-widthstring.prototype.trimendstring.prototype.trimleftstring.prototype.trimrightstring.prototype.trimstartstring_decoderstrip-ansistrip-bomstrip-eofstrip-json-commentssupports-colortabletapabletersertext-tableterser-webpack-pluginto-arraybuffertimers-browserifythrough2to-object-pathto-fast-propertiesto-regextsconfig-pathsto-regex-rangetslibtsutilstty-browserifytype-checktype-detecttype-festtypedarrayunbox-primitiveunicode-canonical-property-names-ecmascriptunicode-match-property-ecmascriptunicode-match-property-value-ecmascriptunion-valueunicode-property-aliases-ecmascriptuniqunique-slugunique-filenameupathunset-valueuri-jsurixurlutiluseutil-deprecatevalidate-npm-package-licensev8-compile-cachevm-browserifywatchpackwebpack-sourceswhichwhich-boxed-primitivewhich-modulewide-alignworker-farmword-wrapwrap-ansiwrappyxtendyallisty18nyargsyargs-parseryargs-unparser
1.0.0

2 years ago