compiler-dom.esm-bundler.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. import { registerRuntimeHelpers, isBuiltInType, createSimpleExpression, createCompilerError, createObjectProperty, createCallExpression, TO_DISPLAY_STRING, transformModel as transformModel$1, findProp, hasDynamicKeyVBind, transformOn as transformOn$1, createCompoundExpression, isStaticExp, noopDirectiveTransform, baseCompile, baseParse } from '@vue/compiler-core';
  2. export * from '@vue/compiler-core';
  3. import { isVoidTag, isHTMLTag, isSVGTag, makeMap, parseStringStyle, capitalize, extend } from '@vue/shared';
  4. const V_MODEL_RADIO = Symbol((process.env.NODE_ENV !== 'production') ? `vModelRadio` : ``);
  5. const V_MODEL_CHECKBOX = Symbol((process.env.NODE_ENV !== 'production') ? `vModelCheckbox` : ``);
  6. const V_MODEL_TEXT = Symbol((process.env.NODE_ENV !== 'production') ? `vModelText` : ``);
  7. const V_MODEL_SELECT = Symbol((process.env.NODE_ENV !== 'production') ? `vModelSelect` : ``);
  8. const V_MODEL_DYNAMIC = Symbol((process.env.NODE_ENV !== 'production') ? `vModelDynamic` : ``);
  9. const V_ON_WITH_MODIFIERS = Symbol((process.env.NODE_ENV !== 'production') ? `vOnModifiersGuard` : ``);
  10. const V_ON_WITH_KEYS = Symbol((process.env.NODE_ENV !== 'production') ? `vOnKeysGuard` : ``);
  11. const V_SHOW = Symbol((process.env.NODE_ENV !== 'production') ? `vShow` : ``);
  12. const TRANSITION = Symbol((process.env.NODE_ENV !== 'production') ? `Transition` : ``);
  13. const TRANSITION_GROUP = Symbol((process.env.NODE_ENV !== 'production') ? `TransitionGroup` : ``);
  14. registerRuntimeHelpers({
  15. [V_MODEL_RADIO]: `vModelRadio`,
  16. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  17. [V_MODEL_TEXT]: `vModelText`,
  18. [V_MODEL_SELECT]: `vModelSelect`,
  19. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  20. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  21. [V_ON_WITH_KEYS]: `withKeys`,
  22. [V_SHOW]: `vShow`,
  23. [TRANSITION]: `Transition`,
  24. [TRANSITION_GROUP]: `TransitionGroup`
  25. });
  26. /* eslint-disable no-restricted-globals */
  27. let decoder;
  28. function decodeHtmlBrowser(raw) {
  29. (decoder || (decoder = document.createElement('div'))).innerHTML = raw;
  30. return decoder.textContent;
  31. }
  32. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  33. const parserOptions = {
  34. isVoidTag,
  35. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  36. isPreTag: tag => tag === 'pre',
  37. decodeEntities: decodeHtmlBrowser ,
  38. isBuiltInComponent: (tag) => {
  39. if (isBuiltInType(tag, `Transition`)) {
  40. return TRANSITION;
  41. }
  42. else if (isBuiltInType(tag, `TransitionGroup`)) {
  43. return TRANSITION_GROUP;
  44. }
  45. },
  46. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  47. getNamespace(tag, parent) {
  48. let ns = parent ? parent.ns : 0 /* HTML */;
  49. if (parent && ns === 2 /* MATH_ML */) {
  50. if (parent.tag === 'annotation-xml') {
  51. if (tag === 'svg') {
  52. return 1 /* SVG */;
  53. }
  54. if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
  55. a.name === 'encoding' &&
  56. a.value != null &&
  57. (a.value.content === 'text/html' ||
  58. a.value.content === 'application/xhtml+xml'))) {
  59. ns = 0 /* HTML */;
  60. }
  61. }
  62. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  63. tag !== 'mglyph' &&
  64. tag !== 'malignmark') {
  65. ns = 0 /* HTML */;
  66. }
  67. }
  68. else if (parent && ns === 1 /* SVG */) {
  69. if (parent.tag === 'foreignObject' ||
  70. parent.tag === 'desc' ||
  71. parent.tag === 'title') {
  72. ns = 0 /* HTML */;
  73. }
  74. }
  75. if (ns === 0 /* HTML */) {
  76. if (tag === 'svg') {
  77. return 1 /* SVG */;
  78. }
  79. if (tag === 'math') {
  80. return 2 /* MATH_ML */;
  81. }
  82. }
  83. return ns;
  84. },
  85. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  86. getTextMode({ tag, ns }) {
  87. if (ns === 0 /* HTML */) {
  88. if (tag === 'textarea' || tag === 'title') {
  89. return 1 /* RCDATA */;
  90. }
  91. if (isRawTextContainer(tag)) {
  92. return 2 /* RAWTEXT */;
  93. }
  94. }
  95. return 0 /* DATA */;
  96. }
  97. };
  98. // Parse inline CSS strings for static style attributes into an object.
  99. // This is a NodeTransform since it works on the static `style` attribute and
  100. // converts it into a dynamic equivalent:
  101. // style="color: red" -> :style='{ "color": "red" }'
  102. // It is then processed by `transformElement` and included in the generated
  103. // props.
  104. const transformStyle = node => {
  105. if (node.type === 1 /* ELEMENT */) {
  106. node.props.forEach((p, i) => {
  107. if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
  108. // replace p with an expression node
  109. node.props[i] = {
  110. type: 7 /* DIRECTIVE */,
  111. name: `bind`,
  112. arg: createSimpleExpression(`style`, true, p.loc),
  113. exp: parseInlineCSS(p.value.content, p.loc),
  114. modifiers: [],
  115. loc: p.loc
  116. };
  117. }
  118. });
  119. }
  120. };
  121. const parseInlineCSS = (cssText, loc) => {
  122. const normalized = parseStringStyle(cssText);
  123. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
  124. };
  125. function createDOMCompilerError(code, loc) {
  126. return createCompilerError(code, loc, (process.env.NODE_ENV !== 'production') || !true ? DOMErrorMessages : undefined);
  127. }
  128. const DOMErrorMessages = {
  129. [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  130. [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  131. [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  132. [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  133. [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  134. [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  135. [55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  136. [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  137. [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  138. [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  139. [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  140. };
  141. const transformVHtml = (dir, node, context) => {
  142. const { exp, loc } = dir;
  143. if (!exp) {
  144. context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
  145. }
  146. if (node.children.length) {
  147. context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
  148. node.children.length = 0;
  149. }
  150. return {
  151. props: [
  152. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  153. ]
  154. };
  155. };
  156. const transformVText = (dir, node, context) => {
  157. const { exp, loc } = dir;
  158. if (!exp) {
  159. context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
  160. }
  161. if (node.children.length) {
  162. context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
  163. node.children.length = 0;
  164. }
  165. return {
  166. props: [
  167. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  168. ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  169. : createSimpleExpression('', true))
  170. ]
  171. };
  172. };
  173. const transformModel = (dir, node, context) => {
  174. const baseResult = transformModel$1(dir, node, context);
  175. // base transform has errors OR component v-model (only need props)
  176. if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
  177. return baseResult;
  178. }
  179. if (dir.arg) {
  180. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  181. }
  182. function checkDuplicatedValue() {
  183. const value = findProp(node, 'value');
  184. if (value) {
  185. context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  186. }
  187. }
  188. const { tag } = node;
  189. const isCustomElement = context.isCustomElement(tag);
  190. if (tag === 'input' ||
  191. tag === 'textarea' ||
  192. tag === 'select' ||
  193. isCustomElement) {
  194. let directiveToUse = V_MODEL_TEXT;
  195. let isInvalidType = false;
  196. if (tag === 'input' || isCustomElement) {
  197. const type = findProp(node, `type`);
  198. if (type) {
  199. if (type.type === 7 /* DIRECTIVE */) {
  200. // :type="foo"
  201. directiveToUse = V_MODEL_DYNAMIC;
  202. }
  203. else if (type.value) {
  204. switch (type.value.content) {
  205. case 'radio':
  206. directiveToUse = V_MODEL_RADIO;
  207. break;
  208. case 'checkbox':
  209. directiveToUse = V_MODEL_CHECKBOX;
  210. break;
  211. case 'file':
  212. isInvalidType = true;
  213. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  214. break;
  215. default:
  216. // text type
  217. (process.env.NODE_ENV !== 'production') && checkDuplicatedValue();
  218. break;
  219. }
  220. }
  221. }
  222. else if (hasDynamicKeyVBind(node)) {
  223. // element has bindings with dynamic keys, which can possibly contain
  224. // "type".
  225. directiveToUse = V_MODEL_DYNAMIC;
  226. }
  227. else {
  228. // text type
  229. (process.env.NODE_ENV !== 'production') && checkDuplicatedValue();
  230. }
  231. }
  232. else if (tag === 'select') {
  233. directiveToUse = V_MODEL_SELECT;
  234. }
  235. else {
  236. // textarea
  237. (process.env.NODE_ENV !== 'production') && checkDuplicatedValue();
  238. }
  239. // inject runtime directive
  240. // by returning the helper symbol via needRuntime
  241. // the import will replaced a resolveDirective call.
  242. if (!isInvalidType) {
  243. baseResult.needRuntime = context.helper(directiveToUse);
  244. }
  245. }
  246. else {
  247. context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  248. }
  249. // native vmodel doesn't need the `modelValue` props since they are also
  250. // passed to the runtime as `binding.value`. removing it reduces code size.
  251. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  252. p.key.content === 'modelValue'));
  253. return baseResult;
  254. };
  255. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  256. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  257. // event propagation management
  258. `stop,prevent,self,` +
  259. // system modifiers + exact
  260. `ctrl,shift,alt,meta,exact,` +
  261. // mouse
  262. `middle`);
  263. // left & right could be mouse or key modifiers based on event type
  264. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  265. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  266. const resolveModifiers = (key, modifiers) => {
  267. const keyModifiers = [];
  268. const nonKeyModifiers = [];
  269. const eventOptionModifiers = [];
  270. for (let i = 0; i < modifiers.length; i++) {
  271. const modifier = modifiers[i];
  272. if (isEventOptionModifier(modifier)) {
  273. // eventOptionModifiers: modifiers for addEventListener() options,
  274. // e.g. .passive & .capture
  275. eventOptionModifiers.push(modifier);
  276. }
  277. else {
  278. // runtimeModifiers: modifiers that needs runtime guards
  279. if (maybeKeyModifier(modifier)) {
  280. if (isStaticExp(key)) {
  281. if (isKeyboardEvent(key.content)) {
  282. keyModifiers.push(modifier);
  283. }
  284. else {
  285. nonKeyModifiers.push(modifier);
  286. }
  287. }
  288. else {
  289. keyModifiers.push(modifier);
  290. nonKeyModifiers.push(modifier);
  291. }
  292. }
  293. else {
  294. if (isNonKeyModifier(modifier)) {
  295. nonKeyModifiers.push(modifier);
  296. }
  297. else {
  298. keyModifiers.push(modifier);
  299. }
  300. }
  301. }
  302. }
  303. return {
  304. keyModifiers,
  305. nonKeyModifiers,
  306. eventOptionModifiers
  307. };
  308. };
  309. const transformClick = (key, event) => {
  310. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  311. return isStaticClick
  312. ? createSimpleExpression(event, true)
  313. : key.type !== 4 /* SIMPLE_EXPRESSION */
  314. ? createCompoundExpression([
  315. `(`,
  316. key,
  317. `) === "onClick" ? "${event}" : (`,
  318. key,
  319. `)`
  320. ])
  321. : key;
  322. };
  323. const transformOn = (dir, node, context) => {
  324. return transformOn$1(dir, node, context, baseResult => {
  325. const { modifiers } = dir;
  326. if (!modifiers.length)
  327. return baseResult;
  328. let { key, value: handlerExp } = baseResult.props[0];
  329. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers);
  330. // normalize click.right and click.middle since they don't actually fire
  331. if (nonKeyModifiers.includes('right')) {
  332. key = transformClick(key, `onContextmenu`);
  333. }
  334. if (nonKeyModifiers.includes('middle')) {
  335. key = transformClick(key, `onMouseup`);
  336. }
  337. if (nonKeyModifiers.length) {
  338. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  339. handlerExp,
  340. JSON.stringify(nonKeyModifiers)
  341. ]);
  342. }
  343. if (keyModifiers.length &&
  344. // if event name is dynamic, always wrap with keys guard
  345. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  346. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  347. handlerExp,
  348. JSON.stringify(keyModifiers)
  349. ]);
  350. }
  351. if (eventOptionModifiers.length) {
  352. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  353. key = isStaticExp(key)
  354. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  355. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  356. }
  357. return {
  358. props: [createObjectProperty(key, handlerExp)]
  359. };
  360. });
  361. };
  362. const transformShow = (dir, node, context) => {
  363. const { exp, loc } = dir;
  364. if (!exp) {
  365. context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
  366. }
  367. return {
  368. props: [],
  369. needRuntime: context.helper(V_SHOW)
  370. };
  371. };
  372. const warnTransitionChildren = (node, context) => {
  373. if (node.type === 1 /* ELEMENT */ &&
  374. node.tagType === 1 /* COMPONENT */) {
  375. const component = context.isBuiltInComponent(node.tag);
  376. if (component === TRANSITION) {
  377. return () => {
  378. if (node.children.length && hasMultipleChildren(node)) {
  379. context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
  380. start: node.children[0].loc.start,
  381. end: node.children[node.children.length - 1].loc.end,
  382. source: ''
  383. }));
  384. }
  385. };
  386. }
  387. }
  388. };
  389. function hasMultipleChildren(node) {
  390. // #1352 filter out potential comment nodes.
  391. const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
  392. const child = children[0];
  393. return (children.length !== 1 ||
  394. child.type === 11 /* FOR */ ||
  395. (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
  396. }
  397. const ignoreSideEffectTags = (node, context) => {
  398. if (node.type === 1 /* ELEMENT */ &&
  399. node.tagType === 0 /* ELEMENT */ &&
  400. (node.tag === 'script' || node.tag === 'style')) {
  401. context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  402. context.removeNode();
  403. }
  404. };
  405. const DOMNodeTransforms = [
  406. transformStyle,
  407. ...((process.env.NODE_ENV !== 'production') ? [warnTransitionChildren] : [])
  408. ];
  409. const DOMDirectiveTransforms = {
  410. cloak: noopDirectiveTransform,
  411. html: transformVHtml,
  412. text: transformVText,
  413. model: transformModel,
  414. on: transformOn,
  415. show: transformShow
  416. };
  417. function compile(template, options = {}) {
  418. return baseCompile(template, extend({}, parserOptions, options, {
  419. nodeTransforms: [
  420. // ignore <script> and <tag>
  421. // this is not put inside DOMNodeTransforms because that list is used
  422. // by compiler-ssr to generate vnode fallback branches
  423. ignoreSideEffectTags,
  424. ...DOMNodeTransforms,
  425. ...(options.nodeTransforms || [])
  426. ],
  427. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  428. transformHoist: null
  429. }));
  430. }
  431. function parse(template, options = {}) {
  432. return baseParse(template, extend({}, parserOptions, options));
  433. }
  434. export { DOMDirectiveTransforms, DOMNodeTransforms, TRANSITION, TRANSITION_GROUP, V_MODEL_CHECKBOX, V_MODEL_DYNAMIC, V_MODEL_RADIO, V_MODEL_SELECT, V_MODEL_TEXT, V_ON_WITH_KEYS, V_ON_WITH_MODIFIERS, V_SHOW, compile, createDOMCompilerError, parse, parserOptions, transformStyle };